Skip to content

armgit / fuobe

Public Imported from GitHub
0

The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.

Account results: keep a checked SVG as image/svg+xml

Adarsh380b00d4445b
diff --git a/scripts/readopt-svg-results.mjs b/scripts/readopt-svg-results.mjs
new file mode 100644
index 00000000..5791291b
--- /dev/null
+++ b/scripts/readopt-svg-results.mjs
@@ -0,0 +1,112 @@
+#!/usr/bin/env node
+/**
+ * Results that are real SVGs but were stored as application/octet-stream (.bin) before an account could keep an SVG
+ * result (an account's "Image to vector" run): each is made an image/svg+xml file again, so the run card, the delivery
+ * page and the Library show it.
+ *
+ * node scripts/readopt-svg-results.mjs # dry run: lists what it would change, changes nothing
+ * node scripts/readopt-svg-results.mjs --apply # changes them
+ *
+ * The data folder is FUOBE_DATA_DIR, or ./data. Safe while the server runs. Only a file that passes the same check a
+ * new SVG result passes (src/server/svg-file.ts: UTF-8, an <svg> root in the SVG namespace, nothing active in it) is
+ * changed; any other .bin stays as it is. The asset keeps its id, owner, hold and checks: its file is renamed from .bin
+ * to .svg, its row says image/svg+xml, and every run's outputs and inputs that named the old URL name the new one.
+ * Prints ids and paths only.
+ */
+import fs from "node:fs";
+import path from "node:path";
+import { fileURLToPath, pathToFileURL } from "node:url";
+import Database from "better-sqlite3";
+
+// Node reads src/ as ES modules after a first look: that note is expected here.
+process.removeAllListeners("warning");
+process.on("warning", (w) => (w.name !== "Warning" || !/Module type of/.test(w.message) ? console.warn(`${w.name}: ${w.message}`) : undefined));
+
+const ROOT = path.join(path.dirname(fileURLToPath(import.meta.url)), "..");
+const { isSvgFile } = await import(pathToFileURL(path.join(ROOT, "src", "server", "svg-file.ts")).href);
+
+const apply = process.argv.includes("--apply");
+const dir = path.resolve(process.env.FUOBE_DATA_DIR ?? path.join(process.cwd(), "data"));
+const dbFile = path.join(dir, "fuobe.db");
+const filesDir = path.join(dir, "files");
+
+function fail(message) {
+ console.error(`readopt-svg-results: ${message}`);
+ process.exit(1);
+}
+
+if (!fs.existsSync(dbFile)) fail(`no database at ${dbFile}: set FUOBE_DATA_DIR to the data folder`);
+
+const db = new Database(dbFile);
+db.pragma("busy_timeout = 5000");
+
+const fileUrl = (rel) => `/api/files/${rel.split(path.sep).join("/").split("\\").join("/")}`;
+const inFiles = (rel) => {
+ const abs = path.resolve(filesDir, rel);
+ return abs.startsWith(filesDir + path.sep) ? abs : null;
+};
+
+/** Every output of a run that is an octet-stream .bin asset: its asset row, when its file is a checked SVG. */
+const gens = db.prepare("SELECT id, outputs_json FROM generations WHERE instr(outputs_json, 'application/octet-stream') > 0").all();
+const getAsset = db.prepare("SELECT id, rel_path, content_type, generation_id FROM assets WHERE id = ?");
+const found = new Map();
+let skipped = 0;
+for (const g of gens) {
+ let outputs;
+ try {
+ outputs = JSON.parse(g.outputs_json);
+ } catch {
+ continue;
+ }
+ if (!Array.isArray(outputs)) continue;
+ for (const o of outputs) {
+ if (!o || o.contentType !== "application/octet-stream" || typeof o.assetId !== "string" || found.has(o.assetId)) continue;
+ const a = getAsset.get(o.assetId);
+ if (!a || a.content_type !== "application/octet-stream" || !/\.bin$/.test(a.rel_path)) continue;
+ const abs = inFiles(a.rel_path);
+ if (!abs || !isSvgFile(abs)) {
+ skipped++;
+ continue;
+ }
+ found.set(a.id, { asset: a, abs, generationId: g.id });
+ }
+}
+
+console.log(`${found.size} SVG result(s) stored as .bin${skipped ? `; ${skipped} other .bin result(s) left as they are` : ""}${apply ? "" : " (dry run: --apply changes them)"}`);
+
+const runsNaming = db.prepare("SELECT id, outputs_json, request_json FROM generations WHERE instr(outputs_json, ?) > 0 OR instr(request_json, ?) > 0");
+const setRun = db.prepare("UPDATE generations SET outputs_json = ?, request_json = ? WHERE id = ?");
+const setAsset = db.prepare("UPDATE assets SET rel_path = ?, content_type = 'image/svg+xml', kind = 'image' WHERE id = ? AND rel_path = ? AND content_type = 'application/octet-stream'");
+
+let changed = 0;
+for (const { asset, abs, generationId } of found.values()) {
+ const rel = asset.rel_path.replace(/\.bin$/, ".svg");
+ const from = fileUrl(asset.rel_path);
+ const to = fileUrl(rel);
+ console.log(`${apply ? "changing" : "would change"} run ${generationId} asset ${asset.id}: ${from} -> ${to}`);
+ if (!apply) continue;
+ const dest = inFiles(rel);
+ if (!dest || fs.existsSync(dest)) {
+ console.warn(` skipped: ${to} is there already`);
+ continue;
+ }
+ fs.renameSync(abs, dest);
+ try {
+ db.transaction(() => {
+ if (setAsset.run(rel, asset.id, asset.rel_path).changes !== 1) throw new Error("the asset changed meanwhile");
+ for (const r of runsNaming.all(from, from)) {
+ const outputs = JSON.parse(r.outputs_json.split(from).join(to));
+ for (const o of Array.isArray(outputs) ? outputs : []) {
+ if (o && (o.assetId === asset.id || o.url === to)) Object.assign(o, { url: to, kind: "image", contentType: "image/svg+xml" });
+ }
+ setRun.run(JSON.stringify(outputs), r.request_json.split(from).join(to), r.id);
+ }
+ })();
+ changed++;
+ } catch (e) {
+ fs.renameSync(dest, abs);
+ console.warn(` skipped: ${e.message}`);
+ }
+}
+if (apply) console.log(`${changed} changed`);
+db.close();
diff --git a/src/server/computer/http.ts b/src/server/computer/http.ts
index 56af44d6..254670f6 100644
--- a/src/server/computer/http.ts
+++ b/src/server/computer/http.ts
@@ -8,6 +8,7 @@ import { accountById, accountGpu, authEnabled, crossSite, hostAllowed, LoginGuar
import { hit } from "../rate";
import { getSetting } from "../settings";
import { RelayError, type Principal } from "./tasks";
+import { isSvgFile } from "../svg-file";
import { isWorkerAuth, workerFromAuth, type WorkerRow } from "./workers";
/**
@@ -107,9 +108,6 @@ const notWhatWasAsked = (w: WantedFile) => `Couldn't save a result from your Com
/** An SVG's first bytes: white space (a byte order mark is one), then its XML declaration, a comment or its <svg> tag. */
const SVG_HEAD = /^\s*(<\?xml[\s?]|<!--|<svg[\s>/])/;
-/** What a kept SVG never holds: scripts, event handlers, a page inside it, entities. */
-const SVG_ACTIVE = /<script\b|<foreignObject\b|<!ENTITY|\son[a-z]+\s*=|javascript:/i;
-const SVG_MAX_BYTES = 64 * 2 ** 20;
/** A Niantic splat's header, inside its gzip: "NGSP" (little-endian). */
const SPZ_MAGIC = 0x5053474e;
@@ -172,22 +170,6 @@ export function checkWholeOutput(file: string, w: WantedFile, contentType: strin
if (!ok) throw new Error(notWhatWasAsked(w));
}
-/**
- * A real SVG: UTF-8, its root an <svg> in the SVG namespace after at most an XML declaration, comments and a DOCTYPE
- * with no internal subset, closed at its end, with nothing active in it (SVG_ACTIVE).
- */
-export function isSvgFile(file: string): boolean {
- try {
- if (fs.statSync(file).size > SVG_MAX_BYTES) return false;
- const text = new TextDecoder("utf-8", { fatal: true }).decode(fs.readFileSync(file));
- const body = text.replace(/^(?:\s|<\?xml[^>]*\?>|<!--[\s\S]*?-->|<!DOCTYPE\s+svg\b[^[>]*>)*/, "");
- const root = /^<svg\b[^>]*>/.exec(body)?.[0];
- return !!root && /\sxmlns\s*=\s*["']http:\/\/www\.w3\.org\/2000\/svg["']/.test(root) && /<\/svg\s*>\s*$/.test(body) && !SVG_ACTIVE.test(body);
- } catch {
- return false;
- }
-}
-
/** A real splat (.spz): gzip, and inside it the header: "NGSP", version 1 to 3, at least one point, SH degree 0 to 3. */
export function isSpzFile(file: string): boolean {
let fd: number | null = null;
diff --git a/src/server/file-response.ts b/src/server/file-response.ts
index 2e769670..8439e97d 100644
--- a/src/server/file-response.ts
+++ b/src/server/file-response.ts
@@ -4,6 +4,9 @@ import { pipeline, type Readable } from "node:stream";
import { cachedPatches, patchStream } from "./media-clean";
import { absolutePath, contentTypeFor } from "./storage";
+/** The policy every stored SVG is served with, whoever asks (an <img> of an SVG never runs scripts anyway). */
+export const SVG_CSP = "default-src 'none'; style-src 'unsafe-inline'; img-src data:; sandbox";
+
/**
* A stored file as an HTTP response, with byte ranges (video seeking), a UTF-8 charset for text,
* `nosniff`, a sandbox CSP (and a script-free one for SVG). `relPath` is under the files folder; traversal is
@@ -61,7 +64,8 @@ export function fileResponse(request: Request, relPath: string, opts: { cache?:
"Content-Security-Policy": "sandbox",
...opts.headers,
};
- if (type === "image/svg+xml") headers["Content-Security-Policy"] = "default-src 'none'; style-src 'unsafe-inline'; sandbox";
+ // An SVG opened on its own: its own styles and embedded (data:) pictures draw, nothing else loads or runs.
+ if (type === "image/svg+xml") Object.assign(headers, { "Content-Security-Policy": SVG_CSP, "X-Content-Type-Options": "nosniff" });
const download = new URL(request.url).searchParams.get("download");
if (download) headers["Content-Disposition"] = `attachment; filename="${download.replace(/[^\w.-]/g, "_")}"`;
const range = request.headers.get("range");
diff --git a/src/server/generations.ts b/src/server/generations.ts
index bc5af39e..647d2763 100644
--- a/src/server/generations.ts
+++ b/src/server/generations.ts
@@ -168,6 +168,7 @@ import { inDemoScope, outsideDemo } from "./demo-scope";
import { moderationConfigured } from "./moderation";
import { holdForCheck, sweepOutputChecks } from "./output-checks";
import { absolutePath, adoptFile, contentTypeFor, deleteAsset, localHead, readRef, saveFile, scratchDir, scratchOutputFile } from "./storage";
+import { isSvgData, isSvgFile } from "./svg-file";
interface Row {
id: string;
@@ -5229,7 +5230,10 @@ const ACCOUNT_LIMITS_FILE_BYTES = 2 ** 30;
/** An account's files are full (accountTotalBytes): the job fails with this message. */
class AccountFilesFull extends Error {}
-/** Types an account's result is stored as; any other is stored as application/octet-stream (.bin), never served as a page. */
+/**
+ * Types an account's result is stored as, with image/svg+xml for a checked SVG (accountType); any other is stored as
+ * application/octet-stream (.bin), never served as a page.
+ */
const ACCOUNT_OUTPUT_TYPES = new Set([
"image/png",
"image/jpeg",
@@ -5252,8 +5256,10 @@ const ACCOUNT_OUTPUT_TYPES = new Set([
"text/vtt",
]);
-const accountType = (t: string) => {
+/** The type an account's result is kept as. An SVG only when `svg()` says its bytes are a checked one (src/server/svg-file.ts). */
+const accountType = (t: string, svg: () => boolean) => {
const bare = t.split(";")[0].trim().toLowerCase();
+ if (bare === "image/svg+xml") return svg() ? bare : "application/octet-stream";
return ACCOUNT_OUTPUT_TYPES.has(bare) ? bare : "application/octet-stream";
};
@@ -5296,7 +5302,7 @@ async function persistAccountOutput(o: RichOutput, generationId: string, account
roomFor(account, fs.statSync(dest).size, dest);
const header = res.headers.get("content-type")?.split(";")[0];
const given = o.contentType ?? (header && header !== "application/octet-stream" ? header : contentTypeFor(new URL(o.url).searchParams.get("filename") ?? o.url));
- const asset = adoptFile({ from: dest, contentType: accountType(given), source: "generation", generationId, accountId: account });
+ const asset = adoptFile({ from: dest, contentType: accountType(given, () => isSvgFile(dest)), source: "generation", generationId, accountId: account });
const meta = relinkMain(linked, o.url, asset.url);
const text = o.text ?? (asset.kind === "text" && asset.size <= MAX_INLINE_TEXT * 4 ? fs.readFileSync(absolutePath(asset.relPath), "utf8") : undefined);
return {
@@ -5327,7 +5333,7 @@ async function persistRelayOutput(o: RichOutput, generationId: string, account:
const contentType = o.contentType ?? file.contentType ?? "application/octet-stream";
const size = fs.statSync(from).size;
if (account) roomFor(account, size, o.url.startsWith("scratch:") ? from : undefined);
- const asset = adoptFile({ from, contentType: account ? accountType(contentType) : contentType, source: "generation", generationId, ...(account && { accountId: account }) });
+ const asset = adoptFile({ from, contentType: account ? accountType(contentType, () => isSvgFile(from)) : contentType, source: "generation", generationId, ...(account && { accountId: account }) });
const meta = relinkMain(linked, o.url, asset.url);
const text = o.text ?? (asset.kind === "text" && asset.size <= MAX_INLINE_TEXT * 4 ? fs.readFileSync(absolutePath(asset.relPath), "utf8") : undefined);
return {
@@ -5340,8 +5346,8 @@ async function persistRelayOutput(o: RichOutput, generationId: string, account:
};
}
-/** Save one result. `pre`: the files it links to, kept already (persistArtifacts runs once for a copy tried again). */
-async function persistOutput(o: RichOutput, generationId: string, pre?: { linked: Record<string, unknown> | undefined }): Promise<OutputFile> {
+/** Save one result (exported for tests). `pre`: the files it links to, kept already (persistArtifacts runs once for a copy tried again). */
+export async function persistOutput(o: RichOutput, generationId: string, pre?: { linked: Record<string, unknown> | undefined }): Promise<OutputFile> {
const linked = pre ? pre.linked : await persistArtifacts(o.meta, generationId, o.url);
const account = tenantAccount();
if (o.url?.startsWith("relay:") || o.url?.startsWith("scratch:")) return persistRelayOutput(o, generationId, account, linked);
@@ -5368,7 +5374,7 @@ async function persistOutput(o: RichOutput, generationId: string, pre?: { linked
}
if (account) {
roomFor(account, data.length);
- contentType = accountType(contentType!);
+ contentType = accountType(contentType!, () => isSvgData(data));
}
const asset = saveFile({ data, contentType: contentType!, source: "generation", generationId });
const meta = relinkMain(linked, o.url, asset.url);
diff --git a/src/server/svg-file.ts b/src/server/svg-file.ts
new file mode 100644
index 00000000..0d3fd9dd
--- /dev/null
+++ b/src/server/svg-file.ts
@@ -0,0 +1,36 @@
+import fs from "node:fs";
+
+/**
+ * A checked SVG: the only SVG Fuobe keeps as image/svg+xml (a computer's result, an account's result). No "server-only"
+ * import, so the repair script (scripts/ops/readopt-svg-results.mjs) can load it with Node's own type stripping.
+ */
+
+/** What a kept SVG never holds: scripts, event handlers, a page inside it, entities. */
+export const SVG_ACTIVE = /<script\b|<foreignObject\b|<!ENTITY|\son[a-z]+\s*=|javascript:/i;
+export const SVG_MAX_BYTES = 64 * 2 ** 20;
+
+/**
+ * A real SVG: UTF-8, its root an <svg> in the SVG namespace after at most an XML declaration, comments and a DOCTYPE
+ * with no internal subset, closed at its end, with nothing active in it (SVG_ACTIVE).
+ */
+export function isSvgData(data: Uint8Array): boolean {
+ try {
+ if (data.length > SVG_MAX_BYTES) return false;
+ const text = new TextDecoder("utf-8", { fatal: true }).decode(data);
+ const body = text.replace(/^(?:\s|<\?xml[^>]*\?>|<!--[\s\S]*?-->|<!DOCTYPE\s+svg\b[^[>]*>)*/, "");
+ const root = /^<svg\b[^>]*>/.exec(body)?.[0];
+ return !!root && /\sxmlns\s*=\s*["']http:\/\/www\.w3\.org\/2000\/svg["']/.test(root) && /<\/svg\s*>\s*$/.test(body) && !SVG_ACTIVE.test(body);
+ } catch {
+ return false;
+ }
+}
+
+/** isSvgData for a file on disk (never read when it is over SVG_MAX_BYTES). */
+export function isSvgFile(file: string): boolean {
+ try {
+ if (fs.statSync(file).size > SVG_MAX_BYTES) return false;
+ return isSvgData(fs.readFileSync(file));
+ } catch {
+ return false;
+ }
+}
diff --git a/tests/account-svg-results.test.ts b/tests/account-svg-results.test.ts
new file mode 100644
index 00000000..5e4d0b49
--- /dev/null
+++ b/tests/account-svg-results.test.ts
@@ -0,0 +1,129 @@
+import { spawnSync } from "node:child_process";
+import fs from "node:fs";
+import path from "node:path";
+import { describe, expect, it } from "vitest";
+import { tempDir } from "./helpers/temp-dir";
+
+/**
+ * An account's SVG result (Image to vector on a worker): kept as image/svg+xml when it is a checked SVG, as
+ * application/octet-stream (.bin) otherwise; served with a script-free policy; and results stored as .bin before this
+ * made SVGs again by scripts/readopt-svg-results.mjs.
+ */
+
+const dir = tempDir("fuobe-account-svg-");
+process.env.FUOBE_DATA_DIR = dir;
+process.env.FUOBE_PUBLIC_SIGNUP = "1";
+delete process.env.FUOBE_PASSWORD;
+globalThis.__fuobeTestDiskFree = 1e13;
+
+const auth = await import("@/server/auth");
+const { asAccount, persistOutput } = await import("@/server/generations");
+const { absolutePath, newScratchOutput, saveFile } = await import("@/server/storage");
+const { fileResponse, SVG_CSP } = await import("@/server/file-response");
+const { db } = await import("@/server/db");
+
+const CLEAN_SVG = `<?xml version="1.0" encoding="UTF-8"?>\n<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10"><path d="M0 0h10v10z" fill="#5d4bdb"/></svg>\n`;
+const SCRIPT_SVG = `<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script></svg>`;
+
+auth.setPassword("install password");
+const account = auth.createAccount("[email protected]", "long enough").id;
+
+/** A result the provider wrote to the scratch folder (the same path a worker's relay: result takes), kept as the account's. */
+function keepScratch(body: string, contentType = "image/svg+xml") {
+ const s = newScratchOutput("svg");
+ fs.writeFileSync(s.file, body);
+ return asAccount(account, () => persistOutput({ url: s.url, kind: "image", contentType }, "gen-svg-test", { linked: undefined }));
+}
+
+describe("an account's SVG result", () => {
+ it("is kept as image/svg+xml when it is a checked SVG", async () => {
+ const out = await keepScratch(CLEAN_SVG);
+ expect(out.contentType).toBe("image/svg+xml");
+ expect(out.kind).toBe("image");
+ expect(out.url).toMatch(/\.svg$/);
+ expect(fs.readFileSync(absolutePath(out.url.replace(/^\/api\/files\//, "")), "utf8")).toBe(CLEAN_SVG);
+ });
+
+ it("with a script in it stays application/octet-stream (.bin)", async () => {
+ const out = await keepScratch(SCRIPT_SVG);
+ expect(out.contentType).toBe("application/octet-stream");
+ expect(out.url).toMatch(/\.bin$/);
+ const handler = await keepScratch(`<svg xmlns="http://www.w3.org/2000/svg"><rect onclick="x()"/></svg>`);
+ expect(handler.contentType).toBe("application/octet-stream");
+ });
+
+ it("from a data: link (persistOutput's own branch) is checked the same way", async () => {
+ const url = (s: string) => `data:image/svg+xml;base64,${Buffer.from(s).toString("base64")}`;
+ const ok = await asAccount(account, () => persistOutput({ url: url(CLEAN_SVG), kind: "image" }, "gen-svg-data", { linked: undefined }));
+ expect(ok.contentType).toBe("image/svg+xml");
+ const bad = await asAccount(account, () => persistOutput({ url: url(SCRIPT_SVG), kind: "image" }, "gen-svg-data", { linked: undefined }));
+ expect(bad.contentType).toBe("application/octet-stream");
+ });
+});
+
+describe("serving a stored SVG", () => {
+ it("always sends the script-free policy and nosniff, and keeps a download's file name", async () => {
+ const url = saveFile({ data: Buffer.from(CLEAN_SVG), contentType: "image/svg+xml", source: "generation", accountId: account }).url;
+ const rel = url.replace(/^\/api\/files\//, "");
+ for (const [q, headers] of [["", undefined], ["?download=logo.svg", { "Content-Security-Policy": "sandbox", "X-Content-Type-Options": "sniff" }]] as const) {
+ const res = fileResponse(new Request(`http://localhost:3000${url}${q}`), rel, headers ? { headers } : {});
+ expect(res.status).toBe(200);
+ expect(res.headers.get("content-type")).toBe("image/svg+xml");
+ expect(res.headers.get("content-security-policy")).toBe(SVG_CSP);
+ expect(SVG_CSP).toBe("default-src 'none'; style-src 'unsafe-inline'; img-src data:; sandbox");
+ expect(res.headers.get("x-content-type-options")).toBe("nosniff");
+ if (q) expect(res.headers.get("content-disposition")).toBe(`attachment; filename="logo.svg"`);
+ await res.body?.cancel();
+ }
+ });
+});
+
+describe("scripts/readopt-svg-results.mjs", () => {
+ const run = (...args: string[]) => {
+ const r = spawnSync(process.execPath, [path.join(process.cwd(), "scripts", "readopt-svg-results.mjs"), ...args], { env: { ...process.env, FUOBE_DATA_DIR: dir }, encoding: "utf8" });
+ return { code: r.status, out: `${r.stdout}${r.stderr}` };
+ };
+
+ it("makes an SVG stored as .bin an SVG again (dry run first), and leaves any other .bin alone", () => {
+ const svg = saveFile({ data: Buffer.from(CLEAN_SVG), contentType: "application/octet-stream", source: "generation", generationId: "gen-old-svg", accountId: account });
+ const other = saveFile({ data: Buffer.from(SCRIPT_SVG), contentType: "application/octet-stream", source: "generation", generationId: "gen-old-svg", accountId: account });
+ expect(svg.relPath).toMatch(/\.bin$/);
+ const now = Date.now();
+ const outputs = [
+ { url: svg.url, kind: "image", contentType: "application/octet-stream", assetId: svg.id },
+ { url: other.url, kind: "image", contentType: "application/octet-stream", assetId: other.id },
+ ];
+ const insert = db().prepare(
+ "INSERT INTO generations (id, feature, model_id, engine, provider, op, kind, status, request_json, outputs_json, created_at, updated_at) VALUES (?, 'image', 'oss-vectorize', 'open', 'comfyui', 'vectorize', 'image', 'succeeded', ?, ?, ?, ?)",
+ );
+ insert.run("gen-old-svg", JSON.stringify({ account }), JSON.stringify(outputs), now, now);
+ // A later run that used the result as its input.
+ insert.run("gen-next", JSON.stringify({ account, inputs: { images: [svg.url] } }), "[]", now, now);
+
+ const dry = run();
+ expect(dry.code, dry.out).toBe(0);
+ expect(dry.out).toContain("1 SVG result(s) stored as .bin; 1 other .bin result(s) left as they are (dry run");
+ expect(dry.out).not.toContain("@example.com");
+ expect(fs.existsSync(absolutePath(svg.relPath))).toBe(true);
+ expect((db().prepare("SELECT content_type FROM assets WHERE id = ?").get(svg.id) as { content_type: string }).content_type).toBe("application/octet-stream");
+
+ const applied = run("--apply");
+ expect(applied.code, applied.out).toBe(0);
+ expect(applied.out).toContain("1 changed");
+ const row = db().prepare("SELECT rel_path, content_type, kind, account_id FROM assets WHERE id = ?").get(svg.id) as { rel_path: string; content_type: string; kind: string; account_id: string };
+ expect(row).toMatchObject({ content_type: "image/svg+xml", kind: "image", account_id: account });
+ expect(row.rel_path).toMatch(/\.svg$/);
+ expect(fs.existsSync(absolutePath(svg.relPath))).toBe(false);
+ expect(fs.readFileSync(absolutePath(row.rel_path), "utf8")).toBe(CLEAN_SVG);
+ const newUrl = svg.url.replace(/\.bin$/, ".svg");
+ const kept = JSON.parse((db().prepare("SELECT outputs_json FROM generations WHERE id = 'gen-old-svg'").get() as { outputs_json: string }).outputs_json);
+ expect(kept[0]).toEqual({ url: newUrl, kind: "image", contentType: "image/svg+xml", assetId: svg.id });
+ expect(kept[1]).toEqual(outputs[1]);
+ const next = JSON.parse((db().prepare("SELECT request_json FROM generations WHERE id = 'gen-next'").get() as { request_json: string }).request_json);
+ expect(next.inputs.images).toEqual([newUrl]);
+ expect((db().prepare("SELECT content_type FROM assets WHERE id = ?").get(other.id) as { content_type: string }).content_type).toBe("application/octet-stream");
+
+ // Run again: nothing left to change.
+ expect(run("--apply").out).toContain("0 SVG result(s) stored as .bin");
+ });
+});