api.test.ts 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. import fs from 'node:fs'
  2. import path from 'node:path'
  3. import pino from 'pino'
  4. import { afterAll, beforeAll, describe, expect, it } from 'vitest'
  5. import type { AgentEvent, ProviderStatusDto } from '@agent-server/shared'
  6. import { createApp, type App } from '../src/app'
  7. import { buildServer } from '../src/http/server'
  8. import type { AgentProvider, RunContext } from '../src/providers/types'
  9. /** 假引擎:输出文本 → 请求审批 → 写产出文件 */
  10. class FakeProvider implements AgentProvider {
  11. readonly id = 'claude' as const
  12. lastCtx: RunContext | null = null
  13. async run(ctx: RunContext) {
  14. this.lastCtx = ctx
  15. ctx.setProviderSessionId('fake-session')
  16. ctx.emit('message.delta', { messageId: 'm1', text: '你好' })
  17. ctx.emit('message.completed', { messageId: 'm1', text: '你好' })
  18. if (ctx.input.text.includes('审批')) {
  19. ctx.emit('tool.started', { toolCallId: 't1', name: 'Bash', title: 'echo', input: { command: 'echo' } })
  20. const outcome = await ctx.interact({ kind: 'approval', tool: 'Bash', title: 'echo', input: {}, options: ['allow_once', 'allow_session', 'deny'] })
  21. ctx.emit('tool.completed', { toolCallId: 't1', status: outcome.resolution === 'allowed' ? 'ok' : 'denied', output: '', truncated: false })
  22. }
  23. if (ctx.input.text.includes('等待')) await new Promise((_, reject) => ctx.signal.addEventListener('abort', () => reject(new Error('aborted'))))
  24. fs.writeFileSync(path.join(ctx.workspaceDir, 'outputs/report.md'), '# 报告')
  25. return { usage: { inputTokens: 1, outputTokens: 2, cacheReadTokens: 0, cacheWriteTokens: 0, costUsd: 0.001 } }
  26. }
  27. async status(): Promise<ProviderStatusDto> {
  28. return { id: 'claude', enabled: true, available: true, loggedIn: true, account: 'test', cliPath: '', version: 'x', models: ['m'], defaultModel: 'm', message: null }
  29. }
  30. }
  31. let app: App
  32. let server: Awaited<ReturnType<typeof buildServer>>
  33. let apiKey: string
  34. const fake = new FakeProvider()
  35. const auth = () => ({ authorization: `Bearer ${apiKey}` })
  36. async function waitFor<T>(fn: () => T | undefined, ms = 3000): Promise<T> {
  37. const end = Date.now() + ms
  38. while (Date.now() < end) {
  39. const v = fn()
  40. if (v) return v
  41. await new Promise(r => setTimeout(r, 20))
  42. }
  43. throw new Error('timeout')
  44. }
  45. const events = async (sid: string) =>
  46. (await server.inject({ method: 'GET', url: `/v1/sessions/${sid}/events`, headers: auth() })).json().items as AgentEvent[]
  47. beforeAll(async () => {
  48. const log = pino({ level: 'silent' })
  49. app = createApp(log, { providers: { claude: fake } })
  50. server = await buildServer(app, { logger: log })
  51. apiKey = app.apiKeys.create('test').key
  52. })
  53. afterAll(() => server.close())
  54. describe('鉴权', () => {
  55. it('没有 Key 返回 401', async () => {
  56. expect((await server.inject({ method: 'GET', url: '/v1/sessions' })).statusCode).toBe(401)
  57. })
  58. it('后台登录后可以访问管理接口', async () => {
  59. const login = await server.inject({ method: 'POST', url: '/admin/v1/auth/login', payload: { password: 'test-password' } })
  60. expect(login.statusCode).toBe(200)
  61. const cookie = login.cookies[0]!
  62. const res = await server.inject({ method: 'GET', url: '/admin/v1/settings', cookies: { [cookie.name]: cookie.value } })
  63. expect(res.statusCode).toBe(200)
  64. expect(res.json().settings.paths.workspaceRoot).toContain('workspaces')
  65. })
  66. it('错误密码返回 401', async () => {
  67. expect((await server.inject({ method: 'POST', url: '/admin/v1/auth/login', payload: { password: 'nope' } })).statusCode).toBe(401)
  68. })
  69. })
  70. describe('会话与 Run', () => {
  71. it('完整流程:上传 → 发送 → 审批 → 产出文件', async () => {
  72. const created = await server.inject({ method: 'POST', url: '/v1/sessions', headers: auth(), payload: {} })
  73. expect(created.statusCode).toBe(201)
  74. const sid = created.json().id as string
  75. const boundary = 'xBOUNDARYx'
  76. const upload = await server.inject({
  77. method: 'POST', url: `/v1/sessions/${sid}/files`,
  78. headers: { ...auth(), 'content-type': `multipart/form-data; boundary=${boundary}` },
  79. payload: `--${boundary}\r\nContent-Disposition: form-data; name="file"; filename="销售.csv"\r\nContent-Type: text/csv\r\n\r\na,b\n1,2\n\r\n--${boundary}--\r\n`,
  80. })
  81. expect(upload.statusCode).toBe(201)
  82. const fileId = upload.json()[0].id as string
  83. expect(upload.json()[0].path).toBe('uploads/销售.csv')
  84. const sent = await server.inject({ method: 'POST', url: `/v1/sessions/${sid}/messages`, headers: auth(), payload: { text: '请审批', attachments: [fileId] } })
  85. expect(sent.statusCode).toBe(202)
  86. const runId = sent.json().id as string
  87. // 会话忙时不能再发
  88. const busy = await server.inject({ method: 'POST', url: `/v1/sessions/${sid}/messages`, headers: auth(), payload: { text: 'x' } })
  89. expect(busy.statusCode).toBe(409)
  90. const itx = await waitFor(() => app.interactions.pendingFor(sid)[0])
  91. expect(fake.lastCtx?.input.attachments[0]?.path).toBe('uploads/销售.csv')
  92. const detail = await server.inject({ method: 'GET', url: `/v1/sessions/${sid}`, headers: auth() })
  93. expect(detail.json().status).toBe('waiting_input')
  94. const reply = await server.inject({ method: 'POST', url: `/v1/interactions/${itx.interactionId}`, headers: auth(), payload: { decision: 'allow_once' } })
  95. expect(reply.statusCode).toBe(200)
  96. const again = await server.inject({ method: 'POST', url: `/v1/interactions/${itx.interactionId}`, headers: auth(), payload: { decision: 'allow_once' } })
  97. expect(again.statusCode).toBe(409)
  98. await waitFor(() => app.runs.activeForSession(sid) === undefined || undefined)
  99. const run = (await server.inject({ method: 'GET', url: `/v1/runs/${runId}`, headers: auth() })).json()
  100. expect(run.status).toBe('completed')
  101. expect(run.usage.outputTokens).toBe(2)
  102. const types = (await events(sid)).map(e => e.type)
  103. expect(types).toEqual(expect.arrayContaining([
  104. 'user.message', 'run.queued', 'run.started', 'message.completed', 'tool.started',
  105. 'interaction.required', 'interaction.resolved', 'tool.completed', 'file.changed', 'usage', 'run.completed',
  106. ]))
  107. // 内存缓冲中包含瞬时的 delta 事件
  108. expect(types).toContain('message.delta')
  109. const files = (await server.inject({ method: 'GET', url: `/v1/sessions/${sid}/files`, headers: auth() })).json()
  110. const report = files.find((f: { path: string }) => f.path === 'outputs/report.md')
  111. expect(report.origin).toBe('agent')
  112. const dl = await server.inject({ method: 'GET', url: `/v1/files/${report.id}`, headers: auth() })
  113. expect(dl.body).toBe('# 报告')
  114. const session = (await server.inject({ method: 'GET', url: `/v1/sessions/${sid}`, headers: auth() })).json()
  115. expect(session.title).toBe('请审批')
  116. })
  117. it('中断运行中的 Run', async () => {
  118. const sid = (await server.inject({ method: 'POST', url: '/v1/sessions', headers: auth(), payload: {} })).json().id
  119. const runId = (await server.inject({ method: 'POST', url: `/v1/sessions/${sid}/messages`, headers: auth(), payload: { text: '等待' } })).json().id
  120. await waitFor(() => app.runs.activeForSession(sid)?.status === 'running' || undefined)
  121. expect((await server.inject({ method: 'POST', url: `/v1/runs/${runId}/interrupt`, headers: auth() })).statusCode).toBe(202)
  122. await waitFor(() => app.runs.activeForSession(sid) === undefined || undefined)
  123. expect(app.runs.get(runId).status).toBe('interrupted')
  124. expect((await events(sid)).at(-1)?.type).toBe('run.interrupted')
  125. })
  126. it('其他 API Key 看不到这个会话', async () => {
  127. const sid = (await server.inject({ method: 'POST', url: '/v1/sessions', headers: auth(), payload: {} })).json().id
  128. const otherKey = app.apiKeys.create('other').key
  129. const res = await server.inject({ method: 'GET', url: `/v1/sessions/${sid}`, headers: { authorization: `Bearer ${otherKey}` } })
  130. expect(res.statusCode).toBe(404)
  131. })
  132. it('删除会话同时删除工作区', async () => {
  133. const created = await app.sessions.create(app.apiKeys.list()[0]!.id, {})
  134. expect(fs.existsSync(created.workspaceDir)).toBe(true)
  135. await app.sessions.delete(created.id, 'admin')
  136. expect(fs.existsSync(created.workspaceDir)).toBe(false)
  137. })
  138. })
  139. describe('资料库', () => {
  140. it('拒绝不安全的路径', () => {
  141. expect(() => app.knowledge.create({ name: 'home', path: '~' })).toThrow(/全局禁止项/)
  142. expect(() => app.knowledge.create({ name: 'none', path: '/does/not/exist' })).toThrow(/不存在/)
  143. })
  144. })