feat(models): 增加模型显示名重命名 (#614)

* feat(models): add WUI model display aliases

Persist display-only model aliases in Web UI app config, surface them in the model selector/search, and keep canonical model IDs for Hermes calls.

* fix(models): improve WUI model alias editing

* fix(models): clarify unlisted model picker

* fix(models): scope aliases to providers
This commit is contained in:
Zhicheng Han
2026-05-11 16:18:13 +02:00
committed by GitHub
parent 7b781b4f42
commit b8be47d8d6
20 changed files with 898 additions and 57 deletions
+15 -2
View File
@@ -41,8 +41,8 @@ export interface AvailableModelGroup {
available_models?: string[]
api_key: string
builtin?: boolean
/** 可选:模型 ID -> 元数据(preview/disabled)。目前仅 Copilot 提供。 */
model_meta?: Record<string, { preview?: boolean; disabled?: boolean }>
/** 可选:模型 ID -> 元数据(preview/disabled/alias)。alias 仅用于 Web UI 展示。 */
model_meta?: Record<string, { preview?: boolean; disabled?: boolean; alias?: string }>
}
export interface AvailableModelsResponse {
@@ -50,6 +50,8 @@ export interface AvailableModelsResponse {
default_provider: string
groups: AvailableModelGroup[]
allProviders: AvailableModelGroup[]
/** Web UI-only display aliases keyed by provider -> canonical model ID. */
model_aliases?: Record<string, Record<string, string>>
model_visibility?: ModelVisibility
}
@@ -90,6 +92,17 @@ export async function updateDefaultModel(data: {
})
}
export async function updateModelAlias(data: {
provider: string
model: string
alias: string
}): Promise<void> {
await request('/api/hermes/model-alias', {
method: 'PUT',
body: JSON.stringify(data),
})
}
export async function addCustomProvider(data: CustomProvider): Promise<void> {
await request('/api/hermes/config/providers', {
method: 'POST',
@@ -1,6 +1,6 @@
<script setup lang="ts">
import { ref, computed } from 'vue'
import { NButton, NCheckbox, NCheckboxGroup, NModal, useMessage, useDialog } from 'naive-ui'
import { NButton, NCheckbox, NCheckboxGroup, NModal, NInput, useMessage, useDialog } from 'naive-ui'
import type { AvailableModelGroup } from '@/api/hermes/system'
import { useModelsStore } from '@/stores/hermes/models'
import { useAppStore } from '@/stores/hermes/app'
@@ -21,6 +21,13 @@ const isCustom = computed(() => !props.provider.builtin && props.provider.provid
const isCopilot = computed(() => props.provider.provider === 'copilot')
const displayName = computed(() => props.provider.label)
const deleting = ref(false)
const showAliasListModal = ref(false)
const showAliasModal = ref(false)
const aliasProvider = ref('')
const aliasModel = ref('')
const aliasInput = ref('')
const showVisibilityModal = ref(false)
const visibilitySaving = ref(false)
const selectedVisibleModels = ref<string[]>([])
@@ -31,6 +38,36 @@ const visibilityRule = computed(() => appStore.getProviderVisibility(props.provi
const isFiltered = computed(() => visibilityRule.value.mode === 'include')
const visibleCountLabel = computed(() => `${props.provider.models.length}/${allModels.value.length}`)
function modelAlias(model: string) {
return appStore.getModelAlias(model, props.provider.provider)
}
function modelDisplayName(model: string) {
return appStore.displayModelName(model, props.provider.provider)
}
function openAliasEditor(model: string) {
aliasProvider.value = props.provider.provider
aliasModel.value = model
aliasInput.value = appStore.getModelAlias(model, props.provider.provider)
showAliasModal.value = true
}
async function saveAlias() {
if (!aliasModel.value || !aliasProvider.value) return
try {
await appStore.setModelAlias(aliasModel.value, aliasProvider.value, aliasInput.value)
showAliasModal.value = false
} catch (e: any) {
message.error(e.message || t('models.aliasSaveFailed'))
}
}
async function clearAlias() {
aliasInput.value = ''
await saveAlias()
}
function openVisibilityModal() {
const rule = appStore.getProviderVisibility(props.provider.provider)
selectedVisibleModels.value = rule.mode === 'include' ? allModels.value.filter(m => rule.models.includes(m)) : [...allModels.value]
@@ -137,11 +174,17 @@ async function handleDelete() {
</span>
</div>
<div class="models-list">
<span
<button
v-for="model in provider.models.slice(0, 20)"
:key="model"
class="model-tag"
>{{ model }}</span>
class="model-tag model-tag-button"
type="button"
:title="t('models.aliasTitleFor', { model })"
@click="openAliasEditor(model)"
>
<span class="model-tag-name">{{ modelDisplayName(model) }}</span>
<span v-if="modelAlias(model)" class="model-tag-id">{{ model }}</span>
</button>
<span v-if="provider.models.length > 20" class="model-tag model-tag-more">
+{{ provider.models.length - 20 }} {{ t('models.more') }}
</span>
@@ -149,10 +192,59 @@ async function handleDelete() {
</div>
<div class="card-actions">
<NButton size="tiny" quaternary @click="showAliasListModal = true">{{ t('models.aliasManage') }}</NButton>
<NButton size="tiny" quaternary @click="openVisibilityModal">{{ t('models.manageVisibleModels') }}</NButton>
<NButton size="tiny" quaternary type="error" :loading="deleting" @click="handleDelete">{{ t('common.delete') }}</NButton>
</div>
<NModal
v-model:show="showAliasListModal"
preset="card"
:title="t('models.aliasManageFor', { provider: displayName })"
:style="{ width: 'min(560px, calc(100vw - 32px))' }"
:mask-closable="true"
>
<div class="alias-list-hint">{{ t('models.aliasHint') }}</div>
<div class="alias-list">
<div v-for="model in provider.models" :key="model" class="alias-row">
<div class="alias-row-text">
<span class="alias-row-name">{{ modelDisplayName(model) }}</span>
<code class="alias-row-id">{{ model }}</code>
</div>
<NButton size="tiny" quaternary @click="openAliasEditor(model)">{{ t('models.aliasEdit') }}</NButton>
</div>
</div>
</NModal>
<NModal
v-model:show="showAliasModal"
preset="card"
:title="aliasModel ? t('models.aliasTitleFor', { model: aliasModel }) : t('models.aliasTitle')"
:style="{ width: 'min(420px, calc(100vw - 32px))' }"
:mask-closable="true"
>
<NInput
v-model:value="aliasInput"
:placeholder="t('models.aliasPlaceholder')"
clearable
@keydown.enter="saveAlias"
/>
<div v-if="aliasModel" class="model-alias-canonical">
{{ t('models.aliasCanonical', { model: aliasModel }) }}
</div>
<div class="model-alias-hint">{{ t('models.aliasHint') }}</div>
<template #footer>
<div class="model-alias-actions">
<NButton quaternary :disabled="!appStore.getModelAlias(aliasModel, aliasProvider)" @click="clearAlias">
{{ t('models.aliasUseOriginal') }}
</NButton>
<div class="model-alias-spacer" />
<NButton @click="showAliasModal = false">{{ t('common.cancel') }}</NButton>
<NButton type="primary" @click="saveAlias">{{ t('common.save') }}</NButton>
</div>
</template>
</NModal>
<NModal
v-model:show="showVisibilityModal"
preset="card"
@@ -172,7 +264,8 @@ async function handleDelete() {
:value="model"
class="visibility-model"
>
<code>{{ model }}</code>
<code>{{ modelDisplayName(model) }}</code>
<code v-if="modelAlias(model)" class="visibility-model-id">{{ model }}</code>
</NCheckbox>
</NCheckboxGroup>
</div>
@@ -291,7 +384,8 @@ async function handleDelete() {
.model-tag {
display: inline-flex;
align-items: center;
height: 20px;
gap: 5px;
min-height: 22px;
font-size: 10px;
font-family: $font-code;
padding: 2px 6px;
@@ -299,7 +393,7 @@ async function handleDelete() {
background: rgba(var(--accent-primary-rgb), 0.08);
color: $text-secondary;
white-space: nowrap;
max-width: 200px;
max-width: 260px;
overflow: hidden;
text-overflow: ellipsis;
@@ -310,6 +404,28 @@ async function handleDelete() {
}
}
.model-tag-button {
border: 0;
cursor: pointer;
text-align: left;
&:hover {
background: rgba(var(--accent-primary-rgb), 0.16);
color: $text-primary;
}
}
.model-tag-name,
.model-tag-id {
overflow: hidden;
text-overflow: ellipsis;
}
.model-tag-id {
color: $text-muted;
font-size: 9px;
}
.card-actions {
display: flex;
gap: 8px;
@@ -317,6 +433,78 @@ async function handleDelete() {
padding-top: 10px;
}
.alias-list-hint,
.model-alias-hint {
color: $text-muted;
font-size: 12px;
}
.alias-list-hint {
margin-bottom: 12px;
}
.alias-list {
display: flex;
flex-direction: column;
gap: 6px;
max-height: 45vh;
overflow-y: auto;
}
.alias-row {
display: flex;
align-items: center;
gap: 12px;
padding: 8px;
border: 1px solid $border-light;
border-radius: $radius-sm;
}
.alias-row-text {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
gap: 2px;
}
.alias-row-name {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
color: $text-primary;
font-family: $font-code;
font-size: 12px;
}
.alias-row-id,
.model-alias-canonical {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
color: $text-muted;
font-family: $font-code;
font-size: 11px;
}
.model-alias-canonical {
margin-top: 8px;
}
.model-alias-hint {
margin-top: 6px;
}
.model-alias-actions {
display: flex;
align-items: center;
gap: 8px;
}
.model-alias-spacer {
flex: 1;
}
.visibility-hint {
margin: 0 0 10px;
color: $text-secondary;
@@ -350,6 +538,12 @@ async function handleDelete() {
}
}
.visibility-model-id {
margin-left: 6px;
color: $text-muted !important;
font-size: 11px !important;
}
.visibility-actions {
display: flex;
align-items: center;
@@ -13,6 +13,8 @@ const collapsedGroups = ref<Record<string, boolean>>({})
const customInput = ref('')
const customProvider = ref('')
const selectedDisplayName = computed(() => appStore.displayModelName(appStore.selectedModel, appStore.selectedProvider))
const providerOptions = computed(() => {
const current = appStore.selectedProvider
customProvider.value = current
@@ -29,13 +31,13 @@ const modelGroupsWithCustom = computed(() =>
}))
)
const customModelSet = computed(() => {
const set = new Set<string>()
for (const models of Object.values(appStore.customModels)) {
models.forEach(m => set.add(m))
}
return set
})
function isCustomModel(model: string, provider: string) {
return (appStore.customModels[provider] || []).includes(model)
}
async function removeCustomModel(model: string, provider: string) {
await appStore.removeCustomModel(model, provider)
}
const filteredGroups = computed(() => {
const q = searchQuery.value.toLowerCase().trim()
@@ -43,7 +45,10 @@ const filteredGroups = computed(() => {
return modelGroupsWithCustom.value
.map(g => ({
...g,
models: g.models.filter(m => m.toLowerCase().includes(q)),
models: g.models.filter(m => {
const displayName = appStore.displayModelName(m, g.provider)
return m.toLowerCase().includes(q) || displayName.toLowerCase().includes(q)
}),
}))
.filter(g => g.models.length > 0 || g.label.toLowerCase().includes(q))
})
@@ -64,6 +69,14 @@ function handleSelect(model: string, provider: string) {
searchQuery.value = ''
}
function modelDisplayName(model: string, provider: string) {
return appStore.displayModelName(model, provider)
}
function modelAlias(model: string, provider: string) {
return appStore.getModelAlias(model, provider)
}
function handleCustomSubmit() {
const model = customInput.value.trim()
if (!model || !customProvider.value) return
@@ -89,7 +102,7 @@ function openModal() {
<div class="model-selector">
<div class="model-label">{{ t('models.title') }}</div>
<button class="model-trigger" @click="openModal">
<span class="model-name" :title="appStore.selectedModel">{{ appStore.selectedModel || '—' }}</span>
<span class="model-name" :title="appStore.selectedModel">{{ selectedDisplayName || '—' }}</span>
<svg class="model-arrow" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<polyline points="6 9 12 15 18 9" />
</svg>
@@ -134,10 +147,24 @@ function openModal() {
:title="group.model_meta?.[model]?.disabled ? t('models.disabledTooltip') : ''"
@click="handleSelect(model, group.provider)"
>
<span class="model-item-name">{{ model }}</span>
<span class="model-item-label">
<span class="model-item-name">{{ modelDisplayName(model, group.provider) }}</span>
<span v-if="modelAlias(model, group.provider)" class="model-item-id">
{{ t('models.aliasCanonical', { model }) }}
</span>
</span>
<span v-if="group.model_meta?.[model]?.preview" class="model-badge-preview">{{ t('models.previewBadge') }}</span>
<span v-if="group.model_meta?.[model]?.disabled" class="model-badge-disabled">{{ t('models.disabledBadge') }}</span>
<span v-if="customModelSet.has(model)" class="model-badge-custom">{{ t('models.customBadge') }}</span>
<span v-if="isCustomModel(model, group.provider)" class="model-badge-custom">{{ t('models.customBadge') }}</span>
<button
v-if="isCustomModel(model, group.provider)"
class="model-custom-remove"
type="button"
:title="t('models.removeCustomModel')"
@click.stop="removeCustomModel(model, group.provider)"
>
×
</button>
<svg v-if="model === appStore.selectedModel && group.provider === appStore.selectedProvider" class="model-check" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
<polyline points="20 6 9 17 4 12" />
</svg>
@@ -169,6 +196,7 @@ function openModal() {
</div>
</div>
</NModal>
</div>
</template>
@@ -308,8 +336,15 @@ function openModal() {
}
}
.model-item-name {
.model-item-label {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
gap: 2px;
}
.model-item-name {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
@@ -317,6 +352,17 @@ function openModal() {
font-size: 12px;
}
.model-item-id {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
color: $text-muted;
font-family: $font-code;
font-size: 10px;
font-weight: 400;
}
.model-check {
flex-shrink: 0;
color: $accent-primary;
@@ -334,6 +380,25 @@ function openModal() {
letter-spacing: 0.03em;
}
.model-custom-remove {
flex-shrink: 0;
width: 18px;
height: 18px;
border: 0;
border-radius: 50%;
background: transparent;
color: $text-muted;
cursor: pointer;
line-height: 18px;
padding: 0;
&:hover {
background: rgba(var(--error-rgb), 0.12);
color: $error;
}
}
.model-badge-preview {
flex-shrink: 0;
font-size: 9px;
+2 -2
View File
@@ -419,8 +419,8 @@ jobTriggered: 'Job ausgelost',
previewBadge: 'VORSCHAU',
disabledBadge: 'NICHT VERFÜGBAR',
disabledTooltip: "Dieses Modell ist für Ihr Konto derzeit nicht verfügbar.",
customModelPlaceholder: 'Benutzerdefinierter Modellname',
customModelHint: 'Enter zum Laden',
customModelPlaceholder: 'Nicht gelistete Modell-ID',
customModelHint: 'Für vom Provider unterstützte Modelle, die die API nicht zurückgibt; keine Anzeige-Umbenennung. Enter zum Laden.',
noProviders: 'Keine Anbieter gefunden. Fugen Sie einen benutzerdefinierten Anbieter hinzu, um zu beginnen.',
builtIn: 'Integriert',
customType: 'Benutzerdefiniert',
+13 -2
View File
@@ -547,12 +547,23 @@ export default {
previewBadge: 'PREVIEW',
disabledBadge: 'UNAVAILABLE',
disabledTooltip: "This model is currently unavailable for your account.",
customModelPlaceholder: 'Custom model name',
customModelHint: 'Enter to load',
customModelPlaceholder: 'Unlisted model ID',
customModelHint: 'For provider-supported models not returned by the API; not a display rename. Press Enter to load.',
removeCustomModel: 'Remove this unlisted model',
noProviders: 'No providers found. Add a custom provider to get started.',
models: 'Models',
count: 'models',
more: 'more',
aliasEdit: 'Rename',
aliasTitle: 'Model display name',
aliasTitleFor: 'Display name for {model}',
aliasPlaceholder: 'Leave empty to use original model ID',
aliasHint: 'Display-only alias. Hermes still receives the canonical model ID.',
aliasCanonical: 'Original ID: {model}',
aliasUseOriginal: 'Use original ID',
aliasManage: 'Display names',
aliasManageFor: 'Display names for {provider}',
aliasSaveFailed: 'Failed to save display name',
manageVisibleModels: 'Manage visible models',
manageVisibleModelsFor: 'Manage visible models for {name}',
visibilityHint: 'Only affects the Web UI model picker and Models page. Hermes CLI provider/model config is not rewritten; calls still use canonical model IDs.',
+2 -2
View File
@@ -419,8 +419,8 @@ jobTriggered: 'Job ejecutado',
previewBadge: 'VISTA PREVIA',
disabledBadge: 'NO DISPONIBLE',
disabledTooltip: "Este modelo no está disponible para tu cuenta.",
customModelPlaceholder: 'Nombre del modelo personalizado',
customModelHint: 'Enter para cargar',
customModelPlaceholder: 'ID de modelo no listado',
customModelHint: 'Para modelos compatibles con el proveedor que la API no devuelve; no es un cambio de nombre visible. Enter para cargar.',
noProviders: 'No se encontraron proveedores. Anade un proveedor personalizado para comenzar.',
builtIn: 'Integrado',
customType: 'Personalizado',
+2 -2
View File
@@ -419,8 +419,8 @@ jobTriggered: 'Job declenche',
previewBadge: 'APERÇU',
disabledBadge: 'INDISPONIBLE',
disabledTooltip: "Ce modèle n'est pas disponible pour votre compte.",
customModelPlaceholder: 'Nom du modèle personnalisé',
customModelHint: 'Entrée pour charger',
customModelPlaceholder: 'ID de modèle non listé',
customModelHint: 'Pour les modèles pris en charge par le fournisseur mais non renvoyés par lAPI ; ce nest pas un renommage affiché. Entrée pour charger.',
noProviders: 'Aucun fournisseur trouve. Ajoutez un fournisseur personnalise pour commencer.',
builtIn: 'Integre',
customType: 'Personnalise',
+2 -2
View File
@@ -419,8 +419,8 @@ export default {
previewBadge: 'プレビュー',
disabledBadge: '利用不可',
disabledTooltip: "このモデルは現在のアカウントでは利用できません。",
customModelPlaceholder: 'カスタムモデル名',
customModelHint: 'Enterで読み込み',
customModelPlaceholder: '未掲載のモデル ID',
customModelHint: 'プロバイダーは対応しているが API が返さないモデル用です。表示名の変更ではありません。Enter で読み込み',
noProviders: 'プロバイダーがありません。カスタムプロバイダーを追加して始めましょう。',
builtIn: '組み込み',
customType: 'カスタム',
+2 -2
View File
@@ -419,8 +419,8 @@ export default {
previewBadge: '프리뷰',
disabledBadge: '사용 불가',
disabledTooltip: "이 모델은 현재 계정에서 사용할 수 없습니다.",
customModelPlaceholder: '사용자 지정 모델 이름',
customModelHint: 'Enter로 불러오기',
customModelPlaceholder: '목록에 없는 모델 ID',
customModelHint: '제공자는 지원하지만 API가 반환하지 않는 모델용입니다. 표시 이름 변경이 아닙니다. Enter로 불러옵니다.',
noProviders: 'Provider가 없습니다. 사용자 지정 Provider를 추가하여 시작하세요.',
builtIn: '내장',
customType: '사용자 지정',
+2 -2
View File
@@ -419,8 +419,8 @@ jobTriggered: 'Job acionado',
previewBadge: 'PRÉVIA',
disabledBadge: 'INDISPONÍVEL',
disabledTooltip: "Este modelo não está disponível para sua conta.",
customModelPlaceholder: 'Nome do modelo personalizado',
customModelHint: 'Enter para carregar',
customModelPlaceholder: 'ID de modelo não listado',
customModelHint: 'Para modelos compatíveis com o provedor que a API não retorna; não é uma renomeação de exibição. Enter para carregar.',
noProviders: 'Nenhum provedor encontrado. Adicione um provedor personalizado para comecar.',
builtIn: 'Integrado',
customType: 'Personalizado',
+13 -2
View File
@@ -547,12 +547,23 @@ export default {
previewBadge: '预览',
disabledBadge: '不可用',
disabledTooltip: "此模型当前账号不可用",
customModelPlaceholder: '自定义模型名称',
customModelHint: '按回车加载',
customModelPlaceholder: '未列出的模型 ID',
customModelHint: '仅用于 provider 支持但未返回的模型;不是重命名。按回车加载',
removeCustomModel: '移除这个未列出的模型',
noProviders: '暂无 Provider,添加一个开始吧。',
models: '模型列表',
count: '个模型',
more: '个更多',
aliasEdit: '重命名',
aliasTitle: '模型显示名',
aliasTitleFor: '{model} 的显示名',
aliasPlaceholder: '留空则使用原始模型 ID',
aliasHint: '仅修改 Web UI 显示名,发送给 Hermes 的仍是原始模型 ID。',
aliasCanonical: '原始 ID{model}',
aliasUseOriginal: '恢复原始 ID',
aliasManage: '显示名',
aliasManageFor: '{provider} 的显示名',
aliasSaveFailed: '保存显示名失败',
manageVisibleModels: '管理可见模型',
manageVisibleModelsFor: '管理 {name} 可见模型',
visibilityHint: '仅影响 Web UI 的模型选择器和模型页展示,不会改写 Hermes CLI 的 provider/model 配置。实际调用仍使用原始模型 ID。',
+114 -6
View File
@@ -1,6 +1,17 @@
import { defineStore } from 'pinia'
import { ref } from 'vue'
import { checkHealth, fetchAvailableModels, updateDefaultModel, updateModelVisibility, triggerUpdate, type AvailableModelGroup, type AvailableModelsResponse, type ModelVisibility, type ModelVisibilityRule } from '@/api/hermes/system'
import {
checkHealth,
fetchAvailableModels,
updateDefaultModel,
updateModelVisibility,
triggerUpdate,
updateModelAlias,
type AvailableModelGroup,
type AvailableModelsResponse,
type ModelVisibility,
type ModelVisibilityRule,
} from '@/api/hermes/system'
const WEB_UI_VERSION = __APP_VERSION__
@@ -20,6 +31,7 @@ export const useAppStore = defineStore('app', () => {
const selectedModel = ref('')
const selectedProvider = ref('')
const customModels = ref<Record<string, string[]>>({})
const modelAliases = ref<Record<string, Record<string, string>>>({})
const modelVisibility = ref<ModelVisibility>({})
const healthPollTimer = ref<ReturnType<typeof setInterval>>()
const nodeVersion = ref('')
@@ -61,13 +73,55 @@ export const useAppStore = defineStore('app', () => {
function applyAvailableModelsResponse(res: AvailableModelsResponse) {
modelGroups.value = res.groups
modelAliases.value = res.model_aliases || {}
modelVisibility.value = res.model_visibility || {}
const defaultGroup = res.groups.find(g => g.provider === (res.default_provider || '') && g.models.includes(res.default))
const inferredGroup = res.groups.find(g => g.models.includes(res.default))
const defaultModel = res.default || ''
const defaultProvider = res.default_provider || ''
const explicitGroup = res.groups.find(g => g.provider === defaultProvider && g.models.includes(defaultModel))
const inferredGroup = res.groups.find(g => g.models.includes(defaultModel))
const fallbackGroup = res.groups.find(g => g.models.length > 0)
const selectedGroup = defaultGroup || inferredGroup || fallbackGroup
selectedModel.value = selectedGroup ? (defaultGroup || inferredGroup ? res.default : selectedGroup.models[0]) : ''
selectedProvider.value = selectedGroup?.provider || ''
const providerGroup = defaultProvider ? res.groups.find(g => g.provider === defaultProvider) : undefined
const allProvider = defaultProvider ? res.allProviders.find(g => g.provider === defaultProvider) : undefined
const providerCatalog = providerGroup?.available_models?.length
? providerGroup.available_models
: allProvider?.available_models?.length
? allProvider.available_models
: allProvider?.models || []
const visibilityRule = defaultProvider ? modelVisibility.value[defaultProvider] : undefined
const hiddenByVisibility = !!(
defaultModel &&
visibilityRule?.mode === 'include' &&
!visibilityRule.models.includes(defaultModel) &&
(providerCatalog.length === 0 || providerCatalog.includes(defaultModel))
)
const unlistedDefault = !!(
defaultModel &&
defaultProvider &&
providerGroup &&
!providerGroup.models.includes(defaultModel) &&
!hiddenByVisibility
)
if (explicitGroup || inferredGroup) {
const selectedGroup = explicitGroup || inferredGroup!
selectedModel.value = defaultModel
selectedProvider.value = selectedGroup.provider
customModels.value = {}
} else if (unlistedDefault) {
selectedModel.value = defaultModel
selectedProvider.value = defaultProvider
customModels.value = { [defaultProvider]: [defaultModel] }
} else if (fallbackGroup) {
selectedModel.value = fallbackGroup.models[0]
selectedProvider.value = fallbackGroup.provider
customModels.value = {}
} else {
selectedModel.value = ''
selectedProvider.value = ''
customModels.value = {}
}
}
async function loadModels() {
@@ -79,6 +133,34 @@ export const useAppStore = defineStore('app', () => {
}
}
function getModelAlias(modelId: string, provider?: string): string {
if (provider) return modelAliases.value[provider]?.[modelId] || ''
for (const aliases of Object.values(modelAliases.value)) {
if (aliases[modelId]) return aliases[modelId]
}
return ''
}
function displayModelName(modelId: string, provider?: string): string {
return getModelAlias(modelId, provider) || modelId
}
async function setModelAlias(modelId: string, provider: string, alias: string) {
const cleanAlias = alias.trim()
await updateModelAlias({ provider, model: modelId, alias: cleanAlias })
const next = { ...modelAliases.value }
const providerAliases = { ...(next[provider] || {}) }
if (cleanAlias) {
providerAliases[modelId] = cleanAlias
next[provider] = providerAliases
} else {
delete providerAliases[modelId]
if (Object.keys(providerAliases).length > 0) next[provider] = providerAliases
else delete next[provider]
}
modelAliases.value = next
}
async function switchModel(modelId: string, providerOverride?: string) {
try {
// Find the group containing this model to get provider info
@@ -99,6 +181,27 @@ export const useAppStore = defineStore('app', () => {
}
}
async function removeCustomModel(modelId: string, provider: string) {
const providerModels = customModels.value[provider] || []
if (!providerModels.includes(modelId)) return
const nextCustomModels = { ...customModels.value }
const remaining = providerModels.filter(m => m !== modelId)
if (remaining.length > 0) nextCustomModels[provider] = remaining
else delete nextCustomModels[provider]
customModels.value = nextCustomModels
if (selectedModel.value === modelId && selectedProvider.value === provider) {
const providerGroup = modelGroups.value.find(g => g.provider === provider && g.models.length > 0)
const fallbackGroup = providerGroup || modelGroups.value.find(g => g.models.length > 0)
if (fallbackGroup) {
await switchModel(fallbackGroup.models[0], fallbackGroup.provider)
} else {
selectedModel.value = ''
selectedProvider.value = ''
}
}
}
function getProviderVisibility(provider: string): ModelVisibilityRule {
return modelVisibility.value[provider] || { mode: 'all', models: [] }
@@ -160,6 +263,7 @@ export const useAppStore = defineStore('app', () => {
doUpdate,
modelGroups,
customModels,
modelAliases,
modelVisibility,
selectedModel,
selectedProvider,
@@ -170,6 +274,10 @@ export const useAppStore = defineStore('app', () => {
loadModels,
applyAvailableModelsResponse,
switchModel,
removeCustomModel,
getModelAlias,
displayModelName,
setModelAlias,
getProviderVisibility,
isModelVisible,
setModelVisibility,
@@ -15,9 +15,9 @@ const showModal = ref(false)
onMounted(async () => {
// invalidate copilot gh logout / VS Code 退 list
// providerscheck-token
// providers appStore check-token
try { await checkCopilotToken() } catch { /* ignore */ }
modelsStore.fetchProviders()
await Promise.all([modelsStore.fetchProviders(), appStore.loadModels()])
})
function openCreateModal() {
@@ -10,10 +10,57 @@ import { MODEL_CONTEXT_TABLE } from '../../db/hermes/schemas'
const PROVIDER_MODEL_CATALOG = buildProviderModelMap()
type ModelMeta = { preview?: boolean; disabled?: boolean }
type ModelMeta = { preview?: boolean; disabled?: boolean; alias?: string }
type AvailableGroup = { provider: string; label: string; base_url: string; models: string[]; api_key: string; builtin?: boolean; model_meta?: Record<string, ModelMeta>; available_models?: string[] }
type ModelVisibility = Record<string, ModelVisibilityRule>
const RESERVED_ALIAS_KEYS = new Set(['__proto__', 'prototype', 'constructor'])
function isSafeAliasKey(value: string): boolean {
const trimmed = value.trim()
return !!trimmed && trimmed.length <= 512 && !RESERVED_ALIAS_KEYS.has(trimmed)
}
function createAliasMap(): Record<string, string> {
return Object.create(null) as Record<string, string>
}
function createProviderAliasMap(): Record<string, Record<string, string>> {
return Object.create(null) as Record<string, Record<string, string>>
}
function normalizeAliases(value: unknown): Record<string, Record<string, string>> {
const normalized = createProviderAliasMap()
if (!value || typeof value !== 'object' || Array.isArray(value)) return normalized
for (const [provider, models] of Object.entries(value as Record<string, unknown>)) {
if (!isSafeAliasKey(provider) || !models || typeof models !== 'object' || Array.isArray(models)) continue
for (const [model, alias] of Object.entries(models as Record<string, unknown>)) {
if (!isSafeAliasKey(model) || typeof alias !== 'string') continue
const trimmed = alias.trim()
if (!trimmed || trimmed.length > 512) continue
if (!Object.hasOwn(normalized, provider)) normalized[provider] = createAliasMap()
normalized[provider][model] = trimmed
}
}
return normalized
}
function applyModelAliases<T extends { provider: string; models: string[]; model_meta?: Record<string, ModelMeta> }>(groups: T[], aliases: Record<string, Record<string, string>>): T[] {
return groups.map((group) => {
const providerAliases = aliases[group.provider]
if (!providerAliases) return group
const modelMeta: Record<string, ModelMeta> = { ...(group.model_meta || {}) }
let changed = false
for (const model of group.models) {
const alias = providerAliases[model]
if (!alias) continue
modelMeta[model] = { ...(modelMeta[model] || {}), alias }
changed = true
}
return changed ? { ...group, model_meta: modelMeta } : group
})
}
function uniqueStrings(values: unknown): string[] {
if (!Array.isArray(values)) return []
return Array.from(new Set(values.map(v => String(v || '').trim()).filter(Boolean)))
@@ -158,6 +205,7 @@ export async function getAvailable(ctx: any) {
// 时也不返回。避免误把 VS Code/gh CLI 用户的全局凭证当作 hermes provider。
const appConfig = await readAppConfig()
const copilotEnabled = appConfig.copilotEnabled === true
const modelAliases = normalizeAliases(appConfig.modelAliases)
const modelVisibility = normalizeModelVisibility(appConfig.modelVisibility)
// 兼容老用户:上一版本会"自动 fallback discovery"出 Copilot;升级后这些用户的
@@ -186,7 +234,7 @@ export async function getAvailable(ctx: any) {
}
const catalogModels = PROVIDER_MODEL_CATALOG[providerKey]
let modelsList: string[] = catalogModels && catalogModels.length > 0 ? [...catalogModels] : []
let modelMeta: Record<string, { preview?: boolean; disabled?: boolean }> | undefined
let modelMeta: Record<string, ModelMeta> | undefined
if (providerKey === 'copilot') {
const live = await getCopilotLive()
if (live.length > 0) {
@@ -250,7 +298,8 @@ export async function getAvailable(ctx: any) {
}
for (const g of groups) { g.models = Array.from(new Set(g.models)) }
const visibleGroups = applyModelVisibility(groups, modelVisibility)
const groupsWithAliases = applyModelAliases(groups, modelAliases)
const visibleGroups = applyModelVisibility(groupsWithAliases, modelVisibility)
const visibleDefault = resolveVisibleDefault(currentDefault, currentDefaultProvider, visibleGroups)
// 动态拉一次 copilot 模型用于 allProviders 展示(同一请求复用缓存)
@@ -264,6 +313,7 @@ export async function getAvailable(ctx: any) {
base_url: p.base_url,
models: p.value === 'copilot' && liveCopilotIds.length > 0 ? liveCopilotIds : p.models,
}))
const allProviders = applyModelAliases(allProvidersBase, modelAliases)
if (groups.length === 0) {
const fallback = buildModelGroups(config)
@@ -278,13 +328,15 @@ export async function getAvailable(ctx: any) {
api_key: '',
}
})
const visibleFallbackGroups = applyModelVisibility(fallbackGroups, modelVisibility)
const fallbackGroupsWithAliases = applyModelAliases(fallbackGroups, modelAliases)
const visibleFallbackGroups = applyModelVisibility(fallbackGroupsWithAliases, modelVisibility)
const fallbackDefault = resolveVisibleDefault(fallback.default, currentDefaultProvider, visibleFallbackGroups)
ctx.body = {
default: fallbackDefault.defaultModel,
default_provider: fallbackDefault.defaultProvider,
groups: visibleFallbackGroups,
allProviders: allProvidersBase,
allProviders,
model_aliases: modelAliases,
model_visibility: modelVisibility,
}
return
@@ -294,7 +346,8 @@ export async function getAvailable(ctx: any) {
default: visibleDefault.defaultModel,
default_provider: visibleDefault.defaultProvider,
groups: visibleGroups,
allProviders: allProvidersBase,
allProviders,
model_aliases: modelAliases,
model_visibility: modelVisibility,
}
} catch (err: any) {
@@ -303,6 +356,55 @@ export async function getAvailable(ctx: any) {
}
}
export async function setModelAlias(ctx: any) {
const body = ctx.request.body
const provider = body && typeof body === 'object' && !Array.isArray(body) ? body.provider : undefined
const model = body && typeof body === 'object' && !Array.isArray(body) ? body.model : undefined
const alias = body && typeof body === 'object' && !Array.isArray(body) ? body.alias : undefined
if (typeof provider !== 'string' || typeof model !== 'string' || (alias !== undefined && typeof alias !== 'string')) {
ctx.status = 400
ctx.body = { error: 'Invalid provider, model, or alias' }
return
}
const cleanProvider = provider.trim()
const cleanModel = model.trim()
const cleanAlias = (alias || '').trim()
if (!isSafeAliasKey(cleanProvider) || !isSafeAliasKey(cleanModel)) {
ctx.status = 400
ctx.body = { error: 'Invalid provider or model' }
return
}
if (cleanAlias.length > 512) {
ctx.status = 400
ctx.body = { error: 'Alias is too long' }
return
}
try {
const appConfig = await readAppConfig()
const modelAliases = normalizeAliases(appConfig.modelAliases)
if (cleanAlias) {
if (!Object.hasOwn(modelAliases, cleanProvider)) modelAliases[cleanProvider] = createAliasMap()
modelAliases[cleanProvider][cleanModel] = cleanAlias
} else {
if (Object.hasOwn(modelAliases, cleanProvider)) delete modelAliases[cleanProvider][cleanModel]
if (Object.hasOwn(modelAliases, cleanProvider) && Object.keys(modelAliases[cleanProvider]).length === 0) {
delete modelAliases[cleanProvider]
}
}
await writeAppConfig({ modelAliases })
ctx.body = { success: true, model_aliases: modelAliases }
} catch (err: any) {
ctx.status = 500
ctx.body = { error: err.message }
}
}
export async function getConfigModels(ctx: any) {
try {
const config = await readConfigYaml()
@@ -6,6 +6,7 @@ export const modelRoutes = new Router()
modelRoutes.get('/api/hermes/available-models', ctrl.getAvailable)
modelRoutes.get('/api/hermes/config/models', ctrl.getConfigModels)
modelRoutes.put('/api/hermes/config/model', ctrl.setConfigModel)
modelRoutes.put('/api/hermes/model-alias', ctrl.setModelAlias)
modelRoutes.put('/api/hermes/model-visibility', ctrl.setModelVisibility)
// Model context routes
@@ -18,6 +18,10 @@ export interface AppConfig {
// owns the provider list, system credentials are merely a fallback source.
copilotEnabled?: boolean
// Web UI-only model display aliases. Keys are provider -> canonical model ID -> display label.
// These aliases never replace the canonical model ID sent back to Hermes.
modelAliases?: Record<string, Record<string, string>>
// Web UI-only model picker visibility. This filters what the WUI exposes in
// its sidebar/model pages and never renames or rewrites Hermes canonical
// provider/model IDs. Hermes CLI config remains the upstream source of truth.
@@ -256,7 +256,7 @@ function resolveHermesAgentRoot(): string {
'/opt/hermes',
join(homedir(), '.hermes', 'hermes-agent'), // Unix/Linux/macOS
]
// Windows specific path
if (process.platform === 'win32' && process.env.LOCALAPPDATA) {
candidates.push(join(process.env.LOCALAPPDATA, 'hermes', 'hermes-agent'))
+171 -2
View File
@@ -6,6 +6,7 @@ const mockSystemApi = vi.hoisted(() => ({
checkHealth: vi.fn(),
fetchAvailableModels: vi.fn(),
updateDefaultModel: vi.fn(),
updateModelAlias: vi.fn(),
updateModelVisibility: vi.fn(),
triggerUpdate: vi.fn(),
}))
@@ -35,8 +36,6 @@ describe('App Store', () => {
expect(window.localStorage.getItem('hermes_sidebar_collapsed')).toBe('0')
})
it('loads model visibility and falls back when the configured default is hidden', async () => {
mockSystemApi.fetchAvailableModels.mockResolvedValue({
default: 'deepseek-chat',
@@ -64,10 +63,57 @@ describe('App Store', () => {
})
expect(store.selectedModel).toBe('deepseek-reasoner')
expect(store.selectedProvider).toBe('deepseek')
expect(store.customModels).toEqual({})
expect(store.isModelVisible('deepseek', 'deepseek-reasoner')).toBe(true)
expect(store.isModelVisible('deepseek', 'deepseek-chat')).toBe(false)
})
it('loads aliases while falling back from a hidden default without rehydrating it as custom', async () => {
mockSystemApi.fetchAvailableModels.mockResolvedValue({
default: 'deepseek-chat',
default_provider: 'deepseek',
groups: [
{
provider: 'deepseek',
label: 'DeepSeek',
base_url: 'https://api.deepseek.com/v1',
api_key: 'sk-test',
models: ['deepseek-reasoner'],
available_models: ['deepseek-chat', 'deepseek-reasoner'],
},
],
allProviders: [
{
provider: 'deepseek',
label: 'DeepSeek',
base_url: 'https://api.deepseek.com/v1',
api_key: 'sk-test',
models: ['deepseek-chat', 'deepseek-reasoner'],
},
],
model_aliases: {
deepseek: { 'deepseek-reasoner': 'Reasoner Alias' },
},
model_visibility: {
deepseek: { mode: 'include', models: ['deepseek-reasoner'] },
},
})
const store = useAppStore()
await store.loadModels()
expect(store.modelAliases).toEqual({
deepseek: { 'deepseek-reasoner': 'Reasoner Alias' },
})
expect(store.modelVisibility).toEqual({
deepseek: { mode: 'include', models: ['deepseek-reasoner'] },
})
expect(store.selectedModel).toBe('deepseek-reasoner')
expect(store.selectedProvider).toBe('deepseek')
expect(store.displayModelName('deepseek-reasoner', 'deepseek')).toBe('Reasoner Alias')
expect(store.customModels).toEqual({})
})
it('persists model visibility without changing the canonical selected model id', async () => {
mockSystemApi.fetchAvailableModels.mockResolvedValue({
default: 'deepseek-reasoner',
@@ -118,4 +164,127 @@ describe('App Store', () => {
expect(consoleError).toHaveBeenCalledWith('Failed to update Hermes Web UI:', expect.any(Error))
consoleError.mockRestore()
})
it('loads model aliases and resolves display names without changing canonical IDs', async () => {
mockSystemApi.fetchAvailableModels.mockResolvedValue({
default: 'deepseek-v4-flash',
default_provider: 'deepseek',
groups: [{
provider: 'deepseek',
label: 'DeepSeek',
base_url: 'https://api.deepseek.com/v1',
models: ['deepseek-v4-flash'],
api_key: '',
}],
allProviders: [],
model_aliases: {
deepseek: { 'deepseek-v4-flash': 'Flash Alias' },
},
})
const store = useAppStore()
await store.loadModels()
expect(store.selectedModel).toBe('deepseek-v4-flash')
expect(store.getModelAlias('deepseek-v4-flash', 'deepseek')).toBe('Flash Alias')
expect(store.displayModelName('deepseek-v4-flash', 'deepseek')).toBe('Flash Alias')
expect(store.displayModelName('unknown', 'deepseek')).toBe('unknown')
})
it('keeps aliases scoped to their provider when model IDs overlap', async () => {
mockSystemApi.fetchAvailableModels.mockResolvedValue({
default: 'shared-model',
default_provider: 'provider-a',
groups: [
{
provider: 'provider-a',
label: 'Provider A',
base_url: 'https://a.example/v1',
models: ['shared-model'],
api_key: '',
},
{
provider: 'provider-b',
label: 'Provider B',
base_url: 'https://b.example/v1',
models: ['shared-model'],
api_key: '',
},
],
allProviders: [],
model_aliases: {
'provider-a': { 'shared-model': 'A Alias' },
},
})
const store = useAppStore()
await store.loadModels()
expect(store.displayModelName('shared-model', 'provider-a')).toBe('A Alias')
expect(store.displayModelName('shared-model', 'provider-b')).toBe('shared-model')
expect(store.displayModelName('shared-model')).toBe('A Alias')
})
it('rehydrates an active unlisted default model as removable after loading models', async () => {
mockSystemApi.fetchAvailableModels.mockResolvedValue({
default: 'manually-supported-id',
default_provider: 'deepseek',
groups: [{
provider: 'deepseek',
label: 'DeepSeek',
base_url: 'https://api.deepseek.com/v1',
models: ['deepseek-v4-flash'],
api_key: '',
}],
allProviders: [],
model_aliases: {},
})
const store = useAppStore()
await store.loadModels()
expect(store.selectedModel).toBe('manually-supported-id')
expect(store.customModels).toEqual({ deepseek: ['manually-supported-id'] })
})
it('saves and clears model aliases via the Web UI-only alias API', async () => {
mockSystemApi.updateModelAlias.mockResolvedValue(undefined)
const store = useAppStore()
await store.setModelAlias('deepseek-v4-flash', 'deepseek', ' Flash Alias ')
expect(mockSystemApi.updateModelAlias).toHaveBeenCalledWith({
provider: 'deepseek',
model: 'deepseek-v4-flash',
alias: 'Flash Alias',
})
expect(store.modelAliases).toEqual({ deepseek: { 'deepseek-v4-flash': 'Flash Alias' } })
await store.setModelAlias('deepseek-v4-flash', 'deepseek', '')
expect(store.modelAliases).toEqual({})
})
it('removes an unlisted custom model and falls back to a listed model when active', async () => {
mockSystemApi.updateDefaultModel.mockResolvedValue(undefined)
const store = useAppStore()
store.modelGroups = [{
provider: 'deepseek',
label: 'DeepSeek',
base_url: 'https://api.deepseek.com/v1',
models: ['deepseek-v4-flash'],
api_key: '',
}]
await store.switchModel('test', 'deepseek')
expect(store.selectedModel).toBe('test')
expect(store.customModels).toEqual({ deepseek: ['test'] })
await store.removeCustomModel('test', 'deepseek')
expect(store.customModels).toEqual({})
expect(store.selectedModel).toBe('deepseek-v4-flash')
expect(mockSystemApi.updateDefaultModel).toHaveBeenLastCalledWith({
default: 'deepseek-v4-flash',
provider: 'deepseek',
})
})
})
+130
View File
@@ -0,0 +1,130 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
const { mockReadAppConfig, mockWriteAppConfig } = vi.hoisted(() => ({
mockReadAppConfig: vi.fn(),
mockWriteAppConfig: vi.fn(),
}))
vi.mock('../../packages/server/src/services/app-config', () => ({
readAppConfig: mockReadAppConfig,
writeAppConfig: mockWriteAppConfig,
}))
vi.mock('../../packages/server/src/services/config-helpers', () => ({
readConfigYaml: vi.fn(),
writeConfigYaml: vi.fn(),
fetchProviderModels: vi.fn(),
buildModelGroups: vi.fn(() => ({ default: '', default_provider: '', groups: [] })),
PROVIDER_ENV_MAP: {},
}))
vi.mock('../../packages/server/src/shared/providers', () => ({
buildProviderModelMap: vi.fn(() => ({})),
PROVIDER_PRESETS: [],
}))
vi.mock('../../packages/server/src/services/hermes/copilot-models', () => ({
getCopilotModelsDetailed: vi.fn(),
resolveCopilotOAuthToken: vi.fn(),
}))
vi.mock('../../packages/server/src/db', () => ({
getDb: vi.fn(),
}))
vi.mock('../../packages/server/src/db/hermes/schemas', () => ({
MODEL_CONTEXT_TABLE: 'model_context',
}))
import { setModelAlias } from '../../packages/server/src/controllers/hermes/models'
describe('model alias controller', () => {
beforeEach(() => {
vi.clearAllMocks()
mockWriteAppConfig.mockResolvedValue({})
})
function createCtx(body: unknown) {
return {
request: { body },
status: 200,
body: undefined as unknown,
}
}
it('saves a trimmed alias in Web UI app config', async () => {
mockReadAppConfig.mockResolvedValue({
modelAliases: {
deepseek: { old: 'Old Alias' },
},
})
const ctx = createCtx({ provider: 'deepseek', model: 'deepseek-v4-flash', alias: ' Flash Alias ' })
await setModelAlias(ctx)
expect(mockWriteAppConfig).toHaveBeenCalledWith({
modelAliases: {
deepseek: {
old: 'Old Alias',
'deepseek-v4-flash': 'Flash Alias',
},
},
})
expect(ctx.body).toEqual({
success: true,
model_aliases: {
deepseek: {
old: 'Old Alias',
'deepseek-v4-flash': 'Flash Alias',
},
},
})
})
it('deletes an alias when alias is blank and removes empty provider entries', async () => {
mockReadAppConfig.mockResolvedValue({
modelAliases: {
deepseek: { 'deepseek-v4-flash': 'Flash Alias' },
},
})
const ctx = createCtx({ provider: 'deepseek', model: 'deepseek-v4-flash', alias: ' ' })
await setModelAlias(ctx)
expect(mockWriteAppConfig).toHaveBeenCalledWith({ modelAliases: {} })
expect(ctx.body).toEqual({ success: true, model_aliases: {} })
})
it('rejects missing provider or model', async () => {
const ctx = createCtx({ provider: 'deepseek', alias: 'Alias' })
await setModelAlias(ctx)
expect(ctx.status).toBe(400)
expect(ctx.body).toEqual({ error: 'Invalid provider, model, or alias' })
expect(mockWriteAppConfig).not.toHaveBeenCalled()
})
it('stores inherited Object.prototype names as own alias keys', async () => {
mockReadAppConfig.mockResolvedValue({})
const ctx = createCtx({ provider: 'toString', model: 'valueOf', alias: 'Safe Alias' })
await setModelAlias(ctx)
const written = mockWriteAppConfig.mock.calls[0][0]
expect(written.modelAliases.toString.valueOf).toBe('Safe Alias')
expect(Object.prototype.hasOwnProperty.call(written.modelAliases, 'toString')).toBe(true)
expect(Object.prototype.hasOwnProperty.call(written.modelAliases.toString, 'valueOf')).toBe(true)
})
it('rejects reserved object keys to avoid prototype pollution', async () => {
const ctx = createCtx({ provider: '__proto__', model: 'deepseek-v4-flash', alias: 'Alias' })
await setModelAlias(ctx)
expect(ctx.status).toBe(400)
expect(ctx.body).toEqual({ error: 'Invalid provider or model' })
expect(mockWriteAppConfig).not.toHaveBeenCalled()
expect(({} as Record<string, unknown>).deepseek).toBeUndefined()
})
})
@@ -1,12 +1,14 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
const { mockReadFile, mockReadConfigYaml, mockFetchProviderModels, mockBuildModelGroups, mockReadAppConfig, mockWriteAppConfig } = vi.hoisted(() => ({
const { mockReadFile, mockReadConfigYaml, mockFetchProviderModels, mockBuildModelGroups, mockReadAppConfig, mockWriteAppConfig, mockExistsSync, mockReadFileSync } = vi.hoisted(() => ({
mockReadFile: vi.fn(),
mockReadConfigYaml: vi.fn(),
mockFetchProviderModels: vi.fn(),
mockBuildModelGroups: vi.fn(() => ({ default: '', groups: [] })),
mockReadAppConfig: vi.fn(),
mockWriteAppConfig: vi.fn(),
mockExistsSync: vi.fn(() => false),
mockReadFileSync: vi.fn(),
}))
vi.mock('fs/promises', () => ({
@@ -14,8 +16,8 @@ vi.mock('fs/promises', () => ({
}))
vi.mock('fs', () => ({
existsSync: vi.fn(() => false),
readFileSync: vi.fn(),
existsSync: mockExistsSync,
readFileSync: mockReadFileSync,
}))
vi.mock('../../packages/server/src/services/hermes/hermes-profile', () => ({
@@ -30,12 +32,14 @@ vi.mock('../../packages/server/src/services/config-helpers', () => ({
buildModelGroups: mockBuildModelGroups,
PROVIDER_ENV_MAP: {
deepseek: { api_key_env: 'DEEPSEEK_API_KEY' },
openrouter: {},
},
}))
vi.mock('../../packages/server/src/shared/providers', () => ({
buildProviderModelMap: () => ({
deepseek: ['deepseek-chat', 'deepseek-reasoner'],
openrouter: ['openrouter/auto'],
}),
PROVIDER_PRESETS: [
{
@@ -44,6 +48,12 @@ vi.mock('../../packages/server/src/shared/providers', () => ({
base_url: 'https://api.deepseek.com/v1',
models: ['deepseek-chat', 'deepseek-reasoner'],
},
{
value: 'openrouter',
label: 'OpenRouter',
base_url: 'https://openrouter.ai/api/v1',
models: ['openrouter/auto'],
},
],
}))
@@ -78,6 +88,8 @@ beforeEach(() => {
mockBuildModelGroups.mockReturnValue({ default: '', groups: [] })
mockReadAppConfig.mockResolvedValue({})
mockWriteAppConfig.mockImplementation(async patch => patch)
mockExistsSync.mockReturnValue(false)
mockReadFileSync.mockReturnValue('{}')
})
describe('models controller — model visibility', () => {
@@ -104,6 +116,27 @@ describe('models controller — model visibility', () => {
deepseek: { mode: 'include', models: ['deepseek-reasoner'] },
})
})
it('accepts OAuth providers stored in credential_pool entries', async () => {
mockExistsSync.mockReturnValue(true)
mockReadFileSync.mockReturnValue(JSON.stringify({
credential_pool: {
openrouter: [{ label: 'primary', access_token: 'oauth-token' }],
},
}))
const ctx = makeCtx()
await ctrl.getAvailable(ctx)
expect(ctx.status).toBe(200)
expect(ctx.body.groups).toEqual(expect.arrayContaining([
expect.objectContaining({
provider: 'openrouter',
label: 'OpenRouter',
models: ['openrouter/auto'],
available_models: ['openrouter/auto'],
}),
]))
})