feat: configure embedding servers and transcript agents

This commit is contained in:
yiling
2026-12-04 18:54:29 +08:00
parent 72a7f68c92
commit 553269012c
57 changed files with 1686 additions and 271 deletions
+30
View File
@@ -71,6 +71,36 @@ describe('Agent API', () => {
})
})
it.each(['true', 'false'])(
'protects the Transcript Agent when ENABLE_TRANSCRIPTION_AGENT=%s',
async (value) => {
vi.stubEnv('ENABLE_TRANSCRIPTION_AGENT', value)
try {
vi.mocked(agentService.getAgent).mockResolvedValue({
id: 'transcript1',
teamId: 'team1',
type: 'transcription',
} as Awaited<ReturnType<typeof agentService.getAgent>>)
const payload = JSON.stringify({ type: 'transcription', name: 'Transcript Agent' })
const headers = { 'Content-Type': 'application/json' }
for (const [path, method, body] of [
['/teams/team1/agents', 'POST', payload],
['/agents/transcript1', 'PUT', payload],
['/agents/transcript1/permission', 'PATCH', JSON.stringify({ permission: 'editor' })],
['/agents/transcript1', 'DELETE', undefined],
] as const) {
expect((await app.request(path, { method, headers, body })).status).toBe(403)
}
expect(agentService.createAgent).not.toHaveBeenCalled()
expect(agentService.updateAgent).not.toHaveBeenCalled()
expect(agentService.updateAgentPermission).not.toHaveBeenCalled()
expect(agentService.deleteAgent).not.toHaveBeenCalled()
} finally {
vi.unstubAllEnvs()
}
},
)
describe('GET /teams/:teamId/agents', () => {
it('returns list of agents', async () => {
const mockAgents = [
+15 -24
View File
@@ -1,5 +1,6 @@
import { zValidator } from '@hono/zod-validator'
import { agentService } from '@shumai/core/src/agent/agent'
import { getSystemAgentSetting } from '@shumai/core/src/agent/system-agents'
import { agentSessionService } from '@shumai/core/src/agent/session-service'
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
import {
@@ -68,13 +69,10 @@ const route = new Hono<{ Variables: { user: User } }>()
id: teamId,
})
const isEmbeddingManagedByEnv =
process.env.ENABLE_EMBEDDING_AGENT === 'true' ||
process.env.ENABLE_EMBEDDING_AGENT === 'false'
if (req.type === 'embedding' && isEmbeddingManagedByEnv) {
const managedSetting = getSystemAgentSetting(req.type)
if (managedSetting) {
throw new HTTPException(403, {
message: 'Embedding agent is managed by environment configuration and cannot be created',
message: `${managedSetting.name} is managed by environment configuration and cannot be created`,
})
}
@@ -108,14 +106,13 @@ const route = new Hono<{ Variables: { user: User } }>()
id: agentId,
})
const isEmbeddingManagedByEnv =
process.env.ENABLE_EMBEDDING_AGENT === 'true' ||
process.env.ENABLE_EMBEDDING_AGENT === 'false'
const existingAgent = await agentService.getAgent({ agentId })
if (existingAgent?.type === 'embedding' && isEmbeddingManagedByEnv) {
const managedSetting =
(existingAgent && getSystemAgentSetting(existingAgent.type)) ??
getSystemAgentSetting(req.type)
if (managedSetting) {
throw new HTTPException(403, {
message: 'Embedding agent is managed by environment configuration and cannot be modified',
message: `${managedSetting.name} is managed by environment configuration and cannot be modified`,
})
}
@@ -150,14 +147,11 @@ const route = new Hono<{ Variables: { user: User } }>()
id: agentId,
})
const isEmbeddingManagedByEnv =
process.env.ENABLE_EMBEDDING_AGENT === 'true' ||
process.env.ENABLE_EMBEDDING_AGENT === 'false'
const existingAgent = await agentService.getAgent({ agentId })
if (existingAgent?.type === 'embedding' && isEmbeddingManagedByEnv) {
const managedSetting = existingAgent && getSystemAgentSetting(existingAgent.type)
if (managedSetting) {
throw new HTTPException(403, {
message: 'Embedding agent is managed by environment configuration and cannot be modified',
message: `${managedSetting.name} is managed by environment configuration and cannot be modified`,
})
}
@@ -186,14 +180,11 @@ const route = new Hono<{ Variables: { user: User } }>()
id: agentId,
})
const isEmbeddingManagedByEnv =
process.env.ENABLE_EMBEDDING_AGENT === 'true' ||
process.env.ENABLE_EMBEDDING_AGENT === 'false'
const existingAgent = await agentService.getAgent({ agentId })
if (existingAgent?.type === 'embedding' && isEmbeddingManagedByEnv) {
const managedSetting = existingAgent && getSystemAgentSetting(existingAgent.type)
if (managedSetting) {
throw new HTTPException(403, {
message: 'Embedding agent is managed by environment configuration and cannot be deleted',
message: `${managedSetting.name} is managed by environment configuration and cannot be deleted`,
})
}
+4 -3
View File
@@ -2,6 +2,7 @@ import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'
import { Hono } from 'hono'
import authnRoute from './authn'
import { teamService } from '@shumai/core/src/team/team'
import { transcriptService } from '@shumai/core/src/transcript/transcript'
describe('authn api', () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -17,7 +18,7 @@ describe('authn api', () => {
})
it('GET /signup-info', async () => {
vi.stubEnv('EMBEDDING_PROVIDER', 'gemini-embedding-2')
vi.spyOn(transcriptService, 'isGenerationEnabled').mockResolvedValue(false)
mockGetSignupInfo.mockResolvedValue({
initialized: true,
demoMode: false,
@@ -35,8 +36,8 @@ describe('authn api', () => {
})
})
it('advertises transcription with the local embedding provider', async () => {
vi.stubEnv('EMBEDDING_PROVIDER', 'gemma-embedding-2-openai')
it('advertises transcription when generation is enabled', async () => {
vi.spyOn(transcriptService, 'isGenerationEnabled').mockResolvedValue(true)
mockGetSignupInfo.mockResolvedValue({ initialized: true, demoMode: false })
const res = await new Hono().route('/', authnRoute).request('/signup-info')
+2 -2
View File
@@ -4,7 +4,7 @@ import { userService } from '@shumai/core/src/user/user'
import { auth } from '@shumai/core/src/auth/auth'
import { createGuestToken } from '@shumai/core/src/auth/guest-token'
import { isArchiveStorageEnabled } from '@shumai/core/src/s3/archive-storage'
import { isLocalTranscriptionEnabled } from '@shumai/core/src/transcript/local-transcription'
import { transcriptService } from '@shumai/core/src/transcript/transcript'
import { z } from 'zod'
import { zValidator } from '@hono/zod-validator'
import { ulid } from 'ulid'
@@ -25,7 +25,7 @@ const route = app
initialized: info.initialized,
demoMode: info.demoMode,
archiveStorageEnabled: isArchiveStorageEnabled(),
transcriptionEnabled: isLocalTranscriptionEnabled(),
transcriptionEnabled: await transcriptService.isGenerationEnabled(),
})
})
.get('/me', async (c) => {
+69
View File
@@ -6,6 +6,8 @@ import { authMiddleware } from './middleware/auth'
import { teamService } from '@shumai/core/src/team/team'
import { userMetadataService } from '@shumai/core/src/user-metadata/user-metadata'
import { authzService, ResourceType, Permission } from '@shumai/core/src/authz/authz'
import { embeddingServerService } from '@shumai/core/src/search/embedding-server'
import { HTTPException } from 'hono/http-exception'
vi.mock('@shumai/core/src/authz/authz', () => ({
authzService: {
@@ -112,6 +114,73 @@ describe('team api', () => {
vi.restoreAllMocks()
})
it('lets team members view the effective embedding server settings', async () => {
vi.spyOn(embeddingServerService, 'getSettings').mockResolvedValue({
url: 'http://embedding:9379/v1',
isEnvConfigured: true,
})
const response = await app.request('/teams/t1/embedding-server-settings')
expect(await response.json()).toEqual({
url: 'http://embedding:9379/v1',
isEnvConfigured: true,
})
expect(authzService.hasPermission).toHaveBeenLastCalledWith(
expect.objectContaining({ id: 't1', permission: Permission.Read }),
)
})
it('lets admins save and test embedding server settings', async () => {
vi.mocked(authzService.hasPermission).mockClear()
const url = 'http://embedding:9379/v1'
const settings = { url, isEnvConfigured: false }
const save = vi.spyOn(embeddingServerService, 'updateSettings').mockResolvedValue(settings)
const test = vi.spyOn(embeddingServerService, 'testConnection').mockResolvedValue({ ok: true })
const body = JSON.stringify({ url })
const headers = { 'Content-Type': 'application/json' }
const saved = await app.request('/teams/t1/embedding-server-settings', {
method: 'PUT',
headers,
body,
})
expect(await saved.json()).toEqual(settings)
const tested = await app.request('/teams/t1/embedding-server-settings/test', {
method: 'POST',
headers,
body,
})
expect(await tested.json()).toEqual({ ok: true })
expect(save).toHaveBeenCalledWith('t1', url)
expect(test).toHaveBeenCalledWith('t1', url)
expect(authzService.hasPermission).toHaveBeenNthCalledWith(
1,
expect.objectContaining({ permission: Permission.Admin }),
)
expect(authzService.hasPermission).toHaveBeenNthCalledWith(
2,
expect.objectContaining({ permission: Permission.Admin }),
)
})
it('rejects embedding settings writes and connection tests without admin permission', async () => {
const save = vi.spyOn(embeddingServerService, 'updateSettings')
const test = vi.spyOn(embeddingServerService, 'testConnection')
vi.mocked(authzService.hasPermission).mockRejectedValue(new HTTPException(403))
for (const [method, suffix] of [
['PUT', ''],
['POST', '/test'],
]) {
const denied = await app.request(`/teams/t1/embedding-server-settings${suffix}`, {
method,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ url: 'http://embedding:9379/v1' }),
})
expect(denied.status).toBe(403)
}
expect(save).not.toHaveBeenCalled()
expect(test).not.toHaveBeenCalled()
vi.mocked(authzService.hasPermission).mockResolvedValue(undefined)
})
it('POST /teams returns 404 without creating a team or writing an audit entry', async () => {
const createTeam = vi.spyOn(teamService, 'createTeam').mockResolvedValue({
id: 't1',
+42
View File
@@ -12,6 +12,7 @@ import {
updateRunnerRequestSchema,
updateTurntableSettingsRequestSchema,
updateGotenbergSettingsRequestSchema,
updateEmbeddingServerSettingsRequestSchema,
updateMeRequestSchema,
updateTeamMemberRoleRequestSchema,
createApiTokenRequestSchema,
@@ -31,6 +32,7 @@ import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
import { workflowTaskService } from '@shumai/core/src/workflowTask/workflowTask'
import { turntableService } from '@shumai/core/src/turntable/turntable'
import { gotenbergService } from '@shumai/core/src/gotenberg/gotenberg'
import { embeddingServerService } from '@shumai/core/src/search/embedding-server'
import type { Prisma } from '@shumai/db'
type User = Prisma.UserGetPayload<Record<string, never>>
@@ -405,6 +407,46 @@ const route = new Hono<{ Variables: { user: User } }>()
return c.json(res)
},
)
.get('/teams/:teamId/embedding-server-settings', async (c) => {
const teamId = c.req.param('teamId')
await authzService.hasPermission({
user: c.get('user'),
permission: Permission.Read,
type: ResourceType.Team,
id: teamId,
})
return c.json(await embeddingServerService.getSettings(teamId))
})
.put(
'/teams/:teamId/embedding-server-settings',
zValidator('json', updateEmbeddingServerSettingsRequestSchema),
async (c) => {
const teamId = c.req.param('teamId')
await authzService.hasPermission({
user: c.get('user'),
permission: Permission.Admin,
type: ResourceType.Team,
id: teamId,
})
const { url } = c.req.valid('json')
return c.json(await embeddingServerService.updateSettings(teamId, url))
},
)
.post(
'/teams/:teamId/embedding-server-settings/test',
zValidator('json', updateEmbeddingServerSettingsRequestSchema.partial()),
async (c) => {
const teamId = c.req.param('teamId')
await authzService.hasPermission({
user: c.get('user'),
permission: Permission.Admin,
type: ResourceType.Team,
id: teamId,
})
const { url } = c.req.valid('json')
return c.json(await embeddingServerService.testConnection(teamId, url))
},
)
.get('/teams/:teamId/user-metadata', async (c) => {
const user = c.get('user')
const teamId = c.req.param('teamId')