Skip to content

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

refactor(settings): extract model profile workflows

Danila Poyarkov904c90c3299a
diff --git a/AGENTS.md b/AGENTS.md
index cb4d600dc..632deeca3 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -22,6 +22,10 @@ Bun workspace packages:
The root Tauri/Vite app lives in `src/`; app services and state belong under `src/app/**`, views under `src/views/**`, and app UI under `src/components/**`.
+### Settings UI ownership
+
+Settings components own layout, translated copy, confirmation visibility, and emits. Reactive settings workflows live under the owning app domain's `settings/` folder (for example `src/app/ai/models/settings/profile-editor/{use,selection,connection}.ts`), not a global composables bucket. Use `use.ts` for orchestration and focused sibling modules for substantial sub-workflows. Keep persistence and external operations in domain services, and pure option projections as ordinary functions. Return operation outcomes rather than importing dialogs, routers, or toast UI into workflow composables. Keep newly entered secrets short-lived, never expose saved secrets, and guard async results against changed targets. Small presentation-only computed bindings can remain in components.
+
### Public package exports
Across package/app boundaries, import the owning package's public exports—never workspace internals or forwarding-only shims. `@open-pencil/scene-graph` owns graph types and primitives; `@open-pencil/kiwi` owns low-level Kiwi/FIG helpers; `@open-pencil/core` provides the compatibility barrel plus targeted subpaths listed in `packages/core/package.json`.
diff --git a/packages/core/src/constants.ts b/packages/core/src/constants.ts
index a2fe7e442..c47f574d1 100644
--- a/packages/core/src/constants.ts
+++ b/packages/core/src/constants.ts
@@ -312,10 +312,10 @@ export const AI_PROVIDERS: AIProviderDef[] = [
keyURL: 'https://platform.openai.com/api-keys',
defaultModel: 'gpt-5.6',
models: [
- { id: 'gpt-5.6', name: 'GPT-5.6', tag: 'Best' },
- { id: 'gpt-5.5', name: 'GPT-5.5' },
- { id: 'gpt-5.4-mini', name: 'GPT-5.4 mini', tag: 'Fast' },
- { id: 'gpt-5.4-nano', name: 'GPT-5.4 nano', tag: 'Cheap' }
+ { id: 'gpt-5.6', name: 'GPT-5.6', tag: 'Best', capabilities: ['tools', 'vision'] },
+ { id: 'gpt-5.5', name: 'GPT-5.5', capabilities: ['tools', 'vision'] },
+ { id: 'gpt-5.4-mini', name: 'GPT-5.4 mini', tag: 'Fast', capabilities: ['tools', 'vision'] },
+ { id: 'gpt-5.4-nano', name: 'GPT-5.4 nano', tag: 'Cheap', capabilities: ['tools', 'vision'] }
]
},
{
@@ -367,7 +367,12 @@ export const AI_PROVIDERS: AIProviderDef[] = [
{ id: 'glm-5.3', name: 'GLM-5.3', tag: 'Best' },
{ id: 'glm-5.3-flash', name: 'GLM-5.3-Flash', tag: 'Fast' },
{ id: 'glm-5.2', name: 'GLM-5.2' },
- { id: 'glm-5v-turbo', name: 'GLM-5V-Turbo', tag: 'Vision' },
+ {
+ id: 'glm-5v-turbo',
+ name: 'GLM-5V-Turbo',
+ tag: 'Vision',
+ capabilities: ['tools', 'vision']
+ },
{ id: 'glm-5.1', name: 'GLM-5.1' },
{ id: 'glm-5', name: 'GLM-5' },
{ id: 'glm-5-code', name: 'GLM-5-Code' },
diff --git a/src/app/ai/models/catalog.ts b/src/app/ai/models/catalog.ts
index ac5db879f..8f58c27be 100644
--- a/src/app/ai/models/catalog.ts
+++ b/src/app/ai/models/catalog.ts
@@ -86,9 +86,16 @@ async function resolvedCatalog(fetcher?: typeof fetch): Promise<ModelsDevCatalog
const resolvedFetcher = fetcher ?? nativeFetch
if (!resolvedFetcher) return null
const useCache = resolvedFetcher === nativeFetch
- return useCache
- ? (catalogPromise ??= loadCatalog(resolvedFetcher, { useCache: true }))
- : loadCatalog(resolvedFetcher, { useCache: false })
+ if (!useCache) return loadCatalog(resolvedFetcher, { useCache: false })
+ const pending = (catalogPromise ??= loadCatalog(resolvedFetcher, { useCache: true }))
+ try {
+ const catalog = await pending
+ if (!catalog && catalogPromise === pending) catalogPromise = null
+ return catalog
+ } catch {
+ if (catalogPromise === pending) catalogPromise = null
+ return null
+ }
}
function modelIDCandidates(providerKey: string, modelID: string): string[] {
@@ -112,7 +119,7 @@ function curatedProviderModels(providerID: AIProviderID): ModelOption[] {
function supportsDesignWork(model: ModelsDevModel): boolean {
if (model.tool_call !== true || model.status === 'deprecated') return false
const outputModalities = model.modalities?.output
- return !Array.isArray(outputModalities) || outputModalities.includes('text')
+ return Array.isArray(outputModalities) && outputModalities.includes('text')
}
function mergeCuratedModels(curated: ModelOption[], catalog: ModelOption[]): ModelOption[] {
diff --git a/src/app/ai/models/picker/options.ts b/src/app/ai/models/picker/options.ts
new file mode 100644
index 000000000..172a763aa
--- /dev/null
+++ b/src/app/ai/models/picker/options.ts
@@ -0,0 +1,36 @@
+import type { ModelOption } from '@open-pencil/core/constants'
+
+export interface ModelPickerLabels {
+ recommendedModels: string
+ latestModels: string
+ allModels: string
+ latest: string
+}
+
+const LATEST_MODEL_COUNT = 8
+
+export function modelPickerOptions(
+ models: readonly ModelOption[],
+ recommendations: readonly ModelOption[],
+ labels: ModelPickerLabels
+) {
+ const recommendedIds = new Set(recommendations.map((model) => model.id))
+ const latestIds = new Set(
+ models
+ .filter((model) => !recommendedIds.has(model.id) && model.releaseDate)
+ .slice(0, LATEST_MODEL_COUNT)
+ .map((model) => model.id)
+ )
+ return models.map((model) => {
+ let group = labels.allModels
+ if (recommendedIds.has(model.id)) group = labels.recommendedModels
+ else if (latestIds.has(model.id)) group = labels.latestModels
+ return {
+ value: model.id,
+ label: model.name,
+ description: model.id,
+ meta: model.tag ?? (latestIds.has(model.id) ? labels.latest : undefined),
+ group
+ }
+ })
+}
diff --git a/src/app/ai/models/settings/profile-editor/connection.ts b/src/app/ai/models/settings/profile-editor/connection.ts
new file mode 100644
index 000000000..99d6bb0ca
--- /dev/null
+++ b/src/app/ai/models/settings/profile-editor/connection.ts
@@ -0,0 +1,93 @@
+import { computed, ref, type Ref } from 'vue'
+
+import type { AIProviderDef } from '@open-pencil/core/constants'
+
+import {
+ testProviderConnection,
+ type ProviderConnectionTestFailureReason
+} from '@/app/ai/chat/connection-test'
+import { refreshAIProviderStatus } from '@/app/ai/chat/storage'
+import {
+ findModelConnectionForDraft,
+ modelConnectionCredentialStatus,
+ resolveModelConnectionAPIKey,
+ setModelConnectionAPIKey,
+ type AIModelProfileDraft
+} from '@/app/ai/models'
+import type { CredentialStatus } from '@/app/settings/credentials/types'
+interface ConnectionOptions {
+ draft: AIModelProfileDraft
+ keyInput: Ref<string>
+ providerDef: Readonly<Ref<AIProviderDef>>
+ isACP: Readonly<Ref<boolean>>
+ isHarness: Readonly<Ref<boolean>>
+ customModelSelected: Ref<boolean>
+}
+export function useProfileConnection({
+ draft,
+ keyInput,
+ providerDef,
+ isACP,
+ isHarness,
+ customModelSelected
+}: ConnectionOptions) {
+ const keyStatus = ref<CredentialStatus>('missing')
+ const connectionTestStatus = ref<'idle' | 'testing' | 'success' | 'error'>('idle')
+ const connectionTestReason = ref<ProviderConnectionTestFailureReason | null>(null)
+ const hasExistingKey = computed(() => keyStatus.value === 'configured')
+ const canTest = computed(() => {
+ if (isACP.value || isHarness.value) return false
+ if (!keyInput.value.trim() && !hasExistingKey.value) return false
+ if (providerDef.value.supportsCustomBaseURL && !draft.customBaseURL.trim()) return false
+ return customModelSelected.value
+ ? Boolean(draft.customModelID.trim())
+ : Boolean(draft.modelID.trim())
+ })
+ 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'
+ }
+ 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
+ }
+ return {
+ keyStatus,
+ connectionTestStatus,
+ connectionTestReason,
+ hasExistingKey,
+ canTest,
+ resetConnectionTest,
+ refreshKeyStatus,
+ clearKey,
+ testConnection
+ }
+}
diff --git a/src/app/ai/models/settings/profile-editor/selection.ts b/src/app/ai/models/settings/profile-editor/selection.ts
new file mode 100644
index 000000000..02df5625c
--- /dev/null
+++ b/src/app/ai/models/settings/profile-editor/selection.ts
@@ -0,0 +1,170 @@
+import { computed, ref, watch, type Ref } from 'vue'
+
+import {
+ ACP_AGENTS,
+ AI_PROVIDERS,
+ type AIProviderID,
+ type ModelOption
+} from '@open-pencil/core/constants'
+
+import type { AIModelProfileDraft, AIModelCapability } from '@/app/ai/models'
+import { resolveModelsDevModel } from '@/app/ai/models/catalog'
+import { modelPickerOptions, type ModelPickerLabels } from '@/app/ai/models/picker/options'
+import { useProviderModelCatalog } from '@/app/ai/models/use-provider-model-catalog'
+export function useProfileModelSelection(
+ draft: AIModelProfileDraft,
+ ai: Readonly<Ref<ModelPickerLabels & { customModel: string }>>
+) {
+ const CUSTOM_MODEL_VALUE = '__custom__'
+ const DEFAULT_MAX_OUTPUT_TOKENS = 16384
+ const customModelSelected = ref(
+ Boolean(draft.customModelID.trim()) || draft.providerID === 'harness:pi'
+ )
+ const catalogModel = ref<ModelOption | null>(null)
+ const providerDef = computed(
+ () => AI_PROVIDERS.find((provider) => provider.id === draft.providerID) ?? AI_PROVIDERS[0]
+ )
+ const catalogProviderID = computed(() => draft.providerID)
+ const fallbackModels = computed(() => providerDef.value.models)
+ const { models: availableModels } = useProviderModelCatalog(catalogProviderID, fallbackModels)
+ const isACP = computed(() => draft.providerID.startsWith('acp:'))
+ const isHarness = computed(() => draft.providerID === 'harness:pi')
+ const supportsReasoningEffort = computed(() =>
+ ['openai', 'openai-compatible', 'openrouter'].includes(draft.providerID)
+ )
+ const providerDisplayName = computed(() => {
+ if (!isACP.value) return providerDef.value.name
+ const agentID = draft.providerID.slice('acp:'.length)
+ return ACP_AGENTS.find((agent) => agent.id === agentID)?.name ?? draft.providerID
+ })
+ const modelOptions = computed(() => {
+ const options = modelPickerOptions(availableModels.value, providerDef.value.models, ai.value)
+ if (providerDef.value.supportsCustomModel) {
+ options.push({
+ value: CUSTOM_MODEL_VALUE,
+ label: ai.value.customModel,
+ description: '',
+ meta: undefined,
+ group: ai.value.customModel
+ })
+ }
+ return options
+ })
+ const selectedModelValue = computed(() =>
+ customModelSelected.value ? CUSTOM_MODEL_VALUE : draft.modelID
+ )
+ const knownModel = computed(() => {
+ if (isACP.value) return null
+ if (draft.customModelID.trim()) return catalogModel.value
+ return (
+ catalogModel.value ??
+ availableModels.value.find((model) => model.id === draft.modelID) ??
+ null
+ )
+ })
+ const knownCapabilities = computed<AIModelCapability[]>(() => [
+ ...(knownModel.value?.capabilities ?? ['tools'])
+ ])
+ const outputTokenRecommendation = computed(
+ () => knownModel.value?.recommendedMaxOutputTokens ?? DEFAULT_MAX_OUTPUT_TOKENS
+ )
+ const modelDisplayName = computed(() => {
+ const modelId = draft.customModelID.trim() || draft.modelID
+ return availableModels.value.find((model) => model.id === modelId)?.name || modelId
+ })
+ const toolsEnabled = capabilityModel('tools')
+ const visionEnabled = capabilityModel('vision')
+ 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 effectiveModelID(): string {
+ return customModelSelected.value ? draft.customModelID.trim() : draft.modelID.trim()
+ }
+ async function refreshCatalogModel(): Promise<void> {
+ if (isACP.value) {
+ catalogModel.value = null
+ return
+ }
+ const providerID = draft.providerID
+ const modelID = effectiveModelID()
+ const resolved = await resolveModelsDevModel(providerID, modelID)
+ if (providerID !== draft.providerID || modelID !== effectiveModelID()) return
+ catalogModel.value = resolved
+ applyKnownModelMetadata()
+ }
+ function applyKnownModelMetadata(): void {
+ if (!knownModel.value) return
+ draft.capabilities = [...knownCapabilities.value]
+ draft.maxOutputTokens = outputTokenRecommendation.value
+ }
+ function updateProvider(providerID: AIProviderID): void {
+ catalogModel.value = null
+ draft.providerID = providerID
+ draft.sourceConnectionId = null
+ const provider = AI_PROVIDERS.find((definition) => definition.id === providerID)
+ draft.modelID = provider?.defaultModel ?? ''
+ catalogModel.value = provider?.models.find((model) => model.id === draft.modelID) ?? null
+ draft.customModelID = ''
+ customModelSelected.value = providerID === 'harness:pi'
+ draft.customBaseURL = ''
+ draft.customAPIType = 'completions'
+ if (providerID.startsWith('acp:')) {
+ draft.capabilities = ['tools']
+ if (!draft.name.trim()) draft.name = providerDisplayName.value
+ } else {
+ applyKnownModelMetadata()
+ }
+
+ void refreshCatalogModel()
+ }
+ function updateModel(modelID: string): void {
+ if (modelID === CUSTOM_MODEL_VALUE) {
+ customModelSelected.value = true
+ draft.customModelID = ''
+ catalogModel.value = null
+
+ return
+ }
+ draft.modelID = modelID
+ catalogModel.value = availableModels.value.find((model) => model.id === modelID) ?? null
+ customModelSelected.value = false
+ draft.customModelID = ''
+ applyKnownModelMetadata()
+ void refreshCatalogModel()
+ if (!draft.name.trim()) draft.name = modelDisplayName.value
+ }
+ watch(
+ () => draft.customModelID,
+ () => {
+ if (customModelSelected.value) void refreshCatalogModel()
+ }
+ )
+ void refreshCatalogModel()
+ return {
+ providerDef,
+ isACP,
+ isHarness,
+ customModelSelected,
+ supportsReasoningEffort,
+ providerDisplayName,
+ modelOptions,
+ selectedModelValue,
+ knownModel,
+ knownCapabilities,
+ outputTokenRecommendation,
+ modelDisplayName,
+ toolsEnabled,
+ visionEnabled,
+ applyKnownModelMetadata,
+ updateProvider,
+ updateModel
+ }
+}
diff --git a/src/app/ai/models/settings/profile-editor/use.ts b/src/app/ai/models/settings/profile-editor/use.ts
new file mode 100644
index 000000000..832b2ba66
--- /dev/null
+++ b/src/app/ai/models/settings/profile-editor/use.ts
@@ -0,0 +1,139 @@
+import { computed, reactive, ref, watch } from 'vue'
+import type { Ref } from 'vue'
+
+import type { AIProviderID } from '@open-pencil/core/constants'
+
+import { refreshAIProviderStatus } from '@/app/ai/chat/storage'
+import {
+ aiModelSettings,
+ createModelProfileDraft,
+ modelConnectionUsageCount,
+ modelProfile,
+ removeModelProfile,
+ saveModelProfileDraft,
+ setModelConnectionAPIKey
+} from '@/app/ai/models'
+import type { ModelPickerLabels } from '@/app/ai/models/picker/options'
+
+import { useProfileConnection } from './connection'
+import { useProfileModelSelection } from './selection'
+
+interface ProfileEditorOptions {
+ profileId?: string
+ keyInput: Ref<string>
+ labels: Readonly<Ref<ModelPickerLabels & { customModel: string }>>
+}
+
+export function useModelProfileEditor({ profileId, keyInput, labels: ai }: ProfileEditorOptions) {
+ const draft = reactive(createModelProfileDraft(profileId))
+ const selection = useProfileModelSelection(draft, ai)
+ const {
+ providerDef,
+ isACP,
+ isHarness,
+ customModelSelected,
+ supportsReasoningEffort,
+ providerDisplayName,
+ modelOptions,
+ selectedModelValue,
+ knownModel,
+ knownCapabilities,
+ outputTokenRecommendation,
+ modelDisplayName,
+ toolsEnabled,
+ visionEnabled,
+ applyKnownModelMetadata
+ } = selection
+ const saveError = ref<string | null>(null)
+ const {
+ connectionTestStatus,
+ connectionTestReason,
+ hasExistingKey,
+ canTest,
+ resetConnectionTest,
+ refreshKeyStatus,
+ clearKey,
+ testConnection
+ } = useProfileConnection({ draft, keyInput, providerDef, isACP, isHarness, customModelSelected })
+ const canDelete = computed(() => Boolean(profileId) && aiModelSettings.value.models.length > 1)
+ const canSave = computed(
+ () =>
+ Boolean(draft.name.trim()) &&
+ (isACP.value ||
+ (customModelSelected.value
+ ? Boolean(draft.customModelID.trim())
+ : Boolean(draft.modelID.trim())))
+ )
+ function updateProvider(id: AIProviderID) {
+ selection.updateProvider(id)
+ keyInput.value = ''
+ resetConnectionTest()
+ void refreshKeyStatus()
+ }
+ function updateModel(id: string) {
+ selection.updateModel(id)
+ resetConnectionTest()
+ }
+ async function save(): Promise<boolean> {
+ saveError.value = null
+ try {
+ applyKnownModelMetadata()
+ if (!draft.name.trim()) draft.name = modelDisplayName.value || providerDisplayName.value
+ const profile = saveModelProfileDraft(draft)
+ if (keyInput.value.trim()) {
+ await setModelConnectionAPIKey(profile.connectionId, keyInput.value)
+ await refreshAIProviderStatus()
+ keyInput.value = ''
+ }
+ return true
+ } catch (reason) {
+ saveError.value = reason instanceof Error ? reason.message : String(reason)
+ return false
+ }
+ }
+ async function remove(): Promise<boolean> {
+ if (!profileId) return false
+ const profile = modelProfile(profileId)
+ if (profile && modelConnectionUsageCount(profile.connectionId) === 1) {
+ await setModelConnectionAPIKey(profile.connectionId, '')
+ }
+ removeModelProfile(profileId)
+ await refreshAIProviderStatus()
+
+ return true
+ }
+ watch(
+ () => [draft.customBaseURL, draft.customModelID, draft.customAPIType, draft.modelID],
+ resetConnectionTest
+ )
+ void refreshKeyStatus()
+ return {
+ draft,
+ providerDef,
+ isACP,
+ isHarness,
+ supportsReasoningEffort,
+ providerDisplayName,
+ modelOptions,
+ selectedModelValue,
+ knownModel,
+ knownCapabilities,
+ outputTokenRecommendation,
+ modelDisplayName,
+ hasExistingKey,
+ canDelete,
+ toolsEnabled,
+ visionEnabled,
+ canSave,
+ canTest,
+ connectionTestStatus,
+ connectionTestReason,
+ saveError,
+ updateProvider,
+ updateModel,
+ save,
+ clearKey,
+ testConnection,
+ remove
+ }
+}
diff --git a/src/components/chat/ProviderModelSelect.vue b/src/components/chat/ProviderModelSelect.vue
index 6956c4c37..984469ab8 100644
--- a/src/components/chat/ProviderModelSelect.vue
+++ b/src/components/chat/ProviderModelSelect.vue
@@ -5,6 +5,7 @@ import { useI18n } from '@open-pencil/vue'
import AppCombobox from '@/components/ui/AppCombobox.vue'
import { useAIChat } from '@/app/ai/chat/use'
+import { modelPickerOptions } from '@/app/ai/models/picker/options'
import { useProviderModelCatalog } from '@/app/ai/models/use-provider-model-catalog'
const { modelID, providerDef, providerID } = useAIChat()
@@ -12,28 +13,7 @@ const { ai, common } = useI18n()
const fallbackModels = computed(() => providerDef.value.models)
const { models } = useProviderModelCatalog(providerID, fallbackModels)
-function modelGroup(modelID: string, recommendedIds: Set<string>, latestIds: Set<string>): string {
- if (recommendedIds.has(modelID)) return ai.value.recommendedModels
- if (latestIds.has(modelID)) return ai.value.latestModels
- return ai.value.allModels
-}
-
-const options = computed(() => {
- const recommendedIds = new Set(providerDef.value.models.map((model) => model.id))
- const latestIds = new Set(
- models.value
- .filter((model) => !recommendedIds.has(model.id) && model.releaseDate)
- .slice(0, 8)
- .map((model) => model.id)
- )
- return models.value.map((model) => ({
- value: model.id,
- label: model.name,
- description: model.id,
- meta: model.tag ?? (latestIds.has(model.id) ? ai.value.latest : undefined),
- group: modelGroup(model.id, recommendedIds, latestIds)
- }))
-})
+const options = computed(() => modelPickerOptions(models.value, providerDef.value.models, ai.value))
</script>
<template>
diff --git a/src/components/settings/models/ProfileEditor.vue b/src/components/settings/models/ProfileEditor.vue
index 3be4ed387..da6692351 100644
--- a/src/components/settings/models/ProfileEditor.vue
+++ b/src/components/settings/models/ProfileEditor.vue
@@ -1,30 +1,7 @@
<script setup lang="ts">
-import { computed, reactive, ref, watch } from 'vue'
+import { ref } from 'vue'
import { CollapsibleContent, CollapsibleRoot, CollapsibleTrigger } from 'reka-ui'
import { useI18n } from '@open-pencil/vue'
-
-import { ACP_AGENTS, AI_PROVIDERS, type AIProviderID } from '@open-pencil/core/constants'
-
-import { refreshAIProviderStatus } from '@/app/ai/chat/storage'
-import { resolveModelsDevModel } from '@/app/ai/models/catalog'
-import { useProviderModelCatalog } from '@/app/ai/models/use-provider-model-catalog'
-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'
@@ -35,273 +12,57 @@ import AppInput from '@/components/ui/AppInput.vue'
import AppSelect from '@/components/ui/AppSelect.vue'
import AppSwitch from '@/components/ui/AppSwitch.vue'
import { AppConfirmationDialog } from '@/components/ui/dialog'
-
-const CUSTOM_MODEL_VALUE = '__custom__'
-const DEFAULT_MAX_OUTPUT_TOKENS = 16_384
-
+import { useModelProfileEditor } from '@/app/ai/models/settings/profile-editor/use'
+import type { AIProviderID } from '@open-pencil/core/constants'
const { profileId } = defineProps<{ profileId?: string }>()
const emit = defineEmits<{ done: []; deleted: [] }>()
const { ai, common, credentials } = 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 profile = useModelProfileEditor({ profileId, keyInput, labels: ai })
+const {
+ draft,
+ providerDef,
+ isACP,
+ isHarness,
+ supportsReasoningEffort,
+ modelOptions,
+ selectedModelValue,
+ knownModel,
+ knownCapabilities,
+ outputTokenRecommendation,
+ modelDisplayName,
+ hasExistingKey,
+ canDelete,
+ toolsEnabled,
+ visionEnabled,
+ canSave,
+ canTest,
+ connectionTestStatus,
+ connectionTestReason,
+ saveError,
+ clearKey,
+ testConnection
+} = profile
+const CUSTOM_MODEL_VALUE = '__custom__'
const advancedOpen = ref(Boolean(draft.customModelID.trim()))
-const customModelSelected = ref(
- Boolean(draft.customModelID.trim()) || draft.providerID === 'harness:pi'
-)
-const catalogModel = ref<(typeof providerDef.value.models)[number] | null>(null)
-
-const providerDef = computed(
- () => AI_PROVIDERS.find((provider) => provider.id === draft.providerID) ?? AI_PROVIDERS[0]
-)
-const catalogProviderID = computed(() => draft.providerID)
-const fallbackModels = computed(() => providerDef.value.models)
-const { models: availableModels } = useProviderModelCatalog(catalogProviderID, fallbackModels)
-const isACP = computed(() => draft.providerID.startsWith('acp:'))
-const isHarness = computed(() => draft.providerID === 'harness:pi')
-const supportsReasoningEffort = computed(() =>
- ['openai', 'openai-compatible', 'openrouter'].includes(draft.providerID)
-)
-const providerDisplayName = computed(() => {
- if (!isACP.value) return providerDef.value.name
- const agentID = draft.providerID.slice('acp:'.length)
- return ACP_AGENTS.find((agent) => agent.id === agentID)?.name ?? draft.providerID
-})
-function modelGroup(modelID: string, recommendedIds: Set<string>, latestIds: Set<string>): string {
- if (recommendedIds.has(modelID)) return ai.value.recommendedModels
- if (latestIds.has(modelID)) return ai.value.latestModels
- return ai.value.allModels
-}
-
-const modelOptions = computed(() => {
- const recommendedIds = new Set(providerDef.value.models.map((model) => model.id))
- const latestIds = new Set(
- availableModels.value
- .filter((model) => !recommendedIds.has(model.id) && model.releaseDate)
- .slice(0, 8)
- .map((model) => model.id)
- )
- return [
- ...availableModels.value.map((model) => ({
- value: model.id,
- label: model.name,
- description: model.id,
- meta: model.tag ?? (latestIds.has(model.id) ? ai.value.latest : undefined),
- group: modelGroup(model.id, recommendedIds, latestIds)
- })),
- ...(providerDef.value.supportsCustomModel
- ? [
- {
- value: CUSTOM_MODEL_VALUE,
- label: ai.value.customModel,
- group: ai.value.customModel
- }
- ]
- : [])
- ]
-})
-const selectedModelValue = computed(() =>
- customModelSelected.value ? CUSTOM_MODEL_VALUE : draft.modelID
-)
-const knownModel = computed(() => {
- if (isACP.value) return null
- if (draft.customModelID.trim()) return catalogModel.value
- return (
- catalogModel.value ??
- providerDef.value.models.find((model) => model.id === draft.modelID) ??
- null
- )
-})
-const knownCapabilities = computed<AIModelCapability[]>(() => [
- ...(knownModel.value?.capabilities ?? ['tools'])
-])
-const outputTokenRecommendation = computed(
- () => knownModel.value?.recommendedMaxOutputTokens ?? DEFAULT_MAX_OUTPUT_TOKENS
-)
-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 ||
- (customModelSelected.value
- ? Boolean(draft.customModelID.trim())
- : Boolean(draft.modelID.trim())))
-)
-const canTest = computed(() => {
- if (isACP.value || isHarness.value) return false
- if (!keyInput.value.trim() && !hasExistingKey.value) return false
- if (providerDef.value.supportsCustomBaseURL && !draft.customBaseURL.trim()) return false
- return customModelSelected.value
- ? Boolean(draft.customModelID.trim())
- : Boolean(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 effectiveModelID(): string {
- return customModelSelected.value ? draft.customModelID.trim() : draft.modelID.trim()
-}
-
-async function refreshCatalogModel(): Promise<void> {
- if (isACP.value) {
- catalogModel.value = null
- return
- }
- const providerID = draft.providerID
- const modelID = effectiveModelID()
- catalogModel.value = await resolveModelsDevModel(providerID, modelID)
- if (providerID !== draft.providerID || modelID !== effectiveModelID()) return
- applyKnownModelMetadata()
-}
-
-function applyKnownModelMetadata(): void {
- if (!knownModel.value) return
- draft.capabilities = [...knownCapabilities.value]
- draft.maxOutputTokens = outputTokenRecommendation.value
-}
-
-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 = ''
- customModelSelected.value = providerID === 'harness:pi'
- draft.customBaseURL = ''
- draft.customAPIType = 'completions'
- advancedOpen.value = providerID === 'harness:pi'
- if (providerID.startsWith('acp:')) {
- draft.capabilities = ['tools']
- if (!draft.name.trim()) draft.name = providerDisplayName.value
- } else {
- applyKnownModelMetadata()
- }
- keyInput.value = ''
- resetConnectionTest()
- void refreshCatalogModel()
- void refreshKeyStatus()
-}
-
-function updateModel(modelID: string): void {
- if (modelID === CUSTOM_MODEL_VALUE) {
- customModelSelected.value = true
- draft.customModelID = ''
- advancedOpen.value = true
- catalogModel.value = null
- resetConnectionTest()
- return
- }
- draft.modelID = modelID
- customModelSelected.value = false
- draft.customModelID = ''
- applyKnownModelMetadata()
- void refreshCatalogModel()
- if (!draft.name.trim()) draft.name = modelDisplayName.value
- resetConnectionTest()
+function updateProvider(id: AIProviderID) {
+ profile.updateProvider(id)
+ advancedOpen.value = id === 'harness:pi'
}
-
-async function save(): Promise<void> {
- saveError.value = null
- try {
- applyKnownModelMetadata()
- if (!draft.name.trim()) draft.name = modelDisplayName.value || providerDisplayName.value
- 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)
- }
+function updateModel(id: string) {
+ profile.updateModel(id)
+ if (id === CUSTOM_MODEL_VALUE) advancedOpen.value = true
}
-
-async function clearKey(): Promise<void> {
- const connection = findModelConnectionForDraft(draft)
- if (!connection) return
- await setModelConnectionAPIKey(connection.id, '')
- await refreshAIProviderStatus()
- keyInput.value = ''
- await refreshKeyStatus()
+async function save() {
+ if (await profile.save()) emit('done')
}
-
-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
+async function remove() {
+ if (await profile.remove()) {
+ deleteOpen.value = false
+ emit('deleted')
}
- 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
-)
-watch(
- () => draft.customModelID,
- () => {
- if (customModelSelected.value) void refreshCatalogModel()
- }
-)
-void refreshCatalogModel()
-void refreshKeyStatus()
</script>
<template>
diff --git a/tests/engine/app/ai/catalog.test.ts b/tests/engine/app/ai/catalog.test.ts
index 6946490dd..e8e323040 100644
--- a/tests/engine/app/ai/catalog.test.ts
+++ b/tests/engine/app/ai/catalog.test.ts
@@ -66,6 +66,9 @@ describe('models.dev catalog', () => {
release_date: '2026-09-02',
modalities: { output: ['image'] }
},
+ missingOutput: { tool_call: true },
+ malformedOutput: { tool_call: true, modalities: { output: 'text' } },
+ imageOutput: { tool_call: true, modalities: { output: ['image'] } },
legacy: {
name: 'Legacy',
tool_call: true,
@@ -87,6 +90,9 @@ describe('models.dev catalog', () => {
expect(models.findIndex((model) => model.id === 'gpt-6-preview')).toBeGreaterThan(0)
expect(models.some((model) => model.id === 'gpt-image')).toBeFalse()
expect(models.some((model) => model.id === 'legacy')).toBeFalse()
+ for (const id of ['missingOutput', 'malformedOutput', 'imageOutput']) {
+ expect(models.some((model) => model.id === id)).toBeFalse()
+ }
})
test('falls back to curated models when the catalog request fails', async () => {
@@ -96,6 +102,42 @@ describe('models.dev catalog', () => {
expect(models[0]).toMatchObject({ id: 'claude-sonnet-5', tag: 'Best for design' })
})
+ test('retries a failed shared request and shares a successful request', async () => {
+ const originalFetch = globalThis.fetch
+ let requests = 0
+ globalThis.fetch = (async () => {
+ requests++
+ if (requests === 1) return new Response(null, { status: 503 })
+ return new Response(
+ JSON.stringify({
+ openai: { models: { retryModel: { name: 'Retry model', tool_call: true } } }
+ })
+ )
+ }) as typeof fetch
+ try {
+ expect(await resolveModelsDevModel('openai', 'retryModel')).toBeNull()
+ const [first, second] = await Promise.all([
+ resolveModelsDevModel('openai', 'retryModel'),
+ resolveModelsDevModel('openai', 'retryModel')
+ ])
+ expect(first?.name).toBe('Retry model')
+ expect(second).toEqual(first)
+ expect(requests).toBe(2)
+ } finally {
+ globalThis.fetch = originalFetch
+ }
+ })
+
+ test('preserves vision support in offline curated models', async () => {
+ const failingFetch = (async () => new Response(null, { status: 503 })) as typeof fetch
+ const openai = await listCatalogModels('openai', failingFetch)
+ for (const id of ['gpt-5.6', 'gpt-5.5', 'gpt-5.4-mini', 'gpt-5.4-nano']) {
+ expect(openai.find((model) => model.id === id)?.capabilities).toContain('vision')
+ }
+ const zai = await listCatalogModels('zai', failingFetch)
+ expect(zai.find((model) => model.id === 'glm-5v-turbo')?.capabilities).toContain('vision')
+ })
+
test('returns null when the provider or model is unknown', async () => {
expect(
await resolveModelsDevModel('openai-compatible', 'local', catalogResponse({}))
diff --git a/tests/engine/app/ai/profile-selection.test.ts b/tests/engine/app/ai/profile-selection.test.ts
new file mode 100644
index 000000000..8d73667ed
--- /dev/null
+++ b/tests/engine/app/ai/profile-selection.test.ts
@@ -0,0 +1,67 @@
+import { expect, test } from 'bun:test'
+
+import { effectScope, nextTick, reactive, ref } from 'vue'
+
+import { createModelProfileDraft } from '@/app/ai/models'
+import { resetModelsDevCatalogForTests } from '@/app/ai/models/catalog'
+import { useProfileModelSelection } from '@/app/ai/models/settings/profile-editor/selection'
+
+const labels = ref({
+ recommendedModels: 'Recommended',
+ latestModels: 'Latest',
+ allModels: 'All',
+ latest: 'New',
+ customModel: 'Custom'
+})
+
+test('selection immediately applies loaded catalog metadata and display name', async () => {
+ const originalFetch = globalThis.fetch
+ globalThis.fetch = (async () =>
+ new Response(
+ JSON.stringify({
+ openai: {
+ models: {
+ 'catalog-model': {
+ name: 'Catalog model',
+ tool_call: true,
+ attachment: true,
+ modalities: { output: ['text'] },
+ limit: { output: 32000 }
+ }
+ }
+ }
+ })
+ )) as typeof fetch
+ resetModelsDevCatalogForTests()
+ const scope = effectScope()
+ try {
+ const draft = reactive(createModelProfileDraft())
+ draft.providerID = 'openai'
+ draft.modelID = ''
+ draft.customModelID = ''
+ draft.name = ''
+ const selection = scope.run(() => useProfileModelSelection(draft, labels))
+ if (!selection) throw new Error('Missing selection scope')
+ for (let attempt = 0; attempt < 20; attempt++) {
+ await new Promise((resolve) => {
+ setTimeout(resolve, 0)
+ })
+ if (selection.modelOptions.value.some((option) => option.value === 'catalog-model')) break
+ }
+ expect(selection.modelOptions.value.some((option) => option.value === 'catalog-model')).toBe(
+ true
+ )
+ selection.updateModel('catalog-model')
+ expect(draft.capabilities).toEqual(['tools', 'vision'])
+ expect(draft.maxOutputTokens).toBe(32000)
+ expect(draft.name).toBe('Catalog model')
+ selection.updateProvider('deepseek')
+ await nextTick()
+ expect(selection.providerDef.value.id).toBe('deepseek')
+ expect(draft.capabilities).toEqual(['tools'])
+ } finally {
+ scope.stop()
+ globalThis.fetch = originalFetch
+ resetModelsDevCatalogForTests()
+ }
+})