优化页面交互并增强 Provider 配置能力
Build / build (push) Canceled after 0s
Playwright / e2e (push) Canceled after 0s

- 表单下拉框不再用 label 包裹,改为 div + aria-label,避免点击后
  下拉面板瞬间关闭
- Provider 卡片新增「从上游获取模型」和「修改」入口,支持编辑
  base URL、API Key 与 api_mode,凭据写入对应的环境变量
- 服务端抽出 provider-model-discovery 统一不同 api_mode 的模型发现,
  旧的 custom_providers 与新的 providers 字典结构都能正确更新
- Agent Bridge 改为后台启动,HTTP 接口在 Python 运行时就绪前即可用;
  worker 连接被拒时按类型重试,不重放可能已产生副作用的请求
- 断线重连后恢复 profiles、models 与会话列表,健康检查改为自调度
  的 setTimeout,离线时 2 秒后重试
- 批量删除确认文案改用 Popconfirm content,避免变成侧栏触发器文本
This commit is contained in:
2026-10-22 14:29:48 +08:00
committed by trae-solo-agent
parent 90c759c760
commit 3ca960f388
35 changed files with 876 additions and 78 deletions
@@ -0,0 +1,83 @@
import { createServer, type Server } from 'net'
import { afterEach, describe, expect, it } from 'vitest'
import { AgentBridgeClient } from '../../packages/server/src/services/hermes/agent-bridge/client'
const servers: Server[] = []
afterEach(async () => {
await Promise.all(servers.splice(0).map(server => new Promise<void>(resolve => server.close(() => resolve()))))
})
async function broker(reply: (request: Record<string, unknown>) => Record<string, unknown>, retryMs = 1000) {
const server = createServer(socket => {
let buffer = ''
socket.on('data', data => {
buffer += data.toString()
if (!buffer.includes('\n')) return
socket.end(`${JSON.stringify(reply(JSON.parse(buffer)))}\n`)
})
})
servers.push(server)
await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve))
const address = server.address()
if (!address || typeof address === 'string') throw new Error('Missing test broker address')
return new AgentBridgeClient({ endpoint: `tcp://127.0.0.1:${address.port}`, connectRetryMs: retryMs, timeoutMs: 1000 })
}
const refused = { ok: false, error: '[Errno 111] Connection refused', error_type: 'ConnectionRefusedError' }
describe('Agent Bridge worker readiness', () => {
it('waits for a cold worker and for a worker restarting after idle without losing the message', async () => {
const requests: Record<string, unknown>[] = []
let ready = false
const client = await broker(request => {
requests.push(request)
if (!ready) {
ready = true
return refused
}
return { ok: true, run_id: `run-${requests.length}`, session_id: request.session_id }
})
await expect(client.chat('session', 'first message', [], undefined, 'default')).resolves.toMatchObject({ ok: true })
ready = false
await expect(client.chat('session', 'after idle', [{ role: 'user', content: 'first message' }])).resolves.toMatchObject({ ok: true })
expect(requests).toHaveLength(4)
expect(requests[0]).toEqual(requests[1])
expect(requests[2]).toEqual(requests[3])
})
it('retries a worker socket that has not been created yet', async () => {
let attempts = 0
const client = await broker(() => ++attempts === 1
? { ok: false, error: '[Errno 2] No such file or directory', error_type: 'FileNotFoundError' }
: { ok: true })
await expect(client.request({ action: 'worker_ping', profile: 'default' })).resolves.toEqual({ ok: true })
expect(attempts).toBe(2)
})
it.each([
{ ok: false, error: '[Errno 111] Connection refused' },
{ ok: false, error: '[Errno 111] Connection refused', error_type: 'RuntimeError' },
{ ok: false, error: 'worker closed without a response', error_type: 'RuntimeError' },
{ ok: false, error: 'timed out', error_type: 'TimeoutError' },
])('does not replay ambiguous failures: $error_type $error', async response => {
let attempts = 0
const client = await broker(() => { attempts++; return response })
await expect(client.chat('session', 'message')).rejects.toThrow(response.error)
expect(attempts).toBe(1)
})
it('stops retrying persistent worker refusal within the configured budget', async () => {
let attempts = 0
const client = await broker(() => { attempts++; return refused }, 150)
await expect(client.chat('session', 'message')).rejects.toThrow('Connection refused')
expect(attempts).toBeGreaterThan(1)
expect(attempts).toBeLessThanOrEqual(4)
})
it('honors disabled retries', async () => {
let attempts = 0
const client = await broker(() => { attempts++; return refused }, 0)
await expect(client.chat('session', 'message')).rejects.toThrow('Connection refused')
expect(attempts).toBe(1)
})
})
@@ -409,6 +409,8 @@ describe('models controller — model visibility', () => {
expect(ctx.body.groups).toEqual(expect.arrayContaining([
expect.objectContaining({
provider: 'lmstudio',
credentials_editable: true,
base_url_env: 'LM_BASE_URL',
label: 'LM Studio',
base_url: 'http://127.0.0.1:1234/v1',
models: ['eee'],
@@ -647,4 +649,22 @@ describe('models controller — model visibility', () => {
expect(ctx.body).toEqual({ error: 'Select at least one model' })
expect(mockWriteAppConfig).not.toHaveBeenCalled()
})
it.each([
{ ok: false, status: 401, json: async () => ({}) },
{ ok: true, status: 200, json: async () => ({ data: [] }) },
{ ok: true, status: 200, json: async () => ({ unexpected: [] }) },
])('keeps the cached catalog when an upstream refresh fails or has no models ($status)', async response => {
const originalFetch = globalThis.fetch
globalThis.fetch = vi.fn(async () => response) as any
try {
mockWriteProviderModelCatalogEntry.mockClear()
const ctx = makeCtx({ provider: 'deepseek', base_url: 'https://api.deepseek.com/v1', api_key: 'test', update_cache: true })
await ctrl.fetchProviderModelList(ctx)
expect(ctx.status).toBe(502)
expect(mockWriteProviderModelCatalogEntry).not.toHaveBeenCalled()
} finally {
globalThis.fetch = originalFetch
}
})
})
@@ -0,0 +1,39 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { discoverProviderModels } from '../../packages/server/src/services/hermes/provider-model-discovery'
afterEach(() => vi.unstubAllGlobals())
describe('live provider model discovery', () => {
it('uses Anthropic authentication and collects every page before returning the catalog', async () => {
const fetch = vi.fn()
.mockResolvedValueOnce({ ok: true, json: async () => ({ data: [{ id: 'MiniMax-M3' }], has_more: true, last_id: 'MiniMax-M3' }) })
.mockResolvedValueOnce({ ok: true, json: async () => ({ data: [{ id: 'MiniMax-M2.7' }], has_more: false }) })
vi.stubGlobal('fetch', fetch)
await expect(discoverProviderModels('https://proxy.invalid/anthropic/v1/', 'test-key', true)).resolves.toEqual(['MiniMax-M2.7', 'MiniMax-M3'])
expect(fetch).toHaveBeenNthCalledWith(1, 'https://proxy.invalid/anthropic/v1/models', expect.objectContaining({
headers: { 'x-api-key': 'test-key', 'anthropic-version': '2023-06-01' },
}))
expect(fetch.mock.calls[1][0]).toContain('after_id=MiniMax-M3')
})
it('uses Bearer authentication for OpenAI-compatible endpoints and normalizes model IDs', async () => {
const fetch = vi.fn().mockResolvedValue({ ok: true, json: async () => ({ data: [{ id: 'b' }, { id: '' }, { id: 'a' }, { id: 'b' }] }) })
vi.stubGlobal('fetch', fetch)
await expect(discoverProviderModels('https://proxy.invalid', 'test-key')).resolves.toEqual(['a', 'b'])
expect(fetch).toHaveBeenCalledWith('https://proxy.invalid/v1/models', expect.objectContaining({ headers: { Authorization: 'Bearer test-key' } }))
})
it('rejects a failed later page instead of returning a partial list', async () => {
vi.stubGlobal('fetch', vi.fn()
.mockResolvedValueOnce({ ok: true, json: async () => ({ data: [{ id: 'first' }], has_more: true, last_id: 'first' }) })
.mockResolvedValueOnce({ ok: false, status: 503 }))
await expect(discoverProviderModels('https://proxy.invalid/v1', 'test-key', true)).rejects.toThrow('HTTP 503')
})
it('rejects a repeated cursor instead of looping', async () => {
const fetch = vi.fn().mockResolvedValue({ ok: true, json: async () => ({ data: [{ id: 'first' }], has_more: true, last_id: 'first' }) })
vi.stubGlobal('fetch', fetch)
await expect(discoverProviderModels('https://proxy.invalid/v1', 'test-key', true)).rejects.toThrow('invalid model pagination')
expect(fetch).toHaveBeenCalledTimes(2)
})
})
@@ -127,4 +127,67 @@ describe('providers controller update', () => {
expect(defaultConfig.custom_providers[0].api_mode).toBe('codex_responses')
expect(researchConfig.custom_providers[0].api_mode).toBe('chat_completions')
})
it('updates a built-in Base URL and key without changing defaults or another profile', async () => {
const { update } = await loadProvidersController()
const before = readFileSync(join(hermesHome, 'profiles', 'research', 'config.yaml'), 'utf8')
const ctx = makeCtx('minimax-cn', { base_url: 'https://proxy.invalid/anthropic/v1', api_key: 'new-key' })
await update(ctx)
expect(ctx.body).toEqual({ success: true })
const env = readFileSync(join(hermesHome, 'profiles', 'research', '.env'), 'utf8')
expect(env).toContain('MINIMAX_CN_API_KEY=new-key')
expect(env).toContain('MINIMAX_CN_BASE_URL=https://proxy.invalid/anthropic/v1')
expect(readFileSync(join(hermesHome, '.env'), 'utf8')).not.toContain('new-key')
expect(readFileSync(join(hermesHome, 'profiles', 'research', 'config.yaml'), 'utf8')).toBe(before)
})
it('keeps an existing key when only the URL is edited', async () => {
const { update } = await loadProvidersController()
const ctx = makeCtx('deepseek', { base_url: 'https://new.invalid/v1' })
await update(ctx)
const env = readFileSync(join(hermesHome, 'profiles', 'research', '.env'), 'utf8')
expect(env).toContain('DEEPSEEK_API_KEY=old-research-key')
expect(env).toContain('DEEPSEEK_BASE_URL=https://new.invalid/v1')
})
it('edits a dict-backed provider in place and preserves its models and extra configuration', async () => {
const path = join(hermesHome, 'profiles', 'research', 'config.yaml')
writeFileSync(path, YAML.dump({
model: { provider: 'custom:dict-proxy', default: 'selected-model' },
providers: { original_key: {
name: 'dict-proxy', url: 'https://old.invalid/v1', api_key: 'old-key',
models: { 'selected-model': { context_length: 12345 } }, extra_body: { keep: true },
} },
}))
const { update } = await loadProvidersController()
const ctx = makeCtx('custom:dict-proxy', {
base_url: 'https://new.invalid/v1', api_key: 'new-key', source: 'providers', providerKey: 'original_key',
})
await update(ctx)
expect(ctx.body).toEqual({ success: true })
const config = readYaml(path)
expect(config.custom_providers).toBeUndefined()
expect(config.model).toEqual({ provider: 'custom:dict-proxy', default: 'selected-model' })
expect(config.providers.original_key).toMatchObject({
base_url: 'https://new.invalid/v1', api_key: 'new-key',
models: { 'selected-model': { context_length: 12345 } }, extra_body: { keep: true },
})
})
it('updates an env-backed custom key in the same profile', async () => {
const path = join(hermesHome, 'profiles', 'research', 'config.yaml')
writeFileSync(path, YAML.dump({ providers: { proxy: { base_url: 'https://proxy.invalid/v1', key_env: 'PROXY_KEY', model: 'keep' } } }))
const { update } = await loadProvidersController()
await update(makeCtx('custom:proxy', { api_key: 'new-key', source: 'providers', providerKey: 'proxy' }))
expect(readFileSync(join(hermesHome, 'profiles', 'research', '.env'), 'utf8')).toContain('PROXY_KEY=new-key')
expect(readYaml(path).providers.proxy.model).toBe('keep')
})
it.each(['', 'bad-url', 'file:///tmp/model'])('rejects an invalid URL before writing the key: %s', async base_url => {
const { update } = await loadProvidersController()
const ctx = makeCtx('deepseek', { base_url, api_key: 'must-not-save' })
await update(ctx)
expect(ctx.status).toBe(400)
expect(readFileSync(join(hermesHome, 'profiles', 'research', '.env'), 'utf8')).toContain('DEEPSEEK_API_KEY=old-research-key')
})
})