workspaceRoutes.test.ts 36 KB

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