The open source AI video agent: turns any coding agent into a video agent, with an editor to change anything it makes.
Windows: tests pass on windows-latest (#1)
riverisbuildingf4861889b3a5
diff --git a/.changeset/windows-fixes.md b/.changeset/windows-fixes.mdnew file mode 100644index 0000000..158faf5--- /dev/null+++ b/.changeset/windows-fixes.md@@ -0,0 +1,7 @@+---+"openfilm": patch+---++Windows: an ffmpeg that is stopped (a cancelled render or export, a mix that runs too long) ends with the real ffmpeg+behind a Chocolatey or Scoop shim; a name with a `:` is cleaned on import, rename and new folders as on macOS and+Linux, not refused; Studio's supervisor opens the null device by its Windows name.diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 9734f0a..06fe40e 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -16,6 +16,8 @@ jobs:matrix:os: [ubuntu-latest, macos-latest, windows-latest]runs-on: ${{ matrix.os }}+ # a test that hangs ends the job, not hours later+ timeout-minutes: 45env:# the tests never start Electron: no need for its 100 MB downloadELECTRON_SKIP_BINARY_DOWNLOAD: '1'diff --git a/packages/openfilm/package.json b/packages/openfilm/package.jsonindex fedb32d..3dcd7ab 100644--- a/packages/openfilm/package.json+++ b/packages/openfilm/package.json@@ -60,7 +60,7 @@},"scripts": {"dev": "node scripts/dev.mjs",- "test": "node --test --test-concurrency=1 --test-timeout=120000 src/*.test.mjs studio/*.test.mjs studio/server/*.test.mjs studio/server/providers/*.test.mjs studio/ui/src/editor/*.test.ts studio/ui/src/lib/*.test.ts",+ "test": "node --test --test-concurrency=1 --test-timeout=300000 src/*.test.mjs studio/*.test.mjs studio/server/*.test.mjs studio/server/providers/*.test.mjs studio/ui/src/editor/*.test.ts studio/ui/src/lib/*.test.ts","typecheck": "tsc -p studio/server && tsc -p studio/ui","build:ui": "vite build --config studio/ui/vite.config.ts","prepare": "npm run build:ui",diff --git a/packages/openfilm/src/render.mjs b/packages/openfilm/src/render.mjsindex 2d58518..20f8653 100644--- a/packages/openfilm/src/render.mjs+++ b/packages/openfilm/src/render.mjs@@ -4,7 +4,7 @@ import { mkdirSync, rmSync, writeFileSync } from 'node:fs';import { availableParallelism, totalmem } from 'node:os';import { basename, dirname, extname, join, resolve } from 'node:path';import { FilmPage } from './host.mjs';-import { ffmpeg, filmSound, fmt, mix, open, outDir, parseTarget, shown, UsageError, write } from './shared.mjs';+import { ffmpeg, filmSound, fmt, kill, mix, open, outDir, parseTarget, shown, UsageError, write } from './shared.mjs';const BT709 = ['-colorspace', 'bt709', '-color_primaries', 'bt709', '-color_trc', 'bt709', '-color_range', 'tv'];const TAG_709 = ['-bsf:v', 'h264_metadata=colour_primaries=1:transfer_characteristics=1:matrix_coefficients=1:video_full_range_flag=0'];@@ -133,7 +133,7 @@ async function encode({ film, a, b, file }, { fps, samples, shutter, duration, f'-vf', blur + format.pix, '-r', String(fps), ...format.video, file], { input: true });/* a cancelled render stops its encoder at once: the frames ffmpeg still holds are thrown away, not encoded (a 4Kencode takes seconds to drain); the parts folder goes with it (see render's finally) */- const stop = () => enc.proc.kill('SIGKILL');+ const stop = () => kill(enc.proc);enc.proc.stdin.on('error', () => {});signal?.addEventListener('abort', stop, { once: true });try {diff --git a/packages/openfilm/src/shared.d.mts b/packages/openfilm/src/shared.d.mtsindex 2a26fec..788e6ce 100644--- a/packages/openfilm/src/shared.d.mts+++ b/packages/openfilm/src/shared.d.mts@@ -16,5 +16,7 @@ export declare function open(target: string, opts?: { root?: string }): Promise</** The film's sound from `from` seconds on, as clips to mix: its sound clips and its videos' own sound. */export declare function filmSound(s: OpenFilm, from: number): Promise<MixClip[]>;export declare class UsageError extends Error {}+/** Stop a process at once, with its children on Windows. */+export declare function kill(proc: import('node:child_process').ChildProcess): void;/** Run ffmpeg (`-nostdin`, errors only) with `args`; rejects with its error, or when it runs past `timeoutMs`. */export declare function ffmpeg(args: string[], opts?: { input?: boolean; timeoutMs?: number; what?: string }): { proc: import('node:child_process').ChildProcess; done: Promise<void> };diff --git a/packages/openfilm/src/shared.mjs b/packages/openfilm/src/shared.mjsindex a59ecdc..fc94151 100644--- a/packages/openfilm/src/shared.mjs+++ b/packages/openfilm/src/shared.mjs@@ -105,6 +105,17 @@ export function shown(path) {export const fmt = (t) => `${Number(t.toFixed(3))}s`;export const hash = (buf) => createHash('sha1').update(buf).digest('hex').slice(0, 12);+/**+ * Stop a process at once. On Windows ffmpeg is often a shim (Chocolatey, Scoop) that runs the real one as its child:+ * the whole tree goes, or the real one runs on and holds the pipes open.+ * @param {import('node:child_process').ChildProcess} proc+ */+export function kill(proc) {+ if (proc.exitCode !== null || proc.signalCode !== null) return;+ if (process.platform === 'win32' && proc.pid) spawn('taskkill', ['/pid', String(proc.pid), '/T', '/F'], { stdio: 'ignore', windowsHide: true }).on('error', () => proc.kill());+ else proc.kill('SIGKILL');+}+/** Run ffmpeg; `timeoutMs`: stop it and fail with `what` when it has not finished by then. */export function ffmpeg(args, { input = false, timeoutMs = 0, what = 'ffmpeg' } = {}) {/* -nostdin: ffmpeg never reads keys from a terminal it was started in (an agent's shell is one) */@@ -112,7 +123,7 @@ export function ffmpeg(args, { input = false, timeoutMs = 0, what = 'ffmpeg' } =let err = '';proc.stderr.on('data', (d) => { err += d; });let late = false;- const timer = timeoutMs > 0 ? setTimeout(() => { late = true; proc.kill('SIGKILL'); }, timeoutMs) : null;+ const timer = timeoutMs > 0 ? setTimeout(() => { late = true; kill(proc); }, timeoutMs) : null;timer?.unref();const done = new Promise((ok, fail) => {proc.on('error', (e) => fail(new Error(`ffmpeg: ${e.code === 'ENOENT' ? 'not found on the PATH' : e.message}`)));diff --git a/packages/openfilm/src/timeline.test.mjs b/packages/openfilm/src/timeline.test.mjsindex 4acbfd3..c3861e9 100644--- a/packages/openfilm/src/timeline.test.mjs+++ b/packages/openfilm/src/timeline.test.mjs@@ -362,6 +362,8 @@ test('watched, a film shows the video on at the moment first asked for, sought ofor (const [t, id, want] of [[0, 'first', 0], [2.5, 'later', 1.5]]) {/* a page just loaded, as Studio's preview comes up: nothing drawn yet, the first moment asked for by a person */await s.film.page.reload();+ /* window.film may not be there yet when the reload resolves */+ await s.film.page.waitForFunction(() => Boolean(window.film));await s.film.page.evaluate(() => window.film.ready);const seen = await s.film.page.evaluate(async ([t, id]) => {const v = document.getElementById(id);diff --git a/packages/openfilm/studio/server/browse.test.mjs b/packages/openfilm/studio/server/browse.test.mjsindex cb5b8a2..aa4e9c4 100644--- a/packages/openfilm/studio/server/browse.test.mjs+++ b/packages/openfilm/studio/server/browse.test.mjs@@ -7,7 +7,7 @@ import { BrowseError, browseFolder, browsePlaces, within } from './browse.mjs';let root, outside;before(() => {- const scratch = realpathSync(mkdtempSync(join(tmpdir(), 'of-browse-')));+ const scratch = realpathSync.native(mkdtempSync(join(tmpdir(), 'of-browse-')));root = join(scratch, 'home');outside = join(scratch, 'elsewhere');mkdirSync(join(root, 'Films', 'Launch'), { recursive: true });diff --git a/packages/openfilm/studio/server/exports.mjs b/packages/openfilm/studio/server/exports.mjsindex a1be42b..c0f06ec 100644--- a/packages/openfilm/studio/server/exports.mjs+++ b/packages/openfilm/studio/server/exports.mjs@@ -55,7 +55,7 @@ import { homedir, tmpdir } from 'node:os';import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';import { fileURLToPath } from 'node:url';import { FilmPage, launch } from '../../src/host.mjs';-import { filmSound, mix, open } from '../../src/shared.mjs';+import { filmSound, kill as killProcess, mix, open } from '../../src/shared.mjs';import { FILM_FILE, clipFade, filmHtml, fittedFade, kindOf, pictureRect, readFilmFile } from '../../src/film-doc.mjs';import { NLE_FPS, nleFps, planNleTimeline, probeSource, soundStem, xmemlDocument } from './nle.mjs';import { slidesPdf, writePptx } from './slides.mjs';@@ -371,7 +371,7 @@ function run(args, signal, input) {const proc = spawn('ffmpeg', ['-hide_banner', '-nostdin', '-loglevel', 'error', '-y', ...args], { stdio: [input ? 'pipe' : 'ignore', 'ignore', 'pipe'], windowsHide: true });let err = '';proc.stderr?.on('data', (d) => { err += d; });- const kill = () => proc.kill('SIGKILL');+ const kill = () => killProcess(proc);signal.addEventListener('abort', kill, { once: true });proc.on('error', (e) => { signal.removeEventListener('abort', kill); fail(new Error(`ffmpeg: ${/** @type {NodeJS.ErrnoException} */ (e).code === 'ENOENT' ? 'not found on the PATH' : e.message}`)); });proc.on('close', (code) => {diff --git a/packages/openfilm/studio/server/exports.test.mjs b/packages/openfilm/studio/server/exports.test.mjsindex 899b9e2..4a39d8d 100644--- a/packages/openfilm/studio/server/exports.test.mjs+++ b/packages/openfilm/studio/server/exports.test.mjs@@ -4,6 +4,7 @@ import { execFileSync, spawnSync } from 'node:child_process';import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';import { homedir, tmpdir } from 'node:os';import { join } from 'node:path';+import { fileURLToPath } from 'node:url';import { createExports, exportCapabilities, exportsRoot, ExportError, frameBox, dimsForShortEdge, projectFiles, projectSizes } from './exports.mjs';import { allocateLanes, containMotion, fadeKeyframes, frameSpan, nleRate, planNleTimeline, xmemlDocument } from './nle.mjs';import { pptxParts } from './slides.mjs';@@ -481,7 +482,7 @@ test('editing software: an xmeml folder; pages rendered with alpha, footage placassert.deepEqual(sounds, [['shot', 'TRUE', 0, 40], ['slow', 'TRUE', 40, 60], ['voice', 'TRUE', 5, 25], ['bed', 'FALSE', 0, 25]]);/* every clip's media is there for all of its frames; a sound at another speed is made as long as its clip, slowed orsped as the film plays it (an editor plays it at its own speed: shorter, it would stop halfway through its clip) */- const paths = new Map(found.video.flat().concat(found.audio.flat()).filter((c) => c.path).map((c) => [c.file, decodeURIComponent(c.path.replace(/^file:\/\/localhost/, ''))]));+ const paths = new Map(found.video.flat().concat(found.audio.flat()).filter((c) => c.path).map((c) => [c.file, fileURLToPath(c.path.replace(/^file:\/\/localhost\//, 'file:///'))]));for (const c of [...found.video.flat(), ...found.audio.flat()]) {const media = paths.get(c.file);if (/\.png$/.test(media)) continue;diff --git a/packages/openfilm/studio/server/files.mjs b/packages/openfilm/studio/server/files.mjsindex 1dbb443..a962e47 100644--- a/packages/openfilm/studio/server/files.mjs+++ b/packages/openfilm/studio/server/files.mjs@@ -110,6 +110,16 @@ export function cleanName(name) {return `${clean.slice(0, 120 - ext.length).trimEnd()}${ext}`;}+/**+ * A path as a person asked for it, before its name is cleaned: refused when it leaves the project or reaches into+ * `.film/`. The name is checked up to a `:`, which cleaning takes out (on Windows it would name a stream of a file).+ * @param {string} root @param {string} rel+ */+function askedInside(root, rel) {+ const cut = typeof rel === 'string' ? rel.lastIndexOf('/') : -1;+ inside(root, typeof rel === 'string' ? `${rel.slice(0, cut + 1)}${rel.slice(cut + 1).split(':')[0]}` : rel);+}+/** A project-relative path with its last part cleaned (cleanName); the folders before it are where it goes, as they are. */function cleanLast(/** @type {string} */ rel) {const cut = typeof rel === 'string' ? rel.lastIndexOf('/') : -1;@@ -189,7 +199,7 @@ let imports = 0;* @returns {Promise<{ path: string, reused: boolean }>}*/export async function importFile(root, rel, body) {- inside(root, rel);+ askedInside(root, rel);const asked = cleanLast(rel);const dir = dirname(inside(root, asked));await mkdir(dir, { recursive: true });@@ -223,7 +233,7 @@ export async function importFile(root, rel, body) {/** Make a folder under assets/ (a person's folder shows even while empty). */export async function makeFolder(/** @type {string} */ root, /** @type {string} */ asked) {- inside(root, asked);+ askedInside(root, asked);const rel = cleanLast(asked);const abs = inside(root, rel);if (existsSync(abs)) throw new FileError(`${rel} is already there`, 409);@@ -239,7 +249,7 @@ export async function makeFolder(/** @type {string} */ root, /** @type {string}*/export async function moveFile(root, from, asked) {const src = inside(root, from);- inside(root, asked);+ askedInside(root, asked);const to = cleanLast(asked);const dst = inside(root, to);if (!existsSync(src)) throw new FileError(`${from} is not there`, 404);diff --git a/packages/openfilm/studio/server/history.test.mjs b/packages/openfilm/studio/server/history.test.mjsindex 31f45f0..303f0c0 100644--- a/packages/openfilm/studio/server/history.test.mjs+++ b/packages/openfilm/studio/server/history.test.mjs@@ -2,12 +2,13 @@ import { test, before } from 'node:test';import assert from 'node:assert/strict';import { execFileSync } from 'node:child_process';import { randomBytes } from 'node:crypto';-import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, renameSync, statSync, utimesSync, writeFileSync } from 'node:fs';+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, statSync, utimesSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';import {checkout, commitChanges, deleteBranch, discardChanges, historyFiles, log, mergeBranch, renameBranch, restoreCommit, status,} from './history.mjs';+import { replaceFile } from './atomic.mjs';let trash;before(() => {@@ -334,7 +335,8 @@ test('a project moved or renamed keeps its history: every call names the folder/* as git init wrote it, and as an earlier Studio left it: where the folder was */execFileSync('git', ['--git-dir', gitDir(before), 'config', 'core.worktree', before]);const root = join(before, '..', `${before.split(/[\\/]/).pop()}-moved`);- renameSync(before, root);+ /* the commit's tidy-up (git gc --auto) may still be running in the folder: Windows refuses the move for a moment */+ await replaceFile(before, root);assert.equal(worktree(root), before, 'the history still says the old folder');assert.deepEqual((await log(root)).map((c) => c.message), ['First cut']);assert.equal(worktree(root), root, 'and says the new one once used');diff --git a/packages/openfilm/studio/server/main.mjs b/packages/openfilm/studio/server/main.mjsindex 605668d..da86373 100644--- a/packages/openfilm/studio/server/main.mjs+++ b/packages/openfilm/studio/server/main.mjs@@ -12,14 +12,14 @@*/import { spawn } from 'node:child_process';import { fstatSync, openSync, readFileSync } from 'node:fs';-import { setPriority } from 'node:os';+import { devNull, setPriority } from 'node:os';import { join } from 'node:path';import { fileURLToPath } from 'node:url';/* fds 0–2 open before anything else is: a launcher that closed one (a detached shell, a service) would make everyspawn of ffmpeg, ffprobe or git fail with EBADF from then on, while the page still says Studio is up */for (const fd of [0, 1, 2]) {- try { fstatSync(fd); } catch { openSync('/dev/null', fd === 0 ? 'r' : 'a'); }+ try { fstatSync(fd); } catch { openSync(devNull, fd === 0 ? 'r' : 'a'); }}/* below the person's own apps: an export or a poster never takes the computer from them, and what Studio starts(its browsers, ffmpeg) runs at this priority too */diff --git a/packages/openfilm/studio/server/main.test.mjs b/packages/openfilm/studio/server/main.test.mjsindex 731d2ff..37be933 100644--- a/packages/openfilm/studio/server/main.test.mjs+++ b/packages/openfilm/studio/server/main.test.mjs@@ -6,8 +6,9 @@ import { mkdtempSync, readFileSync, rmSync } from 'node:fs';import { createServer } from 'node:net';import { tmpdir } from 'node:os';import { join } from 'node:path';+import { fileURLToPath } from 'node:url';-const MAIN = new URL('./main.mjs', import.meta.url).pathname;+const MAIN = fileURLToPath(new URL('./main.mjs', import.meta.url));const sleep = (ms) => new Promise((r) => setTimeout(r, ms));const freePort = () => new Promise((done) => { const s = createServer().listen(0, '127.0.0.1', () => { const { port } = /** @type {import('node:net').AddressInfo} */ (s.address()); s.close(() => done(port)); }); });@@ -51,6 +52,8 @@ test('a Studio that ends unexpectedly is started again on the same address; oneassert.equal(await Promise.race([ended, sleep(15_000).then(() => 'still running')]), 0);} finally {if (supervisor.exitCode === null) supervisor.kill('SIGKILL');+ /* its Studio too, when the test failed before it quit: a killed supervisor leaves it running */+ try { process.kill(JSON.parse(readFileSync(join(home, 'run.json'), 'utf8')).pid, 'SIGKILL'); } catch { /* gone */ }rmSync(home, { recursive: true, force: true });}});