workspaceRoutes.test.ts 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  1. // @vitest-environment node
  2. import { mkdtempSync, rmSync, readFileSync } from 'node:fs'
  3. import { tmpdir } from 'node:os'
  4. import { join } from 'node:path'
  5. import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
  6. import { randomUUID } from 'node:crypto'
  7. import request from 'supertest'
  8. import type Koa from 'koa'
  9. import { createApplication, type ApplicationRuntime } from '../../src/server/app'
  10. import { loadServerConfig } from '../../src/server/config'
  11. import { LocalAuthStore, type LocalUser } from '../../src/server/localAuth'
  12. import { WorkspaceAssets } from '../../src/server/workspaceAssets'
  13. let home: string, runtime: ApplicationRuntime, cookie: string, csrf: string, upstream: string[], bridgeReady: boolean
  14. const first: LocalUser = {
  15. id: 'first',
  16. username: 'first',
  17. role: 'admin',
  18. enabled: true,
  19. mustChangePassword: false,
  20. createdAt: 1,
  21. updatedAt: 1,
  22. }
  23. class TestAuth extends LocalAuthStore {
  24. override current(ctx: Koa.Context) {
  25. return this.require(ctx)
  26. }
  27. override require(ctx: Koa.Context) {
  28. return { ...first, id: ctx.get('x-test-user') || 'first' }
  29. }
  30. override requireAdmin(ctx: Koa.Context) {
  31. return this.require(ctx)
  32. }
  33. override canUseSource() { return true }
  34. override currentFromCookieHeader() {
  35. return first
  36. }
  37. override isUserActive() {
  38. return true
  39. }
  40. }
  41. function req(method: 'get' | 'post' | 'put' | 'patch' | 'delete', path: string, user = 'first') {
  42. return request(runtime.app.callback())
  43. [method](path)
  44. .set('Host', '127.0.0.1:15300')
  45. .set('Origin', 'http://127.0.0.1:15300')
  46. .set('Cookie', cookie)
  47. .set('X-CSRF-Token', csrf)
  48. .set('x-test-user', user)
  49. }
  50. beforeEach(async () => {
  51. home = mkdtempSync(join(tmpdir(), 'yaoyao-workspace-routes-'))
  52. upstream = []
  53. bridgeReady = false
  54. const config = loadServerConfig({
  55. HERMES_YAOYAO_HOME: home,
  56. HERMES_YAOYAO_UPSTREAM: 'http://127.0.0.1:19119',
  57. HERMES_YAOYAO_ALLOWED_HOSTS: '127.0.0.1,localhost',
  58. })
  59. runtime = createApplication({
  60. config,
  61. auth: new TestAuth(home, false),
  62. fetchImpl: (async (input) => {
  63. const path = new URL(String(input)).pathname
  64. upstream.push(path)
  65. const body =
  66. path === '/api/plugins/yaoyao-bot-bridge/capabilities' && bridgeReady
  67. ? {version:1,ready:true,in_process:true,native_tools:true}
  68. : path === '/api/pair/v1/capabilities'
  69. ? {protocolVersion:1,serviceType:'yaoyao-web',nodeId:'11111111-1111-4111-8111-111111111111',fingerprint:'f'.repeat(64)}
  70. : path === '/api/pair/v1/claim'
  71. ? {protocolVersion:1,serviceType:'yaoyao-web',nodeId:'11111111-1111-4111-8111-111111111111',fingerprint:'f'.repeat(64),deviceId:'22222222-2222-4222-8222-222222222222',token:'delegated-token',scopes:['agents.read','sessions.execute','history.read'],serverUrl:'http://child.test:15300/node/22222222-2222-4222-8222-222222222222'}
  72. : path === '/api/status'
  73. ? { auth_required: true }
  74. : path === '/api/auth/me'
  75. ? { user_id: 'upstream' }
  76. : path.endsWith('/api/profiles')
  77. ? { profiles: [{ name: 'default', display_name: '基础 Agent' }] }
  78. : { ok: true }
  79. return new Response(JSON.stringify(body), {
  80. status: path.includes('/plugins/') && !bridgeReady ? 404 : 200,
  81. headers: { 'Content-Type': 'application/json' },
  82. })
  83. }) as typeof fetch,
  84. })
  85. const b = await request(runtime.app.callback())
  86. .get('/api/app/bootstrap')
  87. .set('Host', '127.0.0.1:15300')
  88. .expect(200)
  89. cookie = (b.headers['set-cookie'] as unknown as string[]).map((v) => v.split(';')[0]).join('; ')
  90. csrf = b.body.csrfToken
  91. })
  92. afterEach(() => {
  93. runtime.close()
  94. rmSync(home, { recursive: true, force: true })
  95. })
  96. describe('application workspace HTTP contract', () => {
  97. it.each(['archive', 'delete'] as const)('%s removes a confirmed ordinary member from all groups atomically', async action => {
  98. const store = runtime.workspace
  99. const lead = store.createAgent('first', { name: '管理者', profile: 'default' })
  100. const bot = store.createAgent('first', { name: '待处理成员', profile: 'default' })
  101. const direct = store.list<any>('first', 'conversation').find(c => c.kind === 'direct' && c.memberIds[0] === bot.id)
  102. const group = store.createGroup('first', { name: '设计群', memberIds: [lead.id, bot.id], administratorId: lead.id, autoReplyIds: [bot.id], memberRoles: { [bot.id]: { name: '设计', description: '' } } })
  103. const oldGroup = store.createGroup('first', { name: '旧群', memberIds: [lead.id, bot.id], administratorId: lead.id })
  104. store.updateConversation('first', oldGroup.id, { archived: true })
  105. const path = `/api/app/conversations/${direct.id}/lifecycle`
  106. const preview = (await req('get', path).expect(200)).body
  107. expect(preview.groups).toEqual(expect.arrayContaining([{ id: group.id, name: '设计群', administrator: false }, { id: oldGroup.id, name: '旧群', administrator: false }]))
  108. await req('post', path).send({ action }).expect(409)
  109. expect((await req('patch', `/api/app/agents/${bot.id}`).send({ archived: true }).expect(409)).body.code).toBe('agent_in_group')
  110. await req('get', path, 'foreign').expect(404)
  111. await req('post', path, 'foreign').send({ action, confirmationToken: preview.confirmationToken }).expect(404)
  112. await req('post', path).set('X-CSRF-Token', 'invalid').send({ action, confirmationToken: preview.confirmationToken }).expect(403)
  113. await req('post', path).send({ action, confirmationToken: preview.confirmationToken }).expect(200)
  114. expect(store.require<any>('first', 'conversation', group.id)).toMatchObject({ memberIds: [lead.id], autoReplyIds: [], memberRoles: {}, administratorId: lead.id })
  115. expect(store.require<any>('first', 'conversation', oldGroup.id).memberIds).toEqual([lead.id])
  116. if (action === 'delete') {
  117. expect(store.get('first', 'agent', bot.id)).toBeUndefined()
  118. expect(store.get('first', 'conversation', direct.id)).toBeUndefined()
  119. } else {
  120. expect(store.require<any>('first', 'agent', bot.id).archived).toBe(true)
  121. await req('post', path).send({ action: 'restore' }).expect(200)
  122. expect(store.require<any>('first', 'conversation', direct.id).archived).toBe(false)
  123. expect(store.require<any>('first', 'conversation', group.id).memberIds).toEqual([lead.id])
  124. }
  125. expect(store.get('first', 'agent', lead.id)).toBeDefined()
  126. })
  127. it.each(['archive', 'delete'] as const)('blocks %s for a group administrator without removing other memberships', async action => {
  128. const store = runtime.workspace
  129. const bot = store.createAgent('first', { name: '群管理者', profile: 'default' })
  130. const other = store.createAgent('first', { name: '其他成员', profile: 'default' })
  131. const direct = store.list<any>('first', 'conversation').find(c => c.kind === 'direct' && c.memberIds[0] === bot.id)
  132. const regular = store.createGroup('first', { name: '普通群', memberIds: [bot.id, other.id], administratorId: other.id })
  133. const managed = store.createGroup('first', { name: '管理群', memberIds: [bot.id, other.id], administratorId: bot.id })
  134. const path = `/api/app/conversations/${direct.id}/lifecycle`
  135. const preview = (await req('get', path).expect(200)).body
  136. const cursor = store.cursor('first')
  137. const result = await req('post', path).send({ action, confirmationToken: preview.confirmationToken }).expect(409)
  138. expect(result.body.code).toBe('agent_group_administrator')
  139. expect(result.body.error).toContain('管理群')
  140. expect(store.require<any>('first', 'conversation', regular.id).memberIds).toContain(bot.id)
  141. expect(store.require<any>('first', 'conversation', managed.id).administratorId).toBe(bot.id)
  142. expect(store.require<any>('first', 'agent', bot.id).archived).toBe(false)
  143. expect(store.cursor('first')).toBe(cursor)
  144. })
  145. it('rejects a stale group confirmation and rolls back membership on a later deletion failure', async () => {
  146. const store = runtime.workspace
  147. const lead = store.createAgent('first', { name: '负责人', profile: 'default' })
  148. const bot = store.createAgent('first', { name: '成员', profile: 'default' })
  149. const direct = store.list<any>('first', 'conversation').find(c => c.kind === 'direct' && c.memberIds[0] === bot.id)
  150. const path = `/api/app/conversations/${direct.id}/lifecycle`
  151. const old = (await req('get', path).expect(200)).body
  152. const group = store.createGroup('first', { name: '后来加入的群', memberIds: [lead.id, bot.id], administratorId: lead.id })
  153. expect((await req('post', path).send({ action: 'delete', confirmationToken: old.confirmationToken }).expect(409)).body.code).toBe('lifecycle_confirmation_stale')
  154. const current = (await req('get', path).expect(200)).body
  155. store.put('first', 'turn', 'pending', { id: 'pending', agentId: bot.id, conversationId: group.id, status: 'uncertain' })
  156. await req('post', path).send({ action: 'archive', confirmationToken: current.confirmationToken }).expect(409)
  157. store.remove('first', 'turn', 'pending')
  158. const cursor = store.cursor('first')
  159. const failure = vi.spyOn(store, 'deleteAgent').mockImplementation(() => { throw new Error('模拟写入失败') })
  160. await req('post', path).send({ action: 'delete', confirmationToken: current.confirmationToken }).expect(500)
  161. failure.mockRestore()
  162. expect(store.require<any>('first', 'conversation', group.id).memberIds).toContain(bot.id)
  163. expect(store.require<any>('first', 'agent', bot.id).archived).toBe(false)
  164. expect(store.require<any>('first', 'conversation', direct.id).archived).toBe(false)
  165. expect(store.cursor('first')).toBe(cursor)
  166. })
  167. it('deletes an unarchived group while preserving its member Bots', async () => {
  168. const store = runtime.workspace
  169. const a = store.createAgent('first', { name: '甲', profile: 'default' }), b = store.createAgent('first', { name: '乙', profile: 'default' })
  170. const group = store.createGroup('first', { name: '待删除群', memberIds: [a.id, b.id], administratorId: a.id })
  171. const path = `/api/app/conversations/${group.id}/lifecycle`
  172. const preview = (await req('get', path).expect(200)).body
  173. await req('post', path).send({ action: 'delete', confirmationToken: preview.confirmationToken }).expect(200)
  174. expect(store.get('first', 'conversation', group.id)).toBeUndefined()
  175. expect(store.get('first', 'agent', a.id)).toBeDefined()
  176. expect(store.get('first', 'agent', b.id)).toBeDefined()
  177. })
  178. it('deletes only archived owned chats, clears their records, and preserves library files and members', async () => {
  179. const store = runtime.workspace
  180. const lead = store.createAgent('first', { name: '负责人', profile: 'default' })
  181. const member = store.createAgent('first', { name: '成员', profile: 'default' })
  182. const group = store.createGroup('first', { name: '待删除群聊', memberIds: [lead.id, member.id], administratorId: lead.id })
  183. const task = store.tasks('first', group.id)[0]!
  184. const path = `/api/app/conversations/${group.id}`
  185. await req('delete', path).expect(409)
  186. store.updateConversation('first', group.id, { archived: true })
  187. store.put('second', 'conversation', group.id, group)
  188. for (const kind of ['message', 'run', 'turn', 'interaction', 'interaction-binding', 'binding', 'assignment']) {
  189. store.put('first', kind, kind, { id: kind, conversationId: group.id, conversationTaskId: task.id, status: 'complete' })
  190. store.put('second', kind, kind, { id: kind, conversationId: group.id })
  191. }
  192. store.put('first', 'context', task.id, { used: 5 })
  193. const bindingKey = `${group.id}:${task.id}:${lead.id}`
  194. store.put('first', 'binding', bindingKey, { conversationTaskId: task.id, sessionId: 'session' })
  195. store.put('first', 'interaction-binding', 'legacy-interaction', { key: bindingKey, taskId: 'turn' })
  196. store.put('second', 'binding', bindingKey, { sessionId: 'other-session' })
  197. store.put('first', 'file', 'file', { id: 'file', conversationId: group.id, messageId: 'message', name: '保留.txt' })
  198. await req('delete', path, 'third').expect(404)
  199. await req('delete', path).set('X-CSRF-Token', 'invalid').expect(403)
  200. await req('delete', path).expect(200)
  201. await req('get', path).expect(404)
  202. expect(store.get('first', 'context', task.id)).toBeUndefined()
  203. expect(store.get('first', 'conversation-task', task.id)).toBeUndefined()
  204. expect(store.list('first', 'message')).toEqual([])
  205. expect(store.list('first', 'run')).toEqual([])
  206. expect(store.list('first', 'binding')).toEqual([])
  207. expect(store.list('first', 'interaction-binding')).toEqual([])
  208. expect(store.get('second', 'binding', bindingKey)).toEqual({ sessionId: 'other-session' })
  209. expect(store.get('first', 'file', 'file')).toEqual({ id: 'file', name: '保留.txt' })
  210. expect(store.list('first', 'agent')).toHaveLength(2)
  211. expect(store.get('second', 'conversation', group.id)).toEqual(group)
  212. expect(store.get('second', 'message', 'message')).toBeDefined()
  213. expect((await req('get', '/api/app/events')).body.events.some((e: any) => e.type === 'conversation.deleted' && e.conversationId === group.id)).toBe(true)
  214. })
  215. it('deletes an archived Bot and its direct chat only after group references are removed', async () => {
  216. const store = runtime.workspace
  217. const bot = store.createAgent('first', { name: '归档 Bot', profile: 'default' })
  218. const member = store.createAgent('first', { name: '成员', profile: 'default' })
  219. const direct = store.list<any>('first', 'conversation').find(c => c.memberIds[0] === bot.id)!
  220. const group = store.createGroup('first', { name: '关联群', memberIds: [bot.id, member.id], administratorId: member.id })
  221. const path = `/api/app/agents/${bot.id}`
  222. await req('delete', path).expect(409)
  223. store.updateAgent('first', bot.id, { archived: true })
  224. await req('delete', `/api/app/conversations/${direct.id}`).expect(400)
  225. expect((await req('delete', path).expect(409)).body.code).toBe('agent_in_group')
  226. expect(store.get('first', 'agent', bot.id)).toBeDefined()
  227. store.updateConversation('first', group.id, { memberIds: [member.id] })
  228. await req('delete', path, 'second').expect(404)
  229. await req('delete', path).expect(200)
  230. expect(store.get('first', 'agent', bot.id)).toBeUndefined()
  231. expect(store.get('first', 'conversation', direct.id)).toBeUndefined()
  232. expect(store.get('first', 'conversation', group.id)).toBeDefined()
  233. expect(store.get('first', 'agent', member.id)).toBeDefined()
  234. })
  235. it('keeps archived chats intact while runs or delegated goals are unresolved', async () => {
  236. const store = runtime.workspace
  237. const bot = store.createAgent('first', { name: '运行中', profile: 'default' })
  238. const direct = store.list<any>('first', 'conversation')[0]!
  239. store.updateAgent('first', bot.id, { archived: true })
  240. store.put('first', 'run', 'pending', { id: 'pending', conversationId: direct.id, status: 'uncertain' })
  241. const path = `/api/app/agents/${bot.id}`
  242. await req('delete', path).expect(409)
  243. expect(store.get('first', 'conversation', direct.id)).toBeDefined()
  244. store.remove('first', 'run', 'pending')
  245. store.put('first', 'goal', 'delegated', { id: 'delegated', conversationId: 'another-chat', origin: { conversationId: direct.id }, status: 'waiting' })
  246. await req('delete', path).expect(409)
  247. expect(store.get('first', 'agent', bot.id)).toBeDefined()
  248. })
  249. it('resumes a stopped goal from a real user request without duplicating its run',async()=>{
  250. vi.spyOn(runtime.workspaceRuntime,'wake').mockImplementation(()=>{})
  251. vi.spyOn(runtime.workspaceRuntime.teamTools,'requireAvailable').mockResolvedValue()
  252. const lead=runtime.workspace.createAgent('first',{name:'任务负责人',profile:'default',canManageTeam:true})
  253. const member=runtime.workspace.createAgent('first',{name:'成员',profile:'default'})
  254. const source=runtime.workspace.list<any>('first','conversation').find(c=>c.kind==='direct'&&c.memberIds[0]===lead.id)!
  255. const original=runtime.workspaceRuntime.send('first',source.id,{requestId:randomUUID(),content:'完成任务'})
  256. const team=runtime.workspace.createGroup('first',{name:'任务组',memberIds:[lead.id,member.id],administratorId:lead.id})
  257. const task=runtime.workspace.tasks('first',team.id)[0]!
  258. runtime.workspaceRuntime.tasks.begin('first',task,lead,'完成任务',{conversationId:source.id,runId:original.id,agentId:lead.id})
  259. await req('post',`/api/app/conversations/${team.id}/tasks/${task.id}/stop`).send({}).expect(200)
  260. const input={requestId:randomUUID()}
  261. const resumed=await req('post',`/api/app/conversations/${team.id}/tasks/${task.id}/resume`).send(input).expect(200)
  262. expect(resumed.body.goal.status).toBe('running')
  263. const repeated=await req('post',`/api/app/conversations/${team.id}/tasks/${task.id}/resume`).send(input).expect(200)
  264. expect(repeated.body.run.id).toBe(resumed.body.run.id)
  265. await req('post',`/api/app/conversations/${team.id}/tasks/${task.id}/resume`,'second').send({requestId:randomUUID()}).expect(404)
  266. })
  267. it('grants team management only with a ready bridge and persists explicit revocation', async () => {
  268. const denied = await req('post','/api/app/agents').send({name:'老板',profile:'default',canManageTeam:true}).expect(409)
  269. expect(denied.body.code).toBe('team_tools_unavailable')
  270. expect((await req('get','/api/app/agents')).body.agents).toEqual([])
  271. bridgeReady = true
  272. const agent = (await req('post','/api/app/agents').send({name:'老板',profile:'default',canManageTeam:true}).expect(201)).body.agent
  273. expect(agent.canManageTeam).toBe(true)
  274. await req('patch',`/api/app/agents/${agent.id}`,'second').send({canManageTeam:false}).expect(404)
  275. bridgeReady = false
  276. const disabled = await req('patch',`/api/app/agents/${agent.id}`).send({canManageTeam:false}).expect(200)
  277. expect(disabled.body.agent.canManageTeam).toBe(false)
  278. expect((await req('get','/api/app/agents')).body.agents[0].canManageTeam).toBe(false)
  279. await req('patch',`/api/app/agents/${agent.id}`).send({canManageTeam:true}).expect(409)
  280. })
  281. it('accepts only child pairing, hides credentials, and scopes address edits to the owner', async () => {
  282. const code = new URL('yaoyao://pair')
  283. for (const [key,value] of Object.entries({v:'1',url:'http://child.test:15300',node:'11111111-1111-4111-8111-111111111111',id:'33333333-3333-4333-8333-333333333333',fingerprint:'f'.repeat(64),secret:'s'.repeat(64)})) code.searchParams.set(key,value)
  284. await req('post','/api/app/nodes').send({name:'legacy',url:'http://child.test:9119',username:'user',password:'password'}).expect(400)
  285. await req('post','/api/app/nodes').send({name:'child',qrPayload:code.href.replace('://pair','://login')}).expect(400)
  286. await req('post','/api/app/nodes').send({name:'child',qrPayload:code.href}).expect(201)
  287. const listing=await req('get','/api/app/nodes').expect(200), node=listing.body.nodes[0]
  288. expect(node.transport).toBe('paired-web'); expect(JSON.stringify(listing.body)).not.toContain('delegated-token'); expect(node.secret).toBeUndefined()
  289. expect((await req('get','/api/app/nodes','second').expect(200)).body.nodes).toEqual([])
  290. await req('patch',`/api/app/nodes/${node.id}`,'second').send({name:'other',url:'http://new-ip.test:15300'}).expect(404)
  291. await req('patch',`/api/app/nodes/${node.id}`).send({name:'new name',url:'http://new-ip.test:15300'}).expect(200)
  292. const updated=(await req('get','/api/app/nodes').expect(200)).body.nodes[0]
  293. expect(updated.id).toBe(node.id); expect(updated.url).toBe('http://new-ip.test:15300/')
  294. const sources=(await req('get','/api/app/agents/sources').expect(200)).body.sources
  295. expect(sources.some((s:any)=>s.nodeId===node.id && s.profile==='default')).toBe(true)
  296. })
  297. it('archives native-chat uploads through the standard file API with user ownership', async () => {
  298. const assets = new WorkspaceAssets(runtime.workspace, runtime.workspaceRuntime.nodes, home)
  299. await assets.archiveText(
  300. 'first',
  301. '{"path":"/tmp/native-upload.txt"}',
  302. 'local',
  303. 'default',
  304. 'native-session',
  305. 'native-message',
  306. 'user',
  307. )
  308. const page = await req('get', '/api/app/files').expect(200)
  309. expect(page.body.items[0]).toMatchObject({
  310. name: 'native-upload.txt',
  311. sender: 'user',
  312. profile: 'default',
  313. })
  314. expect(upstream).toContain('/api/files/download')
  315. expect((await req('get', '/api/app/files', 'second')).body.items).toEqual([])
  316. expect(upstream.some((p) => p.includes('/plugins/'))).toBe(false)
  317. })
  318. it('works without plugin discovery, installation, or any plugin HTTP request', async () => {
  319. const capabilities = (await req('get', '/api/app/capabilities').expect(200)).body.features
  320. expect(capabilities).toContain('editableGroups')
  321. expect(capabilities).not.toContain('immutableGroups')
  322. await req('get', '/api/app/files').expect(200)
  323. await req('get', '/api/app/voice/runtime').expect(200)
  324. await req('get', '/api/app/system/update/status').expect(200)
  325. await req('post', '/api/app/plugins/yaoyao/reconcile').send({}).expect(410)
  326. await req('get', '/api/plugins/yaoyao/v1/capabilities').expect(410)
  327. expect(upstream.some((p) => p.includes('/plugins/'))).toBe(false)
  328. })
  329. it('changes members over HTTP while protecting the administrator and ownership', async () => {
  330. const a = (
  331. await req('post', '/api/app/agents').send({ name: '编辑', profile: 'default' }).expect(201)
  332. ).body.agent
  333. const b = (
  334. await req('post', '/api/app/agents').send({ name: '审查', profile: 'default' }).expect(201)
  335. ).body.agent
  336. const c = (
  337. await req('post', '/api/app/conversations')
  338. .send({ name: '团队', memberIds: [a.id, b.id], administratorId: a.id })
  339. .expect(201)
  340. ).body.conversation
  341. const rows = await req('get', '/api/app/conversations').expect(200)
  342. expect(rows.body.conversations).toHaveLength(3)
  343. await req('patch', `/api/app/conversations/${c.id}`)
  344. .send({ memberIds: [b.id], administratorId: b.id })
  345. .expect(400)
  346. await req('patch', `/api/app/conversations/${c.id}`).send({ memberIds: [a.id] }).expect(200)
  347. expect((await req('get', `/api/app/conversations/${c.id}`)).body.conversation.memberIds).toEqual([a.id])
  348. await req('patch', `/api/app/conversations/${c.id}`).send({ memberIds: [a.id, b.id] }).expect(200)
  349. await req('get', `/api/app/conversations/${c.id}`, 'second').expect(404)
  350. await req('patch', `/api/app/agents/${a.id}`, 'second').send({ name: '入侵' }).expect(404)
  351. expect((await req('get', '/api/app/events', 'second')).body.events).toEqual([])
  352. expect(upstream.some((p) => p.includes('sessions'))).toBe(false)
  353. })
  354. it('creates, lists, renames, selects, and deletes group tasks without changing remote members', async () => {
  355. const a = (
  356. await req('post', '/api/app/agents').send({ name: '本机管理员', profile: 'default' }).expect(201)
  357. ).body.agent
  358. const b = (
  359. await req('post', '/api/app/agents').send({ name: '远程成员', nodeId: 'local', profile: 'default' }).expect(201)
  360. ).body.agent
  361. const conversation = (
  362. await req('post', '/api/app/conversations')
  363. .send({ name: '多任务团队', memberIds: [a.id, b.id], administratorId: a.id })
  364. .expect(201)
  365. ).body.conversation
  366. const initial = (await req('get', `/api/app/conversations/${conversation.id}/tasks`).expect(200)).body.tasks
  367. expect(initial).toHaveLength(1)
  368. expect(initial[0]).toMatchObject({
  369. conversationId: conversation.id,
  370. title: '新任务',
  371. titleSource: 'automatic',
  372. messageCount: 0,
  373. })
  374. const task = (
  375. await req('post', `/api/app/conversations/${conversation.id}/tasks`)
  376. .send({ title: '远程 Agent 调研' })
  377. .expect(201)
  378. ).body.task
  379. expect(task).toMatchObject({ title: '远程 Agent 调研', titleSource: 'user' })
  380. const renamed = (
  381. await req('patch', `/api/app/conversations/${conversation.id}/tasks/${task.id}`)
  382. .send({ title: '远程 Agent 复核' })
  383. .expect(200)
  384. ).body.task
  385. expect(renamed).toMatchObject({ title: '远程 Agent 复核', titleSource: 'user' })
  386. const detail = (await req('get', `/api/app/conversations/${conversation.id}?taskId=${task.id}`).expect(200)).body
  387. expect(detail.task.id).toBe(task.id)
  388. expect(detail.tasks.map((row: { id: string }) => row.id)).toContain(task.id)
  389. expect(detail.messages).toEqual([])
  390. expect(detail.conversation).toMatchObject({ memberIds: [a.id, b.id], administratorId: a.id })
  391. expect((await req('put', `/api/app/conversations/${conversation.id}/tasks/${task.id}/read`).send({ seq: 100 }).expect(200)).body.task)
  392. .toMatchObject({ readSeq: 0, lastSeq: 0, unreadCount: 0 })
  393. await req('get', `/api/app/conversations/${conversation.id}/tasks`, 'second').expect(404)
  394. await req('delete', `/api/app/conversations/${conversation.id}/tasks/${task.id}`).expect(200)
  395. const remaining = (await req('get', `/api/app/conversations/${conversation.id}/tasks`).expect(200)).body.tasks
  396. expect(remaining.map((row: { id: string }) => row.id)).not.toContain(task.id)
  397. expect((await req('get', `/api/app/conversations/${conversation.id}`)).body.conversation)
  398. .toMatchObject({ memberIds: [a.id, b.id], administratorId: a.id })
  399. await req('delete', `/api/app/conversations/${conversation.id}/tasks/${initial[0].id}`).expect(200)
  400. const replacement = (await req('get', `/api/app/conversations/${conversation.id}/tasks`).expect(200)).body.tasks
  401. expect(replacement).toHaveLength(1)
  402. expect(replacement[0].id).not.toBe(initial[0].id)
  403. })
  404. it('archives files on the Web server, preserves native library fields, and blocks cross-user downloads', async () => {
  405. const f = (
  406. await req('post', '/api/app/uploads')
  407. .attach('files', Buffer.from('hello'), { filename: 'hello.txt', contentType: 'text/plain' })
  408. .expect(201)
  409. ).body.files[0]
  410. expect(f.path).toBeUndefined()
  411. expect(runtime.uploads.cleanupUncommitted(0)).toBe(0)
  412. const list = await req('get', '/api/app/files').expect(200),
  413. item = list.body.items[0]
  414. expect(typeof item.id).toBe('number')
  415. expect(item.path).toBe(`/api/app/files/${f.id}/download`)
  416. expect(item).toMatchObject({ name: 'hello.txt', size: 5, exists: true, archiveStatus: 'ready' })
  417. expect((await req('get', item.path).expect(200)).text).toBe('hello')
  418. await req('get', item.path, 'second').expect(404)
  419. await req('get', `/api/app/files/${item.id}/download`, 'second').expect(404)
  420. expect((await req('get', '/api/app/files', 'second')).body.total).toBe(0)
  421. expect(upstream.some((p) => p.includes('/files'))).toBe(false)
  422. })
  423. it('does not serve uploaded HTML or SVG as executable same-origin previews', async () => {
  424. const f = (
  425. await req('post', '/api/app/uploads')
  426. .attach('files', Buffer.from('<svg onload="alert(1)"/>'), {
  427. filename: 'unsafe.svg',
  428. contentType: 'image/svg+xml',
  429. })
  430. .expect(201)
  431. ).body.files[0]
  432. const response = await req('get', `/api/app/files/${f.id}/preview`).expect(200)
  433. expect(response.headers['content-type']).toContain('application/octet-stream')
  434. expect(response.headers['content-disposition']).toContain('attachment')
  435. })
  436. it('persists encrypted voice credentials while giving each user their own selected voice', async () => {
  437. await req('put', '/api/app/admin/duplex-voice')
  438. .send({
  439. apiKey: 'private-test-key',
  440. voices: [
  441. { id: 'a', name: '甲' },
  442. { id: 'b', name: '乙' },
  443. ],
  444. currentVoiceId: 'a',
  445. })
  446. .expect(200)
  447. const publicResponse = await req('get', '/api/app/admin/duplex-voice').expect(200)
  448. expect(publicResponse.body.hasApiKey).toBe(true)
  449. expect(publicResponse.body.apiKey).toBeUndefined()
  450. await req('put', '/api/app/voice/current-voice', 'second')
  451. .send({ currentVoiceId: 'b' })
  452. .expect(200)
  453. expect((await req('get', '/api/app/voice/runtime')).body.currentVoiceId).toBe('a')
  454. expect((await req('get', '/api/app/voice/runtime', 'second')).body.currentVoiceId).toBe('b')
  455. expect(
  456. readFileSync(join(home, 'workspace.sqlite3')).includes(Buffer.from('private-test-key')),
  457. ).toBe(false)
  458. })
  459. it('stores monotonic profile-scoped context snapshots without a plugin', async () => {
  460. const path = '/api/app/session-context/session-one?profile=default'
  461. const b = { usedTokens: 200, limitTokens: 1000, percent: 20, observedAt: 20 }
  462. await req('put', path).send(b).expect(200)
  463. await req('put', path)
  464. .send({ ...b, usedTokens: 10, observedAt: 10 })
  465. .expect(200)
  466. expect((await req('get', path)).body.snapshot).toMatchObject({ ...b, sessionId: 'session-one' })
  467. expect((await req('get', path, 'second')).body.snapshot).toBeNull()
  468. expect(
  469. (await req('get', '/api/app/session-context/session-one?profile=other')).body.snapshot,
  470. ).toBeNull()
  471. })
  472. it('protects internal Hermes session IDs on native HTTP endpoints', async () => {
  473. runtime.workspace.put('first', 'binding', 'binding', {
  474. storedId: 'internal-session',
  475. runtimeId: 'internal-runtime',
  476. aliases: ['old-id'],
  477. })
  478. await req('get', '/api/app/sessions/internal-session/messages').expect(404)
  479. await req('get', '/api/sessions/old-id/messages', 'second').expect(404)
  480. expect(upstream.some((p) => p.includes('internal-session') || p.includes('old-id'))).toBe(false)
  481. })
  482. })