Add session-level bridge model settings (#811)

This commit is contained in:
ekko
2026-05-17 12:20:53 +08:00
committed by GitHub
parent fa035f348e
commit 5e8f8bd4a1
35 changed files with 697 additions and 60 deletions
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "hermes-web-ui",
"version": "0.5.26",
"version": "0.5.27",
"description": "Self-hosted AI chat dashboard for Hermes Agent — multi-model web UI with multi-platform integration",
"repository": {
"type": "git",
+2
View File
@@ -16,6 +16,8 @@ export interface StartRunRequest {
instructions?: string
session_id?: string
model?: string
provider?: string
model_groups?: Array<{ provider: string; models: string[] }>
queue_id?: string
source?: 'api_server' | 'cli'
}
@@ -4,6 +4,7 @@ export interface ConversationSummary {
id: string
source: string
model: string
provider?: string
title: string | null
started_at: number
ended_at: number | null
@@ -4,6 +4,7 @@ export interface SessionSummary {
id: string
source: string
model: string
provider?: string
title: string | null
preview?: string
started_at: number
@@ -147,6 +148,18 @@ export async function setSessionWorkspace(id: string, workspace: string | null):
}
}
export async function setSessionModel(id: string, model: string, provider: string): Promise<boolean> {
try {
await request(`/api/hermes/sessions/${id}/model`, {
method: 'POST',
body: JSON.stringify({ model, provider }),
})
return true
} catch {
return false
}
}
export async function exportSession(id: string, mode: 'full' | 'compressed' = 'full', ext: 'json' | 'txt' = 'json'): Promise<void> {
const baseUrl = getBaseUrlValue()
const token = getApiKey()
@@ -1,15 +1,18 @@
<script setup lang="ts">
import { renameSession, setSessionWorkspace, batchDeleteSessions, exportSession } from "@/api/hermes/sessions";
import { useChatStore, type Session } from "@/stores/hermes/chat";
import { useAppStore } from "@/stores/hermes/app";
import { useSessionBrowserPrefsStore } from "@/stores/hermes/session-browser-prefs";
import {
NButton,
NDropdown,
NInput,
NModal,
NSelect,
NTooltip,
NPopconfirm,
useMessage,
type DropdownOption,
} from "naive-ui";
import { computed, nextTick, onMounted, onUnmounted, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
@@ -23,6 +26,7 @@ import SessionListItem from "./SessionListItem.vue";
import DrawerPanel from "./DrawerPanel.vue";
const chatStore = useChatStore();
const appStore = useAppStore();
const sessionBrowserPrefsStore = useSessionBrowserPrefsStore();
const message = useMessage();
const { t } = useI18n();
@@ -331,15 +335,25 @@ const contextSessionPinned = computed(() =>
? sessionBrowserPrefsStore.isPinned(contextSessionId.value)
: false,
);
const contextSession = computed(() =>
contextSessionId.value
? chatStore.sessions.find((session) => session.id === contextSessionId.value) || null
: null,
);
const contextMenuOptions = computed(() => [
{
const contextMenuOptions = computed(() => {
const options: DropdownOption[] = [{
label: t(contextSessionPinned.value ? "chat.unpin" : "chat.pin"),
key: "pin",
},
{ label: t("chat.rename"), key: "rename" },
{ label: t("chat.setWorkspace"), key: "workspace" },
{
{ label: t("chat.setWorkspace"), key: "workspace" }]
if (contextSession.value?.source === "cli") {
options.push({ label: t("chat.setModel"), key: "model" })
}
options.push({
label: t("chat.export"),
key: "export",
children: [
@@ -360,9 +374,10 @@ const contextMenuOptions = computed(() => [
],
},
],
},
{ label: t("chat.copySessionId"), key: "copy-id" },
]);
})
options.push({ label: t("chat.copySessionId"), key: "copy-id" })
return options
});
function handleContextMenu(e: MouseEvent, sessionId: string) {
e.preventDefault();
@@ -411,6 +426,8 @@ async function handleContextMenuSelect(key: string) {
workspaceSessionId.value = contextSessionId.value;
workspaceValue.value = session?.workspace || "";
showWorkspaceModal.value = true;
} else if (key === "model") {
openSessionModelModal(contextSessionId.value);
} else if (key === "rename") {
const session = chatStore.sessions.find(
(s) => s.id === contextSessionId.value,
@@ -473,6 +490,98 @@ async function handleWorkspaceConfirm() {
}
showWorkspaceModal.value = false;
}
const showSessionModelModal = ref(false);
const sessionModelSessionId = ref<string | null>(null);
const sessionModelSearch = ref("");
const sessionModelCollapsedGroups = ref<Record<string, boolean>>({});
const sessionModelValue = ref("");
const sessionModelProvider = ref("");
const sessionModelCustomInput = ref("");
const sessionModelCustomProvider = ref("");
const sessionModelProviderOptions = computed(() =>
appStore.modelGroups.map((group) => ({ label: group.label, value: group.provider })),
);
const sessionModelGroupsWithCustom = computed(() =>
appStore.modelGroups.map((group) => ({
...group,
models: [
...group.models,
...(appStore.customModels[group.provider] || []).filter(
(model) => !group.models.includes(model),
),
],
})),
);
const filteredSessionModelGroups = computed(() => {
const query = sessionModelSearch.value.trim().toLowerCase();
if (!query) return sessionModelGroupsWithCustom.value;
return sessionModelGroupsWithCustom.value
.map((group) => ({
...group,
models: group.models.filter((model) => {
const displayName = appStore.displayModelName(model, group.provider);
return model.toLowerCase().includes(query) || displayName.toLowerCase().includes(query);
}),
}))
.filter((group) => group.models.length > 0 || group.label.toLowerCase().includes(query));
});
function openSessionModelModal(sessionId: string) {
const session = chatStore.sessions.find((s) => s.id === sessionId);
sessionModelSessionId.value = sessionId;
sessionModelValue.value = session?.model || appStore.selectedModel || "";
sessionModelProvider.value = session?.provider || appStore.selectedProvider || "";
sessionModelCustomProvider.value = sessionModelProvider.value;
sessionModelSearch.value = "";
sessionModelCustomInput.value = "";
sessionModelCollapsedGroups.value = {};
showSessionModelModal.value = true;
}
function isSessionModelGroupCollapsed(provider: string) {
return !!sessionModelCollapsedGroups.value[provider];
}
function toggleSessionModelGroup(provider: string) {
sessionModelCollapsedGroups.value[provider] = !sessionModelCollapsedGroups.value[provider];
}
function isCustomSessionModel(model: string, provider: string) {
return (appStore.customModels[provider] || []).includes(model);
}
function sessionModelDisplayName(model: string, provider: string) {
return appStore.displayModelName(model, provider);
}
function sessionModelAlias(model: string, provider: string) {
return appStore.getModelAlias(model, provider);
}
async function selectSessionModel(model: string, provider: string) {
const meta = appStore.modelGroups.find((group) => group.provider === provider)?.model_meta?.[model];
if (meta?.disabled || !sessionModelSessionId.value) return;
const ok = await chatStore.switchSessionModel(model, provider, sessionModelSessionId.value);
if (ok) {
sessionModelValue.value = model;
sessionModelProvider.value = provider;
showSessionModelModal.value = false;
message.success(t("chat.modelSet"));
} else {
message.error(t("chat.modelSetFailed"));
}
}
async function handleSessionModelCustomSubmit() {
const model = sessionModelCustomInput.value.trim();
const provider = sessionModelCustomProvider.value;
if (!model || !provider) return;
await selectSessionModel(model, provider);
}
</script>
<template>
@@ -737,6 +846,104 @@ async function handleWorkspaceConfirm() {
<FolderPicker v-model="workspaceValue" />
</NModal>
<NModal
v-model:show="showSessionModelModal"
preset="card"
:title="t('chat.setModelTitle')"
:style="{ width: 'min(480px, calc(100vw - 32px))' }"
:mask-closable="true"
>
<NInput
v-model:value="sessionModelSearch"
:placeholder="t('models.searchPlaceholder')"
clearable
size="small"
class="session-model-search"
/>
<div class="session-model-list">
<div v-for="group in filteredSessionModelGroups" :key="group.provider" class="session-model-group">
<div class="session-model-group-header" @click="toggleSessionModelGroup(group.provider)">
<svg
class="session-model-group-arrow"
:class="{ collapsed: isSessionModelGroupCollapsed(group.provider) }"
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>
<span class="session-model-group-label">{{ group.label }}</span>
<span class="session-model-group-count">{{ group.models.length }}</span>
</div>
<div v-show="!isSessionModelGroupCollapsed(group.provider)" class="session-model-group-items">
<div
v-for="model in group.models"
:key="model"
class="session-model-item"
:class="{
active: model === sessionModelValue && group.provider === sessionModelProvider,
disabled: !!group.model_meta?.[model]?.disabled,
}"
:title="group.model_meta?.[model]?.disabled ? t('models.disabledTooltip') : ''"
@click="selectSessionModel(model, group.provider)"
>
<span class="session-model-item-label">
<span class="session-model-item-name">{{ sessionModelDisplayName(model, group.provider) }}</span>
<span v-if="sessionModelAlias(model, group.provider)" class="session-model-item-id">
{{ t('models.aliasCanonical', { model }) }}
</span>
</span>
<span v-if="group.model_meta?.[model]?.preview" class="session-model-badge-preview">{{ t('models.previewBadge') }}</span>
<span v-if="group.model_meta?.[model]?.disabled" class="session-model-badge-disabled">{{ t('models.disabledBadge') }}</span>
<span v-if="isCustomSessionModel(model, group.provider)" class="session-model-badge-custom">{{ t('models.customBadge') }}</span>
<svg
v-if="model === sessionModelValue && group.provider === sessionModelProvider"
class="session-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>
</div>
</div>
</div>
<div v-if="filteredSessionModelGroups.length === 0" class="session-model-empty">
{{ sessionModelSearch ? 'No results' : 'No models' }}
</div>
<div class="session-model-custom">
<div class="session-model-custom-row">
<NSelect
v-model:value="sessionModelCustomProvider"
:options="sessionModelProviderOptions"
size="small"
class="session-model-custom-provider"
/>
<NInput
v-model:value="sessionModelCustomInput"
:placeholder="t('models.customModelPlaceholder')"
size="small"
class="session-model-custom-input"
@keydown.enter="handleSessionModelCustomSubmit"
/>
</div>
<div class="session-model-custom-hint">
{{ t('models.customModelHint') }}
</div>
</div>
</div>
</NModal>
<div class="chat-main">
<header class="chat-header">
<div class="header-left">
@@ -935,6 +1142,186 @@ async function handleWorkspaceConfirm() {
position: relative;
}
.session-model-search {
margin-bottom: 12px;
}
.session-model-list {
max-height: 50vh;
overflow-y: auto;
scrollbar-width: thin;
}
.session-model-group {
margin-bottom: 4px;
}
.session-model-group-header {
display: flex;
align-items: center;
gap: 6px;
padding: 8px;
font-size: 12px;
font-weight: 600;
color: $text-secondary;
cursor: pointer;
border-radius: $radius-sm;
user-select: none;
transition: background-color $transition-fast;
&:hover {
background-color: $bg-secondary;
}
}
.session-model-group-arrow {
flex-shrink: 0;
transition: transform $transition-fast;
&.collapsed {
transform: rotate(-90deg);
}
}
.session-model-group-label {
flex: 1;
}
.session-model-group-count {
font-size: 11px;
color: $text-muted;
font-weight: 400;
}
.session-model-group-items {
padding-left: 8px;
}
.session-model-item {
display: flex;
align-items: center;
gap: 8px;
padding: 7px 10px;
font-size: 13px;
color: $text-secondary;
border-radius: $radius-sm;
cursor: pointer;
transition: all $transition-fast;
&:hover {
background-color: rgba(var(--accent-primary-rgb), 0.06);
color: $text-primary;
}
&.active {
color: $accent-primary;
font-weight: 500;
}
&.disabled {
opacity: 0.45;
cursor: not-allowed;
&:hover {
background-color: transparent;
color: $text-secondary;
}
}
}
.session-model-item-label {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
gap: 2px;
}
.session-model-item-name,
.session-model-item-id {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-family: $font-code;
}
.session-model-item-name {
font-size: 12px;
}
.session-model-item-id {
color: $text-muted;
font-size: 10px;
font-weight: 400;
}
.session-model-check {
flex-shrink: 0;
color: $accent-primary;
}
.session-model-badge-preview,
.session-model-badge-custom,
.session-model-badge-disabled {
flex-shrink: 0;
font-size: 9px;
font-weight: 600;
padding: 1px 5px;
border-radius: 3px;
margin-right: 4px;
letter-spacing: 0.03em;
}
.session-model-badge-preview {
color: #fff;
background: #d97706;
}
.session-model-badge-custom {
color: #fff;
background: $accent-primary;
}
.session-model-badge-disabled {
color: $text-muted;
background: transparent;
border: 1px solid $border-color;
padding: 0 5px;
}
.session-model-empty {
padding: 24px 0;
text-align: center;
font-size: 13px;
color: $text-muted;
}
.session-model-custom {
margin-top: 12px;
padding-top: 12px;
border-top: 1px solid $border-color;
}
.session-model-custom-row {
display: flex;
gap: 8px;
}
.session-model-custom-provider {
width: 160px;
flex-shrink: 0;
}
.session-model-custom-input {
flex: 1;
}
.session-model-custom-hint {
margin-top: 6px;
font-size: 11px;
color: $text-muted;
}
.session-list {
width: 220px;
border-right: 1px solid $border-color;
@@ -1,11 +1,13 @@
<script setup lang="ts">
import { fetchConversationDetail, fetchConversationSummaries, type ConversationDetail, type ConversationSummary } from '@/api/hermes/conversations'
import { formatTimestampSeconds, getSourceLabel } from '@/shared/session-display'
import { useAppStore } from '@/stores/hermes/app'
import { computed, onMounted, onUnmounted, ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'
const props = defineProps<{ humanOnly: boolean }>()
const { t } = useI18n()
const appStore = useAppStore()
const POLL_INTERVAL_MS = 15000
@@ -20,6 +22,11 @@ let sessionsRequestId = 0
let detailRequestId = 0
const selectedSession = computed(() => sessions.value.find(session => session.id === selectedSessionId.value) || null)
const selectedSessionModelName = computed(() =>
selectedSession.value?.model
? appStore.displayModelName(selectedSession.value.model, selectedSession.value.provider)
: '',
)
function roleLabel(role: string): string {
return role === 'user' ? t('chat.monitorRoleUser') : t('chat.monitorRoleAssistant')
@@ -153,7 +160,7 @@ onUnmounted(() => {
<div class="conversation-monitor__detail-meta">
<span>{{ getSourceLabel(selectedSession.source) }}</span>
<span>·</span>
<span>{{ selectedSession.model }}</span>
<span :title="selectedSession.model">{{ selectedSessionModelName }}</span>
<span>·</span>
<span>{{ linkedSessionsLabel(selectedSession.thread_session_count) }}</span>
</div>
@@ -1,8 +1,9 @@
<script setup lang="ts">
import { ref, onUnmounted } from 'vue'
import { computed, ref, onUnmounted } from 'vue'
import { NPopconfirm, NCheckbox } from 'naive-ui'
import { useI18n } from 'vue-i18n'
import type { Session } from '@/stores/hermes/chat'
import { useAppStore } from '@/stores/hermes/app'
import { formatTimestampMs } from '@/shared/session-display'
const props = defineProps<{
@@ -23,6 +24,12 @@ const emit = defineEmits<{
}>()
const { t } = useI18n()
const appStore = useAppStore()
const sessionModelName = computed(() =>
props.session.model
? appStore.displayModelName(props.session.model, props.session.provider)
: '',
)
let longPressTimer: ReturnType<typeof setTimeout> | null = null
const longPressTriggered = ref(false)
@@ -97,7 +104,7 @@ onUnmounted(() => {
</span>
</span>
<span class="session-item-meta">
<span v-if="session.model" class="session-item-model">{{ session.model }}</span>
<span v-if="sessionModelName" class="session-item-model" :title="session.model">{{ sessionModelName }}</span>
<span class="session-item-time">{{ formatTimestampMs(session.createdAt) }}</span>
</span>
</div>
@@ -130,7 +130,7 @@ async function handleDelete() {
// 服务端会在默认模型属于 copilot 时清掉 model.default,这里再清理本地
// 会话级 model/provider,避免 Chat 页继续显示已下架的 copilot 模型。
chatStore.clearProviderFromSessions('copilot')
await Promise.all([modelsStore.fetchProviders(), appStore.loadModels()])
await modelsStore.fetchProviders()
} else {
await modelsStore.removeProvider(props.provider.provider)
}
+10
View File
@@ -5,6 +5,16 @@ export interface ChangelogEntry {
}
export const changelog: ChangelogEntry[] = [
{
version: '0.5.27',
date: '2026-05-17',
changes: [
'changelog.new_0_5_27_1',
'changelog.new_0_5_27_2',
'changelog.new_0_5_27_3',
'changelog.new_0_5_27_4',
],
},
{
version: '0.5.26',
date: '2026-05-17',
+4
View File
@@ -932,6 +932,10 @@ jobTriggered: 'Job ausgelost',
new_0_5_26_10: 'Support Hermes Agent package installs when no source checkout is available',
new_0_5_26_11: 'Add xAI Grok OAuth login for SuperGrok subscription users and update Grok model presets',
new_0_5_26_12: 'Expand browser, chat streaming, provider, gateway, config, plugin, and Bridge test coverage',
new_0_5_27_1: 'Add session-level model settings for Bridge chats, with independent provider and model saved per session',
new_0_5_27_2: 'Right-click a Bridge session and choose Set Model to switch the model for that session',
new_0_5_27_3: 'Runs now validate the session model and fall back to the current default model when the saved model is unavailable',
new_0_5_27_4: 'Context compression now follows the current Profile default selected model by default',
new_0_5_5_1: '🎉 Tag der Arbeit! Heute wird nicht gearbeitet, bitte habt Verständnis',
new_0_5_5_2: 'Verlaufsseite für Hermes-Sitzungshistorie hinzugefügt',
new_0_5_5_3: 'Verlaufsseite verwaltet Sitzungen unabhängig ohne Störung des aktiven Chats',
+8
View File
@@ -226,6 +226,10 @@ export default {
workspacePlaceholder: 'Enter project path, e.g. /home/user/project',
workspaceSet: 'Workspace set',
workspaceSetFailed: 'Failed to set workspace',
setModel: 'Set Model',
setModelTitle: 'Set Session Model',
modelSet: 'Model set',
modelSetFailed: 'Failed to set model',
other: 'Other',
runFailed: 'Run failed',
error: 'Error',
@@ -1224,6 +1228,10 @@ export default {
new_0_5_26_10: 'Support Hermes Agent package installs when no source checkout is available',
new_0_5_26_11: 'Add xAI Grok OAuth login for SuperGrok subscription users and update Grok model presets',
new_0_5_26_12: 'Expand browser, chat streaming, provider, gateway, config, plugin, and Bridge test coverage',
new_0_5_27_1: 'Add session-level model settings for Bridge chats, with independent provider and model saved per session',
new_0_5_27_2: 'Right-click a Bridge session and choose Set Model to switch the model for that session',
new_0_5_27_3: 'Runs now validate the session model and fall back to the current default model when the saved model is unavailable',
new_0_5_27_4: 'Context compression now follows the current Profile default selected model by default',
new_0_5_6_1: 'Add voice playback feature with Web Speech API: manual button, auto-play toggle, rainbow border animation, and mobile optimization',
new_0_5_6_2: 'Add robust LLM JSON parser with tolerance for Python format and extract text from streaming events',
+4
View File
@@ -928,6 +928,10 @@ jobTriggered: 'Job ejecutado',
new_0_5_26_10: 'Support Hermes Agent package installs when no source checkout is available',
new_0_5_26_11: 'Add xAI Grok OAuth login for SuperGrok subscription users and update Grok model presets',
new_0_5_26_12: 'Expand browser, chat streaming, provider, gateway, config, plugin, and Bridge test coverage',
new_0_5_27_1: 'Add session-level model settings for Bridge chats, with independent provider and model saved per session',
new_0_5_27_2: 'Right-click a Bridge session and choose Set Model to switch the model for that session',
new_0_5_27_3: 'Runs now validate the session model and fall back to the current default model when the saved model is unavailable',
new_0_5_27_4: 'Context compression now follows the current Profile default selected model by default',
new_0_5_5_1: '🎉 ¡Feliz Día del Trabajo! Hoy no se trabaja, agradezcan su comprensión',
new_0_5_5_2: 'Añadida página de historial para sesiones Hermes',
new_0_5_5_3: 'La página de historial gestiona sesiones de forma independiente',
+4
View File
@@ -927,6 +927,10 @@ jobTriggered: 'Job declenche',
new_0_5_26_10: 'Support Hermes Agent package installs when no source checkout is available',
new_0_5_26_11: 'Add xAI Grok OAuth login for SuperGrok subscription users and update Grok model presets',
new_0_5_26_12: 'Expand browser, chat streaming, provider, gateway, config, plugin, and Bridge test coverage',
new_0_5_27_1: 'Add session-level model settings for Bridge chats, with independent provider and model saved per session',
new_0_5_27_2: 'Right-click a Bridge session and choose Set Model to switch the model for that session',
new_0_5_27_3: 'Runs now validate the session model and fall back to the current default model when the saved model is unavailable',
new_0_5_27_4: 'Context compression now follows the current Profile default selected model by default',
new_0_5_5_1: '🎉 Joyeuse Fête du Travail! Pas de travail aujourd\'hui, merci de votre compréhension',
new_0_5_5_2: 'Ajout d\'une page d\'historique pour les sessions Hermes',
new_0_5_5_3: 'La page d\'historique gère les sessions de manière indépendante',
+4
View File
@@ -928,6 +928,10 @@ export default {
new_0_5_26_10: 'Support Hermes Agent package installs when no source checkout is available',
new_0_5_26_11: 'Add xAI Grok OAuth login for SuperGrok subscription users and update Grok model presets',
new_0_5_26_12: 'Expand browser, chat streaming, provider, gateway, config, plugin, and Bridge test coverage',
new_0_5_27_1: 'Add session-level model settings for Bridge chats, with independent provider and model saved per session',
new_0_5_27_2: 'Right-click a Bridge session and choose Set Model to switch the model for that session',
new_0_5_27_3: 'Runs now validate the session model and fall back to the current default model when the saved model is unavailable',
new_0_5_27_4: 'Context compression now follows the current Profile default selected model by default',
new_0_5_5_1: '🎉 労働者の日!今日はお休みです、何卒ご理解ください',
new_0_5_5_2: 'Hermesセッション履歴ページを追加',
new_0_5_5_3: '履歴ページはアクティブチャットに干渉せずにセッション管理',
+4
View File
@@ -928,6 +928,10 @@ export default {
new_0_5_26_10: 'Support Hermes Agent package installs when no source checkout is available',
new_0_5_26_11: 'Add xAI Grok OAuth login for SuperGrok subscription users and update Grok model presets',
new_0_5_26_12: 'Expand browser, chat streaming, provider, gateway, config, plugin, and Bridge test coverage',
new_0_5_27_1: 'Add session-level model settings for Bridge chats, with independent provider and model saved per session',
new_0_5_27_2: 'Right-click a Bridge session and choose Set Model to switch the model for that session',
new_0_5_27_3: 'Runs now validate the session model and fall back to the current default model when the saved model is unavailable',
new_0_5_27_4: 'Context compression now follows the current Profile default selected model by default',
new_0_5_5_1: '🎉 노동절 감사합니다! 오늘은 쉬니까 양해 부탁드립니다',
new_0_5_5_2: 'Hermes 세션 기록 페이지 추가',
new_0_5_5_3: '기록 페이지는 독립적으로 세션 관리',
+4
View File
@@ -928,6 +928,10 @@ jobTriggered: 'Job acionado',
new_0_5_26_10: 'Support Hermes Agent package installs when no source checkout is available',
new_0_5_26_11: 'Add xAI Grok OAuth login for SuperGrok subscription users and update Grok model presets',
new_0_5_26_12: 'Expand browser, chat streaming, provider, gateway, config, plugin, and Bridge test coverage',
new_0_5_27_1: 'Add session-level model settings for Bridge chats, with independent provider and model saved per session',
new_0_5_27_2: 'Right-click a Bridge session and choose Set Model to switch the model for that session',
new_0_5_27_3: 'Runs now validate the session model and fall back to the current default model when the saved model is unavailable',
new_0_5_27_4: 'Context compression now follows the current Profile default selected model by default',
new_0_5_5_1: '🎉 Feliz Dia do Trabalhador! Hoje não se trabalha, obrigado pela compreensão',
new_0_5_5_2: 'Adicionada página de histórico para sessões Hermes',
new_0_5_5_3: 'Página de histórico gerencia sessões de forma independente',
@@ -1221,6 +1221,10 @@ export default {
new_0_5_26_10: '支援未找到原始碼目錄時使用套件安裝的 Hermes Agent',
new_0_5_26_11: '新增 xAI Grok OAuth 登入,支援 SuperGrok 訂閱使用者授權,並更新 Grok 模型預設',
new_0_5_26_12: '擴展瀏覽器、聊天串流、Provider、Gateway、設定、外掛和 Bridge 測試覆蓋',
new_0_5_27_1: '新增 Bridge 工作階段級模型設定,每個工作階段可獨立保存 provider 和 model',
new_0_5_27_2: '在 Bridge 工作階段列表中右鍵工作階段,選擇「設定模型」即可為目前工作階段切換模型',
new_0_5_27_3: '執行時會自動校驗工作階段模型是否可用;不可用時回退到目前預設模型並更新工作階段',
new_0_5_27_4: '上下文壓縮預設跟隨目前 Profile 的預設選中模型',
new_0_5_6_1: '新增語音播放功能:使用 Web Speech API,支援手動播放按鈕、自動播放開關、彩虹邊框動畫和行動端最佳化',
new_0_5_6_2: '新增強健的 LLM JSON 解析器,相容 Python 格式並從串流事件中擷取文字',
new_0_5_6_3: 'Skills 功能增強:使用統計、來源過濾、封存技能、來源追溯和釘選切換',
+8
View File
@@ -226,6 +226,10 @@ export default {
workspacePlaceholder: '输入项目路径,例如 /home/user/project',
workspaceSet: '工作区已设置',
workspaceSetFailed: '设置工作区失败',
setModel: '设置模型',
setModelTitle: '设置会话模型',
modelSet: '模型已设置',
modelSetFailed: '设置模型失败',
other: '其他',
runFailed: '运行失败',
error: '错误',
@@ -1226,6 +1230,10 @@ export default {
new_0_5_26_10: '支持未找到源码目录时使用包安装的 Hermes Agent',
new_0_5_26_11: '新增 xAI Grok OAuth 登录,支持 SuperGrok 订阅用户授权,并更新 Grok 模型预设',
new_0_5_26_12: '扩展浏览器、聊天流式、Provider、Gateway、配置、插件和 Bridge 测试覆盖',
new_0_5_27_1: '新增 Bridge 会话级模型设置,每个会话可以独立保存 provider 和 model',
new_0_5_27_2: '在 Bridge 会话列表中右键会话,选择“设置模型”即可为当前会话切换模型',
new_0_5_27_3: '运行时会自动校验会话模型是否可用;不可用时回退到当前默认模型并更新会话',
new_0_5_27_4: '上下文压缩默认跟随当前 Profile 的默认选中模型',
new_0_5_6_1: '新增语音播放功能:使用 Web Speech API,支持手动播放按钮、自动播放开关、彩虹边框动画和移动端优化',
new_0_5_6_2: '新增健壮的 LLM JSON 解析器,兼容 Python 格式并从流式事件中提取文本',
+24 -8
View File
@@ -17,6 +17,7 @@ import { hasApiKey } from '@/api/client'
const WEB_UI_VERSION = __APP_VERSION__
const SIDEBAR_COLLAPSED_KEY = 'hermes_sidebar_collapsed'
const MODELS_CACHE_TTL_MS = 30000
export const useAppStore = defineStore('app', () => {
const sidebarOpen = ref(false)
@@ -42,6 +43,8 @@ export const useAppStore = defineStore('app', () => {
const streamEnabled = ref(true)
const sessionPersistence = ref(true)
const maxTokens = ref(4096)
let modelsLoadPromise: Promise<void> | null = null
let modelsLoadedAt = 0
async function doUpdate(): Promise<boolean> {
updating.value = true
@@ -128,14 +131,26 @@ export const useAppStore = defineStore('app', () => {
}
}
async function loadModels() {
async function loadModels(force = false) {
if (!hasApiKey()) return
try {
const res = await fetchAvailableModels()
applyAvailableModelsResponse(res)
} catch {
// ignore
}
if (!force && modelsLoadPromise) return modelsLoadPromise
if (!force && modelGroups.value.length > 0 && Date.now() - modelsLoadedAt < MODELS_CACHE_TTL_MS) return
modelsLoadPromise = (async () => {
try {
const res = await fetchAvailableModels()
applyAvailableModelsResponse(res)
modelsLoadedAt = Date.now()
} catch {
// ignore
} finally {
modelsLoadPromise = null
}
})()
return modelsLoadPromise
}
async function reloadModels() {
return loadModels(true)
}
function getModelAlias(modelId: string, provider?: string): string {
@@ -220,7 +235,7 @@ export const useAppStore = defineStore('app', () => {
async function setModelVisibility(provider: string, rule: ModelVisibilityRule) {
const res = await updateModelVisibility({ provider, mode: rule.mode, models: rule.models })
modelVisibility.value = res.model_visibility || {}
await loadModels()
await reloadModels()
}
function startHealthPolling(interval = 30000) {
@@ -285,6 +300,7 @@ export const useAppStore = defineStore('app', () => {
maxTokens,
checkConnection,
loadModels,
reloadModels,
applyAvailableModelsResponse,
switchModel,
removeCustomModel,
+27 -12
View File
@@ -1,5 +1,5 @@
import { startRunViaSocket, resumeSession, registerSessionHandlers, unregisterSessionHandlers, getChatRunSocket, respondToolApproval, type RunEvent, type ContentBlock as ContentBlockImport } from '@/api/hermes/chat'
import { deleteSession as deleteSessionApi, fetchSession, fetchSessions, type HermesMessage, type SessionSummary } from '@/api/hermes/sessions'
import { deleteSession as deleteSessionApi, fetchSession, fetchSessions, setSessionModel, type HermesMessage, type SessionSummary } from '@/api/hermes/sessions'
import { getApiKey } from '@/api/client'
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
@@ -238,7 +238,7 @@ function mapHermesSession(s: SessionSummary): Session {
createdAt: Math.round(s.started_at * 1000),
updatedAt: Math.round((s.last_active || s.ended_at || s.started_at) * 1000),
model: s.model,
provider: (s as any).billing_provider || '',
provider: s.provider || (s as any).billing_provider || '',
messageCount: s.message_count,
endedAt: s.ended_at != null ? Math.round(s.ended_at * 1000) : null,
lastActiveAt: s.last_active != null ? Math.round(s.last_active * 1000) : undefined,
@@ -611,18 +611,25 @@ export const useChatStore = defineStore('chat', () => {
// Inherit current global model
const appStore = useAppStore()
session.model = appStore.selectedModel || undefined
session.provider = appStore.selectedProvider || ''
switchSession(session.id)
}
async function switchSessionModel(modelId: string, provider?: string) {
if (!activeSession.value) return
activeSession.value.model = modelId
activeSession.value.provider = provider || ''
// If provider changed, update global config too (Hermes requires it)
if (provider) {
const { useAppStore } = await import('./app')
await useAppStore().switchModel(modelId, provider)
async function switchSessionModel(modelId: string, provider?: string, sessionId?: string): Promise<boolean> {
const targetId = sessionId || activeSession.value?.id
if (!targetId) return false
const ok = await setSessionModel(targetId, modelId, provider || '')
if (!ok) return false
const target = sessions.value.find(s => s.id === targetId)
if (target) {
target.model = modelId
target.provider = provider || ''
}
if (activeSession.value?.id === targetId) {
activeSession.value.model = modelId
activeSession.value.provider = provider || ''
}
return true
}
async function deleteSession(sessionId: string) {
@@ -903,13 +910,21 @@ export const useChatStore = defineStore('chat', () => {
}
const appStore = useAppStore()
await appStore.loadModels()
const sessionModel = activeSession.value?.model || appStore.selectedModel
const isBridgeSource = activeSession.value?.source === 'cli'
const sessionProvider = activeSession.value?.provider || appStore.selectedProvider
const runPayload = {
input,
session_id: sid,
model: sessionModel || undefined,
model: isBridgeSource ? undefined : sessionModel || undefined,
provider: isBridgeSource ? undefined : sessionProvider || undefined,
model_groups: appStore.modelGroups.map(group => ({
provider: group.provider,
models: group.models,
})),
queue_id: userMsg.id,
source: (activeSession.value?.source === 'cli' ? 'cli' : 'api_server') as 'cli' | 'api_server',
source: (isBridgeSource ? 'cli' : 'api_server') as 'cli' | 'api_server',
}
if (shouldQueue) {
+1 -5
View File
@@ -52,21 +52,17 @@ export const useModelsStore = defineStore('models', () => {
await systemApi.updateDefaultModel({ default: modelId, provider })
defaultModel.value = modelId
const appStore = useAppStore()
appStore.loadModels()
appStore.reloadModels()
}
async function addProvider(data: CustomProvider) {
await systemApi.addCustomProvider(data)
await fetchProviders()
const appStore = useAppStore()
appStore.loadModels()
}
async function removeProvider(name: string) {
await systemApi.removeCustomProvider(name)
await fetchProviders()
const appStore = useAppStore()
appStore.loadModels()
}
return {
@@ -5,19 +5,17 @@ import { useI18n } from 'vue-i18n'
import ProvidersPanel from '@/components/hermes/models/ProvidersPanel.vue'
import ProviderFormModal from '@/components/hermes/models/ProviderFormModal.vue'
import { useModelsStore } from '@/stores/hermes/models'
import { useAppStore } from '@/stores/hermes/app'
import { checkCopilotToken } from '@/api/hermes/copilot-auth'
const { t } = useI18n()
const modelsStore = useModelsStore()
const appStore = useAppStore()
const showModal = ref(false)
onMounted(async () => {
// 先 invalidate 后端 copilot 缓存(gh logout / VS Code 退出后下一次 list 立刻反映),
// 再拉 providers 与 appStore 的模型显示名配置。check-token 失败不阻断。
try { await checkCopilotToken() } catch { /* ignore */ }
await Promise.all([modelsStore.fetchProviders(), appStore.loadModels()])
await modelsStore.fetchProviders()
})
function openCreateModal() {
@@ -30,7 +28,6 @@ function handleModalClose() {
async function handleSaved() {
await modelsStore.fetchProviders()
appStore.loadModels()
handleModalClose()
}
</script>
@@ -41,6 +41,7 @@ export async function listConversations(ctx: any) {
id: s.id,
source: s.source,
model: s.model,
provider: s.provider,
title: s.title,
started_at: s.started_at,
ended_at: s.ended_at,
@@ -267,6 +268,28 @@ export async function setWorkspace(ctx: any) {
ctx.body = { ok: true }
}
export async function setModel(ctx: any) {
const { model, provider } = ctx.request.body as { model?: string; provider?: string }
if (!model || typeof model !== 'string') {
ctx.status = 400
ctx.body = { error: 'model is required' }
return
}
if (provider !== undefined && provider !== null && typeof provider !== 'string') {
ctx.status = 400
ctx.body = { error: 'provider must be a string' }
return
}
const { updateSession, getSession, createSession } = await import('../../db/hermes/session-store')
const { getActiveProfileName } = await import('../../services/hermes/hermes-profile')
const id = ctx.params.id
if (!getSession(id)) {
createSession({ id, profile: getActiveProfileName(), title: '' })
}
updateSession(id, { model: model.trim(), provider: (provider || '').trim() } as any)
ctx.body = { ok: true }
}
export async function contextLength(ctx: any) {
const profile = (ctx.query.profile as string) || undefined
ctx.body = { context_length: getModelContextLength(profile) }
+1
View File
@@ -34,6 +34,7 @@ export const SESSIONS_SCHEMA: Record<string, string> = {
source: 'TEXT NOT NULL DEFAULT \'api_server\'',
user_id: 'TEXT',
model: 'TEXT NOT NULL DEFAULT \'\'',
provider: 'TEXT NOT NULL DEFAULT \'\'',
title: 'TEXT',
started_at: 'INTEGER NOT NULL',
ended_at: 'INTEGER',
@@ -12,6 +12,7 @@ export interface HermesSessionRow {
source: string
user_id: string | null
model: string
provider: string
title: string | null
started_at: number
ended_at: number | null
@@ -85,6 +86,7 @@ function mapSessionRow(row: Record<string, unknown>): HermesSessionRow {
source: String(row.source || 'api_server'),
user_id: row.user_id != null ? String(row.user_id) : null,
model: String(row.model || ''),
provider: String(row.provider || ''),
title,
started_at: Number(row.started_at || 0),
ended_at: row.ended_at != null ? Number(row.ended_at) : null,
@@ -131,6 +133,7 @@ export function createSession(data: {
profile?: string
source?: string
model?: string
provider?: string
title?: string
workspace?: string
}): HermesSessionRow {
@@ -139,7 +142,7 @@ export function createSession(data: {
if (!isSqliteAvailable()) {
return {
id: data.id, profile: data.profile || 'default', source,
user_id: null, model: data.model || '', title: data.title || null,
user_id: null, model: data.model || '', provider: data.provider || '', title: data.title || null,
started_at: now, ended_at: null, end_reason: null,
message_count: 0, tool_call_count: 0,
input_tokens: 0, output_tokens: 0, cache_read_tokens: 0, cache_write_tokens: 0, reasoning_tokens: 0,
@@ -149,9 +152,9 @@ export function createSession(data: {
}
const db = getDb()!
db.prepare(
`INSERT INTO ${SESSIONS_TABLE} (id, profile, source, model, title, started_at, last_active, workspace)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
).run(data.id, data.profile || 'default', source, data.model || '', data.title || null, now, now, data.workspace || null)
`INSERT INTO ${SESSIONS_TABLE} (id, profile, source, model, provider, title, started_at, last_active, workspace)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
).run(data.id, data.profile || 'default', source, data.model || '', data.provider || '', data.title || null, now, now, data.workspace || null)
return getSession(data.id)!
}
@@ -21,4 +21,5 @@ sessionRoutes.delete('/api/hermes/sessions/:id', ctrl.remove)
sessionRoutes.post('/api/hermes/sessions/batch-delete', ctrl.batchRemove)
sessionRoutes.post('/api/hermes/sessions/:id/rename', ctrl.rename)
sessionRoutes.post('/api/hermes/sessions/:id/workspace', ctrl.setWorkspace)
sessionRoutes.post('/api/hermes/sessions/:id/model', ctrl.setModel)
sessionRoutes.get('/api/hermes/workspace/folders', ctrl.listWorkspaceFolders)
@@ -28,6 +28,13 @@ export interface AgentBridgeRequestOptions {
timeoutMs?: number
}
export interface AgentBridgeChatOptions {
force_compress?: boolean
storage_message?: AgentBridgeMessage
model?: string
provider?: string
}
export type AgentBridgeMessage =
| string
| Array<Record<string, unknown>>
@@ -306,7 +313,7 @@ export class AgentBridgeClient {
conversationHistory?: unknown[],
instructions?: string,
profile?: string,
options: { force_compress?: boolean; storage_message?: AgentBridgeMessage } = {},
options: AgentBridgeChatOptions = {},
): Promise<AgentBridgeChatStarted> {
return this.request<AgentBridgeChatStarted>({
action: 'chat',
@@ -316,6 +323,8 @@ export class AgentBridgeClient {
...(conversationHistory ? { conversation_history: conversationHistory } : {}),
...(instructions ? { instructions } : {}),
...(profile ? { profile } : {}),
...(options.model ? { model: options.model } : {}),
...(options.provider ? { provider: options.provider } : {}),
...(options.force_compress ? { force_compress: true } : {}),
})
}
@@ -491,12 +491,21 @@ class AgentPool:
self,
session_id: str,
profile: str | None = None,
model: str | None = None,
provider: str | None = None,
) -> AgentSession:
requested_model = str(model or "").strip()
requested_provider = str(provider or "").strip()
with self._lock:
existing = self._sessions.get(session_id)
if existing is not None:
# If profile changed, destroy old session and recreate
if profile and existing.config.get("profile") != profile:
config_changed = bool(
(profile and existing.config.get("profile") != profile)
or (requested_model and existing.config.get("model") != requested_model)
or (requested_provider and existing.config.get("provider") != requested_provider)
)
if config_changed:
if not existing.running:
self._destroy_session(session_id)
else:
@@ -512,8 +521,8 @@ class AgentPool:
with _profile_env(profile):
cfg = _load_cfg()
resolved_model = _resolve_model(cfg)
runtime = _resolve_runtime(resolved_model)
resolved_model = requested_model or _resolve_model(cfg)
runtime = _resolve_runtime(resolved_model, requested_provider or None)
agent_cfg = cfg.get("agent") or {}
prompt = str(agent_cfg.get("system_prompt", "") or "").strip() or None
@@ -949,8 +958,10 @@ class AgentPool:
conversation_history: list[dict[str, Any]] | None = None,
profile: str | None = None,
force_compress: bool = False,
model: str | None = None,
provider: str | None = None,
) -> RunRecord:
session = self.get_or_create(session_id, profile=profile)
session = self.get_or_create(session_id, profile=profile, model=model, provider=provider)
with session.lock:
if session.running:
raise RuntimeError(f"session {session_id} is already running")
@@ -1265,6 +1276,8 @@ class BridgeServer:
instructions = req.get("instructions") or req.get("system_message")
conversation_history = req.get("conversation_history")
profile = req.get("profile")
model = req.get("model")
provider = req.get("provider")
record = self.pool.start_chat(
session_id,
message,
@@ -1273,6 +1286,8 @@ class BridgeServer:
conversation_history,
profile,
bool(req.get("force_compress")),
model,
provider,
)
if req.get("wait"):
timeout = float(req.get("timeout", 0) or 0)
@@ -75,14 +75,14 @@ export async function loadSessionStateFromDb(sid: string, _sessionMap: Map<strin
export async function handleApiRun(
nsp: ReturnType<Server['of']>,
socket: Socket,
data: { input: string | ContentBlock[]; session_id?: string; model?: string; instructions?: string; source?: string },
data: { input: string | ContentBlock[]; session_id?: string; model?: string; provider?: string; instructions?: string; source?: string },
profile: string,
sessionMap: Map<string, SessionState>,
gatewayManager: any,
skipUserMessage = false,
dequeueNextQueuedRun: (socket: Socket, sessionId: string, fallbackProfile?: string) => void,
) {
const { input, session_id, model, instructions } = data
const { input, session_id, model, provider, instructions } = data
// Build full instructions with system prompt + workspace context
let fullInstructions = instructions
@@ -131,7 +131,7 @@ export async function handleApiRun(
if (!getSession(session_id)) {
const previewText = extractTextForPreview(input)
const preview = previewText.replace(/[\r\n]/g, ' ').substring(0, 100)
createSession({ id: session_id, profile, source: 'api_server', model, title: preview })
createSession({ id: session_id, profile, source: 'api_server', model, provider, title: preview })
}
addMessage({
@@ -153,7 +153,7 @@ export async function handleApiRun(
if (!getSession(session_id)) {
const previewText = extractTextForPreview(input)
const preview = previewText.replace(/[\r\n]/g, ' ').substring(0, 100)
createSession({ id: session_id, profile, source: 'api_server', model, title: preview })
createSession({ id: session_id, profile, source: 'api_server', model, provider, title: preview })
}
addMessage({
session_id,
@@ -5,10 +5,11 @@
import type { Server, Socket } from 'socket.io'
import { getSystemPrompt } from '../../../lib/llm-prompt'
import { getSession, createSession, addMessage, updateSessionStats } from '../../../db/hermes/session-store'
import { getSession, createSession, addMessage, updateSession, updateSessionStats } from '../../../db/hermes/session-store'
import { updateUsage } from '../../../db/hermes/usage-store'
import { logger, bridgeLogger } from '../../logger'
import { AgentBridgeClient, type AgentBridgeMessage, type AgentBridgeOutput } from '../agent-bridge'
import { readConfigYaml } from '../../config-helpers'
import { contentBlocksToString, convertContentBlocksForAgent, extractTextForPreview, isContentBlockArray } from './content-blocks'
import { buildCompressedHistory } from './compression'
import { pushState, replaceState } from './compression'
@@ -29,10 +30,34 @@ import type { ChatMessage } from '../../../lib/context-compressor'
const BRIDGE_USAGE_FLUSH_DELAY_MS = 200
type RunModelGroup = { provider: string; models: string[] }
async function resolveDefaultModelConfig(): Promise<{ model: string; provider: string }> {
try {
const config = await readConfigYaml()
const modelConfig = config?.model
const model = typeof modelConfig === 'string'
? modelConfig.trim()
: String(modelConfig?.default || '').trim()
const provider = typeof modelConfig === 'object'
? String(modelConfig?.provider || '').trim()
: ''
return { model, provider }
} catch {
return { model: '', provider: '' }
}
}
function hasModelInGroups(groups: RunModelGroup[] | undefined, provider: string, model: string): boolean {
if (!groups?.length || !provider || !model) return false
const group = groups.find(item => item.provider === provider)
return Array.isArray(group?.models) && group.models.includes(model)
}
export async function handleBridgeRun(
nsp: ReturnType<Server['of']>,
socket: Socket,
data: { input: string | ContentBlock[]; session_id?: string; model?: string; instructions?: string; source?: string },
data: { input: string | ContentBlock[]; session_id?: string; model?: string; provider?: string; model_groups?: RunModelGroup[]; instructions?: string; source?: string },
profile: string,
sessionMap: Map<string, SessionState>,
gatewayManager: any,
@@ -41,7 +66,7 @@ export async function handleBridgeRun(
loadSessionStateFromDbFn: (sid: string, sessionMap: Map<string, SessionState>) => Promise<SessionState>,
dequeueNextQueuedRun: (socket: Socket, sessionId: string, fallbackProfile?: string) => void,
) {
const { input, session_id, model, instructions } = data
const { input, session_id, instructions } = data
if (!session_id) {
socket.emit('run.failed', { event: 'run.failed', error: 'session_id is required for cli source' })
return
@@ -51,6 +76,22 @@ export async function handleBridgeRun(
? `${getSystemPrompt()}\n${instructions}`
: getSystemPrompt()
const sessionRow = getSession(session_id)
const sessionModel = sessionRow?.model || ''
const sessionProvider = sessionRow?.provider || ''
const hasGroups = Array.isArray(data.model_groups) && data.model_groups.length > 0
const sessionModelAvailable = hasGroups && hasModelInGroups(data.model_groups, sessionProvider, sessionModel)
const shouldUseDefault = !sessionModel || !sessionProvider || !sessionModelAvailable
const defaultModelConfig = shouldUseDefault
? await resolveDefaultModelConfig()
: { model: '', provider: '' }
const resolvedModel = shouldUseDefault ? defaultModelConfig.model : sessionModel
const resolvedProvider = shouldUseDefault ? defaultModelConfig.provider : sessionProvider
if (sessionRow) {
const updates: { model?: string; provider?: string } = {}
if (resolvedModel && sessionRow.model !== resolvedModel) updates.model = resolvedModel
if (resolvedProvider && sessionRow.provider !== resolvedProvider) updates.provider = resolvedProvider
if (Object.keys(updates).length > 0) updateSession(session_id, updates)
}
if (sessionRow?.workspace) {
const workspaceCtx = `[Current working directory: ${sessionRow.workspace}]`
fullInstructions = `\n${workspaceCtx}\n${fullInstructions}`
@@ -93,7 +134,7 @@ export async function handleBridgeRun(
if (!getSession(session_id)) {
const previewText = extractTextForPreview(input)
const preview = previewText.replace(/[\r\n]/g, ' ').substring(0, 100)
createSession({ id: session_id, profile, source: 'cli', model, title: preview })
createSession({ id: session_id, profile, source: 'cli', model: resolvedModel, provider: resolvedProvider, title: preview })
}
addMessage({
session_id,
@@ -142,7 +183,11 @@ export async function handleBridgeRun(
bridgeHistory,
fullInstructions,
profile,
bridgeStorageInput !== undefined ? { storage_message: bridgeStorageInput } : {},
{
...(bridgeStorageInput !== undefined ? { storage_message: bridgeStorageInput } : {}),
...(resolvedModel ? { model: resolvedModel } : {}),
...(resolvedProvider ? { provider: resolvedProvider } : {}),
},
)
state.runId = started.run_id
bridgeLogger.info({
@@ -66,6 +66,8 @@ export class ChatRunSocket {
session_id?: string
model?: string
instructions?: string
provider?: string
model_groups?: Array<{ provider: string; models: string[] }>
queue_id?: string
source?: string
}) => {
@@ -102,6 +104,8 @@ export class ChatRunSocket {
queue_id: data.queue_id || `queue_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`,
input: data.input,
model: data.model,
provider: data.provider,
model_groups: data.model_groups,
instructions: data.instructions,
profile: currentProfile(),
source,
@@ -191,7 +195,15 @@ export class ChatRunSocket {
private async handleRun(
socket: Socket,
data: { input: string | ContentBlock[]; session_id?: string; model?: string; instructions?: string; source?: string },
data: {
input: string | ContentBlock[]
session_id?: string
model?: string
provider?: string
model_groups?: Array<{ provider: string; models: string[] }>
instructions?: string
source?: string
},
profile: string,
skipUserMessage = false,
) {
@@ -273,6 +285,8 @@ export class ChatRunSocket {
input: next.input,
session_id: sessionId,
model: next.model,
provider: next.provider,
model_groups: next.model_groups,
instructions: next.instructions,
source: next.source,
}, next.profile || fallbackProfile, true)
@@ -29,6 +29,8 @@ export interface QueuedRun {
queue_id: string
input: string | ContentBlock[]
model?: string
provider?: string
model_groups?: Array<{ provider: string; models: string[] }>
instructions?: string
profile: string
source?: ChatRunSource
@@ -1,6 +1,7 @@
// @vitest-environment jsdom
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { mount } from '@vue/test-utils'
import { createPinia, setActivePinia } from 'pinia'
const mockConversationsApi = vi.hoisted(() => ({
fetchConversationSummaries: vi.fn(),
@@ -38,6 +39,7 @@ function deferred<T>() {
describe('ConversationMonitorPane', () => {
beforeEach(() => {
vi.clearAllMocks()
setActivePinia(createPinia())
vi.useFakeTimers()
mockConversationsApi.fetchConversationSummaries.mockResolvedValue([
{
+23
View File
@@ -12,6 +12,8 @@ const localGetSessionDetailMock = vi.fn()
const localSearchSessionsMock = vi.fn()
const localDeleteSessionMock = vi.fn()
const localRenameSessionMock = vi.fn()
const localCreateSessionMock = vi.fn()
const localUpdateSessionMock = vi.fn()
const getGroupChatServerMock = vi.fn()
const getLocalUsageStatsMock = vi.fn()
const getActiveProfileNameMock = vi.fn()
@@ -55,6 +57,9 @@ vi.mock('../../packages/server/src/db/hermes/session-store', () => ({
getSessionDetail: localGetSessionDetailMock,
deleteSession: localDeleteSessionMock,
renameSession: localRenameSessionMock,
createSession: localCreateSessionMock,
getSession: getSessionMock,
updateSession: localUpdateSessionMock,
}))
vi.mock('../../packages/server/src/db/hermes/usage-store', () => ({
@@ -110,6 +115,8 @@ describe('session conversations controller', () => {
localSearchSessionsMock.mockReset()
localDeleteSessionMock.mockReset()
localRenameSessionMock.mockReset()
localCreateSessionMock.mockReset()
localUpdateSessionMock.mockReset()
getGroupChatServerMock.mockReset()
getGroupChatServerMock.mockReturnValue(null)
getLocalUsageStatsMock.mockReset()
@@ -296,6 +303,22 @@ describe('session conversations controller', () => {
])
})
it('sets a session model and provider in the local session store', async () => {
getSessionMock.mockReturnValue({ id: 'session-1' })
const mod = await import('../../packages/server/src/controllers/hermes/sessions')
const ctx: any = {
params: { id: 'session-1' },
request: { body: { model: 'grok-4', provider: 'xai' } },
body: null,
}
await mod.setModel(ctx)
expect(localCreateSessionMock).not.toHaveBeenCalled()
expect(localUpdateSessionMock).toHaveBeenCalledWith('session-1', { model: 'grok-4', provider: 'xai' })
expect(ctx.body).toEqual({ ok: true })
})
describe('exportSession', () => {
it('returns session as JSON download with correct headers (full mode)', async () => {
const sessionData = { id: 'abc-123', title: 'Test Session', messages: [{ id: 1, role: 'user', content: 'hello' }] }
+4
View File
@@ -11,6 +11,7 @@ const getMock = vi.fn(async (ctx: any) => { ctx.body = { session: { id: ctx.para
const removeMock = vi.fn(async (ctx: any) => { ctx.body = { ok: true } })
const renameMock = vi.fn(async (ctx: any) => { ctx.body = { ok: true } })
const setWorkspaceMock = vi.fn(async (ctx: any) => { ctx.body = { ok: true } })
const setModelMock = vi.fn(async (ctx: any) => { ctx.body = { ok: true } })
const listWorkspaceFoldersMock = vi.fn(async (ctx: any) => { ctx.body = { folders: [] } })
const usageBatchMock = vi.fn(async (ctx: any) => { ctx.body = {} })
const usageSingleMock = vi.fn(async (ctx: any) => { ctx.body = { input_tokens: 0, output_tokens: 0 } })
@@ -32,6 +33,7 @@ vi.mock('../../packages/server/src/controllers/hermes/sessions', () => ({
batchRemove: batchRemoveMock,
rename: renameMock,
setWorkspace: setWorkspaceMock,
setModel: setModelMock,
listWorkspaceFolders: listWorkspaceFoldersMock,
usageBatch: usageBatchMock,
usageSingle: usageSingleMock,
@@ -51,6 +53,7 @@ describe('session routes', () => {
getMock.mockClear()
removeMock.mockClear()
renameMock.mockClear()
setModelMock.mockClear()
})
it('registers conversations, session list, and search routes', async () => {
@@ -71,6 +74,7 @@ describe('session routes', () => {
'/api/hermes/sessions/:id/export',
'/api/hermes/sessions/:id/usage',
'/api/hermes/sessions/:id/rename',
'/api/hermes/sessions/:id/model',
]))
})