Skip to content

AI-native design editor. Open-source Figma alternative.

feat(ai): configure reusable model profiles

Danila Poyarkove56727c22c69
diff --git a/AGENTS.md b/AGENTS.md
index cdf33f19f..6672cf20c 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -149,7 +149,7 @@ Release commits are the exception: keep using `Release v0.x.y`.
Keep this section light; implementation details move often.
-- ACP UI/transport lives under `src/app/ai/acp/**`; provider definitions live in `packages/core/src/constants.ts`; app prompts live under `src/app/ai/**`. Public docs: `packages/docs/programmable/ai-chat.md` and `packages/docs/programmable/mcp-server.md`.
+- ACP UI/transport lives under `src/app/ai/acp/**`; provider definitions live in `packages/core/src/constants.ts`; app prompts live under `src/app/ai/**`. Direct model configuration lives under `src/app/ai/models/**`: reusable profiles reference provider connections, roles resolve to profiles, and runtime creation resolves credentials lazily. Keep model profiles, provider connections, and role assignments separate rather than returning to singleton provider/model settings. Public docs: `packages/docs/programmable/ai-chat.md` and `packages/docs/programmable/mcp-server.md`.
- ACP transport uses Tauri shell permissions, so check `desktop/capabilities/**` when changing agent launch behavior.
- Collaboration lives under `src/app/collab/**` and is documented in `packages/docs/programmable/collaboration.md`. It uses Trystero + Yjs + awareness; preserve crypto-safe room IDs and peer cleanup semantics when changing it.
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 123ce7881..4c2634ac3 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -20,6 +20,7 @@
- Target a specific open document and page from live CLI and MCP automation, including sessions with multiple documents.
- Test OpenAI-compatible provider connections from AI settings with clearer setup errors.
- Manage AI, agent, and media credentials from unified Settings, using the system credential store on desktop and optional encrypted storage in the browser.
+- Assign separate Design, Review, Fast, and Vision models, providers, endpoints, and credentials from AI settings.
- Connect an S3-compatible storage workspace with local-first saves, background synchronization, and centrally managed credentials.
- Build custom property panels with new Vue SDK number fields, bindable values, property sections, responsive property grids, segmented controls, property lists, color models, fill controls, and gradient primitives.
- Connect local MCP clients through automatically discovered private Unix sockets on macOS and Linux, with localhost TCP fallback. (#338)
@@ -29,6 +30,7 @@
- Choose Freeform, vertical, horizontal, or grid flow directly from the contextual Layout section, with sizing grouped alongside it and current Layout guide terminology.
- Redesign the editor chrome and Design panel with denser aligned controls, clearer selection and section states, improved menus and overlays, consistent light/dark theming, and better keyboard and screen-reader behavior.
+- Center full-area empty and setup states consistently across panels, dialogs, and workspaces.
- Scale the Layers panel to documents with thousands of nodes through virtualized rows, faster incremental updates, stable expansion, range selection, and scroll-to-selection.
- Resolve fonts before text appears, with language-aware CJK and Arabic fallback, character-specific remote subsets, and more reliable rendering as fonts load.
- Open and save large `.fig` documents substantially faster while preserving original metadata and user edits; corrupted compressed data now reports an error instead of being opened as valid content.
diff --git a/packages/docs/programmable/ai-chat.md b/packages/docs/programmable/ai-chat.md
index 8c336d781..96957d76e 100644
--- a/packages/docs/programmable/ai-chat.md
+++ b/packages/docs/programmable/ai-chat.md
@@ -11,8 +11,10 @@ Press <kbd>⌘</kbd><kbd>J</kbd> (<kbd>Ctrl</kbd> + <kbd>J</kbd>) to open the AI
1. Open the AI chat panel (<kbd>⌘</kbd><kbd>J</kbd>)
2. Click the settings icon
-3. Choose a provider and enter your API key
-4. Select a model
+3. Add a model and configure its provider, model ID, credentials, and capabilities
+4. Save the model and assign it to **Design agent**
+
+You can configure multiple reusable models and separately assign models for design work, reviews, fast tasks, and image input. Models using the same provider connection reuse its stored credential.
### Supported Providers
diff --git a/packages/vue/src/i18n/locales/de/dialogs.json b/packages/vue/src/i18n/locales/de/dialogs.json
index 7f6e848ae..dc0a8107c 100644
--- a/packages/vue/src/i18n/locales/de/dialogs.json
+++ b/packages/vue/src/i18n/locales/de/dialogs.json
@@ -68,6 +68,35 @@
"settings": "Einstellungen",
"settingsDescription": "Integrationen und App-Einstellungen verwalten.",
"settingsAIAndAgents": "KI und Agenten",
+ "models": "Modelle",
+ "modelsDescription": "Wiederverwendbare Modelle und ihre Anbieter-Verbindungen konfigurieren.",
+ "addModel": "Modell hinzufügen",
+ "editModel": "Modell bearbeiten",
+ "modelEditorDescription": "Anbieter, Modell, Zugangsdaten und Fähigkeiten.",
+ "modelName": "Name",
+ "modelCapabilities": "Fähigkeiten",
+ "modelCapabilityTools": "Werkzeugaufrufe",
+ "modelCapabilityVision": "Bildeingabe",
+ "modelCapabilityToolsShort": "Werkzeuge",
+ "modelCapabilityVisionShort": "Vision",
+ "modelNeedsCredential": "Schlüssel fehlt",
+ "modelAgentConnection": "Agent",
+ "saveModel": "Modell speichern",
+ "deleteModel": "Modell löschen",
+ "deleteModelDescription": "Dieses Modell und seine Rollenzuweisungen löschen?",
+ "modelAssignments": "Zuweisungen",
+ "modelAssignmentsDescription": "Lege fest, welches Modell welche Aufgabe übernimmt.",
+ "modelRoleDesign": "Design-Agent",
+ "modelRoleReview": "Prüfung",
+ "modelRoleFast": "Schnelle Aufgaben",
+ "modelRoleVision": "Vision",
+ "modelRoleDesignDescription": "KI-Chat und Canvas-Bearbeitung",
+ "modelRoleReviewDescription": "Explizite Plan- und Designprüfungen",
+ "modelRoleFastDescription": "Kostengünstige Hintergrundarbeit",
+ "modelRoleVisionDescription": "Screenshots und Bildreferenzen",
+ "modelRoleUseDesign": "Wie Design",
+ "noModel": "Keines",
+ "back": "Zurück",
"settingsMedia": "Medien",
"settingsStorage": "Cloud-Speicher",
"storageWorkspace": "Speicher-Arbeitsbereich",
diff --git a/packages/vue/src/i18n/locales/es/dialogs.json b/packages/vue/src/i18n/locales/es/dialogs.json
index 503828225..a5c88b29c 100644
--- a/packages/vue/src/i18n/locales/es/dialogs.json
+++ b/packages/vue/src/i18n/locales/es/dialogs.json
@@ -68,6 +68,35 @@
"settings": "Ajustes",
"settingsDescription": "Gestiona integraciones y preferencias de la aplicación.",
"settingsAIAndAgents": "IA y agentes",
+ "models": "Modelos",
+ "modelsDescription": "Configura modelos reutilizables y sus conexiones de proveedor.",
+ "addModel": "Añadir modelo",
+ "editModel": "Editar modelo",
+ "modelEditorDescription": "Proveedor, modelo, credenciales y capacidades.",
+ "modelName": "Nombre",
+ "modelCapabilities": "Capacidades",
+ "modelCapabilityTools": "Uso de herramientas",
+ "modelCapabilityVision": "Entrada de imágenes",
+ "modelCapabilityToolsShort": "Herramientas",
+ "modelCapabilityVisionShort": "Visión",
+ "modelNeedsCredential": "Falta la clave",
+ "modelAgentConnection": "Agente",
+ "saveModel": "Guardar modelo",
+ "deleteModel": "Eliminar modelo",
+ "deleteModelDescription": "¿Eliminar este modelo y sus asignaciones de rol?",
+ "modelAssignments": "Asignaciones",
+ "modelAssignmentsDescription": "Elige qué modelo configurado gestiona cada tipo de trabajo.",
+ "modelRoleDesign": "Agente de diseño",
+ "modelRoleReview": "Revisión",
+ "modelRoleFast": "Tareas rápidas",
+ "modelRoleVision": "Visión",
+ "modelRoleDesignDescription": "Chat de IA y edición del lienzo",
+ "modelRoleReviewDescription": "Revisiones explícitas de planes y diseños",
+ "modelRoleFastDescription": "Trabajo económico en segundo plano",
+ "modelRoleVisionDescription": "Capturas y referencias visuales",
+ "modelRoleUseDesign": "Igual que Diseño",
+ "noModel": "Ninguno",
+ "back": "Atrás",
"settingsMedia": "Multimedia",
"settingsStorage": "Almacenamiento en la nube",
"storageWorkspace": "Espacio de almacenamiento",
diff --git a/packages/vue/src/i18n/locales/fr/dialogs.json b/packages/vue/src/i18n/locales/fr/dialogs.json
index 377bdc408..0ddc77c64 100644
--- a/packages/vue/src/i18n/locales/fr/dialogs.json
+++ b/packages/vue/src/i18n/locales/fr/dialogs.json
@@ -68,6 +68,35 @@
"settings": "Paramètres",
"settingsDescription": "Gérez les intégrations et les préférences de l’application.",
"settingsAIAndAgents": "IA et agents",
+ "models": "Modèles",
+ "modelsDescription": "Configurez des modèles réutilisables et leurs connexions fournisseur.",
+ "addModel": "Ajouter un modèle",
+ "editModel": "Modifier le modèle",
+ "modelEditorDescription": "Fournisseur, modèle, identifiants et capacités.",
+ "modelName": "Nom",
+ "modelCapabilities": "Capacités",
+ "modelCapabilityTools": "Appels d’outils",
+ "modelCapabilityVision": "Entrée d’images",
+ "modelCapabilityToolsShort": "Outils",
+ "modelCapabilityVisionShort": "Vision",
+ "modelNeedsCredential": "Clé requise",
+ "modelAgentConnection": "Agent",
+ "saveModel": "Enregistrer le modèle",
+ "deleteModel": "Supprimer le modèle",
+ "deleteModelDescription": "Supprimer ce modèle et ses affectations de rôle ?",
+ "modelAssignments": "Affectations",
+ "modelAssignmentsDescription": "Choisissez le modèle configuré pour chaque type de tâche.",
+ "modelRoleDesign": "Agent de design",
+ "modelRoleReview": "Révision",
+ "modelRoleFast": "Tâches rapides",
+ "modelRoleVision": "Vision",
+ "modelRoleDesignDescription": "Chat IA et modifications du canevas",
+ "modelRoleReviewDescription": "Révisions explicites des plans et designs",
+ "modelRoleFastDescription": "Travail économique en arrière-plan",
+ "modelRoleVisionDescription": "Captures et références visuelles",
+ "modelRoleUseDesign": "Comme Design",
+ "noModel": "Aucun",
+ "back": "Retour",
"settingsMedia": "Médias",
"settingsStorage": "Stockage cloud",
"storageWorkspace": "Espace de stockage",
diff --git a/packages/vue/src/i18n/locales/it/dialogs.json b/packages/vue/src/i18n/locales/it/dialogs.json
index 8a9e4f3f5..b4916194a 100644
--- a/packages/vue/src/i18n/locales/it/dialogs.json
+++ b/packages/vue/src/i18n/locales/it/dialogs.json
@@ -68,6 +68,35 @@
"settings": "Impostazioni",
"settingsDescription": "Gestisci integrazioni e preferenze dell’app.",
"settingsAIAndAgents": "IA e agenti",
+ "models": "Modelli",
+ "modelsDescription": "Configura modelli riutilizzabili e le connessioni ai provider.",
+ "addModel": "Aggiungi modello",
+ "editModel": "Modifica modello",
+ "modelEditorDescription": "Provider, modello, credenziali e funzionalità.",
+ "modelName": "Nome",
+ "modelCapabilities": "Funzionalità",
+ "modelCapabilityTools": "Chiamate agli strumenti",
+ "modelCapabilityVision": "Input immagini",
+ "modelCapabilityToolsShort": "Strumenti",
+ "modelCapabilityVisionShort": "Visione",
+ "modelNeedsCredential": "Chiave necessaria",
+ "modelAgentConnection": "Agente",
+ "saveModel": "Salva modello",
+ "deleteModel": "Elimina modello",
+ "deleteModelDescription": "Eliminare questo modello e le relative assegnazioni?",
+ "modelAssignments": "Assegnazioni",
+ "modelAssignmentsDescription": "Scegli quale modello gestisce ogni tipo di attività.",
+ "modelRoleDesign": "Agente di design",
+ "modelRoleReview": "Revisione",
+ "modelRoleFast": "Attività rapide",
+ "modelRoleVision": "Visione",
+ "modelRoleDesignDescription": "Chat IA e modifiche alla tela",
+ "modelRoleReviewDescription": "Revisioni esplicite di piani e design",
+ "modelRoleFastDescription": "Attività economiche in background",
+ "modelRoleVisionDescription": "Screenshot e riferimenti visivi",
+ "modelRoleUseDesign": "Come Design",
+ "noModel": "Nessuno",
+ "back": "Indietro",
"settingsMedia": "Media",
"settingsStorage": "Archiviazione cloud",
"storageWorkspace": "Area di archiviazione",
diff --git a/packages/vue/src/i18n/locales/ja/dialogs.json b/packages/vue/src/i18n/locales/ja/dialogs.json
index 323fe7635..8f71feb97 100644
--- a/packages/vue/src/i18n/locales/ja/dialogs.json
+++ b/packages/vue/src/i18n/locales/ja/dialogs.json
@@ -68,6 +68,35 @@
"settings": "設定",
"settingsDescription": "連携サービスとアプリの設定を管理します。",
"settingsAIAndAgents": "AIとエージェント",
+ "models": "モデル",
+ "modelsDescription": "再利用可能なモデルとプロバイダー接続を設定します。",
+ "addModel": "モデルを追加",
+ "editModel": "モデルを編集",
+ "modelEditorDescription": "プロバイダー、モデル、認証情報、機能。",
+ "modelName": "名前",
+ "modelCapabilities": "機能",
+ "modelCapabilityTools": "ツール呼び出し",
+ "modelCapabilityVision": "画像入力",
+ "modelCapabilityToolsShort": "ツール",
+ "modelCapabilityVisionShort": "ビジョン",
+ "modelNeedsCredential": "キーが必要",
+ "modelAgentConnection": "エージェント",
+ "saveModel": "モデルを保存",
+ "deleteModel": "モデルを削除",
+ "deleteModelDescription": "このモデルと役割の割り当てを削除しますか?",
+ "modelAssignments": "割り当て",
+ "modelAssignmentsDescription": "作業の種類ごとに使用するモデルを選択します。",
+ "modelRoleDesign": "デザインエージェント",
+ "modelRoleReview": "レビュー",
+ "modelRoleFast": "高速タスク",
+ "modelRoleVision": "ビジョン",
+ "modelRoleDesignDescription": "AIチャットとキャンバス編集",
+ "modelRoleReviewDescription": "計画とデザインの明示的なレビュー",
+ "modelRoleFastDescription": "低コストのバックグラウンド処理",
+ "modelRoleVisionDescription": "スクリーンショットと画像参照",
+ "modelRoleUseDesign": "デザインと同じ",
+ "noModel": "なし",
+ "back": "戻る",
"settingsMedia": "メディア",
"settingsStorage": "クラウドストレージ",
"storageWorkspace": "ストレージワークスペース",
diff --git a/packages/vue/src/i18n/locales/pl/dialogs.json b/packages/vue/src/i18n/locales/pl/dialogs.json
index 76fd66ed0..62bcef9f2 100644
--- a/packages/vue/src/i18n/locales/pl/dialogs.json
+++ b/packages/vue/src/i18n/locales/pl/dialogs.json
@@ -68,6 +68,35 @@
"settings": "Ustawienia",
"settingsDescription": "Zarządzaj integracjami i preferencjami aplikacji.",
"settingsAIAndAgents": "AI i agenci",
+ "models": "Modele",
+ "modelsDescription": "Skonfiguruj modele wielokrotnego użytku i połączenia z dostawcami.",
+ "addModel": "Dodaj model",
+ "editModel": "Edytuj model",
+ "modelEditorDescription": "Dostawca, model, dane logowania i możliwości.",
+ "modelName": "Nazwa",
+ "modelCapabilities": "Możliwości",
+ "modelCapabilityTools": "Wywołania narzędzi",
+ "modelCapabilityVision": "Obrazy wejściowe",
+ "modelCapabilityToolsShort": "Narzędzia",
+ "modelCapabilityVisionShort": "Wizja",
+ "modelNeedsCredential": "Brak klucza",
+ "modelAgentConnection": "Agent",
+ "saveModel": "Zapisz model",
+ "deleteModel": "Usuń model",
+ "deleteModelDescription": "Usunąć ten model i jego przypisania ról?",
+ "modelAssignments": "Przypisania",
+ "modelAssignmentsDescription": "Wybierz model obsługujący każdy rodzaj pracy.",
+ "modelRoleDesign": "Agent projektowy",
+ "modelRoleReview": "Recenzja",
+ "modelRoleFast": "Szybkie zadania",
+ "modelRoleVision": "Wizja",
+ "modelRoleDesignDescription": "Czat AI i edycja obszaru roboczego",
+ "modelRoleReviewDescription": "Jawne recenzje planów i projektów",
+ "modelRoleFastDescription": "Tania praca w tle",
+ "modelRoleVisionDescription": "Zrzuty ekranu i odniesienia wizualne",
+ "modelRoleUseDesign": "Jak Projektowanie",
+ "noModel": "Brak",
+ "back": "Wstecz",
"settingsMedia": "Media",
"settingsStorage": "Przechowywanie w chmurze",
"storageWorkspace": "Obszar przechowywania",
diff --git a/packages/vue/src/i18n/locales/ru/dialogs.json b/packages/vue/src/i18n/locales/ru/dialogs.json
index 57bc0c03f..4a75ced1d 100644
--- a/packages/vue/src/i18n/locales/ru/dialogs.json
+++ b/packages/vue/src/i18n/locales/ru/dialogs.json
@@ -68,6 +68,35 @@
"settings": "Настройки",
"settingsDescription": "Управление интеграциями и настройками приложения.",
"settingsAIAndAgents": "ИИ и агенты",
+ "models": "Модели",
+ "modelsDescription": "Настройте переиспользуемые модели и подключения к провайдерам.",
+ "addModel": "Добавить модель",
+ "editModel": "Изменить модель",
+ "modelEditorDescription": "Провайдер, модель, учётные данные и возможности.",
+ "modelName": "Название",
+ "modelCapabilities": "Возможности",
+ "modelCapabilityTools": "Вызов инструментов",
+ "modelCapabilityVision": "Ввод изображений",
+ "modelCapabilityToolsShort": "Инструменты",
+ "modelCapabilityVisionShort": "Зрение",
+ "modelNeedsCredential": "Нужен ключ",
+ "modelAgentConnection": "Агент",
+ "saveModel": "Сохранить модель",
+ "deleteModel": "Удалить модель",
+ "deleteModelDescription": "Удалить эту модель и её назначения ролей?",
+ "modelAssignments": "Назначения",
+ "modelAssignmentsDescription": "Выберите модель для каждого типа работы.",
+ "modelRoleDesign": "Дизайн-агент",
+ "modelRoleReview": "Проверка",
+ "modelRoleFast": "Быстрые задачи",
+ "modelRoleVision": "Зрение",
+ "modelRoleDesignDescription": "ИИ-чат и редактирование холста",
+ "modelRoleReviewDescription": "Явная проверка планов и макетов",
+ "modelRoleFastDescription": "Недорогая фоновая работа",
+ "modelRoleVisionDescription": "Снимки экрана и визуальные референсы",
+ "modelRoleUseDesign": "Как для дизайна",
+ "noModel": "Нет",
+ "back": "Назад",
"settingsMedia": "Медиа",
"settingsStorage": "Облачное хранилище",
"storageWorkspace": "Рабочая область хранилища",
diff --git a/packages/vue/src/i18n/locales/zh-cn/dialogs.json b/packages/vue/src/i18n/locales/zh-cn/dialogs.json
index 61050fd47..606095eb0 100644
--- a/packages/vue/src/i18n/locales/zh-cn/dialogs.json
+++ b/packages/vue/src/i18n/locales/zh-cn/dialogs.json
@@ -68,6 +68,35 @@
"settings": "设置",
"settingsDescription": "管理集成和应用偏好设置。",
"settingsAIAndAgents": "AI 和代理",
+ "models": "模型",
+ "modelsDescription": "配置可复用模型及其提供商连接。",
+ "addModel": "添加模型",
+ "editModel": "编辑模型",
+ "modelEditorDescription": "提供商、模型、凭据和能力。",
+ "modelName": "名称",
+ "modelCapabilities": "能力",
+ "modelCapabilityTools": "工具调用",
+ "modelCapabilityVision": "图像输入",
+ "modelCapabilityToolsShort": "工具",
+ "modelCapabilityVisionShort": "视觉",
+ "modelNeedsCredential": "需要密钥",
+ "modelAgentConnection": "代理",
+ "saveModel": "保存模型",
+ "deleteModel": "删除模型",
+ "deleteModelDescription": "删除此模型及其角色分配?",
+ "modelAssignments": "分配",
+ "modelAssignmentsDescription": "选择每类工作使用的已配置模型。",
+ "modelRoleDesign": "设计代理",
+ "modelRoleReview": "审查",
+ "modelRoleFast": "快速任务",
+ "modelRoleVision": "视觉",
+ "modelRoleDesignDescription": "AI 聊天和画布编辑",
+ "modelRoleReviewDescription": "明确的计划和设计审查",
+ "modelRoleFastDescription": "低成本后台工作",
+ "modelRoleVisionDescription": "截图和图像参考",
+ "modelRoleUseDesign": "与设计相同",
+ "noModel": "无",
+ "back": "返回",
"settingsMedia": "媒体",
"settingsStorage": "云存储",
"storageWorkspace": "存储工作区",
diff --git a/packages/vue/src/i18n/messages/dialogs.ts b/packages/vue/src/i18n/messages/dialogs.ts
index a3173d3a5..31f885c68 100644
--- a/packages/vue/src/i18n/messages/dialogs.ts
+++ b/packages/vue/src/i18n/messages/dialogs.ts
@@ -117,6 +117,35 @@ export const dialogMessageDefaults = {
settings: 'Settings',
settingsDescription: 'Manage integrations and app preferences.',
settingsAIAndAgents: 'AI & agents',
+ models: 'Models',
+ modelsDescription: 'Configure reusable models and their provider connections.',
+ addModel: 'Add model',
+ editModel: 'Edit model',
+ modelEditorDescription: 'Provider, model, credentials, and capabilities.',
+ modelName: 'Name',
+ modelCapabilities: 'Capabilities',
+ modelCapabilityTools: 'Tool calling',
+ modelCapabilityVision: 'Image input',
+ modelCapabilityToolsShort: 'Tools',
+ modelCapabilityVisionShort: 'Vision',
+ modelNeedsCredential: 'Needs key',
+ modelAgentConnection: 'Agent',
+ saveModel: 'Save model',
+ deleteModel: 'Delete model',
+ deleteModelDescription: 'Delete this model and remove its role assignments?',
+ modelAssignments: 'Assignments',
+ modelAssignmentsDescription: 'Choose which configured model handles each type of work.',
+ modelRoleDesign: 'Design agent',
+ modelRoleReview: 'Review',
+ modelRoleFast: 'Fast tasks',
+ modelRoleVision: 'Vision',
+ modelRoleDesignDescription: 'AI chat and canvas edits',
+ modelRoleReviewDescription: 'Explicit plan and design reviews',
+ modelRoleFastDescription: 'Low-cost background work',
+ modelRoleVisionDescription: 'Screenshots and image references',
+ modelRoleUseDesign: 'Same as Design',
+ noModel: 'None',
+ back: 'Back',
settingsMedia: 'Media',
settingsStorage: 'Cloud storage',
storageWorkspace: 'Storage workspace',
diff --git a/src/app/ai/chat/storage.ts b/src/app/ai/chat/storage.ts
index c8cb0fac3..65f95d5f4 100644
--- a/src/app/ai/chat/storage.ts
+++ b/src/app/ai/chat/storage.ts
@@ -1,49 +1,41 @@
-import { useLocalStorage } from '@vueuse/core'
import { computed, ref, watch } from 'vue'
-import {
- AI_PROVIDERS,
- DEFAULT_AI_MODEL,
- DEFAULT_AI_PROVIDER,
- IS_TAURI
-} from '@open-pencil/core/constants'
-import type { AIProviderID } from '@open-pencil/core/constants'
+import { IS_TAURI } from '@open-pencil/core/constants'
import { setPexelsApiKey, setUnsplashAccessKey } from '@open-pencil/core/tools'
+import {
+ designCustomAPIType,
+ designCustomBaseURL,
+ designCustomModelID,
+ designMaxOutputTokens,
+ designModelConnection,
+ designModelID,
+ designProviderDefinition,
+ designProviderID,
+ modelConnectionCredentialRef
+} from '@/app/ai/models'
import { appCredentialServices, browserCredentialsRemembered } from '@/app/settings/credentials/app'
import {
initializeCredentialMigration,
PEXELS_CREDENTIAL,
- providerCredentialRef,
UNSPLASH_CREDENTIAL
} from '@/app/settings/credentials/migration'
import { setAppCredentialPersistence } from '@/app/settings/credentials/persistence'
import type { CredentialRef, CredentialStatus } from '@/app/settings/credentials/types'
-const STORAGE_PREFIX = 'open-pencil:'
-
-export const providerID = useLocalStorage<AIProviderID>(
- `${STORAGE_PREFIX}ai-provider`,
- DEFAULT_AI_PROVIDER
-)
-export const modelID = useLocalStorage(`${STORAGE_PREFIX}ai-model`, DEFAULT_AI_MODEL)
-export const customBaseURL = useLocalStorage(`${STORAGE_PREFIX}ai-base-url`, '')
-export const customModelID = useLocalStorage(`${STORAGE_PREFIX}ai-custom-model`, '')
-export const customAPIType = useLocalStorage<'completions' | 'responses'>(
- `${STORAGE_PREFIX}ai-api-type`,
- 'completions'
-)
-export const maxOutputTokens = useLocalStorage(`${STORAGE_PREFIX}ai-max-output-tokens`, 16384)
+export const providerID = designProviderID
+export const modelID = designModelID
+export const customBaseURL = designCustomBaseURL
+export const customModelID = designCustomModelID
+export const customAPIType = designCustomAPIType
+export const maxOutputTokens = designMaxOutputTokens
+export const providerDef = designProviderDefinition
export const apiKeyStatus = ref<CredentialStatus>('missing')
export const pexelsKeyStatus = ref<CredentialStatus>('missing')
export const unsplashKeyStatus = ref<CredentialStatus>('missing')
const credentialRevision = ref(0)
-export const providerDef = computed(
- () => AI_PROVIDERS.find((provider) => provider.id === providerID.value) ?? AI_PROVIDERS[0]
-)
-
export const isACPProvider = computed(() => providerID.value.startsWith('acp:'))
export const isConfigured = computed(() => {
@@ -58,13 +50,15 @@ async function refreshStatus(reference: CredentialRef): Promise<CredentialStatus
return appCredentialServices.manager.status(reference)
}
-async function refreshProviderStatus(provider: AIProviderID): Promise<void> {
- if (provider.startsWith('acp:')) {
- apiKeyStatus.value = 'missing'
- return
- }
- const status = await refreshStatus(providerCredentialRef(provider))
- if (providerID.value === provider) apiKeyStatus.value = status
+function designCredentialReference(): CredentialRef | null {
+ const connection = designModelConnection.value
+ if (!connection || connection.providerID.startsWith('acp:')) return null
+ return modelConnectionCredentialRef(connection)
+}
+
+export async function refreshAIProviderStatus(): Promise<void> {
+ const reference = designCredentialReference()
+ apiKeyStatus.value = reference ? await refreshStatus(reference) : 'missing'
}
async function refreshMediaCredentials(): Promise<void> {
@@ -87,19 +81,19 @@ async function refreshMediaCredentials(): Promise<void> {
}
export const credentialsReady = initializeCredentialMigration().then(async () => {
- await Promise.all([refreshProviderStatus(providerID.value), refreshMediaCredentials()])
+ await Promise.all([refreshAIProviderStatus(), refreshMediaCredentials()])
return undefined
})
-export async function resolveAPIKey(provider = providerID.value): Promise<string | null> {
+export async function resolveAPIKey(): Promise<string | null> {
await credentialsReady
- if (provider.startsWith('acp:')) return null
- return appCredentialServices.resolver.resolve(providerCredentialRef(provider))
+ const reference = designCredentialReference()
+ return reference ? appCredentialServices.resolver.resolve(reference) : null
}
export async function setAPIKey(key: string): Promise<void> {
- if (providerID.value.startsWith('acp:')) return
- const reference = providerCredentialRef(providerID.value)
+ const reference = designCredentialReference()
+ if (!reference) return
const value = key.trim()
if (value) await appCredentialServices.manager.set(reference, value)
else await appCredentialServices.manager.clear(reference)
@@ -126,23 +120,24 @@ export async function setUnsplashKey(key: string): Promise<void> {
export async function setRememberCredentials(remembered: boolean): Promise<void> {
await credentialsReady
await setAppCredentialPersistence(remembered)
- await Promise.all([refreshProviderStatus(providerID.value), refreshMediaCredentials()])
+ await Promise.all([refreshAIProviderStatus(), refreshMediaCredentials()])
credentialRevision.value++
}
export { browserCredentialsRemembered }
export function registerAIChatEffects(markTransportDirty: () => void) {
- watch(providerID, (id) => {
- const definition = AI_PROVIDERS.find((provider) => provider.id === id)
- if (definition?.defaultModel) modelID.value = definition.defaultModel
- void refreshProviderStatus(id)
- markTransportDirty()
- })
-
+ watch(
+ () => designModelConnection.value?.id,
+ () => {
+ void refreshAIProviderStatus()
+ markTransportDirty()
+ }
+ )
watch(modelID, markTransportDirty)
watch(customModelID, markTransportDirty)
watch(customAPIType, markTransportDirty)
watch(customBaseURL, markTransportDirty)
+ watch(maxOutputTokens, markTransportDirty)
watch(credentialRevision, markTransportDirty)
}
diff --git a/src/app/ai/chat/transports.ts b/src/app/ai/chat/transports.ts
index 14167c9bb..da1cff0ea 100644
--- a/src/app/ai/chat/transports.ts
+++ b/src/app/ai/chat/transports.ts
@@ -1,13 +1,14 @@
import { Chat } from '@ai-sdk/vue'
import { DirectChatTransport, stepCountIs, ToolLoopAgent } from 'ai'
-import type { ChatTransport, UIMessage } from 'ai'
+import type { ChatTransport, LanguageModel, UIMessage } from 'ai'
import type { ComputedRef, Ref } from 'vue'
import { ACP_AGENTS } from '@open-pencil/core/constants'
import type { ACPAgentID, AIProviderID } from '@open-pencil/core/constants'
-import { createLanguageModel, resolveLanguageModelID } from '@/app/ai/chat/model'
+import { resolveLanguageModelID } from '@/app/ai/chat/model'
import SYSTEM_PROMPT from '@/app/ai/chat/system-prompt.md?raw'
+import { createAIModelRuntime } from '@/app/ai/models'
import { MAX_AGENT_STEPS, createAITools, recordStepUsage, resetRunSteps } from '@/app/ai/tools'
import type { getActiveEditorStore } from '@/app/editor/active-store'
@@ -18,23 +19,14 @@ type ChatSessionOptions = {
isACPProvider: ComputedRef<boolean>
providerID: Ref<AIProviderID>
credentialsReady: Promise<void>
- resolveAPIKey: (providerID: AIProviderID) => Promise<string | null>
- modelID: Ref<string>
- customModelID: Ref<string>
- customBaseURL: Ref<string>
- customAPIType: Ref<'completions' | 'responses'>
- maxOutputTokens: Ref<number>
getActiveEditorStore: () => EditorStore
}
type ToolLoopTransportOptions = {
store: EditorStore
providerID: AIProviderID
- apiKey: string
- modelID: string
- customModelID: string
- customBaseURL: string
- customAPIType: 'completions' | 'responses'
+ model: LanguageModel
+ effectiveModelID: string
maxOutputTokens: number
}
@@ -63,28 +55,17 @@ export async function createACPTransport(providerID: AIProviderID) {
export function createToolLoopTransport({
store,
providerID,
- apiKey,
- modelID,
- customModelID,
- customBaseURL,
- customAPIType,
+ model,
+ effectiveModelID,
maxOutputTokens
}: ToolLoopTransportOptions) {
const tools = createAITools(store)
- const effectiveModelID = resolveLanguageModelID({ providerID, modelID, customModelID })
const cacheProviderOptions = supportsAnthropicCaching(providerID, effectiveModelID)
? ANTHROPIC_CACHE_CONTROL
: undefined
const agent = new ToolLoopAgent({
- model: createLanguageModel({
- providerID,
- apiKey,
- modelID,
- customModelID,
- customBaseURL,
- customAPIType
- }),
+ model,
instructions: SYSTEM_PROMPT,
tools,
stopWhen: stepCountIs(MAX_AGENT_STEPS),
@@ -120,12 +101,6 @@ export function createChatSessionManager({
isACPProvider,
providerID,
credentialsReady,
- resolveAPIKey,
- modelID,
- customModelID,
- customBaseURL,
- customAPIType,
- maxOutputTokens,
getActiveEditorStore
}: ChatSessionOptions) {
let transportDirty = false
@@ -154,19 +129,20 @@ export function createChatSessionManager({
void acpTransportInstance?.destroy()
acpTransportInstance = null
- const activeProviderID = providerID.value
- const apiKey = await resolveAPIKey(activeProviderID)
- if (!apiKey) throw new Error('AI provider credential is unavailable')
-
+ const runtime = await createAIModelRuntime('design')
+ if (runtime?.kind !== 'direct') {
+ throw new Error('The Design model is not configured for direct API access')
+ }
return createToolLoopTransport({
store,
- providerID: activeProviderID,
- apiKey,
- modelID: modelID.value,
- customModelID: customModelID.value,
- customBaseURL: customBaseURL.value,
- customAPIType: customAPIType.value,
- maxOutputTokens: maxOutputTokens.value
+ providerID: runtime.role.connection.providerID,
+ model: runtime.model,
+ effectiveModelID: resolveLanguageModelID({
+ providerID: runtime.role.connection.providerID,
+ modelID: runtime.role.profile.modelID,
+ customModelID: runtime.role.profile.customModelID
+ }),
+ maxOutputTokens: runtime.role.profile.maxOutputTokens
})
}
diff --git a/src/app/ai/chat/use.ts b/src/app/ai/chat/use.ts
index 86199dc57..c0b2ea867 100644
--- a/src/app/ai/chat/use.ts
+++ b/src/app/ai/chat/use.ts
@@ -35,12 +35,6 @@ const chatSession = createChatSessionManager({
isACPProvider,
providerID,
credentialsReady,
- resolveAPIKey,
- modelID,
- customModelID,
- customBaseURL,
- customAPIType,
- maxOutputTokens,
getActiveEditorStore
})
diff --git a/src/app/ai/models/index.ts b/src/app/ai/models/index.ts
new file mode 100644
index 000000000..39008b2c7
--- /dev/null
+++ b/src/app/ai/models/index.ts
@@ -0,0 +1,3 @@
+export * from './runtime'
+export * from './store'
+export * from './types'
diff --git a/src/app/ai/models/runtime.ts b/src/app/ai/models/runtime.ts
new file mode 100644
index 000000000..44c992d6f
--- /dev/null
+++ b/src/app/ai/models/runtime.ts
@@ -0,0 +1,84 @@
+import type { LanguageModel } from 'ai'
+
+import { createLanguageModel } from '@/app/ai/chat/model'
+import { modelConnection, resolveAIModelRole } from '@/app/ai/models/store'
+import type { AIModelConnection, AIModelRole, ResolvedAIModelRole } from '@/app/ai/models/types'
+import { appCredentialServices } from '@/app/settings/credentials/app'
+import {
+ initializeCredentialMigration,
+ providerCredentialRef
+} from '@/app/settings/credentials/migration'
+import type { CredentialRef, CredentialStatus } from '@/app/settings/credentials/types'
+
+export type DirectAIModelRuntime = {
+ kind: 'direct'
+ role: ResolvedAIModelRole
+ model: LanguageModel
+}
+
+export type ACPModelRuntime = {
+ kind: 'acp'
+ role: ResolvedAIModelRole
+}
+
+export type AIModelRuntime = DirectAIModelRuntime | ACPModelRuntime
+
+export function modelConnectionCredentialRef(connection: AIModelConnection): CredentialRef {
+ return providerCredentialRef(connection.providerID, connection.credentialProfileId)
+}
+
+export async function modelConnectionCredentialStatus(
+ connectionId: string
+): Promise<CredentialStatus> {
+ const connection = modelConnection(connectionId)
+ if (!connection || connection.providerID.startsWith('acp:')) return 'missing'
+ return appCredentialServices.manager.status(modelConnectionCredentialRef(connection))
+}
+
+export async function setModelConnectionAPIKey(connectionId: string, value: string): Promise<void> {
+ const connection = modelConnection(connectionId)
+ if (!connection || connection.providerID.startsWith('acp:')) return
+ const reference = modelConnectionCredentialRef(connection)
+ const key = value.trim()
+ if (key) await appCredentialServices.manager.set(reference, key)
+ else await appCredentialServices.manager.clear(reference)
+}
+
+export async function resolveModelConnectionAPIKey(connectionId: string): Promise<string | null> {
+ await initializeCredentialMigration()
+ const connection = modelConnection(connectionId)
+ if (!connection || connection.providerID.startsWith('acp:')) return null
+ return appCredentialServices.resolver.resolve(modelConnectionCredentialRef(connection))
+}
+
+export async function createAIModelRuntime(role: AIModelRole): Promise<AIModelRuntime | null> {
+ const resolved = resolveAIModelRole(role)
+ if (!resolved) return null
+ if (role === 'design' && !resolved.profile.capabilities.includes('tools')) {
+ throw new Error('The Design model must support tools')
+ }
+ if (role === 'vision' && !resolved.profile.capabilities.includes('vision')) {
+ throw new Error('The Vision model must support image input')
+ }
+ if (resolved.connection.providerID.startsWith('acp:')) {
+ if (role !== 'design') {
+ throw new Error('ACP agents can only be assigned to the Design agent role')
+ }
+ return { kind: 'acp', role: resolved }
+ }
+
+ const apiKey = await resolveModelConnectionAPIKey(resolved.connection.id)
+ if (!apiKey) throw new Error(`Credential is unavailable for the ${role} model role`)
+ return {
+ kind: 'direct',
+ role: resolved,
+ model: createLanguageModel({
+ providerID: resolved.connection.providerID,
+ apiKey,
+ modelID: resolved.profile.modelID,
+ customModelID: resolved.profile.customModelID,
+ customBaseURL: resolved.connection.customBaseURL,
+ customAPIType: resolved.connection.customAPIType
+ })
+ }
+}
diff --git a/src/app/ai/models/storage.ts b/src/app/ai/models/storage.ts
new file mode 100644
index 000000000..90fdaee76
--- /dev/null
+++ b/src/app/ai/models/storage.ts
@@ -0,0 +1,54 @@
+import { StorageSerializers, useLocalStorage } from '@vueuse/core'
+
+const STORAGE_PREFIX = 'open-pencil:'
+const MODEL_SETTINGS_KEY = `${STORAGE_PREFIX}ai-model-settings`
+
+const modelSettings = useLocalStorage<unknown>(MODEL_SETTINGS_KEY, null, {
+ serializer: StorageSerializers.object,
+ writeDefaults: false
+})
+
+const legacyValues = {
+ 'ai-provider': useLocalStorage<string | null>(`${STORAGE_PREFIX}ai-provider`, null, {
+ serializer: StorageSerializers.string,
+ writeDefaults: false
+ }),
+ 'ai-model': useLocalStorage<string | null>(`${STORAGE_PREFIX}ai-model`, null, {
+ serializer: StorageSerializers.string,
+ writeDefaults: false
+ }),
+ 'ai-custom-model': useLocalStorage<string | null>(`${STORAGE_PREFIX}ai-custom-model`, null, {
+ serializer: StorageSerializers.string,
+ writeDefaults: false
+ }),
+ 'ai-base-url': useLocalStorage<string | null>(`${STORAGE_PREFIX}ai-base-url`, null, {
+ serializer: StorageSerializers.string,
+ writeDefaults: false
+ }),
+ 'ai-api-type': useLocalStorage<string | null>(`${STORAGE_PREFIX}ai-api-type`, null, {
+ serializer: StorageSerializers.string,
+ writeDefaults: false
+ }),
+ 'ai-max-output-tokens': useLocalStorage<string | null>(
+ `${STORAGE_PREFIX}ai-max-output-tokens`,
+ null,
+ {
+ serializer: StorageSerializers.string,
+ writeDefaults: false
+ }
+ )
+}
+
+export type LegacyAIModelStorageKey = keyof typeof legacyValues
+
+export function readLegacyAIModelStorage(key: LegacyAIModelStorageKey): string | null {
+ return legacyValues[key].value
+}
+
+export function readAIModelSettingsStorage(): unknown {
+ return modelSettings.value
+}
+
+export function writeAIModelSettingsStorage(value: unknown): void {
+ modelSettings.value = value
+}
diff --git a/src/app/ai/models/store.ts b/src/app/ai/models/store.ts
new file mode 100644
index 000000000..b34269d59
--- /dev/null
+++ b/src/app/ai/models/store.ts
@@ -0,0 +1,426 @@
+import { computed, ref, watch } from 'vue'
+
+import {
+ AI_PROVIDERS,
+ DEFAULT_AI_MODEL,
+ DEFAULT_AI_PROVIDER,
+ type AIProviderID
+} from '@open-pencil/core/constants'
+
+import {
+ readAIModelSettingsStorage,
+ readLegacyAIModelStorage,
+ writeAIModelSettingsStorage
+} from '@/app/ai/models/storage'
+import type {
+ AIModelCapability,
+ AIModelConnection,
+ AIModelProfile,
+ AIModelProfileDraft,
+ AIModelProfileId,
+ AIModelRole,
+ AIModelRoleAssignment,
+ AIModelSettings,
+ OptionalAIModelRole,
+ ResolvedAIModelRole
+} from '@/app/ai/models/types'
+
+const LEGACY_CONNECTION_ID = 'connection-default'
+const LEGACY_MODEL_ID: AIModelProfileId = 'model-default'
+const DEFAULT_MAX_OUTPUT_TOKENS = 16_384
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
+}
+
+function isProviderID(value: unknown): value is AIProviderID {
+ return typeof value === 'string' && AI_PROVIDERS.some((provider) => provider.id === value)
+}
+
+function isAPIType(value: unknown): value is 'completions' | 'responses' {
+ return value === 'completions' || value === 'responses'
+}
+
+function isCapability(value: unknown): value is AIModelCapability {
+ return value === 'tools' || value === 'vision'
+}
+
+function stringValue(value: unknown, fallback = ''): string {
+ return typeof value === 'string' ? value : fallback
+}
+
+function numberValue(value: unknown, fallback: number): number {
+ return typeof value === 'number' && Number.isFinite(value) ? value : fallback
+}
+
+function parseConnection(value: unknown): AIModelConnection | null {
+ if (!isRecord(value)) return null
+ const id = stringValue(value.id)
+ const credentialProfileId = stringValue(value.credentialProfileId)
+ if (!id || !credentialProfileId || !isProviderID(value.providerID)) return null
+ return {
+ id,
+ providerID: value.providerID,
+ customBaseURL: stringValue(value.customBaseURL),
+ customAPIType: isAPIType(value.customAPIType) ? value.customAPIType : 'completions',
+ credentialProfileId
+ }
+}
+
+function parseProfile(value: unknown, connectionIds: Set<string>): AIModelProfile | null {
+ if (!isRecord(value)) return null
+ const id = stringValue(value.id)
+ const connectionId = stringValue(value.connectionId)
+ if (!id.startsWith('model-') || !connectionIds.has(connectionId)) return null
+ const capabilities = Array.isArray(value.capabilities)
+ ? value.capabilities.filter(isCapability)
+ : ['tools' as const]
+ return {
+ id: id as AIModelProfileId,
+ name: stringValue(value.name, 'Model'),
+ connectionId,
+ modelID: stringValue(value.modelID),
+ customModelID: stringValue(value.customModelID),
+ maxOutputTokens: numberValue(value.maxOutputTokens, DEFAULT_MAX_OUTPUT_TOKENS),
+ capabilities: [...new Set(capabilities)]
+ }
+}
+
+function optionalAssignment(value: unknown, modelIds: Set<string>): AIModelRoleAssignment {
+ if (value === 'design' || value === null) return value
+ return typeof value === 'string' && modelIds.has(value) ? (value as AIModelProfileId) : null
+}
+
+function parseSettings(value: unknown): AIModelSettings | null {
+ if (!isRecord(value) || value.version !== 1) return null
+ const connections = Array.isArray(value.connections)
+ ? value.connections.map(parseConnection).filter((connection) => connection !== null)
+ : []
+ const connectionIds = new Set(connections.map((connection) => connection.id))
+ const models = Array.isArray(value.models)
+ ? value.models
+ .map((profile) => parseProfile(profile, connectionIds))
+ .filter((profile) => profile !== null)
+ : []
+ if (!models.length) return null
+ const modelIds = new Set(models.map((profile) => profile.id))
+ const rawAssignments = isRecord(value.assignments) ? value.assignments : {}
+ const rawDesign = stringValue(rawAssignments.design)
+ const design = rawDesign.startsWith('model-') ? (rawDesign as AIModelProfileId) : models[0].id
+ return {
+ version: 1,
+ connections,
+ models,
+ assignments: {
+ design: modelIds.has(design) ? design : models[0].id,
+ review: optionalAssignment(rawAssignments.review, modelIds),
+ fast: optionalAssignment(rawAssignments.fast, modelIds),
+ vision: optionalAssignment(rawAssignments.vision, modelIds)
+ }
+ }
+}
+
+function legacySettings(): AIModelSettings {
+ const storedProvider = readLegacyAIModelStorage('ai-provider')
+ const providerID = isProviderID(storedProvider) ? storedProvider : DEFAULT_AI_PROVIDER
+ const provider = AI_PROVIDERS.find((definition) => definition.id === providerID)
+ const modelID = readLegacyAIModelStorage('ai-model') ?? provider?.defaultModel ?? DEFAULT_AI_MODEL
+ const customModelID = readLegacyAIModelStorage('ai-custom-model') ?? ''
+ const displayModel = customModelID || modelID
+ const name = displayModel
+ ? provider?.models.find((model) => model.id === displayModel)?.name || displayModel
+ : 'Design model'
+ const maxOutputTokens = Number(readLegacyAIModelStorage('ai-max-output-tokens'))
+ return {
+ version: 1,
+ connections: [
+ {
+ id: LEGACY_CONNECTION_ID,
+ providerID,
+ customBaseURL: readLegacyAIModelStorage('ai-base-url') ?? '',
+ customAPIType:
+ readLegacyAIModelStorage('ai-api-type') === 'responses' ? 'responses' : 'completions',
+ credentialProfileId: 'default'
+ }
+ ],
+ models: [
+ {
+ id: LEGACY_MODEL_ID,
+ name,
+ connectionId: LEGACY_CONNECTION_ID,
+ modelID,
+ customModelID,
+ maxOutputTokens: Number.isFinite(maxOutputTokens)
+ ? maxOutputTokens
+ : DEFAULT_MAX_OUTPUT_TOKENS,
+ capabilities: ['tools']
+ }
+ ],
+ assignments: {
+ design: LEGACY_MODEL_ID,
+ review: 'design',
+ fast: 'design',
+ vision: null
+ }
+ }
+}
+
+function loadSettings(): AIModelSettings {
+ return parseSettings(readAIModelSettingsStorage()) ?? legacySettings()
+}
+
+export const aiModelSettings = ref<AIModelSettings>(loadSettings())
+
+watch(aiModelSettings, (settings) => writeAIModelSettingsStorage(settings), { deep: true })
+
+function createConnectionId(): string {
+ return `connection-${crypto.randomUUID()}`
+}
+
+function createModelId(): AIModelProfileId {
+ return `model-${crypto.randomUUID()}`
+}
+
+export function modelProfile(profileId: string): AIModelProfile | null {
+ return aiModelSettings.value.models.find((profile) => profile.id === profileId) ?? null
+}
+
+export function modelConnection(connectionId: string): AIModelConnection | null {
+ return (
+ aiModelSettings.value.connections.find((connection) => connection.id === connectionId) ?? null
+ )
+}
+
+export function resolveAIModelRole(role: AIModelRole): ResolvedAIModelRole | null {
+ const assignment = aiModelSettings.value.assignments[role]
+ if (assignment === null) return null
+ const profileId = assignment === 'design' ? aiModelSettings.value.assignments.design : assignment
+ const profile = modelProfile(profileId)
+ if (!profile) return null
+ if (role === 'design' && !profile.capabilities.includes('tools')) return null
+ if (role === 'vision' && !profile.capabilities.includes('vision')) return null
+ const connection = modelConnection(profile.connectionId)
+ return connection ? { requestedRole: role, profile, connection } : null
+}
+
+function connectionMatchesDraft(
+ connection: AIModelConnection,
+ draft: AIModelProfileDraft
+): boolean {
+ return (
+ connection.providerID === draft.providerID &&
+ connection.customBaseURL === draft.customBaseURL.trim() &&
+ connection.customAPIType === draft.customAPIType
+ )
+}
+
+export function findModelConnectionForDraft(draft: AIModelProfileDraft): AIModelConnection | null {
+ const source = draft.sourceConnectionId ? modelConnection(draft.sourceConnectionId) : null
+ if (source && connectionMatchesDraft(source, draft)) return source
+ return (
+ aiModelSettings.value.connections.find((connection) =>
+ connectionMatchesDraft(connection, draft)
+ ) ?? null
+ )
+}
+
+function connectionForDraft(draft: AIModelProfileDraft): AIModelConnection {
+ const existing = findModelConnectionForDraft(draft)
+ if (existing) return existing
+ const id = createConnectionId()
+ const connection: AIModelConnection = {
+ id,
+ providerID: draft.providerID,
+ customBaseURL: draft.customBaseURL.trim(),
+ customAPIType: draft.customAPIType,
+ credentialProfileId: id
+ }
+ aiModelSettings.value.connections.push(connection)
+ return connection
+}
+
+function draftForProfile(
+ profile: AIModelProfile,
+ connection: AIModelConnection
+): AIModelProfileDraft {
+ return {
+ profileId: profile.id,
+ sourceConnectionId: profile.connectionId,
+ name: profile.name,
+ providerID: connection.providerID,
+ modelID: profile.modelID,
+ customModelID: profile.customModelID,
+ customBaseURL: connection.customBaseURL,
+ customAPIType: connection.customAPIType,
+ maxOutputTokens: profile.maxOutputTokens,
+ capabilities: [...profile.capabilities]
+ }
+}
+
+function newProfileDraft(connection: AIModelConnection | null): AIModelProfileDraft {
+ const providerID = connection?.providerID ?? DEFAULT_AI_PROVIDER
+ const provider = AI_PROVIDERS.find((definition) => definition.id === providerID)
+ return {
+ profileId: null,
+ sourceConnectionId: connection?.id ?? null,
+ name: '',
+ providerID,
+ modelID: provider?.defaultModel ?? '',
+ customModelID: '',
+ customBaseURL: connection?.customBaseURL ?? '',
+ customAPIType: connection?.customAPIType ?? 'completions',
+ maxOutputTokens: DEFAULT_MAX_OUTPUT_TOKENS,
+ capabilities: ['tools']
+ }
+}
+
+export function createModelProfileDraft(profileId?: string): AIModelProfileDraft {
+ const profile = profileId ? modelProfile(profileId) : null
+ const profileConnection = profile ? modelConnection(profile.connectionId) : null
+ if (profile && profileConnection) return draftForProfile(profile, profileConnection)
+ const designConnection = resolveAIModelRole('design')?.connection ?? null
+ return newProfileDraft(designConnection ?? aiModelSettings.value.connections[0])
+}
+
+export function saveModelProfileDraft(draft: AIModelProfileDraft): AIModelProfile {
+ const provider = AI_PROVIDERS.find((definition) => definition.id === draft.providerID)
+ const effectiveModel = draft.customModelID.trim() || draft.modelID.trim()
+ if (!draft.name.trim()) throw new Error('Model name is required')
+ if (!draft.providerID.startsWith('acp:') && !effectiveModel) {
+ throw new Error('Model ID is required')
+ }
+ if (
+ draft.profileId === aiModelSettings.value.assignments.design &&
+ !draft.capabilities.includes('tools')
+ ) {
+ throw new Error('The Design model must support tools')
+ }
+ const connection = connectionForDraft(draft)
+ const profile: AIModelProfile = {
+ id: draft.profileId ?? createModelId(),
+ name: draft.name.trim(),
+ connectionId: connection.id,
+ modelID: draft.modelID.trim() || provider?.defaultModel || '',
+ customModelID: draft.customModelID.trim(),
+ maxOutputTokens: Math.max(1024, Math.round(draft.maxOutputTokens)),
+ capabilities: [...new Set(draft.capabilities)]
+ }
+ const index = aiModelSettings.value.models.findIndex((model) => model.id === profile.id)
+ if (index === -1) aiModelSettings.value.models.push(profile)
+ else aiModelSettings.value.models[index] = profile
+ if (
+ aiModelSettings.value.assignments.vision === profile.id &&
+ !profile.capabilities.includes('vision')
+ ) {
+ aiModelSettings.value.assignments.vision = null
+ }
+ return profile
+}
+
+export function modelConnectionUsageCount(connectionId: string): number {
+ return aiModelSettings.value.models.filter((profile) => profile.connectionId === connectionId)
+ .length
+}
+
+export function removeModelProfile(profileId: string): void {
+ if (aiModelSettings.value.models.length <= 1) return
+ const removed = modelProfile(profileId)
+ aiModelSettings.value.models = aiModelSettings.value.models.filter(
+ (profile) => profile.id !== profileId
+ )
+ const fallback =
+ aiModelSettings.value.models.find((profile) => profile.capabilities.includes('tools')) ??
+ aiModelSettings.value.models[0]
+ if (aiModelSettings.value.assignments.design === profileId) {
+ aiModelSettings.value.assignments.design = fallback.id
+ if (
+ aiModelSettings.value.assignments.vision === 'design' &&
+ !fallback.capabilities.includes('vision')
+ ) {
+ aiModelSettings.value.assignments.vision = null
+ }
+ }
+ for (const role of ['review', 'fast', 'vision'] as const) {
+ if (aiModelSettings.value.assignments[role] === profileId) {
+ aiModelSettings.value.assignments[role] = null
+ }
+ }
+ if (removed && modelConnectionUsageCount(removed.connectionId) === 0) {
+ aiModelSettings.value.connections = aiModelSettings.value.connections.filter(
+ (connection) => connection.id !== removed.connectionId
+ )
+ }
+}
+
+export function setModelRoleAssignment(role: 'design', assignment: AIModelProfileId): void
+export function setModelRoleAssignment(
+ role: OptionalAIModelRole,
+ assignment: AIModelRoleAssignment
+): void
+export function setModelRoleAssignment(role: AIModelRole, assignment: AIModelRoleAssignment): void {
+ if (role === 'design') {
+ if (assignment === null || assignment === 'design') return
+ const profile = modelProfile(assignment)
+ if (!profile?.capabilities.includes('tools')) return
+ aiModelSettings.value.assignments.design = assignment
+ return
+ }
+ if (assignment !== null && assignment !== 'design' && !modelProfile(assignment)) return
+ if (role === 'vision' && assignment !== null) {
+ const profile =
+ assignment === 'design'
+ ? modelProfile(aiModelSettings.value.assignments.design)
+ : modelProfile(assignment)
+ if (!profile?.capabilities.includes('vision')) return
+ }
+ aiModelSettings.value.assignments[role] = assignment
+}
+
+export function replaceAIModelSettings(settings: AIModelSettings): void {
+ aiModelSettings.value = structuredClone(settings)
+}
+
+export const designModelProfile = computed(() => resolveAIModelRole('design')?.profile ?? null)
+export const designModelConnection = computed(
+ () => resolveAIModelRole('design')?.connection ?? null
+)
+export const designProviderID = computed(
+ () => designModelConnection.value?.providerID ?? DEFAULT_AI_PROVIDER
+)
+export const designProviderDefinition = computed(
+ () => AI_PROVIDERS.find((provider) => provider.id === designProviderID.value) ?? AI_PROVIDERS[0]
+)
+export const designModelID = computed({
+ get: () => designModelProfile.value?.modelID ?? '',
+ set: (modelID: string) => {
+ const profile = designModelProfile.value
+ if (profile) profile.modelID = modelID
+ }
+})
+export const designCustomModelID = computed({
+ get: () => designModelProfile.value?.customModelID ?? '',
+ set: (modelID: string) => {
+ const profile = designModelProfile.value
+ if (profile) profile.customModelID = modelID
+ }
+})
+export const designCustomBaseURL = computed(() => designModelConnection.value?.customBaseURL ?? '')
+export const designCustomAPIType = computed(
+ () => designModelConnection.value?.customAPIType ?? 'completions'
+)
+export const designMaxOutputTokens = computed(
+ () => designModelProfile.value?.maxOutputTokens ?? DEFAULT_MAX_OUTPUT_TOKENS
+)
+
+export function modelSettingsSnapshot(): AIModelSettings {
+ const settings = aiModelSettings.value
+ return {
+ version: 1,
+ connections: settings.connections.map((connection) => ({ ...connection })),
+ models: settings.models.map((profile) => ({
+ ...profile,
+ capabilities: [...profile.capabilities]
+ })),
+ assignments: { ...settings.assignments }
+ }
+}
diff --git a/src/app/ai/models/types.ts b/src/app/ai/models/types.ts
new file mode 100644
index 000000000..3c6cc3589
--- /dev/null
+++ b/src/app/ai/models/types.ts
@@ -0,0 +1,61 @@
+import type { AIProviderID } from '@open-pencil/core/constants'
+
+export const AI_MODEL_ROLES = ['design', 'review', 'fast', 'vision'] as const
+export const AI_MODEL_CAPABILITIES = ['tools', 'vision'] as const
+
+export type AIModelRole = (typeof AI_MODEL_ROLES)[number]
+export type AIModelProfileId = `model-${string}`
+export type AIModelRoleAssignment = AIModelProfileId | 'design' | null
+export type AIModelCapability = (typeof AI_MODEL_CAPABILITIES)[number]
+export type OptionalAIModelRole = Exclude<AIModelRole, 'design'>
+
+export type AIModelConnection = {
+ id: string
+ providerID: AIProviderID
+ customBaseURL: string
+ customAPIType: 'completions' | 'responses'
+ credentialProfileId: string
+}
+
+export type AIModelProfile = {
+ id: AIModelProfileId
+ name: string
+ connectionId: string
+ modelID: string
+ customModelID: string
+ maxOutputTokens: number
+ capabilities: AIModelCapability[]
+}
+
+export type AIModelAssignments = {
+ design: AIModelProfileId
+ review: AIModelRoleAssignment
+ fast: AIModelRoleAssignment
+ vision: AIModelRoleAssignment
+}
+
+export type AIModelSettings = {
+ version: 1
+ connections: AIModelConnection[]
+ models: AIModelProfile[]
+ assignments: AIModelAssignments
+}
+
+export type AIModelProfileDraft = {
+ profileId: AIModelProfileId | null
+ sourceConnectionId: string | null
+ name: string
+ providerID: AIProviderID
+ modelID: string
+ customModelID: string
+ customBaseURL: string
+ customAPIType: 'completions' | 'responses'
+ maxOutputTokens: number
+ capabilities: AIModelCapability[]
+}
+
+export type ResolvedAIModelRole = {
+ requestedRole: AIModelRole
+ profile: AIModelProfile
+ connection: AIModelConnection
+}
diff --git a/src/app/settings/credentials/migration.ts b/src/app/settings/credentials/migration.ts
index 48a458604..e6a0e5e72 100644
--- a/src/app/settings/credentials/migration.ts
+++ b/src/app/settings/credentials/migration.ts
@@ -10,11 +10,14 @@ const MIGRATION_VERSION_KEY = `${STORAGE_PREFIX}credential-migration`
const MIGRATION_VERSION = '1'
const LEGACY_OPENROUTER_KEY = `${STORAGE_PREFIX}openrouter-api-key`
-export function providerCredentialRef(providerId: AIProviderID): CredentialRef {
+export function providerCredentialRef(
+ providerId: AIProviderID,
+ profileId = 'default'
+): CredentialRef {
if (providerId.startsWith('acp:')) {
throw new Error('ACP agents do not use API-key credentials')
}
- return credentialRef(providerId, 'api-key')
+ return credentialRef(providerId, 'api-key', profileId)
}
export const PEXELS_CREDENTIAL = credentialRef('pexels', 'api-key')
diff --git a/src/app/settings/credentials/persistence.ts b/src/app/settings/credentials/persistence.ts
index 63d2185ff..ddcc55414 100644
--- a/src/app/settings/credentials/persistence.ts
+++ b/src/app/settings/credentials/persistence.ts
@@ -1,23 +1,38 @@
import { AI_PROVIDERS } from '@open-pencil/core/constants'
+import { aiModelSettings, modelConnectionCredentialRef } from '@/app/ai/models'
import { storageCredentialRefs, storageProviderRegistry } from '@/app/integrations/storage'
import {
PEXELS_CREDENTIAL,
UNSPLASH_CREDENTIAL,
providerCredentialRef
} from '@/app/settings/credentials/migration'
+import { credentialKey } from '@/app/settings/credentials/reference'
import { setBrowserCredentialPersistence } from './app'
import type { CredentialRef } from './types'
+function uniqueCredentialRefs(references: CredentialRef[]): CredentialRef[] {
+ return [...new Map(references.map((reference) => [credentialKey(reference), reference])).values()]
+}
+
export function appCredentialRefs(): CredentialRef[] {
- const aiCredentials = AI_PROVIDERS.filter((provider) => !provider.id.startsWith('acp:')).map(
+ const legacyAIRefs = AI_PROVIDERS.filter((provider) => !provider.id.startsWith('acp:')).map(
(provider) => providerCredentialRef(provider.id)
)
+ const modelConnectionRefs = aiModelSettings.value.connections
+ .filter((connection) => !connection.providerID.startsWith('acp:'))
+ .map(modelConnectionCredentialRef)
const storageCredentials = storageProviderRegistry
.list()
.flatMap((provider) => storageCredentialRefs(provider.id))
- return [...aiCredentials, PEXELS_CREDENTIAL, UNSPLASH_CREDENTIAL, ...storageCredentials]
+ return uniqueCredentialRefs([
+ ...legacyAIRefs,
+ ...modelConnectionRefs,
+ PEXELS_CREDENTIAL,
+ UNSPLASH_CREDENTIAL,
+ ...storageCredentials
+ ])
}
export function setAppCredentialPersistence(remembered: boolean): Promise<void> {
diff --git a/src/components/settings/SettingsDialog.vue b/src/components/settings/SettingsDialog.vue
index 578512325..a315bdfc7 100644
--- a/src/components/settings/SettingsDialog.vue
+++ b/src/components/settings/SettingsDialog.vue
@@ -7,28 +7,15 @@ import { IS_TAURI } from '@open-pencil/core/constants'
import { useAIChat } from '@/app/ai/chat/use'
import { appCredentialServices } from '@/app/settings/credentials/app'
import { settingsDialogOpen, settingsDialogSection } from '@/app/settings/dialog'
-import ApiKeySection from '@/components/settings/provider/ApiKeySection.vue'
-import ApiTypeSection from '@/components/settings/provider/ApiTypeSection.vue'
-import CustomEndpointSection from '@/components/settings/provider/CustomEndpointSection.vue'
-import MaxTokensSection from '@/components/settings/provider/MaxTokensSection.vue'
+import ModelsPanel from '@/components/settings/models/ModelsPanel.vue'
import StockPhotoKeysSection from '@/components/settings/provider/StockPhotoKeysSection.vue'
-import TestConnectionSection from '@/components/settings/provider/TestConnectionSection.vue'
-import { provideProviderSettings } from '@/components/settings/provider/context'
-import ProviderSelectField from '@/components/settings/provider-select/ProviderSelectField.vue'
import StorageSettingsPanel from '@/components/settings/storage/StorageSettingsPanel.vue'
import AppSwitch from '@/components/ui/AppSwitch.vue'
import { AppDialogFooter, AppDialogHeader, AppDialogRoot } from '@/components/ui/dialog'
const { dialogs } = useI18n()
const { browserCredentialsRemembered, setRememberCredentials } = useAIChat()
-const providerSettings = provideProviderSettings()
-
-function save(): void {
- void providerSettings.save()
-}
-
function onOpenChange(open: boolean): void {
- if (!open) save()
settingsDialogOpen.value = open
}
@@ -57,6 +44,7 @@ const navigationClass =
<AppDialogRoot
:open="settingsDialogOpen"
size="lg"
+ height="tall"
data-test-id="app-settings-dialog"
@update:open="onOpenChange"
>
@@ -103,16 +91,10 @@ const navigationClass =
<div class="min-h-0 flex-1 overflow-y-auto p-4">
<section
v-if="settingsDialogSection === 'ai'"
- class="flex flex-col gap-2.5"
+ class="flex h-full flex-col"
data-test-id="settings-ai-panel"
>
- <h3 class="text-xs font-semibold text-surface">{{ dialogs.settingsAIAndAgents }}</h3>
- <ProviderSelectField data-test-id="settings-ai-provider" />
- <MaxTokensSection />
- <CustomEndpointSection />
- <ApiTypeSection />
- <ApiKeySection />
- <TestConnectionSection />
+ <ModelsPanel />
</section>
<section
diff --git a/src/components/settings/models/ModelsPanel.vue b/src/components/settings/models/ModelsPanel.vue
new file mode 100644
index 000000000..f16f5a182
--- /dev/null
+++ b/src/components/settings/models/ModelsPanel.vue
@@ -0,0 +1,160 @@
+<script setup lang="ts">
+import { computed, ref, watch } from 'vue'
+import { useI18n } from '@open-pencil/vue'
+
+import { AI_PROVIDERS } from '@open-pencil/core/constants'
+
+import { aiModelSettings, modelConnection, modelConnectionCredentialStatus } from '@/app/ai/models'
+import type { CredentialStatus } from '@/app/settings/credentials/types'
+import ProfileEditor from '@/components/settings/models/ProfileEditor.vue'
+import RoleAssignments from '@/components/settings/models/RoleAssignments.vue'
+
+const { dialogs } = useI18n()
+const editing = ref(false)
+const editingProfileId = ref<string>()
+const statusByConnection = ref<Record<string, CredentialStatus>>({})
+const profiles = computed(() =>
+ aiModelSettings.value.models.map((profile) => {
+ const connection = modelConnection(profile.connectionId)
+ const provider = AI_PROVIDERS.find((definition) => definition.id === connection?.providerID)
+ const modelId = profile.customModelID || profile.modelID
+ const modelName = provider?.models.find((model) => model.id === modelId)?.name || modelId
+ return {
+ ...profile,
+ providerID: connection?.providerID ?? '',
+ providerName: provider?.name ?? connection?.providerID ?? '',
+ modelName
+ }
+ })
+)
+
+function addModel(): void {
+ editingProfileId.value = undefined
+ editing.value = true
+}
+
+function editModel(profileId: string): void {
+ editingProfileId.value = profileId
+ editing.value = true
+}
+
+async function refreshStatuses(): Promise<void> {
+ const entries = await Promise.all(
+ aiModelSettings.value.connections.map(
+ async (connection) =>
+ [connection.id, await modelConnectionCredentialStatus(connection.id)] as const
+ )
+ )
+ statusByConnection.value = Object.fromEntries(entries)
+}
+
+function statusLabel(connectionId: string, providerID: string): string {
+ if (providerID.startsWith('acp:')) return dialogs.value.modelAgentConnection
+ const status = statusByConnection.value[connectionId]
+ if (status === 'configured') return dialogs.value.connected
+ if (status === 'locked' || status === 'unavailable') return dialogs.value.unavailable
+ return dialogs.value.modelNeedsCredential
+}
+
+function closeEditor(): void {
+ editing.value = false
+ editingProfileId.value = undefined
+ void refreshStatuses()
+}
+
+watch(
+ () => aiModelSettings.value.connections.map((connection) => connection.id),
+ () => void refreshStatuses(),
+ { immediate: true }
+)
+</script>
+
+<template>
+ <ProfileEditor
+ v-if="editing"
+ :key="editingProfileId ?? 'new'"
+ :profile-id="editingProfileId"
+ @done="closeEditor"
+ @deleted="closeEditor"
+ />
+
+ <div v-else class="scrollbar-thin flex min-h-0 flex-1 flex-col overflow-y-auto pr-1">
+ <section>
+ <div class="mb-2 flex items-center justify-between">
+ <div>
+ <h3 class="text-xs font-semibold text-surface">{{ dialogs.models }}</h3>
+ <p class="text-[10px] text-muted">{{ dialogs.modelsDescription }}</p>
+ </div>
+ <button
+ type="button"
+ class="flex items-center gap-1 rounded bg-accent px-2.5 py-1.5 text-[11px] font-medium text-white hover:bg-accent/90"
+ data-test-id="settings-add-model"
+ @click="addModel"
+ >
+ <icon-lucide-plus class="size-3" />
+ {{ dialogs.addModel }}
+ </button>
+ </div>
+
+ <div class="flex flex-col gap-1.5" data-test-id="settings-model-list">
+ <button
+ v-for="profile in profiles"
+ :key="profile.id"
+ type="button"
+ class="group flex items-center gap-3 rounded border border-border bg-panel-field px-3 py-2 text-left hover:border-panel-focus hover:bg-panel-field-hover"
+ :data-model-id="profile.id"
+ @click="editModel(profile.id)"
+ >
+ <div class="flex size-8 shrink-0 items-center justify-center rounded bg-panel text-muted">
+ <icon-lucide-bot class="size-4" />
+ </div>
+ <div class="min-w-0 flex-1">
+ <p class="truncate text-[11px] font-medium text-surface">{{ profile.name }}</p>
+ <p class="truncate text-[10px] text-muted">
+ {{ profile.providerName
+ }}<span v-if="profile.modelName"> · {{ profile.modelName }}</span>
+ </p>
+ </div>
+ <div class="flex shrink-0 items-center gap-1">
+ <span
+ class="mr-1 flex items-center gap-1 text-[9px] text-muted"
+ :data-state="
+ statusByConnection[profile.connectionId] === 'configured' ? 'configured' : 'missing'
+ "
+ >
+ <span
+ class="size-1.5 rounded-full bg-muted data-[state=configured]:bg-[var(--color-success)]"
+ :data-state="
+ statusByConnection[profile.connectionId] === 'configured'
+ ? 'configured'
+ : 'missing'
+ "
+ />
+ {{ statusLabel(profile.connectionId, profile.providerID) }}
+ </span>
+ <span
+ v-for="capability in profile.capabilities"
+ :key="capability"
+ class="rounded bg-panel px-1.5 py-0.5 text-[9px] text-muted"
+ >
+ {{
+ capability === 'tools'
+ ? dialogs.modelCapabilityToolsShort
+ : dialogs.modelCapabilityVisionShort
+ }}
+ </span>
+ </div>
+ <icon-lucide-chevron-right class="size-3.5 shrink-0 text-muted" />
+ </button>
+ </div>
+ </section>
+
+ <section class="mt-5 border-t border-border pt-4">
+ <div class="mb-3">
+ <h3 class="text-xs font-semibold text-surface">{{ dialogs.modelAssignments }}</h3>
+ <p class="text-[10px] text-muted">{{ dialogs.modelAssignmentsDescription }}</p>
+ </div>
+ <RoleAssignments />
+ </section>
+ </div>
+</template>
diff --git a/src/components/settings/models/ProfileEditor.vue b/src/components/settings/models/ProfileEditor.vue
new file mode 100644
index 000000000..64faf8f7c
--- /dev/null
+++ b/src/components/settings/models/ProfileEditor.vue
@@ -0,0 +1,371 @@
+<script setup lang="ts">
+import { computed, reactive, ref, watch } from 'vue'
+import {
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogDescription,
+ AlertDialogTitle
+} from 'reka-ui'
+import { useI18n } from '@open-pencil/vue'
+
+import { AI_PROVIDERS, type AIProviderID } from '@open-pencil/core/constants'
+
+import { refreshAIProviderStatus } from '@/app/ai/chat/storage'
+import {
+ testProviderConnection,
+ type ProviderConnectionTestFailureReason
+} from '@/app/ai/chat/connection-test'
+import {
+ aiModelSettings,
+ createModelProfileDraft,
+ findModelConnectionForDraft,
+ modelConnectionCredentialStatus,
+ modelConnectionUsageCount,
+ modelProfile,
+ removeModelProfile,
+ resolveModelConnectionAPIKey,
+ saveModelProfileDraft,
+ setModelConnectionAPIKey,
+ type AIModelCapability
+} from '@/app/ai/models'
+import ProviderConnectionTestButton from '@/components/chat/ProviderConnectionTestButton.vue'
+import ProviderSelect from '@/components/settings/provider-select/ProviderSelect.vue'
+import ProviderSettingsField from '@/components/settings/provider/ProviderSettingsField.vue'
+import ProviderSettingsInput from '@/components/settings/provider/ProviderSettingsInput.vue'
+import ProviderSettingsKeyField from '@/components/settings/provider/ProviderSettingsKeyField.vue'
+import AppInput from '@/components/ui/AppInput.vue'
+import AppSelect from '@/components/ui/AppSelect.vue'
+import AppSwitch from '@/components/ui/AppSwitch.vue'
+import { AppAlertDialogRoot, AppDialogBody, AppDialogFooter } from '@/components/ui/dialog'
+
+const { profileId } = defineProps<{ profileId?: string }>()
+const emit = defineEmits<{ done: []; deleted: [] }>()
+const { dialogs } = useI18n()
+const draft = reactive(createModelProfileDraft(profileId))
+const keyInput = ref('')
+const keyStatus = ref<'configured' | 'missing' | 'unavailable' | 'locked'>('missing')
+const saveError = ref<string | null>(null)
+const connectionTestStatus = ref<'idle' | 'testing' | 'success' | 'error'>('idle')
+const connectionTestReason = ref<ProviderConnectionTestFailureReason | null>(null)
+const deleteOpen = ref(false)
+
+const providerDef = computed(
+ () => AI_PROVIDERS.find((provider) => provider.id === draft.providerID) ?? AI_PROVIDERS[0]
+)
+const isACP = computed(() => draft.providerID.startsWith('acp:'))
+const modelOptions = computed(() =>
+ providerDef.value.models.map((model) => ({ value: model.id, label: model.name }))
+)
+const modelDisplayName = computed(() => {
+ const modelId = draft.customModelID.trim() || draft.modelID
+ return providerDef.value.models.find((model) => model.id === modelId)?.name || modelId
+})
+const hasExistingKey = computed(() => keyStatus.value === 'configured')
+const canDelete = computed(() => Boolean(profileId) && aiModelSettings.value.models.length > 1)
+const toolsEnabled = capabilityModel('tools')
+const visionEnabled = capabilityModel('vision')
+const canSave = computed(
+ () =>
+ Boolean(draft.name.trim()) &&
+ (isACP.value || Boolean(draft.customModelID.trim() || draft.modelID.trim()))
+)
+const canTest = computed(() => {
+ if (isACP.value) return false
+ if (!keyInput.value.trim() && !hasExistingKey.value) return false
+ if (providerDef.value.supportsCustomBaseURL && !draft.customBaseURL.trim()) return false
+ return Boolean(draft.customModelID.trim() || draft.modelID.trim())
+})
+
+function capabilityModel(capability: AIModelCapability) {
+ return computed({
+ get: () => draft.capabilities.includes(capability),
+ set: (enabled: boolean) => {
+ if (enabled && !draft.capabilities.includes(capability)) draft.capabilities.push(capability)
+ if (!enabled) {
+ draft.capabilities = draft.capabilities.filter((value) => value !== capability)
+ }
+ }
+ })
+}
+
+function resetConnectionTest(): void {
+ connectionTestStatus.value = 'idle'
+ connectionTestReason.value = null
+}
+
+async function refreshKeyStatus(): Promise<void> {
+ const connection = findModelConnectionForDraft(draft)
+ keyStatus.value = connection ? await modelConnectionCredentialStatus(connection.id) : 'missing'
+}
+
+function updateProvider(providerID: AIProviderID): void {
+ draft.providerID = providerID
+ draft.sourceConnectionId = null
+ const provider = AI_PROVIDERS.find((definition) => definition.id === providerID)
+ draft.modelID = provider?.defaultModel ?? ''
+ draft.customModelID = ''
+ draft.customBaseURL = ''
+ draft.customAPIType = 'completions'
+ if (providerID.startsWith('acp:')) {
+ draft.capabilities = ['tools']
+ if (!draft.name.trim()) draft.name = provider?.name ?? ''
+ }
+ keyInput.value = ''
+ resetConnectionTest()
+ void refreshKeyStatus()
+}
+
+function updateModel(modelID: string): void {
+ draft.modelID = modelID
+ if (!draft.name.trim()) draft.name = modelDisplayName.value
+ resetConnectionTest()
+}
+
+async function save(): Promise<void> {
+ saveError.value = null
+ try {
+ if (!draft.name.trim()) draft.name = modelDisplayName.value || providerDef.value.name
+ const profile = saveModelProfileDraft(draft)
+ if (keyInput.value.trim()) {
+ await setModelConnectionAPIKey(profile.connectionId, keyInput.value)
+ await refreshAIProviderStatus()
+ keyInput.value = ''
+ }
+ emit('done')
+ } catch (reason) {
+ saveError.value = reason instanceof Error ? reason.message : String(reason)
+ }
+}
+
+async function clearKey(): Promise<void> {
+ const connection = findModelConnectionForDraft(draft)
+ if (!connection) return
+ await setModelConnectionAPIKey(connection.id, '')
+ await refreshAIProviderStatus()
+ keyInput.value = ''
+ await refreshKeyStatus()
+}
+
+async function testConnection(): Promise<void> {
+ connectionTestStatus.value = 'testing'
+ connectionTestReason.value = null
+ const connection = findModelConnectionForDraft(draft)
+ const existingKey = connection ? await resolveModelConnectionAPIKey(connection.id) : null
+ const result = await testProviderConnection({
+ providerID: draft.providerID,
+ apiKey: keyInput.value.trim() || existingKey || '',
+ modelID: draft.modelID,
+ customModelID: draft.customModelID,
+ customBaseURL: draft.customBaseURL,
+ customAPIType: draft.customAPIType
+ })
+ if (result.ok) {
+ connectionTestStatus.value = 'success'
+ return
+ }
+ connectionTestStatus.value = 'error'
+ connectionTestReason.value = result.reason
+}
+
+async function remove(): Promise<void> {
+ if (!profileId) return
+ const profile = modelProfile(profileId)
+ if (profile && modelConnectionUsageCount(profile.connectionId) === 1) {
+ await setModelConnectionAPIKey(profile.connectionId, '')
+ }
+ removeModelProfile(profileId)
+ await refreshAIProviderStatus()
+ deleteOpen.value = false
+ emit('deleted')
+}
+
+watch(
+ () => [draft.customBaseURL, draft.customModelID, draft.customAPIType, draft.modelID],
+ resetConnectionTest
+)
+void refreshKeyStatus()
+</script>
+
+<template>
+ <div class="flex min-h-0 flex-1 flex-col" data-test-id="settings-model-editor">
+ <div class="flex items-center gap-2 border-b border-border pb-3">
+ <button
+ type="button"
+ class="flex size-6 items-center justify-center rounded text-muted hover:bg-hover hover:text-surface"
+ :aria-label="dialogs.back"
+ @click="emit('done')"
+ >
+ <icon-lucide-arrow-left class="size-3.5" />
+ </button>
+ <div>
+ <h3 class="text-xs font-semibold text-surface">
+ {{ profileId ? dialogs.editModel : dialogs.addModel }}
+ </h3>
+ <p class="text-[10px] text-muted">{{ dialogs.modelEditorDescription }}</p>
+ </div>
+ </div>
+
+ <div class="scrollbar-thin flex min-h-0 flex-1 flex-col gap-2.5 overflow-y-auto py-3 pr-1">
+ <ProviderSettingsField :label="dialogs.modelName">
+ <AppInput
+ v-model="draft.name"
+ :aria-label="dialogs.modelName"
+ :placeholder="modelDisplayName"
+ size="sm"
+ />
+ </ProviderSettingsField>
+
+ <ProviderSettingsField :label="dialogs.aiProvider">
+ <ProviderSelect
+ :model-value="draft.providerID"
+ :aria-label="dialogs.aiProvider"
+ data-test-id="settings-model-provider"
+ :ui="{
+ trigger:
+ 'w-full justify-between rounded border border-border bg-input px-2.5 py-1.5 text-xs text-surface',
+ item: 'rounded px-2 py-1.5 text-[11px]'
+ }"
+ @update:model-value="updateProvider"
+ />
+ </ProviderSettingsField>
+
+ <template v-if="!isACP">
+ <ProviderSettingsField v-if="modelOptions.length" :label="dialogs.modelID">
+ <AppSelect
+ :model-value="draft.modelID"
+ :options="modelOptions"
+ :label="dialogs.modelID"
+ @update:model-value="updateModel(String($event))"
+ />
+ </ProviderSettingsField>
+
+ <ProviderSettingsField v-if="providerDef.supportsCustomBaseURL" :label="dialogs.baseURL">
+ <ProviderSettingsInput
+ v-model="draft.customBaseURL"
+ :aria-label="dialogs.baseURL"
+ placeholder="http://localhost:11434/v1"
+ />
+ </ProviderSettingsField>
+
+ <ProviderSettingsField v-if="providerDef.supportsCustomModel" :label="dialogs.modelID">
+ <ProviderSettingsInput
+ v-model="draft.customModelID"
+ :aria-label="dialogs.modelID"
+ data-test-id="provider-settings-custom-model"
+ placeholder="e.g. llama-3.3-70b"
+ />
+ </ProviderSettingsField>
+
+ <ProviderSettingsField
+ v-if="draft.providerID === 'openai-compatible'"
+ :label="dialogs.apiType"
+ >
+ <AppSelect
+ v-model="draft.customAPIType"
+ :label="dialogs.apiType"
+ :options="[
+ { value: 'completions', label: dialogs.completions },
+ { value: 'responses', label: dialogs.responses }
+ ]"
+ />
+ </ProviderSettingsField>
+
+ <ProviderSettingsField :label="dialogs.maxOutputTokens">
+ <ProviderSettingsInput
+ v-model.number="draft.maxOutputTokens"
+ :aria-label="dialogs.maxOutputTokens"
+ type="number"
+ :min="1024"
+ :max="128000"
+ :step="1024"
+ />
+ </ProviderSettingsField>
+
+ <ProviderSettingsKeyField
+ v-model="keyInput"
+ :label="dialogs.apiKey"
+ :saved="hasExistingKey"
+ kind="api"
+ :placeholder="hasExistingKey ? dialogs.keySavedReplace : providerDef.keyPlaceholder"
+ :key-url="providerDef.keyURL"
+ :key-url-label="dialogs.getAPIKeyGeneric"
+ @clear="clearKey"
+ />
+
+ <ProviderConnectionTestButton
+ :status="connectionTestStatus"
+ :reason="connectionTestReason"
+ :disabled="!canTest"
+ @test="testConnection"
+ />
+ </template>
+
+ <div class="rounded border border-border p-2.5">
+ <p class="mb-2 text-[11px] font-medium text-surface">{{ dialogs.modelCapabilities }}</p>
+ <div class="flex flex-col gap-2">
+ <div class="flex items-center justify-between gap-3">
+ <span class="text-[11px] text-muted">{{ dialogs.modelCapabilityTools }}</span>
+ <AppSwitch v-model="toolsEnabled" :label="dialogs.modelCapabilityTools" />
+ </div>
+ <div class="flex items-center justify-between gap-3">
+ <span class="text-[11px] text-muted">{{ dialogs.modelCapabilityVision }}</span>
+ <AppSwitch v-model="visionEnabled" :label="dialogs.modelCapabilityVision" />
+ </div>
+ </div>
+ </div>
+
+ <p v-if="saveError" class="text-[10px] text-danger" role="alert">{{ saveError }}</p>
+ </div>
+
+ <div class="flex shrink-0 items-center gap-2 border-t border-border pt-3">
+ <button
+ v-if="canDelete"
+ type="button"
+ class="rounded px-2.5 py-1.5 text-[11px] text-danger hover:bg-danger/10"
+ @click="deleteOpen = true"
+ >
+ {{ dialogs.deleteModel }}
+ </button>
+ <button
+ type="button"
+ class="ml-auto rounded px-2.5 py-1.5 text-[11px] text-muted hover:bg-hover hover:text-surface"
+ @click="emit('done')"
+ >
+ {{ dialogs.cancel }}
+ </button>
+ <button
+ type="button"
+ class="rounded bg-accent px-3 py-1.5 text-[11px] font-medium text-white hover:bg-accent/90 disabled:opacity-50"
+ :disabled="!canSave"
+ @click="save"
+ >
+ {{ dialogs.saveModel }}
+ </button>
+ </div>
+ </div>
+
+ <AppAlertDialogRoot v-model:open="deleteOpen" data-test-id="delete-model-dialog">
+ <div class="border-b border-border px-4 py-3">
+ <AlertDialogTitle class="text-sm font-semibold text-surface">
+ {{ dialogs.deleteModel }}
+ </AlertDialogTitle>
+ </div>
+ <AppDialogBody>
+ <AlertDialogDescription class="text-xs text-muted">
+ {{ dialogs.deleteModelDescription }}
+ </AlertDialogDescription>
+ </AppDialogBody>
+ <AppDialogFooter>
+ <AlertDialogCancel as-child>
+ <button class="rounded px-3 py-1.5 text-xs text-muted hover:bg-hover">
+ {{ dialogs.cancel }}
+ </button>
+ </AlertDialogCancel>
+ <AlertDialogAction as-child>
+ <button class="rounded bg-danger px-3 py-1.5 text-xs text-white" @click="remove">
+ {{ dialogs.deleteModel }}
+ </button>
+ </AlertDialogAction>
+ </AppDialogFooter>
+ </AppAlertDialogRoot>
+</template>
diff --git a/src/components/settings/models/RoleAssignments.vue b/src/components/settings/models/RoleAssignments.vue
new file mode 100644
index 000000000..d60c9058e
--- /dev/null
+++ b/src/components/settings/models/RoleAssignments.vue
@@ -0,0 +1,106 @@
+<script setup lang="ts">
+import { computed } from 'vue'
+import { useI18n } from '@open-pencil/vue'
+
+import {
+ aiModelSettings,
+ modelProfile,
+ setModelRoleAssignment,
+ type AIModelRole,
+ type OptionalAIModelRole
+} from '@/app/ai/models'
+import AppSelect from '@/components/ui/AppSelect.vue'
+
+const { dialogs } = useI18n()
+const SAME_AS_DESIGN = '__design__'
+const NO_MODEL = '__none__'
+
+const roleDefinitions = computed(() => [
+ {
+ role: 'design' as const,
+ label: dialogs.value.modelRoleDesign,
+ description: dialogs.value.modelRoleDesignDescription
+ },
+ {
+ role: 'review' as const,
+ label: dialogs.value.modelRoleReview,
+ description: dialogs.value.modelRoleReviewDescription
+ },
+ {
+ role: 'fast' as const,
+ label: dialogs.value.modelRoleFast,
+ description: dialogs.value.modelRoleFastDescription
+ },
+ {
+ role: 'vision' as const,
+ label: dialogs.value.modelRoleVision,
+ description: dialogs.value.modelRoleVisionDescription
+ }
+])
+
+function assignmentValue(role: AIModelRole): string {
+ const assignment = aiModelSettings.value.assignments[role]
+ if (assignment === null) return NO_MODEL
+ return assignment === 'design' ? SAME_AS_DESIGN : assignment
+}
+
+function optionsForRole(role: AIModelRole) {
+ const profiles = aiModelSettings.value.models
+ .filter((profile) => {
+ if (role === 'design') return profile.capabilities.includes('tools')
+ if (role === 'vision') return profile.capabilities.includes('vision')
+ return true
+ })
+ .map((profile) => ({ value: profile.id, label: profile.name }))
+ if (role === 'design') return profiles
+
+ const design = modelProfile(aiModelSettings.value.assignments.design)
+ const canInherit = role !== 'vision' || design?.capabilities.includes('vision')
+ return [
+ ...(canInherit ? [{ value: SAME_AS_DESIGN, label: dialogs.value.modelRoleUseDesign }] : []),
+ { value: NO_MODEL, label: dialogs.value.noModel },
+ ...profiles
+ ]
+}
+
+function updateAssignment(role: AIModelRole, value: string): void {
+ if (role === 'design') {
+ const profile = modelProfile(value)
+ if (profile) setModelRoleAssignment('design', profile.id)
+ return
+ }
+ if (value === NO_MODEL) {
+ setModelRoleAssignment(role as OptionalAIModelRole, null)
+ return
+ }
+ if (value === SAME_AS_DESIGN) {
+ setModelRoleAssignment(role as OptionalAIModelRole, 'design')
+ return
+ }
+ const profile = modelProfile(value)
+ if (profile) setModelRoleAssignment(role as OptionalAIModelRole, profile.id)
+}
+</script>
+
+<template>
+ <div class="flex flex-col gap-2">
+ <div
+ v-for="definition in roleDefinitions"
+ :key="definition.role"
+ class="grid grid-cols-[10rem_minmax(0,1fr)] items-center gap-3"
+ :data-model-role="definition.role"
+ >
+ <div class="min-w-0">
+ <p class="text-[11px] font-medium text-surface">{{ definition.label }}</p>
+ <p class="text-[10px] leading-tight text-muted">{{ definition.description }}</p>
+ </div>
+ <AppSelect
+ :model-value="assignmentValue(definition.role)"
+ :options="optionsForRole(definition.role)"
+ :label="definition.label"
+ :data-test-id="`settings-model-assignment-${definition.role}`"
+ @update:model-value="updateAssignment(definition.role, String($event))"
+ />
+ </div>
+ </div>
+</template>
diff --git a/src/components/settings/provider-select/ProviderSelect.vue b/src/components/settings/provider-select/ProviderSelect.vue
index cb2f63624..b9cf2192f 100644
--- a/src/components/settings/provider-select/ProviderSelect.vue
+++ b/src/components/settings/provider-select/ProviderSelect.vue
@@ -7,11 +7,9 @@ import {
ACP_AGENTS,
AI_PROVIDERS,
AUTOMATION_HTTP_PORT,
- IS_TAURI
+ IS_TAURI,
+ type AIProviderID
} from '@open-pencil/core/constants'
-import { useAIChat } from '@/app/ai/chat/use'
-
-const { providerID, providerDef } = useAIChat()
const mcpAvailable = ref(false)
@@ -37,34 +35,40 @@ async function checkMCPHealth(retries = 3, delayMs = 1000) {
}
}
+interface ProviderSelectProps {
+ allowAgents?: boolean
+ ui?: {
+ trigger?: string
+ content?: string
+ item?: string
+ label?: string
+ separator?: string
+ }
+}
+
+const { allowAgents = true, ui } = defineProps<ProviderSelectProps>()
+
if (IS_TAURI) {
onMounted(() => {
void checkMCPHealth()
})
}
-const acpAgents = computed(() => (IS_TAURI && mcpAvailable.value ? ACP_AGENTS : []))
+const acpAgents = computed(() => (allowAgents && IS_TAURI && mcpAvailable.value ? ACP_AGENTS : []))
+
+const providerID = defineModel<AIProviderID>({ required: true })
+const providerDef = computed(
+ () => AI_PROVIDERS.find((provider) => provider.id === providerID.value) ?? AI_PROVIDERS[0]
+)
const displayName = computed(() => {
if (providerID.value.startsWith('acp:')) {
const agentId = providerID.value.replace('acp:', '')
- return ACP_AGENTS.find((a) => a.id === agentId)?.name ?? providerID.value
+ return ACP_AGENTS.find((agent) => agent.id === agentId)?.name ?? providerID.value
}
return providerDef.value.name
})
-interface ProviderSelectProps {
- ui?: {
- trigger?: string
- content?: string
- item?: string
- label?: string
- separator?: string
- }
-}
-
-const { ui } = defineProps<ProviderSelectProps>()
-
const groups = computed(() => {
const result: Array<{ label?: string; items: Array<{ value: string; label: string }> }> = []
diff --git a/src/components/settings/provider-select/ProviderSelectField.vue b/src/components/settings/provider-select/ProviderSelectField.vue
deleted file mode 100644
index 28233a3eb..000000000
--- a/src/components/settings/provider-select/ProviderSelectField.vue
+++ /dev/null
@@ -1,13 +0,0 @@
-<script setup lang="ts">
-import ProviderSelect from '@/components/settings/provider-select/ProviderSelect.vue'
-</script>
-
-<template>
- <ProviderSelect
- :ui="{
- trigger:
- 'w-full justify-between rounded border border-border bg-input px-2.5 py-1.5 text-xs text-surface',
- item: 'rounded px-2 py-1.5 text-[11px]'
- }"
- />
-</template>
diff --git a/src/components/settings/provider/ApiKeySection.vue b/src/components/settings/provider/ApiKeySection.vue
deleted file mode 100644
index d586421ad..000000000
--- a/src/components/settings/provider/ApiKeySection.vue
+++ /dev/null
@@ -1,24 +0,0 @@
-<script setup lang="ts">
-import { useI18n } from '@open-pencil/vue'
-
-import ProviderSettingsKeyField from '@/components/settings/provider/ProviderSettingsKeyField.vue'
-import { useProviderSettingsContext } from '@/components/settings/provider/context'
-
-const ctx = useProviderSettingsContext()
-const { dialogs } = useI18n()
-</script>
-
-<template>
- <ProviderSettingsKeyField
- v-if="!ctx.isACP"
- v-model="ctx.keyInput"
- :label="dialogs.apiKey"
- :saved="ctx.apiKeyStatus === 'configured'"
- kind="api"
- :placeholder="ctx.hasExistingKey ? dialogs.keySavedReplace : ctx.providerDef.keyPlaceholder"
- :key-url="ctx.providerDef.keyURL"
- :key-url-label="dialogs.getAPIKeyGeneric"
- @clear="ctx.clearKey"
- @change="ctx.save"
- />
-</template>
diff --git a/src/components/settings/provider/ApiTypeSection.vue b/src/components/settings/provider/ApiTypeSection.vue
deleted file mode 100644
index cb6bc431c..000000000
--- a/src/components/settings/provider/ApiTypeSection.vue
+++ /dev/null
@@ -1,41 +0,0 @@
-<script setup lang="ts">
-import { TabsContent, TabsList, TabsRoot, TabsTrigger } from 'reka-ui'
-import { useI18n } from '@open-pencil/vue'
-
-import ProviderSettingsField from '@/components/settings/provider/ProviderSettingsField.vue'
-import { useProviderSettingsContext } from '@/components/settings/provider/context'
-
-const ctx = useProviderSettingsContext()
-const { dialogs } = useI18n()
-</script>
-
-<template>
- <ProviderSettingsField
- v-if="!ctx.isACP && ctx.providerID === 'openai-compatible'"
- :label="dialogs.apiType"
- >
- <TabsRoot
- :model-value="ctx.customAPIType"
- data-test-id="provider-settings-api-type"
- class="flex flex-col"
- @update:model-value="ctx.setCustomAPIType"
- >
- <TabsList class="flex rounded bg-canvas">
- <TabsTrigger
- value="completions"
- class="flex-1 rounded px-2 py-1 text-[10px] text-muted data-[state=active]:bg-hover data-[state=active]:text-surface"
- >
- {{ dialogs.completions }}
- </TabsTrigger>
- <TabsTrigger
- value="responses"
- class="flex-1 rounded px-2 py-1 text-[10px] text-muted data-[state=active]:bg-hover data-[state=active]:text-surface"
- >
- {{ dialogs.responses }}
- </TabsTrigger>
- </TabsList>
- <TabsContent value="completions" />
- <TabsContent value="responses" />
- </TabsRoot>
- </ProviderSettingsField>
-</template>
diff --git a/src/components/settings/provider/CustomEndpointSection.vue b/src/components/settings/provider/CustomEndpointSection.vue
deleted file mode 100644
index 8fa6c69c8..000000000
--- a/src/components/settings/provider/CustomEndpointSection.vue
+++ /dev/null
@@ -1,52 +0,0 @@
-<script setup lang="ts">
-import { computed, ref } from 'vue'
-import { useI18n } from '@open-pencil/vue'
-
-import { listProviderModels } from '@/app/ai/chat/provider-models'
-import AppComboboxInput from '@/components/ui/AppComboboxInput.vue'
-import ProviderSettingsField from '@/components/settings/provider/ProviderSettingsField.vue'
-import ProviderSettingsInput from '@/components/settings/provider/ProviderSettingsInput.vue'
-import { useProviderSettingsContext } from '@/components/settings/provider/context'
-
-const ctx = useProviderSettingsContext()
-const { dialogs } = useI18n()
-const suggestedModels = ref<Array<{ id: string; name: string }>>([])
-const showModelSuggestions = computed(() => ctx.providerID === 'openrouter')
-
-async function loadModelSuggestions() {
- if (!showModelSuggestions.value || suggestedModels.value.length) return
- suggestedModels.value = await listProviderModels(ctx.providerID)
-}
-</script>
-
-<template>
- <template v-if="!ctx.isACP">
- <ProviderSettingsField v-if="ctx.providerDef.supportsCustomBaseURL" :label="dialogs.baseURL">
- <ProviderSettingsInput
- v-model="ctx.baseURLInput"
- data-test-id="provider-settings-base-url"
- placeholder="http://localhost:11434/v1"
- @change="ctx.save"
- />
- </ProviderSettingsField>
-
- <ProviderSettingsField v-if="ctx.providerDef.supportsCustomModel" :label="dialogs.modelID">
- <AppComboboxInput
- v-if="showModelSuggestions"
- v-model="ctx.customModelInput"
- data-test-id="provider-settings-custom-model"
- :options="suggestedModels.map((model) => ({ value: model.id, label: model.name }))"
- placeholder="e.g. meta-llama/llama-3.3-70b-instruct"
- @focusin="loadModelSuggestions"
- @update:model-value="ctx.save"
- />
- <ProviderSettingsInput
- v-else
- v-model="ctx.customModelInput"
- data-test-id="provider-settings-custom-model"
- placeholder="e.g. llama-3.3-70b"
- @change="ctx.save"
- />
- </ProviderSettingsField>
- </template>
-</template>
diff --git a/src/components/settings/provider/MaxTokensSection.vue b/src/components/settings/provider/MaxTokensSection.vue
deleted file mode 100644
index 8c6d0482a..000000000
--- a/src/components/settings/provider/MaxTokensSection.vue
+++ /dev/null
@@ -1,23 +0,0 @@
-<script setup lang="ts">
-import { useI18n } from '@open-pencil/vue'
-
-import ProviderSettingsField from '@/components/settings/provider/ProviderSettingsField.vue'
-import ProviderSettingsInput from '@/components/settings/provider/ProviderSettingsInput.vue'
-import { useProviderSettingsContext } from '@/components/settings/provider/context'
-
-const ctx = useProviderSettingsContext()
-const { dialogs } = useI18n()
-</script>
-
-<template>
- <ProviderSettingsField v-if="!ctx.isACP" :label="dialogs.maxOutputTokens">
- <ProviderSettingsInput
- v-model.number="ctx.maxOutputTokens"
- type="number"
- data-test-id="provider-settings-max-tokens"
- :min="1024"
- :max="128000"
- :step="1024"
- />
- </ProviderSettingsField>
-</template>
diff --git a/src/components/settings/provider/StockPhotoKeysSection.vue b/src/components/settings/provider/StockPhotoKeysSection.vue
index a2d301023..ed0e87039 100644
--- a/src/components/settings/provider/StockPhotoKeysSection.vue
+++ b/src/components/settings/provider/StockPhotoKeysSection.vue
@@ -1,39 +1,66 @@
<script setup lang="ts">
+import { computed, ref } from 'vue'
import { useI18n } from '@open-pencil/vue'
+import { useAIChat } from '@/app/ai/chat/use'
import ProviderSettingsKeyField from '@/components/settings/provider/ProviderSettingsKeyField.vue'
-import { useProviderSettingsContext } from '@/components/settings/provider/context'
-const ctx = useProviderSettingsContext()
const { dialogs } = useI18n()
+const { pexelsKeyStatus, setPexelsKey, unsplashKeyStatus, setUnsplashKey } = useAIChat()
+const pexelsKeyInput = ref('')
+const unsplashKeyInput = ref('')
+const hasExistingPexelsKey = computed(() => pexelsKeyStatus.value === 'configured')
+const hasExistingUnsplashKey = computed(() => unsplashKeyStatus.value === 'configured')
+
+async function savePexelsKey(): Promise<void> {
+ const value = pexelsKeyInput.value.trim()
+ if (!value) return
+ await setPexelsKey(value)
+ pexelsKeyInput.value = ''
+}
+
+async function saveUnsplashKey(): Promise<void> {
+ const value = unsplashKeyInput.value.trim()
+ if (!value) return
+ await setUnsplashKey(value)
+ unsplashKeyInput.value = ''
+}
+
+async function clearPexelsKey(): Promise<void> {
+ await setPexelsKey('')
+ pexelsKeyInput.value = ''
+}
+
+async function clearUnsplashKey(): Promise<void> {
+ await setUnsplashKey('')
+ unsplashKeyInput.value = ''
+}
</script>
<template>
<ProviderSettingsKeyField
- v-model="ctx.pexelsKeyInput"
+ v-model="pexelsKeyInput"
:label="dialogs.pexelsAPIKey"
- :saved="ctx.pexelsKeyStatus === 'configured'"
+ :saved="hasExistingPexelsKey"
kind="pexels"
- :placeholder="
- ctx.hasExistingPexelsKey ? dialogs.keySavedReplace : dialogs.stockPhotoToolOptional
- "
+ :placeholder="hasExistingPexelsKey ? dialogs.keySavedReplace : dialogs.stockPhotoToolOptional"
key-url="https://www.pexels.com/api/"
:key-url-label="dialogs.getPexelsAPIKey"
- @clear="ctx.clearPexelsKey"
- @change="ctx.save"
+ @clear="clearPexelsKey"
+ @change="savePexelsKey"
/>
<ProviderSettingsKeyField
- v-model="ctx.unsplashKeyInput"
+ v-model="unsplashKeyInput"
:label="dialogs.unsplashAccessKey"
- :saved="ctx.unsplashKeyStatus === 'configured'"
+ :saved="hasExistingUnsplashKey"
kind="unsplash"
:placeholder="
- ctx.hasExistingUnsplashKey ? dialogs.keySavedReplace : dialogs.pexelsAlternativeOptional
+ hasExistingUnsplashKey ? dialogs.keySavedReplace : dialogs.pexelsAlternativeOptional
"
key-url="https://unsplash.com/oauth/applications"
:key-url-label="dialogs.getUnsplashAccessKey"
- @clear="ctx.clearUnsplashKey"
- @change="ctx.save"
+ @clear="clearUnsplashKey"
+ @change="saveUnsplashKey"
/>
</template>
diff --git a/src/components/settings/provider/TestConnectionSection.vue b/src/components/settings/provider/TestConnectionSection.vue
deleted file mode 100644
index 8d3f8af8c..000000000
--- a/src/components/settings/provider/TestConnectionSection.vue
+++ /dev/null
@@ -1,16 +0,0 @@
-<script setup lang="ts">
-import ProviderConnectionTestButton from '@/components/chat/ProviderConnectionTestButton.vue'
-import { useProviderSettingsContext } from '@/components/settings/provider/context'
-
-const ctx = useProviderSettingsContext()
-</script>
-
-<template>
- <ProviderConnectionTestButton
- v-if="!ctx.isACP"
- :status="ctx.connectionTestStatus"
- :reason="ctx.connectionTestReason"
- :disabled="!ctx.canTestConnection"
- @test="ctx.testConnection"
- />
-</template>
diff --git a/src/components/settings/provider/context.ts b/src/components/settings/provider/context.ts
deleted file mode 100644
index ba4bb1350..000000000
--- a/src/components/settings/provider/context.ts
+++ /dev/null
@@ -1,196 +0,0 @@
-import { computed, inject, provide, proxyRefs, ref, watch } from 'vue'
-import type { InjectionKey, ShallowUnwrapRef } from 'vue'
-
-import {
- testProviderConnection,
- type ProviderConnectionTestFailureReason
-} from '@/app/ai/chat/connection-test'
-import { useAIChat } from '@/app/ai/chat/use'
-
-function createProviderSettingsContext() {
- const {
- providerID,
- providerDef,
- apiKeyStatus,
- setAPIKey,
- resolveAPIKey,
- customBaseURL,
- customModelID,
- modelID,
- customAPIType,
- maxOutputTokens,
- pexelsKeyStatus,
- setPexelsKey,
- unsplashKeyStatus,
- setUnsplashKey
- } = useAIChat()
-
- const isACP = computed(() => providerID.value.startsWith('acp:'))
- const keyInput = ref('')
- const pexelsKeyInput = ref('')
- const unsplashKeyInput = ref('')
- const baseURLInput = ref(customBaseURL.value)
- const customModelInput = ref(customModelID.value)
- const hasExistingKey = ref(apiKeyStatus.value === 'configured')
- const hasExistingPexelsKey = ref(pexelsKeyStatus.value === 'configured')
- const hasExistingUnsplashKey = ref(unsplashKeyStatus.value === 'configured')
- const connectionTestStatus = ref<'idle' | 'testing' | 'success' | 'error'>('idle')
- const connectionTestReason = ref<ProviderConnectionTestFailureReason | null>(null)
-
- const canTestConnection = computed(() => {
- if (isACP.value) return false
- if (!keyInput.value.trim() && !hasExistingKey.value) return false
- if (providerDef.value.supportsCustomBaseURL && !baseURLInput.value.trim()) return false
- if (providerDef.value.supportsCustomModel && !customModelInput.value.trim()) return false
- return true
- })
-
- function resetConnectionTest() {
- connectionTestStatus.value = 'idle'
- connectionTestReason.value = null
- }
-
- watch(providerID, () => {
- keyInput.value = ''
- hasExistingKey.value = apiKeyStatus.value === 'configured'
- baseURLInput.value = customBaseURL.value
- customModelInput.value = customModelID.value
- resetConnectionTest()
- })
-
- watch([keyInput, baseURLInput, customModelInput, customAPIType], resetConnectionTest)
- watch(apiKeyStatus, (status) => {
- hasExistingKey.value = status === 'configured'
- })
- watch(pexelsKeyStatus, (status) => {
- hasExistingPexelsKey.value = status === 'configured'
- })
- watch(unsplashKeyStatus, (status) => {
- hasExistingUnsplashKey.value = status === 'configured'
- })
-
- async function save() {
- if (keyInput.value.trim()) {
- await setAPIKey(keyInput.value.trim())
- hasExistingKey.value = true
- keyInput.value = ''
- }
- if (pexelsKeyInput.value.trim()) {
- await setPexelsKey(pexelsKeyInput.value.trim())
- hasExistingPexelsKey.value = true
- pexelsKeyInput.value = ''
- }
- if (unsplashKeyInput.value.trim()) {
- await setUnsplashKey(unsplashKeyInput.value.trim())
- hasExistingUnsplashKey.value = true
- unsplashKeyInput.value = ''
- }
- if (providerDef.value.supportsCustomBaseURL) {
- customBaseURL.value = baseURLInput.value.trim()
- }
- if (providerDef.value.supportsCustomModel) {
- customModelID.value = customModelInput.value.trim()
- }
- }
-
- async function clearKey() {
- await setAPIKey('')
- keyInput.value = ''
- hasExistingKey.value = false
- }
-
- async function clearPexelsKey() {
- await setPexelsKey('')
- pexelsKeyInput.value = ''
- hasExistingPexelsKey.value = false
- }
-
- async function clearUnsplashKey() {
- await setUnsplashKey('')
- unsplashKeyInput.value = ''
- hasExistingUnsplashKey.value = false
- }
-
- function setCustomAPIType(value: string) {
- customAPIType.value = value as 'completions' | 'responses'
- void save()
- }
-
- async function testConnection() {
- if (connectionTestStatus.value === 'testing') return
- connectionTestStatus.value = 'testing'
- connectionTestReason.value = null
-
- const result = await testProviderConnection({
- providerID: providerID.value,
- apiKey: keyInput.value.trim() || (await resolveAPIKey()) || '',
- modelID: modelID.value,
- customModelID: providerDef.value.supportsCustomModel
- ? customModelInput.value.trim()
- : customModelID.value,
- customBaseURL: providerDef.value.supportsCustomBaseURL
- ? baseURLInput.value.trim()
- : customBaseURL.value,
- customAPIType: customAPIType.value
- })
-
- if (result.ok) {
- connectionTestStatus.value = 'success'
- connectionTestReason.value = null
- return
- }
-
- connectionTestStatus.value = 'error'
- connectionTestReason.value = result.reason
- }
-
- return {
- providerID,
- providerDef,
- apiKeyStatus,
- modelID,
- customAPIType,
- customBaseURL,
- customModelID,
- maxOutputTokens,
- pexelsKeyStatus,
- unsplashKeyStatus,
- isACP,
- keyInput,
- pexelsKeyInput,
- unsplashKeyInput,
- baseURLInput,
- customModelInput,
- hasExistingKey,
- hasExistingPexelsKey,
- hasExistingUnsplashKey,
- connectionTestStatus,
- connectionTestReason,
- canTestConnection,
- save,
- clearKey,
- clearPexelsKey,
- clearUnsplashKey,
- setCustomAPIType,
- testConnection
- }
-}
-
-export type ProviderSettingsContext = ShallowUnwrapRef<
- ReturnType<typeof createProviderSettingsContext>
->
-
-const PROVIDER_SETTINGS_KEY: InjectionKey<ProviderSettingsContext> =
- Symbol('ProviderSettingsContext')
-
-export function provideProviderSettings() {
- const ctx = proxyRefs(createProviderSettingsContext())
- provide(PROVIDER_SETTINGS_KEY, ctx)
- return ctx
-}
-
-export function useProviderSettingsContext(): ProviderSettingsContext {
- const ctx = inject(PROVIDER_SETTINGS_KEY)
- if (!ctx) throw new Error('Provider settings controls must be used within ProviderSettings')
- return ctx
-}
diff --git a/src/components/ui/dialog/AppAlertDialogRoot.vue b/src/components/ui/dialog/AppAlertDialogRoot.vue
index 06b377a5b..2b71922bb 100644
--- a/src/components/ui/dialog/AppAlertDialogRoot.vue
+++ b/src/components/ui/dialog/AppAlertDialogRoot.vue
@@ -27,7 +27,7 @@ const cls = computed(() => useDialogUI(ui, { size, height }))
</script>
<template>
- <AlertDialogRoot :open="open">
+ <AlertDialogRoot :open="open" @update:open="open = $event">
<AlertDialogPortal>
<AlertDialogOverlay
data-slot="alert-dialog-overlay"
diff --git a/tests/e2e/chat/panel.spec.ts b/tests/e2e/chat/panel.spec.ts
index 0cc012758..8c26173e3 100644
--- a/tests/e2e/chat/panel.spec.ts
+++ b/tests/e2e/chat/panel.spec.ts
@@ -153,9 +153,12 @@ test('saving API key in unified settings shows chat interface', async () => {
'unchecked'
)
await expect(page.getByTestId('settings-credential-backend')).toContainText('this session only')
- await page.getByTestId('settings-ai-provider').click()
+ await page.locator('[data-model-id]').first().click()
+ await page.getByTestId('settings-model-provider').click()
await page.getByRole('option', { name: 'OpenRouter' }).click()
+ await page.getByLabel('Name').fill('Claude Sonnet')
await apiKeyInput().fill(key)
+ await page.getByRole('button', { name: 'Save model' }).click()
await page.getByTestId('app-settings-done').click()
await expect(chatInput()).toBeVisible()
@@ -236,16 +239,20 @@ test('OpenRouter accepts a custom model ID from provider settings', async () =>
await page.keyboard.press('Escape')
await page.getByTestId('provider-settings-trigger').click()
+ await page.locator('[data-model-id]').first().click()
const customModelInput = page.getByTestId('provider-settings-custom-model')
await expect(customModelInput).toBeVisible()
await customModelInput.fill(customModel)
+ await page.getByRole('button', { name: 'Save model' }).click()
await page.getByTestId('app-settings-done').click()
await expect(page.getByTestId('chat-custom-model-label')).toContainText(customModel)
await expect(page.getByTestId('chat-model-selector')).toBeHidden()
await page.getByTestId('provider-settings-trigger').click()
+ await page.locator('[data-model-id]').first().click()
await page.getByTestId('provider-settings-custom-model').fill('')
+ await page.getByRole('button', { name: 'Save model' }).click()
await page.getByTestId('app-settings-done').click()
await expect(page.getByTestId('chat-model-selector')).toBeVisible()
@@ -268,6 +275,9 @@ test('"Get API key" link opens external URL via window.open', async () => {
await canvas.waitForInit()
await chatTab().click()
await page.getByTestId('provider-setup-open-settings').click()
+ await page.locator('[data-model-id]').first().click()
+ await page.getByTestId('settings-model-provider').click()
+ await page.getByRole('option', { name: 'OpenRouter' }).click()
const link = page.getByRole('button', { name: 'Get API key →' })
await expect(link).toBeVisible()
diff --git a/tests/e2e/settings/credentials.spec.ts b/tests/e2e/settings/credentials.spec.ts
index 01065071b..bf3648ca1 100644
--- a/tests/e2e/settings/credentials.spec.ts
+++ b/tests/e2e/settings/credentials.spec.ts
@@ -33,6 +33,44 @@ test('storage settings keep secrets behind the credential manager', async ({ pag
await expect(secretField.locator('input')).not.toHaveAttribute('placeholder', /Key saved/)
})
+test('model library keeps reusable profiles and role assignments', async ({ page }) => {
+ await page.goto('/?test')
+ const canvas = new CanvasHelper(page)
+ await canvas.waitForInit()
+
+ await page.getByTestId('app-settings-trigger').click()
+ await page.getByTestId('settings-add-model').click()
+ await page.getByLabel('Name').fill('Fast model')
+ await page.getByTestId('settings-model-provider').click()
+ await page.getByRole('option', { name: 'Google AI' }).click()
+ await page.getByLabel('Model ID').click()
+ await page.getByRole('option', { name: 'Gemini 3 Flash' }).click()
+ await page.getByRole('button', { name: 'Save model' }).click()
+
+ await page.getByTestId('settings-add-model').click()
+ await page.getByLabel('Name').fill('Vision model')
+ await page.getByTestId('settings-model-provider').click()
+ await page.getByRole('option', { name: 'OpenRouter' }).click()
+ await page.getByLabel('Model ID').first().click()
+ await page.getByRole('option', { name: 'Kimi K2.5' }).click()
+ await page.getByRole('switch', { name: 'Image input' }).click()
+ await page.getByRole('button', { name: 'Save model' }).click()
+
+ await page.getByTestId('settings-model-assignment-fast').click()
+ await page.getByRole('option', { name: 'Fast model' }).click()
+ await page.getByTestId('settings-model-assignment-vision').click()
+ await page.getByRole('option', { name: 'Vision model' }).click()
+ await page.getByTestId('app-settings-done').click()
+
+ await page.reload()
+ await canvas.waitForInit()
+ await page.getByTestId('app-settings-trigger').click()
+ await expect(page.getByTestId('settings-model-list')).toContainText('Fast model')
+ await expect(page.getByTestId('settings-model-list')).toContainText('Vision model')
+ await expect(page.getByTestId('settings-model-assignment-fast')).toContainText('Fast model')
+ await expect(page.getByTestId('settings-model-assignment-vision')).toContainText('Vision model')
+})
+
test('remembered browser credentials survive reload and clear centrally', async ({ page }) => {
await page.goto('/?test')
const canvas = new CanvasHelper(page)
@@ -49,9 +87,12 @@ test('remembered browser credentials survive reload and clear centrally', async
'encrypted browser storage'
)
- await page.getByTestId('settings-ai-provider').click()
+ await page.locator('[data-model-id]').first().click()
+ await page.getByTestId('settings-model-provider').click()
await page.getByRole('option', { name: 'OpenRouter' }).click()
+ await page.getByLabel('Name').fill('Claude Sonnet')
await page.getByTestId('provider-settings-api-key').fill('sk-or-remembered-test-key')
+ await page.getByRole('button', { name: 'Save model' }).click()
await page.getByTestId('app-settings-done').click()
await expect(page.getByTestId('chat-input')).toBeVisible()
@@ -61,7 +102,9 @@ test('remembered browser credentials survive reload and clear centrally', async
await expect(page.getByTestId('chat-input')).toBeVisible()
await page.getByTestId('app-settings-trigger').click()
+ await page.locator('[data-model-id]').first().click()
await page.getByTestId('provider-settings-clear-key').click()
+ await page.getByRole('button', { name: 'Back' }).click()
await page.getByTestId('settings-remember-credentials').click()
await page.getByTestId('app-settings-done').click()
diff --git a/tests/engine/app/ai/model-roles.test.ts b/tests/engine/app/ai/model-roles.test.ts
new file mode 100644
index 000000000..9b8cf255e
--- /dev/null
+++ b/tests/engine/app/ai/model-roles.test.ts
@@ -0,0 +1,139 @@
+import { afterEach, beforeEach, describe, expect, test } from 'bun:test'
+
+import {
+ createAIModelRuntime,
+ createModelProfileDraft,
+ modelSettingsSnapshot,
+ removeModelProfile,
+ replaceAIModelSettings,
+ resolveAIModelRole,
+ saveModelProfileDraft,
+ setModelConnectionAPIKey,
+ setModelRoleAssignment,
+ type AIModelSettings
+} from '@/app/ai/models'
+import { appCredentialRefs } from '@/app/settings/credentials/persistence'
+import { credentialKey } from '@/app/settings/credentials/reference'
+
+let original: AIModelSettings
+
+function settingsFixture(): AIModelSettings {
+ return {
+ version: 1,
+ connections: [
+ {
+ id: 'connection-anthropic',
+ providerID: 'anthropic',
+ customBaseURL: '',
+ customAPIType: 'completions',
+ credentialProfileId: 'anthropic-main'
+ },
+ {
+ id: 'connection-google',
+ providerID: 'google',
+ customBaseURL: '',
+ customAPIType: 'completions',
+ credentialProfileId: 'google-main'
+ }
+ ],
+ models: [
+ {
+ id: 'model-design',
+ name: 'Design model',
+ connectionId: 'connection-anthropic',
+ modelID: 'claude-sonnet-4-6-20260301',
+ customModelID: '',
+ maxOutputTokens: 16_384,
+ capabilities: ['tools', 'vision']
+ },
+ {
+ id: 'model-fast',
+ name: 'Fast model',
+ connectionId: 'connection-google',
+ modelID: 'gemini-3-flash-preview',
+ customModelID: '',
+ maxOutputTokens: 8192,
+ capabilities: ['tools']
+ }
+ ],
+ assignments: {
+ design: 'model-design',
+ review: 'design',
+ fast: 'model-fast',
+ vision: 'design'
+ }
+ }
+}
+
+beforeEach(() => {
+ original = modelSettingsSnapshot()
+ replaceAIModelSettings(settingsFixture())
+})
+
+afterEach(() => {
+ replaceAIModelSettings(original)
+})
+
+describe('AI model profiles and role assignments', () => {
+ test('resolves inherited and independent assignments', () => {
+ expect(resolveAIModelRole('review')).toMatchObject({
+ requestedRole: 'review',
+ profile: { id: 'model-design' },
+ connection: { id: 'connection-anthropic' }
+ })
+ expect(resolveAIModelRole('fast')).toMatchObject({
+ requestedRole: 'fast',
+ profile: { id: 'model-fast' },
+ connection: { id: 'connection-google' }
+ })
+ })
+
+ test('enforces role capability requirements', () => {
+ setModelRoleAssignment('design', 'model-fast')
+ expect(resolveAIModelRole('design')?.profile.id).toBe('model-fast')
+
+ setModelRoleAssignment('vision', 'model-fast')
+ expect(resolveAIModelRole('vision')).toBeNull()
+
+ setModelRoleAssignment('vision', null)
+ expect(resolveAIModelRole('vision')).toBeNull()
+ })
+
+ test('reuses matching provider connections when adding models', () => {
+ const draft = createModelProfileDraft()
+ draft.name = 'Review model'
+ draft.providerID = 'anthropic'
+ draft.modelID = 'claude-opus-4-6-20260301'
+ draft.sourceConnectionId = null
+
+ const profile = saveModelProfileDraft(draft)
+ expect(profile.connectionId).toBe('connection-anthropic')
+ expect(modelSettingsSnapshot().connections).toHaveLength(2)
+ })
+
+ test('repairs assignments when removing a model', () => {
+ removeModelProfile('model-design')
+ const settings = modelSettingsSnapshot()
+ expect(settings.assignments.design).toBe('model-fast')
+ expect(settings.assignments.vision).toBeNull()
+ expect(settings.connections.map((connection) => connection.id)).toEqual(['connection-google'])
+ })
+
+ test('includes configured connection credentials in persistence changes', () => {
+ const keys = appCredentialRefs().map(credentialKey)
+ expect(keys).toContain('v1:anthropic:anthropic-main:api-key')
+ expect(keys).toContain('v1:google:google-main:api-key')
+ })
+
+ test('creates a role runtime without exposing its resolved credential', async () => {
+ await setModelConnectionAPIKey('connection-anthropic', 'review-secret')
+ try {
+ const runtime = await createAIModelRuntime('review')
+ expect(runtime?.kind).toBe('direct')
+ expect(runtime?.role.profile.id).toBe('model-design')
+ expect(runtime).not.toHaveProperty('apiKey')
+ } finally {
+ await setModelConnectionAPIKey('connection-anthropic', '')
+ }
+ })
+})