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.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Generations: keep a result's other formats and preview as files, not provider links
Claudef851fd0b666f
diff --git a/src/server/generations.ts b/src/server/generations.tsindex 7c1b4f09..a5785e04 100644--- a/src/server/generations.ts+++ b/src/server/generations.ts@@ -1200,37 +1200,64 @@ function inlineText(text: string | undefined, meta: Record<string, unknown> | un}/**- * Extra files a result carries as links (meta.artifacts: LTX HDR's EXR zip, Higgsfield's fbx / zip) are kept- * too, so the Library never depends on a provider's expiring URL. Links are streamed to disk (an EXR zip runs- * to gigabytes); one that can't be fetched stays as it was (the result's actions still offer it).+ * Extra files a result carries as links are kept too, so the Library never depends on a provider's expiring URL:+ * meta.artifacts (LTX HDR's EXR zip, Higgsfield's fbx / zip), meta.formats (a 3D model's other formats, a rig's FBX+ * and its walk and run cycles, SAM 3D's splat) and meta.preview (a 3D model's render, the cut-out a splat was+ * made from). Links are streamed to disk (an EXR zip runs to gigabytes); one that can't be fetched stays as it+ * was (the result's actions still offer it). A link to the main file itself (`main`) is left for persistOutput.*/-export async function persistArtifacts(meta: Record<string, unknown> | undefined, generationId: string): Promise<Record<string, unknown> | undefined> {- const links = meta?.artifacts;- if (!links || typeof links !== "object" || Array.isArray(links)) return meta;- const kept: Record<string, unknown> = {};- for (const [k, v] of Object.entries(links as Record<string, unknown>)) {- kept[k] = v;- if (typeof v !== "string" || !/^(https?:|data:)/.test(v)) continue;- try {- if (v.startsWith("data:")) {- const f = await readRef(v);- kept[k] = saveFile({ data: f.data, contentType: f.contentType, source: "generation", generationId }).url;- continue;- }- const dest = path.join(scratchDir(), `${generationId}-${k}-${nanoid(6)}`);- const res = await fetchRemoteToFile(v, dest);- const name = new URL(res.url).pathname.split("/").pop() || undefined;- const header = res.contentType && res.contentType !== "application/octet-stream" ? res.contentType : null;- kept[k] = adoptFile({ from: dest, contentType: header ?? contentTypeFor(name ?? "", "application/octet-stream"), name, source: "generation", generationId }).url;- } catch (e) {- console.warn(`[fuobe] could not keep the ${k} file of ${generationId}: ${(e as Error).message}`);+export async function persistArtifacts(meta: Record<string, unknown> | undefined, generationId: string, main?: string): Promise<Record<string, unknown> | undefined> {+ if (!meta) return meta;+ let out = meta;+ for (const key of LINK_MAPS) {+ const links = meta[key];+ if (!links || typeof links !== "object" || Array.isArray(links)) continue;+ const kept: Record<string, unknown> = {};+ for (const [k, v] of Object.entries(links as Record<string, unknown>)) kept[k] = v === main ? v : await keepLink(v, key === "artifacts" ? k : `${key}-${k}`, generationId);+ out = { ...out, [key]: kept };+ }+ for (const key of LINKS) if (typeof meta[key] === "string" && meta[key] !== main) out = { ...out, [key]: await keepLink(meta[key], key, generationId) };+ return out;+}++/** Maps of extra files by name, and single extra files, that a result links to (see persistArtifacts). */+const LINK_MAPS = ["artifacts", "formats"] as const;+const LINKS = ["preview"] as const;++/** A provider's link stored as a file of the generation (its local URL), or the link as it was when it can't be fetched. */+async function keepLink(v: unknown, label: string, generationId: string): Promise<unknown> {+ if (typeof v !== "string" || !/^(https?:|data:)/.test(v)) return v;+ try {+ if (v.startsWith("data:")) {+ const f = await readRef(v);+ return saveFile({ data: f.data, contentType: f.contentType, source: "generation", generationId }).url;}+ const dest = path.join(scratchDir(), `${generationId}-${label}-${nanoid(6)}`);+ const res = await fetchRemoteToFile(v, dest);+ const name = new URL(res.url).pathname.split("/").pop() || undefined;+ const header = res.contentType && res.contentType !== "application/octet-stream" ? res.contentType : null;+ return adoptFile({ from: dest, contentType: header ?? contentTypeFor(name ?? "", "application/octet-stream"), name, source: "generation", generationId }).url;+ } catch (e) {+ console.warn(`[fuobe] could not keep the ${label} file of ${generationId}: ${(e as Error).message}`);+ return v;}- return { ...meta, artifacts: kept };+}++/** The extra links that pointed at the main file point at its stored copy. */+function relinkMain(meta: Record<string, unknown> | undefined, from: string, to: string): Record<string, unknown> | undefined {+ if (!meta || !from) return meta;+ let out = meta;+ for (const key of LINK_MAPS) {+ const links = meta[key];+ if (!links || typeof links !== "object" || Array.isArray(links) || !Object.values(links).includes(from)) continue;+ out = { ...out, [key]: Object.fromEntries(Object.entries(links as Record<string, unknown>).map(([k, v]) => [k, v === from ? to : v])) };+ }+ for (const key of LINKS) if (meta[key] === from) out = { ...out, [key]: to };+ return out;}async function persistOutput(o: RichOutput, generationId: string): Promise<OutputFile> {- const meta = await persistArtifacts(o.meta, generationId);+ const linked = await persistArtifacts(o.meta, generationId, o.url);let data: Buffer;let contentType = o.contentType;if (!o.url && o.text !== undefined) {@@ -1252,6 +1279,7 @@ async function persistOutput(o: RichOutput, generationId: string): Promise<OutpucontentType ??= header && header !== "application/octet-stream" ? header : contentTypeFor(new URL(o.url).searchParams.get("filename") ?? o.url);}const asset = saveFile({ data, contentType: contentType!, source: "generation", generationId });+ const meta = relinkMain(linked, o.url, asset.url);// A text file's words travel with the generation, so feeds and the next chained step can use them.const text = o.text ?? (asset.kind === "text" ? data.toString("utf8") : undefined);return {diff --git a/tests/model3d.test.ts b/tests/model3d.test.tsindex 79bee869..b29b5c6b 100644--- a/tests/model3d.test.ts+++ b/tests/model3d.test.ts@@ -185,6 +185,52 @@ describe("what the cards show", () => {});});+describe("the extra files are kept", () => {+ it("a rig's walk and run cycles and FBX, SAM 3D's splat and the preview become files of the generation", async () => {+ const http = await import("node:http");+ const server = http.createServer((req, res) => {+ if (req.url === "/gone.glb") return void res.writeHead(404).end();+ res.setHeader("content-type", "application/octet-stream");+ res.end(Buffer.from(`file ${req.url}`));+ });+ await new Promise<void>((r) => server.listen(0, "127.0.0.1", r));+ const at = (p: string) => `http://127.0.0.1:${(server.address() as { port: number }).port}${p}`;+ process.env.FUOBE_ALLOW_PRIVATE_URLS = "1";+ try {+ const outs = extractOutputs(+ {+ rigged_character_glb: { url: at("/rig.glb") },+ animation_glb: { url: at("/anim.glb") },+ animation_fbx: { url: at("/anim.fbx") },+ basic_animations: { walking_glb: { url: at("/walk.glb") }, running_glb: { url: at("/gone.glb") } },+ },+ "rig-3d",+ );+ const kept = await gens.persistArtifacts(outs[0].meta, "genrig", outs[0].url);+ const formats = kept?.formats as Record<string, string>;+ expect(formats.walking).toMatch(/^\/api\/files\/outputs\/.+\.glb$/);+ expect(formats.rigged).toMatch(/^\/api\/files\/outputs\/.+\.glb$/);+ expect(formats.fbx).toMatch(/^\/api\/files\/outputs\/.+\.fbx$/);+ // Gone at the provider: the link stays.+ expect(formats.running).toBe(at("/gone.glb"));+ expect(kept).toMatchObject({ rigged: true, animated: true });+ const file = path.join(dir, "files", decodeURIComponent(formats.walking.slice("/api/files/".length)));+ expect(fs.readFileSync(file, "utf8")).toBe("file /walk.glb");++ const sam = extractOutputs({ model_glb: { url: at("/o.glb") }, gaussian_splat: { url: at("/o.ply") }, thumbnail: { url: at("/o.png") } }, "image-to-3d");+ const samKept = await gens.persistArtifacts(sam[0].meta, "gensam", sam[0].url);+ expect((samKept?.formats as Record<string, string>).splat).toMatch(/^\/api\/files\/outputs\/.+\.ply$/);+ expect(samKept?.preview).toMatch(/^\/api\/files\/outputs\//);+ // A format that is the main file itself is left to persistOutput (it isn't fetched twice).+ const same = await gens.persistArtifacts({ formats: { glb: at("/o.glb"), obj: at("/o.obj") } }, "gensame", at("/o.glb"));+ expect(same?.formats).toMatchObject({ glb: at("/o.glb"), obj: expect.stringMatching(/^\/api\/files\//) });+ } finally {+ delete process.env.FUOBE_ALLOW_PRIVATE_URLS;+ server.close();+ }+ });+});+describe("open engine: multi-view TRELLIS.2 (image-to-3d-trellis2-multiview)", () => {const manifest = getWorkflow("image-to-3d-trellis2-multiview").manifest;const prep = (images: string[], extra?: Record<string, unknown>) =>