seoanything-cli 2.3.0 → 2.4.0

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.
package/src/cli.test.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { readFileSync } from "node:fs";
2
- import { describe, expect, it } from "vitest";
2
+ import { describe, expect, it, vi } from "vitest";
3
3
  import { EXIT, main, parse } from "./cli.js";
4
4
  import { exitCodeFor } from "./api.js";
5
5
 
@@ -28,6 +28,23 @@ describe("exit codes (TRD §17.1)", () => {
28
28
  expect((await run(["--help"])).code).toBe(0);
29
29
  expect((await run(["--version"])).out).toContain(JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version);
30
30
  });
31
+ it("sites task refuses a bad rule or status before calling the server", async () => {
32
+ const id = "0123456789abcdef01234567";
33
+ expect((await run(["sites", "task", id, "title_missing"])).code).toBe(2);
34
+ expect((await run(["sites", "task", id, "title_missing", "done", "--server", "http://127.0.0.1:9"])).code).toBe(2);
35
+ expect((await run(["sites", "task", id, "../crawls", "fixed", "--server", "http://127.0.0.1:9"])).code).toBe(2);
36
+ expect((await run(["sites", "crawl", "../x"])).code).toBe(2);
37
+ });
38
+ it("sites sync walks the parts the server names, then stops", async () => {
39
+ const seen = [];
40
+ vi.stubGlobal("fetch", async (url, init) => { const { part } = JSON.parse(init.body); seen.push(`${init.method} ${url} ${part}`); return new Response(JSON.stringify({ part, next: part < 5 ? part + 1 : null, rows: 2 }), { headers: { "content-type": "application/json" } }); });
41
+ try {
42
+ const r = await run(["sites", "sync", "0123456789abcdef01234567", "--server", "http://sa.test", "--json"]);
43
+ expect(r.code).toBe(0);
44
+ expect(JSON.parse(r.out).rows).toBe(10);
45
+ expect(seen).toEqual([1, 2, 3, 4, 5].map((n) => `POST http://sa.test/api/v1/visibility/sites/0123456789abcdef01234567/sync ${n}`));
46
+ } finally { vi.unstubAllGlobals(); }
47
+ });
31
48
  it("whoami without credentials exits 3; unreachable server exits 5", async () => {
32
49
  const env = { ...process.env }; delete process.env.SEOANYTHING_API_KEY; delete process.env.SEOANYTHING_TOKEN;
33
50
  process.env.XDG_CONFIG_HOME = "/nonexistent-seoanything-test";
@@ -37,3 +54,98 @@ describe("exit codes (TRD §17.1)", () => {
37
54
  process.env = env;
38
55
  });
39
56
  });
57
+
58
+ describe("B2 and B3 commands: live links, results by channel, topics, keyword map, CrUX, Bing", () => {
59
+ const post = "0123456789abcdef01234567", key = "linkedin:linkedin.com/posts/abc";
60
+ const results = { manualOnly: true, copies: [{ key, channel: "linkedin", label: "LinkedIn", url: "https://www.linkedin.com/posts/abc", totals: { days: 1, views: 120, clicks: 4, reactions: null, comments: null, shares: null }, days: [] }] };
61
+ const withFetch = async (body, fn) => {
62
+ const seen = [];
63
+ vi.stubGlobal("fetch", async (url, init) => { seen.push(`${init.method} ${url.replace("http://sa.test/api/v1", "")}${init.body ? ` ${init.body}` : ""}`); return new Response(JSON.stringify(body), { headers: { "content-type": "application/json" } }); });
64
+ try { await fn(); } finally { vi.unstubAllGlobals(); }
65
+ return seen;
66
+ };
67
+ const srv = ["--server", "http://sa.test"];
68
+ it("refuse bad ids, keys, days and numbers before calling the server", async () => {
69
+ for (const argv of [
70
+ ["blog", "results", "../x"], ["blog", "results", post, "set", key, "yesterday", "--views", "1"], ["blog", "results", post, "set", key, "2026-11-16"],
71
+ ["blog", "results", post, "set", key, "2026-11-16", "--views", "-3"], ["blog", "results", post, "drop", key, "2026-11-16"], ["blog", "unlink", post, "has spaces"],
72
+ ["blog", "link", post, "linkedin"], ["blog", "video", "../x"], ["keywords", "target", post, "../x", "none"], ["keywords", "lists", "../x"], ["plan"], ["sites", "crux", "../x"], ["bing", "key"],
73
+ ]) expect((await run([...argv, "--server", "http://127.0.0.1:9"])).code, argv.join(" ")).toBe(2);
74
+ });
75
+ it("call the routes, a copy key as one encoded path segment", async () => {
76
+ const seen = await withFetch(results, async () => {
77
+ expect((await run(["blog", "results", post, ...srv])).out).toContain("views 120 · clicks 4 · reactions –");
78
+ await run(["blog", "results", post, "set", key, "2026-11-16", "--views", "120", "--clicks", "4", ...srv]);
79
+ await run(["blog", "results", post, "remove", key, "2026-11-16", ...srv]);
80
+ await run(["blog", "link", post, "linkedin", "https://www.linkedin.com/posts/abc", "--replaces", "linkedin:linkedin.com/posts/old", ...srv]);
81
+ await run(["blog", "unlink", post, key, ...srv]);
82
+ });
83
+ const k = encodeURIComponent(key);
84
+ expect(seen).toEqual([
85
+ `GET /blog/posts/${post}/results`,
86
+ `PUT /blog/posts/${post}/results {"copyKey":"${key}","day":"2026-11-16","views":120,"clicks":4}`,
87
+ `DELETE /blog/posts/${post}/results/${k}/2026-11-16`,
88
+ `PUT /blog/posts/${post}/links {"channel":"linkedin","url":"https://www.linkedin.com/posts/abc","replaces":"linkedin:linkedin.com/posts/old"}`,
89
+ `DELETE /blog/posts/${post}/links/${k}`,
90
+ ]);
91
+ });
92
+ it("plan topics, keyword lists and targets, suggest with engines, crux and bing", async () => {
93
+ const seen = [];
94
+ const answer = (path) => path.endsWith("/plan/topics") ? { searchConsole: true, topics: [{ topic: "trail shoes", keywords: 3, written: 1, published: 1, clicks: 12, impressions: 300, position: 8.4, hasData: true, channels: ["linkedin"], items: [] }] }
95
+ : path.includes("/keywords/suggest") ? { q: "shoes", found: [{ text: "shoes for trail", engines: ["google", "youtube"] }], suggestions: ["shoes for trail"], engines: ["google", "youtube"] }
96
+ : path.includes("/keywords/") ? { targetUrl: null }
97
+ : path.endsWith("/crux") ? { origin: { origin: "https://example.com", url: null, phone: { ok: true, weeks: [{ end: "2026-11-15", lcp: 2100, inp: 180, cls: 0.05 }] }, desktop: { ok: false, reason: "no_data", message: "not enough data" } }, pages: [] }
98
+ : path.endsWith("/bing/stats") ? { days: 28, more: 0, sites: [{ url: "https://example.com/", clicks: 9, impressions: 80, daily: [], queries: [{ query: "trail shoes", clicks: 5 }] }, { url: "https://other.com/", error: "Couldn't read this site from Bing." }] }
99
+ : { items: [] };
100
+ const outs = [];
101
+ vi.stubGlobal("fetch", async (url, init) => { const path = url.replace("http://sa.test/api/v1", ""); seen.push(`${init.method} ${path}${init.body ? ` ${init.body}` : ""}`); return new Response(JSON.stringify(answer(path)), { headers: { "content-type": "application/json" } }); });
102
+ try {
103
+ for (const argv of [["plan", "topics"], ["keywords", "suggest", "shoes"], ["keywords", "lists"], ["keywords", "target", post, post, "none"], ["sites", "crux", post], ["bing"]]) { const r = await run([...argv, ...srv]); expect(r.code, argv.join(" ")).toBe(0); outs.push(r.out); }
104
+ } finally { vi.unstubAllGlobals(); }
105
+ expect(seen).toEqual(["GET /plan/topics", "GET /keywords/suggest?q=shoes&hl=en&geo=US", "GET /keyword-lists", `PATCH /keyword-lists/${post}/keywords/${post} {"targetUrl":null}`, `GET /visibility/sites/${post}/crux`, "GET /connections/bing/stats"]);
106
+ expect(outs[0]).toContain("12 clicks · 300 impressions · position 8.4 · on linkedin");
107
+ expect(outs[1]).toContain("shoes for trail · google, youtube");
108
+ expect(outs[3]).toBe("target page cleared.");
109
+ expect(outs[4]).toContain("LCP 2100 ms · INP 180 ms · CLS 0.05");
110
+ expect(outs[4]).toContain("not enough data");
111
+ expect(outs[5]).toContain("trail shoes (5)");
112
+ expect(outs[5]).toContain("Couldn't read this site from Bing.");
113
+ });
114
+ });
115
+
116
+ describe("blog video", () => {
117
+ const post = "0123456789abcdef01234567", srv = ["--server", "http://sa.test"];
118
+ const brief = { prompt: "Make this post into a 75 second film.", install: { skill: "npx skills add Moh4696/cinematic-skill", python: "pip install skia-python numpy pillow", ffmpeg: "brew install ffmpeg" }, script: { title: "Trail shoes", takes: [], fact_notes: [] } };
119
+ const withBrief = async (fn) => {
120
+ const seen = [];
121
+ vi.stubGlobal("fetch", async (url, init) => { seen.push(`${init.method} ${url.replace("http://sa.test/api/v1", "")}`); return new Response(JSON.stringify(brief), { headers: { "content-type": "application/json" } }); });
122
+ try { await fn(); } finally { vi.unstubAllGlobals(); }
123
+ return seen;
124
+ };
125
+ it("prints the install lines and the prompt, --json the full answer", async () => {
126
+ const seen = await withBrief(async () => {
127
+ const r = await run(["blog", "video", post, ...srv]);
128
+ expect(r.code).toBe(0);
129
+ expect(r.out).toContain(" npx skills add Moh4696/cinematic-skill\n pip install skia-python numpy pillow\n brew install ffmpeg");
130
+ expect(r.out).toContain("Make this post into a 75 second film.");
131
+ expect(JSON.parse((await run(["blog", "video", post, "--json", ...srv])).out)).toEqual(brief);
132
+ });
133
+ expect(seen).toEqual([`GET /blog/posts/${post}/video-brief`, `GET /blog/posts/${post}/video-brief`]);
134
+ });
135
+ it("--out writes script.json and replaces an existing file only with --force", async () => {
136
+ const { mkdtempSync, writeFileSync } = await import("node:fs");
137
+ const { tmpdir } = await import("node:os");
138
+ const file = `${mkdtempSync(`${tmpdir()}/sa-video-`)}/script.json`;
139
+ await withBrief(async () => {
140
+ expect((await run(["blog", "video", post, "--out", file, ...srv])).code).toBe(0);
141
+ expect(JSON.parse(readFileSync(file, "utf8"))).toEqual(brief.script);
142
+ writeFileSync(file, "mine");
143
+ const again = await run(["blog", "video", post, "--out", file, ...srv]);
144
+ expect(again.code).toBe(2);
145
+ expect(again.err).toContain("already exists");
146
+ expect(readFileSync(file, "utf8")).toBe("mine");
147
+ expect((await run(["blog", "video", post, "--out", file, "--force", ...srv])).code).toBe(0);
148
+ expect(JSON.parse(readFileSync(file, "utf8"))).toEqual(brief.script);
149
+ });
150
+ });
151
+ });
package/src/connect.js CHANGED
@@ -5,10 +5,11 @@
5
5
  // (`connect --code`, which the settings page hands to your own AI app) that can only open this computer's link.
6
6
  import { spawn } from "node:child_process";
7
7
  import { randomBytes } from "node:crypto";
8
- import { accessSync, closeSync, constants, mkdirSync, mkdtempSync, openSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
8
+ import { accessSync, closeSync, constants, copyFileSync, existsSync, mkdirSync, mkdtempSync, openSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
9
9
  import os from "node:os";
10
10
  import path from "node:path";
11
11
  import { StringDecoder } from "node:string_decoder";
12
+ import { fileURLToPath } from "node:url";
12
13
  import { CliError, client, exitCodeFor } from "./api.js";
13
14
  import { configDir, loadConfig, saveConfig } from "./config.js";
14
15
  import { VERSION } from "./mcp.js";
@@ -225,6 +226,174 @@ export async function runJob(job, { binaries, env = ownEnv(), signal, run = runP
225
226
  } finally { rmSync(root, { recursive: true, force: true }); }
226
227
  }
227
228
 
229
+ // ---------------------------------------------------------------- video: the cinematic-film skill's own scripts, run here
230
+ const VIDEO_MS = 40 * 60_000;
231
+ const VIDEO_LOOKS = ["wall", "studio", "blueprint", "night"];
232
+ const VIDEO_SIZES = ["1080x1920", "1920x1080"];
233
+ const SCENE_FILE = fileURLToPath(new URL("./film/scene_auto.py", import.meta.url));
234
+
235
+ /** Where the cinematic-film skill may be installed, first match wins. */
236
+ export function filmSkillDirs(source = process.env, home = os.homedir()) {
237
+ return [source.SEOANYTHING_FILM_SKILL, ...[".claude", ".agents", ".codex"].map((d) => path.join(home, d, "skills", "cinematic-film")), path.join(home, ".cinematic-skill", "skills", "cinematic-film")].filter(Boolean);
238
+ }
239
+
240
+ /** The skill folder plus python3 (with skia-python, numpy, pillow), ffmpeg/ffprobe and a free voice, or what is missing. */
241
+ export async function detectVideo({ env = ownEnv(), source = process.env, home = os.homedir(), run = runProcess } = {}) {
242
+ const missing = [];
243
+ const skill = filmSkillDirs(source, home).find((d) => existsSync(path.join(d, "scripts", "render.py")) && existsSync(path.join(d, "scripts", "engine.py")));
244
+ if (!skill) missing.push("the cinematic-film skill (https://github.com/Moh4696/cinematic-skill, or set SEOANYTHING_FILM_SKILL)");
245
+ const python = findBinary("python3", env);
246
+ let pyOk = false;
247
+ if (python) try { pyOk = (await run([python, "-c", "import skia, numpy, PIL"], { env, timeoutMs: 60_000 })).code === 0; } catch { /* stays false */ }
248
+ if (!pyOk) missing.push(python ? "skia-python, numpy or pillow (python3 -m pip install skia-python numpy pillow)" : "python3");
249
+ const ffmpeg = findBinary("ffmpeg", env);
250
+ if (!ffmpeg || !findBinary("ffprobe", env)) missing.push("ffmpeg");
251
+ if (!findBinary("say", env) && !findBinary("espeak-ng", env)) missing.push("a free voice (macOS say or espeak-ng)");
252
+ return missing.length ? { missing } : { skill, python, ffmpeg };
253
+ }
254
+
255
+ // one line of narration text: no control characters, no leading dash (never read as a flag), no say/SSML markup
256
+ const clean = (v, max) => String(v ?? "").replace(/[\u0000-\u001f\u007f<>]|\[\[|\]\]/g, " ").replace(/\s+/g, " ").replace(/^[\s-]+/, "").trim().slice(0, max);
257
+
258
+ /** A {"type":"video"} message, checked, with a rebuilt script.json (fresh ids and take names, every field capped). */
259
+ export function checkVideo(m) {
260
+ const bad = (msg) => new JobError("failed", msg);
261
+ if (typeof m?.id !== "string" || !/^[0-9a-f]{8,64}$/.test(m.id)) throw bad("invalid job id.");
262
+ if (!VIDEO_LOOKS.includes(m.look)) throw bad("unknown look.");
263
+ if (!VIDEO_SIZES.includes(m.size)) throw bad("unknown size.");
264
+ const s = m.script;
265
+ if (!s || typeof s !== "object" || !Array.isArray(s.takes)) throw bad("the script has no takes.");
266
+ let id = 0;
267
+ const takes = [];
268
+ for (const t of s.takes) {
269
+ if (!t || !Array.isArray(t.lines)) throw bad("a take has no lines.");
270
+ const lines = [];
271
+ for (const l of t.lines) {
272
+ if (!l || typeof l.text !== "string" || ["spoken", "typed", "hero"].some((k) => l[k] != null && typeof l[k] !== "string")) throw bad("each line needs text, and spoken, typed and hero must be text.");
273
+ const text = clean(l.text, 300), spoken = clean(l.spoken || l.text, 400);
274
+ if (!text || !spoken) throw bad("a line is empty.");
275
+ if (++id > 40) throw bad("a script can have at most 40 lines.");
276
+ const gap = typeof l.gap_after === "number" && l.gap_after >= 0 && l.gap_after <= 3 ? { gap_after: l.gap_after } : {};
277
+ lines.push({ id, text, spoken, hero: clean(l.hero, 160), typed: clean(l.typed, 80), ...gap });
278
+ }
279
+ if (lines.length) takes.push(lines);
280
+ }
281
+ if (!id) throw bad("the script has no lines.");
282
+ const dropped = fitWords(takes);
283
+ id = 0; // ids and take names again from 1, after any dropped lines
284
+ const named = takes.map((lines, i) => ({ take: `T${String(i + 1).padStart(2, "0")}`, lines: lines.map((l) => ({ ...l, id: ++id })) }));
285
+ const title = clean(m.title || s.title, 120) || "Video";
286
+ return { id: m.id, title, slug: typeof m.slug === "string" ? m.slug : title, look: m.look, size: m.size, script: { title, takes: named }, dropped };
287
+ }
288
+
289
+ // about 90 s of the free voice (~145 words a minute): Shorts, Reels and TikTok want under 90 s
290
+ export const MAX_WORDS = 215;
291
+ const words = (l) => l.spoken.split(" ").filter(Boolean).length;
292
+
293
+ /** Drop whole lines from the middle takes (never the first or last take) until the spoken words fit. Changes `takes` (arrays of lines); returns how many lines went. */
294
+ export function fitWords(takes, max = MAX_WORDS) {
295
+ let total = takes.flat().reduce((n, l) => n + words(l), 0), dropped = 0;
296
+ while (total > max) {
297
+ // the middle take with the most lines (the later one on a tie) gives up its last line
298
+ let pick = -1;
299
+ for (let i = 1; i < takes.length - 1; i++) if (takes[i].length && (pick < 0 || takes[i].length >= takes[pick].length)) pick = i;
300
+ if (pick < 0) break; // only the first and last takes are left: they stay whole
301
+ total -= words(takes[pick].pop());
302
+ dropped++;
303
+ }
304
+ for (let i = takes.length - 1; i >= 0; i--) if (!takes[i].length) takes.splice(i, 1);
305
+ return dropped;
306
+ }
307
+
308
+ /** A new folder ~/SEOAnything/videos/<slug>-<YYYYMMDD-HHMMSS> (slug [a-z0-9-], 60 chars at most), never an existing one. */
309
+ export function videoFolder(slug, now = new Date(), root = path.join(os.homedir(), "SEOAnything", "videos")) {
310
+ const s = String(slug ?? "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+/, "").slice(0, 60).replace(/-+$/, "") || "video";
311
+ const p2 = (n) => String(n).padStart(2, "0");
312
+ const base = path.join(root, `${s}-${now.getFullYear()}${p2(now.getMonth() + 1)}${p2(now.getDate())}-${p2(now.getHours())}${p2(now.getMinutes())}${p2(now.getSeconds())}`);
313
+ let dir = base;
314
+ for (let n = 2; existsSync(dir); n++) dir = `${base}-${n}`;
315
+ return dir;
316
+ }
317
+
318
+ /** The skill's steps after the project exists, in order, each with the progress it reports when done. */
319
+ export function videoSteps(dir, size) {
320
+ const p = ["--project", dir];
321
+ return [
322
+ { stage: "voice", pct: 15, args: ["tts_say.py", ...p] },
323
+ { stage: "timing", pct: 22, args: ["split_takes.py", ...p] },
324
+ { stage: "timing", pct: 28, args: ["build_narration.py", ...p] },
325
+ { stage: "assets", pct: 33, args: ["prep_assets.py", ...p] },
326
+ { stage: "sound", pct: 36, args: ["render.py", ...p, "--cues"] },
327
+ { stage: "sound", pct: 40, args: ["build_sfx.py", ...p] },
328
+ { stage: "sound", pct: 45, args: ["mix_soundtrack.py", ...p] },
329
+ { stage: "render", pct: 88, args: ["render.py", ...p, "--size", size, "--out", "out/film.mp4", "--audio", "audio/mix.m4a"] },
330
+ { stage: "captions", pct: 97, args: ["burn_captions.py", ...p, "--video", "out/film.mp4", "--audio", "audio/mix.m4a", "--out", "out/film_captions.mp4"], optional: true },
331
+ ];
332
+ }
333
+
334
+ /** Make one film in a new folder with the skill's scripts and the free voice. Resolves { path, seconds, bytes }. */
335
+ export async function runVideo(msg, { setup, env = ownEnv(), run = runProcess, signal, onProgress = () => {}, log = () => {}, root, now = new Date() } = {}) {
336
+ const job = checkVideo(msg);
337
+ if (job.dropped) log(` video: the script was over ${MAX_WORDS} words (about 90 s), so ${job.dropped} middle line${job.dropped > 1 ? "s were" : " was"} left out.`);
338
+ const dir = videoFolder(job.slug, now, root);
339
+ mkdirSync(path.dirname(dir), { recursive: true });
340
+ const scripts = path.join(setup.skill, "scripts");
341
+ const deadline = Date.now() + VIDEO_MS;
342
+ const exec = async (name, argv) => {
343
+ const left = deadline - Date.now();
344
+ if (left <= 0) throw new JobError("timeout", "the video took longer than 40 minutes.");
345
+ let r;
346
+ // idle limit = what is left: a render prints nothing while its chunks encode
347
+ try { r = await run(argv, { cwd: scripts, env, timeoutMs: left, idleMs: left, signal }); }
348
+ catch (e) {
349
+ if (e.code === "timeout") throw new JobError("timeout", "the video took longer than 40 minutes.");
350
+ if (e.code === "cancelled") throw new JobError("cancelled", "the video was cancelled.");
351
+ throw new JobError("failed", `${name}: ${e.message}`);
352
+ }
353
+ if (r.code !== 0) throw new JobError("failed", `${name} failed: ${(r.stderr.trim() || r.stdout.trim()).slice(-400)}`);
354
+ };
355
+ const py = ([script, ...args]) => exec(script, [setup.python, path.join(scripts, script), ...args]);
356
+ await py(["new_project.py", dir]);
357
+ mkdirSync(dir, { recursive: true });
358
+ const put = (name, data) => writeFileSync(path.join(dir, name), JSON.stringify(data, null, 1) + "\n");
359
+ put("script.json", job.script);
360
+ put("photos.json", { grade: "natural", photos: [], recreations: [] });
361
+ put("map.json", { maps: [] });
362
+ put("film.json", { look: job.look, size: job.size });
363
+ copyFileSync(SCENE_FILE, path.join(dir, "scene.py"));
364
+ onProgress("setup", 5);
365
+ let captioned = false;
366
+ for (const step of videoSteps(dir, job.size)) {
367
+ try { await py(step.args); }
368
+ catch (e) { if (!step.optional || e.code !== "failed") throw e; continue; } // no captions: the clean film is still a film
369
+ if (step.optional) captioned = true;
370
+ onProgress(step.stage, step.pct);
371
+ }
372
+ let file = path.join(dir, "out", captioned ? "film_captions.mp4" : "film.mp4");
373
+ if (!existsSync(file)) throw new JobError("failed", "the render finished without a film file.");
374
+ // a phone-sized copy (H.264 high, CRF 23, AAC 128k, faststart, same frame size); the big masters stay only if this fails.
375
+ // the 3 Mbit/s cap: the look's film grain kept CRF 23 alone at 11 Mbit/s (139 MB for 101 s); capped it is 35 MB
376
+ const small = path.join(dir, "out", "film_final.mp4");
377
+ if (setup.ffmpeg) {
378
+ try {
379
+ await exec("ffmpeg", [setup.ffmpeg, "-hide_banner", "-nostdin", "-loglevel", "error", "-y", "-i", file, "-c:v", "libx264", "-profile:v", "high", "-preset", "medium", "-crf", "23",
380
+ "-maxrate", "3M", "-bufsize", "6M", "-pix_fmt", "yuv420p", "-c:a", "aac", "-b:a", "128k", "-movflags", "+faststart", small]);
381
+ if (!statSync(small).size) throw new JobError("failed", "empty");
382
+ for (const f of ["film.mp4", "film_captions.mp4"]) rmSync(path.join(dir, "out", f), { force: true });
383
+ file = small;
384
+ } catch (e) {
385
+ if (e.code === "timeout" || e.code === "cancelled") throw e;
386
+ rmSync(small, { force: true });
387
+ log(` video: the phone-sized copy failed, keeping the full-size film (${String(e.message).slice(0, 200)})`);
388
+ }
389
+ }
390
+ onProgress("captions", 100);
391
+ const bytes = statSync(file).size;
392
+ let seconds = 0;
393
+ try { seconds = Math.round(JSON.parse(readFileSync(path.join(dir, "audio", "timing.json"), "utf8")).total_duration * 10) / 10 || 0; } catch { /* unknown length */ }
394
+ return { path: file, seconds, bytes };
395
+ }
396
+
228
397
  /** This computer's stable id, made once and kept in the config file. */
229
398
  export function deviceIdFor() {
230
399
  const cfg = loadConfig();
@@ -251,12 +420,12 @@ export async function pair({ server, code, deviceId = deviceIdFor(), hostname =
251
420
  }
252
421
 
253
422
  /** Re-run `connect` detached from this terminal or AI app, logging to a file, and return at once. */
254
- export function startBackground(server, { script = process.argv[1], spawnImpl = spawn } = {}) {
423
+ export function startBackground(server, { script = process.argv[1], spawnImpl = spawn, video = false } = {}) {
255
424
  mkdirSync(configDir(), { recursive: true, mode: 0o700 });
256
425
  const log = path.join(configDir(), "connect.log");
257
426
  const out = openSync(log, "w", 0o600);
258
427
  try {
259
- const child = spawnImpl(process.execPath, [script, "connect", "--server", server], { detached: true, stdio: ["ignore", out, out], windowsHide: true });
428
+ const child = spawnImpl(process.execPath, [script, "connect", "--server", server, ...(video ? ["--video"] : [])], { detached: true, stdio: ["ignore", out, out], windowsHide: true });
260
429
  child.unref();
261
430
  return { pid: child.pid, log };
262
431
  } finally { closeSync(out); }
@@ -266,7 +435,8 @@ export function startBackground(server, { script = process.argv[1], spawnImpl =
266
435
  * Connect and serve until the user stops it or the server disconnects this computer. Resolves with the reason.
267
436
  * `deviceToken` (from a setup code) wins over `token` (the user's login); `onUnlinked` runs when the cloud no longer accepts it.
268
437
  */
269
- export async function connect({ server, token, deviceToken, onUnlinked, log = console.error, hostname = os.hostname(), signal, WebSocketImpl = globalThis.WebSocket } = {}) {
438
+ export async function connect({ server, token, deviceToken, onUnlinked, log = console.error, hostname = os.hostname(), signal, WebSocketImpl = globalThis.WebSocket,
439
+ video = false, detectVideoImpl = detectVideo, runVideoImpl = runVideo } = {}) {
270
440
  if (!WebSocketImpl) throw new CliError("seoanything connect needs Node 22 or newer (built-in WebSocket).", 1);
271
441
  const api = client({ server, token });
272
442
  const deviceId = deviceIdFor();
@@ -275,7 +445,14 @@ export async function connect({ server, token, deviceToken, onUnlinked, log = co
275
445
  if (!found.length) throw new CliError("no AI CLI found on PATH. install claude, codex or agy, sign in to it once, then run connect again.", 1);
276
446
  for (const f of found) log(`✓ found ${KINDS[f.kind].label} ${f.version} at ${f.path}`);
277
447
  let binaries = Object.fromEntries(found.map((f) => [f.kind, f.path]));
278
- const hello = () => ({ type: "hello", deviceId, name: hostname.slice(0, 80), platform: process.platform, version: VERSION, clis: found.map((f) => ({ kind: f.kind, version: f.version, models: f.models })), features: ["rescan"] });
448
+ // --video: offered only when the skill and its tools are all here
449
+ let film = null;
450
+ if (video) {
451
+ const v = await detectVideoImpl({ env });
452
+ if (v.missing) log(`! video is off: missing ${v.missing.join("; ")}.`);
453
+ else { film = v; log(`✓ video: cinematic-film at ${v.skill}, films go to ${path.join(os.homedir(), "SEOAnything", "videos")}`); }
454
+ }
455
+ const hello = () => ({ type: "hello", deviceId, name: hostname.slice(0, 80), platform: process.platform, version: VERSION, clis: found.map((f) => ({ kind: f.kind, version: f.version, models: f.models })), features: film ? ["rescan", "video"] : ["rescan"] });
279
456
  // asked from the settings page: pick up a CLI installed since this connector started, without a restart
280
457
  async function rescan(ws) {
281
458
  const now = await detect(env);
@@ -288,7 +465,9 @@ export async function connect({ server, token, deviceToken, onUnlinked, log = co
288
465
  const jobs = new Map();
289
466
  let socket, attempt = 0, stopped = false, finish;
290
467
  const done = new Promise((r) => (finish = r));
291
- const stop = (reason) => { if (stopped) return; stopped = true; for (const j of jobs.values()) j.abort(); try { socket?.close(1000); } catch { /* closed */ } finish(reason); };
468
+ let videoJob = null; // { id, ac, last }: one film at a time, beside the chat jobs (it never takes one of their MAX_JOBS slots)
469
+ let unsentVideo = null; // a film's last word (done or failed) that went out while the link was down: sent again on the next welcome
470
+ const stop = (reason) => { if (stopped) return; stopped = true; for (const j of jobs.values()) j.abort(); videoJob?.ac.abort(); try { socket?.close(1000); } catch { /* closed */ } finish(reason); };
292
471
  signal?.addEventListener("abort", () => stop("connector closed. your chats fall back to the cloud models until you run connect again."), { once: true });
293
472
  const send = (ws, m) => { if (ws.readyState === 1) ws.send(JSON.stringify(m)); };
294
473
 
@@ -316,6 +495,31 @@ export async function connect({ server, token, deviceToken, onUnlinked, log = co
316
495
  } finally { clearTimeout(flushTimer); jobs.delete(job.id); }
317
496
  }
318
497
 
498
+ // a film outlives a dropped link: it reports on whichever socket is open, and repeats its progress so the cloud knows it is alive
499
+ async function startVideo(m) {
500
+ if (typeof m.id !== "string") return;
501
+ const tell = (msg) => socket && send(socket, msg);
502
+ // the link can drop mid-film (Wi-Fi, DNS): the final answer is kept until a socket takes it
503
+ const final = (msg) => { if (socket?.readyState === 1) send(socket, msg); else unsentVideo = msg; };
504
+ const fail = (code, message) => final({ type: "video_failed", id: m.id, code, message });
505
+ if (!film) return fail("missing_setup", "this computer was not started with --video, or is missing the film tools.");
506
+ if (videoJob) return fail("busy", "this computer is already making a video.");
507
+ const ac = new AbortController();
508
+ videoJob = { id: m.id, ac, last: { type: "video_progress", id: m.id, stage: "setup", pct: 0 } };
509
+ const job = videoJob;
510
+ const beat = setInterval(() => tell(job.last), 60_000);
511
+ log(`→ video: making "${String(m.title ?? "").slice(0, 80)}"…`);
512
+ try {
513
+ const r = await runVideoImpl(m, { setup: film, env, signal: ac.signal, log, onProgress: (stage, pct) => { job.last = { type: "video_progress", id: m.id, stage, pct }; tell(job.last); } });
514
+ final({ type: "video_done", id: m.id, ...r });
515
+ log(`✓ video: ${r.path}`);
516
+ } catch (e) {
517
+ const code = ["timeout", "cancelled", "missing_setup"].includes(e.code) ? e.code : "failed";
518
+ fail(code, String(e.message ?? "the video failed").slice(0, 400));
519
+ log(`✗ video: ${e.message}`);
520
+ } finally { clearInterval(beat); videoJob = null; }
521
+ }
522
+
319
523
  async function open() {
320
524
  if (stopped) return;
321
525
  let url;
@@ -333,10 +537,18 @@ export async function connect({ server, token, deviceToken, onUnlinked, log = co
333
537
  });
334
538
  ws.addEventListener("message", (ev) => {
335
539
  let m; try { m = JSON.parse(String(ev.data)); } catch { return; }
336
- if (m.type === "welcome") { attempt = 0; log(`✓ linked to ${server} as "${hostname}". chats and blog posts can now use your CLI while this keeps running.`); }
540
+ if (m.type === "welcome") {
541
+ attempt = 0;
542
+ // back after a drop: say where the film is, or how it ended, so the website doesn't give up on it
543
+ if (videoJob) send(ws, videoJob.last);
544
+ if (unsentVideo) { send(ws, unsentVideo); unsentVideo = null; }
545
+ log(`✓ linked to ${server} as "${hostname}". chats and blog posts can now use your CLI while this keeps running.`);
546
+ }
337
547
  else if (m.type === "run") startJob(ws, m);
338
548
  else if (m.type === "rescan") rescan(ws);
339
549
  else if (m.type === "cancel") jobs.get(m.id)?.abort();
550
+ else if (m.type === "video") startVideo(m);
551
+ else if (m.type === "video_cancel") { if (videoJob?.id === m.id) videoJob.ac.abort(); }
340
552
  else if (m.type === "revoked") { if (deviceToken) onUnlinked?.(); stop("this computer was disconnected in SEOAnything settings."); }
341
553
  });
342
554
  ws.addEventListener("close", (ev) => {
@@ -1,8 +1,8 @@
1
- import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
1
+ import { mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
2
2
  import os from "node:os";
3
3
  import path from "node:path";
4
4
  import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
5
- import { buildArgs, checkJob, connect, deltaOf, listModels, ownEnv, pair, parseModels, parseOutput, runJob, startBackground } from "./connect.js";
5
+ import { JobError, buildArgs, checkJob, checkVideo, connect, deltaOf, detectVideo, filmSkillDirs, fitWords, listModels, ownEnv, pair, parseModels, parseOutput, runJob, runVideo, startBackground, videoFolder } from "./connect.js";
6
6
 
7
7
  const job = { kind: "claude", prompt: "say ok", system: "be brief", timeout: 60 };
8
8
  let root;
@@ -147,6 +147,8 @@ describe("linking with a setup code", () => {
147
147
  const [cmd, args, opts] = spawnImpl.mock.calls[0];
148
148
  expect([cmd, args]).toEqual([process.execPath, ["/bin/seo.js", "connect", "--server", server]]);
149
149
  expect(opts.detached).toBe(true); expect(child.unref).toHaveBeenCalled();
150
+ startBackground(server, { script: "/bin/seo.js", spawnImpl, video: true });
151
+ expect(spawnImpl.mock.calls[1][1]).toEqual(["/bin/seo.js", "connect", "--server", server, "--video"]);
150
152
  });
151
153
 
152
154
  it("links with the computer token, says hello once per scan, and looks again when asked", async () => {
@@ -168,6 +170,45 @@ describe("linking with a setup code", () => {
168
170
  expect(await done).toMatch(/connector closed/);
169
171
  });
170
172
 
173
+ it("offers video only with --video and the tools found, runs one film at a time and cancels it", async () => {
174
+ FakeSocket.all = [];
175
+ vi.stubGlobal("fetch", vi.fn(async () => Response.json({ url: "wss://seo.test/x" })));
176
+ const ac = new AbortController();
177
+ const runVideoImpl = vi.fn((_m, { signal, onProgress }) => new Promise((_, reject) => {
178
+ onProgress("voice", 15);
179
+ signal.addEventListener("abort", () => reject(new JobError("cancelled", "the video was cancelled.")));
180
+ }));
181
+ const done = connect({ server, deviceToken: "u1.tok", log: () => {}, signal: ac.signal, WebSocketImpl: FakeSocket, video: true, detectVideoImpl: async () => ({ skill: "/s", python: "/py" }), runVideoImpl });
182
+ await vi.waitFor(() => expect(FakeSocket.all[0]?.sent.length).toBe(1), { timeout: 5000 });
183
+ const ws = FakeSocket.all[0];
184
+ expect(ws.sent[0].features).toEqual(["rescan", "video"]);
185
+ ws.emit("message", { data: JSON.stringify({ type: "video", id: "aa11", look: "night", size: "1920x1080", script: {} }) });
186
+ ws.emit("message", { data: JSON.stringify({ type: "video", id: "bb22" }) });
187
+ expect(ws.sent.slice(1)).toEqual([
188
+ { type: "video_progress", id: "aa11", stage: "voice", pct: 15 },
189
+ { type: "video_failed", id: "bb22", code: "busy", message: "this computer is already making a video." },
190
+ ]);
191
+ ws.emit("message", { data: JSON.stringify({ type: "video_cancel", id: "aa11" }) });
192
+ await vi.waitFor(() => expect(ws.sent.at(-1)).toMatchObject({ type: "video_failed", id: "aa11", code: "cancelled" }));
193
+ expect(runVideoImpl).toHaveBeenCalledOnce();
194
+ ac.abort();
195
+ await done;
196
+ });
197
+
198
+ it("leaves video off and says what is missing", async () => {
199
+ FakeSocket.all = [];
200
+ vi.stubGlobal("fetch", vi.fn(async () => Response.json({ url: "wss://seo.test/x" })));
201
+ const ac = new AbortController(), logs = [];
202
+ const done = connect({ server, deviceToken: "u1.tok", log: (s) => logs.push(s), signal: ac.signal, WebSocketImpl: FakeSocket, video: true, detectVideoImpl: async () => ({ missing: ["ffmpeg"] }) });
203
+ await vi.waitFor(() => expect(FakeSocket.all[0]?.sent.length).toBe(1), { timeout: 5000 });
204
+ expect(FakeSocket.all[0].sent[0].features).toEqual(["rescan"]);
205
+ expect(logs).toContain("! video is off: missing ffmpeg.");
206
+ FakeSocket.all[0].emit("message", { data: JSON.stringify({ type: "video", id: "aa11" }) });
207
+ expect(FakeSocket.all[0].sent.at(-1)).toMatchObject({ type: "video_failed", code: "missing_setup" });
208
+ ac.abort();
209
+ await done;
210
+ });
211
+
171
212
  it("forgets the computer token when it is disconnected from the settings page", async () => {
172
213
  FakeSocket.all = [];
173
214
  vi.stubGlobal("fetch", vi.fn(async () => Response.json({ url: "wss://seo.test/x" })));
@@ -202,3 +243,136 @@ describe("model lists", () => {
202
243
  expect(await listModels("codex", "/bin/codex", {}, async () => { throw new Error("boom"); })).toEqual([]);
203
244
  });
204
245
  });
246
+
247
+ describe("video", () => {
248
+ const line = (text, extra = {}) => ({ text, spoken: text, hero: "h", typed: "", ...extra });
249
+ const msg = (lines = [line("One."), line("Two.")], extra = {}) => ({ type: "video", id: "abcd1234", title: "NPL final", slug: "npl-final", look: "night", size: "1920x1080", script: { title: "x", takes: [{ take: "../evil", lines }] }, ...extra });
250
+ let tmp;
251
+ beforeEach(() => { tmp = mkdtempSync(path.join(os.tmpdir(), "vid-")); });
252
+ afterEach(() => rmSync(tmp, { recursive: true, force: true }));
253
+
254
+ it("looks for the skill in the env folder first, then the agent skill folders", () => {
255
+ expect(filmSkillDirs({ SEOANYTHING_FILM_SKILL: "/x" }, "/h")).toEqual(["/x", "/h/.claude/skills/cinematic-film", "/h/.agents/skills/cinematic-film", "/h/.codex/skills/cinematic-film", "/h/.cinematic-skill/skills/cinematic-film"]);
256
+ expect(filmSkillDirs({}, "/h")[0]).toBe("/h/.claude/skills/cinematic-film");
257
+ });
258
+
259
+ it("finds the skill, python with skia, ffmpeg and a voice, or names what is missing", async () => {
260
+ const bin = path.join(tmp, "bin"), skill = path.join(tmp, "home", ".codex", "skills", "cinematic-film", "scripts");
261
+ mkdirSync(bin); mkdirSync(skill, { recursive: true });
262
+ for (const b of ["python3", "ffmpeg", "ffprobe", "say"]) writeFileSync(path.join(bin, b), "#!/bin/sh\n", { mode: 0o755 });
263
+ for (const f of ["render.py", "engine.py"]) writeFileSync(path.join(skill, f), "");
264
+ const env = { PATH: bin }, home = path.join(tmp, "home");
265
+ const ok = vi.fn(async () => ({ code: 0, stdout: "", stderr: "" }));
266
+ expect(await detectVideo({ env, source: {}, home, run: ok })).toEqual({ skill: path.dirname(skill), python: path.join(bin, "python3"), ffmpeg: path.join(bin, "ffmpeg") });
267
+ expect(ok.mock.calls[0][0]).toEqual([path.join(bin, "python3"), "-c", "import skia, numpy, PIL"]);
268
+ const r = await detectVideo({ env, source: {}, home, run: async () => ({ code: 1, stdout: "", stderr: "No module named skia" }) });
269
+ expect(r.missing).toEqual([expect.stringMatching(/skia-python/)]);
270
+ rmSync(path.join(bin, "ffprobe")); rmSync(path.join(skill, "engine.py"));
271
+ expect((await detectVideo({ env, source: {}, home, run: ok })).missing).toEqual([expect.stringMatching(/cinematic-film skill/), "ffmpeg"]);
272
+ });
273
+
274
+ it("checks the message and rebuilds the script: fresh ids and take names, no dashes or markup, fields capped", () => {
275
+ const j = checkVideo(msg([line("-v Alex hi [[volm 0]]", { typed: "x".repeat(200), gap_after: 9 }), line("B", { spoken: "", gap_after: 1 })]));
276
+ expect(j.script.takes).toEqual([{ take: "T01", lines: [
277
+ { id: 1, text: "v Alex hi volm 0", spoken: "v Alex hi volm 0", hero: "h", typed: "x".repeat(80) },
278
+ { id: 2, text: "B", spoken: "B", hero: "h", typed: "", gap_after: 1 },
279
+ ] }]);
280
+ expect(j).toMatchObject({ id: "abcd1234", look: "night", size: "1920x1080", slug: "npl-final" });
281
+ expect(() => checkVideo(msg(undefined, { id: "../x" }))).toThrow(/job id/);
282
+ expect(() => checkVideo(msg(undefined, { look: "neon" }))).toThrow(/look/);
283
+ expect(() => checkVideo(msg(undefined, { size: "4k" }))).toThrow(/size/);
284
+ expect(() => checkVideo(msg(Array.from({ length: 41 }, () => line("a"))))).toThrow(/40 lines/);
285
+ expect(() => checkVideo(msg([line("a", { typed: 5 })]))).toThrow(/must be text/);
286
+ expect(() => checkVideo(msg([]))).toThrow(/no lines/);
287
+ expect(() => checkVideo({ ...msg(), script: "x" })).toThrow(/no takes/);
288
+ });
289
+
290
+ it("names a new folder from a clean slug and the time, never reusing one", () => {
291
+ const now = new Date(2026, 10, 17, 9, 5, 7);
292
+ expect(videoFolder("../NPL Final: Tickets!!", now, tmp)).toBe(path.join(tmp, "npl-final-tickets-20261117-090507"));
293
+ expect(path.basename(videoFolder("a".repeat(80), now, tmp))).toBe(`${"a".repeat(60)}-20261117-090507`);
294
+ expect(path.basename(videoFolder("", now, tmp))).toBe("video-20261117-090507");
295
+ mkdirSync(path.join(tmp, "x-20261117-090507"));
296
+ expect(path.basename(videoFolder("x", now, tmp))).toBe("x-20261117-090507-2");
297
+ });
298
+
299
+ // a fake skill run: records each script and writes what the real one would leave behind
300
+ const fakeRun = (calls, failOn) => async (argv, opts) => {
301
+ const script = argv[0] === "/ff" ? "ffmpeg" : path.basename(argv[1]), dir = argv[2] === "--project" ? argv[3] : argv[2];
302
+ calls.push({ script, args: argv.slice(script === "ffmpeg" ? 1 : 2), cwd: opts.cwd, env: opts.env });
303
+ if (script === failOn) return { code: 1, stdout: "", stderr: "Traceback...\nboom" };
304
+ if (script === "ffmpeg") { writeFileSync(argv.at(-1), "small"); return { code: 0, stdout: "", stderr: "" }; }
305
+ if (script === "build_narration.py") { mkdirSync(path.join(dir, "audio"), { recursive: true }); writeFileSync(path.join(dir, "audio", "timing.json"), '{"total_duration": 12.34}'); }
306
+ const out = opts && argv.includes("--out") ? argv[argv.indexOf("--out") + 1] : null;
307
+ if (out) { mkdirSync(path.join(dir, "out"), { recursive: true }); writeFileSync(path.join(dir, out), "mp4!"); }
308
+ return { code: 0, stdout: "", stderr: "" };
309
+ };
310
+
311
+ it("runs the skill's steps in order in a new folder and reports the phone-sized copy of the captioned film", async () => {
312
+ const calls = [], progress = [];
313
+ const r = await runVideo(msg(), { setup: { skill: "/skill", python: "/py", ffmpeg: "/ff" }, env: { PATH: "/bin" }, run: fakeRun(calls), onProgress: (s, p) => progress.push([s, p]), root: tmp, now: new Date(2026, 10, 17, 9, 5, 7) });
314
+ const dir = path.join(tmp, "npl-final-20261117-090507");
315
+ expect(calls.map((c) => c.script)).toEqual(["new_project.py", "tts_say.py", "split_takes.py", "build_narration.py", "prep_assets.py", "render.py", "build_sfx.py", "mix_soundtrack.py", "render.py", "burn_captions.py", "ffmpeg"]);
316
+ expect(calls[0].args).toEqual([dir]);
317
+ expect(calls[5].args).toEqual(["--project", dir, "--cues"]);
318
+ expect(calls[8].args).toEqual(["--project", dir, "--size", "1920x1080", "--out", "out/film.mp4", "--audio", "audio/mix.m4a"]);
319
+ expect(calls.every((c) => c.cwd === "/skill/scripts" && c.env.PATH === "/bin")).toBe(true);
320
+ const out = path.join(dir, "out");
321
+ expect(calls.at(-1).args).toEqual(["-hide_banner", "-nostdin", "-loglevel", "error", "-y", "-i", path.join(out, "film_captions.mp4"), "-c:v", "libx264", "-profile:v", "high", "-preset", "medium", "-crf", "23",
322
+ "-maxrate", "3M", "-bufsize", "6M", "-pix_fmt", "yuv420p", "-c:a", "aac", "-b:a", "128k", "-movflags", "+faststart", path.join(out, "film_final.mp4")]);
323
+ expect(progress.map((p) => p[0])).toEqual(["setup", "voice", "timing", "timing", "assets", "sound", "sound", "sound", "render", "captions", "captions"]);
324
+ expect(progress.slice(-2)).toEqual([["captions", 97], ["captions", 100]]);
325
+ expect(r).toEqual({ path: path.join(out, "film_final.mp4"), seconds: 12.3, bytes: 5 });
326
+ expect(readdirSync(out)).toEqual(["film_final.mp4"]); // the big masters are gone
327
+ expect(JSON.parse(readFileSync(path.join(dir, "film.json"), "utf8"))).toEqual({ look: "night", size: "1920x1080" });
328
+ expect(JSON.parse(readFileSync(path.join(dir, "script.json"), "utf8")).takes[0].take).toBe("T01");
329
+ expect(readFileSync(path.join(dir, "scene.py"), "utf8")).toMatch(/def build_film\(doc\)/);
330
+ });
331
+
332
+ it("hands over the clean film when captions fail, and stops with stderr's tail when a step fails", async () => {
333
+ const r = await runVideo(msg(), { setup: { skill: "/skill", python: "/py" }, run: fakeRun([], "burn_captions.py"), root: tmp });
334
+ expect(path.basename(r.path)).toBe("film.mp4"); // no ffmpeg in the setup: no small copy
335
+ const calls2 = [];
336
+ const r2 = await runVideo(msg(), { setup: { skill: "/skill", python: "/py", ffmpeg: "/ff" }, run: fakeRun(calls2, "burn_captions.py"), root: tmp });
337
+ expect(calls2.at(-1).args).toContain(path.join(path.dirname(r2.path), "film.mp4"));
338
+ expect(path.basename(r2.path)).toBe("film_final.mp4");
339
+ const calls = [];
340
+ await expect(runVideo(msg(), { setup: { skill: "/skill", python: "/py" }, run: fakeRun(calls, "split_takes.py"), root: tmp })).rejects.toMatchObject({ code: "failed", message: "split_takes.py failed: Traceback...\nboom" });
341
+ expect(calls.map((c) => c.script)).toEqual(["new_project.py", "tts_say.py", "split_takes.py"]);
342
+ });
343
+
344
+ it("keeps the full-size films when the small copy fails", async () => {
345
+ const logs = [], progress = [];
346
+ const r = await runVideo(msg(), { setup: { skill: "/skill", python: "/py", ffmpeg: "/ff" }, run: fakeRun([], "ffmpeg"), root: tmp, log: (s) => logs.push(s), onProgress: (s, p) => progress.push([s, p]) });
347
+ expect(path.basename(r.path)).toBe("film_captions.mp4");
348
+ expect(r.bytes).toBe(4);
349
+ expect(readdirSync(path.dirname(r.path)).sort()).toEqual(["film.mp4", "film_captions.mp4"]);
350
+ expect(logs[0]).toMatch(/phone-sized copy failed.*ffmpeg failed: Traceback/);
351
+ expect(progress.at(-1)).toEqual(["captions", 100]);
352
+ });
353
+
354
+ it("keeps a script near 90 s: drops whole lines from the middle takes, never the first or last take", () => {
355
+ const L = (n, tag = "w") => ({ spoken: Array(n).fill(tag).join(" ") });
356
+ const takes = [[L(60, "a"), L(60, "a")], [L(30), L(30), L(30)], [L(30), L(30)], [L(60, "z")]];
357
+ expect(fitWords(takes)).toBe(4); // 330 words, 30 a cut, the fuller middle take first (the later one on a tie): 210
358
+ expect(takes.map((t) => t.length)).toEqual([2, 1, 1]); // the emptied take is gone
359
+ const short = [[L(5)], [L(5)]];
360
+ expect(fitWords(short)).toBe(0);
361
+ const ends = [[L(200)], [L(10)], [L(200)]];
362
+ expect(fitWords(ends)).toBe(1); // only the middle may go; the ends stay whole even when still over
363
+ expect(ends.length).toBe(2);
364
+ const many = (n) => ({ text: "x", spoken: Array(n).fill("w").join(" "), hero: "", typed: "" });
365
+ const j = checkVideo({ ...msg(), script: { takes: [{ lines: [many(100)] }, { lines: [many(10), many(10)] }, { lines: [many(10)] }, { lines: [many(100)] }] } });
366
+ expect(j.dropped).toBe(2);
367
+ expect(j.script.takes.map((t) => [t.take, t.lines.map((l) => l.id)])).toEqual([["T01", [1]], ["T02", [2]], ["T03", [3]]]);
368
+ });
369
+
370
+ it("stops at once when cancelled or out of time", async () => {
371
+ const ac = new AbortController();
372
+ const run = (argv, { signal }) => new Promise((_, reject) => signal.addEventListener("abort", () => reject(new JobError("cancelled", "the call was cancelled."))));
373
+ const p = runVideo(msg(), { setup: { skill: "/skill", python: "/py" }, run, signal: ac.signal, root: tmp });
374
+ ac.abort();
375
+ await expect(p).rejects.toMatchObject({ code: "cancelled" });
376
+ await expect(runVideo(msg(), { setup: { skill: "/s", python: "/py" }, run: async () => { throw new JobError("timeout", "x"); }, root: tmp })).rejects.toMatchObject({ code: "timeout", message: "the video took longer than 40 minutes." });
377
+ });
378
+ });