AI-native design editor. Open-source Figma alternative.
feat(ai): test provider connections
Danila Poyarkov29538005fb84
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 20bd09173..cca3c4136 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -33,6 +33,7 @@### Fixes+- Add AI provider connection testing with clearer setup errors for OpenAI-compatible endpoints.- Increase per-test timeout for slow `gold-preview.fig` fixture tests (`clipboard roundtrip`, `group reclassification`, `glyph blob preservation`, `auto-layout text measurement`, and `render/canvas/cache`) so they no longer flake on slower CI runners.- Fix clone operations (duplicate, instance creation, clipboard copy) sharing mutable references with the original — editing fills, strokes, variable bindings, overrides, or vector networks on one no longer corrupts the other.- Fix instance overrides shallow-copied on clone — override values containing objects are now deep-copied.diff --git a/packages/vue/src/i18n/messages.ts b/packages/vue/src/i18n/messages.tsindex cf4871d14..98252163c 100644--- a/packages/vue/src/i18n/messages.ts+++ b/packages/vue/src/i18n/messages.ts@@ -395,6 +395,23 @@ export const dialogMessages = i18n('dialogs', {clickToFollowPeer: params('Click to follow {name}'),connectAIProvider: 'Connect an AI provider to start chatting.',connect: 'Connect',+ testConnection: 'Test connection',+ testingConnection: 'Testing…',+ connectionTestSuccess: 'Connected successfully. Model is reachable.',+ connectionTestMissingAPIKey: 'Enter an API key before testing.',+ connectionTestMissingBaseURL: 'Enter a base URL before testing.',+ connectionTestMissingModel: 'Enter a model ID before testing.',+ connectionTestInvalidBaseURL:+ 'Base URL is invalid. Use a full URL like https://api.example.com/v1.',+ connectionTestAuthFailed: 'Authentication failed. Check your API key.',+ connectionTestModelNotFound: 'Model not found. Check the model ID.',+ connectionTestAPITypeMismatch:+ 'This endpoint does not appear to support the selected API type. Try Completions or Responses.',+ connectionTestBrowserNetworkFailed:+ 'Could not reach this endpoint from the browser. Try the desktop app or use an endpoint with CORS enabled.',+ connectionTestNetworkFailed:+ 'Could not reach the endpoint. Check the URL and your network connection.',+ connectionTestUnknownFailed: 'Connection test failed. Check the provider settings and try again.',getAPIKey: params('Get an {provider} API key →'),oneKeyManyModels: 'One key for 100+ models from all providers.',describeChange: 'Describe a change…',diff --git a/packages/vue/src/locales/de.json b/packages/vue/src/locales/de.jsonindex 132a179e6..5f980634c 100644--- a/packages/vue/src/locales/de.json+++ b/packages/vue/src/locales/de.json@@ -278,6 +278,19 @@"selectLayerForJSX": "Wähle eine Ebene, um ihren JSX-Code zu sehen","connectAIProvider": "Verbinde einen KI-Anbieter, um den Chat zu starten.","connect": "Verbinden",+ "testConnection": "Test connection",+ "testingConnection": "Testing…",+ "connectionTestSuccess": "Connected successfully. Model is reachable.",+ "connectionTestMissingAPIKey": "Enter an API key before testing.",+ "connectionTestMissingBaseURL": "Enter a base URL before testing.",+ "connectionTestMissingModel": "Enter a model ID before testing.",+ "connectionTestInvalidBaseURL": "Base URL is invalid. Use a full URL like https://api.example.com/v1.",+ "connectionTestAuthFailed": "Authentication failed. Check your API key.",+ "connectionTestModelNotFound": "Model not found. Check the model ID.",+ "connectionTestAPITypeMismatch": "This endpoint does not appear to support the selected API type. Try Completions or Responses.",+ "connectionTestBrowserNetworkFailed": "Could not reach this endpoint from the browser. Try the desktop app or use an endpoint with CORS enabled.",+ "connectionTestNetworkFailed": "Could not reach the endpoint. Check the URL and your network connection.",+ "connectionTestUnknownFailed": "Connection test failed. Check the provider settings and try again.","getAPIKey": "Einen {provider}-API-Schlüssel erhalten →","oneKeyManyModels": "Ein Schlüssel für über 100 Modelle aller Anbieter.","describeChange": "Beschreibe eine Änderung…",diff --git a/packages/vue/src/locales/es.json b/packages/vue/src/locales/es.jsonindex 90ab16272..c8a5c9406 100644--- a/packages/vue/src/locales/es.json+++ b/packages/vue/src/locales/es.json@@ -278,6 +278,19 @@"selectLayerForJSX": "Selecciona una capa para ver su código JSX","connectAIProvider": "Conecta un proveedor de IA para empezar a chatear.","connect": "Conectar",+ "testConnection": "Test connection",+ "testingConnection": "Testing…",+ "connectionTestSuccess": "Connected successfully. Model is reachable.",+ "connectionTestMissingAPIKey": "Enter an API key before testing.",+ "connectionTestMissingBaseURL": "Enter a base URL before testing.",+ "connectionTestMissingModel": "Enter a model ID before testing.",+ "connectionTestInvalidBaseURL": "Base URL is invalid. Use a full URL like https://api.example.com/v1.",+ "connectionTestAuthFailed": "Authentication failed. Check your API key.",+ "connectionTestModelNotFound": "Model not found. Check the model ID.",+ "connectionTestAPITypeMismatch": "This endpoint does not appear to support the selected API type. Try Completions or Responses.",+ "connectionTestBrowserNetworkFailed": "Could not reach this endpoint from the browser. Try the desktop app or use an endpoint with CORS enabled.",+ "connectionTestNetworkFailed": "Could not reach the endpoint. Check the URL and your network connection.",+ "connectionTestUnknownFailed": "Connection test failed. Check the provider settings and try again.","getAPIKey": "Obtener una clave API de {provider} →","oneKeyManyModels": "Una clave para más de 100 modelos de todos los proveedores.","describeChange": "Describe un cambio…",diff --git a/packages/vue/src/locales/fr.json b/packages/vue/src/locales/fr.jsonindex 1fb8e290c..9339ffd7c 100644--- a/packages/vue/src/locales/fr.json+++ b/packages/vue/src/locales/fr.json@@ -278,6 +278,19 @@"selectLayerForJSX": "Sélectionnez un calque pour voir son code JSX","connectAIProvider": "Connectez un fournisseur d’IA pour commencer à discuter.","connect": "Connecter",+ "testConnection": "Test connection",+ "testingConnection": "Testing…",+ "connectionTestSuccess": "Connected successfully. Model is reachable.",+ "connectionTestMissingAPIKey": "Enter an API key before testing.",+ "connectionTestMissingBaseURL": "Enter a base URL before testing.",+ "connectionTestMissingModel": "Enter a model ID before testing.",+ "connectionTestInvalidBaseURL": "Base URL is invalid. Use a full URL like https://api.example.com/v1.",+ "connectionTestAuthFailed": "Authentication failed. Check your API key.",+ "connectionTestModelNotFound": "Model not found. Check the model ID.",+ "connectionTestAPITypeMismatch": "This endpoint does not appear to support the selected API type. Try Completions or Responses.",+ "connectionTestBrowserNetworkFailed": "Could not reach this endpoint from the browser. Try the desktop app or use an endpoint with CORS enabled.",+ "connectionTestNetworkFailed": "Could not reach the endpoint. Check the URL and your network connection.",+ "connectionTestUnknownFailed": "Connection test failed. Check the provider settings and try again.","getAPIKey": "Obtenir une clé API {provider} →","oneKeyManyModels": "Une clé pour plus de 100 modèles de tous les fournisseurs.","describeChange": "Décrivez un changement…",diff --git a/packages/vue/src/locales/it.json b/packages/vue/src/locales/it.jsonindex e68262056..68b26b7f4 100644--- a/packages/vue/src/locales/it.json+++ b/packages/vue/src/locales/it.json@@ -278,6 +278,19 @@"selectLayerForJSX": "Seleziona un livello per vedere il suo codice JSX","connectAIProvider": "Collega un provider AI per iniziare a chattare.","connect": "Connetti",+ "testConnection": "Test connection",+ "testingConnection": "Testing…",+ "connectionTestSuccess": "Connected successfully. Model is reachable.",+ "connectionTestMissingAPIKey": "Enter an API key before testing.",+ "connectionTestMissingBaseURL": "Enter a base URL before testing.",+ "connectionTestMissingModel": "Enter a model ID before testing.",+ "connectionTestInvalidBaseURL": "Base URL is invalid. Use a full URL like https://api.example.com/v1.",+ "connectionTestAuthFailed": "Authentication failed. Check your API key.",+ "connectionTestModelNotFound": "Model not found. Check the model ID.",+ "connectionTestAPITypeMismatch": "This endpoint does not appear to support the selected API type. Try Completions or Responses.",+ "connectionTestBrowserNetworkFailed": "Could not reach this endpoint from the browser. Try the desktop app or use an endpoint with CORS enabled.",+ "connectionTestNetworkFailed": "Could not reach the endpoint. Check the URL and your network connection.",+ "connectionTestUnknownFailed": "Connection test failed. Check the provider settings and try again.","getAPIKey": "Ottieni una chiave API {provider} →","oneKeyManyModels": "Una chiave per oltre 100 modelli di tutti i provider.","describeChange": "Descrivi una modifica…",diff --git a/packages/vue/src/locales/ja.json b/packages/vue/src/locales/ja.jsonindex 51da0161d..175be61ef 100644--- a/packages/vue/src/locales/ja.json+++ b/packages/vue/src/locales/ja.json@@ -278,6 +278,19 @@"selectLayerForJSX": "JSXコードを表示するレイヤーを選択してください","connectAIProvider": "チャットを始めるには、AIプロバイダーを接続してください。","connect": "接続",+ "testConnection": "Test connection",+ "testingConnection": "Testing…",+ "connectionTestSuccess": "Connected successfully. Model is reachable.",+ "connectionTestMissingAPIKey": "Enter an API key before testing.",+ "connectionTestMissingBaseURL": "Enter a base URL before testing.",+ "connectionTestMissingModel": "Enter a model ID before testing.",+ "connectionTestInvalidBaseURL": "Base URL is invalid. Use a full URL like https://api.example.com/v1.",+ "connectionTestAuthFailed": "Authentication failed. Check your API key.",+ "connectionTestModelNotFound": "Model not found. Check the model ID.",+ "connectionTestAPITypeMismatch": "This endpoint does not appear to support the selected API type. Try Completions or Responses.",+ "connectionTestBrowserNetworkFailed": "Could not reach this endpoint from the browser. Try the desktop app or use an endpoint with CORS enabled.",+ "connectionTestNetworkFailed": "Could not reach the endpoint. Check the URL and your network connection.",+ "connectionTestUnknownFailed": "Connection test failed. Check the provider settings and try again.","getAPIKey": "{provider} からAPIキーを取得 →","oneKeyManyModels": "1つのキーで、すべてのプロバイダーの100以上のモデルに対応。","describeChange": "変更内容を入力…",diff --git a/packages/vue/src/locales/pl.json b/packages/vue/src/locales/pl.jsonindex 9837bef4a..ceb73aa95 100644--- a/packages/vue/src/locales/pl.json+++ b/packages/vue/src/locales/pl.json@@ -278,6 +278,19 @@"selectLayerForJSX": "Wybierz warstwę, aby zobaczyć jej kod JSX","connectAIProvider": "Połącz dostawcę AI, aby rozpocząć czat.","connect": "Połącz",+ "testConnection": "Test connection",+ "testingConnection": "Testing…",+ "connectionTestSuccess": "Connected successfully. Model is reachable.",+ "connectionTestMissingAPIKey": "Enter an API key before testing.",+ "connectionTestMissingBaseURL": "Enter a base URL before testing.",+ "connectionTestMissingModel": "Enter a model ID before testing.",+ "connectionTestInvalidBaseURL": "Base URL is invalid. Use a full URL like https://api.example.com/v1.",+ "connectionTestAuthFailed": "Authentication failed. Check your API key.",+ "connectionTestModelNotFound": "Model not found. Check the model ID.",+ "connectionTestAPITypeMismatch": "This endpoint does not appear to support the selected API type. Try Completions or Responses.",+ "connectionTestBrowserNetworkFailed": "Could not reach this endpoint from the browser. Try the desktop app or use an endpoint with CORS enabled.",+ "connectionTestNetworkFailed": "Could not reach the endpoint. Check the URL and your network connection.",+ "connectionTestUnknownFailed": "Connection test failed. Check the provider settings and try again.","getAPIKey": "Pobierz klucz API {provider} →","oneKeyManyModels": "Jeden klucz do ponad 100 modeli od wszystkich dostawców.","describeChange": "Opisz zmianę…",diff --git a/packages/vue/src/locales/ru.json b/packages/vue/src/locales/ru.jsonindex dbd928cf3..eaf428c27 100644--- a/packages/vue/src/locales/ru.json+++ b/packages/vue/src/locales/ru.json@@ -278,6 +278,19 @@"selectLayerForJSX": "Выберите слой, чтобы увидеть его JSX-код","connectAIProvider": "Подключите AI-провайдера, чтобы начать чат.","connect": "Подключить",+ "testConnection": "Test connection",+ "testingConnection": "Testing…",+ "connectionTestSuccess": "Connected successfully. Model is reachable.",+ "connectionTestMissingAPIKey": "Enter an API key before testing.",+ "connectionTestMissingBaseURL": "Enter a base URL before testing.",+ "connectionTestMissingModel": "Enter a model ID before testing.",+ "connectionTestInvalidBaseURL": "Base URL is invalid. Use a full URL like https://api.example.com/v1.",+ "connectionTestAuthFailed": "Authentication failed. Check your API key.",+ "connectionTestModelNotFound": "Model not found. Check the model ID.",+ "connectionTestAPITypeMismatch": "This endpoint does not appear to support the selected API type. Try Completions or Responses.",+ "connectionTestBrowserNetworkFailed": "Could not reach this endpoint from the browser. Try the desktop app or use an endpoint with CORS enabled.",+ "connectionTestNetworkFailed": "Could not reach the endpoint. Check the URL and your network connection.",+ "connectionTestUnknownFailed": "Connection test failed. Check the provider settings and try again.","getAPIKey": "Получить API-ключ {provider} →","oneKeyManyModels": "Один ключ для 100+ моделей от разных провайдеров.","describeChange": "Опишите изменение…",diff --git a/packages/vue/src/locales/zh-CN.json b/packages/vue/src/locales/zh-CN.jsonindex 47540b66e..828ab4e72 100644--- a/packages/vue/src/locales/zh-CN.json+++ b/packages/vue/src/locales/zh-CN.json@@ -278,6 +278,19 @@"selectLayerForJSX": "选择一个图层以查看其 JSX 代码","connectAIProvider": "连接 AI 提供商以开始聊天。","connect": "连接",+ "testConnection": "Test connection",+ "testingConnection": "Testing…",+ "connectionTestSuccess": "Connected successfully. Model is reachable.",+ "connectionTestMissingAPIKey": "Enter an API key before testing.",+ "connectionTestMissingBaseURL": "Enter a base URL before testing.",+ "connectionTestMissingModel": "Enter a model ID before testing.",+ "connectionTestInvalidBaseURL": "Base URL is invalid. Use a full URL like https://api.example.com/v1.",+ "connectionTestAuthFailed": "Authentication failed. Check your API key.",+ "connectionTestModelNotFound": "Model not found. Check the model ID.",+ "connectionTestAPITypeMismatch": "This endpoint does not appear to support the selected API type. Try Completions or Responses.",+ "connectionTestBrowserNetworkFailed": "Could not reach this endpoint from the browser. Try the desktop app or use an endpoint with CORS enabled.",+ "connectionTestNetworkFailed": "Could not reach the endpoint. Check the URL and your network connection.",+ "connectionTestUnknownFailed": "Connection test failed. Check the provider settings and try again.","getAPIKey": "获取 {provider} API 密钥 →","oneKeyManyModels": "一个密钥即可使用来自所有提供商的 100+ 模型。","describeChange": "描述一个更改…",diff --git a/src/app/ai/chat/connection-test.ts b/src/app/ai/chat/connection-test.tsnew file mode 100644index 000000000..66fa5f696--- /dev/null+++ b/src/app/ai/chat/connection-test.ts@@ -0,0 +1,137 @@+import { generateText } from 'ai'++import { createLanguageModel, resolveLanguageModelID, type ModelConfig } from '@/app/ai/chat/model'+import { isTauri } from '@/app/tauri/env'++export type ProviderConnectionTestResult =+ | { ok: true }+ | { ok: false; reason: ProviderConnectionTestFailureReason }++export type ProviderConnectionTestFailureReason =+ | 'missing-api-key'+ | 'missing-base-url'+ | 'missing-model'+ | 'invalid-base-url'+ | 'auth'+ | 'model-not-found'+ | 'api-type'+ | 'browser-network'+ | 'network'+ | 'unknown'++function isCompatibleProvider(providerID: ModelConfig['providerID']): boolean {+ return providerID === 'openai-compatible' || providerID === 'anthropic-compatible'+}++function validateConfig(config: ModelConfig): ProviderConnectionTestFailureReason | null {+ if (!config.apiKey.trim()) return 'missing-api-key'+ if (isCompatibleProvider(config.providerID)) {+ if (!config.customBaseURL.trim()) return 'missing-base-url'+ try {+ const url = new URL(config.customBaseURL.trim())+ if (url.protocol !== 'http:' && url.protocol !== 'https:') return 'invalid-base-url'+ } catch {+ return 'invalid-base-url'+ }+ }+ if (!resolveLanguageModelID(config).trim()) return 'missing-model'+ return null+}++type ProviderErrorShape = {+ statusCode?: unknown+ status?: unknown+ responseStatusCode?: unknown+ responseStatus?: unknown+ code?: unknown+ response?: { status?: unknown }+}++function isProviderErrorShape(error: unknown): error is ProviderErrorShape {+ return typeof error === 'object' && error !== null+}++function statusNumber(value: unknown): number | null {+ if (typeof value === 'number') return value+ if (typeof value === 'string' && /^\d+$/.test(value)) return Number(value)+ return null+}++function errorStatus(error: unknown): number | null {+ if (!isProviderErrorShape(error)) return null+ return (+ statusNumber(error.statusCode) ??+ statusNumber(error.status) ??+ statusNumber(error.responseStatusCode) ??+ statusNumber(error.responseStatus) ??+ statusNumber(error.code) ??+ statusNumber(error.response?.status)+ )+}++function errorText(error: unknown): string {+ if (error instanceof Error) return `${error.name}: ${error.message}`+ return String(error)+}++function classifyStatus(+ status: number | null,+ text: string+): ProviderConnectionTestFailureReason | null {+ if (status === 401 || status === 403) return 'auth'+ if (status === 404) return 'model-not-found'+ if (status !== 400 && status !== 405) return null+ if (text.includes('model')) return 'model-not-found'+ if (text.includes('responses') || text.includes('chat') || text.includes('endpoint')) {+ return 'api-type'+ }+ return null+}++function classifyMessage(text: string): ProviderConnectionTestFailureReason | null {+ if (+ text.includes('api key') ||+ text.includes('authentication') ||+ text.includes('unauthorized')+ ) {+ return 'auth'+ }+ if (text.includes('model') && (text.includes('not found') || text.includes('does not exist'))) {+ return 'model-not-found'+ }+ if (+ text.includes('failed to fetch') ||+ text.includes('networkerror') ||+ text.includes('load failed')+ ) {+ return isTauri() ? 'network' : 'browser-network'+ }+ if (text.includes('connection') || text.includes('network') || text.includes('timeout')) {+ return 'network'+ }+ return null+}++function classifyError(error: unknown): ProviderConnectionTestFailureReason {+ const text = errorText(error).toLowerCase()+ return classifyStatus(errorStatus(error), text) ?? classifyMessage(text) ?? 'unknown'+}++export async function testProviderConnection(+ config: ModelConfig+): Promise<ProviderConnectionTestResult> {+ const invalidReason = validateConfig(config)+ if (invalidReason) return { ok: false, reason: invalidReason }++ try {+ await generateText({+ model: createLanguageModel(config),+ prompt: 'Reply with OK.',+ maxOutputTokens: 1,+ abortSignal: AbortSignal.timeout(15_000)+ })+ return { ok: true }+ } catch (error) {+ return { ok: false, reason: classifyError(error) }+ }+}diff --git a/src/components/chat/ProviderConnectionTestButton.vue b/src/components/chat/ProviderConnectionTestButton.vuenew file mode 100644index 000000000..3d9f78828--- /dev/null+++ b/src/components/chat/ProviderConnectionTestButton.vue@@ -0,0 +1,73 @@+<script setup lang="ts">+import { computed } from 'vue'+import { useI18n } from '@open-pencil/vue'++import type { ProviderConnectionTestFailureReason } from '@/app/ai/chat/connection-test'++interface ProviderConnectionTestButtonProps {+ status: 'idle' | 'testing' | 'success' | 'error'+ reason?: ProviderConnectionTestFailureReason | null+ disabled?: boolean+}++const { status, reason, disabled = false } = defineProps<ProviderConnectionTestButtonProps>()+const emit = defineEmits<{ test: [] }>()+const { dialogs } = useI18n()++const resultMessage = computed(() => {+ if (status === 'success') return dialogs.value.connectionTestSuccess+ if (status !== 'error') return null++ switch (reason) {+ case 'missing-api-key':+ return dialogs.value.connectionTestMissingAPIKey+ case 'missing-base-url':+ return dialogs.value.connectionTestMissingBaseURL+ case 'missing-model':+ return dialogs.value.connectionTestMissingModel+ case 'invalid-base-url':+ return dialogs.value.connectionTestInvalidBaseURL+ case 'auth':+ return dialogs.value.connectionTestAuthFailed+ case 'model-not-found':+ return dialogs.value.connectionTestModelNotFound+ case 'api-type':+ return dialogs.value.connectionTestAPITypeMismatch+ case 'browser-network':+ return dialogs.value.connectionTestBrowserNetworkFailed+ case 'network':+ return dialogs.value.connectionTestNetworkFailed+ default:+ return dialogs.value.connectionTestUnknownFailed+ }+})++const isTesting = computed(() => status === 'testing')+</script>++<template>+ <div class="flex flex-col gap-1">+ <button+ type="button"+ data-test-id="provider-test-connection"+ class="rounded border border-panel bg-panel px-2 py-1 text-[11px] font-medium text-surface hover:bg-hover disabled:cursor-not-allowed disabled:opacity-50"+ :disabled="isTesting || disabled"+ @click="emit('test')"+ >+ <span class="inline-flex items-center justify-center gap-1.5">+ <icon-lucide-loader-2 v-if="isTesting" class="size-3 animate-spin" />+ <icon-lucide-plug-zap v-else class="size-3" />+ {{ isTesting ? dialogs.testingConnection : dialogs.testConnection }}+ </span>+ </button>++ <p+ v-if="resultMessage"+ class="text-[10px] leading-snug"+ :class="status === 'success' ? 'text-green-400' : 'text-red-400'"+ data-test-id="provider-test-connection-result"+ >+ {{ resultMessage }}+ </p>+ </div>+</template>diff --git a/src/components/chat/ProviderSettings/ProviderSettings.vue b/src/components/chat/ProviderSettings/ProviderSettings.vueindex 335ced09c..f066fab33 100644--- a/src/components/chat/ProviderSettings/ProviderSettings.vue+++ b/src/components/chat/ProviderSettings/ProviderSettings.vue@@ -9,6 +9,7 @@ import CustomEndpointSection from '@/components/chat/ProviderSettings/CustomEndpimport MaxTokensSection from '@/components/chat/ProviderSettings/MaxTokensSection.vue'import ProviderSelectField from '@/components/chat/ProviderSelect/ProviderSelectField.vue'import StockPhotoKeysSection from '@/components/chat/ProviderSettings/StockPhotoKeysSection.vue'+import TestConnectionSection from '@/components/chat/ProviderSettings/TestConnectionSection.vue'import { provideProviderSettings } from '@/components/chat/ProviderSettings/context'import { usePopoverUI } from '@/components/ui/popover'import Tip from '@/components/ui/Tip.vue'@@ -59,6 +60,7 @@ function onInteractOutside(e: Event) {<CustomEndpointSection /><ApiTypeSection /><ApiKeySection />+ <TestConnectionSection /><PopoverCloseclass="mt-1 w-full rounded bg-accent px-2 py-1 text-center text-[11px] font-medium text-white hover:bg-accent/90"diff --git a/src/components/chat/ProviderSettings/TestConnectionSection.vue b/src/components/chat/ProviderSettings/TestConnectionSection.vuenew file mode 100644index 000000000..128cda758--- /dev/null+++ b/src/components/chat/ProviderSettings/TestConnectionSection.vue@@ -0,0 +1,16 @@+<script setup lang="ts">+import ProviderConnectionTestButton from '@/components/chat/ProviderConnectionTestButton.vue'+import { useProviderSettingsContext } from '@/components/chat/ProviderSettings/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/chat/ProviderSettings/context.ts b/src/components/chat/ProviderSettings/context.tsindex fa1d97e9b..29bbc00fc 100644--- a/src/components/chat/ProviderSettings/context.ts+++ b/src/components/chat/ProviderSettings/context.ts@@ -1,6 +1,10 @@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() {@@ -11,6 +15,7 @@ function createProviderSettingsContext() {setAPIKey,customBaseURL,customModelID,+ modelID,customAPIType,maxOutputTokens,pexelsApiKey,@@ -26,14 +31,33 @@ function createProviderSettingsContext() {const hasExistingKey = ref(!!apiKey.value)const hasExistingPexelsKey = ref(!!pexelsApiKey.value)const hasExistingUnsplashKey = ref(!!unsplashAccessKey.value)+ const connectionTestStatus = ref<'idle' | 'testing' | 'success' | 'error'>('idle')+ const connectionTestReason = ref<ProviderConnectionTestFailureReason | null>(null)++ const effectiveAPIKey = computed(() => keyInput.value.trim() || apiKey.value)+ const canTestConnection = computed(() => {+ if (isACP.value) return false+ if (!effectiveAPIKey.value.trim()) 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 = !!apiKey.valuebaseURLInput.value = customBaseURL.valuecustomModelInput.value = customModelID.value+ resetConnectionTest()})+ watch([keyInput, baseURLInput, customModelInput, customAPIType], resetConnectionTest)+function save() {if (keyInput.value.trim()) {setAPIKey(keyInput.value.trim())@@ -81,10 +105,39 @@ function createProviderSettingsContext() {save()}+ async function testConnection() {+ if (connectionTestStatus.value === 'testing') return+ connectionTestStatus.value = 'testing'+ connectionTestReason.value = null++ const result = await testProviderConnection({+ providerID: providerID.value,+ apiKey: effectiveAPIKey.value,+ 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,apiKey,+ modelID,customAPIType,customBaseURL,customModelID,@@ -100,11 +153,15 @@ function createProviderSettingsContext() {hasExistingKey,hasExistingPexelsKey,hasExistingUnsplashKey,+ connectionTestStatus,+ connectionTestReason,+ canTestConnection,save,clearKey,clearPexelsKey,clearUnsplashKey,- setCustomAPIType+ setCustomAPIType,+ testConnection}}diff --git a/src/components/chat/ProviderSetup.vue b/src/components/chat/ProviderSetup.vueindex db2e82b0d..fe5d3bfe3 100644--- a/src/components/chat/ProviderSetup.vue+++ b/src/components/chat/ProviderSetup.vue@@ -1,6 +1,11 @@<script setup lang="ts">-import { computed, ref } from 'vue'+import { computed, ref, watch } from 'vue'+import {+ testProviderConnection,+ type ProviderConnectionTestFailureReason+} from '@/app/ai/chat/connection-test'+import ProviderConnectionTestButton from '@/components/chat/ProviderConnectionTestButton.vue'import ProviderSelectField from '@/components/chat/ProviderSelect/ProviderSelectField.vue'import AppInput from '@/components/ui/AppInput.vue'import AppTextButton from '@/components/ui/AppTextButton.vue'@@ -9,7 +14,8 @@ import { ACP_AGENTS } from '@open-pencil/core/constants'import { openExternalLink } from '@/app/shell/ui'import { useI18n } from '@open-pencil/vue'-const { providerID, providerDef, setAPIKey, customBaseURL, customModelID } = useAIChat()+const { providerID, providerDef, setAPIKey, modelID, customBaseURL, customModelID, customAPIType } =+ useAIChat()const { dialogs } = useI18n()const isACP = computed(() => providerID.value.startsWith('acp:'))@@ -22,6 +28,57 @@ const acpAgent = computed(() => {const keyInput = ref('')const baseURLInput = ref(customBaseURL.value)const customModelInput = ref(customModelID.value)+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()) return false+ if (providerDef.value.supportsCustomBaseURL && !baseURLInput.value.trim()) return false+ if (+ providerDef.value.supportsCustomModel &&+ providerID.value !== 'openrouter' &&+ !customModelInput.value.trim()+ ) {+ return false+ }+ return true+})++function resetConnectionTest() {+ connectionTestStatus.value = 'idle'+ connectionTestReason.value = null+}++watch([providerID, keyInput, baseURLInput, customModelInput, customAPIType], resetConnectionTest)++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(),+ 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+}function save() {const key = keyInput.value.trim()@@ -68,6 +125,13 @@ function save() {:placeholder="providerDef.keyPlaceholder"/>+ <ProviderConnectionTestButton+ :status="connectionTestStatus"+ :reason="connectionTestReason"+ :disabled="!canTestConnection"+ @test="testConnection"+ />+<buttontype="submit"data-test-id="api-key-save"