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(keys): apply the display name typed on the custom endpoint form (#715)
Tashfeene938acba99d3
diff --git a/server/src/__tests__/db/migrate/custom-endpoint-host-labels.test.ts b/server/src/__tests__/db/migrate/custom-endpoint-host-labels.test.tsnew file mode 100644index 00000000..bdc66464--- /dev/null+++ b/server/src/__tests__/db/migrate/custom-endpoint-host-labels.test.ts@@ -0,0 +1,72 @@+import Database from 'better-sqlite3';+import { afterEach, describe, expect, it } from 'vitest';+import { up, down } from '../../../db/migrations/20260802_000001_custom_endpoint_host_labels.js';++// A minimal stand-in for api_keys: the data-only migration only reads+// platform / label / base_url.+function makeDb(): Database.Database {+ const db = new Database(':memory:');+ db.exec(`+ CREATE TABLE api_keys (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ platform TEXT NOT NULL,+ label TEXT,+ base_url TEXT+ );+ `);+ const insert = db.prepare('INSERT INTO api_keys (platform, label, base_url) VALUES (?, ?, ?)');+ insert.run('custom', 'Custom', 'http://127.0.0.1:11434/v1'); // legacy default (#704)+ insert.run('custom', 'Custom', 'http://192.168.1.50:8080/v1'); // …and its indistinguishable twin+ insert.run('custom', 'Ollama box', 'http://127.0.0.1:1234/v1');// operator's own name: untouched+ insert.run('custom', 'Custom', null); // no URL to rename to+ insert.run('groq', 'Custom', null); // catalog key that must NOT change+ return db;+}++function labels(db: Database.Database): (string | null)[] {+ return (db.prepare('SELECT label FROM api_keys ORDER BY id').all() as { label: string | null }[])+ .map(r => r.label);+}++const dbs: Database.Database[] = [];+afterEach(() => {+ for (const db of dbs.splice(0)) db.close();+});++describe('custom_endpoint_host_labels migration (#704)', () => {+ it('renames the legacy default to the endpoint host and leaves everything else alone', () => {+ const db = makeDb();+ dbs.push(db);++ up(db);++ expect(labels(db)).toEqual([+ '127.0.0.1:11434',+ '192.168.1.50:8080',+ 'Ollama box',+ 'Custom', // no base_url: nothing to rename to+ 'Custom', // not a custom endpoint+ ]);+ });++ it('is idempotent — a second up() produces the identical result', () => {+ const db = makeDb();+ dbs.push(db);++ up(db);+ const once = labels(db);+ up(db);++ expect(labels(db)).toEqual(once);+ });++ it('down() restores the generic label on the endpoints up() renamed', () => {+ const db = makeDb();+ dbs.push(db);++ up(db);+ down(db);++ expect(labels(db)).toEqual(['Custom', 'Custom', 'Ollama box', 'Custom', 'Custom']);+ });+});diff --git a/server/src/__tests__/db/migrate/registry-drift.test.ts b/server/src/__tests__/db/migrate/registry-drift.test.tsnew file mode 100644index 00000000..6119e73f--- /dev/null+++ b/server/src/__tests__/db/migrate/registry-drift.test.ts@@ -0,0 +1,30 @@+import fs from 'node:fs';+import path from 'node:path';+import { fileURLToPath } from 'node:url';+import { describe, expect, it } from 'vitest';+import { DEFAULT_MIGRATIONS } from '../../../db/migrate/defaults.js';++// The runner walks the static DEFAULT_MIGRATIONS list, not the directory, so a+// migration file that nobody registered is skipped in silence: it never runs,+// nothing fails, and the gap only shows up as a symptom on an upgraded install.+// Adding the file and forgetting the registry is the easy mistake — this makes+// it a failing test instead of a quiet no-op.+const here = path.dirname(fileURLToPath(import.meta.url));+const MIGRATIONS_DIR = path.resolve(here, '../../../db/migrations');++describe('migration registry', () => {+ it('registers every migration file on disk', () => {+ const onDisk = fs.readdirSync(MIGRATIONS_DIR)+ .filter(name => name.endsWith('.ts') && !name.endsWith('.d.ts'))+ .sort();+ const registered = DEFAULT_MIGRATIONS.map(m => m.filename).sort();++ expect(registered).toEqual(onDisk);+ });++ it('keeps the registry in filename order — the order they are applied in', () => {+ const filenames = DEFAULT_MIGRATIONS.map(m => m.filename);++ expect(filenames).toEqual([...filenames].sort());+ });+});diff --git a/server/src/__tests__/db/migrate/roundtrip.test.ts b/server/src/__tests__/db/migrate/roundtrip.test.tsindex fd488b1d..7445a1ef 100644--- a/server/src/__tests__/db/migrate/roundtrip.test.ts+++ b/server/src/__tests__/db/migrate/roundtrip.test.ts@@ -22,6 +22,7 @@ const ATTEMPT_ERROR_SUMMARY_FILENAME = '20260726_000006_attempt_error_summary.tsconst AGENT_COMPATIBILITY_FILENAME = '20260727_000001_agent_compatibility.ts';const TOMBSTONE_PROVENANCE_FILENAME = '20260728_000001_tombstone_provenance.ts';const CUSTOM_MODEL_ENDPOINT_IDENTITY_FILENAME = '20260729_000001_custom_model_endpoint_identity.ts';+const CUSTOM_ENDPOINT_HOST_LABELS_FILENAME = '20260802_000001_custom_endpoint_host_labels.ts';interface SchemaRow {type: string;@@ -90,6 +91,7 @@ describe('migration round trip', () => {AGENT_COMPATIBILITY_FILENAME,TOMBSTONE_PROVENANCE_FILENAME,CUSTOM_MODEL_ENDPOINT_IDENTITY_FILENAME,+ CUSTOM_ENDPOINT_HOST_LABELS_FILENAME,]);} finally {db.close();@@ -112,6 +114,14 @@ describe('migration round trip', () => {VALUES ('custom', 'roundtrip-custom', 'Roundtrip Custom', 50, 50, 1, 0, 1, 'user')`).run();+ // Same reasoning for the endpoint-label rename (#704): it only touches+ // custom api_keys rows, so seed one in its post-migration state (labelled+ // with its host) for the down (host -> 'Custom') and up to exercise.+ db.prepare(`+ INSERT INTO api_keys (platform, label, encrypted_key, iv, auth_tag, base_url)+ VALUES ('custom', '127.0.0.1:11434', 'x', 'x', 'x', 'http://127.0.0.1:11434/v1')+ `).run();+const fullState = snapshotAppState(db);await runDownToBaseline(db);diff --git a/server/src/__tests__/routes/custom-modalities.test.ts b/server/src/__tests__/routes/custom-modalities.test.tsindex 849615f3..b95b679a 100644--- a/server/src/__tests__/routes/custom-modalities.test.ts+++ b/server/src/__tests__/routes/custom-modalities.test.ts@@ -267,4 +267,68 @@ describe('custom provider modalities', () => {const def = getDb().prepare("SELECT value FROM settings WHERE key = 'embeddings_default_family'").get() as { value: string };expect(def.value).not.toBe('local-delete-family');});++ // The display name is optional on these routes too: unnamed means "call it+ // after the model id", and a later submit that leaves the field blank must+ // not reset a name that is already there (#704).+ it('leaves an embedding model unnamed as its id, and keeps a name across a blank re-submit', async () => {+ globalThis.fetch = vi.fn(async () => embeddingResponse(3)) as any;++ const unnamed = await post(app, '/api/embeddings/custom', {+ baseUrl: 'http://127.0.0.1:8585/v1',+ model: 'plain-embed',+ family: 'name-family',+ });+ expect(unnamed.status).toBe(201);+ expect(unnamed.body.displayName).toBe('plain-embed');++ const named = await post(app, '/api/embeddings/custom', {+ baseUrl: 'http://127.0.0.1:8585/v1',+ model: 'named-embed',+ family: 'name-family',+ displayName: 'My Embedder',+ });+ expect(named.body.displayName).toBe('My Embedder');++ // Re-submit with the name field left blank — e.g. to change the family.+ const again = await post(app, '/api/embeddings/custom', {+ baseUrl: 'http://127.0.0.1:8585/v1',+ model: 'named-embed',+ family: 'name-family',+ });+ expect(again.status).toBe(201);+ expect(again.body.displayName).toBe('My Embedder');++ const row = getDb().prepare(+ "SELECT display_name FROM embedding_models WHERE platform = 'custom' AND model_id = 'named-embed'",+ ).get() as any;+ expect(row.display_name).toBe('My Embedder');+ });++ it('does the same for image and audio models', async () => {+ const unnamed = await post(app, '/api/media/custom', {+ baseUrl: 'http://127.0.0.1:8686/v1',+ model: 'plain-image',+ modality: 'image',+ });+ expect(unnamed.body.displayName).toBe('plain-image');++ await post(app, '/api/media/custom', {+ baseUrl: 'http://127.0.0.1:8686/v1',+ model: 'named-tts',+ modality: 'audio',+ displayName: 'My Voice',+ });+ const again = await post(app, '/api/media/custom', {+ baseUrl: 'http://127.0.0.1:8686/v1',+ model: 'named-tts',+ modality: 'audio',+ });+ expect(again.body.displayName).toBe('My Voice');++ const row = getDb().prepare(+ "SELECT display_name FROM media_models WHERE platform = 'custom' AND model_id = 'named-tts'",+ ).get() as any;+ expect(row.display_name).toBe('My Voice');+ });});diff --git a/server/src/__tests__/routes/custom-provider.test.ts b/server/src/__tests__/routes/custom-provider.test.tsindex b846b486..cd25d6de 100644--- a/server/src/__tests__/routes/custom-provider.test.ts+++ b/server/src/__tests__/routes/custom-provider.test.ts@@ -356,6 +356,107 @@ describe('Custom Provider Endpoints', () => {const { status } = await post(app, '/api/keys/custom', { baseUrl: 'http://127.0.0.1:9999/v1' });expect(status).toBe(400);});++ // The dashboard's custom form always posts the plural `models`, even for a+ // single id, and puts the name it collected in the top-level displayName.+ // That name used to be bound to the singular `model` alone, so the field+ // was a no-op and the row landed named after its model id (#704).+ it('applies the top-level displayName to a lone model sent as a models array', async () => {+ const { status, body } = await post(app, '/api/keys/custom', {+ baseUrl: 'http://127.0.0.1:9998/v1',+ models: ['qwen3:4b'],+ displayName: 'My Local Qwen',+ });+ expect(status).toBe(201);+ expect(body.models[0].displayName).toBe('My Local Qwen');++ const row = getDb().prepare(+ "SELECT display_name FROM models WHERE platform = 'custom' AND model_id = 'qwen3:4b'",+ ).get() as any;+ expect(row.display_name).toBe('My Local Qwen');+ });++ it('never fans a single displayName out across several ids', async () => {+ const { status, body } = await post(app, '/api/keys/custom', {+ baseUrl: 'http://127.0.0.1:9997/v1',+ models: ['mistral:7b', 'gemma2:9b'],+ displayName: 'Should Not Apply',+ });+ expect(status).toBe(201);+ expect(body.models.map((m: any) => m.displayName).sort()).toEqual(['gemma2:9b', 'mistral:7b']);+ });++ it('lets a per-entry displayName win over the top-level one', async () => {+ const { status, body } = await post(app, '/api/keys/custom', {+ baseUrl: 'http://127.0.0.1:9996/v1',+ models: [{ model: 'phi4:mini', displayName: 'Per Entry' }],+ displayName: 'Top Level',+ });+ expect(status).toBe(201);+ expect(body.models[0].displayName).toBe('Per Entry');+ });++ // The name is optional in the form and optional on the wire: not naming a+ // model is a real choice, not an omission to paper over.+ it.each([+ ['omitted', undefined],+ ['empty', ''],+ ['blank', ' '],+ ])('falls back to the model id when the display name is %s', async (kind, displayName) => {+ const modelId = `unnamed-${kind}`;+ const { status, body } = await post(app, '/api/keys/custom', {+ baseUrl: 'http://127.0.0.1:9995/v1',+ models: [modelId],+ ...(displayName === undefined ? {} : { displayName }),+ });+ expect(status).toBe(201);+ expect(body.models[0].displayName).toBe(modelId);++ const row = getDb().prepare(+ "SELECT display_name FROM models WHERE platform = 'custom' AND model_id = ?",+ ).get(modelId) as any;+ expect(row.display_name).toBe(modelId);+ });++ // "Fetch models" (#488) re-posts bare ids for everything the endpoint+ // serves, including models already registered. Leaving the name out must+ // mean "no opinion", not "reset it" — the same rule the capability flags+ // already follow.+ it('keeps a name already on the model when a later submit omits one', async () => {+ await post(app, '/api/keys/custom', {+ baseUrl: 'http://127.0.0.1:9994/v1',+ models: ['keeper:1'],+ displayName: 'Kept Name',+ });++ const { status, body } = await post(app, '/api/keys/custom', {+ baseUrl: 'http://127.0.0.1:9994/v1',+ models: ['keeper:1', 'newcomer:1'],+ });+ expect(status).toBe(201);+ expect(body.models.find((m: any) => m.model === 'keeper:1').displayName).toBe('Kept Name');+ // …while a model nobody named still takes its id.+ expect(body.models.find((m: any) => m.model === 'newcomer:1').displayName).toBe('newcomer:1');++ const row = getDb().prepare(+ "SELECT display_name FROM models WHERE platform = 'custom' AND model_id = 'keeper:1'",+ ).get() as any;+ expect(row.display_name).toBe('Kept Name');+ });++ it('still renames a model when a later submit does name one', async () => {+ await post(app, '/api/keys/custom', {+ baseUrl: 'http://127.0.0.1:9993/v1',+ models: ['renamed:1'],+ displayName: 'First Name',+ });+ const { body } = await post(app, '/api/keys/custom', {+ baseUrl: 'http://127.0.0.1:9993/v1',+ models: ['renamed:1'],+ displayName: 'Second Name',+ });+ expect(body.models[0].displayName).toBe('Second Name');+ });});// #470: custom models used to register with supports_tools = 0, so agenticdiff --git a/server/src/db/migrate/defaults.ts b/server/src/db/migrate/defaults.tsindex 52607b6e..6d7ec146 100644--- a/server/src/db/migrate/defaults.ts+++ b/server/src/db/migrate/defaults.ts@@ -17,6 +17,7 @@ import * as attemptErrorSummary from '../migrations/20260726_000006_attempt_erroimport * as agentCompatibility from '../migrations/20260727_000001_agent_compatibility.js';import * as tombstoneProvenance from '../migrations/20260728_000001_tombstone_provenance.js';import * as customModelEndpointIdentity from '../migrations/20260729_000001_custom_model_endpoint_identity.js';+import * as customEndpointHostLabels from '../migrations/20260802_000001_custom_endpoint_host_labels.js';export interface MigrationModule {up(db: Db): void;@@ -46,6 +47,7 @@ export const ATTEMPT_ERROR_SUMMARY_FILENAME = '20260726_000006_attempt_error_sumexport const AGENT_COMPATIBILITY_FILENAME = '20260727_000001_agent_compatibility.ts';export const TOMBSTONE_PROVENANCE_FILENAME = '20260728_000001_tombstone_provenance.ts';export const CUSTOM_MODEL_ENDPOINT_IDENTITY_FILENAME = '20260729_000001_custom_model_endpoint_identity.ts';+export const CUSTOM_ENDPOINT_HOST_LABELS_FILENAME = '20260802_000001_custom_endpoint_host_labels.ts';export const DEFAULT_MIGRATIONS: readonly DefaultMigration[] = [{ filename: LEGACY_BASELINE_FILENAME, module: legacyBaseline },@@ -66,4 +68,5 @@ export const DEFAULT_MIGRATIONS: readonly DefaultMigration[] = [{ filename: AGENT_COMPATIBILITY_FILENAME, module: agentCompatibility },{ filename: TOMBSTONE_PROVENANCE_FILENAME, module: tombstoneProvenance },{ filename: CUSTOM_MODEL_ENDPOINT_IDENTITY_FILENAME, module: customModelEndpointIdentity },+ { filename: CUSTOM_ENDPOINT_HOST_LABELS_FILENAME, module: customEndpointHostLabels },];diff --git a/server/src/db/migrations/20260802_000001_custom_endpoint_host_labels.ts b/server/src/db/migrations/20260802_000001_custom_endpoint_host_labels.tsnew file mode 100644index 00000000..a0df1854--- /dev/null+++ b/server/src/db/migrations/20260802_000001_custom_endpoint_host_labels.ts@@ -0,0 +1,58 @@+// Migration: rename legacy 'Custom' endpoint labels to their host (#704)+// Created: 2026-08-02+//+// DOWN: reversible (see below)+//+// Custom endpoints registered before #705 all took the literal label 'Custom',+// so every panel that identifies a key by its label alone — analytics,+// cooldowns, quota signals, the models list — showed a column of identical+// rows once more than one relay was configured. New endpoints now default to+// the endpoint's host, but that only helped installs starting from scratch:+// an upgrade kept the indistinguishable labels already on record.+//+// Only rows still holding the exact default are touched. A label the operator+// typed (including one they deliberately typed as 'Custom' — indistinguishable+// from the default, and renaming it to the host is the same outcome they would+// get by re-adding the endpoint) is the only ambiguity; anything else they+// named stays untouched.+//+// Data only — no schema change.++import type { Db } from '../types.js';++interface KeyRow { id: number; base_url: string | null }++/** The host of an endpoint URL, or null when there is nothing usable to+ * rename to. Mirrors defaultCustomEndpointLabel in services/custom-endpoint,+ * inlined so this migration keeps working if that helper later changes. */+function hostOf(baseUrl: string | null): string | null {+ if (!baseUrl) return null;+ try {+ return new URL(baseUrl).host || null;+ } catch {+ return null;+ }+}++export function up(db: Db): void {+ const rows = db.prepare(+ "SELECT id, base_url FROM api_keys WHERE platform = 'custom' AND label = 'Custom'",+ ).all() as KeyRow[];+ const update = db.prepare('UPDATE api_keys SET label = ? WHERE id = ?');+ for (const row of rows) {+ const host = hostOf(row.base_url);+ if (host) update.run(host, row.id);+ }+}++/** Put back the generic label on every custom endpoint that currently carries+ * exactly its own host, which is the set `up` could have produced. */+export function down(db: Db): void {+ const rows = db.prepare(+ "SELECT id, label, base_url FROM api_keys WHERE platform = 'custom'",+ ).all() as (KeyRow & { label: string | null })[];+ const update = db.prepare("UPDATE api_keys SET label = 'Custom' WHERE id = ?");+ for (const row of rows) {+ if (row.label && row.label === hostOf(row.base_url)) update.run(row.id);+ }+}diff --git a/server/src/routes/embeddings.ts b/server/src/routes/embeddings.tsindex 43569978..573c4803 100644--- a/server/src/routes/embeddings.ts+++ b/server/src/routes/embeddings.ts@@ -95,7 +95,10 @@ embeddingsRouter.post('/custom', async (req: Request, res: Response) => {res.status(400).json({ error: { message: 'model is required' } });return;}- const displayName = parsed.data.displayName?.trim() || modelId;+ // Optional: NULL means "no opinion". A new model takes its id, and a model+ // already on record keeps the name it has instead of being reset by a submit+ // that simply left the field blank (#704).+ const submittedName = parsed.data.displayName?.trim() || null;const family = parsed.data.family?.trim() || modelId;const providedKey = parsed.data.apiKey?.trim() || undefined;const label = parsed.data.label?.trim() || undefined;@@ -162,7 +165,7 @@ embeddingsRouter.post('/custom', async (req: Request, res: Response) => {db.prepare(`UPDATE embedding_modelsSET family = ?,- display_name = ?,+ display_name = COALESCE(?, display_name),dimensions = ?,max_input_tokens = ?,priority = ?,@@ -170,7 +173,7 @@ embeddingsRouter.post('/custom', async (req: Request, res: Response) => {quota_label = ?,key_id = ?WHERE id = ?- `).run(family, displayName, dimensions, parsed.data.maxInputTokens ?? null, priority, quotaLabel, bindKeyId, existingModel.id);+ `).run(family, submittedName, dimensions, parsed.data.maxInputTokens ?? null, priority, quotaLabel, bindKeyId, existingModel.id);return { modelDbId: existingModel.id, keyId, storedKeyForMask };}@@ -178,11 +181,13 @@ embeddingsRouter.post('/custom', async (req: Request, res: Response) => {INSERT INTO embedding_models(family, platform, model_id, display_name, dimensions, max_input_tokens, priority, enabled, quota_label, key_id)VALUES (?, 'custom', ?, ?, ?, ?, ?, 1, ?, ?)- `).run(family, modelId, displayName, dimensions, parsed.data.maxInputTokens ?? null, priority, quotaLabel, bindKeyId);+ `).run(family, modelId, submittedName ?? modelId, dimensions, parsed.data.maxInputTokens ?? null, priority, quotaLabel, bindKeyId);return { modelDbId: Number(model.lastInsertRowid), keyId, storedKeyForMask };});const result = upsert();+ const storedName = (db.prepare('SELECT display_name FROM embedding_models WHERE id = ?')+ .get(result.modelDbId) as { display_name: string }).display_name;res.status(201).json({success: true,keyId: result.keyId,@@ -190,7 +195,7 @@ embeddingsRouter.post('/custom', async (req: Request, res: Response) => {platform: 'custom',baseUrl,model: modelId,- displayName,+ displayName: storedName,family,dimensions,maskedKey: maskKey(result.storedKeyForMask),diff --git a/server/src/routes/keys.ts b/server/src/routes/keys.tsindex 384f9fc0..16b434f6 100644--- a/server/src/routes/keys.ts+++ b/server/src/routes/keys.ts@@ -703,12 +703,14 @@ keysRouter.post('/custom', async (req: Request, res: Response) => {const label = parsed.data.label?.trim() || undefined;// Flatten singular + plural inputs into one list, dedupe by model id, drop- // blanks. The singular `displayName` only applies to a lone `model` (it can't- // sensibly fan out across many ids). Capability flags resolve per-entry first,- // then fall back to the submit-level defaults, then to undefined (DB default).+ // blanks. Capability flags resolve per-entry first, then fall back to the+ // submit-level defaults, then to undefined (DB default). `displayName` is+ // optional and stays NULL when the submit did not name the model: the field+ // is genuinely optional, so an unnamed model takes its id on insert and keeps+ // whatever name it already has on re-registration (see the upsert below).const topTools = parsed.data.supportsTools;const topVision = parsed.data.supportsVision;- const entries: { modelId: string; displayName: string; supportsTools?: boolean; supportsVision?: boolean }[] = [];+ const entries: { modelId: string; displayName: string | null; supportsTools?: boolean; supportsVision?: boolean }[] = [];const seen = new Set<string>();const addEntry = (rawId: string, rawDisplay?: string, tools?: boolean, vision?: boolean) => {const modelId = rawId.trim();@@ -716,7 +718,7 @@ keysRouter.post('/custom', async (req: Request, res: Response) => {seen.add(modelId);entries.push({modelId,- displayName: (rawDisplay?.trim() || modelId),+ displayName: rawDisplay?.trim() || null,supportsTools: tools ?? topTools,supportsVision: vision ?? topVision,});@@ -726,6 +728,17 @@ keysRouter.post('/custom', async (req: Request, res: Response) => {if (typeof m === 'string') addEntry(m);else addEntry(m.model, m.displayName, m.supportsTools, m.supportsVision);}+ // A lone model submitted through the plural `models` also carries its name in+ // the top-level `displayName` — that is exactly what the dashboard's custom+ // form sends, and binding the field to the singular `model` alone silently+ // dropped the name the user typed, leaving the row named after its model id+ // (#704). Only a submit that resolves to ONE unnamed model may take it: a+ // single name cannot fan out across several ids, which is why the form+ // disables the input as soon as a second id is entered.+ const soleName = parsed.data.displayName?.trim();+ if (soleName && !parsed.data.model?.trim() && entries.length === 1 && entries[0]!.displayName === null) {+ entries[0]!.displayName = soleName;+ }const db = getDb();@@ -788,7 +801,10 @@ keysRouter.post('/custom', async (req: Request, res: Response) => {// credential doesn't re-bind it (#619).// Capability flags: an unset flag binds NULL so COALESCE picks the insert// default (tools 1, vision 0) on a new row and preserves the existing- // value on re-registration. (#470)+ // value on re-registration. (#470) An omitted display name binds NULL the+ // same way — it falls back to the model id on a new row and leaves a name+ // already on the row alone, so the bulk re-registration behind "Fetch+ // models" (which posts bare ids) can't wipe names the operator set.const bound = db.prepare("SELECT key_id FROM models WHERE platform = 'custom' AND model_id = ? AND endpoint_scope = ?",).get(modelId, endpointScope) as { key_id: number | null } | undefined;@@ -804,12 +820,12 @@ keysRouter.post('/custom', async (req: Request, res: Response) => {(platform, model_id, display_name, intelligence_rank, speed_rank, size_label,rpm_limit, rpd_limit, tpm_limit, tpd_limit, monthly_token_budget, context_window, enabled, key_id,supports_tools, supports_vision, source, endpoint_scope)- VALUES ('custom', @modelId, @displayName, @intelligenceRank, @speedRank, @sizeLabel,+ VALUES ('custom', @modelId, COALESCE(@displayName, @modelId), @intelligenceRank, @speedRank, @sizeLabel,NULL, NULL, NULL, NULL, '', NULL, 1, @keyId,COALESCE(@tools, 1), COALESCE(@vision, 0), 'user', @endpointScope)ON CONFLICT(platform, model_id, endpoint_scope)DO UPDATE SET- display_name = excluded.display_name,+ display_name = COALESCE(@displayName, display_name),key_id = excluded.key_id,enabled = 1,supports_tools = COALESCE(@tools, supports_tools),@@ -820,9 +836,12 @@ keysRouter.post('/custom', async (req: Request, res: Response) => {endpointScope,});+ // Read back rather than echo the submitted values: an omitted display name+ // or capability flag resolves in SQL, so the row is the only place that+ // knows what this model is actually called now.const modelRow = db.prepare(- "SELECT id, supports_tools, supports_vision FROM models WHERE platform = 'custom' AND model_id = ? AND endpoint_scope = ?",- ).get(modelId, endpointScope) as { id: number; supports_tools: number; supports_vision: number };+ "SELECT id, display_name, supports_tools, supports_vision FROM models WHERE platform = 'custom' AND model_id = ? AND endpoint_scope = ?",+ ).get(modelId, endpointScope) as { id: number; display_name: string; supports_tools: number; supports_vision: number };// Append to the fallback chain if not already present.const inChain = db.prepare('SELECT 1 FROM fallback_config WHERE model_db_id = ?').get(modelRow.id);@@ -835,7 +854,7 @@ keysRouter.post('/custom', async (req: Request, res: Response) => {registered.push({modelDbId: modelRow.id,model: modelId,- displayName,+ displayName: modelRow.display_name,supportsTools: modelRow.supports_tools === 1,supportsVision: modelRow.supports_vision === 1,created,diff --git a/server/src/routes/media.ts b/server/src/routes/media.tsindex 88a0cbda..4101e116 100644--- a/server/src/routes/media.ts+++ b/server/src/routes/media.ts@@ -119,7 +119,10 @@ mediaRouter.post('/custom', (req: Request, res: Response) => {res.status(400).json({ error: { message: 'model is required' } });return;}- const displayName = parsed.data.displayName?.trim() || modelId;+ // Optional: NULL means "no opinion". A new model takes its id, and a model+ // already on record keeps the name it has instead of being reset by a submit+ // that simply left the field blank (#704).+ const submittedName = parsed.data.displayName?.trim() || null;const label = parsed.data.label?.trim() || undefined;const providedKey = parsed.data.apiKey?.trim() || undefined;const quotaLabel = parsed.data.quotaLabel?.trim() || 'custom endpoint';@@ -149,14 +152,14 @@ mediaRouter.post('/custom', (req: Request, res: Response) => {if (existingModel) {db.prepare(`UPDATE media_models- SET display_name = ?,+ SET display_name = COALESCE(?, display_name),modality = ?,priority = ?,enabled = 1,quota_label = ?,key_id = ?WHERE id = ?- `).run(displayName, parsed.data.modality, priority, quotaLabel, bindKeyId, existingModel.id);+ `).run(submittedName, parsed.data.modality, priority, quotaLabel, bindKeyId, existingModel.id);return { modelDbId: existingModel.id, keyId, storedKeyForMask };}@@ -164,11 +167,13 @@ mediaRouter.post('/custom', (req: Request, res: Response) => {INSERT INTO media_models(platform, model_id, display_name, modality, priority, enabled, quota_label, key_id)VALUES ('custom', ?, ?, ?, ?, 1, ?, ?)- `).run(modelId, displayName, parsed.data.modality, priority, quotaLabel, bindKeyId);+ `).run(modelId, submittedName ?? modelId, parsed.data.modality, priority, quotaLabel, bindKeyId);return { modelDbId: Number(model.lastInsertRowid), keyId, storedKeyForMask };});const result = upsert();+ const storedName = (db.prepare('SELECT display_name FROM media_models WHERE id = ?')+ .get(result.modelDbId) as { display_name: string }).display_name;res.status(201).json({success: true,keyId: result.keyId,@@ -176,7 +181,7 @@ mediaRouter.post('/custom', (req: Request, res: Response) => {platform: 'custom',baseUrl,model: modelId,- displayName,+ displayName: storedName,modality: parsed.data.modality,maskedKey: maskKey(result.storedKeyForMask),});