7.4 billion tokens per month. 34 free LLM providers. 635 free model endpoints. All behind one /v1 endpoint, plus any custom OpenAI-compatible endpoint. Smart routing, automatic failover, encrypted keys. Personal experimentation only.
TypeScript
fix(media): send multipart form-data for Cloudflare image models that need it (#714) (#716)
Tashfeenf754988b6e03
diff --git a/server/src/__tests__/services/catalog-sync.test.ts b/server/src/__tests__/services/catalog-sync.test.tsindex 6c266187..c9b7829f 100644--- a/server/src/__tests__/services/catalog-sync.test.ts+++ b/server/src/__tests__/services/catalog-sync.test.ts@@ -502,3 +502,56 @@ describe('applyCatalog: transcriptionModels', () => {expect(reapplyCachedCatalog().reapplied).toBe(false);});});++// Generative media rows (image/audio) carry adapter metadata in meta_json the+// same way transcription rows do — the flavour a platform's endpoint expects.+// Cloudflare hosts both JSON-body image models and the FLUX.2 family, whose+// schema takes multipart only, so the flag has to survive the sync.+describe('applyCatalog: generative media meta', () => {+ beforeAll(() => {+ process.env.ENCRYPTION_KEY = '0'.repeat(64);+ initDb(':memory:');+ });++ function imageCatalog(requestStyle?: string): AnyCatalog {+ const models = existingAsCatalogModels();+ models.push(baseModel({+ platform: 'cloudflare',+ modelId: '@cf/black-forest-labs/flux-2-klein-4b',+ displayName: 'FLUX.2 [klein] 4B',+ modality: 'image',+ ...(requestStyle ? { requestStyle } : {}),+ }));+ models.push(baseModel({+ platform: 'cloudflare',+ modelId: '@cf/black-forest-labs/flux-1-schnell',+ displayName: 'FLUX.1 [schnell]',+ modality: 'image',+ }));+ return catalogOf(models);+ }++ function metaOf(modelId: string): string | null {+ return (getDb().prepare('SELECT meta_json FROM media_models WHERE model_id = ?')+ .get(modelId) as { meta_json: string | null }).meta_json;+ }++ it('carries requestStyle onto an image row, and leaves rows without one NULL', () => {+ applyCatalog(getDb(), imageCatalog('multipart'));+ expect(JSON.parse(metaOf('@cf/black-forest-labs/flux-2-klein-4b')!)).toEqual({ requestStyle: 'multipart' });+ expect(metaOf('@cf/black-forest-labs/flux-1-schnell')).toBeNull();+ });++ it('clears meta when the catalog drops requestStyle (full-snapshot semantics)', () => {+ applyCatalog(getDb(), imageCatalog('multipart'));+ applyCatalog(getDb(), imageCatalog());+ expect(metaOf('@cf/black-forest-labs/flux-2-klein-4b')).toBeNull();+ });++ it('a non-string requestStyle rejects the whole payload', () => {+ const catalog = imageCatalog('multipart');+ (catalog.models[catalog.models.length - 2] as any).requestStyle = 42;+ setSetting('catalog_applied_json', JSON.stringify(catalog));+ expect(reapplyCachedCatalog().reapplied).toBe(false);+ });+});diff --git a/server/src/__tests__/services/media.test.ts b/server/src/__tests__/services/media.test.tsindex 17ab296c..15a81f7d 100644--- a/server/src/__tests__/services/media.test.ts+++ b/server/src/__tests__/services/media.test.ts@@ -22,11 +22,18 @@ function addCustomKey(baseUrl: string, raw = 'custom-media-key'): number {return Number(row.lastInsertRowid);}-function addMedia(platform: string, modelId: string, modality: 'image' | 'audio', priority = 1, keyId: number | null = null) {+function addMedia(+ platform: string,+ modelId: string,+ modality: 'image' | 'audio',+ priority = 1,+ keyId: number | null = null,+ metaJson: string | null = null,+) {getDb().prepare(`- INSERT INTO media_models (platform, model_id, display_name, modality, priority, enabled, quota_label, key_id)- VALUES (?, ?, ?, ?, ?, 1, '', ?)- `).run(platform, modelId, modelId, modality, priority, keyId);+ INSERT INTO media_models (platform, model_id, display_name, modality, priority, enabled, quota_label, key_id, meta_json)+ VALUES (?, ?, ?, ?, ?, 1, '', ?, ?)+ `).run(platform, modelId, modelId, modality, priority, keyId, metaJson);}function jsonResponse(body: unknown) {@@ -73,9 +80,35 @@ describe('media service', () => {it('Cloudflare: JSON {result.image} → b64_json', async () => {addMedia('cloudflare', '@cf/black-forest-labs/flux-1-schnell', 'image');addKey('cloudflare', 'acct123:token456');- globalThis.fetch = vi.fn(async () => jsonResponse({ result: { image: 'CFB64' }, success: true })) as any;+ const fetchMock = vi.fn(async () => jsonResponse({ result: { image: 'CFB64' }, success: true }));+ globalThis.fetch = fetchMock as any;const r = await runImageGeneration('@cf/black-forest-labs/flux-1-schnell', { prompt: 'x' });expect(r.images[0].b64_json).toBe('CFB64');+ // A row without meta keeps the JSON body every other CF image model takes.+ const init = fetchMock.mock.calls[0][1] as RequestInit;+ expect((init.headers as Record<string, string>)['Content-Type']).toBe('application/json');+ expect(JSON.parse(String(init.body))).toMatchObject({ prompt: 'x' });+ });++ it('Cloudflare: requestStyle multipart sends form-data (FLUX.2 rejects JSON)', async () => {+ addMedia('cloudflare', '@cf/black-forest-labs/flux-2-klein-4b', 'image', 1, null,+ JSON.stringify({ requestStyle: 'multipart' }));+ addKey('cloudflare', 'acct123:token456');+ const fetchMock = vi.fn(async () => jsonResponse({ result: { image: 'KLEINB64' }, success: true }));+ globalThis.fetch = fetchMock as any;+ const r = await runImageGeneration('@cf/black-forest-labs/flux-2-klein-4b', {+ prompt: 'a small blue square',+ size: '512x512',+ });+ expect(r.images[0].b64_json).toBe('KLEINB64');+ const init = fetchMock.mock.calls[0][1] as RequestInit;+ expect(init.body).toBeInstanceOf(FormData);+ const form = init.body as FormData;+ expect(form.get('prompt')).toBe('a small blue square');+ expect(form.get('width')).toBe('512');+ expect(form.get('height')).toBe('512');+ // Content-Type must stay unset so fetch supplies the multipart boundary.+ expect((init.headers as Record<string, string>)['Content-Type']).toBeUndefined();});it('Cloudflare: binary SDXL response → b64_json', async () => {diff --git a/server/src/services/catalog-sync.ts b/server/src/services/catalog-sync.tsindex a677b206..3025d7d8 100644--- a/server/src/services/catalog-sync.ts+++ b/server/src/services/catalog-sync.ts@@ -108,6 +108,11 @@ interface CatalogModel {modality?: string;/** Short display note for media models (e.g. "Keyless - up to 1024x1024"). */mediaNote?: string;+ /** Adapter request flavor for media rows, where one platform hosts more than+ * one deployment style (cloudflare images: absent/'json' = JSON body,+ * 'multipart' = form-data, which the FLUX.2 family requires). Mirrors the+ * same field on CatalogTranscriptionModel and lands in meta_json. */+ requestStyle?: string | null;}interface CatalogEmbedding {@@ -207,6 +212,7 @@ function isCatalog(value: unknown): value is Catalog {typeof m?.modelId === 'string' &&typeof m?.displayName === 'string' &&typeof m?.enabled === 'boolean' &&+ (m.requestStyle === undefined || m.requestStyle === null || typeof m.requestStyle === 'string') &&!!m?.limits &&typeof m.limits === 'object',) &&@@ -264,12 +270,12 @@ export function applyCatalog(db: Db, catalog: Catalog): NonNullable<SyncResult['const updateMedia = db.prepare(`UPDATE media_models SETdisplay_name = @displayName, modality = @modality, priority = @priority,- quota_label = @quotaLabel, enabled = @enabled+ quota_label = @quotaLabel, enabled = @enabled, meta_json = @metaJsonWHERE id = @id`);const insertMedia = db.prepare(`- INSERT INTO media_models (platform, model_id, display_name, modality, priority, enabled, quota_label)- VALUES (@platform, @modelId, @displayName, @modality, @priority, @enabled, @quotaLabel)+ INSERT INTO media_models (platform, model_id, display_name, modality, priority, enabled, quota_label, meta_json)+ VALUES (@platform, @modelId, @displayName, @modality, @priority, @enabled, @quotaLabel, @metaJson)`);// Transcription rows share media_models but carry adapter metadata in// meta_json (subtitle capability, upload ceiling, request flavor).@@ -320,11 +326,16 @@ export function applyCatalog(db: Db, catalog: Catalog): NonNullable<SyncResult['if (isCatalogModelTombstoned(db, 'media', m.platform, m.modelId)) continue;inMediaCatalog.add(`${m.platform}:${m.modelId}`);const mrow = selectMedia.get(m.platform, m.modelId) as { id: number; enabled: number } | undefined;+ // Generative-media meta carries only the adapter request flavor today;+ // a row without one stores NULL so the adapter keeps its default.+ const mmeta: Record<string, unknown> = {};+ if (typeof m.requestStyle === 'string') mmeta.requestStyle = m.requestStyle;const mfields = {displayName: m.displayName,modality,priority: m.intelligenceRank ?? 0,quotaLabel: m.mediaNote ?? '',+ metaJson: Object.keys(mmeta).length > 0 ? JSON.stringify(mmeta) : null,};if (mrow) {const enabled = m.enabled ? mrow.enabled : 0; // catalog disable wins; local disable winsdiff --git a/server/src/services/media.ts b/server/src/services/media.tsindex d681cecd..dca16483 100644--- a/server/src/services/media.ts+++ b/server/src/services/media.ts@@ -250,6 +250,20 @@ function parseCfKey(key: string | null): { accountId: string; token: string } {return { accountId: key.slice(0, sep), token: key.slice(sep + 1) };}+/** Adapter request flavor for a generative media row, read from meta_json.+ * One platform can host several deployment styles: Cloudflare takes a JSON+ * body for most image models but multipart/form-data for the FLUX.2 family.+ * Absent meta = the platform's default style, so old rows are untouched. */+function mediaRequestStyle(row: MediaModelRow): string | null {+ if (!row.meta_json) return null;+ try {+ const parsed = JSON.parse(row.meta_json) as { requestStyle?: unknown };+ return typeof parsed?.requestStyle === 'string' ? parsed.requestStyle : null;+ } catch {+ return null;+ }+}+function contentTypeFor(fmt: string): string {switch (fmt) {case 'wav': return 'audio/wav';@@ -332,11 +346,26 @@ async function callImageProvider(}case 'cloudflare': {const { accountId, token } = parseCfKey(key);- const r = await mediaFetch(`https://api.cloudflare.com/client/v4/accounts/${accountId}/ai/run/${row.model_id}`, 'cloudflare', 'image', {- method: 'POST',- headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },- body: JSON.stringify({ prompt: p.prompt, width: w, height: h }),- });+ const url = `https://api.cloudflare.com/client/v4/accounts/${accountId}/ai/run/${row.model_id}`;+ // Most CF image models take a JSON body. The FLUX.2 family declares a+ // multipart input schema and rejects JSON outright ("required properties+ // at '/' are 'multipart'"), so those rows opt in through catalog meta.+ let init: RequestInit;+ if (mediaRequestStyle(row) === 'multipart') {+ // Never set Content-Type by hand — FormData supplies the boundary.+ const form = new FormData();+ form.append('prompt', p.prompt);+ form.append('width', String(w));+ form.append('height', String(h));+ init = { method: 'POST', headers: { Authorization: `Bearer ${token}` }, body: form };+ } else {+ init = {+ method: 'POST',+ headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },+ body: JSON.stringify({ prompt: p.prompt, width: w, height: h }),+ };+ }+ const r = await mediaFetch(url, 'cloudflare', 'image', init);// FLUX returns JSON { result: { image: <b64> } }; SDXL returns raw PNG bytes.const ct = r.headers.get('content-type') ?? '';if (ct.includes('application/json')) {