From ce525199958bd72b4405feb61845c81cf46a2307 Mon Sep 17 00:00:00 2001 From: gganebnyi Date: Mon, 23 Nov 2026 11:28:48 +0200 Subject: [PATCH 1/6] feat(agent): shared model providers an admin sets up for everyone An instance admin adds a custom provider once (any OpenAI Chat Completions or Anthropic Messages endpoint) and every signed-in person gets it beside their own connections. The definition, key and headers live in shared_model_accounts (key and headers sealed); each person's model, effort and on/off live in shared_model_account_prefs (migration 0062). getAccounts/getAccount merge the enabled ones after the person's own accounts as accounts marked shared, so the composer, the default (someone with no account of their own runs on the first one on), the free-tier meter and runs need no change. Picks write the person's prefs row; edit and disconnect of a shared kind are refused with 403, and the set-up probes never fall back to a shared key. A person sees the endpoint's origin only. DOOP_CUSTOM_PROVIDERS=false hides them. Admin routes under /api/admin/shared-providers list, add, edit (a key left out is kept), switch on or off, delete (with every person's prefs), and list models or test before saving, through the same validation and probes as personal providers, which move from index.ts to customProviders.ts. No response carries the key or header values, the admin's included, and the stored ones only go to the origin they were saved for: a probe or edit for another origin must bring its own. For billing a shared provider is the person's own connection: it lifts the free-tier meter, and the server's image keys stop drawing for them as for anyone with a connection. Run failures on a shared provider tell the person to ask their admin rather than to reconnect it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01ABWHJg7QHZpRjDADALswQZ --- server/accountDeletion.ts | 10 +- server/admin.ts | 162 + server/agentModel.ts | 74 +- server/agentRunners.ts | 1 + server/chatCompletionsAgent.ts | 5 +- server/customProviderFetch.ts | 20 + server/customProviders.ts | 61 +- .../migrations/0066_shared_model_accounts.sql | 23 + server/db/migrations/meta/0066_snapshot.json | 5477 +++++++++++++++++ server/db/migrations/meta/_journal.json | 9 +- server/db/schema.ts | 36 + server/index.ts | 74 +- server/modelAccounts.ts | 103 +- server/openaiAgent.ts | 12 +- server/resident.ts | 9 +- server/secretBackfill.ts | 6 + server/sharedModelAccounts.ts | 359 ++ shared/agentRunner.ts | 2 + tests/accountDeletion.test.ts | 18 +- tests/customProvider.test.ts | 98 +- tests/sharedModelAccounts.test.ts | 245 + tests/sharedModelAccountsStore.test.ts | 99 + tests/sharedModelProvidersHttp.test.ts | 353 ++ tests/sharedModelProvidersSealed.test.ts | 72 + 24 files changed, 7251 insertions(+), 77 deletions(-) create mode 100644 server/db/migrations/0066_shared_model_accounts.sql create mode 100644 server/db/migrations/meta/0066_snapshot.json create mode 100644 server/sharedModelAccounts.ts create mode 100644 tests/sharedModelAccounts.test.ts create mode 100644 tests/sharedModelAccountsStore.test.ts create mode 100644 tests/sharedModelProvidersHttp.test.ts create mode 100644 tests/sharedModelProvidersSealed.test.ts diff --git a/server/accountDeletion.ts b/server/accountDeletion.ts index 1034e656f..2826e7402 100644 --- a/server/accountDeletion.ts +++ b/server/accountDeletion.ts @@ -1,6 +1,12 @@ import { eq } from 'drizzle-orm' import { db } from './db/index.ts' -import { linearOAuthStates, liveActivities, liveActivityStarters, slackOAuthStates } from './db/schema.ts' +import { + linearOAuthStates, + liveActivities, + liveActivityStarters, + sharedModelAccountPrefs, + slackOAuthStates, +} from './db/schema.ts' import { forgetLibrary } from './componentLibrary.ts' import { dropPersonalAgents } from './customAgents.ts' import { dropPersonalSkills } from './skills.ts' @@ -37,6 +43,8 @@ export async function purgeUserData(userId: string): Promise<{ deletedCanvases: for (const workspaceId of workspaceIdsFor(userId)) await leaveWorkspace(workspaceId, userId) await db.delete(liveActivities).where(eq(liveActivities.userId, userId)) await db.delete(liveActivityStarters).where(eq(liveActivityStarters.userId, userId)) + /* their model picks and on/off on the providers an admin shares */ + await db.delete(sharedModelAccountPrefs).where(eq(sharedModelAccountPrefs.userId, userId)) await dropPersonalAgents(userId) await dropPersonalSkills(userId) return { deletedCanvases } diff --git a/server/admin.ts b/server/admin.ts index cf4276910..75ff470f5 100644 --- a/server/admin.ts +++ b/server/admin.ts @@ -10,6 +10,29 @@ import * as workspaces from './workspaces.ts' import { loadOidcConfig, loginProvidersConfig } from './auth.ts' import { getInstanceSettings, ssoAdminSignedIn, updateInstanceSettings } from './instanceSettings.ts' import { isInstanceSettingsPatch } from '../shared/instanceSettings.ts' +import { + CustomProviderError, + customConfig, + customFailure, + customSecrets, + discoverCustomModels, + discoveryEndpoint, + takeProbeSlot, + testCustomProvider, +} from './customProviders.ts' +import { CustomProviderUrlError, customProvidersEnabled } from './customProviderFetch.ts' +import { + SharedProviderError, + createSharedProvider, + deleteSharedProvider, + getSharedProvider, + listSharedProviders, + movedSecretsRefusal, + setSharedProviderEnabled, + sharedStatusOf, + updateSharedProvider, +} from './sharedModelAccounts.ts' +import { isCustomProviderKind } from '../shared/customProvider.ts' /** * Instance-admin surface, mounted at /api/admin (so already behind the @@ -126,3 +149,142 @@ adminRouter.patch('/instance-settings', async (req, res) => { if ('refusal' in result) return res.status(409).json({ refusal: result.refusal }) res.json(await instanceSettingsView()) }) + +/* ---- shared model providers (server/sharedModelAccounts.ts): custom + providers set up here once, for every person on the instance. The key and + header values go in and never come back out, here included: the view says + which headers are set and whether there is a key. */ + +async function sharedProvidersView() { + return { + providers: (await listSharedProviders()).map(sharedStatusOf), + /* the operator's switch (DOOP_CUSTOM_PROVIDERS): off hides them from everyone */ + customProviders: customProvidersEnabled(), + } +} + +/** A write's failure: what the admin can fix is said, anything else is a + * bare 500 — a database error can quote the row it was writing. */ +function sharedFailure(res: express.Response, error: unknown, fallback: string) { + if (error instanceof SharedProviderError) return res.status(error.status).json({ error: error.message }) + if (error instanceof CustomProviderError || error instanceof CustomProviderUrlError) { + return res.status(400).json({ error: error.message }) + } + console.error(`[admin] ${fallback}`) + return res.status(500).json({ error: fallback }) +} + +adminRouter.get('/shared-providers', async (req, res) => { + try { + res.json(await sharedProvidersView()) + } catch { + res.status(500).json({ error: 'shared providers unavailable' }) + } +}) + +/* everything below changes or calls a provider, which the operator's switch forbids */ +adminRouter.use('/shared-providers', (_req, res, next) => { + if (!customProvidersEnabled()) return res.status(404).json({ error: 'custom providers are off on this server' }) + next() +}) + +/** The secrets a set-up request for `baseUrl` should use: what it carries, + * else (for a provider being edited) what is stored for it — and those only + * while the request stays on the stored endpoint's origin. */ +async function sharedProbeSecrets(body: Record, baseUrl: string) { + const given = customSecrets(body) + const stored = isCustomProviderKind(body.kind) ? await getSharedProvider(body.kind) : null + if (stored) { + const refusal = movedSecretsRefusal( + { baseUrl: stored.custom.baseUrl, hasKey: !!stored.apiKey, hasHeaders: !!stored.headers }, + baseUrl, + given, + ) + if (refusal) throw new CustomProviderError(refusal) + } + const apiKey = given.apiKey ?? stored?.apiKey + const headers = given.headers ?? stored?.headers + return { ...(apiKey ? { apiKey } : {}), ...(headers ? { headers } : {}) } +} + +/* the endpoint's own model list, to fill the form's rows */ +adminRouter.post('/shared-providers/models', async (req, res) => { + if (!takeProbeSlot(req.user!.id)) return res.status(429).json({ error: 'Too many requests. Wait a few minutes.' }) + try { + const body = (req.body ?? {}) as Record + const endpoint = discoveryEndpoint(body) + const models = await discoverCustomModels({ + config: endpoint, + ...(await sharedProbeSecrets(body, endpoint.baseUrl)), + }) + res.json({ models }) + } catch (error) { + customFailure(res, error, 'could not list that endpoint’s models') + } +}) + +/* one short turn that has to call a tool: the agent cannot work without it */ +adminRouter.post('/shared-providers/test', async (req, res) => { + if (!takeProbeSlot(req.user!.id)) return res.status(429).json({ error: 'Too many requests. Wait a few minutes.' }) + try { + const body = (req.body ?? {}) as Record + const config = customConfig(body) + const model = config.models.find((option) => option.id === body.model) ?? config.models[0] + if (!model) throw new CustomProviderError('Add a model to test') + await testCustomProvider({ config, ...(await sharedProbeSecrets(body, config.baseUrl)) }, model) + res.json({ ok: true, model: model.id }) + } catch (error) { + customFailure(res, error, 'the test turn failed') + } +}) + +adminRouter.post('/shared-providers', async (req, res) => { + try { + const body = (req.body ?? {}) as Record + await createSharedProvider(req.user!.id, customConfig(body), customSecrets(body)) + res.json(await sharedProvidersView()) + } catch (error) { + sharedFailure(res, error, 'could not add that provider') + } +}) + +/* the description, and the key or headers where given: left out keeps them */ +adminRouter.put('/shared-providers/:kind', async (req, res) => { + const kind = req.params.kind + if (!isCustomProviderKind(kind)) return res.status(400).json({ error: 'unknown provider' }) + try { + const body = (req.body ?? {}) as Record + await updateSharedProvider(req.user!.id, kind, customConfig(body), customSecrets(body)) + res.json(await sharedProvidersView()) + } catch (error) { + sharedFailure(res, error, 'could not save that provider') + } +}) + +/* on or off for everyone, its definition kept */ +adminRouter.patch('/shared-providers/:kind', async (req, res) => { + const kind = req.params.kind + if (!isCustomProviderKind(kind)) return res.status(400).json({ error: 'unknown provider' }) + const enabled: unknown = req.body?.enabled + if (typeof enabled !== 'boolean') return res.status(400).json({ error: 'say whether it is on' }) + try { + await setSharedProviderEnabled(req.user!.id, kind, enabled) + res.json(await sharedProvidersView()) + } catch (error) { + sharedFailure(res, error, 'could not change that provider') + } +}) + +/* gone for everyone, with every person's picks on it */ +adminRouter.delete('/shared-providers/:kind', async (req, res) => { + const kind = req.params.kind + if (!isCustomProviderKind(kind)) return res.status(400).json({ error: 'unknown provider' }) + try { + if (!(await deleteSharedProvider(kind))) { + return res.status(404).json({ error: 'That shared provider no longer exists' }) + } + res.json(await sharedProvidersView()) + } catch (error) { + sharedFailure(res, error, 'could not remove that provider') + } +}) diff --git a/server/agentModel.ts b/server/agentModel.ts index 51c150dce..c58bda552 100644 --- a/server/agentModel.ts +++ b/server/agentModel.ts @@ -8,7 +8,8 @@ import type { RunnerPick } from '../shared/agentRunner.ts' import Anthropic from '@anthropic-ai/sdk' import { withFreshToken, accountModelFor, accountVisionFor, accountWithPick, customModelFor } from './modelAccounts.ts' import type { AccountKind, BuiltinAccountKind, ModelAccount } from './modelAccounts.ts' -import { customProviderFetch } from './customProviderFetch.ts' +import { customProviderFetch, redactSecrets } from './customProviderFetch.ts' +import { ModelStreamInterruptedError } from './modelTurnRetry.ts' import { isCustomProviderKind, type CustomModel, type CustomProviderConfig } from '../shared/customProvider.ts' import { ModelAuthError, ModelUnavailableError, effortFor, runAzureTurn, runOpenAiTurn } from './openaiAgent.ts' import type { StopReason, TurnBlock } from './openaiAgent.ts' @@ -65,6 +66,8 @@ export interface AgentModel { label: string /** the user whose account pays, when it isn't the server's key */ userId?: string + /** an admin's shared provider: its key and models are the admin's to fix */ + shared?: true /** false = the model cannot see images and the run degrades to no visual * review; absent means true (every pre-roster provider has vision) */ vision?: boolean @@ -255,6 +258,64 @@ export interface CustomTarget { * model was said to allow. */ export function customTurn(target: CustomTarget, model: CustomModel): AgentModel['run'] { + const run = customTransport(target, model) + return async (req) => { + try { + return await run(req) + } catch (error) { + throw redactedError(error, target) + } + } +} + +/* the classes a run's failure is read by (resident.ts, modelTurnRetry.ts), + whose constructors take the message */ +const ERROR_CLASSES = [ + ModelConfigurationError, + ModelUnavailableError, + ModelAuthError, + ModelStreamInterruptedError, +] as const + +/* how deep a cause chain is followed: undici's socket error sits two down */ +const MAX_CAUSE_DEPTH = 5 + +/** What a retry reads off an error and its causes (modelTurnRetry.ts): the + * `code` and the `name` at each level, and none of their messages, which + * are the endpoint's or the transport's words. */ +function retrySignal(error: unknown, depth = 0): Error | undefined { + if (!error || typeof error !== 'object' || depth >= MAX_CAUSE_DEPTH) return undefined + const { code, name, cause } = error as { code?: unknown; name?: unknown; cause?: unknown } + const signal = new Error(typeof code === 'string' ? code : '') + if (typeof name === 'string') signal.name = name + if (typeof code === 'string') Object.assign(signal, { code }) + const inner = retrySignal(cause, depth + 1) + if (inner) signal.cause = inner + return signal +} + +/** + * A custom provider's failure with its key and header values masked + * (redactSecrets), as a fresh error of the class the run reads. What a retry + * needs survives — the error's `code` and a cause chain of codes and names + * only, so a dropped connection (ECONNRESET, UND_ERR_SOCKET) is still retried + * — and nothing else of the original rides along (no messages in the causes, + * no SDK body or headers) to a log line. A cancel or timeout carries no + * endpoint text and passes as it is. + */ +export function redactedError(error: unknown, secrets: { apiKey?: string; headers?: Record }): unknown { + if (!(error instanceof Error) || error.name === 'AbortError' || error.name === 'TimeoutError') return error + const message = redactSecrets(error.message, secrets) + const Class = ERROR_CLASSES.find((candidate) => error instanceof candidate) ?? Error + const redacted = new Class(message) + const { code } = error as { code?: unknown } + if (typeof code === 'string') Object.assign(redacted, { code }) + const cause = retrySignal(error.cause) + if (cause) redacted.cause = cause + return redacted +} + +function customTransport(target: CustomTarget, model: CustomModel): AgentModel['run'] { const { config, apiKey, headers = {} } = target const budget = (req: AgentTurnRequest) => Math.min(req.maxTokens, model.maxOutputTokens ?? req.maxTokens) if (config.apiType === 'anthropic') { @@ -289,6 +350,8 @@ export function customTurn(target: CustomTarget, model: CustomModel): AgentModel ...(config.echoReasoning ? { echoReasoning: true } : {}), ...(config.tokenParam ? { tokenParam: config.tokenParam } : {}), fetch: customProviderFetch, + /* masked on the whole body, before responseError shortens it */ + redact: (text) => redactSecrets(text, target), } return (req) => runChatCompletionsTurn(chat, { @@ -325,11 +388,18 @@ export function withoutImages(messages: Anthropic.MessageParam[]): Anthropic.Mes function customModel(account: ModelAccount): AgentModel { const config = account.custom const model = customModelFor(account) - if (!config || !model) throw new ModelConfigurationError('Add a model to this custom provider in Settings.') + if (!config || !model) { + throw new ModelConfigurationError( + account.shared + ? 'This shared provider has no model to run. Ask your admin to add one in Admin → Shared models.' + : 'Add a model to this custom provider in Settings.', + ) + } return { provider: account.kind, label: `${config.name} (${model.id})`, userId: account.userId, + ...(account.shared ? { shared: true as const } : {}), vision: model.vision, run: customTurn( { diff --git a/server/agentRunners.ts b/server/agentRunners.ts index 47ed71db8..80cdcf1c8 100644 --- a/server/agentRunners.ts +++ b/server/agentRunners.ts @@ -78,6 +78,7 @@ export async function listRunners(userId: string): Promise { runners.push({ provider: account.kind, name: nameOf(account), + ...(account.shared ? { shared: true as const } : {}), ...(account.email ? { email: account.email } : {}), model: accountModelFor(account), ...(effort ? { effort } : {}), diff --git a/server/chatCompletionsAgent.ts b/server/chatCompletionsAgent.ts index 9fcb3bad6..43a54a3b8 100644 --- a/server/chatCompletionsAgent.ts +++ b/server/chatCompletionsAgent.ts @@ -71,6 +71,9 @@ export interface ChatCompletionsConfig { tokenParam?: CustomTokenParam /** the transport for the request; the global fetch when unset */ fetch?: (url: string, init: RequestInit) => Promise + /** masks credentials in the endpoint's error text before it is shortened + * (a custom provider's key and header values) */ + redact?: (text: string) => string } export function openrouterConfig(apiKey: string, model: string, vision: boolean): ChatCompletionsConfig { @@ -321,7 +324,7 @@ export async function runChatCompletionsTurn(config: ChatCompletionsConfig, req: }), ...(req.signal ? { signal: req.signal } : {}), }) - if (!res.ok) throw await responseError(res, config.label) + if (!res.ok) throw await responseError(res, config.label, config.redact) return fromCompletion((await res.json()) as CompletionBody, config.label) } diff --git a/server/customProviderFetch.ts b/server/customProviderFetch.ts index 1cbfb93fd..49c0f8bb0 100644 --- a/server/customProviderFetch.ts +++ b/server/customProviderFetch.ts @@ -33,6 +33,26 @@ function privateHostsAllowed(): boolean { return env.DOOP_CUSTOM_PROVIDER_PRIVATE_HOSTS } +/* a header value this short is a flag or a tenant letter, not a secret, and + masking it would garble every word it appears in */ +const MIN_REDACTED = 4 + +/** + * Text that came back from a custom provider (an error body, a refusal) with + * the provider's key and every extra header value masked. An endpoint may + * quote the credential it refused ("invalid key sk-…"), and for a shared + * provider that text reaches people who must never see the admin's key: in + * a run's status, a stored error or a log line. Everything derived from an + * endpoint's answer goes through this before it leaves the transport. + */ +export function redactSecrets(text: string, secrets: { apiKey?: string; headers?: Record }): string { + const values = [secrets.apiKey ?? '', ...Object.values(secrets.headers ?? {})] + .filter((value) => value.length >= MIN_REDACTED) + /* longest first, so a key that contains a header value is masked whole */ + .sort((a, b) => b.length - a.length) + return values.reduce((out, value) => out.split(value).join('***'), text) +} + /** The URL if this server may send a request to it, before any network I/O; * the public-address check on its resolved addresses happens per request. */ export function reachableUrl(raw: string | URL): URL { diff --git a/server/customProviders.ts b/server/customProviders.ts index f4bfa81c1..5a5b69ad1 100644 --- a/server/customProviders.ts +++ b/server/customProviders.ts @@ -1,9 +1,19 @@ import type Anthropic from '@anthropic-ai/sdk' +import type express from 'express' import { z } from 'zod' import { customTurn, type CustomTarget } from './agentModel.ts' -import { customProviderFetch, reachableUrl } from './customProviderFetch.ts' +import { CustomProviderUrlError, customProviderFetch, reachableUrl } from './customProviderFetch.ts' import type { ModelOption } from '../shared/modelMenu.ts' -import { MAX_CUSTOM_MODEL_ID, type CustomModel, type CustomProviderConfig } from '../shared/customProvider.ts' +import { + CUSTOM_API_TYPES, + MAX_CUSTOM_MODEL_ID, + normalizeBaseUrl, + parseCustomHeaders, + parseCustomKey, + parseCustomProviderConfig, + type CustomModel, + type CustomProviderConfig, +} from '../shared/customProvider.ts' /** * What Settings asks of a custom provider while it is being set up: which @@ -24,6 +34,53 @@ const ModelList = z.object({ data: z.array(z.object({ id: z.string() })) }) export class CustomProviderError extends Error {} +/* ---- what the set-up routes read off a request: Settings' own + (server/index.ts) and Admin's shared ones (server/admin.ts) */ + +/** The key and headers a request carries: a field left out is undefined, so + * an edit keeps the stored one; an empty key clears it. */ +export function customSecrets(body: Record): { apiKey?: string; headers?: Record } { + const secrets: { apiKey?: string; headers?: Record } = {} + if (body.apiKey !== undefined) { + const key = parseCustomKey(body.apiKey) + if (!key.ok) throw new CustomProviderError(key.error) + secrets.apiKey = key.value + } + if (body.headers !== undefined) { + const headers = parseCustomHeaders(body.headers) + if (!headers.ok) throw new CustomProviderError(headers.error) + secrets.headers = headers.value + } + return secrets +} + +/** A validated provider description whose URL this server may reach. */ +export function customConfig(body: unknown): CustomProviderConfig { + const config = parseCustomProviderConfig(body) + if (!config.ok) throw new CustomProviderError(config.error) + reachableUrl(config.value.baseUrl) + return config.value +} + +/** The endpoint a Fetch models request names, before anything is saved. */ +export function discoveryEndpoint(body: Record): Pick { + const apiType = CUSTOM_API_TYPES.find((type) => type === body.apiType) + if (!apiType) throw new CustomProviderError('Pick the API type') + const baseUrl = normalizeBaseUrl(typeof body.baseUrl === 'string' ? body.baseUrl : '') + if (!baseUrl.ok) throw new CustomProviderError(baseUrl.error) + return { apiType, baseUrl: baseUrl.value } +} + +export function customFailure(res: express.Response, error: unknown, fallback: string) { + if (error instanceof CustomProviderError || error instanceof CustomProviderUrlError) { + return res.status(400).json({ error: error.message }) + } + /* the provider's own error text (a 400 body, a refused model) is what the + person needs to fix their endpoint; never a stack */ + const message = error instanceof Error ? error.message.slice(0, 500) : fallback + return res.status(400).json({ error: message || fallback }) +} + /** * The model ids the endpoint lists: `GET {base}/models` for Chat Completions, * `GET {base}/v1/models` for the Messages API. Many compatible servers list diff --git a/server/db/migrations/0066_shared_model_accounts.sql b/server/db/migrations/0066_shared_model_accounts.sql new file mode 100644 index 000000000..41203089f --- /dev/null +++ b/server/db/migrations/0066_shared_model_accounts.sql @@ -0,0 +1,23 @@ +CREATE TABLE IF NOT EXISTS "shared_model_account_prefs" ( + "user_id" text NOT NULL, + "kind" text NOT NULL, + "model" text, + "reasoning_effort" text, + "enabled" boolean DEFAULT true NOT NULL, + "updated_at" bigint NOT NULL, + CONSTRAINT "shared_model_account_prefs_user_id_kind_pk" PRIMARY KEY("user_id","kind") +); +--> statement-breakpoint +CREATE TABLE IF NOT EXISTS "shared_model_accounts" ( + "kind" text PRIMARY KEY NOT NULL, + "custom" jsonb NOT NULL, + "api_key" text, + "custom_headers" text, + "enabled" boolean DEFAULT true NOT NULL, + "created_by" text, + "updated_by" text, + "created_at" bigint NOT NULL, + "updated_at" bigint NOT NULL +); +--> statement-breakpoint +CREATE INDEX IF NOT EXISTS "shared_model_account_prefs_kind_idx" ON "shared_model_account_prefs" USING btree ("kind"); \ No newline at end of file diff --git a/server/db/migrations/meta/0066_snapshot.json b/server/db/migrations/meta/0066_snapshot.json new file mode 100644 index 000000000..1415dc73a --- /dev/null +++ b/server/db/migrations/meta/0066_snapshot.json @@ -0,0 +1,5477 @@ +{ + "id": "bdda4a48-8f87-4e22-8821-a2d1187f4dec", + "prevId": "fe8ac8ee-c136-43a2-8b99-41438d88fa46", + "version": "7", + "dialect": "postgresql", + "tables": { + "public.activity": { + "name": "activity", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "canvas_id": { + "name": "canvas_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "actor_name": { + "name": "actor_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "actor_kind": { + "name": "actor_kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "actor_color": { + "name": "actor_color", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "message": { + "name": "message", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "frame_id": { + "name": "frame_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "at": { + "name": "at", + "type": "bigint", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "activity_canvas_idx": { + "name": "activity_canvas_idx", + "columns": [ + { + "expression": "canvas_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.agent_defaults": { + "name": "agent_defaults", + "schema": "", + "columns": { + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "provider": { + "name": "provider", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "bigint", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.agent_feedback": { + "name": "agent_feedback", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "at": { + "name": "at", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "category": { + "name": "category", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "message": { + "name": "message", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "tool": { + "name": "tool", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "agent_name": { + "name": "agent_name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "client": { + "name": "client", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "canvas_id": { + "name": "canvas_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "agent_feedback_at_idx": { + "name": "agent_feedback_at_idx", + "columns": [ + { + "expression": "at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.agent_keys": { + "name": "agent_keys", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "secret_hash": { + "name": "secret_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "start": { + "name": "start", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "last_used_at": { + "name": "last_used_at", + "type": "bigint", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "agent_keys_user_idx": { + "name": "agent_keys_user_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "agent_keys_hash_idx": { + "name": "agent_keys_hash_idx", + "columns": [ + { + "expression": "secret_hash", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.agent_overrides": { + "name": "agent_overrides", + "schema": "", + "columns": { + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "role_id": { + "name": "role_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "disabled": { + "name": "disabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "color": { + "name": "color", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "blurb": { + "name": "blurb", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "brief": { + "name": "brief", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "reviewer": { + "name": "reviewer", + "type": "boolean", + "primaryKey": false, + "notNull": false + }, + "updated_by": { + "name": "updated_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "bigint", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": { + "agent_overrides_scope_role_id_pk": { + "name": "agent_overrides_scope_role_id_pk", + "columns": [ + "scope", + "role_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.asset_refs": { + "name": "asset_refs", + "schema": "", + "columns": { + "asset_id": { + "name": "asset_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "frame_id": { + "name": "frame_id", + "type": "text", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "asset_refs_frame_idx": { + "name": "asset_refs_frame_idx", + "columns": [ + { + "expression": "frame_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "asset_refs_asset_id_frame_id_pk": { + "name": "asset_refs_asset_id_frame_id_pk", + "columns": [ + "asset_id", + "frame_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.assets": { + "name": "assets", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "canvas_id": { + "name": "canvas_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "owner_id": { + "name": "owner_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "mime": { + "name": "mime", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "ext": { + "name": "ext", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "size": { + "name": "size", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "uploaded_by": { + "name": "uploaded_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "described_at": { + "name": "described_at", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "described_by": { + "name": "described_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "describe_attempts": { + "name": "describe_attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "describe_payer_id": { + "name": "describe_payer_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "describe_provider": { + "name": "describe_provider", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "assets_canvas_idx": { + "name": "assets_canvas_idx", + "columns": [ + { + "expression": "canvas_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.automation_approvals": { + "name": "automation_approvals", + "schema": "", + "columns": { + "automation_id": { + "name": "automation_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "frame_id": { + "name": "frame_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "approved_at": { + "name": "approved_at", + "type": "bigint", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "automation_approvals_event_idx": { + "name": "automation_approvals_event_idx", + "columns": [ + { + "expression": "automation_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "frame_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "approved_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.automation_runs": { + "name": "automation_runs", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "automation_id": { + "name": "automation_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "started_at": { + "name": "started_at", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "ended_at": { + "name": "ended_at", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "summary": { + "name": "summary", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "canvas_id": { + "name": "canvas_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "failure": { + "name": "failure", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "state": { + "name": "state", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "lease_until": { + "name": "lease_until", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "default": 0 + } + }, + "indexes": { + "automation_runs_automation_idx": { + "name": "automation_runs_automation_idx", + "columns": [ + { + "expression": "automation_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.automations": { + "name": "automations", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "owner_id": { + "name": "owner_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "enabled": { + "name": "enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "schedule": { + "name": "schedule", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "trigger": { + "name": "trigger", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{\"type\":\"schedule\"}'::jsonb" + }, + "approval_since": { + "name": "approval_since", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "steps": { + "name": "steps", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "next_run_at": { + "name": "next_run_at", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "bigint", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "automations_owner_idx": { + "name": "automations_owner_idx", + "columns": [ + { + "expression": "owner_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "automations_next_run_idx": { + "name": "automations_next_run_idx", + "columns": [ + { + "expression": "next_run_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.backgrounds": { + "name": "backgrounds", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "width": { + "name": "width", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "height": { + "name": "height", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "tone": { + "name": "tone", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "style": { + "name": "style", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "avg_color": { + "name": "avg_color", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "palette": { + "name": "palette", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "tags": { + "name": "tags", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "slots": { + "name": "slots", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "text_zone": { + "name": "text_zone", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "enabled": { + "name": "enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "created_at": { + "name": "created_at", + "type": "bigint", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.canvas_members": { + "name": "canvas_members", + "schema": "", + "columns": { + "canvas_id": { + "name": "canvas_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "added_by": { + "name": "added_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "added_at": { + "name": "added_at", + "type": "bigint", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": { + "canvas_members_canvas_id_user_id_pk": { + "name": "canvas_members_canvas_id_user_id_pk", + "columns": [ + "canvas_id", + "user_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.canvases": { + "name": "canvases", + "schema": "", + "columns": { + "pages": { + "name": "pages", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "guides": { + "name": "guides", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "token_themes": { + "name": "token_themes", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "owner_id": { + "name": "owner_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "link_access": { + "name": "link_access", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "published_at": { + "name": "published_at", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "category": { + "name": "category", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "copy_count": { + "name": "copy_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "bigint", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.comments": { + "name": "comments", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "canvas_id": { + "name": "canvas_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "frame_id": { + "name": "frame_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "element_id": { + "name": "element_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "element_origin": { + "name": "element_origin", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "selector": { + "name": "selector", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "snippet": { + "name": "snippet", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "page_id": { + "name": "page_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "x": { + "name": "x", + "type": "double precision", + "primaryKey": false, + "notNull": false + }, + "y": { + "name": "y", + "type": "double precision", + "primaryKey": false, + "notNull": false + }, + "from_name": { + "name": "from_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "from_user_id": { + "name": "from_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "text": { + "name": "text", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "at": { + "name": "at", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "for_agent": { + "name": "for_agent", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "target_agent": { + "name": "target_agent", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "claimed_by": { + "name": "claimed_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "claimed_at": { + "name": "claimed_at", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "failed_at": { + "name": "failed_at", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "failure_reason": { + "name": "failure_reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "resolved_by": { + "name": "resolved_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "resolved_at": { + "name": "resolved_at", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "parent_id": { + "name": "parent_id", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "comments_canvas_idx": { + "name": "comments_canvas_idx", + "columns": [ + { + "expression": "canvas_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.component_revisions": { + "name": "component_revisions", + "schema": "", + "columns": { + "canvas_id": { + "name": "canvas_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "component_id": { + "name": "component_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "rev": { + "name": "rev", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "render_rev": { + "name": "render_rev", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "template": { + "name": "template", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "raw_css": { + "name": "raw_css", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "head": { + "name": "head", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "props": { + "name": "props", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "saved_at": { + "name": "saved_at", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "saved_by": { + "name": "saved_by", + "type": "text", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": { + "component_revisions_canvas_id_component_id_rev_pk": { + "name": "component_revisions_canvas_id_component_id_rev_pk", + "columns": [ + "canvas_id", + "component_id", + "rev" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.components": { + "name": "components", + "schema": "", + "columns": { + "canvas_id": { + "name": "canvas_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "id": { + "name": "id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "template": { + "name": "template", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "css": { + "name": "css", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "raw_css": { + "name": "raw_css", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "head": { + "name": "head", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "props": { + "name": "props", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "slots": { + "name": "slots", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "rev": { + "name": "rev", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "render_rev": { + "name": "render_rev", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "main_frame_id": { + "name": "main_frame_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "code": { + "name": "code", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "source": { + "name": "source", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "history": { + "name": "history", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'active'" + }, + "deleted_at": { + "name": "deleted_at", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "deleted_by": { + "name": "deleted_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "updated_by": { + "name": "updated_by", + "type": "text", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": { + "components_canvas_id_id_pk": { + "name": "components_canvas_id_id_pk", + "columns": [ + "canvas_id", + "id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.custom_agents": { + "name": "custom_agents", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "handle": { + "name": "handle", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "color": { + "name": "color", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "blurb": { + "name": "blurb", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "brief": { + "name": "brief", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "reviewer": { + "name": "reviewer", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "bigint", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "custom_agents_scope_handle_idx": { + "name": "custom_agents_scope_handle_idx", + "columns": [ + { + "expression": "scope", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "handle", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "custom_agents_scope_name_idx": { + "name": "custom_agents_scope_name_idx", + "columns": [ + { + "expression": "scope", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.decisions": { + "name": "decisions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "canvas_id": { + "name": "canvas_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "text": { + "name": "text", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "summary": { + "name": "summary", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "frame_id": { + "name": "frame_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "from_name": { + "name": "from_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "agent_name": { + "name": "agent_name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "at": { + "name": "at", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "distilled_at": { + "name": "distilled_at", + "type": "bigint", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "decisions_canvas_idx": { + "name": "decisions_canvas_idx", + "columns": [ + { + "expression": "canvas_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.design_tokens": { + "name": "design_tokens", + "schema": "", + "columns": { + "canvas_id": { + "name": "canvas_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "value": { + "name": "value", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "themes": { + "name": "themes", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "order": { + "name": "order", + "type": "double precision", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "updated_by": { + "name": "updated_by", + "type": "text", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": { + "design_tokens_canvas_id_name_pk": { + "name": "design_tokens_canvas_id_name_pk", + "columns": [ + "canvas_id", + "name" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.feedback": { + "name": "feedback", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "task_id": { + "name": "task_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "canvas_id": { + "name": "canvas_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "agent_name": { + "name": "agent_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "target_agent": { + "name": "target_agent", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "from_name": { + "name": "from_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "from_user_id": { + "name": "from_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "text": { + "name": "text", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "at": { + "name": "at", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "delivered_at": { + "name": "delivered_at", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "claimed_by": { + "name": "claimed_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "claimed_by_resident": { + "name": "claimed_by_resident", + "type": "boolean", + "primaryKey": false, + "notNull": false + }, + "completed_at": { + "name": "completed_at", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "failed_at": { + "name": "failed_at", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "failure_reason": { + "name": "failure_reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "runner": { + "name": "runner", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "reply": { + "name": "reply", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "feedback_canvas_idx": { + "name": "feedback_canvas_idx", + "columns": [ + { + "expression": "canvas_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.fonts": { + "name": "fonts", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "owner_id": { + "name": "owner_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "family": { + "name": "family", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "weight": { + "name": "weight", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "style": { + "name": "style", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "format": { + "name": "format", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "asset_id": { + "name": "asset_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "ext": { + "name": "ext", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "file_name": { + "name": "file_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "size": { + "name": "size", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "uploaded_by": { + "name": "uploaded_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "bigint", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "fonts_workspace_idx": { + "name": "fonts_workspace_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "fonts_owner_idx": { + "name": "fonts_owner_idx", + "columns": [ + { + "expression": "owner_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.frame_versions": { + "name": "frame_versions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "frame_id": { + "name": "frame_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "canvas_id": { + "name": "canvas_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "html": { + "name": "html", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "width": { + "name": "width", + "type": "double precision", + "primaryKey": false, + "notNull": true + }, + "height": { + "name": "height", + "type": "double precision", + "primaryKey": false, + "notNull": true + }, + "saved_at": { + "name": "saved_at", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "saved_by": { + "name": "saved_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "saved_by_kind": { + "name": "saved_by_kind", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "frame_versions_frame_idx": { + "name": "frame_versions_frame_idx", + "columns": [ + { + "expression": "frame_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "frame_versions_canvas_idx": { + "name": "frame_versions_canvas_idx", + "columns": [ + { + "expression": "canvas_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.frames": { + "name": "frames", + "schema": "", + "columns": { + "page_id": { + "name": "page_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "canvas_id": { + "name": "canvas_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "x": { + "name": "x", + "type": "double precision", + "primaryKey": false, + "notNull": true + }, + "y": { + "name": "y", + "type": "double precision", + "primaryKey": false, + "notNull": true + }, + "width": { + "name": "width", + "type": "double precision", + "primaryKey": false, + "notNull": true + }, + "height": { + "name": "height", + "type": "double precision", + "primaryKey": false, + "notNull": true + }, + "html": { + "name": "html", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "updated_by": { + "name": "updated_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "demo": { + "name": "demo", + "type": "boolean", + "primaryKey": false, + "notNull": false + }, + "hidden": { + "name": "hidden", + "type": "boolean", + "primaryKey": false, + "notNull": false + }, + "locked": { + "name": "locked", + "type": "boolean", + "primaryKey": false, + "notNull": false + }, + "z": { + "name": "z", + "type": "double precision", + "primaryKey": false, + "notNull": false + }, + "rotation": { + "name": "rotation", + "type": "double precision", + "primaryKey": false, + "notNull": false + }, + "approval": { + "name": "approval", + "type": "jsonb", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "frames_canvas_idx": { + "name": "frames_canvas_idx", + "columns": [ + { + "expression": "canvas_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.github_connections": { + "name": "github_connections", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "canvas_id": { + "name": "canvas_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "repo": { + "name": "repo", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "branch": { + "name": "branch", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "token": { + "name": "token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "installation_id": { + "name": "installation_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "deploy_url": { + "name": "deploy_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "last_synced_at": { + "name": "last_synced_at", + "type": "bigint", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "github_connections_canvas_idx": { + "name": "github_connections_canvas_idx", + "columns": [ + { + "expression": "canvas_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.guideline_versions": { + "name": "guideline_versions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "canvas_id": { + "name": "canvas_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "markdown": { + "name": "markdown", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "saved_at": { + "name": "saved_at", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "saved_by": { + "name": "saved_by", + "type": "text", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "guideline_versions_doc_idx": { + "name": "guideline_versions_doc_idx", + "columns": [ + { + "expression": "canvas_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.guidelines": { + "name": "guidelines", + "schema": "", + "columns": { + "canvas_id": { + "name": "canvas_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "markdown": { + "name": "markdown", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "updated_by": { + "name": "updated_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "x": { + "name": "x", + "type": "double precision", + "primaryKey": false, + "notNull": false + }, + "y": { + "name": "y", + "type": "double precision", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": { + "guidelines_canvas_id_name_pk": { + "name": "guidelines_canvas_id_name_pk", + "columns": [ + "canvas_id", + "name" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.image_description_prefs": { + "name": "image_description_prefs", + "schema": "", + "columns": { + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "mode": { + "name": "mode", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'account'" + }, + "updated_at": { + "name": "updated_at", + "type": "bigint", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.image_prefs": { + "name": "image_prefs", + "schema": "", + "columns": { + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "model": { + "name": "model", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "bigint", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.instance_settings": { + "name": "instance_settings", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "email_password_signup": { + "name": "email_password_signup", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "sso_auto_redirect": { + "name": "sso_auto_redirect", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "default_workspace_id": { + "name": "default_workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "updated_by": { + "name": "updated_by", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.integrations": { + "name": "integrations", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "provider": { + "name": "provider", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "access_token": { + "name": "access_token", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "expires_at": { + "name": "expires_at", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "account_name": { + "name": "account_name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "accounts": { + "name": "accounts", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "connected_at": { + "name": "connected_at", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "bigint", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "integrations_user_provider_idx": { + "name": "integrations_user_provider_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "provider", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.library_components": { + "name": "library_components", + "schema": "", + "columns": { + "canvas_id": { + "name": "canvas_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "id": { + "name": "id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "template": { + "name": "template", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "css": { + "name": "css", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "raw_css": { + "name": "raw_css", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "head": { + "name": "head", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "props": { + "name": "props", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "slots": { + "name": "slots", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "code": { + "name": "code", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "nested": { + "name": "nested", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "rev": { + "name": "rev", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "published_at": { + "name": "published_at", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "published_by": { + "name": "published_by", + "type": "text", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": { + "library_components_canvas_id_id_pk": { + "name": "library_components_canvas_id_id_pk", + "columns": [ + "canvas_id", + "id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.linear_installations": { + "name": "linear_installations", + "schema": "", + "columns": { + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "app_user_id": { + "name": "app_user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "access_token": { + "name": "access_token", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "refresh_token": { + "name": "refresh_token", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "expires_at": { + "name": "expires_at", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "connected_at": { + "name": "connected_at", + "type": "bigint", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "linear_installations_user_id_unique": { + "name": "linear_installations_user_id_unique", + "nullsNotDistinct": false, + "columns": [ + "user_id" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.linear_oauth_states": { + "name": "linear_oauth_states", + "schema": "", + "columns": { + "hash": { + "name": "hash", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "verifier": { + "name": "verifier", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "expires_at": { + "name": "expires_at", + "type": "bigint", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.linear_sessions": { + "name": "linear_sessions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "issue_id": { + "name": "issue_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "prompt": { + "name": "prompt", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "canvas_id": { + "name": "canvas_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "task_id": { + "name": "task_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "ack_id": { + "name": "ack_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "result_id": { + "name": "result_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "next_attempt_at": { + "name": "next_attempt_at", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "linked": { + "name": "linked", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "acknowledged": { + "name": "acknowledged", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "reported": { + "name": "reported", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "created_at": { + "name": "created_at", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "bigint", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "linear_sessions_status_idx": { + "name": "linear_sessions_status_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.live_activities": { + "name": "live_activities", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "canvas_id": { + "name": "canvas_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "token": { + "name": "token", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "environment": { + "name": "environment", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "expires_at": { + "name": "expires_at", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "last_payload": { + "name": "last_payload", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "last_timestamp": { + "name": "last_timestamp", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "default": 0 + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "live_activities_token_unique": { + "name": "live_activities_token_unique", + "nullsNotDistinct": false, + "columns": [ + "token" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.live_activity_starters": { + "name": "live_activity_starters", + "schema": "", + "columns": { + "token": { + "name": "token", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "environment": { + "name": "environment", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "origin": { + "name": "origin", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "expires_at": { + "name": "expires_at", + "type": "bigint", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.local_agent_preferences": { + "name": "local_agent_preferences", + "schema": "", + "columns": { + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "enabled": { + "name": "enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "model": { + "name": "model", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'default'" + }, + "effort": { + "name": "effort", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.memory_proposals": { + "name": "memory_proposals", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "canvas_id": { + "name": "canvas_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "guide_name": { + "name": "guide_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "guide_title": { + "name": "guide_title", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "rule": { + "name": "rule", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "rationale": { + "name": "rationale", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "based_on": { + "name": "based_on", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "at": { + "name": "at", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "resolved_by": { + "name": "resolved_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "resolved_at": { + "name": "resolved_at", + "type": "bigint", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "memory_proposals_canvas_idx": { + "name": "memory_proposals_canvas_idx", + "columns": [ + { + "expression": "canvas_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.memory_references": { + "name": "memory_references", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "canvas_id": { + "name": "canvas_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "frame_id": { + "name": "frame_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "html": { + "name": "html", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "width": { + "name": "width", + "type": "double precision", + "primaryKey": false, + "notNull": true + }, + "height": { + "name": "height", + "type": "double precision", + "primaryKey": false, + "notNull": true + }, + "pinned_by": { + "name": "pinned_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "pinned_at": { + "name": "pinned_at", + "type": "bigint", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "memory_references_canvas_idx": { + "name": "memory_references_canvas_idx", + "columns": [ + { + "expression": "canvas_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.model_accounts": { + "name": "model_accounts", + "schema": "", + "columns": { + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "enabled": { + "name": "enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "account_id": { + "name": "account_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "plan": { + "name": "plan", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "access_token": { + "name": "access_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "refresh_token": { + "name": "refresh_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "expires_at": { + "name": "expires_at", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "api_key": { + "name": "api_key", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "model": { + "name": "model", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "reasoning_effort": { + "name": "reasoning_effort", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "custom": { + "name": "custom", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "custom_headers": { + "name": "custom_headers", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "connected_at": { + "name": "connected_at", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "bigint", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": { + "model_accounts_user_id_kind_pk": { + "name": "model_accounts_user_id_kind_pk", + "columns": [ + "user_id", + "kind" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.notification_prefs": { + "name": "notification_prefs", + "schema": "", + "columns": { + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "comment_emails": { + "name": "comment_emails", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "updated_at": { + "name": "updated_at", + "type": "bigint", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.resident_usage": { + "name": "resident_usage", + "schema": "", + "columns": { + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "used": { + "name": "used", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "updated_at": { + "name": "updated_at", + "type": "bigint", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.shared_model_account_prefs": { + "name": "shared_model_account_prefs", + "schema": "", + "columns": { + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "model": { + "name": "model", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "reasoning_effort": { + "name": "reasoning_effort", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "enabled": { + "name": "enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "updated_at": { + "name": "updated_at", + "type": "bigint", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "shared_model_account_prefs_kind_idx": { + "name": "shared_model_account_prefs_kind_idx", + "columns": [ + { + "expression": "kind", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "shared_model_account_prefs_user_id_kind_pk": { + "name": "shared_model_account_prefs_user_id_kind_pk", + "columns": [ + "user_id", + "kind" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.shared_model_accounts": { + "name": "shared_model_accounts", + "schema": "", + "columns": { + "kind": { + "name": "kind", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "custom": { + "name": "custom", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "api_key": { + "name": "api_key", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "custom_headers": { + "name": "custom_headers", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "enabled": { + "name": "enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "updated_by": { + "name": "updated_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "bigint", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.skills": { + "name": "skills", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "handle": { + "name": "handle", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "body": { + "name": "body", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "bigint", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "skills_scope_handle_idx": { + "name": "skills_scope_handle_idx", + "columns": [ + { + "expression": "scope", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "handle", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.slack_installations": { + "name": "slack_installations", + "schema": "", + "columns": { + "team_id": { + "name": "team_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "bot_user_id": { + "name": "bot_user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "bot_token": { + "name": "bot_token", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "connected_at": { + "name": "connected_at", + "type": "bigint", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "slack_installations_user_id_unique": { + "name": "slack_installations_user_id_unique", + "nullsNotDistinct": false, + "columns": [ + "user_id" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.slack_oauth_states": { + "name": "slack_oauth_states", + "schema": "", + "columns": { + "hash": { + "name": "hash", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "expires_at": { + "name": "expires_at", + "type": "bigint", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.slack_sessions": { + "name": "slack_sessions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "team_id": { + "name": "team_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "channel_id": { + "name": "channel_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "thread_ts": { + "name": "thread_ts", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "requester_id": { + "name": "requester_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "response_url": { + "name": "response_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "prompt": { + "name": "prompt", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "canvas_id": { + "name": "canvas_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "task_id": { + "name": "task_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "follow_up": { + "name": "follow_up", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "ack_ts": { + "name": "ack_ts", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "next_attempt_at": { + "name": "next_attempt_at", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "acknowledged": { + "name": "acknowledged", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "linked": { + "name": "linked", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "reported": { + "name": "reported", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "created_at": { + "name": "created_at", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "bigint", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "slack_sessions_status_idx": { + "name": "slack_sessions_status_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "slack_sessions_thread_idx": { + "name": "slack_sessions_thread_idx", + "columns": [ + { + "expression": "team_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "channel_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "thread_ts", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.storybook_sources": { + "name": "storybook_sources", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "canvas_id": { + "name": "canvas_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "url": { + "name": "url", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "components": { + "name": "components", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "tokens": { + "name": "tokens", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "last_result": { + "name": "last_result", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "synced_at": { + "name": "synced_at", + "type": "bigint", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "storybook_sources_canvas_url_idx": { + "name": "storybook_sources_canvas_url_idx", + "columns": [ + { + "expression": "canvas_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "url", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.sync_edges": { + "name": "sync_edges", + "schema": "", + "columns": { + "key_id": { + "name": "key_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "from_page": { + "name": "from_page", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "to_page": { + "name": "to_page", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "count": { + "name": "count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "last_at": { + "name": "last_at", + "type": "bigint", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": { + "sync_edges_key_id_from_page_to_page_pk": { + "name": "sync_edges_key_id_from_page_to_page_pk", + "columns": [ + "key_id", + "from_page", + "to_page" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.sync_keys": { + "name": "sync_keys", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "secret": { + "name": "secret", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "canvas_id": { + "name": "canvas_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "last_used_at": { + "name": "last_used_at", + "type": "bigint", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "sync_keys_canvas_idx": { + "name": "sync_keys_canvas_idx", + "columns": [ + { + "expression": "canvas_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "sync_keys_secret_idx": { + "name": "sync_keys_secret_idx", + "columns": [ + { + "expression": "secret", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.sync_links": { + "name": "sync_links", + "schema": "", + "columns": { + "key_id": { + "name": "key_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "page": { + "name": "page", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "to_page": { + "name": "to_page", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "x": { + "name": "x", + "type": "double precision", + "primaryKey": false, + "notNull": true + }, + "y": { + "name": "y", + "type": "double precision", + "primaryKey": false, + "notNull": true + }, + "width": { + "name": "width", + "type": "double precision", + "primaryKey": false, + "notNull": true + }, + "height": { + "name": "height", + "type": "double precision", + "primaryKey": false, + "notNull": true + }, + "label": { + "name": "label", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "sync_links_page_idx": { + "name": "sync_links_page_idx", + "columns": [ + { + "expression": "key_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "page", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.tasks": { + "name": "tasks", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "canvas_id": { + "name": "canvas_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "agent_name": { + "name": "agent_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "agent_key": { + "name": "agent_key", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "owner": { + "name": "owner", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "color": { + "name": "color", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "started_at": { + "name": "started_at", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "ended_at": { + "name": "ended_at", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "auto": { + "name": "auto", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "queued_by": { + "name": "queued_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "claimed_at": { + "name": "claimed_at", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "failed_at": { + "name": "failed_at", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "failure_reason": { + "name": "failure_reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "pipeline": { + "name": "pipeline", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "stage": { + "name": "stage", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "attachments": { + "name": "attachments", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "queued_by_user_id": { + "name": "queued_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "payload": { + "name": "payload", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "frame_ids": { + "name": "frame_ids", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "runner": { + "name": "runner", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "reply": { + "name": "reply", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "tasks_canvas_idx": { + "name": "tasks_canvas_idx", + "columns": [ + { + "expression": "canvas_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.webhooks": { + "name": "webhooks", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "url": { + "name": "url", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "secret": { + "name": "secret", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "events": { + "name": "events", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "enabled": { + "name": "enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "created_at": { + "name": "created_at", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "last_status": { + "name": "last_status", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "last_at": { + "name": "last_at", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "last_error": { + "name": "last_error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "failures": { + "name": "failures", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + } + }, + "indexes": { + "webhooks_user_idx": { + "name": "webhooks_user_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workspace_invites": { + "name": "workspace_invites", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "role": { + "name": "role", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "invited_by": { + "name": "invited_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "bigint", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "workspace_invites_workspace_email_idx": { + "name": "workspace_invites_workspace_email_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "email", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_invites_email_idx": { + "name": "workspace_invites_email_idx", + "columns": [ + { + "expression": "email", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workspace_members": { + "name": "workspace_members", + "schema": "", + "columns": { + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "role": { + "name": "role", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "added_by": { + "name": "added_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "added_at": { + "name": "added_at", + "type": "bigint", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "workspace_members_user_idx": { + "name": "workspace_members_user_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "workspace_members_workspace_id_user_id_pk": { + "name": "workspace_members_workspace_id_user_id_pk", + "columns": [ + "workspace_id", + "user_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workspaces": { + "name": "workspaces", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "owner_id": { + "name": "owner_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'inactive'" + }, + "plan": { + "name": "plan", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "interval": { + "name": "interval", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "seats": { + "name": "seats", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "seats_bought": { + "name": "seats_bought", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "stripe_customer_id": { + "name": "stripe_customer_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "stripe_subscription_id": { + "name": "stripe_subscription_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "current_period_end": { + "name": "current_period_end", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "cancel_at_period_end": { + "name": "cancel_at_period_end", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "billing_event_at": { + "name": "billing_event_at", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "library_publish": { + "name": "library_publish", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "link_sharing": { + "name": "link_sharing", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "bigint", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.account": { + "name": "account", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "account_id": { + "name": "account_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "provider_id": { + "name": "provider_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "access_token": { + "name": "access_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "refresh_token": { + "name": "refresh_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "id_token": { + "name": "id_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "access_token_expires_at": { + "name": "access_token_expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "refresh_token_expires_at": { + "name": "refresh_token_expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "password": { + "name": "password", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "account_user_id_user_id_fk": { + "name": "account_user_id_user_id_fk", + "tableFrom": "account", + "tableTo": "user", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.oauth_access_token": { + "name": "oauth_access_token", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "access_token": { + "name": "access_token", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "refresh_token": { + "name": "refresh_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "access_token_expires_at": { + "name": "access_token_expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "refresh_token_expires_at": { + "name": "refresh_token_expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "scopes": { + "name": "scopes", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "oauth_access_token_access_token_unique": { + "name": "oauth_access_token_access_token_unique", + "nullsNotDistinct": false, + "columns": [ + "access_token" + ] + }, + "oauth_access_token_refresh_token_unique": { + "name": "oauth_access_token_refresh_token_unique", + "nullsNotDistinct": false, + "columns": [ + "refresh_token" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.oauth_application": { + "name": "oauth_application", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "icon": { + "name": "icon", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "metadata": { + "name": "metadata", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "client_secret": { + "name": "client_secret", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "redirect_urls": { + "name": "redirect_urls", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "disabled": { + "name": "disabled", + "type": "boolean", + "primaryKey": false, + "notNull": false, + "default": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "oauth_application_client_id_unique": { + "name": "oauth_application_client_id_unique", + "nullsNotDistinct": false, + "columns": [ + "client_id" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.oauth_consent": { + "name": "oauth_consent", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "scopes": { + "name": "scopes", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "consent_given": { + "name": "consent_given", + "type": "boolean", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.session": { + "name": "session", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "token": { + "name": "token", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "ip_address": { + "name": "ip_address", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "user_agent": { + "name": "user_agent", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "impersonated_by": { + "name": "impersonated_by", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": { + "session_user_id_user_id_fk": { + "name": "session_user_id_user_id_fk", + "tableFrom": "session", + "tableTo": "user", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "session_token_unique": { + "name": "session_token_unique", + "nullsNotDistinct": false, + "columns": [ + "token" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.user": { + "name": "user", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "email_verified": { + "name": "email_verified", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "image": { + "name": "image", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "role": { + "name": "role", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "banned": { + "name": "banned", + "type": "boolean", + "primaryKey": false, + "notNull": false, + "default": false + }, + "ban_reason": { + "name": "ban_reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "ban_expires": { + "name": "ban_expires", + "type": "timestamp", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "user_email_unique": { + "name": "user_email_unique", + "nullsNotDistinct": false, + "columns": [ + "email" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.verification": { + "name": "verification", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "identifier": { + "name": "identifier", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "value": { + "name": "value", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + } + }, + "enums": {}, + "schemas": {}, + "sequences": {}, + "roles": {}, + "policies": {}, + "views": {}, + "_meta": { + "columns": {}, + "schemas": {}, + "tables": {} + } +} \ No newline at end of file diff --git a/server/db/migrations/meta/_journal.json b/server/db/migrations/meta/_journal.json index 33e8f19ee..337a8e882 100644 --- a/server/db/migrations/meta/_journal.json +++ b/server/db/migrations/meta/_journal.json @@ -456,6 +456,13 @@ "when": 1795256886668, "tag": "0065_storybook_sources", "breakpoints": true + }, + { + "idx": 66, + "version": "7", + "when": 1795596622579, + "tag": "0066_shared_model_accounts", + "breakpoints": true } ] -} +} \ No newline at end of file diff --git a/server/db/schema.ts b/server/db/schema.ts index 58a02cd9b..4498b4d43 100644 --- a/server/db/schema.ts +++ b/server/db/schema.ts @@ -871,6 +871,42 @@ export const agentDefaults = pgTable('agent_defaults', { updatedAt: bigint('updated_at', { mode: 'number' }).notNull(), }) +/** A custom provider an instance admin set up for everyone (Admin → Shared + * models): every signed-in person sees it beside their own connections, and + * none of them can read its key or change it. The key and headers are + * sealed like a personal provider's. */ +export const sharedModelAccounts = pgTable('shared_model_accounts', { + /** 'custom:', minted like a personal provider's kind */ + kind: text('kind').primaryKey(), + /** its name, API type, base URL, models and options (shared/customProvider.ts) */ + custom: jsonb('custom').notNull(), + apiKey: sealedText('api_key'), + /** extra request headers, as JSON */ + customHeaders: sealedText('custom_headers'), + /** off takes it away from everyone, keeping its definition */ + enabled: boolean('enabled').notNull().default(true), + createdBy: text('created_by'), + updatedBy: text('updated_by'), + createdAt: bigint('created_at', { mode: 'number' }).notNull(), + updatedAt: bigint('updated_at', { mode: 'number' }).notNull(), +}) + +/** One person's own settings on a shared provider: the model they picked, the + * effort, and whether they switched it off for themselves. No row = the + * provider's first model, on. Removed with the provider. */ +export const sharedModelAccountPrefs = pgTable( + 'shared_model_account_prefs', + { + userId: text('user_id').notNull(), + kind: text('kind').notNull(), + model: text('model'), + reasoningEffort: text('reasoning_effort'), + enabled: boolean('enabled').notNull().default(true), + updatedAt: bigint('updated_at', { mode: 'number' }).notNull(), + }, + (t) => [primaryKey({ columns: [t.userId, t.kind] }), index('shared_model_account_prefs_kind_idx').on(t.kind)], +) + /* The curated background library behind search_backgrounds (server/backgrounds.ts). Bytes live in object storage under bg/.webp and bg/-t.webp; this row is everything the search ranks on. */ diff --git a/server/index.ts b/server/index.ts index 5b2cc44a6..0d62c5f34 100644 --- a/server/index.ts +++ b/server/index.ts @@ -124,16 +124,18 @@ import { serverTierInfo } from './agentModel.ts' import { imageModelAvailability, serverImageGenEnabled } from './imageGen.ts' import { setImagePref } from './imagePrefs.ts' import { accountsView, listRunners, menuFor } from './agentRunners.ts' -import { CustomProviderError, discoverCustomModels, takeProbeSlot, testCustomProvider } from './customProviders.ts' -import { CustomProviderUrlError, customProvidersEnabled, reachableUrl } from './customProviderFetch.ts' import { - isCustomProviderKind, - normalizeBaseUrl, - parseCustomHeaders, - parseCustomKey, - parseCustomProviderConfig, - CUSTOM_API_TYPES, -} from '../shared/customProvider.ts' + CustomProviderError, + customConfig, + customFailure, + customSecrets, + discoverCustomModels, + discoveryEndpoint, + takeProbeSlot, + testCustomProvider, +} from './customProviders.ts' +import { customProvidersEnabled } from './customProviderFetch.ts' +import { isCustomProviderKind } from '../shared/customProvider.ts' import { setStoredDefault } from './agentDefaults.ts' import { isRunnerProvider } from '../shared/agentRunner.ts' import { modelCatalogFor } from './modelCatalog.ts' @@ -1674,51 +1676,18 @@ app.use('/api/custom-providers', (_req, res, next) => { next() }) -/** The key and headers a request carries: a field left out is undefined, so - * an edit keeps the stored one; an empty key clears it. */ -function customSecrets(body: Record): { apiKey?: string; headers?: Record } { - const secrets: { apiKey?: string; headers?: Record } = {} - if (body.apiKey !== undefined) { - const key = parseCustomKey(body.apiKey) - if (!key.ok) throw new CustomProviderError(key.error) - secrets.apiKey = key.value - } - if (body.headers !== undefined) { - const headers = parseCustomHeaders(body.headers) - if (!headers.ok) throw new CustomProviderError(headers.error) - secrets.headers = headers.value - } - return secrets -} - -/** A validated provider description whose URL this server may reach. */ -function customConfig(body: unknown) { - const config = parseCustomProviderConfig(body) - if (!config.ok) throw new CustomProviderError(config.error) - reachableUrl(config.value.baseUrl) - return config.value -} - /** The secrets a set-up request should use: what it carries, else (for a * provider being edited) what is stored for it. */ async function probeSecrets(userId: string, body: Record) { const given = customSecrets(body) - const stored = isCustomProviderKind(body.kind) ? await modelAccounts.getAccount(userId, body.kind) : null + const account = isCustomProviderKind(body.kind) ? await modelAccounts.getAccount(userId, body.kind) : null + /* never a shared provider's: its key would go to whatever URL this request names */ + const stored = account?.shared ? null : account const apiKey = given.apiKey ?? stored?.apiKey const headers = given.headers ?? stored?.headers return { ...(apiKey ? { apiKey } : {}), ...(headers ? { headers } : {}) } } -function customFailure(res: express.Response, error: unknown, fallback: string) { - if (error instanceof CustomProviderError || error instanceof CustomProviderUrlError) { - return res.status(400).json({ error: error.message }) - } - /* the provider's own error text (a 400 body, a refused model) is what the - person needs to fix their endpoint; never a stack */ - const message = error instanceof Error ? error.message.slice(0, 500) : fallback - return res.status(400).json({ error: message || fallback }) -} - app.post('/api/custom-providers', async (req, res) => { try { const body = (req.body ?? {}) as Record @@ -1740,6 +1709,7 @@ app.put('/api/custom-providers/:kind', async (req, res) => { res.json(await accountsView(req.user!.id)) wakeUserWork(req.user!.id) } catch (error) { + if (error instanceof modelAccounts.SharedAccountError) return res.status(403).json({ error: error.message }) customFailure(res, error, 'could not save that provider') } }) @@ -1750,12 +1720,8 @@ app.post('/api/custom-providers/models', async (req, res) => { if (!takeProbeSlot(userId)) return res.status(429).json({ error: 'Too many requests. Wait a few minutes.' }) try { const body = (req.body ?? {}) as Record - const apiType = CUSTOM_API_TYPES.find((type) => type === body.apiType) - if (!apiType) throw new CustomProviderError('Pick the API type') - const baseUrl = normalizeBaseUrl(typeof body.baseUrl === 'string' ? body.baseUrl : '') - if (!baseUrl.ok) throw new CustomProviderError(baseUrl.error) const models = await discoverCustomModels({ - config: { apiType, baseUrl: baseUrl.value }, + config: discoveryEndpoint(body), ...(await probeSecrets(userId, body)), }) res.json({ models }) @@ -1783,7 +1749,13 @@ app.post('/api/custom-providers/test', async (req, res) => { app.delete('/api/model-account/:kind', async (req, res) => { const kind = req.params.kind if (!modelAccounts.isAccountKind(kind)) return res.status(400).json({ error: 'unknown account kind' }) - await modelAccounts.disconnect(req.user!.id, kind) + try { + await modelAccounts.disconnect(req.user!.id, kind) + } catch (error) { + /* a shared provider is the admin's to remove; switching it off is the person's */ + if (error instanceof modelAccounts.SharedAccountError) return res.status(403).json({ error: error.message }) + return res.status(500).json({ error: 'could not disconnect that account' }) + } res.json(await accountsView(req.user!.id)) }) diff --git a/server/modelAccounts.ts b/server/modelAccounts.ts index b9e22810b..66c859d3d 100644 --- a/server/modelAccounts.ts +++ b/server/modelAccounts.ts @@ -29,6 +29,16 @@ import { type CustomProviderKind, } from '../shared/customProvider.ts' import { effortFor, modelFor } from './openaiAgent.ts' +import { + getSharedPref, + getSharedPrefs, + getSharedProvider, + isSharedKind, + listSharedProviders, + saveSharedPref, + type SharedProvider, + type SharedProviderPrefs, +} from './sharedModelAccounts.ts' /** * "Bring your own model": a user connects their ChatGPT subscription (or an @@ -118,6 +128,9 @@ export interface ModelAccount { custom?: CustomProviderConfig /** a custom provider's extra request headers */ headers?: Record + /** an admin's shared provider (sharedModelAccounts.ts): the person picks + * its model and switches it on or off, nothing more */ + shared?: true } /** A custom provider as Settings shows it: the description, which headers @@ -139,6 +152,8 @@ export interface AccountStatus { effort?: string connectedAt: number custom?: CustomProviderStatus + /** set up by an admin for everyone: no edit, no disconnect */ + shared?: true } export function isBuiltinAccountKind(value: unknown): value is BuiltinAccountKind { @@ -220,26 +235,90 @@ function baseAccount(row: typeof modelAccounts.$inferSelect, kind: AccountKind): } } -/** Every account this person connected, switched on or off, oldest first. */ +/** A shared provider as one person has it: the admin's definition with + * their own model, effort and on/off. */ +function sharedAccount(userId: string, provider: SharedProvider, prefs: SharedProviderPrefs | undefined): ModelAccount { + return { + userId, + kind: provider.kind, + ...(provider.apiKey ? { apiKey: provider.apiKey } : {}), + ...(prefs?.model ? { model: prefs.model } : {}), + ...(prefs?.effort ? { effort: prefs.effort } : {}), + enabled: prefs?.enabled ?? true, + connectedAt: provider.createdAt, + custom: provider.custom, + ...(provider.headers ? { headers: provider.headers } : {}), + shared: true, + } +} + +/** The shared providers an admin has switched on, as this person has them; + * none while the operator has custom providers off. */ +async function sharedAccounts(userId: string): Promise { + if (!customProvidersEnabled()) return [] + const [providers, prefs] = await Promise.all([listSharedProviders({ enabledOnly: true }), getSharedPrefs(userId)]) + return providers.map((provider) => sharedAccount(userId, provider, prefs.get(provider.kind))) +} + +/** Every account this person connected, switched on or off, oldest first, + * then the shared providers an admin has on. */ export async function getAccounts(userId: string): Promise { - const rows = await db - .select() - .from(modelAccounts) - .where(eq(modelAccounts.userId, userId)) - .orderBy(asc(modelAccounts.connectedAt)) - return rows.map(toAccount).filter((account): account is ModelAccount => account !== null) + const [rows, shared] = await Promise.all([ + db.select().from(modelAccounts).where(eq(modelAccounts.userId, userId)).orderBy(asc(modelAccounts.connectedAt)), + sharedAccounts(userId), + ]) + const own = rows.map(toAccount).filter((account): account is ModelAccount => account !== null) + return [...own, ...shared] } -/** One provider's account, switched on or off, or null when not connected. */ +/** One provider's account, switched on or off, or null when not connected + * (a shared provider: when an admin has it on). */ export async function getAccount(userId: string, kind: AccountKind): Promise { const [row] = await db .select() .from(modelAccounts) .where(and(eq(modelAccounts.userId, userId), eq(modelAccounts.kind, kind))) - return row ? toAccount(row) : null + if (row) return toAccount(row) + if (!isCustomProviderKind(kind) || !customProvidersEnabled()) return null + const [provider, prefs] = await Promise.all([getSharedProvider(kind), getSharedPref(userId, kind)]) + return provider?.enabled ? sharedAccount(userId, provider, prefs) : null +} + +/** Refused for a shared provider: only an admin edits or removes one. */ +export class SharedAccountError extends Error { + constructor() { + super('that provider is shared by your admin') + } +} + +/** What a person is told about a shared provider's endpoint: its origin. + * The path, the headers and the key are the admin's business. */ +function sharedBaseUrl(baseUrl: string): string { + try { + return new URL(baseUrl).origin + } catch { + return '' + } } export function statusOf(account: ModelAccount): AccountStatus { + if (account.shared && account.custom) { + return { + kind: account.kind, + enabled: account.enabled, + model: accountModelFor(account), + connectedAt: account.connectedAt, + custom: { + name: account.custom.name, + apiType: account.custom.apiType, + baseUrl: sharedBaseUrl(account.custom.baseUrl), + models: account.custom.models, + headerNames: [], + hasKey: Boolean(account.apiKey), + }, + shared: true, + } + } return { kind: account.kind, enabled: account.enabled, @@ -410,9 +489,11 @@ export async function setAccountEnabled(userId: string, kind: AccountKind, enabl * would undo each other; matching the kind keeps a pick validated for one * provider off an account that switched to another meanwhile. */ async function savePick( - account: Pick, + account: Pick, pick: { model: string } | { reasoningEffort: string } | { enabled: boolean }, ): Promise { + /* a shared provider's pick is this person's own row; the definition is the admin's */ + if (account.shared && isCustomProviderKind(account.kind)) return saveSharedPref(account.userId, account.kind, pick) const written = await db .update(modelAccounts) .set({ ...pick, updatedAt: Date.now() }) @@ -462,6 +543,7 @@ async function save(account: Omit): Pro } export async function disconnect(userId: string, kind: AccountKind): Promise { + if (await isSharedKind(kind)) throw new SharedAccountError() await db.delete(modelAccounts).where(and(eq(modelAccounts.userId, userId), eq(modelAccounts.kind, kind))) } @@ -1085,6 +1167,7 @@ export async function updateCustomProvider( config: CustomProviderConfig, secrets: CustomProviderSecrets, ): Promise { + if (await isSharedKind(kind)) throw new SharedAccountError() const written = await db .update(modelAccounts) .set({ diff --git a/server/openaiAgent.ts b/server/openaiAgent.ts index c1d64c3fc..44dd545e1 100644 --- a/server/openaiAgent.ts +++ b/server/openaiAgent.ts @@ -340,8 +340,16 @@ export async function readEventStream(res: Response): Promise { return final.output?.length ? final : { ...final, output: streamed } } -export async function responseError(res: Response, label: string): Promise { - const text = await res.text().catch(() => '') +/** The endpoint's refusal as an error the run can read. `redact` masks + * credentials in the body (a custom provider's, redactSecrets) and runs on + * the whole body before it is cut short, so a key straddling the cut cannot + * leave its first characters behind. */ +export async function responseError( + res: Response, + label: string, + redact: (text: string) => string = (text) => text, +): Promise { + const text = redact(await res.text().catch(() => '')) const detail = text.slice(0, 400) if (res.status === 401 || res.status === 403) { return new ModelAuthError(`${label} rejected the credentials (${res.status}) — reconnect the account`) diff --git a/server/resident.ts b/server/resident.ts index a6972f540..1e46bba21 100644 --- a/server/resident.ts +++ b/server/resident.ts @@ -1143,7 +1143,9 @@ async function runAgent(canvasId: string, agentName: string, stalled: Set + enabled: boolean + createdAt: number + updatedAt: number +} + +/** One person's own settings on a shared provider. */ +export interface SharedProviderPrefs { + model?: string + effort?: ReasoningEffort + enabled: boolean +} + +/** A shared provider as Admin shows it: the description, which headers are + * set and whether there is a key, never their values. */ +export interface SharedProviderStatus { + kind: CustomProviderKind + enabled: boolean + custom: CustomProviderStatus + createdAt: number + updatedAt: number +} + +/* The secrets are read in their stored (sealed) form, around the column's + decoder (a bare `sql` field, as secretBackfill.ts reads them), and opened + per row in toProvider: a key that cannot be opened (its encryption key + rotated out, the value damaged) then takes out its own provider, not every + person's accounts with it. */ +const COLUMNS = { + kind: sharedModelAccounts.kind, + custom: sharedModelAccounts.custom, + apiKey: sql`${sharedModelAccounts.apiKey}`, + customHeaders: sql`${sharedModelAccounts.customHeaders}`, + enabled: sharedModelAccounts.enabled, + createdAt: sharedModelAccounts.createdAt, + updatedAt: sharedModelAccounts.updatedAt, +} + +interface Row { + kind: string + custom: unknown + /** sealed, as stored */ + apiKey: string | null + customHeaders: string | null + enabled: boolean + createdAt: number + updatedAt: number +} + +/** A sealed value opened, or undefined when it cannot be. */ +function opened(stored: string | null): string | null | undefined { + if (!stored) return null + try { + return open(stored) + } catch { + return undefined + } +} + +/** The row re-checked on the way out, as a personal provider's is, so a row + * written by another build can never run half-valid. */ +function toProvider(row: Row): SharedProvider | null { + if (!isCustomProviderKind(row.kind)) { + console.warn(`[doop-agent] ignoring shared provider with unknown kind "${row.kind}"`) + return null + } + const config = parseCustomProviderConfig(row.custom) + if (!config.ok) { + console.warn(`[doop-agent] ignoring shared provider ${row.kind}: ${config.error}`) + return null + } + const apiKey = opened(row.apiKey) + const customHeaders = opened(row.customHeaders) + if (apiKey === undefined || customHeaders === undefined) { + /* the reason only: the error text could quote the stored value */ + console.warn(`[doop-agent] ignoring shared provider ${row.kind}: its key or headers cannot be unsealed`) + return null + } + let stored: unknown = {} + try { + stored = customHeaders ? JSON.parse(customHeaders) : {} + } catch { + stored = undefined + } + const headers = stored === undefined ? null : parseCustomHeaders(stored) + if (!headers?.ok) { + console.warn(`[doop-agent] ignoring shared provider ${row.kind}: unreadable headers`) + return null + } + return { + kind: row.kind, + custom: config.value, + ...(apiKey ? { apiKey } : {}), + ...(Object.keys(headers.value).length ? { headers: headers.value } : {}), + enabled: row.enabled, + createdAt: row.createdAt, + updatedAt: row.updatedAt, + } +} + +/** Every readable shared provider, on or off (or only those on), oldest first. */ +export async function listSharedProviders(options: { enabledOnly?: boolean } = {}): Promise { + const rows = await db + .select(COLUMNS) + .from(sharedModelAccounts) + .where(options.enabledOnly ? eq(sharedModelAccounts.enabled, true) : undefined) + .orderBy(asc(sharedModelAccounts.createdAt)) + return rows.map(toProvider).filter((provider): provider is SharedProvider => provider !== null) +} + +/** One shared provider, on or off, or null when there is none (or it is unreadable). */ +export async function getSharedProvider(kind: string): Promise { + const [row] = await db.select(COLUMNS).from(sharedModelAccounts).where(eq(sharedModelAccounts.kind, kind)) + return row ? toProvider(row) : null +} + +/** Whether this kind names a shared provider at all, readable or not. */ +export async function isSharedKind(kind: string): Promise { + if (!isCustomProviderKind(kind)) return false + const [row] = await db + .select({ kind: sharedModelAccounts.kind }) + .from(sharedModelAccounts) + .where(eq(sharedModelAccounts.kind, kind)) + return !!row +} + +export function sharedStatusOf(provider: SharedProvider): SharedProviderStatus { + return { + kind: provider.kind, + enabled: provider.enabled, + custom: { + ...provider.custom, + headerNames: Object.keys(provider.headers ?? {}), + hasKey: Boolean(provider.apiKey), + }, + createdAt: provider.createdAt, + updatedAt: provider.updatedAt, + } +} + +function headersColumn(headers: Record): string | null { + return Object.keys(headers).length ? JSON.stringify(headers) : null +} + +/** Add a shared provider; its kind is minted here, never taken from the request. */ +export async function createSharedProvider( + adminId: string, + config: CustomProviderConfig, + secrets: CustomProviderSecrets, +): Promise { + const kind: CustomProviderKind = `${CUSTOM_PROVIDER_PREFIX}${randomBytes(9).toString('hex')}` + const now = Date.now() + /* count and insert under one lock, so two admins adding at once cannot + both see room for one more */ + await db.transaction(async (tx) => { + await tx.execute(sql`select pg_advisory_xact_lock(hashtext('shared-model-accounts'))`) + const existing = await tx.select({ kind: sharedModelAccounts.kind }).from(sharedModelAccounts) + if (existing.length >= MAX_CUSTOM_PROVIDERS) { + throw new SharedProviderError(`An instance can share at most ${MAX_CUSTOM_PROVIDERS} custom providers`) + } + await tx.insert(sharedModelAccounts).values({ + kind, + custom: config, + apiKey: secrets.apiKey || null, + customHeaders: secrets.headers ? headersColumn(secrets.headers) : null, + enabled: true, + createdBy: adminId, + updatedBy: adminId, + createdAt: now, + updatedAt: now, + }) + }) + return kind +} + +function originOf(url: string): string | null { + try { + return new URL(url).origin + } catch { + return null + } +} + +/** Why the stored key or headers may not go along with a request for + * `baseUrl`, or null when they may. They only ever go back to the origin + * they were saved for: a request for another origin brings its own (or says + * "none"), so nobody, an admin included, can send them somewhere new. */ +export function movedSecretsRefusal( + stored: { baseUrl: string; hasKey: boolean; hasHeaders: boolean }, + baseUrl: string, + given: CustomProviderSecrets, +): string | null { + const origin = originOf(stored.baseUrl) + if (origin !== null && origin === originOf(baseUrl)) return null + if (stored.hasKey && given.apiKey === undefined) { + return 'The saved key is only sent to the address it was saved for. Enter the key again, or remove it, to use another address.' + } + if (stored.hasHeaders && given.headers === undefined) { + return 'The saved headers are only sent to the address they were saved for. Enter them again, or remove them, to use another address.' + } + return null +} + +/** Change a shared provider's description, and its key or headers only where + * new ones are given: an edit that leaves the key out keeps it, whoever + * changed it in between — as long as the endpoint keeps its origin. People's + * picks stay (a model no longer listed runs on the first one listed). */ +export async function updateSharedProvider( + adminId: string, + kind: CustomProviderKind, + config: CustomProviderConfig, + secrets: CustomProviderSecrets, +): Promise { + await db.transaction(async (tx) => { + /* held for the write, so the origin checked is the origin replaced */ + const [row] = await tx + .select({ custom: COLUMNS.custom, apiKey: COLUMNS.apiKey, customHeaders: COLUMNS.customHeaders }) + .from(sharedModelAccounts) + .where(eq(sharedModelAccounts.kind, kind)) + .for('update') + if (!row) throw new SharedProviderError('That shared provider no longer exists', 404) + const stored = parseCustomProviderConfig(row.custom) + const refusal = movedSecretsRefusal( + { baseUrl: stored.ok ? stored.value.baseUrl : '', hasKey: !!row.apiKey, hasHeaders: !!row.customHeaders }, + config.baseUrl, + secrets, + ) + if (refusal) throw new SharedProviderError(refusal) + await tx + .update(sharedModelAccounts) + .set({ + custom: config, + ...(secrets.apiKey !== undefined ? { apiKey: secrets.apiKey || null } : {}), + ...(secrets.headers !== undefined ? { customHeaders: headersColumn(secrets.headers) } : {}), + updatedBy: adminId, + updatedAt: Date.now(), + }) + .where(eq(sharedModelAccounts.kind, kind)) + }) +} + +/** Switch a shared provider on or off for everyone, keeping its definition. */ +export async function setSharedProviderEnabled( + adminId: string, + kind: CustomProviderKind, + enabled: boolean, +): Promise { + const written = await db + .update(sharedModelAccounts) + .set({ enabled, updatedBy: adminId, updatedAt: Date.now() }) + .where(eq(sharedModelAccounts.kind, kind)) + .returning({ kind: sharedModelAccounts.kind }) + if (!written.length) throw new SharedProviderError('That shared provider no longer exists', 404) +} + +/** Remove a shared provider, and every person's settings on it. */ +export async function deleteSharedProvider(kind: CustomProviderKind): Promise { + return db.transaction(async (tx) => { + const deleted = await tx + .delete(sharedModelAccounts) + .where(eq(sharedModelAccounts.kind, kind)) + .returning({ kind: sharedModelAccounts.kind }) + await tx.delete(sharedModelAccountPrefs).where(eq(sharedModelAccountPrefs.kind, kind)) + return deleted.length > 0 + }) +} + +function prefsOf(row: typeof sharedModelAccountPrefs.$inferSelect): SharedProviderPrefs { + return { + ...(row.model ? { model: row.model } : {}), + ...(isReasoningEffort(row.reasoningEffort) ? { effort: row.reasoningEffort } : {}), + enabled: row.enabled, + } +} + +/** This person's settings on every shared provider they changed anything on. */ +export async function getSharedPrefs(userId: string): Promise> { + const rows = await db.select().from(sharedModelAccountPrefs).where(eq(sharedModelAccountPrefs.userId, userId)) + return new Map(rows.map((row) => [row.kind, prefsOf(row)])) +} + +export async function getSharedPref(userId: string, kind: string): Promise { + const [row] = await db + .select() + .from(sharedModelAccountPrefs) + .where(and(eq(sharedModelAccountPrefs.userId, userId), eq(sharedModelAccountPrefs.kind, kind))) + return row ? prefsOf(row) : undefined +} + +/** Write ONLY the picked setting, and only while the provider still exists: + * the provider row is held for the write, so a delete either lands first + * (and the pick is refused) or after (and takes the pick with it). */ +export async function saveSharedPref( + userId: string, + kind: CustomProviderKind, + pick: { model: string } | { reasoningEffort: string } | { enabled: boolean }, +): Promise { + await db.transaction(async (tx) => { + const [live] = await tx + .select({ kind: sharedModelAccounts.kind }) + .from(sharedModelAccounts) + .where(eq(sharedModelAccounts.kind, kind)) + .for('share') + if (!live) throw new Error('the connected account changed — pick again') + const now = Date.now() + await tx + .insert(sharedModelAccountPrefs) + .values({ userId, kind, ...pick, updatedAt: now }) + .onConflictDoUpdate({ + target: [sharedModelAccountPrefs.userId, sharedModelAccountPrefs.kind], + set: { ...pick, updatedAt: now }, + }) + }) +} diff --git a/shared/agentRunner.ts b/shared/agentRunner.ts index 15d1b2946..92eac9ae5 100644 --- a/shared/agentRunner.ts +++ b/shared/agentRunner.ts @@ -77,6 +77,8 @@ export interface AgentRunner { provider: RunnerProvider /** 'Claude Plan', 'ChatGPT', 'OpenAI'… */ name: string + /** an admin's shared provider, which may share its name with one of the person's own */ + shared?: true email?: string /** the Claude Plan: whether the desktop that runs it is polling right now */ online?: boolean diff --git a/tests/accountDeletion.test.ts b/tests/accountDeletion.test.ts index e07fc7427..6628b35ce 100644 --- a/tests/accountDeletion.test.ts +++ b/tests/accountDeletion.test.ts @@ -4,6 +4,7 @@ const rig = vi.hoisted(() => ({ deleted: [] as string[], workspaces: new Map>(), dbDeletes: 0, + tables: [] as unknown[], })) vi.mock('../server/db/persist.ts', () => { const noop = () => undefined @@ -26,8 +27,9 @@ vi.mock('../server/db/persist.ts', () => { }) vi.mock('../server/db/index.ts', () => ({ db: { - delete: () => ({ + delete: (table: unknown) => ({ where: async () => { + rig.tables.push(table) rig.dbDeletes += 1 }, }), @@ -48,6 +50,7 @@ beforeEach(() => { for (const canvas of store.allCanvases()) store.deleteCanvas(canvas.id) rig.workspaces.clear() rig.dbDeletes = 0 + rig.tables = [] vi.clearAllMocks() }) @@ -70,8 +73,17 @@ it('deletes only the canvases nobody else can reach, and leaves the rest', async expect(rig.workspaces.get('ws1')?.has('alice')).toBe(false) expect(rig.workspaces.get('ws1')?.has('bob')).toBe(true) // Slack and Linear OAuth handoffs, live activity update tokens, push-to-start tokens, - // the person's own custom agents and their changes to the built-in ones, their own skills - expect(rig.dbDeletes).toBe(7) + // their picks on shared model providers, the person's own custom agents and their changes + // to the built-in ones, their own skills + expect(rig.dbDeletes).toBe(8) +}) + +it('forgets the person’s picks on the model providers an admin shares', async () => { + const { sharedModelAccountPrefs, sharedModelAccounts } = await import('../server/db/schema.ts') + await purgeUserData('alice') + expect(rig.tables).toContain(sharedModelAccountPrefs) + /* the providers themselves are the instance's, not the person's */ + expect(rig.tables).not.toContain(sharedModelAccounts) }) it('disconnects the Slack and Linear agents, so no installation outlives its installer', async () => { diff --git a/tests/customProvider.test.ts b/tests/customProvider.test.ts index 91a2b6a25..c77e26222 100644 --- a/tests/customProvider.test.ts +++ b/tests/customProvider.test.ts @@ -10,10 +10,16 @@ import { parseCustomKey, parseCustomProviderConfig, } from '../shared/customProvider.ts' -import { CustomProviderUrlError, customProviderFetch, reachableUrl } from '../server/customProviderFetch.ts' -import { customTurn, withoutImages } from '../server/agentModel.ts' +import { + CustomProviderUrlError, + customProviderFetch, + reachableUrl, + redactSecrets, +} from '../server/customProviderFetch.ts' +import { ModelAuthError, customTurn, withoutImages } from '../server/agentModel.ts' import { discoverCustomModels, takeProbeSlot, testCustomProvider } from '../server/customProviders.ts' import { IMAGE_OMITTED_NOTE } from '../server/chatCompletionsAgent.ts' +import { isInterruptedModelTurn, retryModelTurn } from '../server/modelTurnRetry.ts' import { stubEnv, unstubAllEnvs } from './envStub.ts' /** @@ -105,6 +111,14 @@ describe('the provider description', () => { }) }) +describe('redactSecrets', () => { + it('masks the key and every header value long enough to be one, the longest first', () => { + const secrets = { apiKey: 'sk-abcd1234', headers: { 'X-Tenant': 'abcd', 'X-Flag': '1' } } + expect(redactSecrets('key sk-abcd1234 tenant abcd flag 1', secrets)).toBe('key *** tenant *** flag 1') + expect(redactSecrets('nothing here', {})).toBe('nothing here') + }) +}) + describe('which URLs the server may reach', () => { afterEach(unstubAllEnvs) @@ -233,6 +247,86 @@ describe('a custom provider’s turns', () => { expect(JSON.stringify(request!.body.messages)).not.toContain('iVBORw0KGgo') }) + it('masks a key that straddles where the error text is cut, at either end of the key', async () => { + const KEY = 'sk-straddling-secret-key-0123456789' + const run = customTurn( + { config: { name: 'Acme', apiType: 'openai-chat', baseUrl: `${base}/v1`, models: [] }, apiKey: KEY }, + { id: 'qwen3-coder', vision: true }, + ) + /* responseError keeps 400 characters of the body: the key starts just + before the cut, then ends just after it */ + for (const before of [399, 400 - KEY.length + 1]) { + reply = (_req, res) => { + res.writeHead(400, { 'Content-Type': 'text/plain' }) + res.end(`${'x'.repeat(before)}${KEY} and more`) + } + const failure = await run({ system: [{ text: 'sys' }], tools: [TOOL], messages: [screenshot], maxTokens: 100 }) + .then(() => undefined) + .catch((error: unknown) => error as Error) + /* masked first, then cut: what is left of the mask, and not one character of the key */ + expect(failure!.message).toMatch(/x\*/) + expect(failure!.message).not.toMatch(/sk-|xs$/) + } + }) + + it('keeps what a retry reads: a connection the endpoint drops is retried', async () => { + const KEY = 'sk-acme-secret-key' + let calls = 0 + reply = (req, res) => { + calls++ + /* the first attempt loses its connection mid-request */ + if (calls === 1) return res.socket?.destroy() + json(res, 200, toolCall) + } + const run = customTurn( + { config: { name: 'Acme', apiType: 'openai-chat', baseUrl: `${base}/v1`, models: [] }, apiKey: KEY }, + { id: 'qwen3-coder', vision: true }, + ) + const turn = () => run({ system: [{ text: 'sys' }], tools: [TOOL], messages: [screenshot], maxTokens: 100 }) + /* the redacted failure still reads as an interrupted turn, by its causes' codes only */ + const dropped = await turn() + .then(() => undefined) + .catch((error: unknown) => error) + expect(isInterruptedModelTurn(dropped)).toBe(true) + calls = 0 + const retries: number[] = [] + const result = await retryModelTurn(turn, { isCanceled: () => false, onRetry: (n) => retries.push(n) }) + expect(result.stop_reason).toBe('tool_use') + expect(retries).toEqual([1]) + expect(calls).toBe(2) + }) + + it('masks the key and header values in whatever the endpoint answers back, on either API type', async () => { + const KEY = 'sk-acme-secret-key' + const TENANT = 'tenant-secret-value' + reply = (_req, res) => + json(res, 400, { error: { message: `Invalid params for key ${KEY} (tenant ${TENANT}, region eu)` } }) + const secrets = { apiKey: KEY, headers: { 'X-Tenant': TENANT, 'X-Flag': 'on' } } + for (const apiType of ['openai-chat', 'anthropic'] as const) { + const run = customTurn( + { config: { name: 'Acme', apiType, baseUrl: `${base}/v1`, models: [] }, ...secrets }, + { id: 'qwen3-coder', vision: true }, + ) + const failure = await run({ system: [{ text: 'sys' }], tools: [TOOL], messages: [screenshot], maxTokens: 100 }) + .then(() => undefined) + .catch((error: unknown) => error as Error) + expect(failure).toBeInstanceOf(Error) + expect(failure!.message).toContain('Invalid params for key *** (tenant ***, region eu)') + /* nothing of the original rides along to a log line */ + expect(failure!.cause).toBeUndefined() + expect(JSON.stringify(failure, Object.getOwnPropertyNames(failure))).not.toMatch(/sk-acme-secret|tenant-secret/) + } + /* the class the run reads its failure by is kept */ + reply = (_req, res) => json(res, 401, { error: { message: `bad key ${KEY}` } }) + const run = customTurn( + { config: { name: 'Acme', apiType: 'openai-chat', baseUrl: `${base}/v1`, models: [] }, ...secrets }, + { id: 'qwen3-coder', vision: true }, + ) + await expect( + run({ system: [{ text: 'sys' }], tools: [TOOL], messages: [screenshot], maxTokens: 100 }), + ).rejects.toBeInstanceOf(ModelAuthError) + }) + it('sends no Authorization at all when the endpoint takes no key', async () => { reply = (_req, res) => json(res, 200, toolCall) const run = customTurn( diff --git a/tests/sharedModelAccounts.test.ts b/tests/sharedModelAccounts.test.ts new file mode 100644 index 000000000..5b8d176fc --- /dev/null +++ b/tests/sharedModelAccounts.test.ts @@ -0,0 +1,245 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { stubEnv, unstubAllEnvs } from './envStub.ts' +import type { SharedProvider, SharedProviderPrefs } from '../server/sharedModelAccounts.ts' + +/** + * Shared providers as one person has them: an admin's definition merged with + * that person's own model, effort and on/off (server/modelAccounts.ts), and + * the store underneath (server/sharedModelAccounts.ts) against a stand-in + * database. The HTTP side is in sharedModelProvidersHttp.test.ts. + */ + +const mocks = vi.hoisted(() => ({ + /* the person's own model_accounts rows */ + rows: vi.fn((): unknown[] => []), + providers: [] as SharedProvider[], + prefs: new Map(), + saveSharedPref: vi.fn(async () => {}), + isSharedKind: vi.fn(async (_kind: string) => false), + deleteModelAccount: vi.fn(async () => {}), + preference: vi.fn(async () => ({ enabled: false, model: 'default' })), + stored: vi.fn((): { provider: string }[] => []), +})) + +vi.mock('../server/db/index.ts', () => { + /* every read here is select → from → where (→ orderBy) */ + const where = () => Object.assign(Promise.resolve(mocks.rows()), { orderBy: async () => mocks.rows() }) + return { + db: { + select: () => ({ from: () => ({ where }) }), + delete: () => ({ where: mocks.deleteModelAccount }), + }, + } +}) +vi.mock('../server/agentDefaults.ts', async (importOriginal) => { + const actual = await importOriginal() + return { ...actual, getStoredDefault: async () => undefined } +}) +vi.mock('../server/localAgentPreferences.ts', () => ({ getLocalAgentPreference: mocks.preference })) +vi.mock('../server/sharedModelAccounts.ts', async (importOriginal) => ({ + ...(await importOriginal()), + listSharedProviders: async ({ enabledOnly = false }: { enabledOnly?: boolean } = {}) => + mocks.providers.filter((provider) => !enabledOnly || provider.enabled), + getSharedProvider: async (kind: string) => mocks.providers.find((provider) => provider.kind === kind) ?? null, + getSharedPrefs: async () => mocks.prefs, + getSharedPref: async (_userId: string, kind: string) => mocks.prefs.get(kind), + saveSharedPref: mocks.saveSharedPref, + isSharedKind: mocks.isSharedKind, +})) + +import { + SharedAccountError, + disconnect, + getAccount, + getAccounts, + setAccountEnabled, + setAccountModel, + statusOf, + updateCustomProvider, +} from '../server/modelAccounts.ts' +import { readConnections } from '../server/agentDefaults.ts' +import { listRunners } from '../server/agentRunners.ts' +import { generatorFor } from '../server/imageGen.ts' + +const GATEWAY = 'custom:0123456789abcdef01' +const OLD_GATEWAY = 'custom:fedcba98765432100f' + +const gateway: SharedProvider = { + kind: GATEWAY, + custom: { + name: 'Acme Gateway', + apiType: 'openai-chat', + baseUrl: 'https://llm.acme.example/team/v1', + models: [ + { id: 'qwen3-coder', vision: true }, + { id: 'glm-5', vision: false }, + ], + }, + apiKey: 'sk-shared-never-shown', + headers: { 'X-Tenant': 'design' }, + enabled: true, + createdAt: 10, + updatedAt: 10, +} +const offGateway: SharedProvider = { ...gateway, kind: OLD_GATEWAY, enabled: false, createdAt: 5 } + +/* the person's own Claude key, connected before the provider was shared */ +const claudeRow = { + userId: 'alice', + kind: 'anthropic-key', + enabled: true, + apiKey: 'sk-ant-own', + connectedAt: 1, + updatedAt: 1, +} + +afterEach(() => { + vi.clearAllMocks() + mocks.rows.mockReturnValue([]) + mocks.isSharedKind.mockResolvedValue(false) + mocks.providers = [] + mocks.prefs = new Map() + unstubAllEnvs() +}) + +describe('getAccounts', () => { + it('lists the person’s own accounts first, then the shared ones an admin has on', async () => { + mocks.rows.mockReturnValue([claudeRow]) + mocks.providers = [offGateway, gateway] + const accounts = await getAccounts('alice') + expect(accounts.map((account) => account.kind)).toEqual(['anthropic-key', GATEWAY]) + expect(accounts[1]).toMatchObject({ + userId: 'alice', + kind: GATEWAY, + shared: true, + enabled: true, + apiKey: 'sk-shared-never-shown', + headers: { 'X-Tenant': 'design' }, + custom: { name: 'Acme Gateway' }, + }) + }) + + it('carries the person’s own pick and on/off, and nobody else’s', async () => { + mocks.providers = [gateway] + mocks.prefs = new Map([[GATEWAY, { model: 'glm-5', enabled: false }]]) + expect(await getAccounts('alice')).toMatchObject([{ kind: GATEWAY, model: 'glm-5', enabled: false }]) + /* no row: the first model, on */ + mocks.prefs = new Map() + const [fresh] = await getAccounts('bob') + expect(fresh).toMatchObject({ kind: GATEWAY, enabled: true }) + expect(fresh?.model).toBeUndefined() + expect(statusOf(fresh!).model).toBe('qwen3-coder') + }) + + it('hides every shared provider while the operator has custom providers off', async () => { + stubEnv('DOOP_CUSTOM_PROVIDERS', 'false') + mocks.providers = [gateway] + expect(await getAccounts('alice')).toEqual([]) + expect(await getAccount('alice', GATEWAY)).toBeNull() + }) +}) + +describe('getAccount', () => { + it('resolves a shared kind like a connected one, and a switched-off or deleted one as nothing', async () => { + mocks.providers = [gateway, offGateway] + mocks.prefs = new Map([[GATEWAY, { model: 'glm-5', enabled: true }]]) + expect(await getAccount('alice', GATEWAY)).toMatchObject({ shared: true, model: 'glm-5' }) + expect(await getAccount('alice', OLD_GATEWAY)).toBeNull() + mocks.providers = [] + expect(await getAccount('alice', GATEWAY)).toBeNull() + }) +}) + +describe('a person’s changes on a shared provider', () => { + it('writes the model and on/off to their own settings, checked against the shared models', async () => { + mocks.providers = [gateway] + await setAccountModel('alice', GATEWAY, 'glm-5') + expect(mocks.saveSharedPref).toHaveBeenCalledWith('alice', GATEWAY, { model: 'glm-5' }) + await setAccountEnabled('alice', GATEWAY, false) + expect(mocks.saveSharedPref).toHaveBeenLastCalledWith('alice', GATEWAY, { enabled: false }) + await expect(setAccountModel('alice', GATEWAY, 'gpt-5')).rejects.toThrow('unknown model') + }) + + it('refuses to edit or remove it', async () => { + mocks.isSharedKind.mockResolvedValue(true) + await expect(disconnect('alice', GATEWAY)).rejects.toBeInstanceOf(SharedAccountError) + await expect( + updateCustomProvider('alice', GATEWAY, gateway.custom, { apiKey: 'sk-mine-now' }), + ).rejects.toBeInstanceOf(SharedAccountError) + expect(mocks.deleteModelAccount).not.toHaveBeenCalled() + }) + + it('still disconnects a personal account', async () => { + await disconnect('alice', 'anthropic-key') + expect(mocks.deleteModelAccount).toHaveBeenCalledOnce() + }) +}) + +describe('what the person is told', () => { + it('says it is shared, with the endpoint’s origin only and nothing about its headers', async () => { + mocks.providers = [gateway] + const [account] = await getAccounts('alice') + const status = statusOf(account!) + expect(status).toMatchObject({ + kind: GATEWAY, + shared: true, + custom: { name: 'Acme Gateway', baseUrl: 'https://llm.acme.example', headerNames: [], hasKey: true }, + }) + const text = JSON.stringify(status) + expect(text).not.toContain('sk-shared-never-shown') + expect(text).not.toContain('design') + expect(text).not.toContain('/team/v1') + }) + + it('names a shared runner apart from a personal provider with the same name', async () => { + mocks.rows.mockReturnValue([ + { + userId: 'alice', + kind: 'custom:aaaaaaaaaaaaaaaaaa', + enabled: true, + custom: gateway.custom, + connectedAt: 1, + updatedAt: 1, + }, + ]) + mocks.providers = [gateway] + const { runners } = await listRunners('alice') + expect(runners.map((runner) => [runner.provider, runner.name, runner.shared])).toEqual([ + ['custom:aaaaaaaaaaaaaaaaaa', 'Acme Gateway', undefined], + [GATEWAY, 'Acme Gateway', true], + ]) + }) +}) + +describe('the default connection', () => { + it('is the first shared provider that is on for someone with no connection of their own', async () => { + mocks.providers = [offGateway, gateway] + expect((await readConnections('newcomer')).default).toBe(GATEWAY) + }) + + it('passes over a shared provider the person switched off', async () => { + mocks.providers = [gateway] + mocks.prefs = new Map([[GATEWAY, { enabled: false }]]) + expect((await readConnections('alice')).default).toBeUndefined() + }) + + it('stays the person’s own account when they have one', async () => { + mocks.rows.mockReturnValue([claudeRow]) + mocks.providers = [gateway] + expect((await readConnections('alice')).default).toBe('anthropic-key') + }) +}) + +describe('image generation', () => { + it('bills a shared provider like the person’s own connection: the server’s image keys stay out', async () => { + stubEnv('OPENAI_API_KEY', 'sk-server-paid') + /* nothing connected at all: the server's key draws */ + const server = await generatorFor('newcomer') + expect(server.ok && server.label).toBe('server') + /* only the shared provider, which cannot draw: nothing does */ + mocks.providers = [gateway] + const shared = await generatorFor('alice') + expect(shared.ok).toBe(false) + expect(!shared.ok && shared.reason).toContain('Acme Gateway') + }) +}) diff --git a/tests/sharedModelAccountsStore.test.ts b/tests/sharedModelAccountsStore.test.ts new file mode 100644 index 000000000..5f3feb7aa --- /dev/null +++ b/tests/sharedModelAccountsStore.test.ts @@ -0,0 +1,99 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' + +/** + * The shared provider store (server/sharedModelAccounts.ts) against a + * stand-in database: a row another build wrote is re-checked on the way out + * and skipped when it does not hold, and removing a provider takes every + * person's settings on it along. + */ + +const mocks = vi.hoisted(() => ({ + rows: vi.fn((): unknown[] => []), + deleted: [] as unknown[], +})) + +vi.mock('../server/db/index.ts', () => { + const where = () => Object.assign(Promise.resolve(mocks.rows()), { orderBy: async () => mocks.rows() }) + const tx = { + delete: (table: unknown) => { + mocks.deleted.push(table) + return { where: () => Object.assign(Promise.resolve(), { returning: async () => [{ kind: 'k' }] }) } + }, + } + return { + db: { + select: () => ({ from: () => ({ where }) }), + transaction: async (run: (t: typeof tx) => Promise) => run(tx), + }, + } +}) + +import { deleteSharedProvider, listSharedProviders } from '../server/sharedModelAccounts.ts' +import { sharedModelAccountPrefs, sharedModelAccounts } from '../server/db/schema.ts' + +const KIND = 'custom:0123456789abcdef01' +const row = { + kind: KIND, + custom: { + name: 'Acme Gateway', + apiType: 'openai-chat', + baseUrl: 'https://llm.acme.example/v1', + models: [{ id: 'qwen3-coder', vision: true }], + }, + apiKey: 'sk-shared-never-logged', + customHeaders: JSON.stringify({ 'X-Tenant': 'design' }), + enabled: true, + createdBy: 'admin', + updatedBy: 'admin', + createdAt: 1, + updatedAt: 1, +} + +afterEach(() => { + vi.restoreAllMocks() + mocks.rows.mockReturnValue([]) + mocks.deleted = [] +}) + +describe('listSharedProviders', () => { + it('reads a stored provider back with its key and headers', async () => { + mocks.rows.mockReturnValue([row]) + expect(await listSharedProviders()).toEqual([ + { + kind: KIND, + custom: row.custom, + apiKey: 'sk-shared-never-logged', + headers: { 'X-Tenant': 'design' }, + enabled: true, + createdAt: 1, + updatedAt: 1, + }, + ]) + }) + + it('skips a row that no longer holds, with a warning that carries no secret', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + mocks.rows.mockReturnValue([ + { ...row, kind: 'custom:aaaaaaaaaaaaaaaaaa', custom: { ...row.custom, models: [] } }, + { ...row, kind: 'custom:bbbbbbbbbbbbbbbbbb', customHeaders: '{not json' }, + { ...row, kind: 'custom:cccccccccccccccccc', customHeaders: JSON.stringify({ Host: 'elsewhere' }) }, + { ...row, kind: 'openai-key' }, + /* sealed under an encryption key this server does not have */ + { ...row, kind: 'custom:dddddddddddddddddd', apiKey: 'enc:v1:gone:c2stc2hhcmVkLW5ldmVyLWxvZ2dlZA' }, + row, + ]) + expect((await listSharedProviders()).map((provider) => provider.kind)).toEqual([KIND]) + expect(warn).toHaveBeenCalledTimes(5) + const logged = JSON.stringify(warn.mock.calls) + expect(logged).not.toContain('sk-shared-never-logged') + expect(logged).not.toContain('design') + expect(logged).not.toContain('c2stc2hhcmVkLW5ldmVyLWxvZ2dlZA') + }) +}) + +describe('deleteSharedProvider', () => { + it('removes every person’s settings on it with it', async () => { + expect(await deleteSharedProvider(KIND)).toBe(true) + expect(mocks.deleted).toEqual([sharedModelAccounts, sharedModelAccountPrefs]) + }) +}) diff --git a/tests/sharedModelProvidersHttp.test.ts b/tests/sharedModelProvidersHttp.test.ts new file mode 100644 index 000000000..79748bfd1 --- /dev/null +++ b/tests/sharedModelProvidersHttp.test.ts @@ -0,0 +1,353 @@ +import { afterAll, beforeAll, describe, expect, it } from 'vitest' +import http from 'node:http' +import type { AddressInfo } from 'node:net' +import { Client, startServer, type Server } from './harness' + +/** + * Shared providers end to end: an admin adds a custom provider in Admin → + * Shared models, every person sees it beside their own connections, picks a + * model or switches it off for themselves, and can neither edit, remove nor + * borrow its key. Against a fake OpenAI-compatible endpoint on loopback (which + * needs the operator's private-hosts switch). The key and header values go in + * and never come back out, not even to the admin. + */ + +let server: Server +let boss: Client +let alice: Client +let bob: Client +let endpoint: http.Server +let base = '' +const seen: { url: string; authorization?: string; tenant?: string }[] = [] +/* every response body any test read, checked for the secrets at the end */ +const bodies: string[] = [] + +beforeAll(async () => { + endpoint = http.createServer((req, res) => { + seen.push({ + url: req.url ?? '', + ...(req.headers.authorization ? { authorization: req.headers.authorization } : {}), + ...(typeof req.headers['x-tenant'] === 'string' ? { tenant: req.headers['x-tenant'] } : {}), + }) + req.resume() + req.on('end', () => { + res.writeHead(200, { 'Content-Type': 'application/json' }) + if (req.url?.endsWith('/models')) + return res.end(JSON.stringify({ data: [{ id: 'qwen3-coder' }, { id: 'glm-5' }] })) + res.end( + JSON.stringify({ + choices: [ + { + finish_reason: 'tool_calls', + message: { tool_calls: [{ id: 'c1', function: { name: 'report_ready', arguments: '{"ready":true}' } }] }, + }, + ], + }), + ) + }) + }) + await new Promise((resolve) => endpoint.listen(0, '127.0.0.1', resolve)) + base = `http://127.0.0.1:${(endpoint.address() as AddressInfo).port}/v1` + server = await startServer({ + ANTHROPIC_API_KEY: '', + OPENAI_API_KEY: '', + DATABASE_URL: '', + SMTP_HOST: '', + ADMIN_EMAILS: 'shared-boss@example.test', + DOOP_CUSTOM_PROVIDER_PRIVATE_HOSTS: 'true', + }) + boss = await new Client(server).signUp('shared-boss@example.test', 'Boss') + alice = await new Client(server).signUp('shared-alice@example.test', 'Alice') + bob = await new Client(server).signUp('shared-bob@example.test', 'Bob') +}, 60000) +afterAll(async () => { + await server?.stop() + await new Promise((resolve) => endpoint.close(() => resolve())) +}) + +interface Status { + kind: string + enabled: boolean + model?: string + shared?: true + custom?: { name: string; baseUrl: string; headerNames: string[]; hasKey: boolean; models: { id: string }[] } +} +interface View { + accounts: Status[] + default?: string + menus: Record +} +interface AdminView { + providers: { kind: string; enabled: boolean; custom: NonNullable }[] + customProviders: boolean +} + +const KEY = 'sk-shared-test-never-echoed' +const HEADER = 'tenant-shared-secret-never-echoed' +const KEY_ELSEWHERE = 'sk-shared-elsewhere-never-echoed' +const provider = { + name: 'Acme Gateway', + apiType: 'openai-chat', + models: [ + { id: 'qwen3-coder', vision: true }, + { id: 'glm-5', vision: false }, + ], +} + +async function read(response: Response): Promise { + const text = await response.text() + bodies.push(text) + return JSON.parse(text) as T +} +const view = async (client: Client) => read(await client.get('/api/model-account')) +const sharedOf = (v: View) => v.accounts.find((account) => account.shared) + +let kind = '' + +describe('the admin routes', () => { + it('are not there for anyone else, the way every admin route is not', async () => { + const somewhere = 'custom:0123456789abcdef01' + const attempts = [ + alice.get('/api/admin/shared-providers'), + alice.post('/api/admin/shared-providers', { ...provider, baseUrl: base }), + alice.put(`/api/admin/shared-providers/${somewhere}`, { ...provider, baseUrl: base }), + alice.patch(`/api/admin/shared-providers/${somewhere}`, { enabled: false }), + alice.delete(`/api/admin/shared-providers/${somewhere}`), + alice.post('/api/admin/shared-providers/models', { apiType: 'openai-chat', baseUrl: base }), + alice.post('/api/admin/shared-providers/test', { ...provider, baseUrl: base }), + ] + for (const response of await Promise.all(attempts)) expect(response.status).toBe(404) + /* and nothing reached the endpoint */ + expect(seen).toEqual([]) + }) + + it('start empty', async () => { + expect(await read(await boss.get('/api/admin/shared-providers'))).toEqual({ + providers: [], + customProviders: true, + }) + }) + + it('refuse what does not hold, saying why', async () => { + const bad = await boss.post('/api/admin/shared-providers', { ...provider, baseUrl: base, models: [] }) + expect(bad.status).toBe(400) + expect((await read<{ error: string }>(bad)).error).toContain('at least one model') + expect((await boss.post('/api/admin/shared-providers', { ...provider, baseUrl: 'ftp://x' })).status).toBe(400) + expect( + (await boss.post('/api/admin/shared-providers', { ...provider, baseUrl: base, headers: { Host: 'x' } })).status, + ).toBe(400) + expect((await boss.put('/api/admin/shared-providers/openai-key', { ...provider, baseUrl: base })).status).toBe(400) + const gone = 'custom:fedcba98765432100f' + expect((await boss.put(`/api/admin/shared-providers/${gone}`, { ...provider, baseUrl: base })).status).toBe(404) + expect((await boss.patch(`/api/admin/shared-providers/${gone}`, { enabled: false })).status).toBe(404) + expect((await boss.patch(`/api/admin/shared-providers/${gone}`, { enabled: 'no' })).status).toBe(400) + expect((await boss.delete(`/api/admin/shared-providers/${gone}`)).status).toBe(404) + }) + + it('list an endpoint’s models and test it before anything is saved', async () => { + const listed = await boss.post('/api/admin/shared-providers/models', { + apiType: 'openai-chat', + baseUrl: base, + apiKey: KEY, + }) + expect(await read(listed)).toEqual({ models: ['qwen3-coder', 'glm-5'] }) + expect(seen.at(-1)).toEqual({ url: '/v1/models', authorization: `Bearer ${KEY}` }) + const tested = await boss.post('/api/admin/shared-providers/test', { ...provider, baseUrl: base, apiKey: KEY }) + expect(await read(tested)).toEqual({ ok: true, model: 'qwen3-coder' }) + }) + + it('add a provider, telling even the admin only that a key is set', async () => { + const added = await read( + await boss.post('/api/admin/shared-providers', { + ...provider, + baseUrl: base, + apiKey: KEY, + headers: { 'X-Tenant': HEADER }, + }), + ) + expect(added.providers).toHaveLength(1) + const [shared] = added.providers + expect(shared).toMatchObject({ + enabled: true, + custom: { name: 'Acme Gateway', baseUrl: base, headerNames: ['X-Tenant'], hasKey: true }, + }) + kind = shared!.kind + expect(kind).toMatch(/^custom:[a-f0-9]{18}$/) + }) +}) + +describe('a person', () => { + it('sees it at once, read-only, as the default when they have nothing of their own', async () => { + const v = await view(alice) + expect(v.accounts).toHaveLength(1) + expect(sharedOf(v)).toMatchObject({ + kind, + shared: true, + enabled: true, + model: 'qwen3-coder', + /* the origin only, and nothing about headers */ + custom: { name: 'Acme Gateway', baseUrl: new URL(base).origin, headerNames: [], hasKey: true }, + }) + expect(v.default).toBe(kind) + expect(v.menus[kind]?.map((m) => m.id)).toEqual(['qwen3-coder', 'glm-5']) + const runners = await read<{ runners: { provider: string; shared?: boolean }[]; default?: string }>( + await alice.get('/api/agent-runners'), + ) + expect(runners.runners).toEqual([expect.objectContaining({ provider: kind, name: 'Acme Gateway', shared: true })]) + expect(runners.default).toBe(kind) + /* the company's model carries the agent: the free tier stops counting */ + expect(await read(await alice.get('/api/agent-allowance'))).toMatchObject({ + byoModel: true, + byoName: 'Acme Gateway', + }) + }) + + it('picks a model and switches it off for themselves only', async () => { + expect((await alice.patch(`/api/model-account/${kind}`, { model: 'not-listed' })).status).toBe(400) + expect( + sharedOf(await read(await alice.patch(`/api/model-account/${kind}`, { model: 'glm-5' }))), + ).toMatchObject({ + model: 'glm-5', + }) + expect( + sharedOf(await read(await alice.patch(`/api/model-account/${kind}`, { enabled: false }))), + ).toMatchObject({ enabled: false, model: 'glm-5' }) + /* Bob, and the definition, are untouched */ + expect(sharedOf(await view(bob))).toMatchObject({ enabled: true, model: 'qwen3-coder' }) + const admin = await read(await boss.get('/api/admin/shared-providers')) + expect(admin.providers[0]).toMatchObject({ enabled: true, custom: { models: provider.models } }) + expect((await alice.patch(`/api/model-account/${kind}`, { enabled: true })).status).toBe(200) + }) + + it('makes it the default like any connection', async () => { + const res = await alice.put('/api/agent-runners/default', { provider: kind }) + expect(res.status).toBe(200) + expect((await read(res)).default).toBe(kind) + }) + + it('cannot edit or remove it', async () => { + const removed = await alice.delete(`/api/model-account/${kind}`) + expect(removed.status).toBe(403) + expect(await read(removed)).toEqual({ error: 'that provider is shared by your admin' }) + const edited = await alice.put(`/api/custom-providers/${kind}`, { ...provider, baseUrl: 'https://evil.example/v1' }) + expect(edited.status).toBe(403) + expect(sharedOf(await view(alice))).toMatchObject({ kind, custom: { baseUrl: new URL(base).origin } }) + }) + + it('cannot send its key anywhere through the set-up probes', async () => { + const before = seen.length + const listed = await alice.post('/api/custom-providers/models', { apiType: 'openai-chat', baseUrl: base, kind }) + expect(listed.status).toBe(200) + await alice.post('/api/custom-providers/test', { ...provider, baseUrl: base, kind }) + const probes = seen.slice(before) + expect(probes.length).toBeGreaterThan(0) + for (const probe of probes) { + expect(probe.authorization).toBeUndefined() + expect(probe.tenant).toBeUndefined() + } + }) + + it('keeps a personal provider of the same name apart from the shared one', async () => { + const own = await read( + await bob.post('/api/custom-providers', { ...provider, baseUrl: base, apiKey: 'sk-bob-own-key' }), + ) + const customs = own.accounts.filter((account) => account.kind.startsWith('custom:')) + expect(customs.map((account) => [account.custom?.name, account.shared ?? false])).toEqual([ + ['Acme Gateway', false], + ['Acme Gateway', true], + ]) + expect(new Set(customs.map((account) => account.kind)).size).toBe(2) + /* his own one, connected by him, is the default now */ + expect(own.default).toBe(customs[0]?.kind) + }) +}) + +describe('the admin, again', () => { + it('edits it without the key, which keeps the key', async () => { + const edited = await read( + await boss.put(`/api/admin/shared-providers/${kind}`, { ...provider, name: 'Acme Gateway (EU)', baseUrl: base }), + ) + expect(edited.providers[0]?.custom).toMatchObject({ + name: 'Acme Gateway (EU)', + hasKey: true, + headerNames: ['X-Tenant'], + }) + /* the stored key and headers still reach the endpoint */ + await boss.post('/api/admin/shared-providers/models', { apiType: 'openai-chat', baseUrl: base, kind }) + expect(seen.at(-1)).toEqual({ url: '/v1/models', authorization: `Bearer ${KEY}`, tenant: HEADER }) + expect(sharedOf(await view(alice))?.custom?.name).toBe('Acme Gateway (EU)') + }) + + it('never sends the saved key or headers to another address', async () => { + /* the same endpoint under another origin: reachable, and not where they were saved for */ + const elsewhere = base.replace('127.0.0.1', 'localhost') + const before = seen.length + const probe = await boss.post('/api/admin/shared-providers/models', { + apiType: 'openai-chat', + baseUrl: elsewhere, + kind, + }) + expect(probe.status).toBe(400) + expect((await read<{ error: string }>(probe)).error).toContain('saved key is only sent') + const tested = await boss.post('/api/admin/shared-providers/test', { ...provider, baseUrl: elsewhere, kind }) + expect(tested.status).toBe(400) + expect(seen.length).toBe(before) + + const moved = await boss.put(`/api/admin/shared-providers/${kind}`, { ...provider, baseUrl: elsewhere }) + expect(moved.status).toBe(400) + expect((await read<{ error: string }>(moved)).error).toContain('saved key is only sent') + /* the key alone is not enough while the headers would still go along */ + const keyOnly = await boss.put(`/api/admin/shared-providers/${kind}`, { + ...provider, + baseUrl: elsewhere, + apiKey: KEY_ELSEWHERE, + }) + expect(keyOnly.status).toBe(400) + expect((await read<{ error: string }>(keyOnly)).error).toContain('saved headers are only sent') + const unchanged = await read(await boss.get('/api/admin/shared-providers')) + expect(unchanged.providers[0]?.custom).toMatchObject({ baseUrl: base, hasKey: true, headerNames: ['X-Tenant'] }) + + /* a move that brings its own key and says "no headers" goes through */ + const moving = await read( + await boss.put(`/api/admin/shared-providers/${kind}`, { + ...provider, + baseUrl: elsewhere, + apiKey: KEY_ELSEWHERE, + headers: {}, + }), + ) + expect(moving.providers[0]?.custom).toMatchObject({ baseUrl: elsewhere, hasKey: true, headerNames: [] }) + await boss.post('/api/admin/shared-providers/models', { apiType: 'openai-chat', baseUrl: elsewhere, kind }) + expect(seen.at(-1)).toEqual({ url: '/v1/models', authorization: `Bearer ${KEY_ELSEWHERE}` }) + }) + + it('switches it off, and it is gone for everyone until it is back on, picks kept', async () => { + expect((await boss.patch(`/api/admin/shared-providers/${kind}`, { enabled: false })).status).toBe(200) + const v = await view(alice) + expect(sharedOf(v)).toBeUndefined() + expect(v.default).toBeUndefined() + expect((await alice.patch(`/api/model-account/${kind}`, { model: 'qwen3-coder' })).status).toBe(400) + expect((await read<{ runners: unknown[] }>(await alice.get('/api/agent-runners'))).runners).toEqual([]) + expect(await read(await alice.get('/api/agent-allowance'))).toMatchObject({ byoModel: false }) + + expect((await boss.patch(`/api/admin/shared-providers/${kind}`, { enabled: true })).status).toBe(200) + expect(sharedOf(await view(alice))).toMatchObject({ kind, model: 'glm-5' }) + }) + + it('removes it for everyone', async () => { + const removed = await read(await boss.delete(`/api/admin/shared-providers/${kind}`)) + expect(removed.providers).toEqual([]) + expect(sharedOf(await view(alice))).toBeUndefined() + expect(sharedOf(await view(bob))).toBeUndefined() + expect((await alice.patch(`/api/model-account/${kind}`, { enabled: true })).status).toBe(400) + }) +}) + +it('never sent the key or a header value back in any response', () => { + expect(bodies.length).toBeGreaterThan(20) + for (const body of bodies) { + expect(body).not.toContain(KEY) + expect(body).not.toContain(KEY_ELSEWHERE) + expect(body).not.toContain(HEADER) + } +}) diff --git a/tests/sharedModelProvidersSealed.test.ts b/tests/sharedModelProvidersSealed.test.ts new file mode 100644 index 000000000..c1e4fc1a7 --- /dev/null +++ b/tests/sharedModelProvidersSealed.test.ts @@ -0,0 +1,72 @@ +import { afterAll, beforeAll, expect, it } from 'vitest' +import { Client, startServer, type Server } from './harness' + +/** + * A shared provider whose key can no longer be unsealed (its encryption key + * rotated out of SECRETS_ENCRYPTION_KEYS, or the value damaged) is skipped on + * its own: everyone's other connections, and the admin's list, keep working. + * The server is rebooted on the same database under a different key. + */ + +const KEY_A = `a:${Buffer.alloc(32, 1).toString('base64')}` +const KEY_B = `b:${Buffer.alloc(32, 2).toString('base64')}` +const ENV = { + ANTHROPIC_API_KEY: '', + OPENAI_API_KEY: '', + DATABASE_URL: '', + SMTP_HOST: '', + ADMIN_EMAILS: 'sealed-boss@example.test', +} +const provider = { + apiType: 'openai-chat', + baseUrl: 'https://llm.acme.example/v1', + models: [{ id: 'qwen3-coder', vision: false }], +} + +let server: Server +let boss: Client +let alice: Client + +beforeAll(async () => { + const first = await startServer({ ...ENV, SECRETS_ENCRYPTION_KEYS: KEY_A }) + boss = await new Client(first).signUp('sealed-boss@example.test', 'Boss') + alice = await new Client(first).signUp('sealed-alice@example.test', 'Alice') + /* sealed under key A, which the reboot below no longer has */ + expect( + (await boss.post('/api/admin/shared-providers', { ...provider, name: 'Old Gateway', apiKey: 'sk-sealed-under-a' })) + .status, + ).toBe(200) + /* a personal provider with nothing sealed in it */ + expect((await alice.post('/api/custom-providers', { ...provider, name: 'Alice’s own' })).status).toBe(200) + first.stop({ keepData: true }) + server = await startServer({ ...ENV, SECRETS_ENCRYPTION_KEYS: KEY_B }, first.dataDir) + for (const client of [boss, alice]) { + await client.post('/api/auth/sign-in/email', { + email: client === boss ? 'sealed-boss@example.test' : 'sealed-alice@example.test', + password: 'password12345', + }) + } +}, 90_000) +afterAll(() => server?.stop()) + +it('skips only the provider whose key cannot be unsealed', async () => { + const added = await boss.post('/api/admin/shared-providers', { + ...provider, + name: 'New Gateway', + apiKey: 'sk-sealed-under-b', + }) + expect(added.status).toBe(200) + const admin = (await (await boss.get('/api/admin/shared-providers')).json()) as { + providers: { custom: { name: string } }[] + } + expect(admin.providers.map((p) => p.custom.name)).toEqual(['New Gateway']) + + const view = (await (await alice.get('/api/model-account')).json()) as { + accounts: { custom?: { name: string }; shared?: true }[] + } + expect(view.accounts.map((a) => [a.custom?.name, a.shared ?? false])).toEqual([ + ['Alice’s own', false], + ['New Gateway', true], + ]) + expect((await alice.get('/api/agent-runners')).status).toBe(200) +}) From 9f03dce346250c035ea69f2d059789fa44e24381 Mon Sep 17 00:00:00 2001 From: gganebnyi Date: Mon, 23 Nov 2026 11:28:51 +0200 Subject: [PATCH 2/6] feat(admin): shared models in Admin, and the shared badge in Settings MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Admin → Shared models lists each shared provider (name, API type, host, model count, whether a key is set) with an on/off switch, Edit and Remove, and empty, loading, error and switched-off states. Adding and editing open the custom provider form in admin mode: the same fields, Fetch models and Test, through the admin routes; the key is never shown and blank keeps it. In Settings → Doop Agent a shared provider is a connection row with a "Shared by your admin" badge: its model, switch and Make default work; Edit provider and Disconnect are not offered. The composer names a shared runner "Name (shared)" so it reads apart from a personal provider of the same name. Strings in en and pt-BR. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01ABWHJg7QHZpRjDADALswQZ --- src/components/ConnectionTable.tsx | 22 ++- src/components/CustomProviderForm.tsx | 40 +++-- src/components/ModelAccount.tsx | 19 +- src/components/ModelPicker.tsx | 9 +- src/components/SharedProviderSettings.tsx | 200 ++++++++++++++++++++++ src/lib/api.ts | 42 +++++ src/lib/i18n/en/admin.ts | 21 +++ src/lib/i18n/en/models.ts | 6 + src/lib/i18n/pt-BR/admin.ts | 21 +++ src/lib/i18n/pt-BR/models.ts | 6 + src/pages/Admin.tsx | 17 +- tests/customProviderForm.test.tsx | 44 ++++- tests/sharedProviderRow.test.tsx | 94 ++++++++++ 13 files changed, 516 insertions(+), 25 deletions(-) create mode 100644 src/components/SharedProviderSettings.tsx create mode 100644 tests/sharedProviderRow.test.tsx diff --git a/src/components/ConnectionTable.tsx b/src/components/ConnectionTable.tsx index 57c06790d..e8c373732 100644 --- a/src/components/ConnectionTable.tsx +++ b/src/components/ConnectionTable.tsx @@ -87,6 +87,7 @@ export function ConnectionRow({ onMakeDefault, onDisconnect, menuItems = [], + badge, panel, error, }: { @@ -101,9 +102,12 @@ export function ConnectionRow({ model: ReactNode onToggle: (on: boolean) => void onMakeDefault?: () => void - onDisconnect: () => void + /** unset for a connection the person cannot remove (an admin's shared one) */ + onDisconnect?: () => void /** the provider's own actions, between Make default and Disconnect */ menuItems?: { label: string; onSelect: () => void }[] + /** one more badge after the name: where the connection comes from */ + badge?: ReactNode /** what opens under the row: a key to replace, a task under way */ panel?: ReactNode /** why the last change to this connection failed, shown under it */ @@ -122,6 +126,7 @@ export function ConnectionRow({ sub={sub} badges={ <> + {badge} {isDefault && {t('models.isDefault')}} {off && {t('models.off')}} @@ -154,10 +159,17 @@ export function ConnectionRow({ {item.label} ))} - - - {t('models.disconnect')} - + {onDisconnect && ( + <> + + + {t('models.disconnect')} + + + )} diff --git a/src/components/CustomProviderForm.tsx b/src/components/CustomProviderForm.tsx index 2d41405c8..5e6779d77 100644 --- a/src/components/CustomProviderForm.tsx +++ b/src/components/CustomProviderForm.tsx @@ -1,6 +1,6 @@ import { useId, useState } from 'react' -import { api } from '../lib/api' -import type { CustomProviderInput, ModelAccounts, ModelAccountStatus } from '../lib/api' +import { adminApi, api } from '../lib/api' +import type { AdminSharedProviders, CustomProviderInput, ModelAccounts, ModelAccountStatus } from '../lib/api' import { useT } from '../lib/i18n' import { headersFromText, @@ -31,6 +31,9 @@ import { FieldError } from './ConnectionTable' * * On an edit the stored key and headers are never shown: blank fields keep * them, and each has its own Remove. + * + * Admin → Shared models opens the same form in admin mode: the same fields, + * saved and probed through the admin routes, for a provider everyone gets. */ interface ModelRow { @@ -48,16 +51,21 @@ const row = (id = '', vision = false, maxOutputTokens = ''): ModelRow => ({ vision, }) +/** Where the form saves and probes: the person's own providers, or (admin) + * the instance's shared ones. */ +type FormMode = + | { admin?: false; onSaved: (view: ModelAccounts) => void } + | { admin: true; onSaved: (view: AdminSharedProviders) => void } + export function CustomProviderForm({ provider, - onSaved, onClose, + ...mode }: { /** the provider being edited; a new one when unset */ - provider?: ModelAccountStatus - onSaved: (view: ModelAccounts) => void + provider?: Pick onClose: () => void -}) { +} & FormMode) { const t = useT() const ids = useId() const stored = provider?.custom @@ -139,7 +147,11 @@ export function CustomProviderForm({ if (!body) return setBusy('save') try { - onSaved(kind ? await api.updateCustomProvider(kind, body) : await api.addCustomProvider(body)) + if (mode.admin) { + mode.onSaved(kind ? await adminApi.updateSharedProvider(kind, body) : await adminApi.addSharedProvider(body)) + } else { + mode.onSaved(kind ? await api.updateCustomProvider(kind, body) : await api.addCustomProvider(body)) + } } catch (e) { failWith(e) } finally { @@ -151,7 +163,8 @@ export function CustomProviderForm({ setError('') setBusy('fetch') try { - const { models: listed } = await api.discoverCustomModels({ apiType, baseUrl, ...probeSecrets() }) + const discover = mode.admin ? adminApi.discoverSharedModels : api.discoverCustomModels + const { models: listed } = await discover({ apiType, baseUrl, ...probeSecrets() }) setDiscovered(listed) if (!listed.length) setError(t('models.customNoModelsListed')) } catch (e) { @@ -169,7 +182,8 @@ export function CustomProviderForm({ if (!body || !first) return setBusy('test') try { - const result = await api.testCustomProvider({ ...body, ...probeSecrets(), model: first.id }) + const probe = mode.admin ? adminApi.testSharedProvider : api.testCustomProvider + const result = await probe({ ...body, ...probeSecrets(), model: first.id }) setTested(t('models.customTestPassed', { model: result.model })) } catch (e) { failWith(e) @@ -192,9 +206,13 @@ export function CustomProviderForm({ return ( - {kind ? t('models.customEditTitle', { name: stored?.name ?? '' }) : t('models.customTitle')} + {kind + ? t('models.customEditTitle', { name: stored?.name ?? '' }) + : mode.admin + ? t('models.customSharedTitle') + : t('models.customTitle')} - {t('models.customLede')} + {mode.admin ? t('models.customSharedLede') : t('models.customLede')}
diff --git a/src/components/ModelAccount.tsx b/src/components/ModelAccount.tsx index 437dd9ef6..f0df1678c 100644 --- a/src/components/ModelAccount.tsx +++ b/src/components/ModelAccount.tsx @@ -17,6 +17,7 @@ import { Button } from './ui/button' import { Input } from './ui/input' import { Modal, ModalActions, ModalLede, ModalTitle } from './ui/modal' import { Dot } from './ui/dot' +import { Badge } from './ui/badge' import { isReasoningEffort, reasoningEffortOptions, type ReasoningEffort } from '../../shared/modelMenu' import { t as translate, useT, type PlainMessageKey } from '../lib/i18n' import { cn } from '@/lib/utils' @@ -657,11 +658,14 @@ export function ModelAccountPanel({ onChange }: { onChange?: () => void }) { setWaiting(false) } - /* every custom provider is a connection of its own, named by its person */ + /* every custom provider is a connection of its own, named by its person; + an admin's shared one is the person's to pick a model on and switch off, + never to edit or remove */ const customEntries: Entry[] = view.accounts.flatMap((account) => { const kind = account.kind if (!isCustomProviderKind(kind) || !account.custom) return [] const { name } = account.custom + const shared = account.shared === true return [ { connected: true, @@ -677,8 +681,12 @@ export function ModelAccountPanel({ onChange }: { onChange?: () => void }) { model={modelCell(kind, name)} onToggle={(on) => void toggle(kind, on)} onMakeDefault={() => void makeDefault(kind)} - onDisconnect={() => void remove(kind)} - menuItems={[{ label: t('models.customEdit'), onSelect: () => setCustomForm(kind) }]} + {...(shared + ? { badge: {t('models.sharedBadge')} } + : { + onDisconnect: () => void remove(kind), + menuItems: [{ label: t('models.customEdit'), onSelect: () => setCustomForm(kind) }], + })} error={errorFor(kind)} /> ), @@ -686,6 +694,7 @@ export function ModelAccountPanel({ onChange }: { onChange?: () => void }) { ] }) const editing = customForm && customForm !== 'new' ? accountOf(customForm) : undefined + const editable = editing && !editing.shared ? editing : undefined /* the Plan is connected when this desktop may run it */ /* in a browser the Plan is connected once it is on: work started here runs @@ -853,9 +862,9 @@ export function ModelAccountPanel({ onChange }: { onChange?: () => void }) { {error}

)} - {customForm && (customForm === 'new' || editing) && ( + {customForm && (customForm === 'new' || editable) && ( setCustomForm(null)} onSaved={(next) => { const added = customForm === 'new' diff --git a/src/components/ModelPicker.tsx b/src/components/ModelPicker.tsx index 251008730..ed39047b3 100644 --- a/src/components/ModelPicker.tsx +++ b/src/components/ModelPicker.tsx @@ -138,9 +138,14 @@ export function ModelPicker({ disabled = false }: { disabled?: boolean }) { <> {runners.runners.map((runner) => ( - {/* one connection needs no name; several are told apart by theirs */} + {/* one connection needs no name; several are told apart by theirs, + and an admin's shared one by saying so (it may share a name) */} - {runners.runners.length > 1 ? runner.name : t('models.model')} + {runners.runners.length > 1 + ? runner.shared + ? t('models.sharedRunnerName', { name: runner.name }) + : runner.name + : t('models.model')} (null) + const [failed, setFailed] = useState(false) + const [error, setError] = useState(null) + const [busy, setBusy] = useState(false) + /* the form: adding one, or editing the one named */ + const [form, setForm] = useState<'new' | CustomProviderKind | null>(null) + const [confirmDelete, setConfirmDelete] = useState(null) + + /* the list loads once; every change answers with the new list */ + const load = () => + adminApi + .sharedProviders() + .then((next) => { + setView(next) + setFailed(false) + }) + .catch(() => setFailed(true)) + + useEffect(() => { + void load() + }, []) + + async function change(request: () => Promise) { + setBusy(true) + setError(null) + try { + setView(await request()) + } catch (e) { + const body = (e as { body?: { error?: unknown } })?.body + setError(typeof body?.error === 'string' && body.error ? body.error : t('admin.saveFailed')) + } finally { + setBusy(false) + } + } + + if (failed) { + return ( +
+

{t('admin.sharedLoadFailed')}

+ +
+ ) + } + if (!view) return

{t('admin.loading')}

+ + const editing = form && form !== 'new' ? view.providers.find((p) => p.kind === form) : undefined + const available = view.customProviders + + return ( +
+ {!available && {t('admin.sharedOff')}} + {error && {error}} + + +
+ {t('admin.sharedTitle')} + {t('admin.sharedDescription')} +
+ {available && ( + + )} +
+ {view.providers.length === 0 ? ( + + {t('admin.sharedEmpty')} + + ) : ( + view.providers.map((provider) => ( + void change(() => adminApi.setSharedProviderEnabled(provider.kind, enabled))} + onEdit={() => setForm(provider.kind)} + onDelete={() => setConfirmDelete(provider)} + /> + )) + )} +
+ + {form && (form === 'new' || editing) && ( + setForm(null)} + onSaved={(next) => { + setView(next) + setError(null) + setForm(null) + }} + /> + )} + !open && setConfirmDelete(null)} + title={t('admin.sharedDeleteTitle', { name: confirmDelete?.custom.name ?? '' })} + description={t('admin.sharedDeleteDescription')} + confirmLabel={t('admin.sharedDelete')} + destructive + onConfirm={() => { + const target = confirmDelete + setConfirmDelete(null) + if (target) void change(() => adminApi.deleteSharedProvider(target.kind)) + }} + /> +
+ ) +} + +/** A custom provider's line: the host it talks to. */ +function hostOf(baseUrl: string): string { + try { + return new URL(baseUrl).host + } catch { + return baseUrl + } +} + +function ProviderRow({ + provider, + busy, + onToggle, + onEdit, + onDelete, +}: { + provider: AdminSharedProvider + busy: boolean + onToggle: (enabled: boolean) => void + onEdit: () => void + onDelete: () => void +}) { + const t = useT() + const { custom } = provider + const id = `shared-${provider.kind.replace(/[^a-z0-9]/gi, '-')}` + return ( + + {custom.name} + {!provider.enabled && {t('models.off')}} + + } + action={ + <> + + + + + } + > + + {custom.apiType === 'anthropic' ? t('models.customApiAnthropic') : t('models.customApiOpenai')} + · + + {hostOf(custom.baseUrl)} + + · + {t('admin.sharedModelCount', { count: custom.models.length })} + · + {custom.hasKey ? t('admin.sharedKeySet') : t('admin.sharedNoKey')} + + + ) +} diff --git a/src/lib/api.ts b/src/lib/api.ts index 0d02bd492..b0a81166a 100644 --- a/src/lib/api.ts +++ b/src/lib/api.ts @@ -339,6 +339,9 @@ export interface ModelAccountStatus { connectedAt: number /** a custom provider's description: never its key or header values */ custom?: CustomProviderStatus + /** an admin's shared provider: its model and on/off are the person's, + * nothing else (no edit, no disconnect); `custom.baseUrl` is its origin */ + shared?: true } export interface CustomProviderStatus extends CustomProviderConfig { @@ -1085,6 +1088,22 @@ export interface AdminInstanceSettings { ssoAdminSignedIn: boolean } +/** Admin → Shared models: one provider everyone sees, never its key or + * header values. */ +export interface AdminSharedProvider { + kind: CustomProviderKind + enabled: boolean + custom: CustomProviderStatus + createdAt: number + updatedAt: number +} + +export interface AdminSharedProviders { + providers: AdminSharedProvider[] + /** false when the operator has switched custom providers off (nobody sees these then) */ + customProviders: boolean +} + /** Instance-admin surface. Every route 404s for non-admins, so a failure here * is indistinguishable from the feature not existing — which is the point. */ export const adminApi = { @@ -1092,6 +1111,29 @@ export const adminApi = { instanceSettings: () => req('/api/admin/instance-settings'), updateInstanceSettings: (patch: InstanceSettingsPatch) => req('/api/admin/instance-settings', { method: 'PATCH', body: JSON.stringify(patch) }), + sharedProviders: () => req('/api/admin/shared-providers'), + addSharedProvider: (input: CustomProviderInput) => + req('/api/admin/shared-providers', { method: 'POST', body: JSON.stringify(input) }), + updateSharedProvider: (kind: CustomProviderKind, input: CustomProviderInput) => + req(`/api/admin/shared-providers/${encodeURIComponent(kind)}`, { + method: 'PUT', + body: JSON.stringify(input), + }), + setSharedProviderEnabled: (kind: CustomProviderKind, enabled: boolean) => + req(`/api/admin/shared-providers/${encodeURIComponent(kind)}`, { + method: 'PATCH', + body: JSON.stringify({ enabled }), + }), + deleteSharedProvider: (kind: CustomProviderKind) => + req(`/api/admin/shared-providers/${encodeURIComponent(kind)}`, { method: 'DELETE' }), + /** as api.discoverCustomModels, with a shared provider's stored key for `kind` */ + discoverSharedModels: (input: Parameters[0]) => + req<{ models: string[] }>('/api/admin/shared-providers/models', { method: 'POST', body: JSON.stringify(input) }), + testSharedProvider: (input: CustomProviderInput & { model: string; kind?: CustomProviderKind }) => + req<{ ok: true; model: string }>('/api/admin/shared-providers/test', { + method: 'POST', + body: JSON.stringify(input), + }), stats: () => req('/api/admin/stats'), users: () => req('/api/admin/users'), agentFeedback: (query: { kind?: AgentFeedbackKind; q?: string; before?: AdminAgentFeedback }) => { diff --git a/src/lib/i18n/en/admin.ts b/src/lib/i18n/en/admin.ts index defe6b591..65aeff267 100644 --- a/src/lib/i18n/en/admin.ts +++ b/src/lib/i18n/en/admin.ts @@ -89,4 +89,25 @@ export const admin = { refusalWorkspaceNotFound: 'That workspace no longer exists.', refusalInvalid: 'That change was not understood.', saveFailed: 'Could not save — try again.', + + sharedNav: 'Shared models', + sharedTab: 'Models', + sharedLoadFailed: 'Could not load the shared providers.', + sharedTitle: 'Shared model providers', + sharedDescription: + 'Custom providers everyone on this instance gets beside their own connections: they pick a model or switch one off for themselves, and never see its key or settings. Someone with no connection of their own runs on the first one that is on.', + sharedAdd: 'Add provider', + sharedEmpty: + 'No shared providers yet. Add your gateway (LiteLLM, vLLM, Ollama…) once and nobody has to paste its key.', + sharedOff: + 'Custom providers are switched off on this server (DOOP_CUSTOM_PROVIDERS=false), so nobody sees these until it is turned back on.', + sharedUse: 'Share {name} with everyone', + sharedEdit: 'Edit', + sharedDelete: 'Remove', + sharedDeleteTitle: 'Remove {name}?', + sharedDeleteDescription: + 'It disappears for everyone at once, with each person’s model pick on it. To take it away for now, switch it off instead.', + sharedModelCount: { one: '{count} model', other: '{count} models' }, + sharedKeySet: 'key set', + sharedNoKey: 'no key', } as const diff --git a/src/lib/i18n/en/models.ts b/src/lib/i18n/en/models.ts index 7c710ef80..689161c07 100644 --- a/src/lib/i18n/en/models.ts +++ b/src/lib/i18n/en/models.ts @@ -217,4 +217,10 @@ export const models = { customTestPassed: '{model} answered with a tool call. Ready to use.', customSave: 'Save', customAdd: 'Add provider', + /* shared providers: set up by an admin for everyone (Admin → Shared models) */ + customSharedTitle: 'Shared provider', + customSharedLede: + 'Everyone on this instance gets this provider beside their own connections, and can pick its model or switch it off for themselves. The key is stored encrypted on the server and never shown again, here included.', + sharedBadge: 'Shared by your admin', + sharedRunnerName: '{name} (shared)', } as const diff --git a/src/lib/i18n/pt-BR/admin.ts b/src/lib/i18n/pt-BR/admin.ts index 874a0b214..23eab53d8 100644 --- a/src/lib/i18n/pt-BR/admin.ts +++ b/src/lib/i18n/pt-BR/admin.ts @@ -90,4 +90,25 @@ export const admin: Catalog['admin'] = { refusalWorkspaceNotFound: 'Esse workspace não existe mais.', refusalInvalid: 'Essa alteração não foi entendida.', saveFailed: 'Não foi possível salvar — tente de novo.', + + sharedNav: 'Modelos compartilhados', + sharedTab: 'Modelos', + sharedLoadFailed: 'Não foi possível carregar os provedores compartilhados.', + sharedTitle: 'Provedores de modelo compartilhados', + sharedDescription: + 'Provedores personalizados que todos nesta instância recebem ao lado das próprias conexões: cada pessoa escolhe um modelo ou desliga um só para si, e nunca vê a chave nem as configurações. Quem não tem conexão própria usa o primeiro que estiver ligado.', + sharedAdd: 'Adicionar provedor', + sharedEmpty: + 'Nenhum provedor compartilhado ainda. Adicione seu gateway (LiteLLM, vLLM, Ollama…) uma vez e ninguém precisa colar a chave.', + sharedOff: + 'Os provedores personalizados estão desligados neste servidor (DOOP_CUSTOM_PROVIDERS=false), então ninguém os vê até que sejam religados.', + sharedUse: 'Compartilhar {name} com todos', + sharedEdit: 'Editar', + sharedDelete: 'Remover', + sharedDeleteTitle: 'Remover {name}?', + sharedDeleteDescription: + 'Ele some para todos na hora, junto com o modelo que cada pessoa escolheu nele. Para tirá-lo por enquanto, desligue-o.', + sharedModelCount: { one: '{count} modelo', other: '{count} modelos' }, + sharedKeySet: 'chave definida', + sharedNoKey: 'sem chave', } diff --git a/src/lib/i18n/pt-BR/models.ts b/src/lib/i18n/pt-BR/models.ts index 6afe07678..82448d335 100644 --- a/src/lib/i18n/pt-BR/models.ts +++ b/src/lib/i18n/pt-BR/models.ts @@ -220,4 +220,10 @@ export const models: Catalog['models'] = { customTestPassed: '{model} respondeu com uma chamada de ferramenta. Pronto para usar.', customSave: 'Salvar', customAdd: 'Adicionar provedor', + /* provedores compartilhados: configurados por um admin para todos (Admin → Modelos compartilhados) */ + customSharedTitle: 'Provedor compartilhado', + customSharedLede: + 'Todos nesta instância recebem este provedor ao lado das próprias conexões, e podem escolher o modelo ou desligá-lo só para si. A chave fica criptografada no servidor e nunca é mostrada de novo, nem aqui.', + sharedBadge: 'Compartilhado pelo seu admin', + sharedRunnerName: '{name} (compartilhado)', } diff --git a/src/pages/Admin.tsx b/src/pages/Admin.tsx index 0e2112766..3d6cd90e6 100644 --- a/src/pages/Admin.tsx +++ b/src/pages/Admin.tsx @@ -17,9 +17,11 @@ import { GridIcon, LockIcon, MessageSquareIcon, + ServerIcon, UsersIcon, } from '../components/ui/icons' import { SignInSettings } from '../components/SignInSettings' +import { SharedProviderSettings } from '../components/SharedProviderSettings' import { Tabs, TabsList, TabsTrigger } from '../components/ui/tabs' import { Button } from '../components/ui/button' import { ConfirmDialog } from '../components/ui/alert-dialog' @@ -60,7 +62,7 @@ const LINK_TITLE = { edit: 'admin.linkAccessEdit', } as const satisfies Record -type Tab = 'canvases' | 'users' | 'feedback' | 'signin' +type Tab = 'canvases' | 'users' | 'feedback' | 'signin' | 'models' /* the header's search, for the tabs that are lists */ const SEARCH_LABEL: Partial> = { @@ -195,6 +197,14 @@ export function Admin() { > {t('admin.signInNav')} + } + active={tab === 'models'} + onClick={() => setTab('models')} + > + {t('admin.sharedNav')} +
@@ -257,6 +267,9 @@ export function Admin() { {t('admin.signInTab')} + + {t('admin.sharedTab')} + @@ -310,6 +323,8 @@ export function Admin() { ) : tab === 'signin' ? ( + ) : tab === 'models' ? ( + ) : (
{users === null &&

…

} diff --git a/tests/customProviderForm.test.tsx b/tests/customProviderForm.test.tsx index e358ccf85..f23994b56 100644 --- a/tests/customProviderForm.test.tsx +++ b/tests/customProviderForm.test.tsx @@ -2,7 +2,16 @@ import { act } from 'react' import { createRoot, type Root } from 'react-dom/client' import { afterEach, beforeEach, expect, it, vi } from 'vitest' -const mocks = vi.hoisted(() => ({ add: vi.fn(), update: vi.fn(), discover: vi.fn(), test: vi.fn() })) +const mocks = vi.hoisted(() => ({ + add: vi.fn(), + update: vi.fn(), + discover: vi.fn(), + test: vi.fn(), + addShared: vi.fn(), + updateShared: vi.fn(), + discoverShared: vi.fn(), + testShared: vi.fn(), +})) vi.mock('../src/lib/api', () => ({ api: { addCustomProvider: mocks.add, @@ -10,6 +19,12 @@ vi.mock('../src/lib/api', () => ({ discoverCustomModels: mocks.discover, testCustomProvider: mocks.test, }, + adminApi: { + addSharedProvider: mocks.addShared, + updateSharedProvider: mocks.updateShared, + discoverSharedModels: mocks.discoverShared, + testSharedProvider: mocks.testShared, + }, })) import { CustomProviderForm } from '../src/components/CustomProviderForm' import type { ModelAccountStatus } from '../src/lib/api' @@ -126,3 +141,30 @@ it('edits without resending the stored key or headers, and lists the endpoint’ await click('Save') expect(mocks.update).toHaveBeenLastCalledWith(provider.kind, expect.objectContaining({ apiKey: '', headers: {} })) }) + +it('in admin mode saves and probes a shared provider through the admin routes', async () => { + const shared = { providers: [], customProviders: true } + mocks.addShared.mockResolvedValue(shared) + mocks.discoverShared.mockResolvedValue({ models: ['qwen3-coder'] }) + mocks.testShared.mockResolvedValue({ ok: true, model: 'qwen3-coder' }) + const onSaved = vi.fn() + act(() => root.render( {}} />)) + expect(document.body.textContent).toContain('Shared provider') + act(() => { + type(field('input[placeholder="My provider"]'), 'Acme Gateway') + type(field('input[placeholder="https://api.example.com/v1"]'), 'https://llm.example.com/v1') + type(field('input[placeholder="my-model-id"]'), 'qwen3-coder') + type(field('input[type="password"]'), 'sk-gateway') + }) + await click('Fetch models') + expect(mocks.discoverShared).toHaveBeenCalledWith(expect.objectContaining({ apiKey: 'sk-gateway' })) + await click('Test') + expect(mocks.testShared).toHaveBeenCalledWith(expect.objectContaining({ model: 'qwen3-coder' })) + await click('Add provider') + expect(mocks.addShared).toHaveBeenCalledWith(expect.objectContaining({ name: 'Acme Gateway', apiKey: 'sk-gateway' })) + expect(onSaved).toHaveBeenCalledWith(shared) + /* nothing went through a person's own routes */ + expect(mocks.add).not.toHaveBeenCalled() + expect(mocks.discover).not.toHaveBeenCalled() + expect(mocks.test).not.toHaveBeenCalled() +}) diff --git a/tests/sharedProviderRow.test.tsx b/tests/sharedProviderRow.test.tsx new file mode 100644 index 000000000..99615d9b5 --- /dev/null +++ b/tests/sharedProviderRow.test.tsx @@ -0,0 +1,94 @@ +// @vitest-environment happy-dom +import { act } from 'react' +import { createRoot, type Root } from 'react-dom/client' +import { afterEach, beforeEach, expect, it, vi } from 'vitest' +const SHARED = 'custom:0123456789abcdef01' +const OWN = 'custom:aaaaaaaaaaaaaaaaaa' +const mocks = vi.hoisted(() => ({ + disconnect: vi.fn(), + toggle: vi.fn(), +})) +const custom = (baseUrl: string) => ({ + name: 'Acme Gateway', + apiType: 'openai-chat' as const, + baseUrl, + models: [{ id: 'qwen3-coder', vision: true }], + headerNames: [], + hasKey: true, +}) +const view = { + accounts: [ + { kind: OWN, enabled: true, model: 'qwen3-coder', connectedAt: 1, custom: custom('https://mine.example/v1') }, + { + kind: SHARED, + enabled: true, + model: 'qwen3-coder', + connectedAt: 2, + custom: custom('https://llm.acme.example'), + shared: true, + }, + ], + default: SHARED, + chatgptEnabled: true, + menus: {}, + customProviders: true, +} +vi.mock('../src/lib/auth', () => ({ authClient: { useSession: () => ({ data: { user: { id: 'alice' } } }) } })) +vi.mock('../src/lib/api', () => ({ + api: { + modelAccounts: async () => view, + agentModels: async () => ({ models: [], live: true }), + disconnectModelAccount: mocks.disconnect, + setModelAccountEnabled: mocks.toggle, + }, +})) +vi.mock('../src/lib/localAgent', () => ({ useLocalAgent: () => ({ enabled: false }) })) +vi.mock('../src/lib/store', () => ({ useStore: { getState: () => ({ allowanceChanged: vi.fn() }) } })) +vi.mock('../src/lib/posthog', () => ({ posthog: { capture: vi.fn() } })) +vi.mock('../src/components/LocalClaude', () => ({ LocalClaudeRow: () => null })) +import { ModelAccountPanel } from '../src/components/ModelAccount' +;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true + +/* An admin's shared provider sits among the person's connections with a + badge saying so: its switch and Make default work, Edit and Disconnect are + not offered. A personal provider of the same name keeps both. */ + +let root: Root +let container: HTMLDivElement +beforeEach(async () => { + vi.clearAllMocks() + container = document.createElement('div') + document.body.append(container) + root = createRoot(container) + await act(async () => root.render()) +}) +afterEach(() => { + act(() => root.unmount()) + container.remove() +}) + +const rows = () => Array.from(container.querySelectorAll('[role="listitem"]')) +const rowOf = (host: string) => rows().find((row) => row.textContent?.includes(host))! + +async function menuOf(row: HTMLElement): Promise { + act(() => { + row + .querySelector('[aria-label="More for Acme Gateway"]')! + .dispatchEvent(new PointerEvent('pointerdown', { bubbles: true, button: 0, pointerType: 'mouse' })) + }) + const items = Array.from(document.querySelectorAll('[role="menuitem"]')).map((el) => el.textContent) + act(() => document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }))) + return items.filter((item): item is string => !!item) +} + +it('badges the shared provider and offers no edit or disconnect on it', async () => { + const shared = rowOf('llm.acme.example') + expect(shared.textContent).toContain('Shared by your admin') + expect(await menuOf(shared)).toEqual(['Make default']) +}) + +it('keeps a personal provider of the same name editable and removable', async () => { + const own = rowOf('mine.example') + expect(own.textContent).not.toContain('Shared by your admin') + expect(await menuOf(own)).toEqual(['Make default', 'Edit provider', 'Disconnect']) +}) From 9ebb1da51e72f59ab20a566a54da324aeb9e69e2 Mon Sep 17 00:00:00 2001 From: gganebnyi Date: Mon, 23 Nov 2026 11:28:54 +0200 Subject: [PATCH 3/6] docs: shared model providers spec, TECHSTACK and .env.example Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01ABWHJg7QHZpRjDADALswQZ --- .context/TECHSTACK.md | 18 +++ .context/specs/INDEX.md | 3 + .context/specs/shared-model-providers.md | 148 +++++++++++++++++++++++ .env.example | 5 +- 4 files changed, 172 insertions(+), 2 deletions(-) create mode 100644 .context/specs/shared-model-providers.md diff --git a/.context/TECHSTACK.md b/.context/TECHSTACK.md index 84f0e258b..526cdc8b0 100644 --- a/.context/TECHSTACK.md +++ b/.context/TECHSTACK.md @@ -277,6 +277,24 @@ server/index.ts` in prod. `erasableSyntaxOnly` and `verbatimModuleSyntax` in tsc Advanced: extra headers (routing and framing headers refused), `max_tokens` vs `max_completion_tokens`, and echoing `reasoning_content`. Tests: `customProvider.test.ts`, `customProvidersHttp.test.ts`, `customProviderForm.test.tsx`. +- Shared model providers (`server/sharedModelAccounts.ts`, `src/components/SharedProviderSettings.tsx`): + a custom provider an instance admin sets up once in Admin → Shared models, for every signed-in + person. The definition lives in `shared_model_accounts` (kind `custom:`, key and headers sealed, + `enabled`, at most 10; migration 0066) and each person's own model, effort and on/off in + `shared_model_account_prefs` (deleted with the provider). `getAccounts`/`getAccount` merge the + enabled ones after the person's own accounts as `ModelAccount`s marked `shared`, so the composer + pick, the default (someone with no account of their own defaults to the first one on), the free-tier + meter and runs treat it like any connection; picks write the prefs row, and edit, disconnect and the + set-up probes' stored-secret fallback refuse a shared kind (403). A person's view gives its origin + only, no header names. `GET/POST /api/admin/shared-providers`, `PUT/PATCH/DELETE +/api/admin/shared-providers/:kind` and `/models`, `/test` (the same validation, probes and form as + personal ones, in admin mode); the admin view never carries the key or header values either, only + `hasKey` and `headerNames`, and the stored key and headers only go to the origin they were saved for + (a probe or edit for another origin must bring its own). `DOOP_CUSTOM_PROVIDERS=false` hides them + from everyone. For image billing a shared provider is the person's own connection, so the server's + image keys do not draw for them. Tests: + `sharedModelAccounts.test.ts`, `sharedModelAccountsStore.test.ts`, `sharedModelProvidersHttp.test.ts`, + `sharedProviderRow.test.tsx`, `customProviderForm.test.tsx`. - Reasoning effort on a user's OpenAI account (ChatGPT subscription or OpenAI key): the pick lives in `model_accounts.reasoning_effort` (`REASONING_EFFORTS` in `shared/modelMenu.ts`: low / medium / high / xhigh), set through `PATCH /api/model-account/:kind { effort }`, read by `effortFor` in diff --git a/.context/specs/INDEX.md b/.context/specs/INDEX.md index f490ef93a..29745051a 100644 --- a/.context/specs/INDEX.md +++ b/.context/specs/INDEX.md @@ -6,6 +6,9 @@ lists every file in this folder. ## Active +- [shared-model-providers.md](shared-model-providers.md) - Shared model providers: custom + providers an admin sets up once for every user (Admin → Shared models), per-user model pick and + on/off, sealed key never returned; `shared_model_accounts` + prefs, `/api/admin/shared-providers`. - [skills.md](skills.md) - Team skills: named markdown instructions a workspace or person writes once, invoked by `/handle` in a request and added to the resident agent's system prompt for that run; storage, `/api/skills`, the settings card. Issue #380. diff --git a/.context/specs/shared-model-providers.md b/.context/specs/shared-model-providers.md new file mode 100644 index 000000000..872a8a393 --- /dev/null +++ b/.context/specs/shared-model-providers.md @@ -0,0 +1,148 @@ +# Shared model providers (instance-wide) + +Status: implemented + +## Problem + +A custom provider (Settings → Doop Agent → Custom provider) is stored per person (`model_accounts`, key +`user_id + kind`). A company that self-hosts Doop next to its own model gateway (LiteLLM, vLLM, Ollama…) has to make +every employee paste the same base URL, key and model list. New people start with no agent at all until they do. +Doop's only instance-wide model knob is the free tier (`DOOP_AGENT_PROVIDER` + `ANTHROPIC_API_KEY`), which offers one +fixed model and no model menu. + +## Goal + +A Doop **admin** defines one or more **shared custom providers** once. Every signed-in user sees them in the agent and +model pickers next to their personal connections, can pick a model and switch a shared provider off for themselves, +and cannot see the key or edit or remove the provider. New users get a working agent at their first sign-in. + +Out of scope: workspace-scoped sharing, sharing built-in kinds (ChatGPT/OpenAI/Anthropic keys), per-user quotas. + +## Behaviour + +1. **Admin → Instance → "Shared model providers"** lists the shared providers: name, API type, base URL, model count, + on/off. Admins can add one (the existing `CustomProviderForm`: name, API type, base URL, key, headers, models, + vision, max output tokens, Test, Fetch models), edit it (the key is never shown; blank keeps it), switch it off, or + delete it. +2. **Users** see each enabled shared provider as a connection labelled with its name and a "Shared by your admin" badge. + Model picker, the "use for agent" default and the per-user on/off toggle work as for a personal provider. Edit, + Remove and the key field are absent. +3. **Precedence:** shared and personal providers coexist (different kinds). The agent default resolution (`agentDefaults`) + treats a shared provider like any connected account. A user without any personal account therefore defaults to the + first enabled shared provider, so new users "just work". +4. **Per-user state on a shared provider** (picked model, reasoning effort, on/off) is stored per user. Changing it never + touches the shared definition or other users. +5. **Admin switches a provider off or deletes it:** it disappears for everyone immediately. Per-user prefs for a deleted + provider are deleted. +6. **Operator switches:** `DOOP_CUSTOM_PROVIDERS=false` disables shared providers too. `DOOP_CUSTOM_PROVIDER_PRIVATE_HOSTS` + applies to them exactly as to personal ones (same fetch path). +7. **Free-tier meter:** a shared provider counts as "a connected model account" for `RESIDENT_TASK_LIMIT` / allowance + purposes, like a personal one: the run is on the company's model, not the server's paid key. + **Image generation** bills it the same way: a person with a shared provider has a connection of their own, so the + server's image keys (`OPENAI_API_KEY`, `GEMINI_API_KEY`), which cover only people who connected no model account, + no longer draw for them. A shared provider cannot draw images, so such a person draws only with an image-capable + account of their own (ChatGPT, OpenAI or Gemini key). +8. **Security:** + - The shared key and headers are sealed at rest like personal ones (`sealedText`). They are read sealed and opened + per provider: one whose key or headers cannot be unsealed (its encryption key rotated out of + `SECRETS_ENCRYPTION_KEYS`, the value damaged) is skipped with a warning, for people and in Admin alike, and + never takes anyone's other connections down with it. + - They are never returned by any API, including to admins, and never sent anywhere new: the stored key and headers + go only to the origin they were saved for. An admin probe (`/models`, `/test`) for another origin, or an edit + that moves the base URL to another origin, has to bring its own key and headers (or say "none", an empty value); + otherwise it is refused with 400 saying so. + - Text from the endpoint (an error body, a refusal) has the key and every header value masked + (`redactSecrets` in `server/customProviderFetch.ts`) before it reaches a person, a log line or a stored run + error, since an endpoint may quote the credential it refused. This holds for personal providers too. + - Admin routes are behind `isAdmin`. + - Users get a read-only view with no `baseUrl` secrets: its origin only, and no header names. + - The full base URL is shown to admins only (a stored base URL never carries credentials: the validator refuses + them). + - The set-up probes (`/api/custom-providers/models|test`) never fall back to a shared provider's stored key, which + would let a person send it to a URL of their choosing. +9. **Wording:** where a run fails on a shared provider's credential or configuration, the card and status line tell the + person to ask their admin (Admin → Shared models) rather than to reconnect or edit it. These are server-written + English strings, like every other run failure; there is no i18n catalog on the server. + +## Data + +- `shared_model_accounts`: + - `kind` PK (`custom:`, same id format as personal); + - `custom` jsonb (`CustomProviderConfig`); + - `api_key` sealed; + - `custom_headers` sealed; + - `enabled` bool; + - `created_by`, `updated_by`, `created_at`, `updated_at`. +- `shared_model_account_prefs`: + - `user_id`, `kind` (PK both); + - `model` text null, `reasoning_effort` text null, `enabled` bool default true; + - `updated_at`. +- Migration `0066_shared_model_accounts.sql` (next free number on main), idempotent (`IF NOT EXISTS`). + +## Code shape + +- `server/sharedModelAccounts.ts` holds CRUD for the shared table (reusing `parseCustomProviderConfig` and + `parseCustomHeaders`) and the prefs read/write. +- `server/modelAccounts.ts`: + - `getAccounts(userId)` returns personal accounts, then the enabled shared ones merged with the user's prefs, as + `ModelAccount & { shared: true }`; + - `getAccount(userId, kind)` resolves shared kinds the same way; + - `setAccountModel`, `setAccountEffort` and `setAccountEnabled` on a shared kind write prefs; + - `disconnect` and `updateCustomProvider` on a shared kind are refused (`403 shared provider`). +- `statusOf()` adds `shared: true`. `/api/model-account` returns it; the UI hides edit/remove when it is set. +- `server/admin.ts` gets `GET/POST /api/admin/shared-providers`, `PUT/PATCH/DELETE /api/admin/shared-providers/:kind` + (`PATCH { enabled }` switches one on or off without resending its description), and + `POST /api/admin/shared-providers/test|models`, reusing the custom-provider test and model-discovery code. They sit + behind the admin router's existing guard, which answers a non-admin 404 like every other admin route. +- UI: + - `src/pages/Admin.tsx` gets a new section that reuses `CustomProviderForm` in "admin" mode; + - `src/components/ModelAccount.tsx` shows the shared badge and hides the edit and remove actions; + - i18n keys go into `src/lib/i18n/en/*` and `src/lib/i18n/pt-BR/*`, as every locale carries the same keys. + +## Tests + +- **Unit:** + - merge order and prefs; + - per-user model and enable; + - refusal to edit or delete a shared kind as a user; + - a disabled or deleted shared provider disappears; + - `DOOP_CUSTOM_PROVIDERS=false` hides shared providers; + - the default agent resolution picks a shared provider for a user with no accounts; + - image generation does not fall back to the server's image keys for a user with only a shared provider. +- **HTTP:** + - admin-only guards (a non-admin gets the admin router's 404 on every route); + - the stored key and headers never go to another origin (admin probes and edits); + - the key is never in any response; + - create → user sees it → admin disables → user no longer sees it. +- Existing suites stay green: `bun run typecheck`, `bun run lint`, `bun run test`. + +## Notes + +- Deleting an account deletes that person's prefs rows (`purgeUserData`); the shared providers stay. +- Two admins editing one shared provider at once: the last write wins, the same as personal providers. A key or headers + left out of an edit are kept whoever wrote them last. +- A person who never picked a model runs on the provider's first model (`models[0]`), so reordering the list in Admin + moves them. A pick on a model that is later removed falls back the same way. +- Image descriptions (`server/imageDescriptions.ts`) run on the uploader's default connection, else their first enabled + account whose (picked) model sees images, before any server describer. A shared provider whose model sees images + therefore describes uploads for people with nothing of their own, on the company's endpoint. + +## Upgrade notes + +- Image generation: a person whose only connection is a shared provider is billed as having a connection of their own, + so the server's image keys no longer draw for them (they did not draw for people with a personal provider either). + +- Migration `0066_shared_model_accounts` adds the two tables; it is the next free number on upstream `main` at the time + of writing and runs on boot like every other. Nothing existing changes. +- The migration is idempotent (`CREATE TABLE IF NOT EXISTS`, `CREATE INDEX IF NOT EXISTS`). An earlier draft of this + branch numbered it `0062`; a fork that ran that draft already has both tables, and the renumbered migration runs over + them without error. +- Such a fork must also delete the draft's row from `drizzle.__drizzle_migrations` before it boots this version + (`DELETE FROM drizzle.__drizzle_migrations WHERE created_at = 1795420894296`). Drizzle applies only migrations newer + than the last one it recorded, and that row's timestamp is newer than upstream's `0062`–`0065`, which would + otherwise be skipped without an error. A fork that already booted this version without doing so deletes the + `0066` row too (`created_at IN (1795420894296, 1795596622579)`) and boots again: upstream's four then run, and + `0066` runs again over the existing tables. +- A fork carrying this branch before it merges must rebase it before each upstream sync: if upstream adds its own + migration with the same number, the branch's migration has to be renumbered (and its snapshot regenerated) on top + of upstream's. diff --git a/.env.example b/.env.example index 7bcbc8c51..a82071b68 100644 --- a/.env.example +++ b/.env.example @@ -520,8 +520,9 @@ # Kimi Code (a Kimi membership's quota); China: https://api.kimi.com/coding/v1/chat/completions #KIMI_CODE_CHAT_URL=https://api.kimi.ai/coding/v1/chat/completions # Custom providers: people connect any OpenAI- or Anthropic-compatible API by -# its base URL in Settings → Doop Agent. false switches the feature off (and -# takes existing ones out of use). +# its base URL in Settings → Doop Agent, and admins share one with everyone in +# Admin → Shared models. false switches the feature off (and takes existing +# ones, shared ones included, out of use). #DOOP_CUSTOM_PROVIDERS=true # A custom provider's URL is user input, so by default it is reached over # public addresses only (https, DNS pinned per request). On a self-hosted From a7bad4239dc50c1ea329eb8f6ed1056f1c83e19b Mon Sep 17 00:00:00 2001 From: gganebnyi Date: Mon, 23 Nov 2026 15:28:08 +0200 Subject: [PATCH 4/6] feat(agent): image models on custom providers, personal and shared A Chat Completions custom provider can list image models next to its chat models (`imageModels: { id, name?, transparent? }[]`, at most 20, in the same `custom` jsonb, so no migration; descriptions stored before keep parsing). Whoever has the provider connected and on, an admin's shared one included, finds them in GET /api/image-model after the registry and can pick one (stored in image_prefs as `custom:/`). With no pick, the first one is the default once nothing on the registry can run, so a person whose only connection is a shared provider draws on it from their first sign-in. generate_image draws through POST {baseUrl}/images/generations over customProviderFetch (private hosts, DNS pinning, no redirects, size cap) with the provider's key and headers and imageApiGenerator's body. It reads data[0].b64_json, or fetches data[0].url the same way, sending the credentials only to the base URL's origin, and accepts PNG, JPEG or WebP only. It is billed as the person's own connection; a pick that cannot run (switched off, deleted, delisted, or custom providers off) refuses with the fix and never falls back to another model or a server key. A 401/403 on a shared provider tells the person to ask their admin. Endpoint text that reaches a person or a log (a refusal body, a 429, an error beside a 200) has the provider's key and header values masked, as its chat turns do. With no pick, the person's own credentials (registry accounts, then custom image models) come before anything a server key pays for, Seedream on ARK_API_KEY included. Disconnecting a personal provider or deleting a shared one deletes the image-model picks on it. generate_image (MCP and resident) takes an optional `transparent`: only a model marked so is sent `background: "transparent"`, and the result says whether the cut-out was drawn. Analytics get `custom-personal` or `custom-shared`, never the provider's name. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01ABWHJg7QHZpRjDADALswQZ --- server/guide.ts | 12 +- server/imageGen.ts | 366 ++++++++++++++++++-- server/imagePrefs.ts | 23 +- server/mcp.ts | 9 +- server/modelAccounts.ts | 15 +- server/resident.ts | 8 +- server/sharedModelAccounts.ts | 7 +- shared/customProvider.ts | 80 +++++ tests/customProvider.test.ts | 84 +++++ tests/customProviderImages.test.ts | 450 +++++++++++++++++++++++++ tests/customProviderImagesHttp.test.ts | 318 +++++++++++++++++ tests/sharedModelAccounts.test.ts | 16 +- tests/sharedModelAccountsStore.test.ts | 6 +- 13 files changed, 1339 insertions(+), 55 deletions(-) create mode 100644 tests/customProviderImages.test.ts create mode 100644 tests/customProviderImagesHttp.test.ts diff --git a/server/guide.ts b/server/guide.ts index e173dd318..77422d8f1 100644 --- a/server/guide.ts +++ b/server/guide.ts @@ -661,13 +661,15 @@ any public image URL. Source images in this order: generated image, generate one from a prompt. It returns a permanent URL on this origin plus a preview: look at the preview and judge it like any other asset before it goes in. It draws with the image model your human picked in Settings (GPT Image, Nano - Banana or Seedream), on their connected account (else the server's key), and costs - them quota or money, and takes 20–60 seconds, so write ONE + Banana, Seedream, or an image model their custom or shared provider lists), on their + connected account (else the server's key), and costs them quota or money, and takes + 20–60 seconds, so write ONE considered prompt — subject, style, composition, palette hexes, lighting, what to leave out — and refine a near miss by saying what was wrong rather than rolling the - dice again. Match aspect to the slot (square, landscape, portrait). Images come back - opaque — no transparent cut-outs — so place them in a box, mask them with CSS, or - prompt for the surface color you will put them on. Photography that exists in the + dice again. Match aspect to the slot (square, landscape, portrait). Images usually come + back opaque: pass transparent for a cut-out, which only some image models can draw (the + result says whether you got one); otherwise place the image in a box, mask it with CSS, + or prompt for the surface color you will put it on. Photography that exists in the world is still search_images' job. - **Hero backgrounds are where it shines.** A generated scene can match the palette exactly and leave room where the copy and the product window sit, which no stock diff --git a/server/imageGen.ts b/server/imageGen.ts index 1c6cf21a4..e854c5bfc 100644 --- a/server/imageGen.ts +++ b/server/imageGen.ts @@ -4,12 +4,20 @@ import sharp from 'sharp' import { getAccounts, withFreshToken } from './modelAccounts.ts' import type { ModelAccount } from './modelAccounts.ts' import { getImagePref } from './imagePrefs.ts' +import { customProviderFetch, redactSecrets } from './customProviderFetch.ts' import { ACCOUNT_KIND_LABELS, IMAGE_MODELS } from '../shared/modelMenu.ts' import type { AccountKindName, ImageModelOption } from '../shared/modelMenu.ts' +import { + customImageModelRef, + isCustomProviderKind, + parseCustomImageModelRef, + type CustomImageModel, +} from '../shared/customProvider.ts' import { CHATGPT_URL, DEFAULT_OPENAI_MODEL, ModelAuthError, + ModelUnavailableError, modelFor, OPENAI_URL, ORIGINATOR, @@ -39,6 +47,14 @@ import { * - `ark` (Seedream, BytePlus ModelArk) — server-only via ARK_API_KEY; there * is no ByteDance BYO account. * + * Beside the registry, a custom provider (shared/customProvider.ts) can list + * image models of its own — a gateway in front of a self-hosted FLUX, say — + * which anyone with that provider connected and on can pick. They draw + * through the provider's OpenAI Images API (`POST {baseUrl}/images/generations`) + * on its key and headers, over customProviderFetch like its chat turns, and + * are billed as the person's own connection, an admin's shared provider + * included: no server key ever stands in for one. + * * Whoever pays for the agent run pays for its images; nobody's subscription * ever draws for someone else, and an unavailable choice refuses with the fix * rather than quietly billing a different key. @@ -71,6 +87,8 @@ export interface ImageRequest { prompt: string aspect?: ImageAspect quality?: ImageQuality + /** a cut-out: honoured only by an image model that says it can draw one */ + transparent?: boolean } export interface GeneratedImage { @@ -81,8 +99,12 @@ export interface GeneratedImage { height: number /** a small preview the agent can look at without paying for the full image */ preview: { data: string; mime: 'image/jpeg' } - /** who paid: "ChatGPT", "OpenAI", "Gemini", or "server" */ + /** who paid: "ChatGPT", "OpenAI", "Gemini", "server", or a custom provider's name */ billedTo: string + /** drawn on a custom provider: the person's own, or one an admin shares */ + custom?: 'personal' | 'shared' + /** a transparent background was asked for and the image has one */ + transparent: boolean } /** Something that can generate an image for a given payer, or the reason it cannot. */ @@ -92,6 +114,8 @@ export type Generator = label: string /** set on server-key generators: the env var to blame when auth fails */ authHint?: string + /** a custom provider's image model: whose it is */ + custom?: 'personal' | 'shared' run: (req: ImageRequest) => Promise } | { ok: false; reason: string } @@ -352,6 +376,175 @@ function arkGenerator(apiKey: string, label: string, model: string): Generator { } } +/* ---------------------------------------------------------------- */ +/* a custom provider's image models: its OpenAI Images API */ +/* ---------------------------------------------------------------- */ + +/** A custom provider's image model, on the account that lists it. */ +interface CustomImageChoice { + /** what the image-model preference stores for it */ + ref: string + account: ModelAccount + model: CustomImageModel +} + +interface CustomImageResponse { + data?: { b64_json?: string; url?: string }[] + error?: { message?: string } | string +} + +/* what the image is decoded as; anything else (an SVG, an HTML error page) + is refused before it reaches a frame */ +const CUSTOM_IMAGE_FORMATS = new Set(['png', 'jpeg', 'webp']) + +/* a shared provider is its admin's to fix, a personal one its person's */ +function customFix(account: ModelAccount): string { + return account.shared + ? 'Ask your admin to check it in Admin → Shared models.' + : 'Check the provider in Settings → Doop Agent.' +} + +/** The endpoint's refusal, phrased as the fix the person can make. */ +async function customImageError(res: Response, account: ModelAccount, model: CustomImageModel): Promise { + const name = account.custom!.name + /* masked on the whole body, before responseError shortens it */ + const error = await responseError(res, name, (text) => redactSecrets(text, account)) + if (error instanceof ModelAuthError) { + return new Error( + account.shared + ? `${name} turned down the shared connection your admin set up (${res.status}). Ask your admin to check it in Admin → Shared models.` + : `${name} rejected the API key (${res.status}). Update it in Settings → Doop Agent.`, + { cause: error }, + ) + } + if (error instanceof ModelUnavailableError || res.status === 404) { + return new Error( + `${name} cannot draw with ${model.id} (${res.status}): the endpoint has no such image model, or no /images/generations. ${customFix(account)}`, + { cause: error }, + ) + } + return error +} + +/* every request to the provider, its image links included, goes through + customProviderFetch; a transport failure names the provider */ +async function reachCustom(account: ModelAccount, url: string, init: RequestInit): Promise { + try { + return await customProviderFetch(url, init) + } catch (error) { + const detail = error instanceof Error ? error.message : String(error) + throw new Error(`${account.custom!.name} could not be reached: ${detail} ${customFix(account)}`, { + cause: error, + }) + } +} + +/** An image the endpoint answered with as a link: fetched like the request + * was, its key and headers sent along only to the provider's own origin. */ +async function customImageLink( + account: ModelAccount, + raw: string, + credentials: Record, +): Promise { + const config = account.custom! + let url: URL + try { + url = new URL(raw, `${config.baseUrl}/`) + } catch { + throw new Error(`${config.name} returned an image link that is not a URL. ${customFix(account)}`) + } + const sameOrigin = url.origin === new URL(config.baseUrl).origin + const res = await reachCustom(account, url.href, { + headers: sameOrigin ? credentials : {}, + signal: AbortSignal.timeout(FETCH_TIMEOUT_MS), + }) + if (!res.ok) { + await res.body?.cancel() + throw new Error(`${config.name} returned an image link that answered ${res.status}. ${customFix(account)}`) + } + return Buffer.from(await res.arrayBuffer()) +} + +/* The request is imageApiGenerator's, OpenAI's Images API shape that + gateways (LiteLLM, vLLM, LocalAI) take: the model id, the prompt as + written, one image at a size from SIZES. */ +function customImageGenerator(choice: CustomImageChoice): Generator { + const { account } = choice + const config = account.custom! + const credentials: Record = { + ...account.headers, + ...(account.apiKey ? { Authorization: `Bearer ${account.apiKey}` } : {}), + } + return { + ok: true, + label: config.name, + custom: account.shared ? 'shared' : 'personal', + run: async (req) => { + try { + return await drawCustom(choice, credentials, req) + } catch (error) { + throw redactedImageError(error, account) + } + }, + } +} + +/** + * A custom provider's failure with its key and header values masked: the + * endpoint's own words (a refusal body, a 429, an `error.message` beside a + * 200) reach the person and the logs, and for a shared provider the person + * must never see the admin's key. A fresh error, so no cause carries the + * original along; a cancel or timeout has no endpoint text and passes as is. + */ +function redactedImageError(error: unknown, account: ModelAccount): unknown { + if (!(error instanceof Error) || error.name === 'AbortError' || error.name === 'TimeoutError') return error + return new Error(redactSecrets(error.message, { apiKey: account.apiKey, headers: account.headers })) +} + +async function drawCustom( + { account, model }: CustomImageChoice, + credentials: Record, + req: ImageRequest, +): Promise { + const config = account.custom! + const res = await reachCustom(account, `${config.baseUrl}/images/generations`, { + method: 'POST', + headers: { ...credentials, 'Content-Type': 'application/json', Accept: 'application/json' }, + body: JSON.stringify({ + model: model.id, + prompt: req.prompt, + n: 1, + size: SIZES[req.aspect ?? 'square'], + quality: req.quality ?? 'medium', + output_format: 'png', + ...(req.transparent && model.transparent ? { background: 'transparent' } : {}), + }), + signal: AbortSignal.timeout(FETCH_TIMEOUT_MS), + }) + if (!res.ok) throw await customImageError(res, account, model) + const body = (await res.json().catch(() => null)) as CustomImageResponse | null + const image = body?.data?.[0] + let buf: Buffer + if (image?.b64_json) buf = Buffer.from(image.b64_json, 'base64') + else if (image?.url) buf = await customImageLink(account, image.url, credentials) + else { + const detail = typeof body?.error === 'string' ? body.error : body?.error?.message + throw new Error( + detail + ? `${config.name} did not generate an image: ${redactSecrets(detail, account).slice(0, 300)}` + : `${config.name} returned no image (neither data[0].b64_json nor data[0].url). ${customFix(account)}`, + ) + } + const format = await sharp(buf) + .metadata() + .then((meta) => meta.format as string | undefined) + .catch(() => undefined) + if (!format || !CUSTOM_IMAGE_FORMATS.has(format)) { + throw new Error(`${config.name} returned something that is not a PNG, JPEG or WebP image. ${customFix(account)}`) + } + return buf +} + /* ---------------------------------------------------------------- */ /* which model, on whose credentials */ /* ---------------------------------------------------------------- */ @@ -379,9 +572,13 @@ const NO_ACCOUNTS: PayerAccounts = { all: [], on: [], own: false } const DRAW_INSTEAD = 'Retrying fails the same way until the person connects one; meanwhile use search_images for photography or draw the visual as inline SVG/CSS.' +/** The generate_image `transparent` argument, as both tool schemas describe it. */ +export const TRANSPARENT_NOTE = + 'true asks for a transparent background (a cut-out to place over the design). Only some image models can draw one (a custom provider’s, where its owner says so); the others draw an opaque background, and the result says which you got.' + /** What every generate_image description says up front: who can draw. */ export const IMAGE_PROVIDER_NOTE = - 'It needs an image provider: the person’s ChatGPT subscription, OpenAI API key or Gemini API key, connected and switched on in Settings → Doop Agent (a Claude, OpenRouter, DeepSeek or Kimi connection cannot draw images), or the server’s own image key for someone who has connected no model account. Without one it fails at once saying what to connect: do not retry, use search_images or draw the visual as inline SVG/CSS.' + 'It needs an image provider: the person’s ChatGPT subscription, OpenAI API key or Gemini API key, or a custom provider that lists image models (an admin’s shared one included), connected and switched on in Settings → Doop Agent (a Claude, OpenRouter, DeepSeek or Kimi connection cannot draw images), or the server’s own image key for someone who has connected no model account. Without one it fails at once saying what to connect: do not retry, use search_images or draw the visual as inline SVG/CSS.' /* the accounts that can pay for some image model */ const IMAGE_ACCOUNT_KINDS: readonly string[] = ['chatgpt', 'openai-key', 'gemini-key'] @@ -395,10 +592,17 @@ function listed(names: readonly string[]): string { return `${names.slice(0, -1).join(', ')} and ${names.at(-1)}` } +/* an account that could draw if it were on: an image kind, or a custom + provider that lists image models */ +function drawsImages(account: ModelAccount): boolean { + return IMAGE_ACCOUNT_KINDS.includes(account.kind) || Boolean(account.custom?.imageModels?.length) +} + /** Why no image model at all can run for this payer, and what the person can do about it. */ function noImageProviderReason(accounts: PayerAccounts): string { - const connect = 'connect a ChatGPT subscription, an OpenAI API key or a Gemini API key in Settings → Doop Agent' - const switchedOff = accounts.all.filter((account) => !account.enabled && IMAGE_ACCOUNT_KINDS.includes(account.kind)) + const connect = + 'connect a ChatGPT subscription, an OpenAI API key or a Gemini API key in Settings → Doop Agent, or list image models on a custom provider' + const switchedOff = accounts.all.filter((account) => !account.enabled && drawsImages(account)) if (switchedOff.length > 0) { return `image generation is not available: the person’s ${listed(switchedOff.map(accountName))} connection is switched off. Switch it on in Settings → Doop Agent, or ${connect}. ${DRAW_INSTEAD}` } @@ -421,6 +625,34 @@ function geminiAccount(accounts: readonly ModelAccount[]): ModelAccount | undefi return accounts.find((account) => account.kind === 'gemini-key' && Boolean(account.apiKey)) } +/** The image models the person's switched-on custom providers list, in + * getAccounts' order: their own first, then the shared ones. */ +function customImageChoices(accounts: PayerAccounts): CustomImageChoice[] { + return accounts.on.flatMap((account) => { + const { kind } = account + if (!isCustomProviderKind(kind) || !account.custom?.imageModels) return [] + return account.custom.imageModels.map((model) => ({ ref: customImageModelRef(kind, model.id), account, model })) + }) +} + +/** Why the custom image model the person picked cannot run now. It never + * runs on another model in its place: the fix is theirs to choose. */ +function missingCustomReason(ref: string, accounts: PayerAccounts): string { + const parsed = parseCustomImageModelRef(ref) + const model = parsed?.model ?? ref + const account = parsed ? accounts.all.find((entry) => entry.kind === parsed.kind) : undefined + const pickAnother = 'pick another image model in Settings → Doop Agent' + const meanwhile = 'Meanwhile draw the visual as inline SVG/CSS or use search_images.' + const name = account?.custom?.name + if (name && !account.enabled) { + return `${model} on ${name} is not available: the person’s ${name} connection is switched off. Switch it on in Settings → Doop Agent, or ${pickAnother}. ${meanwhile}` + } + if (name) { + return `${name} no longer lists ${model} as an image model${account.shared ? ' (its admin changed it)' : ''}: ${pickAnother}. ${meanwhile}` + } + return `the image model picked in Settings (${model}) was on a custom provider that is no longer connected: ${pickAnother}. ${meanwhile}` +} + function available(option: ImageModelOption, accounts: PayerAccounts): boolean { switch (option.provider) { case 'openai': @@ -437,17 +669,40 @@ function available(option: ImageModelOption, accounts: PayerAccounts): boolean { } } -/** The registry entries this payer could actually run, for the Settings UI. */ -export async function imageModelAvailability( - payerId?: string, -): Promise<{ id: string; available: boolean; selected: boolean }[]> { +/** One image model as the Settings picker lists it. */ +export interface ImageModelAvailability { + id: string + available: boolean + selected: boolean + /** a custom provider's image model; registry entries carry their own + * names and blurbs in shared/modelMenu.ts */ + custom?: { provider: string; name: string; shared?: true; transparent?: true } +} + +/** The registry entries this payer could actually run, then the image + * models their switched-on custom providers list, for the Settings UI. */ +export async function imageModelAvailability(payerId?: string): Promise { const accounts = payerId ? await payerAccounts(payerId).catch(() => NO_ACCOUNTS) : NO_ACCOUNTS const chosen = await chosenImageModel(payerId, accounts) - return IMAGE_MODELS.map((option) => ({ - id: option.id, - available: available(option, accounts), - selected: chosen?.id === option.id, - })) + const chosenId = chosen ? choiceId(chosen) : undefined + return [ + ...IMAGE_MODELS.map((option) => ({ + id: option.id, + available: available(option, accounts), + selected: chosenId === option.id, + })), + ...customImageChoices(accounts).map(({ ref, account, model }) => ({ + id: ref, + available: true, + selected: chosenId === ref, + custom: { + provider: account.custom!.name, + name: model.name ?? model.id, + ...(account.shared ? { shared: true as const } : {}), + ...(model.transparent ? { transparent: true as const } : {}), + }, + })), + ] } let warnedDefault = false @@ -457,16 +712,29 @@ async function payerAccounts(payerId: string): Promise { return { all, on: all.filter((account) => account.enabled), own: all.length > 0 } } -/** The model a run will draw with: the user's pick, else the server default, - * else the first entry their credentials can run. */ -async function chosenImageModel( - payerId: string | undefined, - accounts: PayerAccounts, -): Promise { +/** What a run draws with: a registry entry, a custom provider's image + * model, or the custom one the person picked that is not there now. */ +type ImageChoice = { option: ImageModelOption } | { custom: CustomImageChoice } | { missing: string } + +/* the id the picker knows the choice by */ +function choiceId(choice: ImageChoice): string { + if ('option' in choice) return choice.option.id + return 'custom' in choice ? choice.custom.ref : choice.missing +} + +/** The model a run will draw with: the user's pick, else (on their own + * credentials) the server default, the first registry entry, the first image + * model of a custom provider of theirs, and only then what a server key pays + * for, the server default first. */ +async function chosenImageModel(payerId: string | undefined, accounts: PayerAccounts): Promise { const pref = payerId ? await getImagePref(payerId) : undefined + const customs = customImageChoices(accounts) if (pref) { const option = IMAGE_MODELS.find((entry) => entry.id === pref) - if (option) return option + if (option) return { option } + const custom = customs.find((entry) => entry.ref === pref) + if (custom) return { custom } + if (parseCustomImageModelRef(pref)) return { missing: pref } } const fallback = IMAGE_MODELS.find((entry) => entry.id === DEFAULT_IMAGE_MODEL) if (!fallback && !warnedDefault) { @@ -475,8 +743,25 @@ async function chosenImageModel( `[image-gen] DOOP_IMAGE_MODEL="${DEFAULT_IMAGE_MODEL}" is not on the image-model registry — ignoring it`, ) } - if (fallback && available(fallback, accounts)) return fallback - return IMAGE_MODELS.find((entry) => available(entry, accounts)) ?? fallback ?? null + /* the person's own credentials first, the server default leading: their + registry accounts, then their custom providers' image models (a shared + one is the company's endpoint, still theirs to draw on) */ + if (fallback && ownCredentials(fallback, accounts)) return { option: fallback } + const own = IMAGE_MODELS.find((entry) => ownCredentials(entry, accounts)) + if (own) return { option: own } + if (customs[0]) return { custom: customs[0] } + /* then what a server key pays for: anything for someone who connected + nothing, and Seedream on ARK_API_KEY for everyone */ + if (fallback && available(fallback, accounts)) return { option: fallback } + const runnable = IMAGE_MODELS.find((entry) => available(entry, accounts)) + if (runnable) return { option: runnable } + return fallback ? { option: fallback } : null +} + +/* runs on the person's own account rather than a server key: for someone + with an account every registry entry but Seedream does, or none at all */ +function ownCredentials(option: ImageModelOption, accounts: PayerAccounts): boolean { + return accounts.own && option.provider !== 'ark' && available(option, accounts) } function providerGenerator(option: ImageModelOption, accounts: PayerAccounts): Generator { @@ -533,7 +818,8 @@ function providerGenerator(option: ImageModelOption, accounts: PayerAccounts): G * default), on their own credentials first, else the matching server key. * An explicit pick that cannot run refuses with the fix — it never quietly * swaps in a different model or bills a key the user did not choose. When no - * model at all can run, the refusal names what to connect instead. + * model at all can run, the refusal names what to connect instead. A custom + * provider's image model only ever runs on that provider. */ export async function generatorFor(payerId?: string): Promise { /* a lookup failure must not read as "no account": that would quietly move @@ -546,12 +832,14 @@ export async function generatorFor(payerId?: string): Promise { : NO_ACCOUNTS /* nothing at all can draw: say what the person can connect, not why the default model in particular cannot run (they never picked it) */ - if (!IMAGE_MODELS.some((entry) => available(entry, accounts))) { + if (!IMAGE_MODELS.some((entry) => available(entry, accounts)) && !customImageChoices(accounts).length) { return { ok: false, reason: noImageProviderReason(accounts) } } - const option = await chosenImageModel(payerId, accounts) - if (!option) return { ok: false, reason: noImageProviderReason(accounts) } - return providerGenerator(option, accounts) + const choice = await chosenImageModel(payerId, accounts) + if (!choice) return { ok: false, reason: noImageProviderReason(accounts) } + if ('custom' in choice) return customImageGenerator(choice.custom) + if ('missing' in choice) return { ok: false, reason: missingCustomReason(choice.missing, accounts) } + return providerGenerator(choice.option, accounts) } /* ---------------------------------------------------------------- */ @@ -559,12 +847,21 @@ export async function generatorFor(payerId?: string): Promise { /* ---------------------------------------------------------------- */ /** Recompress the model's png (large) into what a frame should load, and - * cut a preview the agent can judge it by. */ -async function finish(png: Buffer, billedTo: string): Promise { + * cut a preview the agent can judge it by. A cut-out keeps its alpha in the + * webp; its jpeg preview shows it on white. */ +async function finish( + png: Buffer, + payer: Pick, + cutOut: boolean, +): Promise { const image = sharp(png) const meta = await image.metadata() + /* what was drawn, not what the model was said to do: a cut-out has an + alpha channel that is not opaque everywhere */ + const transparent = cutOut && Boolean(meta.hasAlpha) && !(await sharp(png).stats()).isOpaque const preview = await sharp(png) .resize({ width: PREVIEW_PX, height: PREVIEW_PX, fit: 'inside' }) + .flatten({ background: '#ffffff' }) .jpeg({ quality: 70 }) .toBuffer() return { @@ -573,7 +870,8 @@ async function finish(png: Buffer, billedTo: string): Promise { width: meta.width ?? 0, height: meta.height ?? 0, preview: { data: preview.toString('base64'), mime: 'image/jpeg' }, - billedTo, + ...payer, + transparent, } } @@ -588,7 +886,11 @@ export async function generateImage(payerId: string | undefined, req: ImageReque if (!generator.ok) throw new Error(generator.reason) try { const png = await generator.run({ ...req, prompt }) - return finish(png, generator.label) + return finish( + png, + { billedTo: generator.label, ...(generator.custom ? { custom: generator.custom } : {}) }, + Boolean(req.transparent), + ) } catch (err) { if (err instanceof ModelAuthError && generator.authHint) { /* these are the SERVER's credentials — "reconnect your account" would @@ -600,4 +902,4 @@ export async function generateImage(payerId: string | undefined, req: ImageReque } /* exported for tests */ -export const _internal = { requestBody, SIZES, ARK_SIZES, GEMINI_ASPECTS, chosenImageModel } +export const _internal = { requestBody, SIZES, ARK_SIZES, GEMINI_ASPECTS, chosenImageModel, customImageChoices } diff --git a/server/imagePrefs.ts b/server/imagePrefs.ts index 05f3e260d..f0a5616a2 100644 --- a/server/imagePrefs.ts +++ b/server/imagePrefs.ts @@ -1,18 +1,33 @@ -import { eq } from 'drizzle-orm' +import { eq, like } from 'drizzle-orm' import { db } from './db/index.ts' import { imagePrefs } from './db/schema.ts' import { IMAGE_MODELS } from '../shared/modelMenu.ts' +import { customImageModelRef, parseCustomImageModelRef, type CustomProviderKind } from '../shared/customProvider.ts' + +/* a registry id, or a custom provider's image model (`custom:/`), + whose provider imageGen checks against the person's accounts on every run */ +function isImageModelId(model: string): boolean { + return IMAGE_MODELS.some((option) => option.id === model) || parseCustomImageModelRef(model) !== null +} /** The image model this user picked in Settings, if it is still on the - * registry — a retired id reads as "no preference" rather than an error. */ + * registry or names a custom provider's image model — a retired registry id + * reads as "no preference" rather than an error. */ export async function getImagePref(userId: string): Promise { const [row] = await db.select().from(imagePrefs).where(eq(imagePrefs.userId, userId)) if (!row) return undefined - return IMAGE_MODELS.some((option) => option.id === row.model) ? row.model : undefined + return isImageModelId(row.model) ? row.model : undefined } export async function setImagePref(userId: string, model: string): Promise { - if (!IMAGE_MODELS.some((option) => option.id === model)) throw new Error('unknown image model') + if (!isImageModelId(model)) throw new Error('unknown image model') const row = { userId, model, updatedAt: Date.now() } await db.insert(imagePrefs).values(row).onConflictDoUpdate({ target: imagePrefs.userId, set: row }) } + +/** Every pick on one custom provider's image models, for deleting them with + * the provider (a kind is `custom:` and [a-z0-9], so it holds no LIKE + * wildcard). */ +export function picksOnProvider(kind: CustomProviderKind) { + return like(imagePrefs.model, `${customImageModelRef(kind, '')}%`) +} diff --git a/server/mcp.ts b/server/mcp.ts index 116fa8544..c6e5e7d75 100644 --- a/server/mcp.ts +++ b/server/mcp.ts @@ -2085,11 +2085,12 @@ export function buildMcpServer(owner?: string, ownerId?: string, clientName?: st .optional() .describe('square 1024×1024 (default), landscape 1536×1024, portrait 1024×1536 — match the slot'), quality: z.enum(imageGen.IMAGE_QUALITIES).optional().describe('low is fast and cheap; default medium'), + transparent: z.boolean().optional().describe(imageGen.TRANSPARENT_NOTE), canvas_id: z.string().describe('The canvas this image belongs to'), agent_name: agentName, }, }, - async ({ prompt, aspect, quality, canvas_id, agent_name }) => { + async ({ prompt, aspect, quality, transparent, canvas_id, agent_name }) => { if (!canvasFor(canvas_id, 'edit')) return noCanvas(canvas_id) const now = Date.now() const limitKey = ownerId ?? agent_name @@ -2098,14 +2099,15 @@ export function buildMcpServer(owner?: string, ownerId?: string, clientName?: st hits.push(now) generateHits.set(limitKey, hits) try { - const image = await imageGen.generateImage(ownerId, { prompt, aspect, quality }) + const image = await imageGen.generateImage(ownerId, { prompt, aspect, quality, transparent }) const asset = await assets.createAsset(image.buf, { canvasId: canvas_id, ownerId, uploadedBy: agent_name }) const url = `${env.BETTER_AUTH_URL}/a/${asset.id}.${asset.ext}` capture(ownerId ?? agent_name, 'image_generated', { canvas_id, aspect, quality, - billed_to: image.billedTo, + /* a custom provider's name is its person's or admin's, not an analytics value */ + billed_to: image.custom ? `custom-${image.custom}` : image.billedTo, }) const result = { content: [ @@ -2120,6 +2122,7 @@ export function buildMcpServer(owner?: string, ownerId?: string, clientName?: st mime: asset.mime, size_bytes: asset.size, billed_to: image.billedTo, + ...(transparent ? { transparent: image.transparent } : {}), usage: ``, }, null, diff --git a/server/modelAccounts.ts b/server/modelAccounts.ts index 66c859d3d..a5e74aefd 100644 --- a/server/modelAccounts.ts +++ b/server/modelAccounts.ts @@ -4,7 +4,8 @@ import http from 'node:http' import { createHash, randomBytes, timingSafeEqual } from 'node:crypto' import { and, asc, eq, like, sql } from 'drizzle-orm' import { db } from './db/index.ts' -import { modelAccounts } from './db/schema.ts' +import { imagePrefs, modelAccounts } from './db/schema.ts' +import { picksOnProvider } from './imagePrefs.ts' import { DEEPSEEK_MODELS, DEFAULT_ANTHROPIC_MODEL, @@ -313,6 +314,7 @@ export function statusOf(account: ModelAccount): AccountStatus { apiType: account.custom.apiType, baseUrl: sharedBaseUrl(account.custom.baseUrl), models: account.custom.models, + ...(account.custom.imageModels ? { imageModels: account.custom.imageModels } : {}), headerNames: [], hasKey: Boolean(account.apiKey), }, @@ -544,7 +546,16 @@ async function save(account: Omit): Pro export async function disconnect(userId: string, kind: AccountKind): Promise { if (await isSharedKind(kind)) throw new SharedAccountError() - await db.delete(modelAccounts).where(and(eq(modelAccounts.userId, userId), eq(modelAccounts.kind, kind))) + const account = and(eq(modelAccounts.userId, userId), eq(modelAccounts.kind, kind)) + if (!isCustomProviderKind(kind)) { + await db.delete(modelAccounts).where(account) + return + } + /* a custom provider takes the image model picked on it along */ + await db.transaction(async (tx) => { + await tx.delete(modelAccounts).where(account) + await tx.delete(imagePrefs).where(and(eq(imagePrefs.userId, userId), picksOnProvider(kind))) + }) } /** What a ChatGPT token refresh changes on the account. */ diff --git a/server/resident.ts b/server/resident.ts index 1e46bba21..1dd56b55c 100644 --- a/server/resident.ts +++ b/server/resident.ts @@ -1516,6 +1516,7 @@ const TOOLS: Anthropic.Tool[] = [ enum: [...imageGen.IMAGE_QUALITIES], description: 'low is fast and cheap; default medium', }, + transparent: { type: 'boolean', description: imageGen.TRANSPARENT_NOTE }, }, required: ['prompt'], }, @@ -2360,7 +2361,7 @@ async function runResidentTool( return ok(blocks) } case 'generate_image': { - const raw = block.input as { prompt?: string; aspect?: string; quality?: string } + const raw = block.input as { prompt?: string; aspect?: string; quality?: string; transparent?: unknown } const prompt = String(raw.prompt || '').trim() if (!prompt) return fail('prompt must be a non-empty string') if (runState.imagesGenerated >= MAX_IMAGES_PER_RUN) { @@ -2374,7 +2375,8 @@ async function runResidentTool( const quality = (imageGen.IMAGE_QUALITIES as readonly string[]).includes(String(raw.quality)) ? (raw.quality as imageGen.ImageQuality) : undefined - const image = await imageGen.generateImage(runState.payerId, { prompt, aspect, quality }) + const transparent = raw.transparent === true + const image = await imageGen.generateImage(runState.payerId, { prompt, aspect, quality, transparent }) const asset = await assets.createAsset(image.buf, { canvasId, ...(runState.payerId ? { ownerId: runState.payerId } : {}), @@ -2388,7 +2390,7 @@ async function runResidentTool( { type: 'image', source: { type: 'base64', media_type: image.preview.mime, data: image.preview.data } }, { type: 'text', - text: `Generated ${image.width}×${image.height} (${asset.mime}, billed to ${image.billedTo}) — preview above, judge it before embedding.\nurl: ${url}\nusage: `, + text: `Generated ${image.width}×${image.height} (${asset.mime}, billed to ${image.billedTo}${transparent ? (image.transparent ? ', transparent background' : ', opaque: this image model cannot draw a transparent background') : ''}) — preview above, judge it before embedding.\nurl: ${url}\nusage: `, }, ]) } diff --git a/server/sharedModelAccounts.ts b/server/sharedModelAccounts.ts index f8d9c7507..2ea684ed7 100644 --- a/server/sharedModelAccounts.ts +++ b/server/sharedModelAccounts.ts @@ -1,7 +1,8 @@ import { randomBytes } from 'node:crypto' import { and, asc, eq, sql } from 'drizzle-orm' import { db } from './db/index.ts' -import { sharedModelAccountPrefs, sharedModelAccounts } from './db/schema.ts' +import { imagePrefs, sharedModelAccountPrefs, sharedModelAccounts } from './db/schema.ts' +import { picksOnProvider } from './imagePrefs.ts' import { open } from './secretBox.ts' import { isReasoningEffort, type ReasoningEffort } from '../shared/modelMenu.ts' import { @@ -298,7 +299,8 @@ export async function setSharedProviderEnabled( if (!written.length) throw new SharedProviderError('That shared provider no longer exists', 404) } -/** Remove a shared provider, and every person's settings on it. */ +/** Remove a shared provider, and every person's settings on it, the image + * model they picked on it included. */ export async function deleteSharedProvider(kind: CustomProviderKind): Promise { return db.transaction(async (tx) => { const deleted = await tx @@ -306,6 +308,7 @@ export async function deleteSharedProvider(kind: CustomProviderKind): Promise 0 }) } diff --git a/shared/customProvider.ts b/shared/customProvider.ts index a6c76568d..53c2aee84 100644 --- a/shared/customProvider.ts +++ b/shared/customProvider.ts @@ -11,6 +11,11 @@ * stripped for one that does not, rather than failing the first visual * review) and how many tokens it may write per turn. * + * A Chat Completions provider can also list image models, which the agents' + * generate_image draws with through the endpoint's OpenAI Images API + * (`POST {baseUrl}/images/generations`, server/imageGen.ts). They sit apart + * from the chat models: an image model never drives the agent. + * * This module is the one validator both the server and the Settings form * use; the server re-checks everything it is sent. */ @@ -45,6 +50,17 @@ export interface CustomModel { maxOutputTokens?: number } +/** An image model on a custom provider, drawn with through + * `POST {baseUrl}/images/generations`. */ +export interface CustomImageModel { + /** the id the endpoint is sent */ + id: string + /** what the image-model picker shows; the id when unset */ + name?: string + /** the endpoint honours `background: "transparent"` for this model */ + transparent?: boolean +} + /** What a custom provider is, as stored and as Settings shows it. The key * and the extra headers are kept apart (sealed) and never sent back. */ export interface CustomProviderConfig { @@ -57,10 +73,14 @@ export interface CustomProviderConfig { /** Chat Completions only: send earlier turns' `reasoning_content` back, * which DeepSeek- and Kimi-style servers refuse to run without */ echoReasoning?: boolean + /** Chat Completions only: the models generate_image may draw with; a + * description stored before these existed has none */ + imageModels?: CustomImageModel[] } export const MAX_CUSTOM_PROVIDERS = 10 export const MAX_CUSTOM_MODELS = 50 +export const MAX_CUSTOM_IMAGE_MODELS = 20 export const MAX_CUSTOM_HEADERS = 10 const MAX_NAME = 60 const MAX_URL = 500 @@ -143,6 +163,43 @@ function parseModel(value: unknown, index: number): Parsed { } } +function parseImageModel(value: unknown, index: number): Parsed { + if (!value || typeof value !== 'object') return fail(`Image model ${index + 1} is not valid`) + const { id, name, transparent } = value as Record + const modelId = typeof id === 'string' ? id.trim() : '' + if (!MODEL_ID.test(modelId)) { + return fail(`Image model ${index + 1} needs an id without spaces (at most 120 characters)`) + } + const label = typeof name === 'string' ? name.trim() : '' + if (label.length > MAX_NAME) return fail(`The name of ${modelId} is too long`) + return { + ok: true, + value: { + id: modelId, + ...(label && label !== modelId ? { name: label } : {}), + ...(transparent === true ? { transparent: true } : {}), + }, + } +} + +/** The image models a description lists: none when the field is absent, as + * on every description stored before image models existed. */ +function parseImageModels(value: unknown): Parsed { + if (value === undefined || value === null) return { ok: true, value: [] } + if (!Array.isArray(value)) return fail('Image models must be a list') + if (value.length > MAX_CUSTOM_IMAGE_MODELS) { + return fail(`A provider can list at most ${MAX_CUSTOM_IMAGE_MODELS} image models`) + } + const models: CustomImageModel[] = [] + for (const [index, entry] of value.entries()) { + const model = parseImageModel(entry, index) + if (!model.ok) return model + if (models.some((m) => m.id === model.value.id)) return fail(`${model.value.id} is listed twice as an image model`) + models.push(model.value) + } + return { ok: true, value: models } +} + /** A provider's description as the Settings form sends it. */ export function parseCustomProviderConfig(value: unknown): Parsed { if (!value || typeof value !== 'object') return fail('Fill in the provider') @@ -164,6 +221,9 @@ export function parseCustomProviderConfig(value: unknown): Parsed param === body.tokenParam) + /* the Images API is OpenAI's: an Anthropic-compatible endpoint has none */ + const imageModels = apiType === 'openai-chat' ? parseImageModels(body.imageModels) : { ok: true as const, value: [] } + if (!imageModels.ok) return imageModels return { ok: true, value: { @@ -173,10 +233,30 @@ export function parseCustomProviderConfig(value: unknown): Parsed/`. A + * registry id never starts with `custom:`, and a kind never holds a `/`, so + * the first `/` splits it even when the model id has its own. + */ +export function customImageModelRef(kind: CustomProviderKind, modelId: string): string { + return `${kind}/${modelId}` +} + +const IMAGE_MODEL_REF = /^(custom:[a-z0-9]{8,32})\/(\S{1,120})$/ + +export function parseCustomImageModelRef(value: unknown): { kind: CustomProviderKind; model: string } | null { + if (typeof value !== 'string') return null + const match = IMAGE_MODEL_REF.exec(value) + if (!match || !isCustomProviderKind(match[1])) return null + return { kind: match[1], model: match[2]! } +} + /** Extra request headers, as `{ name: value }`. */ export function parseCustomHeaders(value: unknown): Parsed> { if (value === undefined || value === null) return { ok: true, value: {} } diff --git a/tests/customProvider.test.ts b/tests/customProvider.test.ts index c77e26222..6c0289815 100644 --- a/tests/customProvider.test.ts +++ b/tests/customProvider.test.ts @@ -3,10 +3,13 @@ import http from 'node:http' import type { AddressInfo } from 'node:net' import type Anthropic from '@anthropic-ai/sdk' import { + MAX_CUSTOM_IMAGE_MODELS, + customImageModelRef, headersFromText, isCustomProviderKind, normalizeBaseUrl, parseCustomHeaders, + parseCustomImageModelRef, parseCustomKey, parseCustomProviderConfig, } from '../shared/customProvider.ts' @@ -119,6 +122,87 @@ describe('redactSecrets', () => { }) }) +describe('a provider’s image models', () => { + const base = { + name: 'Acme', + apiType: 'openai-chat', + baseUrl: 'https://llm.acme.example/v1', + models: [{ id: 'qwen3-coder', vision: true }], + } + + it('keeps a description stored before image models existed valid, and adds nothing to it', () => { + const parsed = parseCustomProviderConfig(base) + expect(parsed.ok).toBe(true) + expect(parsed.ok && parsed.value).not.toHaveProperty('imageModels') + /* an empty list is stored as no list, the same shape */ + const empty = parseCustomProviderConfig({ ...base, imageModels: [] }) + expect(empty.ok && empty.value).not.toHaveProperty('imageModels') + }) + + it('normalises each one: a trimmed id, a name only when it says more, transparent only when true', () => { + const parsed = parseCustomProviderConfig({ + ...base, + imageModels: [ + { id: ' flux-dev ', name: ' FLUX.1 dev ', transparent: true }, + { id: 'black-forest-labs/FLUX.1-schnell', name: 'black-forest-labs/FLUX.1-schnell', transparent: 'yes' }, + { id: 'sdxl', name: '' }, + ], + }) + expect(parsed.ok && parsed.value.imageModels).toEqual([ + { id: 'flux-dev', name: 'FLUX.1 dev', transparent: true }, + { id: 'black-forest-labs/FLUX.1-schnell' }, + { id: 'sdxl' }, + ]) + /* the chat models are untouched by them */ + expect(parsed.ok && parsed.value.models).toEqual([{ id: 'qwen3-coder', vision: true }]) + }) + + it('lets one id be a chat model and an image model at once', () => { + const parsed = parseCustomProviderConfig({ ...base, imageModels: [{ id: 'qwen3-coder' }] }) + expect(parsed.ok && parsed.value.imageModels).toEqual([{ id: 'qwen3-coder' }]) + }) + + it('drops them from an Anthropic-compatible provider, which has no Images API', () => { + const parsed = parseCustomProviderConfig({ ...base, apiType: 'anthropic', imageModels: [{ id: 'flux-dev' }] }) + expect(parsed.ok).toBe(true) + expect(parsed.ok && parsed.value).not.toHaveProperty('imageModels') + }) + + it.each([ + [{ imageModels: 'flux-dev' }, 'must be a list'], + [{ imageModels: [{ id: 'has space' }] }, 'Image model 1 needs an id without spaces'], + [{ imageModels: [{ id: '' }] }, 'Image model 1 needs an id'], + [{ imageModels: [{ id: 'x'.repeat(121) }] }, 'at most 120 characters'], + [{ imageModels: [null] }, 'Image model 1 is not valid'], + [{ imageModels: [{ id: 'flux' }, { id: 'flux' }] }, 'listed twice as an image model'], + [{ imageModels: [{ id: 'flux', name: 'n'.repeat(61) }] }, 'too long'], + [ + { imageModels: Array.from({ length: MAX_CUSTOM_IMAGE_MODELS + 1 }, (_, i) => ({ id: `m${i}` })) }, + `at most ${MAX_CUSTOM_IMAGE_MODELS} image models`, + ], + ])('refuses %j', (patch, message) => { + const parsed = parseCustomProviderConfig({ ...base, ...patch }) + expect(parsed.ok).toBe(false) + expect(!parsed.ok && parsed.error).toContain(message) + }) + + it('takes exactly the cap', () => { + const imageModels = Array.from({ length: MAX_CUSTOM_IMAGE_MODELS }, (_, i) => ({ id: `m${i}` })) + const parsed = parseCustomProviderConfig({ ...base, imageModels }) + expect(parsed.ok && parsed.value.imageModels).toHaveLength(MAX_CUSTOM_IMAGE_MODELS) + }) + + it('names one in the image-model preference by its provider and id, a slash in the id included', () => { + const kind = 'custom:0123456789abcdef01' + const ref = customImageModelRef(kind, 'black-forest-labs/FLUX.1-dev') + expect(ref).toBe('custom:0123456789abcdef01/black-forest-labs/FLUX.1-dev') + expect(parseCustomImageModelRef(ref)).toEqual({ kind, model: 'black-forest-labs/FLUX.1-dev' }) + for (const value of ['gpt-image-2', 'custom:0123456789abcdef01', 'custom:short/flux', 'custom:../x/flux', 42]) { + expect(parseCustomImageModelRef(value)).toBeNull() + } + }) +}) + describe('which URLs the server may reach', () => { afterEach(unstubAllEnvs) diff --git a/tests/customProviderImages.test.ts b/tests/customProviderImages.test.ts new file mode 100644 index 000000000..0a18fef80 --- /dev/null +++ b/tests/customProviderImages.test.ts @@ -0,0 +1,450 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import sharp from 'sharp' +import { stubEnv, unstubAllEnvs } from './envStub.ts' +import type { ModelAccount } from '../server/modelAccounts.ts' + +/** + * A custom provider's image models (personal or an admin's shared one): which + * one generate_image picks, that it draws through the provider's own Images + * API on the provider's key and headers, and that nothing else (a server key, + * another connection) ever stands in for one. The HTTP side is in + * customProviderImagesHttp.test.ts. + */ + +vi.mock('../server/modelAccounts.ts', () => ({ + getAccounts: vi.fn(), + withFreshToken: vi.fn((account: unknown) => Promise.resolve(account)), +})) +vi.mock('../server/imagePrefs.ts', () => ({ + getImagePref: vi.fn(() => Promise.resolve(undefined)), +})) + +import { getAccounts } from '../server/modelAccounts.ts' +import { getImagePref } from '../server/imagePrefs.ts' +import { generateImage, generatorFor, imageModelAvailability } from '../server/imageGen.ts' +import { customImageModelRef } from '../shared/customProvider.ts' + +const mockedGetAccounts = vi.mocked(getAccounts) +const mockedGetImagePref = vi.mocked(getImagePref) + +const STUDIO = 'custom:aaaaaaaa11111111' +const GATEWAY = 'custom:bbbbbbbb22222222' +const PERSONAL_KEY = 'sk-personal-never-shown' +const SHARED_KEY = 'sk-shared-never-shown' + +const personal = (patch: Partial = {}): ModelAccount => ({ + userId: 'u1', + kind: STUDIO, + enabled: true, + connectedAt: 1, + apiKey: PERSONAL_KEY, + headers: { 'X-Tenant': 'design' }, + custom: { + name: 'Studio FLUX', + apiType: 'openai-chat', + baseUrl: 'https://img.studio.example/v1', + models: [{ id: 'qwen3-coder', vision: true }], + imageModels: [{ id: 'flux-dev', name: 'FLUX dev', transparent: true }, { id: 'sdxl' }], + }, + ...patch, +}) + +const shared = (patch: Partial = {}): ModelAccount => ({ + userId: 'u1', + kind: GATEWAY, + enabled: true, + connectedAt: 2, + apiKey: SHARED_KEY, + custom: { + name: 'Acme Gateway', + apiType: 'openai-chat', + baseUrl: 'https://llm.acme.example/team/v1', + models: [{ id: 'glm-5', vision: false }], + imageModels: [{ id: 'flux-schnell' }], + }, + shared: true, + ...patch, +}) + +async function png(alpha = false): Promise { + return sharp({ + create: { width: 8, height: 6, channels: 4, background: alpha ? { r: 0, g: 0, b: 0, alpha: 0 } : '#e5533c' }, + }) + .png() + .toBuffer() +} + +async function imagesResponse(given?: unknown) { + const data = given ?? [{ b64_json: (await png()).toString('base64') }] + return new Response(JSON.stringify({ created: 1, data }), { + status: 200, + headers: { 'content-type': 'application/json' }, + }) +} + +const headersOf = (init: RequestInit | undefined) => new Headers(init?.headers as HeadersInit) + +beforeEach(() => { + /* the fake endpoints are not resolved: fetch is stubbed, and the private + hosts switch keeps customProviderFetch on the global fetch */ + stubEnv('DOOP_CUSTOM_PROVIDER_PRIVATE_HOSTS', 'true') +}) +afterEach(() => { + vi.restoreAllMocks() + mockedGetAccounts.mockReset() + mockedGetImagePref.mockReset() + mockedGetImagePref.mockResolvedValue(undefined) + unstubAllEnvs() +}) + +describe('drawing on a personal custom provider', () => { + it('posts the Images API request to the provider with its key and headers, billed to it', async () => { + mockedGetAccounts.mockResolvedValue([personal()]) + mockedGetImagePref.mockResolvedValue(customImageModelRef(STUDIO, 'flux-dev')) + const fetchSpy = vi + .spyOn(globalThis, 'fetch') + .mockResolvedValue(await imagesResponse([{ b64_json: (await png(true)).toString('base64') }])) + + const image = await generateImage('u1', { prompt: 'a red circle', aspect: 'landscape', transparent: true }) + + expect(fetchSpy).toHaveBeenCalledTimes(1) + const [url, init] = fetchSpy.mock.calls[0]! + expect(String(url)).toBe('https://img.studio.example/v1/images/generations') + expect(init!.method).toBe('POST') + /* no redirects: the guarded fetch path, as for the provider's chat turns */ + expect(init!.redirect).toBe('error') + const headers = headersOf(init) + expect(headers.get('authorization')).toBe(`Bearer ${PERSONAL_KEY}`) + expect(headers.get('x-tenant')).toBe('design') + expect(JSON.parse(String(init!.body))).toEqual({ + model: 'flux-dev', + prompt: 'a red circle', + n: 1, + size: '1536x1024', + quality: 'medium', + output_format: 'png', + background: 'transparent', + }) + expect(image).toMatchObject({ billedTo: 'Studio FLUX', custom: 'personal', transparent: true, mime: 'image/webp' }) + }) + + it('keeps a cut-out’s alpha in the stored image', async () => { + mockedGetAccounts.mockResolvedValue([personal()]) + mockedGetImagePref.mockResolvedValue(customImageModelRef(STUDIO, 'flux-dev')) + vi.spyOn(globalThis, 'fetch').mockResolvedValue( + await imagesResponse([{ b64_json: (await png(true)).toString('base64') }]), + ) + const image = await generateImage('u1', { prompt: 'a mascot', transparent: true }) + expect((await sharp(image.buf).metadata()).hasAlpha).toBe(true) + expect(image.preview.mime).toBe('image/jpeg') + }) + + it('reports what was drawn: an opaque answer to a cut-out request is not transparent', async () => { + mockedGetAccounts.mockResolvedValue([personal()]) + mockedGetImagePref.mockResolvedValue(customImageModelRef(STUDIO, 'flux-dev')) + const opaque = await sharp({ create: { width: 8, height: 8, channels: 3, background: '#e5533c' } }) + .png() + .toBuffer() + vi.spyOn(globalThis, 'fetch').mockResolvedValue(await imagesResponse([{ b64_json: opaque.toString('base64') }])) + expect((await generateImage('u1', { prompt: 'x', transparent: true })).transparent).toBe(false) + /* an alpha channel that is opaque everywhere is no cut-out either */ + vi.spyOn(globalThis, 'fetch').mockResolvedValue(await imagesResponse()) + expect((await generateImage('u1', { prompt: 'x', transparent: true })).transparent).toBe(false) + }) + + it('asks for no transparent background from a model that cannot draw one', async () => { + mockedGetAccounts.mockResolvedValue([personal()]) + mockedGetImagePref.mockResolvedValue(customImageModelRef(STUDIO, 'sdxl')) + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(await imagesResponse()) + + const image = await generateImage('u1', { prompt: 'a mascot', transparent: true, quality: 'low' }) + + const body = JSON.parse(String(fetchSpy.mock.calls[0]![1]!.body)) as Record + expect(body).not.toHaveProperty('background') + expect(body).toMatchObject({ model: 'sdxl', size: '1024x1024', quality: 'low' }) + expect(image.transparent).toBe(false) + }) + + it('sends no Authorization at all to an endpoint that takes no key', async () => { + mockedGetAccounts.mockResolvedValue([personal({ apiKey: undefined, headers: undefined })]) + mockedGetImagePref.mockResolvedValue(customImageModelRef(STUDIO, 'sdxl')) + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(await imagesResponse()) + await generateImage('u1', { prompt: 'x' }) + expect(headersOf(fetchSpy.mock.calls[0]![1]).has('authorization')).toBe(false) + }) + + it('keeps a registry pick on the registry when the person also has image models of their own', async () => { + mockedGetAccounts.mockResolvedValue([ + personal(), + { enabled: true, userId: 'u1', kind: 'openai-key', apiKey: 'sk-openai', connectedAt: 3 }, + ]) + mockedGetImagePref.mockResolvedValue('gpt-image-2.5-flare') + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(await imagesResponse()) + const image = await generateImage('u1', { prompt: 'x' }) + expect(String(fetchSpy.mock.calls[0]![0])).toBe('https://api.openai.com/v1/images/generations') + expect(image.billedTo).toBe('OpenAI') + expect(image.custom).toBeUndefined() + }) +}) + +describe('drawing on a shared provider', () => { + it('is where someone with nothing of their own draws by default, on the company’s endpoint, never the server key', async () => { + stubEnv('OPENAI_API_KEY', 'sk-server-paid') + stubEnv('GEMINI_API_KEY', 'gm-server-paid') + mockedGetAccounts.mockResolvedValue([shared()]) + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(await imagesResponse()) + + const image = await generateImage('u1', { prompt: 'a hero backdrop', aspect: 'portrait' }) + + expect(fetchSpy).toHaveBeenCalledTimes(1) + const [url, init] = fetchSpy.mock.calls[0]! + expect(String(url)).toBe('https://llm.acme.example/team/v1/images/generations') + expect(headersOf(init).get('authorization')).toBe(`Bearer ${SHARED_KEY}`) + expect(JSON.parse(String(init!.body))).toMatchObject({ model: 'flux-schnell', size: '1024x1536' }) + expect(image).toMatchObject({ billedTo: 'Acme Gateway', custom: 'shared', transparent: false }) + }) + + it('comes before Seedream on the server’s ARK_API_KEY when nothing is picked', async () => { + stubEnv('ARK_API_KEY', 'ark-server-paid') + mockedGetAccounts.mockResolvedValue([shared()]) + expect(await generatorFor('u1')).toMatchObject({ ok: true, label: 'Acme Gateway', custom: 'shared' }) + expect((await imageModelAvailability('u1')).find((model) => model.selected)?.id).toBe(`${GATEWAY}/flux-schnell`) + /* a pick on Seedream still draws Seedream, the operator having opted into paying for it */ + mockedGetImagePref.mockResolvedValue('seedream-5-0-pro') + expect(await generatorFor('u1')).toMatchObject({ ok: true, label: 'server' }) + }) + + it('keeps the person’s own registry account ahead of their custom image models, and both ahead of Seedream', async () => { + stubEnv('ARK_API_KEY', 'ark-server-paid') + stubEnv('DOOP_IMAGE_MODEL', 'seedream-5-0-pro') + mockedGetAccounts.mockResolvedValue([ + shared(), + { enabled: true, userId: 'u1', kind: 'gemini-key', apiKey: 'gm-user', connectedAt: 3 }, + ]) + expect(await generatorFor('u1')).toMatchObject({ ok: true, label: 'Gemini' }) + /* and someone who connected nothing still starts on the server's default */ + mockedGetAccounts.mockResolvedValue([]) + expect(await generatorFor('u1')).toMatchObject({ ok: true, label: 'server' }) + }) + + it('lists its image models, and the person’s own providers’ first, in the picker’s availability', async () => { + mockedGetAccounts.mockResolvedValue([personal(), shared()]) + mockedGetImagePref.mockResolvedValue(customImageModelRef(GATEWAY, 'flux-schnell')) + + const models = await imageModelAvailability('u1') + + expect(models.filter((m) => m.custom)).toEqual([ + { + id: `${STUDIO}/flux-dev`, + available: true, + selected: false, + custom: { provider: 'Studio FLUX', name: 'FLUX dev', transparent: true }, + }, + { id: `${STUDIO}/sdxl`, available: true, selected: false, custom: { provider: 'Studio FLUX', name: 'sdxl' } }, + { + id: `${GATEWAY}/flux-schnell`, + available: true, + selected: true, + custom: { provider: 'Acme Gateway', name: 'flux-schnell', shared: true }, + }, + ]) + /* the registry is all there still, nothing of it selected */ + expect(models.filter((m) => !m.custom).every((m) => !m.selected)).toBe(true) + /* and never the key */ + expect(JSON.stringify(models)).not.toContain(SHARED_KEY) + }) + + it('says to ask the admin when the endpoint turns the shared key down', async () => { + mockedGetAccounts.mockResolvedValue([shared()]) + vi.spyOn(globalThis, 'fetch').mockResolvedValue(new Response('{"error":"bad key"}', { status: 401 })) + const failure = generateImage('u1', { prompt: 'x' }) + await expect(failure).rejects.toThrow( + /Acme Gateway turned down the shared connection your admin set up \(401\)\. Ask your admin to check it in Admin → Shared models/, + ) + await expect(failure).rejects.not.toThrow(/reconnect|server/) + }) + + it('masks the shared key and header values in whatever the endpoint says back', async () => { + const SECRET_HEADER = 'tenant-secret-never-shown' + mockedGetAccounts.mockResolvedValue([shared({ headers: { 'X-Tenant': SECRET_HEADER } })]) + const answers = [ + new Response(`{"error":{"message":"Invalid params for key ${SHARED_KEY} (${SECRET_HEADER})"}}`, { status: 400 }), + new Response(`rate limit for ${SHARED_KEY}`, { status: 429 }), + new Response(JSON.stringify({ error: { message: `quota of ${SHARED_KEY} exceeded` } }), { status: 200 }), + new Response(`no such model for key ${SHARED_KEY}`, { status: 404 }), + ] + for (const answer of answers) { + vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(answer) + const failure = await generateImage('u1', { prompt: 'x' }).catch((error: Error) => error) + expect(failure).toBeInstanceOf(Error) + const said = JSON.stringify(failure, Object.getOwnPropertyNames(failure)) + expect(said).not.toContain(SHARED_KEY) + expect(said).not.toContain(SECRET_HEADER) + expect((failure as Error).cause).toBeUndefined() + } + }) + + it('masks a key that straddles where the endpoint’s text is cut, at either end of the key', async () => { + mockedGetAccounts.mockResolvedValue([shared()]) + /* a refusal body is cut at 400 characters (responseError), an error + beside a 200 at 300; the key starts just before each cut, then ends + just after it */ + const answers = (cut: number, before: number) => + cut === 400 + ? new Response(`${'x'.repeat(before)}${SHARED_KEY} trailing`, { status: 400 }) + : new Response(JSON.stringify({ error: { message: `${'x'.repeat(before)}${SHARED_KEY} trailing` } }), { + status: 200, + }) + for (const cut of [400, 300]) { + for (const before of [cut - 1, cut - SHARED_KEY.length + 1]) { + vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(answers(cut, before)) + const failure = await generateImage('u1', { prompt: 'x' }).catch((error: Error) => error) + expect((failure as Error).message).toMatch(/x\*/) + expect((failure as Error).message).not.toMatch(/sk-|xs(\W|$)/) + } + } + }) + + it('says to ask the admin when the endpoint has no such image model', async () => { + mockedGetAccounts.mockResolvedValue([shared()]) + vi.spyOn(globalThis, 'fetch').mockResolvedValue( + new Response('{"error":{"message":"model flux-schnell not found"}}', { status: 404 }), + ) + await expect(generateImage('u1', { prompt: 'x' })).rejects.toThrow( + /Acme Gateway cannot draw with flux-schnell \(404\).*Ask your admin/, + ) + }) +}) + +describe('a custom image model that cannot run', () => { + it('refuses when its provider is switched off, rather than drawing on another connection or the server', async () => { + stubEnv('OPENAI_API_KEY', 'sk-server-paid') + mockedGetAccounts.mockResolvedValue([ + personal({ enabled: false }), + { enabled: true, userId: 'u1', kind: 'gemini-key', apiKey: 'gm-user', connectedAt: 3 }, + ]) + mockedGetImagePref.mockResolvedValue(customImageModelRef(STUDIO, 'flux-dev')) + const fetchSpy = vi.spyOn(globalThis, 'fetch') + + const generator = await generatorFor('u1') + + expect(generator.ok).toBe(false) + expect(!generator.ok && generator.reason).toMatch( + /flux-dev on Studio FLUX is not available: the person’s Studio FLUX connection is switched off/, + ) + await expect(generateImage('u1', { prompt: 'x' })).rejects.toThrow(/switched off/) + expect(fetchSpy).not.toHaveBeenCalled() + }) + + it('names the switched-off provider when it was the only thing that could draw, and the server key stays out', async () => { + stubEnv('OPENAI_API_KEY', 'sk-server-paid') + mockedGetAccounts.mockResolvedValue([personal({ enabled: false })]) + const generator = await generatorFor('u1') + expect(generator.ok).toBe(false) + expect(!generator.ok && generator.reason).toMatch(/Studio FLUX connection is switched off/) + }) + + it('refuses when the person switched the shared provider off for themselves', async () => { + stubEnv('OPENAI_API_KEY', 'sk-server-paid') + mockedGetAccounts.mockResolvedValue([shared({ enabled: false })]) + mockedGetImagePref.mockResolvedValue(customImageModelRef(GATEWAY, 'flux-schnell')) + expect(await generatorFor('u1')).toMatchObject({ ok: false }) + }) + + it('refuses when the provider is gone (an admin deleted or switched off the shared one)', async () => { + stubEnv('OPENAI_API_KEY', 'sk-server-paid') + mockedGetAccounts.mockResolvedValue([ + { enabled: true, userId: 'u1', kind: 'openai-key', apiKey: 'sk-openai', connectedAt: 3 }, + ]) + mockedGetImagePref.mockResolvedValue(customImageModelRef(GATEWAY, 'flux-schnell')) + const fetchSpy = vi.spyOn(globalThis, 'fetch') + const generator = await generatorFor('u1') + expect(!generator.ok && generator.reason).toMatch( + /flux-schnell\) was on a custom provider that is no longer connected/, + ) + expect(fetchSpy).not.toHaveBeenCalled() + }) + + it('refuses when the provider no longer lists the model', async () => { + mockedGetAccounts.mockResolvedValue([shared()]) + mockedGetImagePref.mockResolvedValue(customImageModelRef(GATEWAY, 'flux-pro')) + const generator = await generatorFor('u1') + expect(!generator.ok && generator.reason).toMatch(/Acme Gateway no longer lists flux-pro as an image model/) + }) + + it('does not count a provider without image models as one that draws', async () => { + stubEnv('OPENAI_API_KEY', 'sk-server-paid') + mockedGetAccounts.mockResolvedValue([shared({ custom: { ...shared().custom!, imageModels: undefined } })]) + const generator = await generatorFor('u1') + expect(!generator.ok && generator.reason).toMatch(/list image models on a custom provider/) + }) +}) + +describe('what the endpoint answers', () => { + beforeEach(() => { + mockedGetAccounts.mockResolvedValue([personal()]) + mockedGetImagePref.mockResolvedValue(customImageModelRef(STUDIO, 'sdxl')) + }) + + it('fetches an image it links to on its own origin with its credentials', async () => { + const fetchSpy = vi + .spyOn(globalThis, 'fetch') + .mockResolvedValueOnce(await imagesResponse([{ url: '/files/out.png' }])) + .mockResolvedValueOnce(new Response(new Uint8Array(await png()))) + const image = await generateImage('u1', { prompt: 'x' }) + expect(image.width).toBe(8) + const [url, init] = fetchSpy.mock.calls[1]! + expect(String(url)).toBe('https://img.studio.example/files/out.png') + expect(init!.redirect).toBe('error') + expect(headersOf(init).get('authorization')).toBe(`Bearer ${PERSONAL_KEY}`) + }) + + it('fetches an image it links to elsewhere without them', async () => { + const fetchSpy = vi + .spyOn(globalThis, 'fetch') + .mockResolvedValueOnce(await imagesResponse([{ url: 'https://cdn.elsewhere.example/out.png?sig=1' }])) + .mockResolvedValueOnce(new Response(new Uint8Array(await png()))) + await generateImage('u1', { prompt: 'x' }) + const headers = headersOf(fetchSpy.mock.calls[1]![1]) + expect(headers.has('authorization')).toBe(false) + expect(headers.has('x-tenant')).toBe(false) + }) + + it('refuses a link that does not point at an image, or no image at all', async () => { + vi.spyOn(globalThis, 'fetch') + .mockResolvedValueOnce(await imagesResponse([{ url: 'https://cdn.elsewhere.example/out.png' }])) + .mockResolvedValueOnce(new Response('sign in')) + await expect(generateImage('u1', { prompt: 'x' })).rejects.toThrow( + /Studio FLUX returned something that is not a PNG, JPEG or WebP image/, + ) + vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(await imagesResponse([])) + await expect(generateImage('u1', { prompt: 'x' })).rejects.toThrow(/Studio FLUX returned no image/) + }) + + it('passes the endpoint’s own refusal on, and tells a person to fix their key in Settings', async () => { + vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce( + new Response(JSON.stringify({ error: { message: 'prompt blocked by the safety filter' } }), { status: 200 }), + ) + await expect(generateImage('u1', { prompt: 'x' })).rejects.toThrow( + /Studio FLUX did not generate an image: prompt blocked by the safety filter/, + ) + vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(new Response('denied', { status: 403 })) + const failure = generateImage('u1', { prompt: 'x' }) + await expect(failure).rejects.toThrow( + /Studio FLUX rejected the API key \(403\)\. Update it in Settings → Doop Agent/, + ) + await expect(failure).rejects.not.toThrow(new RegExp(PERSONAL_KEY)) + }) + + it('reaches private hosts only when the operator allows them', async () => { + unstubAllEnvs() + mockedGetAccounts.mockResolvedValue([ + personal({ custom: { ...personal().custom!, baseUrl: 'http://127.0.0.1:7860/v1' } }), + ]) + const fetchSpy = vi.spyOn(globalThis, 'fetch') + await expect(generateImage('u1', { prompt: 'x' })).rejects.toThrow( + /Studio FLUX could not be reached: The base URL must start with https:\/\//, + ) + expect(fetchSpy).not.toHaveBeenCalled() + }) +}) diff --git a/tests/customProviderImagesHttp.test.ts b/tests/customProviderImagesHttp.test.ts new file mode 100644 index 000000000..be7fc87d4 --- /dev/null +++ b/tests/customProviderImagesHttp.test.ts @@ -0,0 +1,318 @@ +import { afterAll, beforeAll, describe, expect, it } from 'vitest' +import http from 'node:http' +import type { AddressInfo } from 'node:net' +import sharp from 'sharp' +import { Client, startServer, type Server } from './harness' + +/** + * A custom provider's image models end to end, against the real server and a + * fake OpenAI Images endpoint on loopback (which needs the operator's + * private-hosts switch): an admin lists image models on a shared provider, + * every person finds them in the image-model picker, and generate_image draws + * through the endpoint on the provider's key, which no response ever carries. + * A person can neither change those image models nor borrow the key. A + * personal provider's image models work the same way for their person. + */ + +let server: Server +let boss: Client +let alice: Client +let bob: Client +let endpoint: http.Server +let base = '' +let png = '' +/* what the endpoint draws when asked for a transparent background */ +let cutOut = '' +/* what the endpoint answers next: an image, or a refusal */ +let answer: 'image' | 'refuse' = 'image' +const seen: { url: string; authorization?: string; body?: Record }[] = [] +/* every response body any test read, checked for the secrets at the end */ +const bodies: string[] = [] + +const KEY = 'sk-images-shared-never-echoed' +const BOB_KEY = 'sk-images-bob-never-echoed' + +beforeAll(async () => { + png = ( + await sharp({ create: { width: 16, height: 12, channels: 4, background: '#2b6cb0' } }) + .png() + .toBuffer() + ).toString('base64') + cutOut = ( + await sharp({ create: { width: 16, height: 12, channels: 4, background: { r: 0, g: 0, b: 0, alpha: 0 } } }) + .png() + .toBuffer() + ).toString('base64') + endpoint = http.createServer((req, res) => { + let raw = '' + req.on('data', (chunk: Buffer) => (raw += chunk.toString())) + req.on('end', () => { + seen.push({ + url: req.url ?? '', + ...(req.headers.authorization ? { authorization: req.headers.authorization } : {}), + ...(raw ? { body: JSON.parse(raw) as Record } : {}), + }) + if (req.url?.endsWith('/models')) { + res.writeHead(200, { 'Content-Type': 'application/json' }) + return res.end(JSON.stringify({ data: [{ id: 'qwen3-coder' }, { id: 'flux-schnell' }] })) + } + if (req.url?.endsWith('/images/generations')) { + if (answer === 'refuse') { + res.writeHead(401, { 'Content-Type': 'application/json' }) + return res.end(JSON.stringify({ error: { message: 'invalid key' } })) + } + const transparent = (JSON.parse(raw) as { background?: string }).background === 'transparent' + res.writeHead(200, { 'Content-Type': 'application/json' }) + return res.end(JSON.stringify({ created: 1, data: [{ b64_json: transparent ? cutOut : png }] })) + } + res.writeHead(404) + res.end() + }) + }) + await new Promise((resolve) => endpoint.listen(0, '127.0.0.1', resolve)) + base = `http://127.0.0.1:${(endpoint.address() as AddressInfo).port}/v1` + server = await startServer({ + ANTHROPIC_API_KEY: '', + OPENAI_API_KEY: '', + GEMINI_API_KEY: '', + ARK_API_KEY: '', + DATABASE_URL: '', + SMTP_HOST: '', + ADMIN_EMAILS: 'images-boss@example.test', + DOOP_CUSTOM_PROVIDER_PRIVATE_HOSTS: 'true', + }) + boss = await new Client(server).signUp('images-boss@example.test', 'Boss') + alice = await new Client(server).signUp('images-alice@example.test', 'Alice') + bob = await new Client(server).signUp('images-bob@example.test', 'Bob') +}, 60000) +afterAll(async () => { + await server?.stop() + await new Promise((resolve) => endpoint.close(() => resolve())) +}) + +interface ImageModel { + id: string + available: boolean + selected: boolean + custom?: { provider: string; name: string; shared?: true; transparent?: true } +} +interface AdminView { + providers: { kind: string; custom: { imageModels?: { id: string; transparent?: true }[] } }[] +} + +async function read(response: Response): Promise { + const text = await response.text() + bodies.push(text) + return JSON.parse(text) as T +} +const imageModels = async (client: Client) => + (await read<{ models: ImageModel[] }>(await client.get('/api/image-model'))).models + +/** generate_image over MCP, as the client's own agent key. */ +async function generate(client: Client, args: Record) { + const canvasId = (await read<{ id: string }>(await client.post('/api/canvases', { name: 'Images' }))).id + const secret = (await read<{ secret: string }>(await client.post('/api/agent-keys', { name: 'images-agent' }))).secret + const res = await fetch(`${server.base}/mcp`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + Accept: 'application/json, text/event-stream', + Authorization: `Bearer ${secret}`, + }, + body: JSON.stringify({ + jsonrpc: '2.0', + id: 1, + method: 'tools/call', + params: { name: 'generate_image', arguments: { canvas_id: canvasId, agent_name: 'Tester', ...args } }, + }), + }) + expect(res.status).toBe(200) + const text = await res.text() + bodies.push(text) + const body = JSON.parse(text) as { result: { isError?: boolean; content: { type: string; text?: string }[] } } + return { + isError: !!body.result.isError, + text: body.result.content.map((block) => block.text ?? '').join('\n'), + } +} + +const provider = { + name: 'Acme Images', + apiType: 'openai-chat', + models: [{ id: 'qwen3-coder', vision: true }], + imageModels: [{ id: 'flux-schnell', name: 'FLUX schnell', transparent: true }], +} + +let kind = '' + +describe('a shared provider’s image models', () => { + it('are added and kept by an admin, the key never coming back', async () => { + const created = await read( + await boss.post('/api/admin/shared-providers', { ...provider, baseUrl: base, apiKey: KEY }), + ) + expect(created.providers).toHaveLength(1) + kind = created.providers[0]!.kind + expect(created.providers[0]!.custom.imageModels).toEqual([ + { id: 'flux-schnell', name: 'FLUX schnell', transparent: true }, + ]) + }) + + it('can be filled from the endpoint’s model list', async () => { + const listed = await read<{ models: string[] }>( + await boss.post('/api/admin/shared-providers/models', { apiType: 'openai-chat', baseUrl: base, kind }), + ) + expect(listed.models).toContain('flux-schnell') + }) + + it('are not a person’s to change: the admin routes are not there, and the personal ones refuse', async () => { + const attempt = { ...provider, baseUrl: base, imageModels: [{ id: 'stolen' }] } + expect((await alice.put(`/api/admin/shared-providers/${kind}`, attempt)).status).toBe(404) + expect((await alice.post('/api/admin/shared-providers', attempt)).status).toBe(404) + expect((await alice.put(`/api/custom-providers/${kind}`, attempt)).status).toBe(403) + const view = await read(await boss.get('/api/admin/shared-providers')) + expect(view.providers[0]!.custom.imageModels).toEqual([ + { id: 'flux-schnell', name: 'FLUX schnell', transparent: true }, + ]) + }) + + it('show in everyone’s image-model picker, chosen by default for someone with nothing else that draws', async () => { + const models = await imageModels(alice) + expect(models.find((model) => model.custom)).toEqual({ + id: `${kind}/flux-schnell`, + available: true, + selected: true, + custom: { provider: 'Acme Images', name: 'FLUX schnell', shared: true, transparent: true }, + }) + /* the registry is still there, and nothing on it can run without a key */ + expect(models.filter((model) => !model.custom).every((model) => !model.available)).toBe(true) + /* the person's view of the provider lists them too */ + const accounts = await read<{ accounts: { kind: string; custom?: { imageModels?: unknown[] } }[] }>( + await alice.get('/api/model-account'), + ) + expect(accounts.accounts.find((account) => account.kind === kind)?.custom?.imageModels).toHaveLength(1) + }) + + it('can be picked, while an id no provider of the person lists cannot', async () => { + const picked = await read<{ models: ImageModel[] }>( + await alice.put('/api/image-model', { model: `${kind}/flux-schnell` }), + ) + expect(picked.models.find((model) => model.selected)?.id).toBe(`${kind}/flux-schnell`) + expect((await alice.put('/api/image-model', { model: `${kind}/flux-pro` })).status).toBe(400) + expect((await alice.put('/api/image-model', { model: 'custom:0123456789abcdef01/flux' })).status).toBe(400) + }) + + it('draw through the endpoint on the shared key, billed to the provider', async () => { + seen.length = 0 + const result = await generate(alice, { prompt: 'a blue square', aspect: 'landscape', transparent: true }) + expect(result.isError).toBe(false) + const parsed = JSON.parse(result.text.split('\n\nPreview above')[0]!) as Record + expect(parsed).toMatchObject({ ok: true, billed_to: 'Acme Images', transparent: true, width: 16, height: 12 }) + const call = seen.find((entry) => entry.url.endsWith('/images/generations'))! + expect(call.authorization).toBe(`Bearer ${KEY}`) + expect(call.body).toEqual({ + model: 'flux-schnell', + prompt: 'a blue square', + n: 1, + size: '1536x1024', + quality: 'medium', + output_format: 'png', + background: 'transparent', + }) + /* the stored asset is the image, recompressed */ + const asset = await fetch(String(parsed.url)) + expect(asset.status).toBe(200) + expect(asset.headers.get('content-type')).toContain('image/webp') + }) + + it('tell a person to ask their admin when the endpoint refuses the shared key', async () => { + answer = 'refuse' + try { + const result = await generate(alice, { prompt: 'a blue square' }) + expect(result.isError).toBe(true) + expect(result.text).toMatch(/Acme Images turned down the shared connection your admin set up \(401\)/) + expect(result.text).toContain('Ask your admin') + } finally { + answer = 'image' + } + }) + + it('stop drawing, without a fallback, once the admin switches the provider off', async () => { + expect((await boss.patch(`/api/admin/shared-providers/${kind}`, { enabled: false })).status).toBe(200) + seen.length = 0 + const result = await generate(alice, { prompt: 'a blue square' }) + expect(result.isError).toBe(true) + expect(seen).toHaveLength(0) + expect((await imageModels(alice)).some((model) => model.custom)).toBe(false) + expect((await boss.patch(`/api/admin/shared-providers/${kind}`, { enabled: true })).status).toBe(200) + }) +}) + +describe('a personal provider’s image models', () => { + it('draw for their person on their own key, beside the shared ones', async () => { + const added = await bob.post('/api/custom-providers', { + name: 'Bob Studio', + apiType: 'openai-chat', + baseUrl: base, + apiKey: BOB_KEY, + models: [{ id: 'qwen3-coder', vision: true }], + imageModels: [{ id: 'sdxl' }], + }) + expect(added.status).toBe(200) + bodies.push(await added.text()) + const models = await imageModels(bob) + const own = models.find((model) => model.custom && !model.custom.shared)! + expect(own.custom).toEqual({ provider: 'Bob Studio', name: 'sdxl' }) + /* the person's own come first; the shared one is still offered after them */ + expect(models.filter((model) => model.custom).map((model) => model.custom!.provider)).toEqual([ + 'Bob Studio', + 'Acme Images', + ]) + await read(await bob.put('/api/image-model', { model: own.id })) + + seen.length = 0 + const result = await generate(bob, { prompt: 'a mascot', transparent: true }) + expect(result.isError).toBe(false) + expect(result.text).toContain('"billed_to": "Bob Studio"') + /* sdxl was not said to draw cut-outs: none asked for, none claimed */ + expect(result.text).toContain('"transparent": false') + const call = seen.find((entry) => entry.url.endsWith('/images/generations'))! + expect(call.authorization).toBe(`Bearer ${BOB_KEY}`) + expect(call.body).not.toHaveProperty('background') + /* and nobody else gets them */ + expect((await imageModels(alice)).some((model) => model.custom?.provider === 'Bob Studio')).toBe(false) + }) +}) + +describe('picks on a provider that is gone', () => { + it('go with a personal provider its person disconnects', async () => { + const own = (await imageModels(bob)).find((model) => model.custom?.provider === 'Bob Studio')! + expect(own.selected).toBe(true) + const kindOf = own.id.slice(0, own.id.indexOf('/')) + expect((await bob.delete(`/api/model-account/${kindOf}`)).status).toBe(200) + /* the pick went with it: Bob draws on what is left (the shared provider), + not refused for a pick on a provider that is no longer there */ + const result = await generate(bob, { prompt: 'a mascot' }) + expect(result.isError).toBe(false) + expect(result.text).toContain('"billed_to": "Acme Images"') + }) + + it('go with a shared provider its admin deletes', async () => { + expect((await imageModels(alice)).find((model) => model.selected)?.id).toBe(`${kind}/flux-schnell`) + expect((await boss.delete(`/api/admin/shared-providers/${kind}`)).status).toBe(200) + const result = await generate(alice, { prompt: 'a blue square' }) + expect(result.isError).toBe(true) + /* nothing left to draw with, said as such: no stale pick to blame */ + expect(result.text).toContain('image generation is not available') + expect(result.text).not.toContain('no longer connected') + }) +}) + +describe('the keys', () => { + it('appear in no response', () => { + expect(bodies.length).toBeGreaterThan(10) + for (const body of bodies) { + expect(body).not.toContain(KEY) + expect(body).not.toContain(BOB_KEY) + } + }) +}) diff --git a/tests/sharedModelAccounts.test.ts b/tests/sharedModelAccounts.test.ts index 5b8d176fc..c98c3278e 100644 --- a/tests/sharedModelAccounts.test.ts +++ b/tests/sharedModelAccounts.test.ts @@ -59,7 +59,7 @@ import { } from '../server/modelAccounts.ts' import { readConnections } from '../server/agentDefaults.ts' import { listRunners } from '../server/agentRunners.ts' -import { generatorFor } from '../server/imageGen.ts' +import { generatorFor, imageModelAvailability } from '../server/imageGen.ts' const GATEWAY = 'custom:0123456789abcdef01' const OLD_GATEWAY = 'custom:fedcba98765432100f' @@ -242,4 +242,18 @@ describe('image generation', () => { expect(shared.ok).toBe(false) expect(!shared.ok && shared.reason).toContain('Acme Gateway') }) + + it('draws on a shared provider that lists image models, for everyone, and not once the operator turns custom providers off', async () => { + stubEnv('OPENAI_API_KEY', 'sk-server-paid') + mocks.providers = [{ ...gateway, custom: { ...gateway.custom, imageModels: [{ id: 'flux-schnell' }] } }] + for (const person of ['alice', 'bob']) { + const generator = await generatorFor(person) + expect(generator).toMatchObject({ ok: true, label: 'Acme Gateway', custom: 'shared' }) + expect((await imageModelAvailability(person)).find((model) => model.custom)?.id).toBe(`${GATEWAY}/flux-schnell`) + } + stubEnv('DOOP_CUSTOM_PROVIDERS', 'false') + expect((await imageModelAvailability('alice')).some((model) => model.custom)).toBe(false) + /* with the feature off nobody has a shared provider: as before it existed */ + expect(await generatorFor('alice')).toMatchObject({ ok: true, label: 'server' }) + }) }) diff --git a/tests/sharedModelAccountsStore.test.ts b/tests/sharedModelAccountsStore.test.ts index 5f3feb7aa..79d17174c 100644 --- a/tests/sharedModelAccountsStore.test.ts +++ b/tests/sharedModelAccountsStore.test.ts @@ -29,7 +29,7 @@ vi.mock('../server/db/index.ts', () => { }) import { deleteSharedProvider, listSharedProviders } from '../server/sharedModelAccounts.ts' -import { sharedModelAccountPrefs, sharedModelAccounts } from '../server/db/schema.ts' +import { imagePrefs, sharedModelAccountPrefs, sharedModelAccounts } from '../server/db/schema.ts' const KIND = 'custom:0123456789abcdef01' const row = { @@ -92,8 +92,8 @@ describe('listSharedProviders', () => { }) describe('deleteSharedProvider', () => { - it('removes every person’s settings on it with it', async () => { + it('removes every person’s settings on it with it, their image-model picks on it included', async () => { expect(await deleteSharedProvider(KIND)).toBe(true) - expect(mocks.deleted).toEqual([sharedModelAccounts, sharedModelAccountPrefs]) + expect(mocks.deleted).toEqual([sharedModelAccounts, sharedModelAccountPrefs, imagePrefs]) }) }) From 91dc14c96d53353cc44c5f4019b82db57ef1bcc4 Mon Sep 17 00:00:00 2001 From: gganebnyi Date: Mon, 23 Nov 2026 15:28:11 +0200 Subject: [PATCH 5/6] feat(settings): image models in the custom provider form and the image-model list MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The custom provider form (Settings and Admin → Shared models) gets an Image models section under the models, for the Chat Completions API type: id, optional name, a Transparent switch, remove and Add image model. The ids Fetch models found are offered for both lists. Admin's shared provider row counts its image models. Settings → Doop Agent → Image model lists each custom provider's image models after the registry, one row per provider ("Name (shared)" for an admin's), with a dropdown when it lists several. Strings in en and pt-BR. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01ABWHJg7QHZpRjDADALswQZ --- src/components/CustomProviderForm.tsx | 108 ++++++++++++++++ src/components/ImageModelCard.tsx | 145 ++++++++++++++++------ src/components/SharedProviderSettings.tsx | 6 + src/lib/api.ts | 6 +- src/lib/i18n/en/admin.ts | 1 + src/lib/i18n/en/models.ts | 15 +++ src/lib/i18n/pt-BR/admin.ts | 1 + src/lib/i18n/pt-BR/models.ts | 15 +++ tests/customProviderForm.test.tsx | 124 ++++++++++++++++++ tests/imageModelCard.test.tsx | 119 ++++++++++++++++++ 10 files changed, 502 insertions(+), 38 deletions(-) create mode 100644 tests/imageModelCard.test.tsx diff --git a/src/components/CustomProviderForm.tsx b/src/components/CustomProviderForm.tsx index 5e6779d77..fc841bcac 100644 --- a/src/components/CustomProviderForm.tsx +++ b/src/components/CustomProviderForm.tsx @@ -21,6 +21,7 @@ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '. import { Switch } from './ui/switch' import { Textarea } from './ui/textarea' import { FieldError } from './ConnectionTable' +import { cn } from '@/lib/utils' /** * Settings → Doop Agent → Custom provider: any OpenAI- or Anthropic- @@ -29,6 +30,10 @@ import { FieldError } from './ConnectionTable' * turn. Fetch models asks the endpoint for its list; Test runs one turn that * has to call a tool, which is how the agent does all its work. * + * A Chat Completions provider can also list image models, which the agents' + * generate_image draws with through the endpoint's Images API; the ids Fetch + * models found can go into either list. + * * On an edit the stored key and headers are never shown: blank fields keep * them, and each has its own Remove. * @@ -51,6 +56,20 @@ const row = (id = '', vision = false, maxOutputTokens = ''): ModelRow => ({ vision, }) +interface ImageRow { + key: number + id: string + name: string + transparent: boolean +} + +const imageRow = (id = '', name = '', transparent = false): ImageRow => ({ + key: nextRowKey++, + id, + name, + transparent, +}) + /** Where the form saves and probes: the person's own providers, or (admin) * the instance's shared ones. */ type FormMode = @@ -78,6 +97,10 @@ export function CustomProviderForm({ const [models, setModels] = useState( stored?.models.map((m) => row(m.id, m.vision, m.maxOutputTokens ? String(m.maxOutputTokens) : '')) ?? [row()], ) + /* none until the person adds one: most providers draw nothing */ + const [imageModels, setImageModels] = useState( + stored?.imageModels?.map((m) => imageRow(m.id, m.name ?? '', m.transparent ?? false)) ?? [], + ) const [headersText, setHeadersText] = useState('') const [clearHeaders, setClearHeaders] = useState(false) const [tokenParam, setTokenParam] = useState(stored?.tokenParam ?? 'max_tokens') @@ -104,6 +127,9 @@ export function CustomProviderForm({ models: models .filter((m) => m.id.trim()) .map((m) => ({ id: m.id, vision: m.vision, maxOutputTokens: m.maxOutputTokens.trim() || undefined })), + imageModels: imageModels + .filter((m) => m.id.trim()) + .map((m) => ({ id: m.id, name: m.name, transparent: m.transparent })), tokenParam, echoReasoning, }) @@ -203,6 +229,16 @@ export function CustomProviderForm({ }) const unlisted = discovered?.filter((id) => !models.some((m) => m.id === id)) ?? [] + const updateImageRow = (key: number, patch: Partial) => + setImageModels((rows) => rows.map((m) => (m.key === key ? { ...m, ...patch } : m))) + const addDiscoveredImage = (id: string) => + setImageModels((rows) => { + if (rows.some((m) => m.id === id)) return rows + const blank = rows.find((m) => !m.id.trim()) + return blank ? rows.map((m) => (m === blank ? { ...m, id } : m)) : [...rows, imageRow(id)] + }) + const unlistedImages = discovered?.filter((id) => !imageModels.some((m) => m.id === id)) ?? [] + return ( @@ -356,6 +392,78 @@ export function CustomProviderForm({

{t('models.customModelsHint')}

+ {/* the Images API is OpenAI's: an Anthropic-compatible endpoint has none */} + {apiType === 'openai-chat' && ( +
+ {t('models.customImageModels')} + {imageModels.length > 0 && ( +
+ {imageModels.map((m, index) => ( +
+ updateImageRow(m.key, { id: e.target.value })} + placeholder={t('models.customImageModelIdPlaceholder')} + aria-label={t('models.customImageModelId', { n: index + 1 })} + spellCheck={false} + /> + updateImageRow(m.key, { name: e.target.value })} + placeholder={t('models.customImageModelNamePlaceholder')} + aria-label={t('models.customImageModelName', { n: index + 1 })} + /> + + setImageModels((rows) => rows.filter((r) => r.key !== m.key))} + > + + +
+ ))} +
+ )} +
0 && 'mt-2')}> + + {unlistedImages.length > 0 && ( + + )} +
+

{t('models.customImageModelsHint')}

+
+ )} +
() + for (const model of models) { + const kind = model.custom ? parseCustomImageModelRef(model.id)?.kind : undefined + if (!kind) continue + rows.set(kind, [...(rows.get(kind) ?? []), model]) + } + return [...rows.values()] +} + +/** One pickable row: a tile, a name and a line, a model dropdown when the + * row holds several, and a check on the chosen one. */ +function ImageModelRow({ + tile, + name, + line, + models, + model, + available, + chosen, + busy, + onPick, +}: { + tile: ReactNode + name: string + line: string + models: { id: string; name: string; blurb: string }[] + model: string + available: boolean + chosen: boolean + busy: boolean + onPick: (id: string) => void +}) { + return ( +
+ onPick(model)} + className="flex min-w-0 flex-1 items-center gap-[14px] text-left disabled:cursor-default" + > + + {tile} + + + {name} + {line} + + + {models.length > 1 && ( +
+ +
+ )} + {chosen && } +
+ ) +} + /** * Which image model the agents' generate_image tool draws with, as a list in * the connections' style: pick a row, the chosen one wears a check. The * registry is shared with the server; the server says which entries this * user's credentials can actually run, and unavailable ones stay visible but - * inert, their line saying what to connect. + * inert, their line saying what to connect. After the registry come the + * image models the person's switched-on custom providers list (an admin's + * shared ones included), one row per provider. */ export function ImageModelCard() { const t = useT() @@ -98,7 +163,11 @@ export function ImageModelCard() { try { const { models: next } = await api.setImageModel(id) setModels(next) - posthog.capture('image_model_changed', { model: id }) + /* a custom provider's model id is its person's or admin's, not an analytics value */ + const custom = models.find((m) => m.id === id)?.custom + posthog.capture('image_model_changed', { + model: custom ? (custom.shared ? 'custom-shared' : 'custom-personal') : id, + }) } catch (e) { const body = (e as { body?: { error?: string } })?.body setError(body?.error || (e instanceof Error ? e.message : t('models.failedRetry'))) @@ -121,42 +190,44 @@ export function ImageModelCard() { const familyKey = option.family ? FAMILY_NAMES[option.family] : undefined const name = familyKey ? t(familyKey) : (option.family ?? option.name) return ( -
- void pick(option.id)} - className="flex min-w-0 flex-1 items-center gap-[14px] text-left disabled:cursor-default" - > - - {TILES[option.provider]} - - - - {name} - - - {available ? blurbOf(option) : t(UNAVAILABLE_HINTS[option.provider])} - - - - {variants.length > 1 && ( -
- ({ id: v.id, name: v.name, blurb: blurbOf(v) }))} - model={option.id} - onModel={(id) => void pick(id)} - disabled={busy || !available} - /> -
- )} - {chosen && } -
+ tile={TILES[option.provider]} + name={name} + line={available ? blurbOf(option) : t(UNAVAILABLE_HINTS[option.provider])} + models={variants.map((v) => ({ id: v.id, name: v.name, blurb: blurbOf(v) }))} + model={option.id} + available={available} + chosen={chosen} + busy={busy} + onPick={(id) => void pick(id)} + /> + ) + })} + {customImageRows(models).map((variants) => { + const option = variants.find((v) => v.selected) ?? variants[0]! + const custom = option.custom! + const line = custom.shared + ? t('models.imageCustomSharedBlurb', { model: custom.name }) + : t('models.imageCustomBlurb', { model: custom.name }) + return ( + } + name={custom.shared ? t('models.sharedRunnerName', { name: custom.provider }) : custom.provider} + line={custom.transparent ? `${line} ${t('models.imageCustomTransparent')}` : line} + models={variants.map((v) => ({ + id: v.id, + name: v.custom!.name, + blurb: v.custom!.transparent ? t('models.imageCustomTransparent') : '', + }))} + model={option.id} + available={option.available} + chosen={option.available && option.selected} + busy={busy} + onPick={(id) => void pick(id)} + /> ) })}
diff --git a/src/components/SharedProviderSettings.tsx b/src/components/SharedProviderSettings.tsx index e953b2a81..0ac3533b8 100644 --- a/src/components/SharedProviderSettings.tsx +++ b/src/components/SharedProviderSettings.tsx @@ -193,6 +193,12 @@ function ProviderRow({ · {t('admin.sharedModelCount', { count: custom.models.length })} · + {custom.imageModels?.length ? ( + <> + {t('admin.sharedImageModelCount', { count: custom.imageModels.length })} + · + + ) : null} {custom.hasKey ? t('admin.sharedKeySet') : t('admin.sharedNoKey')} diff --git a/src/lib/api.ts b/src/lib/api.ts index b0a81166a..5d15175fe 100644 --- a/src/lib/api.ts +++ b/src/lib/api.ts @@ -370,11 +370,15 @@ export interface ModelAccounts { customProviders?: boolean } -/** One image-model registry entry's availability for this user. */ +/** One image model's availability for this user: a registry entry, or an + * image model one of their switched-on custom providers lists. */ export interface ImageModelStatus { id: string available: boolean selected: boolean + /** a custom provider's image model (`custom:/`), which the + * shared registry knows nothing about */ + custom?: { provider: string; name: string; shared?: true; transparent?: true } } export interface WebsiteImportResult { diff --git a/src/lib/i18n/en/admin.ts b/src/lib/i18n/en/admin.ts index 65aeff267..e8c7865f2 100644 --- a/src/lib/i18n/en/admin.ts +++ b/src/lib/i18n/en/admin.ts @@ -108,6 +108,7 @@ export const admin = { sharedDeleteDescription: 'It disappears for everyone at once, with each person’s model pick on it. To take it away for now, switch it off instead.', sharedModelCount: { one: '{count} model', other: '{count} models' }, + sharedImageModelCount: { one: '{count} image model', other: '{count} image models' }, sharedKeySet: 'key set', sharedNoKey: 'no key', } as const diff --git a/src/lib/i18n/en/models.ts b/src/lib/i18n/en/models.ts index 689161c07..4f288fa78 100644 --- a/src/lib/i18n/en/models.ts +++ b/src/lib/i18n/en/models.ts @@ -163,6 +163,9 @@ export const models = { imageSeedreamProBlurb: 'ByteDance’s top image model — rich, painterly quality.', imageSeedreamLiteBlurb: 'Faster, cheaper Seedream tier.', imageModelTitle: 'Image model', + imageCustomBlurb: '{model}, drawn on your custom provider.', + imageCustomSharedBlurb: '{model}, drawn on the provider your admin shares.', + imageCustomTransparent: 'Draws transparent backgrounds.', /* custom providers (CustomProviderForm, ModelAccount) */ customRowTitle: 'Custom provider', @@ -202,6 +205,18 @@ export const models = { customAddModel: 'Add model', customModelsHint: 'Each model appears under this provider in the model picker. Turn on Sees images only for models that accept image input: the agent reviews its designs from screenshots.', + customImageModels: 'Image models', + customImageModelsHint: + 'Optional. The agents’ generate_image can draw with these: Doop adds /images/generations to the base URL (the OpenAI Images API) and sends this provider’s key and headers. Turn on Transparent only for models that honour a transparent background.', + customImageModelId: 'Image model {n} id', + customImageModelIdPlaceholder: 'my-image-model', + customImageModelName: 'Image model {n} name', + customImageModelNamePlaceholder: 'Name (optional)', + customImageTransparent: 'Transparent', + customImageTransparentFor: 'Image model {n} draws transparent backgrounds', + customRemoveImageModel: 'Remove image model {n}', + customAddImageModel: 'Add image model', + customAddListedImage: 'Add an image model the endpoint lists', customAdvanced: 'Advanced', customHeaders: 'Extra headers', customHeadersHint: 'One per line, as Name: value. Stored encrypted.', diff --git a/src/lib/i18n/pt-BR/admin.ts b/src/lib/i18n/pt-BR/admin.ts index 23eab53d8..8a65416a3 100644 --- a/src/lib/i18n/pt-BR/admin.ts +++ b/src/lib/i18n/pt-BR/admin.ts @@ -109,6 +109,7 @@ export const admin: Catalog['admin'] = { sharedDeleteDescription: 'Ele some para todos na hora, junto com o modelo que cada pessoa escolheu nele. Para tirá-lo por enquanto, desligue-o.', sharedModelCount: { one: '{count} modelo', other: '{count} modelos' }, + sharedImageModelCount: { one: '{count} modelo de imagem', other: '{count} modelos de imagem' }, sharedKeySet: 'chave definida', sharedNoKey: 'sem chave', } diff --git a/src/lib/i18n/pt-BR/models.ts b/src/lib/i18n/pt-BR/models.ts index 82448d335..52fbe99c2 100644 --- a/src/lib/i18n/pt-BR/models.ts +++ b/src/lib/i18n/pt-BR/models.ts @@ -167,6 +167,9 @@ export const models: Catalog['models'] = { imageSeedreamProBlurb: 'O melhor modelo de imagem da ByteDance — qualidade rica, quase pictórica.', imageSeedreamLiteBlurb: 'Versão mais rápida e barata do Seedream.', imageModelTitle: 'Modelo de imagem', + imageCustomBlurb: '{model}, desenhado no seu provedor personalizado.', + imageCustomSharedBlurb: '{model}, desenhado no provedor que seu admin compartilha.', + imageCustomTransparent: 'Desenha fundos transparentes.', customRowTitle: 'Provedor personalizado', customRowShort: 'Qualquer API compatível com OpenAI ou Anthropic', @@ -205,6 +208,18 @@ export const models: Catalog['models'] = { customAddModel: 'Adicionar modelo', customModelsHint: 'Cada modelo aparece sob este provedor no seletor de modelos. Ative Vê imagens só para modelos que aceitam imagens: o agente revisa seus designs por capturas de tela.', + customImageModels: 'Modelos de imagem', + customImageModelsHint: + 'Opcional. O generate_image dos agentes pode desenhar com eles: o Doop acrescenta /images/generations à URL base (a OpenAI Images API) e envia a chave e os cabeçalhos deste provedor. Ative Transparente só para modelos que respeitam um fundo transparente.', + customImageModelId: 'Id do modelo de imagem {n}', + customImageModelIdPlaceholder: 'id-do-modelo-de-imagem', + customImageModelName: 'Nome do modelo de imagem {n}', + customImageModelNamePlaceholder: 'Nome (opcional)', + customImageTransparent: 'Transparente', + customImageTransparentFor: 'O modelo de imagem {n} desenha fundos transparentes', + customRemoveImageModel: 'Remover o modelo de imagem {n}', + customAddImageModel: 'Adicionar modelo de imagem', + customAddListedImage: 'Adicionar um modelo de imagem que o endpoint lista', customAdvanced: 'Avançado', customHeaders: 'Cabeçalhos extras', customHeadersHint: 'Um por linha, como Nome: valor. Guardados criptografados.', diff --git a/tests/customProviderForm.test.tsx b/tests/customProviderForm.test.tsx index f23994b56..113f753e4 100644 --- a/tests/customProviderForm.test.tsx +++ b/tests/customProviderForm.test.tsx @@ -168,3 +168,127 @@ it('in admin mode saves and probes a shared provider through the admin routes', expect(mocks.discover).not.toHaveBeenCalled() expect(mocks.test).not.toHaveBeenCalled() }) + +/* Image models: their own list under the chat models, for a Chat Completions + provider only, filled by hand or from what Fetch models found. */ + +const imageInputs = (what: 'id' | 'name') => + Array.from(document.querySelectorAll(`input[aria-label^="Image model"][aria-label$="${what}"]`)) + +it('adds image models with their names and the transparent switch, apart from the chat models', async () => { + act(() => root.render( {}} onClose={() => {}} />)) + /* a new provider starts with none */ + expect(document.body.textContent).toContain('Image models') + expect(imageInputs('id')).toHaveLength(0) + act(() => { + type(field('input[placeholder="My provider"]'), 'Studio') + type(field('input[placeholder="https://api.example.com/v1"]'), 'https://img.example.com/v1') + type(field('input[placeholder="my-model-id"]'), 'qwen3-coder') + }) + await click('Add image model') + await click('Add image model') + act(() => { + type(imageInputs('id')[0]!, 'flux-dev') + type(imageInputs('name')[0]!, 'FLUX dev') + type(imageInputs('id')[1]!, 'sdxl') + }) + await act(async () => { + document.querySelector('[aria-label="Image model 1 draws transparent backgrounds"]')!.click() + }) + await click('Add provider') + expect(mocks.add).toHaveBeenCalledWith({ + name: 'Studio', + apiType: 'openai-chat', + baseUrl: 'https://img.example.com/v1', + models: [{ id: 'qwen3-coder', vision: false }], + imageModels: [{ id: 'flux-dev', name: 'FLUX dev', transparent: true }, { id: 'sdxl' }], + apiKey: '', + }) +}) + +it('refuses an image model id the server would refuse, before sending', async () => { + act(() => root.render( {}} onClose={() => {}} />)) + act(() => { + type(field('input[placeholder="My provider"]'), 'Studio') + type(field('input[placeholder="https://api.example.com/v1"]'), 'https://img.example.com/v1') + type(field('input[placeholder="my-model-id"]'), 'qwen3-coder') + }) + await click('Add image model') + act(() => type(imageInputs('id')[0]!, 'flux dev')) + await click('Add provider') + expect(mocks.add).not.toHaveBeenCalled() + expect(document.querySelector('[role="alert"]')?.textContent).toContain('Image model 1 needs an id without spaces') +}) + +it('keeps a provider’s stored image models on an edit, removes one on request, and offers fetched ids for them', async () => { + const provider: ModelAccountStatus = { + kind: 'custom:0123456789abcdef01', + enabled: true, + model: 'glm-5', + connectedAt: 1, + custom: { + name: 'Acme', + apiType: 'openai-chat', + baseUrl: 'https://llm.example.com/v1', + models: [{ id: 'glm-5', vision: true }], + imageModels: [{ id: 'flux-dev', name: 'FLUX dev', transparent: true }, { id: 'sdxl' }], + headerNames: [], + hasKey: true, + }, + } + mocks.discover.mockResolvedValue({ models: ['glm-5', 'flux-dev', 'flux-schnell'] }) + act(() => root.render( {}} onClose={() => {}} />)) + expect(imageInputs('id').map((input) => input.value)).toEqual(['flux-dev', 'sdxl']) + expect(imageInputs('name')[0]!.value).toBe('FLUX dev') + + await click('Save') + expect(mocks.update).toHaveBeenLastCalledWith( + provider.kind, + expect.objectContaining({ imageModels: [{ id: 'flux-dev', name: 'FLUX dev', transparent: true }, { id: 'sdxl' }] }), + ) + + await act(async () => { + document.querySelector('[aria-label="Remove image model 2"]')!.click() + }) + await click('Save') + expect(mocks.update).toHaveBeenLastCalledWith( + provider.kind, + expect.objectContaining({ imageModels: [{ id: 'flux-dev', name: 'FLUX dev', transparent: true }] }), + ) + + /* Fetch models feeds both lists, each offering what it does not list yet */ + await click('Fetch models') + expect(document.querySelector('[aria-label="Add a model the endpoint lists"]')).not.toBeNull() + const trigger = document.querySelector('[aria-label="Add an image model the endpoint lists"]')! + expect(trigger).not.toBeNull() + await act(async () => { + trigger.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true, button: 0, pointerType: 'mouse' })) + }) + const offered = Array.from(document.querySelectorAll('[role="option"]')).map((option) => option.textContent) + expect(offered).toEqual(['glm-5', 'flux-schnell']) + await act(async () => { + Array.from(document.querySelectorAll('[role="option"]')) + .find((option) => option.textContent === 'flux-schnell')! + .click() + }) + expect(imageInputs('id').map((input) => input.value)).toEqual(['flux-dev', 'flux-schnell']) +}) + +it('offers no image models for an Anthropic-compatible provider, which has no Images API', () => { + const provider: ModelAccountStatus = { + kind: 'custom:0123456789abcdef01', + enabled: true, + connectedAt: 1, + custom: { + name: 'Claude gateway', + apiType: 'anthropic', + baseUrl: 'https://llm.example.com', + models: [{ id: 'claude-sonnet-5', vision: true }], + headerNames: [], + hasKey: false, + }, + } + act(() => root.render( {}} onClose={() => {}} />)) + expect(document.body.textContent).not.toContain('Image models') + expect(button('Add image model')).toBeUndefined() +}) diff --git a/tests/imageModelCard.test.tsx b/tests/imageModelCard.test.tsx new file mode 100644 index 000000000..c511a2608 --- /dev/null +++ b/tests/imageModelCard.test.tsx @@ -0,0 +1,119 @@ +// @vitest-environment happy-dom +import { act } from 'react' +import { createRoot, type Root } from 'react-dom/client' +import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import type { ImageModelStatus } from '../src/lib/api' +const OWN = 'custom:aaaaaaaa11111111' +const SHARED = 'custom:bbbbbbbb22222222' +const mocks = vi.hoisted(() => ({ + imageModels: vi.fn(), + setImageModel: vi.fn(), + capture: vi.fn(), +})) +vi.mock('../src/lib/api', () => ({ + api: { imageModels: mocks.imageModels, setImageModel: mocks.setImageModel }, +})) +vi.mock('../src/lib/store', () => ({ + useStore: (select: (state: { allowanceVersion: number }) => unknown) => select({ allowanceVersion: 0 }), +})) +vi.mock('../src/lib/posthog', () => ({ posthog: { capture: mocks.capture } })) +import { ImageModelCard } from '../src/components/ImageModelCard' +import { IMAGE_MODELS } from '../shared/modelMenu' +;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true + +/* The image-model list: after the registry come the image models of the + person's custom providers, one row per provider (a shared one named so), + pickable like any other row. */ + +const registry = (selected = ''): ImageModelStatus[] => + IMAGE_MODELS.map((option) => ({ id: option.id, available: false, selected: option.id === selected })) + +const models = (selected: string): ImageModelStatus[] => [ + ...registry(), + { + id: `${OWN}/flux-dev`, + available: true, + selected: selected === `${OWN}/flux-dev`, + custom: { provider: 'Studio FLUX', name: 'FLUX dev', transparent: true }, + }, + { + id: `${OWN}/sdxl`, + available: true, + selected: selected === `${OWN}/sdxl`, + custom: { provider: 'Studio FLUX', name: 'sdxl' }, + }, + { + id: `${SHARED}/flux-schnell`, + available: true, + selected: selected === `${SHARED}/flux-schnell`, + custom: { provider: 'Acme Gateway', name: 'flux-schnell', shared: true }, + }, +] + +let root: Root +let container: HTMLDivElement +beforeEach(() => { + vi.clearAllMocks() + container = document.createElement('div') + document.body.appendChild(container) + root = createRoot(container) +}) +afterEach(() => { + act(() => root.unmount()) + document.body.innerHTML = '' +}) + +const radios = () => Array.from(document.querySelectorAll('[role="radio"]')) +const radio = (name: string) => radios().find((r) => r.textContent?.includes(name))! + +async function render() { + await act(async () => root.render()) +} + +it('lists each custom provider’s image models as one row after the registry, the shared one named as shared', async () => { + mocks.imageModels.mockResolvedValue({ models: models(`${SHARED}/flux-schnell`) }) + await render() + const names = radios().map((r) => r.querySelector('.font-medium')?.textContent) + expect(names.slice(-2)).toEqual(['Studio FLUX', 'Acme Gateway (shared)']) + /* the personal row shows its first model and says it draws cut-outs */ + expect(radio('Studio FLUX').textContent).toContain('FLUX dev, drawn on your custom provider.') + expect(radio('Studio FLUX').textContent).toContain('Draws transparent backgrounds.') + expect(radio('Acme Gateway').textContent).toContain('flux-schnell, drawn on the provider your admin shares.') + /* the chosen one is checked, and only it */ + expect(radio('Acme Gateway').getAttribute('aria-checked')).toBe('true') + expect(radios().filter((r) => r.getAttribute('aria-checked') === 'true')).toHaveLength(1) + /* a provider with several image models gets the dropdown, one with a single model does not */ + expect(document.querySelector('[aria-label="Model for Studio FLUX"]')).not.toBeNull() + expect(document.querySelector('[aria-label="Model for Acme Gateway (shared)"]')).toBeNull() +}) + +it('picks a custom provider’s image model by its id', async () => { + mocks.imageModels.mockResolvedValue({ models: models('') }) + mocks.setImageModel.mockResolvedValue({ models: models(`${OWN}/flux-dev`) }) + await render() + await act(async () => radio('Studio FLUX').click()) + expect(mocks.setImageModel).toHaveBeenCalledWith(`${OWN}/flux-dev`) + expect(radio('Studio FLUX').getAttribute('aria-checked')).toBe('true') + /* analytics learn the kind of pick, never the provider or model id */ + expect(mocks.capture).toHaveBeenCalledWith('image_model_changed', { model: 'custom-personal' }) +}) + +it('keeps a provider’s row, and its focus, when the pick moves to another of its models', async () => { + mocks.imageModels.mockResolvedValue({ models: models(`${OWN}/flux-dev`) }) + mocks.setImageModel.mockResolvedValue({ models: models(`${OWN}/sdxl`) }) + await render() + const row = radio('Studio FLUX') + row.focus() + await act(async () => row.click()) + /* the server now says sdxl is the pick: the same row shows it */ + expect(mocks.setImageModel).toHaveBeenCalledWith(`${OWN}/flux-dev`) + expect(radio('Studio FLUX')).toBe(row) + expect(row.textContent).toContain('sdxl, drawn on your custom provider.') + expect(document.activeElement).toBe(row) +}) + +it('shows only the registry when no provider lists image models', async () => { + mocks.imageModels.mockResolvedValue({ models: registry() }) + await render() + expect(radios().some((r) => r.textContent?.includes('custom provider'))).toBe(false) +}) From b882ff786c8243393c96db49de9d5212edf108ae Mon Sep 17 00:00:00 2001 From: gganebnyi Date: Mon, 23 Nov 2026 15:28:19 +0200 Subject: [PATCH 6/6] docs: image models on custom providers spec, TECHSTACK and .env.example Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01ABWHJg7QHZpRjDADALswQZ --- .context/TECHSTACK.md | 15 ++- .context/specs/INDEX.md | 4 + .../specs/custom-provider-image-models.md | 118 ++++++++++++++++++ .context/specs/shared-model-providers.md | 5 +- .env.example | 6 +- README.md | 2 +- 6 files changed, 143 insertions(+), 7 deletions(-) create mode 100644 .context/specs/custom-provider-image-models.md diff --git a/.context/TECHSTACK.md b/.context/TECHSTACK.md index 526cdc8b0..471dcc3dd 100644 --- a/.context/TECHSTACK.md +++ b/.context/TECHSTACK.md @@ -275,8 +275,17 @@ server/index.ts` in prod. `erasableSyntaxOnly` and `verbatimModuleSyntax` in tsc response cap; `DOOP_CUSTOM_PROVIDER_PRIVATE_HOSTS` admits private hosts and http for a self-hosted instance, `DOOP_CUSTOM_PROVIDERS=false` turns the feature off (existing ones read as disconnected). Advanced: extra headers (routing and framing headers refused), `max_tokens` vs - `max_completion_tokens`, and echoing `reasoning_content`. Tests: `customProvider.test.ts`, - `customProvidersHttp.test.ts`, `customProviderForm.test.tsx`. + `max_completion_tokens`, and echoing `reasoning_content`. A Chat Completions provider can also list image models + (`imageModels: { id, name?, transparent? }[]` in the same `custom` jsonb, at most 20; + `.context/specs/custom-provider-image-models.md`): they join the Settings image-model list for whoever has the + provider on (picked as `custom:/` in `image_prefs`), and `generate_image` draws with them through + `POST {baseUrl}/images/generations` over `customProviderFetch` on the provider's key and headers (OpenAI's Images API + body; `data[0].b64_json`, or a `data[0].url` fetched the same way, credentials only to the base URL's origin; PNG, JPEG + or WebP only). Billed as the person's own connection, a shared provider included; a pick that cannot run refuses, never + falling back to another model or a server key. `generate_image`'s `transparent` sends `background: "transparent"` only + to a model marked so. Tests: `customProvider.test.ts`, + `customProvidersHttp.test.ts`, `customProviderForm.test.tsx`, `customProviderImages.test.ts`, + `customProviderImagesHttp.test.ts`, `imageModelCard.test.tsx`. - Shared model providers (`server/sharedModelAccounts.ts`, `src/components/SharedProviderSettings.tsx`): a custom provider an instance admin sets up once in Admin → Shared models, for every signed-in person. The definition lives in `shared_model_accounts` (kind `custom:`, key and headers sealed, @@ -292,7 +301,7 @@ server/index.ts` in prod. `erasableSyntaxOnly` and `verbatimModuleSyntax` in tsc `hasKey` and `headerNames`, and the stored key and headers only go to the origin they were saved for (a probe or edit for another origin must bring its own). `DOOP_CUSTOM_PROVIDERS=false` hides them from everyone. For image billing a shared provider is the person's own connection, so the server's - image keys do not draw for them. Tests: + image keys do not draw for them; its image models, if it lists any, draw for everyone on the company's endpoint. Tests: `sharedModelAccounts.test.ts`, `sharedModelAccountsStore.test.ts`, `sharedModelProvidersHttp.test.ts`, `sharedProviderRow.test.tsx`, `customProviderForm.test.tsx`. - Reasoning effort on a user's OpenAI account (ChatGPT subscription or OpenAI key): the pick lives diff --git a/.context/specs/INDEX.md b/.context/specs/INDEX.md index 29745051a..5eea8174f 100644 --- a/.context/specs/INDEX.md +++ b/.context/specs/INDEX.md @@ -9,6 +9,10 @@ lists every file in this folder. - [shared-model-providers.md](shared-model-providers.md) - Shared model providers: custom providers an admin sets up once for every user (Admin → Shared models), per-user model pick and on/off, sealed key never returned; `shared_model_accounts` + prefs, `/api/admin/shared-providers`. +- [custom-provider-image-models.md](custom-provider-image-models.md) - Image models on custom providers + (personal and shared): listed beside the chat models, offered in Settings → Image model, drawn through the + provider's `POST {baseUrl}/images/generations` on its key, billed as the person's own connection, no server-key + fallback, `transparent` cut-outs; no migration (`custom` jsonb, `image_prefs`). - [skills.md](skills.md) - Team skills: named markdown instructions a workspace or person writes once, invoked by `/handle` in a request and added to the resident agent's system prompt for that run; storage, `/api/skills`, the settings card. Issue #380. diff --git a/.context/specs/custom-provider-image-models.md b/.context/specs/custom-provider-image-models.md new file mode 100644 index 000000000..007709fa1 --- /dev/null +++ b/.context/specs/custom-provider-image-models.md @@ -0,0 +1,118 @@ +# Image models on custom providers + +Status: implemented + +## Problem + +Image generation (`generate_image`, MCP and resident) draws only with the built-in registry (`IMAGE_MODELS` in +`shared/modelMenu.ts`): GPT Image on a ChatGPT subscription or an OpenAI key, Nano Banana on a Gemini key, Seedream on +the server's `ARK_API_KEY`. A team that self-hosts an image model has no way in. The usual setup is an OpenAI +Images-compatible endpoint (`POST {baseUrl}/images/generations` answering `data[0].b64_json`): a LiteLLM gateway in front +of ComfyUI/FLUX, vLLM, LocalAI. `OPENAI_IMAGES_URL` does not help: it is server-wide, takes registry ids only and runs on +the server's or a person's OpenAI key, and since shared providers the server key no longer draws for people who have one. + +## Goal + +A custom provider, a person's own or an admin's shared one ([shared-model-providers.md](shared-model-providers.md)), +lists **image models** next to its chat models. Whoever has that provider connected and on finds them in Settings → +Doop Agent → Image model, and `generate_image` draws with the one they picked through the provider's endpoint, on the +provider's key and headers. + +Out of scope: image models on an Anthropic-compatible provider (that API has no images endpoint), image editing or +reference images, a Test button for image models, `DOOP_IMAGE_MODEL` naming a custom image model. + +## Behaviour + +1. **Config.** A Chat Completions provider's description (`CustomProviderConfig`) gets an optional + `imageModels: { id, name?, transparent? }[]`. `transparent` says the endpoint honours `background: "transparent"`. + An id can also be a chat model of the same provider. The list is optional: a description stored before it existed stays valid and is + stored without the field when the list is empty. +2. **Form.** `CustomProviderForm` (Settings and Admin → Shared models) has an "Image models" section under the models, + for the Chat Completions API type only: id, optional name, a Transparent switch, remove, "Add image model". The ids + "Fetch models" found are offered for both lists, each list offering the ids it does not hold yet. +3. **Picker.** `GET /api/image-model` lists the registry entries as before, then one entry per image model of each + custom provider the person has connected and on (their own first, then shared ones), with + `custom: { provider, name, shared?, transparent? }`. `ImageModelCard` shows them as one row per provider ("Name + (shared)" for a shared one) with a dropdown when it lists several. The pick is stored in `image_prefs.model` as + `custom:/` (`customImageModelRef` in `shared/customProvider.ts`); `PUT /api/image-model` accepts only an + id the person's picker lists. +4. **Default.** With no pick, the person's own credentials come first: `DOOP_IMAGE_MODEL` when it runs on an account + of theirs, else the first registry entry that does, else the first custom image model; only then what a server key + pays for (`DOOP_IMAGE_MODEL` first): any entry for someone who connected nothing, and Seedream on `ARK_API_KEY` for + everyone. Someone whose only connection is a shared provider with image models therefore draws on it from their + first sign-in, even where the operator set `ARK_API_KEY`. An explicit pick on Seedream still draws Seedream. +5. **Request.** `POST {baseUrl}/images/generations` through `customProviderFetch` (so `DOOP_CUSTOM_PROVIDER_PRIVATE_HOSTS`, + DNS pinning, no redirects and the 32 MB cap apply), with the provider's headers and `Authorization: Bearer ` when + it has one, and the body `imageApiGenerator` sends to OpenAI: `model`, `prompt`, `n: 1`, `size` from `SIZES`, + `quality`, `output_format: "png"`, plus `background: "transparent"` when the call asked for a cut-out and the model + says it can draw one. +6. **Response.** `data[0].b64_json` is decoded. A `data[0].url` (absolute or relative to the base URL) is fetched through + `customProviderFetch` too, with the provider's key and headers only when it is on the base URL's origin. The result must + decode as PNG, JPEG or WebP, or the call fails saying so; neither field fails with the endpoint's own `error.message` + when it gave one. +7. **Transparent.** `generate_image` (MCP and resident) takes an optional `transparent` boolean. Only a custom image + model marked `transparent` is sent the field; every other model draws opaque. The result says what was drawn, read + off the image (an alpha channel that is not opaque everywhere), not off the flag: `transparent` in the MCP result, a + note in the resident's. The stored WebP keeps the alpha; the preview is flattened on white. +8. **Billing.** A custom image model is the person's own connection, a shared provider included (the company's endpoint + pays). `billed_to` is the provider's name; analytics get `custom-personal` or `custom-shared` instead of the name. +9. **No fallback.** A pick on a custom image model that cannot run now (its provider switched off by the person, switched + off or deleted by its admin, removed, the model taken off the list, or `DOOP_CUSTOM_PROVIDERS=false`) refuses with the + fix ("switch it on, or pick another image model"); it never draws on another model, connection or a server key. When + nothing at all can draw, the refusal names a switched-off provider with image models like a switched-off image account. + Disconnecting a personal provider deletes its person's pick on it, and deleting a shared provider deletes everyone's + (`image_prefs` rows starting `custom:/`, in the same transaction), so they fall back to the default rather than + being refused for a provider that is gone. +10. **Errors.** A 401/403 from a shared provider tells the person to ask their admin (Admin → Shared models), as a run + failure does; from a personal one, to update the key in Settings. A 404 or "no such model" names the model and the + missing `/images/generations`. Other failures carry the endpoint's status and text, like the registry providers', + with the provider's key and every header value masked (`redactSecrets`, as for its chat turns) on the whole text, before + it is shortened: an endpoint may quote + the key it refused, and a shared provider's key must never reach a person or a log. +11. **Security.** The key and headers never appear in any response; image models are part of the description, so a + person's view of a shared provider lists them (they name models, not secrets). Only an admin changes a shared + provider's image models (the admin routes; `PUT /api/custom-providers/:kind` on a shared kind is 403). + +## Data + +No migration: `imageModels` rides in the existing `custom` jsonb of `model_accounts` (0051) and +`shared_model_accounts` (0062), re-checked by `parseCustomProviderConfig` on every read, and the pick in the existing +`image_prefs.model` text column. + +## Code shape + +- `shared/customProvider.ts`: `CustomImageModel`, `MAX_CUSTOM_IMAGE_MODELS` (20), the parser, `customImageModelRef` / + `parseCustomImageModelRef`. +- `server/imagePrefs.ts` accepts a well-formed custom ref; whether it can run is decided per run. +- `server/imageGen.ts`: `customImageChoices(accounts)`, `customImageGenerator` (the request, link fetch, format check, + error wording), `chosenImageModel` returning a registry option, a custom choice or the missing custom pick, + `imageModelAvailability` listing the custom entries, `TRANSPARENT_NOTE` for both tool schemas. +- `server/modelAccounts.ts` `statusOf` passes a shared provider's image models to the person's view. +- UI: `CustomProviderForm.tsx`, `ImageModelCard.tsx`, the image-model count on the Admin row + (`SharedProviderSettings.tsx`); strings in `src/lib/i18n/{en,pt-BR}/models.ts` and `admin.ts`. + +## Tests + +- `customProvider.test.ts`: parsing (normalising, the cap, ids, duplicates, names, Anthropic drops them, stored configs + without the field), the preference ref. +- `customProviderImages.test.ts`: the request (URL, key, headers, body, transparent or not, keyless), personal and shared + draws, the default for someone with only a shared provider while server keys (`ARK_API_KEY` included) are set, the + picker's entries, switched-off / deleted / delisted picks refusing without touching the network, link responses with + and without credentials, non-image and empty answers, error wording, masked secrets (400, 429, an error beside a 200, + 404), transparency read off the image, private hosts. +- `sharedModelAccounts.test.ts`: a shared provider's image models through the real `getAccounts`, and gone with + `DOOP_CUSTOM_PROVIDERS=false`. +- `customProviderImagesHttp.test.ts` (real server, stub endpoint): admin adds image models, a person cannot change them, + the picker lists and picks them, MCP `generate_image` stores the image drawn on the shared key, the 401 wording, + switched off draws nothing, a personal provider's image models, picks deleted with a disconnected or deleted + provider, no key in any response. +- `customProviderForm.test.tsx`, `imageModelCard.test.tsx`: the form section and the picker rows. + +## Notes + +- `quality` and `output_format` are OpenAI's GPT Image fields; a strict server that refuses unknown fields will refuse + them. LiteLLM and most gateways pass or drop them. A per-model "plain request" switch is a follow-up if one turns up. +- A provider still needs at least one chat model, and its image models are offered only while it is on, so it is also a + chat connection. An endpoint that only draws images (no chat model to list) is not supported on its own; a gateway + that serves both, the usual setup, is. Image-only providers would need the config, the agent default and the composer + to skip a provider without chat models, which is a separate change. diff --git a/.context/specs/shared-model-providers.md b/.context/specs/shared-model-providers.md index 872a8a393..249dfedf2 100644 --- a/.context/specs/shared-model-providers.md +++ b/.context/specs/shared-model-providers.md @@ -40,8 +40,9 @@ Out of scope: workspace-scoped sharing, sharing built-in kinds (ChatGPT/OpenAI/A purposes, like a personal one: the run is on the company's model, not the server's paid key. **Image generation** bills it the same way: a person with a shared provider has a connection of their own, so the server's image keys (`OPENAI_API_KEY`, `GEMINI_API_KEY`), which cover only people who connected no model account, - no longer draw for them. A shared provider cannot draw images, so such a person draws only with an image-capable - account of their own (ChatGPT, OpenAI or Gemini key). + no longer draw for them. Such a person draws with an image-capable account of their own (ChatGPT, OpenAI or Gemini + key) or with the image models a provider lists, a shared one included + ([custom-provider-image-models.md](custom-provider-image-models.md)). 8. **Security:** - The shared key and headers are sealed at rest like personal ones (`sealedText`). They are read sealed and opened per provider: one whose key or headers cannot be unsealed (its encryption key rotated out of diff --git a/.env.example b/.env.example index a82071b68..b888a701b 100644 --- a/.env.example +++ b/.env.example @@ -295,7 +295,11 @@ # exception: it has no BYO path, so setting ARK_API_KEY opts this server into # paying for every Seedream generation. Unset keys = a clear "connect an # account / pick another model" message; nobody with a matching connected -# account is affected. +# account is affected. A custom provider (DOOP_CUSTOM_PROVIDERS below) can also +# list image models of its own, drawn through its OpenAI-compatible +# /images/generations on its own key: self-hosted image models (a gateway in +# front of FLUX, say) need no key here, and an admin's shared provider offers +# them to everyone. #OPENAI_API_KEY= #GEMINI_API_KEY= #ARK_API_KEY= diff --git a/README.md b/README.md index 406ef8112..6c617132f 100644 --- a/README.md +++ b/README.md @@ -933,7 +933,7 @@ read-only / destructive / idempotent annotations; the server registers no MCP pr | `search_logos` | Real company logos by brand name or domain (Brandfetch, vector marks) | | `list_backgrounds` | Curated hero/section/bento backgrounds (glows, grainy meshes, aurora, painterly) as thumbnails | | `search_inspiration` | Curated live landing pages with style, colour, fonts and sections (One Page Love) | -| `generate_image` | Generate an image with the model the user picked in Settings (GPT Image, Nano Banana or Seedream) → asset URL | +| `generate_image` | Image from the model picked in Settings (GPT Image, Nano Banana, Seedream, a custom provider's model) → asset URL | | `upload_asset` | Store your own file — from a URL, a one-time local-file upload URL, or inline base64 | | **Web** | | | `view_website` | Inspect one public page read-only; returns a desktop screenshot and visible text without changing the canvas |