Skip to content

The animation engine for agents: blazingly fast math and 3D videos with Manim's Python API, on a Rust GPU core.

Python

Own browser player resources for the connected lifetime

Sina Atalay6b1721ec800b
diff --git a/browser/README.md b/browser/README.md
index e796ae20..f805c929 100644
--- a/browser/README.md
+++ b/browser/README.md
@@ -49,7 +49,9 @@ document.body.append(player);
The first film downloads Python (Pyodide, about 6 MB) and manimgx (about 20 MB); the browser
keeps both. It needs WebGPU: Chrome and Edge 113+, Safari 26, Firefox 141+ on Windows (not yet
-with the float32 blending manimgx's renderer uses).
+with the float32 blending manimgx's renderer uses). The adapter must support float32
+blending and `depth32float-stencil8`: the renderer uses floating-point depth to preserve
+distant surfaces' depth differences.
One file, no dependencies, any bundler. On the command line, `manimgx preview scene.py` plays a
scene file in a window of its own: the same player.
diff --git a/browser/src/director.ts b/browser/src/director.ts
index ae659dbe..3dad8c4c 100644
--- a/browser/src/director.ts
+++ b/browser/src/director.ts
@@ -1,7 +1,7 @@
// The director's worker: Python (Pyodide) running scenes, their takes sent to the page's players.
// manimgx comes from PyPI (micropip), and with it the player's engine, which is handed on.
//
-// In: {boot: {pyodide, manimgx}} once; {film, run: {source, scene}}.
+// In: {boot: {pyodide, manimgx}} once; {film, run: {source, scene}}; {film, drop} on detach.
// Out: {status} while it boots (what it waits for); {engine: {js, wasm, fonts}} once (the
// player: its JS and WebAssembly, and the fonts its face is set in); then each film's take stream,
// {film, feed}: its takes, and between them the director's notes (the file's scenes, an error),
@@ -42,11 +42,14 @@ interface Python {
py: Pyodide;
micropip: Micropip;
runner: Runner;
+ note: (text: string) => Uint8Array<ArrayBuffer>;
+ drop: (film: number) => void;
}
-const queue = new Map<number, Run>(); // film → the latest run asked for, not begun (an edit replaces it)
+const queue = new Map<number, Run | null>(); // the latest run, or teardown after the active run
let booted: Promise<Python | null> | undefined;
let busy = false;
+let failed = false;
function send(data: FromDirector, transfer: Transferable[] = []): void {
postMessage(data, transfer);
@@ -55,13 +58,15 @@ function send(data: FromDirector, transfer: Transferable[] = []): void {
onmessage = ({ data }: MessageEvent<ToDirector>) => {
if ("boot" in data) {
booted = boot(data.boot).catch((error: unknown) => {
- send({ status: `manimgx could not start: ${message(error)}` });
+ failed = true;
+ queue.clear();
+ send({ failure: `manimgx could not start: ${message(error)}` });
return null;
});
return;
}
- if ("run" in data) {
- queue.set(data.film, data.run);
+ if (!failed) {
+ queue.set(data.film, "run" in data ? data.run : null);
drain();
}
};
@@ -87,54 +92,72 @@ from manimgx.drawing.typesetting import FONTS
built.destroy();
send({ engine: { js, wasm, fonts } }, [wasm.buffer, ...fonts.map((f) => f.buffer)]);
const runner = py.runPython(RUNNER) as Runner;
- return { py, micropip, runner };
+ const note = py.runPython("lambda text: to_js(_engine.note(text))") as Python["note"];
+ const drop = py.runPython("drop") as Python["drop"];
+ return { py, micropip, runner, note, drop };
}
async function drain(): Promise<void> {
const python = await booted;
if (!python || busy) return;
- const { py, micropip, runner } = python;
+ const { py, micropip, runner, note, drop } = python;
busy = true;
- for (const [film, { source, scene }] of queue) {
- queue.delete(film);
- const feed = (bytes: Uint8Array<ArrayBuffer>): void =>
- send({ film, feed: bytes.buffer }, [bytes.buffer]);
- await py.loadPackagesFromImports(source); // what the scene imports from Pyodide's own packages
- // a module the scene misses (its own import, or one manimgx imports when needed: networkx
- // for a Graph) is installed, and the scene run again
- const tried: string[] = [];
- for (let missing; (missing = runner(film, source, scene ?? null, feed, tried));) {
- tried.push(missing);
- await micropip.install(missing).catch(() => {});
+ try {
+ for (const [film, run] of queue) {
+ queue.delete(film);
+ const feed = (bytes: Uint8Array<ArrayBuffer>): void =>
+ send({ film, feed: bytes.buffer }, [bytes.buffer]);
+ try {
+ if (run === null) {
+ drop(film);
+ continue;
+ }
+ const { source, scene } = run;
+ await py.loadPackagesFromImports(source); // the scene's Pyodide package imports
+ // A missing module is installed once, then the ordinary runner reports any failure.
+ const tried: string[] = [];
+ for (let missing; (missing = runner(film, source, scene ?? null, feed, tried));) {
+ tried.push(missing);
+ await micropip.install(missing).catch(() => {});
+ }
+ } catch (error) {
+ // Loading and calling Python can fail outside its own scene error boundary. Keep the
+ // error in this film's ordinary note stream so another film or edit can still run.
+ feed(note(JSON.stringify({ error: { message: message(error), type: "Error" } })));
+ }
+ await new Promise<void>((resolve) => setTimeout(resolve)); // let newer runs in
}
- await new Promise<void>((resolve) => setTimeout(resolve)); // let newer runs in
+ } finally {
+ busy = false;
+ if (queue.size) drain();
}
- busy = false;
- if (queue.size) drain();
}
// Python: a film's source run as a scene file, like `manimgx render` runs one, its take sent on.
const RUNNER = `
-import dataclasses, importlib.util, json, sys, traceback
+import dataclasses, importlib.util, json, linecache, shutil, sys, traceback
from pathlib import Path
from pyodide.ffi import to_js
from manimgx import _engine
from manimgx.config import Config, config
from manimgx.scene import Scene
+FILMS = Path("/home/pyodide/films")
+
def run(film, source, name, send, tried):
out = lambda data: send(to_js(data))
- path = Path(f"/home/pyodide/films/{film}/scene.py")
+ path = FILMS / str(film) / "scene.py"
try:
path.parent.mkdir(parents=True, exist_ok=True)
- path.write_text(source)
+ path.write_text(source, encoding="utf-8")
+ linecache.cache.pop(str(path), None)
defaults = Config()
for field in dataclasses.fields(Config):
setattr(config, field.name, getattr(defaults, field.name))
spec = importlib.util.spec_from_file_location("scene", path)
module = importlib.util.module_from_spec(spec)
sys.modules["scene"] = module
- spec.loader.exec_module(module)
+ exec(compile(source, str(path), "exec"), module.__dict__)
scenes = [v for v in vars(module).values() if isinstance(v, type) and issubclass(v, Scene) and v.__module__ == "scene"]
names = [s.__name__ for s in scenes]
if not scenes:
@@ -149,6 +172,17 @@ def run(film, source, name, send, tried):
except Exception as error:
report(out, path, error)
+def drop(film):
+ path = FILMS / str(film) / "scene.py"
+ module = sys.modules.get("scene")
+ if getattr(module, "__file__", None) == str(path):
+ del sys.modules["scene"]
+ for filename in list(linecache.cache):
+ if Path(filename).is_relative_to(path.parent):
+ del linecache.cache[filename]
+ if path.parent.exists():
+ shutil.rmtree(path.parent)
+
def report(out, path, error):
# the scene's own frames, not manimgx's or Pyodide's
frames = [f for f in traceback.extract_tb(error.__traceback__) if f.filename == str(path)]
diff --git a/browser/src/engine.ts b/browser/src/engine.ts
index b6313369..185b9a46 100644
--- a/browser/src/engine.ts
+++ b/browser/src/engine.ts
@@ -6,6 +6,7 @@ export interface Engine {
}
export interface Player {
+ free(): void;
feed(bytes: Uint8Array): void;
key(key: string, ctrl: boolean, alt: boolean, meta: boolean): boolean;
pointer(x: number, y: number): void;
diff --git a/browser/src/player.ts b/browser/src/player.ts
index 60edef74..0bf30a41 100644
--- a/browser/src/player.ts
+++ b/browser/src/player.ts
@@ -31,13 +31,15 @@ export const runtime = {
interface PagePlayer {
wait(): void;
feed(bytes: ArrayBuffer): void;
+ fail(error: string): void;
}
interface Page {
director: Worker;
players: Map<number, PagePlayer>;
- engine: Promise<Engine>;
+ engine: Promise<Engine | null>;
status: string;
+ failure: string | null;
}
let page: Page | undefined; // the page's director, its engine (once it is up), and its players
@@ -51,15 +53,27 @@ function begin(): Page {
if (page) return page;
const director = new Worker(runtime.worker(), { type: "module" });
const players = new Map<number, PagePlayer>();
- let up: (engine: Engine) => void = () => {};
+ let up: (engine: Engine | null) => void = () => {};
const current: Page = {
director,
players,
engine: new Promise((resolve) => (up = resolve)),
status: "Loading Python…",
+ failure: null,
};
page = current;
+ const fail = (error: string): void => {
+ if (current.failure !== null) return;
+ current.failure = current.status = error;
+ up(null);
+ director.terminate();
+ for (const player of players.values()) player.fail(error);
+ };
+ director.onerror = (event) => fail(`manimgx could not start: ${event.message}`);
+ director.onmessageerror = () => fail("manimgx could not read its worker's reply");
director.onmessage = async ({ data }: MessageEvent<FromDirector>) => {
+ if (current.failure !== null) return;
+ if ("failure" in data) return fail(data.failure);
if ("status" in data) {
current.status = data.status;
for (const player of players.values()) player.wait();
@@ -68,16 +82,16 @@ function begin(): Page {
// the player, from the manimgx the director installed: its JS, its WebAssembly, the fonts
// its face is set in
const { js, wasm, fonts } = data.engine;
+ const url = URL.createObjectURL(new Blob([js], { type: "text/javascript" }));
try {
- const engine = (await import(
- URL.createObjectURL(new Blob([js], { type: "text/javascript" }))
- )) as Engine;
+ const engine = (await import(url)) as Engine;
await engine.default({ module_or_path: wasm });
await engine.init(fonts);
up(engine);
} catch (error) {
- current.status = `manimgx can't draw here: ${message(error)}`;
- for (const player of players.values()) player.wait();
+ fail(`manimgx can't draw here: ${message(error)}`);
+ } finally {
+ URL.revokeObjectURL(url);
}
}
if ("film" in data) players.get(data.film)?.feed(data.feed);
@@ -93,7 +107,7 @@ let films = 0;
export class ManimgxPlayer extends HTMLElement {
static observedAttributes = ["scene"];
- #film = ++films;
+ #film = 0;
#canvas: HTMLCanvasElement;
#said: HTMLParagraphElement;
#source: string | null = null;
@@ -101,7 +115,8 @@ export class ManimgxPlayer extends HTMLElement {
#wants: { time: number; playing: boolean | null } = { time: 0, playing: null };
#begun = false;
#failed = false;
- #player: Player | null = null;
+ #player: Player | null = null; // native GPU resources belong to one connected lifetime
+ #connection: AbortController | undefined;
#timer: number | undefined;
#frame = 0;
#root: ShadowRoot;
@@ -123,12 +138,39 @@ export class ManimgxPlayer extends HTMLElement {
connectedCallback(): void {
if (!this.hasAttribute("tabindex")) this.tabIndex = 0; // it takes keys
- // begun a task later: a page can still set `settings` after importing this
- if (!this.#begun) setTimeout(() => this.isConnected && !this.#begun && this.#begin());
+ if (this.#connection || this.#failed) return;
+ this.#film = ++films; // late bytes from an earlier connection belong to its old decoder
+ const connection = (this.#connection = new AbortController());
+ // Begun a task later: a page can still set `settings` after importing this.
+ const task = setTimeout(() => {
+ if (!connection.signal.aborted) this.#begin(connection.signal);
+ });
+ connection.signal.addEventListener(
+ "abort",
+ () => {
+ clearTimeout(task);
+ clearTimeout(this.#timer);
+ cancelAnimationFrame(this.#frame);
+ this.#frame = 0;
+ },
+ { once: true },
+ );
}
disconnectedCallback(): void {
- if (this.#player) this.pause();
+ this.#connection?.abort();
+ this.#connection = undefined;
+ if (page?.players.delete(this.#film) && page.failure === null) {
+ send(page.director, { film: this.#film, drop: true });
+ }
+ this.#backlog = [];
+ const player = this.#player;
+ if (player) {
+ this.#wants = { time: player.time, playing: false };
+ player.pause();
+ this.#player = null;
+ player.free();
+ }
}
attributeChangedCallback(): void {
@@ -187,22 +229,36 @@ export class ManimgxPlayer extends HTMLElement {
// ── the player ─────────────────────────────────────────────────────────────────────────
- async #begin(): Promise<void> {
- this.#begun = true;
- const script = this.querySelector('script[type="text/python"]');
- if (script && this.#source === null) this.#source = dedent(script.textContent);
- const { players, engine } = begin();
- players.set(this.#film, { wait: () => this.#wait(), feed: (bytes) => this.#feed(bytes) });
+ async #begin(signal: AbortSignal): Promise<void> {
+ if (this.#failed) return;
+ if (!this.#begun) {
+ this.#begun = true;
+ const script = this.querySelector('script[type="text/python"]');
+ if (script && this.#source === null) this.#source = dedent(script.textContent);
+ }
+ const { players, engine, failure } = begin();
+ if (failure !== null) return this.#fail(failure);
+ players.set(this.#film, {
+ wait: () => this.#wait(),
+ feed: (bytes) => this.#feed(bytes),
+ fail: (error) => this.#fail(error),
+ });
this.#wait();
if (this.#source !== null) this.#run();
const canvas = this.#canvas;
const box = canvas.getBoundingClientRect();
- [canvas.width, canvas.height] = [
- Math.max(1, Math.round(box.width * devicePixelRatio)),
- Math.max(1, Math.round(box.height * devicePixelRatio)),
- ];
- const made = await engine;
- if (this.#failed) return;
+ const width = Math.max(1, Math.round(box.width * devicePixelRatio));
+ const height = Math.max(1, Math.round(box.height * devicePixelRatio));
+ if (canvas.width !== width) canvas.width = width;
+ if (canvas.height !== height) canvas.height = height;
+ // An unattached element must not be retained by the page's pending runtime promise.
+ const made = await Promise.race([
+ engine,
+ new Promise<undefined>((resolve) =>
+ signal.addEventListener("abort", () => resolve(undefined), { once: true }),
+ ),
+ ]);
+ if (!made || signal.aborted || this.#failed) return;
try {
const { time, playing } = this.#wants;
this.#player = new made.Player(canvas, time, playing ?? this.hasAttribute("autoplay"), MAC);
@@ -211,7 +267,7 @@ export class ManimgxPlayer extends HTMLElement {
return this.#fail(error);
}
this.#said.remove();
- this.#wire();
+ this.#wire(signal);
for (const bytes of this.#backlog.splice(0)) this.#feed(bytes);
this.#after();
}
@@ -221,15 +277,14 @@ export class ManimgxPlayer extends HTMLElement {
}
#fail(error: unknown): void {
- this.#player = null;
this.#failed = true;
- this.#backlog = [];
+ this.disconnectedCallback();
this.#said.textContent = message(error);
this.#root.append(this.#said);
}
#run(): void {
- if (this.#source === null) return;
+ if (this.#source === null || !page?.players.has(this.#film)) return;
send(begin().director, {
film: this.#film,
run: { source: this.#source, scene: this.getAttribute("scene") },
@@ -254,7 +309,7 @@ export class ManimgxPlayer extends HTMLElement {
}
/** What the viewer does, handed on as the web has it; what the player takes, the page doesn't. */
- #wire(): void {
+ #wire(signal: AbortSignal): void {
const p = this.#player,
canvas = this.#canvas;
if (!p) return;
@@ -280,7 +335,7 @@ export class ManimgxPlayer extends HTMLElement {
if (hand(e)) e.preventDefault();
this.#after();
},
- options,
+ { ...options, signal },
);
let pressed: number | null = null; // the pointer that pressed: one at a time, its primary button or finger
on(this, "keydown", (e) => p.key(e.key, e.ctrlKey, e.altKey, e.metaKey));
@@ -311,7 +366,7 @@ export class ManimgxPlayer extends HTMLElement {
);
on(document, "fullscreenchange", () => p.fullscreen(document.fullscreenElement === this));
// drawn at the size the page shows it, in the screen's own pixels: sharp at any size
- new ResizeObserver(([entry]) => {
+ const resize = new ResizeObserver(([entry]) => {
if (!entry) return;
const box = entry.devicePixelContentBoxSize?.[0];
const css = entry.contentBoxSize[0];
@@ -321,21 +376,31 @@ export class ManimgxPlayer extends HTMLElement {
if (this.#player !== p) return;
p.resize(w, h, w / css.inlineSize);
this.#after();
- }).observe(canvas);
+ });
+ resize.observe(canvas);
// out of sight, it draws nothing (its clock and sound go on)
- new IntersectionObserver(([entry]) => {
+ const visibility = new IntersectionObserver(([entry]) => {
if (!entry) return;
if (this.#player !== p) return;
p.hide(!entry.isIntersecting);
this.#after();
- }).observe(this);
+ });
+ visibility.observe(this);
+ signal.addEventListener(
+ "abort",
+ () => {
+ resize.disconnect();
+ visibility.disconnect();
+ },
+ { once: true },
+ );
}
/** What the player asks (its director to run another scene, full screen), its cursor, and its
* next picture, when it is due. */
#after(): void {
const p = this.#player;
- if (!p) return;
+ if (!p || !this.#connection || this.#connection.signal.aborted) return;
for (const [ask, value] of p.asks()) {
if (ask === "scene") {
this.setAttribute("scene", value);
diff --git a/browser/src/protocol.ts b/browser/src/protocol.ts
index 1facf0f1..442fbed9 100644
--- a/browser/src/protocol.ts
+++ b/browser/src/protocol.ts
@@ -9,7 +9,7 @@ export interface Run {
scene: string | null;
}
-export type ToDirector = { boot: Boot } | { film: number; run: Run };
+export type ToDirector = { boot: Boot } | { film: number; run: Run } | { film: number; drop: true };
/** These byte arrays originate in Pyodide and own transferable ArrayBuffers. */
export interface EngineFiles {
@@ -19,7 +19,10 @@ export interface EngineFiles {
}
export type FromDirector =
- { status: string } | { engine: EngineFiles } | { film: number; feed: ArrayBuffer };
+ | { status: string }
+ | { failure: string }
+ | { engine: EngineFiles }
+ | { film: number; feed: ArrayBuffer };
export function message(error: unknown): string {
return String(
diff --git a/browser/tests/browser.test.ts b/browser/tests/browser.test.ts
index 9257b51b..705c5c73 100644
--- a/browser/tests/browser.test.ts
+++ b/browser/tests/browser.test.ts
@@ -10,21 +10,77 @@ const packageJSON = (await Bun.file(new URL("../package.json", import.meta.url))
// Each page gets its own globals and module, just as separate browser tabs do. Loading the
// emitted file also catches packaging mistakes that importing the TypeScript source misses.
-async function page(script: string | null = null) {
- const tasks: (() => void)[] = [];
+async function page(
+ script: string | null = null,
+ failAt: "import" | "wasm" | "fonts" | null = null,
+) {
+ const tasks = new Map<number, () => void>();
+ const frames = new Map<number, () => void>();
+ let taskId = 0;
const blobs: Blob[] = [];
const elements = new Map<string, unknown>();
const workers: Director[] = [];
+ const natives: NativePlayer[] = [];
+ const observers: Observer[] = [];
+ const document = Object.assign(new EventTarget(), { fullscreenElement: null });
+ class Observer {
+ targets = new Set<unknown>();
+ constructor(_callback: unknown) {
+ observers.push(this);
+ }
+ observe(target: unknown) {
+ this.targets.add(target);
+ }
+ disconnect() {
+ this.targets.clear();
+ }
+ }
+ class NativePlayer {
+ time = 0;
+ playing = false;
+ cursor = "default";
+ feeds: number[][] = [];
+ fullscreenChanges = 0;
+ wakeAfter = -1;
+ frees = 0;
+ constructor(_canvas: unknown, time: number, playing: boolean) {
+ this.time = time;
+ this.playing = playing;
+ natives.push(this);
+ }
+ free() {
+ this.frees++;
+ }
+ resize() {}
+ pause() {
+ this.playing = false;
+ }
+ asks() {
+ return [];
+ }
+ wake() {
+ return this.wakeAfter;
+ }
+ feed(bytes: Uint8Array) {
+ if (bytes[0] === 255) throw new Error("decode failed");
+ this.feeds.push([...bytes]);
+ }
+ fullscreen() {
+ this.fullscreenChanges++;
+ }
+ }
const waiting = { textContent: "", remove() {} };
- const canvas = {
+ const canvas = Object.assign(new EventTarget(), {
+ style: { cursor: "" },
width: 0,
height: 0,
getBoundingClientRect: () => ({ width: 320, height: 180 }),
- };
+ });
class Element extends EventTarget {
isConnected = true;
tabIndex = -1;
+ style = { setProperty() {} };
attributes = new Map<string, string>();
shadowRoot = {
innerHTML: "",
@@ -57,6 +113,8 @@ async function page(script: string | null = null) {
class Director {
sent: unknown[] = [];
onmessage: ((event: { data: unknown }) => Promise<void>) | null = null;
+ onerror: ((event: { message: string }) => void) | null = null;
+ terminations = 0;
constructor(
readonly url: string,
readonly options: WorkerOptions,
@@ -66,10 +124,17 @@ async function page(script: string | null = null) {
postMessage(data: unknown) {
this.sent.push(data);
}
+ terminate() {
+ this.terminations++;
+ }
}
const context = createContext({
HTMLElement: Element,
+ AbortController,
+ document,
+ ResizeObserver: Observer,
+ IntersectionObserver: Observer,
navigator: { platform: "Linux" },
customElements: {
get: (name: string) => elements.get(name),
@@ -82,11 +147,44 @@ async function page(script: string | null = null) {
blobs.push(blob);
return `blob:test/${blobs.length}`;
}
+ static override revokeObjectURL() {}
},
devicePixelRatio: 2,
- setTimeout: (callback: () => void) => tasks.push(callback),
+ setTimeout: (callback: () => void) => {
+ tasks.set(++taskId, callback);
+ return taskId;
+ },
+ clearTimeout: (id: number) => tasks.delete(id),
+ requestAnimationFrame: (callback: () => void) => {
+ frames.set(++taskId, callback);
+ return taskId;
+ },
+ cancelAnimationFrame: (id: number) => frames.delete(id),
+ });
+ const engine = new SyntheticModule(
+ ["default", "init", "Player"],
+ function () {
+ this.setExport("default", async () => {
+ if (failAt === "wasm") throw new Error("wasm failed");
+ });
+ this.setExport("init", async () => {
+ if (failAt === "fonts") throw new Error("fonts failed");
+ });
+ this.setExport("Player", NativePlayer);
+ },
+ { context },
+ );
+ await engine.link(() => {
+ throw new Error("Unexpected engine import");
+ });
+ await engine.evaluate();
+ const module = new SourceTextModule(bundle, {
+ context,
+ importModuleDynamically: () => {
+ if (failAt === "import") throw new Error("import failed");
+ return engine;
+ },
});
- const module = new SourceTextModule(bundle, { context });
await module.link(() => {
throw new Error("The published player must be one self-contained module");
});
@@ -97,9 +195,18 @@ async function page(script: string | null = null) {
blobs,
elements,
workers,
+ natives,
+ observers,
+ document,
+ timers: tasks,
+ frames,
waiting,
canvas,
- flush: () => tasks.splice(0).forEach((task) => task()),
+ flush: () => {
+ const batch = [...tasks.values()];
+ tasks.clear();
+ batch.forEach((task) => task());
+ },
};
}
@@ -179,10 +286,153 @@ describe("published browser module", () => {
player.connectedCallback();
state.flush();
expect(state.workers).toHaveLength(1);
- expect(director.sent).toHaveLength(4);
+ expect(director.sent).toHaveLength(6);
});
- test("the embedded worker is executable JavaScript and coalesces pending scene edits", async () => {
+ test("disconnecting frees native resources and subscriptions; reconnecting preserves the time", async () => {
+ const state = await page();
+ const player = new state.api.ManimgxPlayer();
+ player.source = "first";
+ player.connectedCallback();
+ state.flush();
+ const director = state.workers[0]!;
+ await director.onmessage!({ data: { engine: { js: "", wasm: new Uint8Array(), fonts: [] } } });
+ await settle();
+ expect(state.natives).toHaveLength(1);
+ expect(state.observers.filter((observer) => observer.targets.size)).toHaveLength(2);
+ state.natives[0]!.wakeAfter = 0;
+ player.currentTime = 1.25;
+ expect(state.frames.size).toBe(1);
+ state.natives[0]!.wakeAfter = 20;
+ player.currentTime = 1.25;
+ expect(state.timers.size).toBe(1);
+ state.document.dispatchEvent(new Event("fullscreenchange"));
+ expect(state.natives[0]!.fullscreenChanges).toBe(1);
+
+ Object.defineProperty(player, "isConnected", { value: false, writable: true });
+ player.disconnectedCallback();
+ player.disconnectedCallback(); // teardown is idempotent
+ expect(state.natives[0]!.playing).toBe(false);
+ expect(state.natives[0]!.frees).toBe(1);
+ expect(state.frames.size).toBe(0);
+ expect(state.timers.size).toBe(0);
+ state.natives[0]!.wakeAfter = -1;
+ expect(state.observers.every((observer) => observer.targets.size === 0)).toBe(true);
+ state.document.dispatchEvent(new Event("fullscreenchange"));
+ expect(state.natives[0]!.fullscreenChanges).toBe(1);
+ await director.onmessage!({ data: { film: 1, feed: new Uint8Array([1]).buffer } });
+ expect(state.natives[0]!.feeds).toEqual([]);
+ const sent = director.sent.length;
+ player.source = "edited while detached";
+ expect(director.sent).toHaveLength(sent);
+
+ Object.defineProperty(player, "isConnected", { value: true });
+ player.connectedCallback();
+ state.flush();
+ await settle();
+ expect(state.natives).toHaveLength(2);
+ expect(player.currentTime).toBe(1.25);
+ expect(player.paused).toBe(true);
+ expect(state.observers.filter((observer) => observer.targets.size)).toHaveLength(2);
+ expect(director.sent.at(-1)).toEqual({
+ film: 2,
+ run: { source: "edited while detached", scene: null },
+ });
+ state.document.dispatchEvent(new Event("fullscreenchange"));
+ expect(state.natives[0]!.fullscreenChanges).toBe(1);
+ expect(state.natives[1]!.fullscreenChanges).toBe(1);
+ // The previous run may still be sending bytes when this connection's native decoder is
+ // empty. A continuation from that old take must never enter the new decoder.
+ await director.onmessage!({ data: { film: 1, feed: new Uint8Array([255]).buffer } });
+ expect(state.natives[1]!.frees).toBe(0);
+ await director.onmessage!({ data: { film: 2, feed: new Uint8Array([2]).buffer } });
+ expect(state.natives[0]!.feeds).toEqual([]);
+ expect(state.natives[1]!.feeds).toEqual([[2]]);
+ await director.onmessage!({ data: { film: 2, feed: new Uint8Array([255]).buffer } });
+ expect(state.natives[1]!.frees).toBe(1);
+ expect(state.observers.every((observer) => observer.targets.size === 0)).toBe(true);
+ expect(state.waiting.textContent).toBe("decode failed");
+ });
+
+ test("disconnecting during boot does not create an orphan native player", async () => {
+ const state = await page();
+ const player = new state.api.ManimgxPlayer();
+ player.source = "first";
+ player.connectedCallback();
+ state.flush();
+ Object.defineProperty(player, "isConnected", { value: false, writable: true });
+ player.disconnectedCallback();
+ await state.workers[0]!.onmessage!({
+ data: { engine: { js: "", wasm: new Uint8Array(), fonts: [] } },
+ });
+ await settle();
+ expect(state.natives).toHaveLength(0);
+ Object.defineProperty(player, "isConnected", { value: true });
+ player.connectedCallback();
+ state.flush();
+ await settle();
+ expect(state.natives).toHaveLength(1);
+ });
+
+ test("an old connection cannot create a second player when boot finishes after reconnect", async () => {
+ const state = await page();
+ const player = new state.api.ManimgxPlayer();
+ player.connectedCallback();
+ state.flush();
+ player.disconnectedCallback();
+ player.connectedCallback();
+ state.flush();
+ await state.workers[0]!.onmessage!({
+ data: { engine: { js: "", wasm: new Uint8Array(), fonts: [] } },
+ });
+ await settle();
+ expect(state.natives).toHaveLength(1);
+ expect(state.observers.filter((observer) => observer.targets.size)).toHaveLength(2);
+ });
+
+ test.each(["import", "wasm", "fonts", "worker", "boot"] as const)(
+ "%s initialization failure is terminal for existing and future players",
+ async (failure) => {
+ const state = await page(
+ null,
+ ["worker", "boot"].includes(failure) ? null : (failure as "import" | "wasm" | "fonts"),
+ );
+ const player = new state.api.ManimgxPlayer();
+ player.source = "first";
+ player.connectedCallback();
+ state.flush();
+ const director = state.workers[0]!;
+ await director.onmessage!({ data: { film: 1, feed: new Uint8Array([1]).buffer } });
+ if (failure === "worker") director.onerror!({ message: "worker failed" });
+ else if (failure === "boot") await director.onmessage!({ data: { failure: "boot failed" } });
+ else
+ await director.onmessage!({
+ data: { engine: { js: "", wasm: new Uint8Array(), fonts: [] } },
+ });
+ await settle();
+ expect(state.waiting.textContent).toContain(`${failure} failed`);
+ expect(director.terminations).toBe(1);
+ const sent = director.sent.length;
+ player.source = "cannot run";
+ const later = new state.api.ManimgxPlayer();
+ later.source = "cannot run either";
+ later.connectedCallback();
+ state.flush();
+ await settle();
+ expect(director.sent).toHaveLength(sent);
+ expect(state.natives).toHaveLength(0);
+ expect(state.waiting.textContent).toContain(`${failure} failed`);
+ // Even a late successful boot message cannot resurrect this failed runtime or replay
+ // bytes that arrived before initialization failed.
+ await director.onmessage!({
+ data: { engine: { js: "", wasm: new Uint8Array(), fonts: [] } },
+ });
+ await settle();
+ expect(state.natives).toHaveLength(0);
+ },
+ );
+
+ test("the embedded worker coalesces edits and isolates film failures", async () => {
const state = await page();
new state.api.ManimgxPlayer().connectedCallback();
state.flush();
@@ -191,9 +441,11 @@ describe("published browser module", () => {
const imports: string[] = [];
const installs: string[] = [];
const runs: { film: number; source: string; scene: string | null; tried: string[] }[] = [];
+ const drops: number[] = [];
const tasks: (() => void)[] = [];
let destroyed = false;
let allowBoot!: () => void;
+ let allowImports: (() => void) | undefined;
const bootGate = new Promise<void>((resolve) => {
allowBoot = resolve;
});
@@ -206,6 +458,7 @@ describe("published browser module", () => {
send: (bytes: Uint8Array) => void,
tried: string[],
) => {
+ if (source === "broken runner") throw new Error("Python worker failure");
runs.push({ film, source, scene, tried: [...tried] });
if (source === "latest" && !tried.includes("networkx")) return "networkx";
send(new Uint8Array([film]));
@@ -226,13 +479,22 @@ describe("published browser module", () => {
runPython: (source: string) =>
source.includes("def run(")
? runner
- : {
- toJs: () => ["engine source", wasm, fonts],
- destroy: () => {
- destroyed = true;
- },
- },
+ : source === "drop"
+ ? (film: number) => drops.push(film)
+ : source.startsWith("lambda text:")
+ ? (text: string) => new TextEncoder().encode(text)
+ : {
+ toJs: () => ["engine source", wasm, fonts],
+ destroy: () => {
+ destroyed = true;
+ },
+ },
loadPackagesFromImports: async (source: string) => {
+ if (source === "broken imports") throw new Error("Package download failed");
+ if (source === "pending imports")
+ await new Promise<void>((resolve) => {
+ allowImports = resolve;
+ });
imports.push(source);
},
};
@@ -275,6 +537,8 @@ describe("published browser module", () => {
send({ film: 1, run: { source: "stale", scene: null } });
send({ film: 1, run: { source: "latest", scene: "Demo" } });
send({ film: 2, run: { source: "other", scene: null } });
+ send({ film: 9, run: { source: "detached before boot", scene: null } });
+ send({ film: 9, drop: true });
allowBoot();
await settle();
expect(installs).toEqual(["manimgx==test", "networkx"]);
@@ -304,5 +568,93 @@ describe("published browser module", () => {
[2, 2],
]);
for (const { data, transfer } of feeds) expect(transfer).toEqual([data.feed]);
+ tasks.splice(0).forEach((task) => task());
+ await settle();
+ expect(drops).toEqual([9]);
+ // Teardown of one lifetime cannot erase the newly connected film's source directory.
+ send({ film: 2, drop: true });
+ send({ film: 5, run: { source: "reconnected", scene: null } });
+ await settle();
+ expect(drops).toEqual([9, 2]);
+ expect(runs.at(-1)).toMatchObject({ film: 5, source: "reconnected" });
+
+ // A failed dependency load or Python call belongs to one film. It must not lock the
+ // shared queue, and editing that same film must remain possible afterward.
+ for (const [source, error] of [
+ ["broken imports", "Package download failed"],
+ ["broken runner", "Python worker failure"],
+ ]) {
+ tasks.splice(0).forEach((task) => task());
+ await settle();
+ send({ film: 3, run: { source, scene: null } });
+ send({ film: 4, run: { source: "next film", scene: null } });
+ await settle();
+ const failed = messages.at(-1)!.data as { film: number; feed: ArrayBuffer };
+ expect(failed.film).toBe(3);
+ expect(JSON.parse(new TextDecoder().decode(failed.feed))).toEqual({
+ error: { message: error, type: "Error" },
+ });
+ tasks.splice(0).forEach((task) => task());
+ await settle();
+ expect(runs.at(-1)).toMatchObject({ film: 4, source: "next film" });
+ send({ film: 3, run: { source: "corrected", scene: null } });
+ tasks.splice(0).forEach((task) => task());
+ await settle();
+ expect(runs.at(-1)).toMatchObject({ film: 3, source: "corrected" });
+ }
+ tasks.splice(0).forEach((task) => task());
+ await settle();
+ send({ film: 6, run: { source: "pending imports", scene: null } });
+ await settle();
+ send({ film: 6, drop: true });
+ send({ film: 7, run: { source: "new connection", scene: null } });
+ await settle();
+ expect(drops).not.toContain(6);
+ allowImports!();
+ await settle();
+ expect(runs.at(-1)).toMatchObject({ film: 6, source: "pending imports" });
+ expect(drops).not.toContain(6);
+ tasks.splice(0).forEach((task) => task());
+ await settle();
+ expect(drops.at(-1)).toBe(6);
+ expect(runs.at(-1)).toMatchObject({ film: 7, source: "new connection" });
+ });
+
+ test("the embedded worker reports a terminal boot failure and rejects later runs", async () => {
+ const state = await page();
+ new state.api.ManimgxPlayer().connectedCallback();
+ state.flush();
+ const messages: unknown[] = [];
+ const global = {
+ onmessage: null as ((event: { data: unknown }) => void) | null,
+ postMessage: (data: unknown) => messages.push(data),
+ };
+ const worker = new SourceTextModule(await state.blobs[0]!.text(), {
+ context: createContext(global),
+ importModuleDynamically: () => {
+ throw new Error("Python download failed");
+ },
+ });
+ await worker.link(() => {
+ throw new Error("Unexpected dependency");
+ });
+ await worker.evaluate();
+ global.onmessage!({ data: { boot: { pyodide: "https://example.test/", manimgx: "test" } } });
+ global.onmessage!({ data: { film: 1, run: { source: "queued", scene: null } } });
+ await settle();
+ expect(messages).toEqual([
+ { status: "Loading Python…" },
+ { failure: "manimgx could not start: Python download failed" },
+ ]);
+ global.onmessage!({
+ data: {
+ film: 2,
+ get run() {
+ throw new Error("A failed worker must not accept more source");
+ },
+ },
+ });
+ await settle();
+ expect(messages).toHaveLength(2);
});
});
diff --git a/tests/test_browser.py b/tests/test_browser.py
new file mode 100644
index 00000000..cd1844d0
--- /dev/null
+++ b/tests/test_browser.py
@@ -0,0 +1,118 @@
+"""The browser worker's Python source lifetime, exercised by the real Python interpreter."""
+
+import linecache
+import os
+import sys
+from collections.abc import Callable, Iterator
+from pathlib import Path
+from types import ModuleType
+from typing import cast
+
+import pytest
+
+Run = Callable[[int, str, str | None, Callable[[bytes], None], list[str]], str | None]
+Drop = Callable[[int], None]
+
+
+def runner(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> Iterator[tuple[Run, Drop]]:
+ ffi = ModuleType("pyodide.ffi")
+ ffi.__dict__["to_js"] = lambda data: data
+ monkeypatch.setitem(sys.modules, "pyodide.ffi", ffi)
+ # This is the actual Python program shipped inside the browser worker. Only Pyodide's
+ # byte transport and its virtual filesystem root differ from the native interpreter.
+ source = (
+ Path("browser/src/director.ts")
+ .read_text(encoding="utf-8")
+ .split("const RUNNER = `\n", 1)[1]
+ )
+ module = ModuleType("browser_runner")
+ exec(source.split("\n`;", 1)[0], module.__dict__)
+ module.__dict__["FILMS"] = tmp_path
+ run = cast(Run, module.__dict__["run"])
+ drop = cast(Drop, module.__dict__["drop"])
+ previous = sys.modules.get("scene")
+ try:
+ yield run, drop
+ finally:
+ for directory in tmp_path.iterdir():
+ if directory.is_dir():
+ drop(int(directory.name))
+ if previous is not None:
+ sys.modules["scene"] = previous
+
+
+SCENE = """
+from pathlib import Path
+from manimgx import Scene
+
+class Film(Scene):
+ def render(self, *, take):
+ path = Path(__file__).with_name("cache.txt")
+ with path.open("a", encoding="utf-8") as stream:
+ stream.write("one")
+ take(b"one")
+"""
+
+
+def test_film_drop_owns_its_source_cache_and_module(
+ runner: tuple[Run, Drop], tmp_path: Path
+) -> None:
+ run, drop = runner
+ out: list[bytes] = []
+ assert run(1, SCENE, None, out.append, []) is None
+ assert out[-1] == b"one"
+ first = tmp_path / "1" / "scene.py"
+ assert linecache.getline(str(first), 2) == "from pathlib import Path\n"
+ assert run(2, SCENE, None, out.append, []) is None
+ second = sys.modules["scene"]
+ drop(1)
+ drop(1) # a repeated detach does not own any new work
+ assert not first.parent.exists()
+ assert str(first) not in linecache.cache
+ assert sys.modules["scene"] is second
+ assert (tmp_path / "2" / "cache.txt").read_text(encoding="utf-8") == "one"
+ drop(2)
+ assert not (tmp_path / "2").exists()
+ assert "scene" not in sys.modules
+
+
+def test_same_film_edits_preserve_files_and_execute_the_supplied_source(
+ runner: tuple[Run, Drop], tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ run, _ = runner
+ write_text = Path.write_text
+
+ def write(path: Path, source: str, *, encoding: str) -> int:
+ size = write_text(path, source, encoding=encoding)
+ # Browser edits routinely have the same length and land within one filesystem clock
+ # tick. Python's timestamp bytecode cache must not substitute the previous source.
+ os.utime(path, (1_700_000_000, 1_700_000_000))
+ return size
+
+ monkeypatch.setattr(Path, "write_text", write)
+ monkeypatch.setattr(sys, "dont_write_bytecode", False)
+ out: list[bytes] = []
+ run(1, SCENE, None, out.append, [])
+ assert out[-1] == b"one"
+ run(1, SCENE.replace("one", "two"), None, out.append, [])
+ assert out[-1] == b"two"
+ assert (tmp_path / "1" / "cache.txt").read_text(encoding="utf-8") == "onetwo"
+
+
+def test_failed_and_retrying_films_release_their_source_on_drop(
+ runner: tuple[Run, Drop], tmp_path: Path
+) -> None:
+ run, drop = runner
+ out: list[bytes] = []
+ assert run(1, "raise ValueError('bad scene')", None, out.append, []) is None
+ assert out
+ assert run(
+ 2, "import nonexistent_browser_scene_dependency", None, out.append, []
+ ) == ("nonexistent_browser_scene_dependency")
+ for film in [1, 2]:
+ assert (tmp_path / str(film) / "scene.py").is_file()
+ drop(film)
+ assert not (tmp_path / str(film)).exists()