From bf7f18f87172ae5b18c29e120d085ffe60ae7d9c Mon Sep 17 00:00:00 2001 From: Zhangbo-cn <60600082+Zhangbo-cn@users.noreply.github.com> Date: Sat, 28 Nov 2026 23:00:13 +0800 Subject: [PATCH 1/8] feat(provider): configure several modalities from one connection A single API key commonly serves chat, image, video and audio models, but the settings form is kind-scoped: the same address and key had to be entered once per modality. Add a connection as a first-class draft: POST /api/model-configs/discover-many reads declarations per modality and reports per-modality errors, and POST /api/model-configs/connections saves the chosen modalities under one providerId with an explicit saved/rejected receipt. Saving replaces only the rows of the modality being written, so adding an image model later no longer drops the chat models that share the provider. UI: a multi-modal connection form reachable from the model settings overview and the per-kind service list, with per-modality protocol, grouped selection after one discovery, and retry for rejected modalities. Docs: docs/architecture/model-connection-multimodal.md Tests: application discovery isolation, connection save across kinds with partial failure and retry, rejected input, and a browser workflow registered in the gate lane. Refs #558 --- apps/api/src/opendirector_api/main.py | 18 + apps/api/src/opendirector_api/models.py | 42 ++- docs/README.md | 1 + .../model-connection-multimodal.md | 128 +++++++ .../opendirector/application/model_catalog.py | 42 +++ .../infrastructure/model_configs.py | 52 ++- scripts/run-browser-suite.mjs | 1 + src/backend/models.ts | 60 ++++ src/canvas/ModelConnectionForm.tsx | 313 ++++++++++++++++++ src/canvas/ModelSettings.tsx | 31 +- src/canvas/ModelSetup.tsx | 8 +- src/canvas/model-settings.css | 72 ++++ src/i18n/messages/en-US/models.ts | 15 + src/i18n/messages/zh-CN/models.ts | 15 + tests/browser/manifest.json | 6 + tests/browser/model_connection.mjs | 104 ++++++ tests/test_model_catalog.py | 33 ++ tests/test_model_configs.py | 77 +++++ 18 files changed, 1011 insertions(+), 7 deletions(-) create mode 100644 docs/architecture/model-connection-multimodal.md create mode 100644 src/canvas/ModelConnectionForm.tsx create mode 100644 tests/browser/model_connection.mjs diff --git a/apps/api/src/opendirector_api/main.py b/apps/api/src/opendirector_api/main.py index 3b4bf88a3..68c0cdea5 100644 --- a/apps/api/src/opendirector_api/main.py +++ b/apps/api/src/opendirector_api/main.py @@ -34,6 +34,7 @@ from opendirector_api.localization import localized_error from opendirector_api.models import (ModelConfigInput, ModelConfigPublic, AgentModelTest, ModelCapabilityRequest, ModelDiscoveryRequest, ModelBatchInput, + ConnectionDiscoveryRequest, ConnectionSaveRequest, ToolTaskCreate, ToolPlacement, ImageSelectionCreate, AvailabilityRefresh, AvailabilityCatalog, ModelAvailability as ModelAvailabilityResponse) @@ -263,6 +264,23 @@ async def discover_models(value: ModelDiscoveryRequest): protocol=value.protocol, auth_mode=value.authMode, proxy_mode=value.proxyMode) return {'models': models} + @app.post('/api/model-configs/discover-many') + async def discover_connection_models(value: ConnectionDiscoveryRequest): + return {'results': await catalog.discover_many( + [{'kind': entry.kind, 'protocol': entry.protocol} for entry in value.kinds], + value.url, value.apiKey.get_secret_value(), connection_type=value.connectionType, + auth_mode=value.authMode, proxy_mode=value.proxyMode)} + + @app.post('/api/model-configs/connections') + def save_connection(value: ConnectionSaveRequest): + return catalog.save_connection( + [{'kind': entry.kind, 'protocol': entry.protocol, 'modelIds': entry.modelIds, + 'modelOptions': entry.modelOptions} for entry in value.entries], + value.url, value.apiKey.get_secret_value(), connection_type=value.connectionType, + auth_mode=value.authMode, proxy_mode=value.proxyMode, + capability_auto_check=value.capabilityAutoCheck, + provider_id=str(value.providerId) if value.providerId else None) + @app.post('/api/model-configs/test-agent') async def test_agent_model(value: AgentModelTest): elapsed = await catalog.test_agent(value.url, value.modelId, value.apiKey.get_secret_value(), diff --git a/apps/api/src/opendirector_api/models.py b/apps/api/src/opendirector_api/models.py index 75e65dfe7..3b3620e3d 100644 --- a/apps/api/src/opendirector_api/models.py +++ b/apps/api/src/opendirector_api/models.py @@ -12,6 +12,9 @@ class Model(BaseModel): model_config = ConfigDict(extra="forbid") +Protocol = Literal['openai', 'volcengine', 'higgsfield_open', 'bigmodel_video', 'kling_video', 'minimax_video_v2', 'vllm_omni', 'vllm_omni_segmentation', 'vllm_omni_music', 'vllm_omni_depth', 'vllm_omni_score'] + + class Session(Model): projectId: UUID @@ -25,7 +28,7 @@ class AssetSource(Model): class ModelConnection(Model): connectionType: Literal['api', 'self_hosted'] = 'api' - protocol: Literal['openai', 'volcengine', 'higgsfield_open', 'bigmodel_video', 'kling_video', 'minimax_video_v2', 'vllm_omni', 'vllm_omni_segmentation', 'vllm_omni_music', 'vllm_omni_depth', 'vllm_omni_score'] | None = None + protocol: "Protocol" = None authMode: Literal['none', 'bearer'] | None = None proxyMode: Literal['system', 'direct'] | None = None capabilityAutoCheck: bool | None = Field(default=None, strict=True, exclude_if=lambda value: value is None) @@ -64,6 +67,43 @@ class ModelDiscoveryRequest(ModelConfigInput): configId: UUID | None = None +MODEL_KIND = Literal["agent", "image", "video", "audio", "vision"] + + +class ConnectionDiscoveryKind(Model): + kind: MODEL_KIND + protocol: "Protocol" = None + + +class ConnectionDiscoveryRequest(Model): + """Discover models for several modalities of one address and credential.""" + url: str = Field(max_length=2048) + apiKey: SecretStr = SecretStr("") + connectionType: Literal['api', 'self_hosted'] = 'api' + authMode: Literal['none', 'bearer'] | None = None + proxyMode: Literal['system', 'direct'] | None = None + kinds: list[ConnectionDiscoveryKind] = Field(min_length=1, max_length=5) + + +class ConnectionEntry(Model): + """One modality saved as part of a connection.""" + kind: MODEL_KIND + protocol: "Protocol" = None + modelIds: list[str] = Field(min_length=1, max_length=200) + modelOptions: dict[str, ModelOptions] = Field(default_factory=dict, max_length=200) + + +class ConnectionSaveRequest(Model): + url: str = Field(max_length=2048) + apiKey: SecretStr = SecretStr("") + connectionType: Literal['api', 'self_hosted'] = 'api' + authMode: Literal['none', 'bearer'] | None = None + proxyMode: Literal['system', 'direct'] | None = None + capabilityAutoCheck: bool | None = Field(default=None, strict=True) + providerId: UUID | None = None + entries: list[ConnectionEntry] = Field(min_length=1, max_length=5) + + class AgentModelTest(ModelConfigInput): kind: Literal["agent"] = "agent" configId: UUID | None = None diff --git a/docs/README.md b/docs/README.md index dff1456cc..7933e2cb6 100644 --- a/docs/README.md +++ b/docs/README.md @@ -12,6 +12,7 @@ This directory is the entry point for the repository's shared documentation. The | [Desktop architecture](architecture/desktop.md) ([中文](architecture/desktop.zh-CN.md)) | Electron, the Python Host, project storage, and shutdown behavior | Process, request, storage, or lifecycle boundaries change | | [Test contracts](architecture/test-contracts.md) | Test/production boundaries, how to avoid stale assertions and environment-dependent red runs | Test infrastructure, capability gates, or contract ownership change | | [Capability mapping contract](architecture/capability-contract.md) | Evidenced upstream vocabulary, the `(operation, profile) → capability` table, the untranslatable declarations, and how it feeds discovery | Upstream vocabulary, capability ids, or discovery matching change | +| [Multimodal model connections](architecture/model-connection-multimodal.md) | One connection (address + credentials) that adds text, image, video and audio models in one pass, with per-kind discovery and partial-save semantics | The connection object, its endpoints, or multi-kind save rules change | | [Roadmap](development/roadmap.md) | Capability dependencies and delivery criteria | Scope, dependencies, or acceptance criteria change | | [Validation guide](development/validation.md) | Reproducible checks and evidence requirements | Tools, runtime requirements, or validation entry points change | | [Agent turn timing](development/agent-timing.md) ([中文](development/agent-timing.zh-CN.md)) | Where one agent turn spends its time, and the pre-registered bands that decide the next optimization | The ledger, its reader, or a decision band changes | diff --git a/docs/architecture/model-connection-multimodal.md b/docs/architecture/model-connection-multimodal.md new file mode 100644 index 000000000..04f2f144d --- /dev/null +++ b/docs/architecture/model-connection-multimodal.md @@ -0,0 +1,128 @@ +# Multimodal model connections + +## 摘要(中文) + +同一 API Key 往往同时提供语言、图片、视频、语音模型,但当前配置流程是「按模态建服务」:语言、图片、视频、音频各填一次地址与密钥、各自发现模型、各自保存。本文设计「连接(connection)」为第一次类对象:一次填写地址与凭据,按模态分别发现并分组的模型,一次保存为多个 `model-configs`(同一 `providerId`),并对部分失败、能力检查、协议差异和兼容性给出明确语义。本文只描述设计,不代表已实现。 + +Status: implemented for the settings entry point; the first-run wizard and the business CLI still use the per-kind form (see “Delivered scope”). + +## Delivered scope + +Implemented in this repository: + +- `POST /api/model-configs/discover-many` and `POST /api/model-configs/connections`, backed by + `ModelCatalog.discover_many` / `ModelCatalog.save_connection` (`packages/core/src/opendirector/application/model_catalog.py`) + and `ModelConfigs.save_connection` (`packages/core/src/opendirector/infrastructure/model_configs.py`). +- Per-kind saving now replaces only rows of that kind, so a connection can grow kind by kind without + dropping its peers (`save_many` filters `previous` by kind). +- `src/canvas/ModelConnectionForm.tsx`, reachable from Settings → model connections → + “Add a connection (multi-modal)” and from the per-kind service list. +- Tests: `tests/test_model_catalog.py` (discovery isolation), `tests/test_model_configs.py` + (one providerId across kinds, partial failure, retry reusing the connection, rejected input) and the + browser workflow `tests/browser/model_connection.mjs`. + +Not delivered yet: first-run wizard entry, CLI/agent tool parity, reusing an existing connection to add +only a missing kind from the settings list, and translating the panel into the per-kind forms. + +## Problem + +Configuration is currently kind-scoped end to end: + +- UI: `src/canvas/ModelServiceForm.tsx` holds one `kind`; entering the first-run wizard for a MiniMax account with text, image, video and speech models means repeating the same URL and key four times. +- Discovery: `POST /api/model-configs/discover` takes a single `kind` and derives one protocol via `connection_fields()` (`packages/core/src/opendirector/domain/model_connection.py`), so `/models` is read under one protocol only. +- Save: `POST /api/model-configs/batch` accepts one `kind` plus `modelIds` (`apps/api/src/opendirector_api/main.py`). + +The storage layer already models the missing concept: `providerId` groups configurations of different kinds that share `url`, `apiKey`, `connectionType`, `authMode` and `proxyMode` (`packages/core/src/opendirector/infrastructure/model_configs.py`). Today a user can only reach a shared connection by editing an existing configuration, never by creating one. + +## Goals + +1. One form fills address, authentication, proxy mode, capability-check policy, then adds models for several kinds in one pass. +2. Everything saved in that pass belongs to one `providerId`, so later credential edits apply to all kinds. +3. Model ability remains per-kind: a connection is not a claim that every model supports every operation. +4. Partial success is explicit: the user sees which kinds saved, which were rejected and why, and can retry only the failed part. +5. UI, CLI and agent tools keep using the same application service; no entry point gets a private shortcut. + +Non-goals: automatic protocol guessing for self-hosted servers, cross-kind capability inference from model names, credential storage changes, migration of existing configurations. + +## Object model + +``` +Connection (draft or stored providerId) + url, apiKey, connectionType, authMode, proxyMode, capabilityAutoCheck + └── KindEntry (kind, protocol, modelIds[]) # one per kind in this pass + └── ModelConfig (existing object, unchanged) # id, kind, modelId, protocol, ... +``` + +- A connection is identified by `providerId` only after the first successful save; drafts never persist identity. +- `protocol` stays on the kind entry, not on the connection: `openai` for agent/image/audio and `minimax_video_v2`/`kling_video`/`bigmodel_video`/`vllm_omni` for video are not interchangeable. +- A connection may exist with only some kinds configured. Missing kinds are absent, not empty. + +## Discovery + +For each kind the client asks the server to discover models for that kind's candidate protocol: + +- `openai` kinds use `GET {url}/models` through `read_service_models()` (`packages/core/src/opendirector/integrations/model_capabilities.py`). +- Built-in-declaration protocols (`minimax_video_v2`, `kling_video`, `bigmodel_video`, `higgsfield_open`) return the declared list without a network call, as they do today. +- Model ids that appear in several kinds are kept per kind; a shared id is not evidence of shared input rules. + +New endpoint: `POST /api/model-configs/discover-many` with `{url, apiKey, connectionType, authMode, proxyMode, kinds: [{kind, protocol}]}` returning +`{results: [{kind, protocol, models: [id], error: null | {code, message}}]}`. + +Rules: + +- One kind failing does not abort the others; each result carries its own error. +- Total discovery is bounded (kinds requested, response sizes, timeout) so a hung upstream cannot block the form. +- The draft is never written to disk; a failed discovery leaves configuration untouched (same contract as `read_service_models` today). + +## Save + +New endpoint: `POST /api/model-configs/connections` with +`{url, apiKey, connectionType, authMode, proxyMode, capabilityAutoCheck, providerId?, entries: [{kind, protocol, modelIds, modelOptions?}]}`. + +Server behavior: + +1. Validate the connection once (`model_fields`, `connection_fields` per entry). +2. Allocate or reuse `providerId`. +3. Save each entry through the existing `save_many()` path so per-kind rules, duplicate checks and capability declarations still apply. +4. Apply the connection fields to every peer carrying that `providerId`, as `save()` already does. +5. Return `{providerId, saved: [ModelConfig], rejected: [{kind, code, message}], remaining: [...]}`. + +Failure semantics: entries are independent commits. A rejected entry (invalid model id, missing capability declaration, key rejected for that kind) does not roll back the saved ones; the response reports both sets and the UI offers "retry failed kinds" which reuses the same connection fields. This must not be described as all-or-nothing success. + +Idempotency: the request carries an operation id; replaying it with identical input returns the original receipt, and replaying it with different input is rejected, consistent with other mutations. + +## Capability checks + +- `capabilityAutoCheck` stays a connection-level default but each model keeps its own availability record (`docs/guides/model-availability.md`). +- A saved model never blocks on capability probing; probing failure produces an explainable unavailable state, not a failed save. +- Video entries keep explicit `videoCapabilities` requirements; a connection with video models still needs output declarations or manual configuration. + +## UI flow + +1. `添加服务` becomes `添加连接`: provider preset, address, auth, proxy, capability-check policy. +2. `获取模型` runs discovery for every supported kind in one request; results render as collapsible kind sections with per-kind counts and errors. +3. Selecting models across sections enables one `保存连接` action; the footer reports `将启用 N 个模型(语言 x、图片 y、视频 z)`. +4. Save result screen lists saved kinds and rejected kinds with reasons, each with `重试` and `编辑`. +5. First-run wizard (`src/canvas/WelcomeScreen.tsx`) reuses the same component: after saving, the task step only asks for kinds the connection did not provide. +6. Settings → model access lists connections with their kinds, so the user can add a missing kind to an existing connection instead of creating a duplicate service. + +Existing single-kind editing stays available for configurations that are not part of a connection and for self-hosted servers. + +## Bilingual and accessibility + +- Every new message key ships in `zh-CN` and `en-US`; stable values (`providerId`, kind ids, protocol ids) are never translated. +- Kind counts and partial-failure summaries use plural messages, not string concatenation. +- The save footer and the partial-failure list are announced via `role="status"`/`role="alert"`; focus moves to the first rejected entry. + +## Testing + +- Application tests: connection save creates one `providerId` across kinds; credential edit propagates to peers; duplicate model ids within a kind rejected; partially failing entries report saved/rejected sets and stay retryable. +- Discovery tests: one kind returning HTTP 401 while another succeeds; built-in declaration protocols skip the network; oversized responses rejected. +- Browser workflow: `tests/browser/first_run.mjs`-style isolated journey that configures text+image through one connection and asserts the assistant and image selections point at different kinds of the same `providerId`. +- CLI/agent parity: creating the same connection through the business CLI produces identical configuration rows. + +## Compatibility and rollout + +- Existing per-kind endpoints and configurations keep working; no migration, no rewriting of stored `providerId` values. +- The new connection entry point ships behind the same capability contract, so agent tools and CLI gain it only after the application service exists. +- Open question: whether `audio` and `vision` kinds should appear in the default multi-kind discovery, or only after the user picks a task that needs them. diff --git a/packages/core/src/opendirector/application/model_catalog.py b/packages/core/src/opendirector/application/model_catalog.py index 99eb4ac73..1d129ec87 100644 --- a/packages/core/src/opendirector/application/model_catalog.py +++ b/packages/core/src/opendirector/application/model_catalog.py @@ -60,6 +60,48 @@ def save_many(self, kind, url, model_ids, api_key, config_id=None, **options): def delete(self, config_id): self.configs.delete(config_id) + async def discover_many(self, kinds, url, api_key, *, connection_type='api', auth_mode=None, proxy_mode=None, + provider_id=None): + """Read model declarations for several modalities of one address. + + One modality failing does not abort the others; each result carries its + own error so the caller can retry only that part. + """ + existing = self._connection_key_source(provider_id) + if existing and existing.get('url') == (url or '').strip() and not api_key: + api_key = existing.get('apiKey', '') + outcomes = await asyncio.gather(*( + self._discover_one(kind['kind'], url, api_key, connection_type=connection_type, + protocol=kind.get('protocol'), auth_mode=auth_mode, proxy_mode=proxy_mode) + for kind in kinds)) + return [{'kind': kind['kind'], 'protocol': outcome['protocol'], 'models': outcome['models'], 'error': outcome['error']} + for kind, outcome in zip(kinds, outcomes)] + + def _connection_key_source(self, provider_id): + if not provider_id: + return None + return next((dict(row) for row, private in self.configs.catalog_snapshot() + if row.get('providerId') == str(provider_id)), None) + + async def _discover_one(self, kind, url, api_key, *, connection_type, protocol, auth_mode, proxy_mode): + try: + config = _draft(kind, url, 'discovery', api_key, connection_type, protocol, auth_mode, proxy_mode) + models = await read_service_models(config) + return {'protocol': config['protocol'], 'models': list(dict.fromkeys(item['id'] for item in models)), 'error': None} + except ProjectError as error: + resolved = None + try: + resolved = connection_fields(kind, connection_type, protocol, auth_mode, proxy_mode)['protocol'] + except ProjectError: + pass + return {'protocol': resolved, 'models': [], 'error': {'code': error.code, 'message': str(error)}} + + def save_connection(self, entries, url, api_key, *, connection_type='api', auth_mode=None, proxy_mode=None, + capability_auto_check=None, provider_id=None): + return self.configs.save_connection(url, api_key, entries, connection_type=connection_type, + auth_mode=auth_mode, proxy_mode=proxy_mode, + capability_auto_check=capability_auto_check, provider_id=provider_id) + def delete_service(self, config_id): self.configs.delete_service(config_id) diff --git a/packages/core/src/opendirector/infrastructure/model_configs.py b/packages/core/src/opendirector/infrastructure/model_configs.py index 9494704c4..1d1b783f9 100644 --- a/packages/core/src/opendirector/infrastructure/model_configs.py +++ b/packages/core/src/opendirector/infrastructure/model_configs.py @@ -173,7 +173,7 @@ def _write(self, models: list[dict]) -> None: def save_many(self, kind: str, url: str, model_ids: list[str], api_key: str, config_id: str | None = None, *, connection_type='api', protocol=None, - auth_mode=None, proxy_mode=None, video_adapter=None, video_capabilities=None, input_modalities=None, model_options=None, capabilities_supplied=False, capability_auto_check=None) -> list[dict]: + auth_mode=None, proxy_mode=None, video_adapter=None, video_capabilities=None, input_modalities=None, model_options=None, capabilities_supplied=False, capability_auto_check=None, provider_id=None) -> list[dict]: if capability_auto_check is not None and type(capability_auto_check) is not bool: raise ProjectError('自动能力检查设置必须为布尔值。') if kind not in MODEL_KINDS or not 1 <= len(model_ids) <= 200: @@ -202,9 +202,14 @@ def save_many(self, kind: str, url: str, model_ids: list[str], api_key: str, if not existing or existing['url'] != fields[0]['url'] or not existing['apiKey']: raise ProjectError('请填写该服务的 API Key;新地址不能复用原地址的密钥。') key = existing['apiKey'] - provider_id = existing.get('providerId', existing['id']) if existing else str(uuid4()) + provider_id = provider_id or (existing.get('providerId', existing['id']) if existing else str(uuid4())) auto_check = capability_auto_check if capability_auto_check is not None else (existing or {}).get('capabilityAutoCheck') - previous = [item for item in models if item.get('providerId') == provider_id or item['id'] == config_id] + # A connection may hold several kinds, so only this kind's models are + # replaced; peers of other kinds keep their rows and only inherit the + # connection fields below. + previous = [item for item in models + if (item.get('providerId') == provider_id and (item['kind'] == kind or (legacy_segmentation and item['id'] == config_id))) + or item['id'] == config_id] peers = {item['modelId']: item for item in previous} saved = [] for field in fields: @@ -234,6 +239,47 @@ def save_many(self, kind: str, url: str, model_ids: list[str], api_key: str, self._write(remaining + saved) return [self._public(item) for item in saved] + def save_connection(self, url: str, api_key: str, entries: list[dict], *, connection_type='api', auth_mode=None, + proxy_mode=None, capability_auto_check=None, provider_id=None) -> dict: + """Save several modalities of one address and credential as one connection. + + Entries commit independently: a rejected modality does not roll back the + ones that were saved, and the receipt reports both sets so callers can + retry only the failures. + """ + if not 1 <= len(entries) <= len(MODEL_KINDS): + raise ProjectError('请选择 1—5 个模态。') + if len({entry['kind'] for entry in entries}) != len(entries): + raise ProjectError('同一连接中每个模态只能出现一次。') + if capability_auto_check is not None and type(capability_auto_check) is not bool: + raise ProjectError('自动能力检查设置必须为布尔值。') + model_fields(url, 'connection', api_key) + kinds = [item['kind'] for item in entries] + if len(set(kinds)) != len(kinds): + raise ProjectError('同一连接中每个模态只能出现一次。') + with self.lock: + existing = self._read() + reused = next((item for item in existing if provider_id and item.get('providerId') == str(provider_id)), None) + if provider_id and reused is None: + raise ProjectError('连接已被删除,请重新加载。', 404) + shared = str(provider_id) if provider_id else str(uuid4()) + saved, rejected = [], [] + for entry in entries: + try: + saved.extend(self.save_many(entry['kind'], url, entry['modelIds'], api_key, provider_id=shared, + connection_type=connection_type, protocol=entry.get('protocol'), + auth_mode=auth_mode, proxy_mode=proxy_mode, + model_options=entry.get('modelOptions'), + capability_auto_check=capability_auto_check)) + except ProjectError as error: + rejected.append({'kind': entry['kind'], 'code': getattr(error, 'code', None) or 'connection_entry_invalid', + 'message': str(error)}) + if not saved: + raise ProjectError('这个连接没有保存任何模型。', 400) + with self.lock: + peers = [item for item in self._read() if item.get('providerId') == shared] + return {'providerId': shared, 'saved': saved, 'rejected': rejected, 'kinds': sorted({item['kind'] for item in peers})} + def delete_service(self, config_id: str) -> None: with self.lock: models = self._read() diff --git a/scripts/run-browser-suite.mjs b/scripts/run-browser-suite.mjs index 46ba6ca0b..a08bc304a 100644 --- a/scripts/run-browser-suite.mjs +++ b/scripts/run-browser-suite.mjs @@ -81,6 +81,7 @@ const workflows = [ env: { PYTHON: "python" }, }, { name: "first-run setup", script: "tests/browser/first_run.mjs" }, + { name: "multimodal connection", script: "tests/browser/model_connection.mjs" }, { name: "model editor hosts", script: "tests/browser/model_editor_hosts.mjs" }, ]; diff --git a/src/backend/models.ts b/src/backend/models.ts index d1f50f130..eef1a18d7 100644 --- a/src/backend/models.ts +++ b/src/backend/models.ts @@ -72,6 +72,53 @@ export function discoverModels(value: ModelConfigInput, configId?: string) { ); } +export type ConnectionKind = Exclude; + +export interface ConnectionDiscoveryRequest { + url: string; + apiKey: string; + connectionType: "api" | "self_hosted"; + authMode: "none" | "bearer"; + proxyMode: "system" | "direct"; + kinds: { kind: ConnectionKind; protocol: NonNullable }[]; +} + +export interface ConnectionDiscoveryResult { + kind: ConnectionKind; + protocol: NonNullable | null; + models: string[]; + error: { code: string; message: string } | null; +} + +export function discoverConnectionModels(value: ConnectionDiscoveryRequest) { + return request<{ results: ConnectionDiscoveryResult[] }>( + "/model-configs/discover-many", + json("POST", value), + ); +} + +export interface ConnectionSaveRequest { + url: string; + apiKey: string; + connectionType: "api" | "self_hosted"; + authMode: "none" | "bearer"; + proxyMode: "system" | "direct"; + capabilityAutoCheck?: boolean | null; + providerId?: string; + entries: { + kind: ConnectionKind; + protocol: NonNullable; + modelIds: string[]; + }[]; +} + +export interface ConnectionSaveReceipt { + providerId: string; + saved: ModelConfig[]; + rejected: { kind: ConnectionKind; code: string; message: string }[]; + kinds: ConnectionKind[]; +} + export function testAgentModel(value: ModelConfigInput, configId?: string) { return request<{ elapsedMs: number }>( "/model-configs/test-agent", @@ -292,6 +339,17 @@ export function useBackendModels() { await refresh(); void refreshAvailability([saved.id]); }; + const saveConnection = async (value: ConnectionSaveRequest) => { + epoch.current += 1; + const receipt = await request( + "/model-configs/connections", + json("POST", value), + ); + await refresh(); + void refreshAvailability(receipt.saved.map((model) => model.id)); + return receipt; + }; + const saveMany = async ( value: ModelConfigInput, modelIds: string[], @@ -341,6 +399,8 @@ export function useBackendModels() { refresh, save, saveMany, + saveConnection, + discoverConnectionModels, remove, removeService, updateSettings, diff --git a/src/canvas/ModelConnectionForm.tsx b/src/canvas/ModelConnectionForm.tsx new file mode 100644 index 000000000..b966ec959 --- /dev/null +++ b/src/canvas/ModelConnectionForm.tsx @@ -0,0 +1,313 @@ +import { useId, useState, type FormEvent } from "react"; +import { errorMessage } from "../backend/api.ts"; +import { + MODEL_KINDS, + type BackendModels, + type ConnectionKind, + type ConnectionSaveReceipt, +} from "../backend/models.ts"; +import type { ModelConfig } from "../backend/rules.ts"; +import { useT } from "../i18n/I18nProvider"; +import type { MessageKey } from "../i18n/types"; +import { CanvasIcon } from "./CanvasIcon"; + +type Protocol = NonNullable; +type KindState = { + enabled: boolean; + protocol: Protocol; + models: string[]; + selected: string[]; + error: string; + fetched: boolean; +}; + +const KIND_PROTOCOLS: Record = { + agent: ["openai"], + image: ["openai", "volcengine"], + audio: ["openai", "volcengine"], + video: ["minimax_video_v2", "kling_video", "bigmodel_video", "higgsfield_open", "vllm_omni"], +}; +const PROTOCOL_LABELS: Record = { + openai: "models.protocolOption.openaiAgent", + volcengine: "models.protocolOption.volcengine", + minimax_video_v2: "models.protocolOption.minimaxVideo", + kling_video: "models.protocolOption.klingVideo", + bigmodel_video: "models.protocolOption.bigmodelVideo", + higgsfield_open: "models.protocolOption.higgsfieldOpen", + vllm_omni: "models.protocolOption.videos", +}; + +function initialKinds(): Record { + const state = {} as Record; + for (const { id } of MODEL_KINDS) { + state[id] = { + enabled: id === "agent", + protocol: KIND_PROTOCOLS[id][0], + models: [], + selected: [], + error: "", + fetched: false, + }; + } + return state; +} + +/** + * Adds one connection (address + credential) that carries several modalities. + * Discovery and saving stay per kind so a modality can fail without discarding + * the ones that succeeded. + */ +export function ModelConnectionForm({ + catalog, + onClose, + onSaved, +}: { + catalog: BackendModels; + onClose: () => void; + onSaved?: (receipt: ConnectionSaveReceipt) => void; +}) { + const t = useT(); + const fieldId = useId(); + const [url, setUrl] = useState(""); + const [apiKey, setApiKey] = useState(""); + const [showKey, setShowKey] = useState(false); + const [authMode, setAuthMode] = useState<"none" | "bearer">("bearer"); + const [proxyMode, setProxyMode] = useState<"system" | "direct">("direct"); + const [capabilityAutoCheck, setCapabilityAutoCheck] = useState(true); + const [kinds, setKinds] = useState(initialKinds); + const [discovering, setDiscovering] = useState(false); + const [discoveryError, setDiscoveryError] = useState(""); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(""); + const [receipt, setReceipt] = useState(null); + const enabled = (Object.keys(kinds) as ConnectionKind[]).filter((kind) => kinds[kind].enabled); + const selectedCount = enabled.reduce((total, kind) => total + kinds[kind].selected.length, 0); + const locked = busy || discovering; + const update = (kind: ConnectionKind, patch: Partial) => + setKinds((current) => ({ ...current, [kind]: { ...current[kind], ...patch } })); + + const discover = async () => { + if (locked || !enabled.length) return; + setDiscovering(true); + setDiscoveryError(""); + setError(""); + try { + const { results } = await catalog.discoverConnectionModels({ + url, + apiKey: authMode === "none" ? "" : apiKey, + connectionType: "api", + authMode, + proxyMode, + kinds: enabled.map((kind) => ({ kind, protocol: kinds[kind].protocol })), + }); + setKinds((current) => { + const next = { ...current }; + for (const result of results) { + const state = next[result.kind]; + if (!state) continue; + next[result.kind] = { + ...state, + models: result.models, + selected: result.error ? [] : result.models.filter((id) => state.selected.includes(id)), + error: result.error?.message ?? "", + fetched: !result.error, + }; + } + return next; + }); + if (results.every((result) => result.error)) setDiscoveryError(t("models.connection.discoveryFailed")); + } catch (failure) { + setDiscoveryError(errorMessage(failure)); + } finally { + setDiscovering(false); + } + }; + + const submit = async (event: FormEvent) => { + event.preventDefault(); + if (locked) return; + const entries = enabled + .filter((kind) => kinds[kind].selected.length) + .map((kind) => ({ kind, protocol: kinds[kind].protocol, modelIds: kinds[kind].selected })); + if (!entries.length) { + setError(t("models.connection.selectAtLeastOne")); + return; + } + setBusy(true); + setError(""); + try { + const saved = await catalog.saveConnection({ + url, + apiKey: authMode === "none" ? "" : apiKey, + connectionType: "api", + authMode, + proxyMode, + capabilityAutoCheck, + providerId: receipt?.providerId, + entries, + }); + setReceipt(saved); + if (!saved.rejected.length) onSaved?.(saved); + } catch (failure) { + setError(errorMessage(failure)); + } finally { + setBusy(false); + } + }; + + return ( +
void submit(event)} + > +
+ +
+

{t("models.connection.title")}

+

{t("models.connection.subtitle")}

+
+
+
+

{t("models.connection.hint")}

+
+
+ +
+
+ +
+
+ +
+
+
+
+ + +
+
+ setApiKey(event.target.value)} /> + +
+
+
+ {t("models.connection.kindsLabel")} + {MODEL_KINDS.map((spec) => { + const state = kinds[spec.id]; + const kindLabel = t(spec.labelKey); + return ( +
+
+ + {state.enabled && ( + + )} + {state.enabled && state.fetched && ( + + {t("models.connection.kindSelected", { count: state.selected.length })} + + )} +
+ {state.enabled && state.error &&

{state.error}

} + {state.enabled && state.models.length > 0 && ( +
+ {state.models.map((id) => ( + + ))} +
+ )} +
+ ); + })} +
+ {discoveryError &&

{discoveryError}

} + {receipt && ( +
+

{t("models.connection.savedKinds", { count: receipt.saved.length })}

+ {receipt.rejected.length > 0 && ( +
    + {receipt.rejected.map((item) => ( +
  • {t("models.connection.rejected", { + kind: t(MODEL_KINDS.find((spec) => spec.id === item.kind)?.labelKey ?? "models.category.agent"), + message: item.message, + })}
  • + ))} +
+ )} +
+ )} +
+
+

+ {selectedCount + ? t("models.service.willEnable", { count: selectedCount }) + : t("models.connection.selectAtLeastOne")} +

+ + + + {error &&

{error}

} +
+
+ ); +} diff --git a/src/canvas/ModelSettings.tsx b/src/canvas/ModelSettings.tsx index 0dc2096ec..c56c7f966 100644 --- a/src/canvas/ModelSettings.tsx +++ b/src/canvas/ModelSettings.tsx @@ -8,6 +8,7 @@ import { MODEL_KINDS, type BackendModels } from "../backend/models.ts"; import type { ModelConfig } from "../backend/rules.ts"; import { useT } from "../i18n/I18nProvider"; import { ModelServiceForm, type SettingsModelKind } from "./ModelServiceForm"; +import { ModelConnectionForm } from "./ModelConnectionForm"; import { CanvasIcon } from "./CanvasIcon"; import "./model-settings.css"; @@ -26,6 +27,7 @@ export function ModelSettings({ kind: SettingsModelKind; model?: ModelConfig; } | null>(null); + const [addingConnection, setAddingConnection] = useState(false); const [deleting, setDeleting] = useState(null); const [busy, setBusy] = useState(false); const [error, setError] = useState(""); @@ -59,7 +61,11 @@ export function ModelSettings({ if (visibleIds && catalog.connected) void checkAvailability(visibleIds.split(",")); }, [visibleIds, catalog.connected, checkAvailability]); if (category === null) return
- + {addingConnection + ? setAddingConnection(false)} + onSaved={() => setAddingConnection(false)} /> + : setAddingConnection(true)} />}
; return (
@@ -75,7 +81,13 @@ export function ModelSettings({
)} {catalog.connected && - (editing ? ( + (addingConnection ? ( + setAddingConnection(false)} + onSaved={() => setAddingConnection(false)} + /> + ) : editing ? (

{t("models.services.hint")}

+ {services.length > 0 && ( + + )} {services.length > 0 && ( + )} {services.map((model) => { diff --git a/src/canvas/ModelSetup.tsx b/src/canvas/ModelSetup.tsx index efa67ec2c..c65a3c408 100644 --- a/src/canvas/ModelSetup.tsx +++ b/src/canvas/ModelSetup.tsx @@ -20,10 +20,11 @@ function modelSetupMissing(models: ModelConfig[]) { return kinds.filter(kind => !models.some(model => model.kind === kind && isGenerationModel(model))); } -export function ModelSetup({ catalog, onClose, onConfigure }: { +export function ModelSetup({ catalog, onClose, onConfigure, onAddConnection }: { catalog: BackendModels; onClose: () => void; onConfigure: (kind: SetupKind) => void; + onAddConnection?: () => void; }) { const { t, locale, setLocale } = useI18n(); const missing = modelSetupMissing(catalog.models); @@ -57,6 +58,11 @@ export function ModelSetup({ catalog, onClose, onConfigure }: {