workspaceRoutes.test.ts 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825
  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 { saveFileAccess } from '../../src/server/fileAccess'
  14. import { WorkspaceTranscriptStore } from '../../src/client/components/workspace/transcriptStore'
  15. import { SharedComputers, type SharedComputer } from '../../src/server/sharedComputers'
  16. import type { WorkspaceAgent, WorkspaceConversation } from '../../src/shared/workspace'
  17. let home: string, runtime: ApplicationRuntime, cookie: string, csrf: string, upstream: string[], bridgeReady: boolean
  18. const first: LocalUser = {
  19. id: 'first',
  20. username: 'first',
  21. role: 'admin',
  22. enabled: true,
  23. mustChangePassword: false,
  24. createdAt: 1,
  25. updatedAt: 1,
  26. }
  27. class TestAuth extends LocalAuthStore {
  28. override current(ctx: Koa.Context) {
  29. return this.require(ctx)
  30. }
  31. override require(ctx: Koa.Context) {
  32. return { ...first, id: ctx.get('x-test-user') || 'first' }
  33. }
  34. override requireAdmin(ctx: Koa.Context) {
  35. return this.require(ctx)
  36. }
  37. override canUseSource() { return true }
  38. override currentFromCookieHeader() {
  39. return first
  40. }
  41. override isUserActive() {
  42. return true
  43. }
  44. }
  45. function req(method: 'get' | 'post' | 'put' | 'patch' | 'delete', path: string, user = 'first') {
  46. return request(runtime.app.callback())
  47. [method](path)
  48. .set('Host', '127.0.0.1:15300')
  49. .set('Origin', 'http://127.0.0.1:15300')
  50. .set('Cookie', cookie)
  51. .set('X-CSRF-Token', csrf)
  52. .set('x-test-user', user)
  53. }
  54. function shareComputer(...agents: WorkspaceAgent[]): SharedComputer {
  55. const store = runtime.workspace
  56. const shared = new SharedComputers(store, runtime.auth, runtime.workspaceRuntime.nodes, runtime.runners)
  57. for (const agent of agents) {
  58. shared.attachLocalVm('first', agent, 'fixture-runner')
  59. store.put('first', 'agent', agent.id, agent)
  60. }
  61. return store.require('first', 'shared-computer', agents[0]!.computerEnvironmentId!)
  62. }
  63. it('serves file-backed project and memory CRUD with revisions and account isolation', async () => {
  64. const a = runtime.workspace.createAgent('first', { name: '记忆甲', profile: 'default' })
  65. const b = runtime.workspace.createAgent('first', { name: '记忆乙', profile: 'default' })
  66. const group = runtime.workspace.createGroup('first', { name: '项目群', memberIds: [a.id, b.id], collaborationMode: 'discussion' })
  67. const project = await req('post', '/api/app/workspace/projects').send({ requestId: randomUUID(), name: '项目', description: '多群共享', memberIds: [a.id, b.id], groupIds: [group.id] }).expect(200)
  68. const id = project.body.project.id
  69. const created = await req('post', '/api/app/workspace/memories').send({ requestId: randomUUID(), scope: 'project', projectId: id, agentId: a.id, content: '接口兼容旧版本', tier: 'profile' }).expect(200)
  70. const memory = created.body.memory
  71. expect((await req('get', `/api/app/workspace/memories?scope=project&projectId=${id}`).expect(200)).body.memories).toHaveLength(1)
  72. await req('post', '/api/app/workspace/memories').send({ requestId: randomUUID(), scope: 'project', projectId: id, agentId: a.id, id: memory.id, expectedRevision: 0, content: '旧版本修改', tier: 'profile' }).expect(400)
  73. expect((await req('get', `/api/app/workspace/memories/${memory.id}/revisions?scope=project&agentId=${a.id}&projectId=${id}`).expect(200)).body.revisions).toHaveLength(1)
  74. expect((await req('get', '/api/app/workspace/projects', 'second').expect(200)).body.projects).toEqual([])
  75. expect((await req('get', `/api/app/workspace/memory-export?scope=project&projectId=${id}`).expect(200)).text).toContain('接口兼容旧版本')
  76. await req('post', '/api/app/workspace/memories/forget').send({ requestId: randomUUID(), scope: 'project', projectId: id, agentId: a.id, id: memory.id, expectedRevision: 1 }).expect(200)
  77. expect((await req('get', `/api/app/workspace/memories?scope=project&projectId=${id}`).expect(200)).body.memories).toEqual([])
  78. })
  79. beforeEach(async () => {
  80. home = mkdtempSync(join(tmpdir(), 'yaoyao-workspace-routes-'))
  81. upstream = []
  82. bridgeReady = false
  83. const config = loadServerConfig({
  84. HERMES_YAOYAO_HOME: home,
  85. HERMES_YAOYAO_UPSTREAM: 'http://127.0.0.1:19119',
  86. HERMES_YAOYAO_ALLOWED_HOSTS: '127.0.0.1,localhost',
  87. })
  88. runtime = createApplication({
  89. config,
  90. auth: new TestAuth(home, false),
  91. fetchImpl: (async (input) => {
  92. const path = new URL(String(input)).pathname
  93. upstream.push(path)
  94. const body =
  95. path === '/api/plugins/yaoyao-bot-bridge/capabilities' && bridgeReady
  96. ? {version:1,ready:true,in_process:true,native_tools:true}
  97. : path === '/api/pair/v1/capabilities'
  98. ? {protocolVersion:1,serviceType:'yaoyao-web',nodeId:'11111111-1111-4111-8111-111111111111',fingerprint:'f'.repeat(64)}
  99. : path === '/api/pair/v1/claim'
  100. ? {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'}
  101. : path === '/api/status'
  102. ? { auth_required: true }
  103. : path === '/api/auth/me'
  104. ? { user_id: 'upstream' }
  105. : path.endsWith('/api/profiles')
  106. ? { profiles: [{ name: 'default', display_name: '基础 Agent' }] }
  107. : { ok: true }
  108. return new Response(JSON.stringify(body), {
  109. status: path.includes('/plugins/') && !bridgeReady ? 404 : 200,
  110. headers: { 'Content-Type': 'application/json' },
  111. })
  112. }) as typeof fetch,
  113. })
  114. const b = await request(runtime.app.callback())
  115. .get('/api/app/bootstrap')
  116. .set('Host', '127.0.0.1:15300')
  117. .expect(200)
  118. cookie = (b.headers['set-cookie'] as unknown as string[]).map((v) => v.split(';')[0]).join('; ')
  119. csrf = b.body.csrfToken
  120. })
  121. afterEach(() => {
  122. runtime.close()
  123. rmSync(home, { recursive: true, force: true })
  124. })
  125. describe('application workspace HTTP contract', () => {
  126. it.each(['empty', 'existing'] as const)('serves a complete %s Bot snapshot before any Runner or virtual machine is created', async state => {
  127. const store = runtime.workspace
  128. expect(runtime.runners.records()).toEqual([])
  129. expect(store.list('first', 'shared-computer')).toEqual([])
  130. let conversation: WorkspaceConversation | undefined
  131. if (state === 'existing') {
  132. store.createAgent('first', { name: '尚未配置电脑的 Bot', profile: 'default' })
  133. conversation = store.list<WorkspaceConversation>('first', 'conversation')[0]!
  134. store.saveMessage('first', { id: randomUUID(), conversationId: conversation.id, seq: 0, role: 'assistant',
  135. content: '没有虚拟机也能读取聊天记录', reasoning: '', status: 'complete', tools: [], attachments: [], createdAt: Date.now() })
  136. }
  137. const requestsBeforeSnapshot = [...upstream]
  138. const response = await req('get', '/api/app/workspace/snapshot').expect(200).expect('Content-Type', /json/)
  139. const snapshot = response.body
  140. expect(Number.isSafeInteger(snapshot.cursor)).toBe(true)
  141. expect(snapshot.cursor).toBeGreaterThanOrEqual(0)
  142. for (const key of ['agents', 'conversations', 'details', 'projects']) expect(Array.isArray(snapshot[key])).toBe(true)
  143. const client = new WorkspaceTranscriptStore()
  144. expect(() => client.hydrate(snapshot)).not.toThrow()
  145. expect(client.cursor).toBe(snapshot.cursor)
  146. if (conversation) {
  147. expect(client.conversations.map(row => row.id)).toEqual([conversation.id])
  148. expect(client.get(conversation.id)?.messages.map(message => message.content)).toEqual(['没有虚拟机也能读取聊天记录'])
  149. } else {
  150. expect(snapshot).toMatchObject({ cursor: 0, agents: [], conversations: [], details: [] })
  151. }
  152. expect(runtime.runners.records()).toEqual([])
  153. expect(store.list('first', 'shared-computer')).toEqual([])
  154. expect(upstream).toEqual(requestsBeforeSnapshot)
  155. })
  156. it('does not advertise retired remote Bot references and preserves their existing history', async () => {
  157. const store = runtime.workspace
  158. const agent = store.createAgent('first', { name: '历史远程 Bot', profile: 'default' })
  159. store.put('first', 'agent', agent.id, { ...agent, remoteAgentId: randomUUID() })
  160. const conversation = store.list<import('../../src/shared/workspace').WorkspaceConversation>('first', 'conversation')[0]!
  161. store.saveMessage('first', { id: randomUUID(), conversationId: conversation.id, seq: 0, role: 'assistant', content: '保留历史回复', reasoning: '', status: 'complete', tools: [], attachments: [], createdAt: Date.now() })
  162. const capabilities = (await req('get', '/api/app/capabilities').expect(200)).body.features
  163. expect(capabilities).not.toContain('remoteAgentReferences')
  164. expect((await req('get', `/api/app/nodes/${randomUUID()}/agents`).expect(410)).body.code).toBe('remote_agent_removed')
  165. expect((await req('post', '/api/app/agents/remote').send({ nodeId: randomUUID(), agentId: randomUUID() }).expect(410)).body.code).toBe('remote_agent_removed')
  166. expect((await req('get', `/api/app/conversations/${conversation.id}`).expect(200)).body.messages.some((message: { content: string }) => message.content === '保留历史回复')).toBe(true)
  167. expect(store.get('first', 'agent', agent.id)).toBeDefined()
  168. })
  169. it('uses the same ordering for snapshots, list refreshes and pin/message events', async () => {
  170. const store = runtime.workspace
  171. store.createAgent('first', { name: '排序验证', profile: 'default' })
  172. const base = store.list<import('../../src/shared/workspace').WorkspaceConversation>('first', 'conversation')[0]!
  173. store.remove('first', 'conversation', base.id)
  174. for (const item of [
  175. { id: 'a-old', lastMessageAt: 100, pinned: false },
  176. { id: 'b-new', lastMessageAt: 200, pinned: false },
  177. { id: 'z-pin', lastMessageAt: 50, pinned: true },
  178. ]) store.put('first', 'conversation', item.id, { ...base, ...item })
  179. const snapshot = (await req('get', '/api/app/workspace/snapshot').expect(200)).body
  180. const list = (await req('get', '/api/app/conversations').expect(200)).body.conversations
  181. expect(snapshot.conversations.map((c: { id: string }) => c.id)).toEqual(['z-pin', 'b-new', 'a-old'])
  182. expect(list.map((c: { id: string }) => c.id)).toEqual(snapshot.conversations.map((c: { id: string }) => c.id))
  183. const clients = [new WorkspaceTranscriptStore(), new WorkspaceTranscriptStore()]
  184. clients.forEach(client => client.hydrate(snapshot))
  185. const stop = store.observe((owner, event) => { if (owner === 'first') clients.forEach(client => client.apply(event)) })
  186. try {
  187. store.saveMessage('first', { id: randomUUID(), conversationId: 'a-old', seq: 0, role: 'assistant',
  188. content: '新的回复', reasoning: '', status: 'complete', attachments: [], tools: [], createdAt: 300 })
  189. clients.forEach(client => expect(client.conversations.map(c => c.id)).toEqual(['z-pin', 'a-old', 'b-new']))
  190. await req('patch', '/api/app/conversations/a-old').send({ pinned: true }).expect(200)
  191. const expected = ['a-old', 'z-pin', 'b-new']
  192. clients.forEach(client => expect(client.conversations.map(c => c.id)).toEqual(expected))
  193. expect((await req('get', '/api/app/workspace/snapshot').expect(200)).body.conversations.map((c: { id: string }) => c.id)).toEqual(expected)
  194. expect((await req('get', '/api/app/conversations').expect(200)).body.conversations.map((c: { id: string }) => c.id)).toEqual(expected)
  195. } finally { stop() }
  196. })
  197. it.each(['direct', 'group'] as const)('uses versioned unread acknowledgments for %s without recounting history', async kind => {
  198. const store = runtime.workspace
  199. const first = store.createAgent('first', { name: '未读甲', profile: 'default' })
  200. const second = store.createAgent('first', { name: '未读乙', profile: 'default' })
  201. const conversation = kind === 'group'
  202. ? store.createGroup('first', { name: '未读群', memberIds: [first.id, second.id], administratorId: first.id })
  203. : store.list<any>('first', 'conversation').find(c => c.memberIds[0] === first.id)
  204. const task = kind === 'group' ? store.tasks('first', conversation.id)[0] : undefined
  205. const message: import('../../src/shared/workspace').WorkspaceMessage = { id: randomUUID(), conversationId: conversation.id, conversationTaskId: task?.id,
  206. seq: 0, role: 'assistant', content: '进行中', reasoning: '', status: 'streaming', attachments: [], tools: [], createdAt: Date.now() }
  207. store.saveMessage('first', message)
  208. const snapshot = (await req('get', `/api/app/conversations/${conversation.id}`).expect(200)).body
  209. const read = snapshot.task ?? snapshot.conversation
  210. expect(read.unread).toBe(false)
  211. message.status = 'complete'; message.content = '已完成'; store.saveMessage('first', message)
  212. const path = `/api/app/conversations/${conversation.id}${task ? `/tasks/${task.id}` : ''}/read`
  213. const display = vi.spyOn(store, 'messageForDisplay')
  214. const stale = (await req('put', path).send({ seq: read.lastSeq, unreadVersion: read.unreadVersion }).expect(200)).body
  215. expect(stale.conversation.unread).toBe(true)
  216. const current = stale.task ?? stale.conversation
  217. const acknowledged = (await req('put', path).send({ seq: current.lastSeq, unreadVersion: current.unreadVersion }).expect(200)).body
  218. expect(acknowledged.conversation).toMatchObject({ unread: false, unreadCount: 0 })
  219. expect(display).not.toHaveBeenCalled()
  220. await req('put', path, 'foreign').send({ seq: current.lastSeq, unreadVersion: current.unreadVersion }).expect(404)
  221. await req('put', path).send({ seq: current.lastSeq, unreadVersion: -1 }).expect(400)
  222. display.mockRestore()
  223. })
  224. it.each(['archive', 'delete'] as const)('%s removes a confirmed ordinary member from all groups atomically', async action => {
  225. const store = runtime.workspace
  226. const lead = store.createAgent('first', { name: '管理者', profile: 'default' })
  227. const bot = store.createAgent('first', { name: '待处理成员', profile: 'default' })
  228. const direct = store.list<any>('first', 'conversation').find(c => c.kind === 'direct' && c.memberIds[0] === bot.id)
  229. const group = store.createGroup('first', { name: '设计群', memberIds: [lead.id, bot.id], administratorId: lead.id, autoReplyIds: [bot.id], memberRoles: { [bot.id]: { name: '设计', description: '' } } })
  230. const oldGroup = store.createGroup('first', { name: '旧群', memberIds: [lead.id, bot.id], administratorId: lead.id })
  231. store.updateConversation('first', oldGroup.id, { archived: true })
  232. const path = `/api/app/conversations/${direct.id}/lifecycle`
  233. const preview = (await req('get', path).expect(200)).body
  234. expect(preview.groups).toEqual(expect.arrayContaining([{ id: group.id, name: '设计群', administrator: false }, { id: oldGroup.id, name: '旧群', administrator: false }]))
  235. await req('post', path).send({ action }).expect(409)
  236. expect((await req('patch', `/api/app/agents/${bot.id}`).send({ archived: true }).expect(409)).body.code).toBe('agent_in_group')
  237. await req('get', path, 'foreign').expect(404)
  238. await req('post', path, 'foreign').send({ action, confirmationToken: preview.confirmationToken }).expect(404)
  239. await req('post', path).set('X-CSRF-Token', 'invalid').send({ action, confirmationToken: preview.confirmationToken }).expect(403)
  240. await req('post', path).send({ action, confirmationToken: preview.confirmationToken }).expect(200)
  241. expect(store.require<any>('first', 'conversation', group.id)).toMatchObject({ memberIds: [lead.id], autoReplyIds: [], memberRoles: {}, administratorId: lead.id })
  242. expect(store.require<any>('first', 'conversation', oldGroup.id).memberIds).toEqual([lead.id])
  243. if (action === 'delete') {
  244. expect(store.get('first', 'agent', bot.id)).toBeUndefined()
  245. expect(store.get('first', 'conversation', direct.id)).toBeUndefined()
  246. } else {
  247. expect(store.require<any>('first', 'agent', bot.id).archived).toBe(true)
  248. await req('post', path).send({ action: 'restore' }).expect(200)
  249. expect(store.require<any>('first', 'conversation', direct.id).archived).toBe(false)
  250. expect(store.require<any>('first', 'conversation', group.id).memberIds).toEqual([lead.id])
  251. }
  252. expect(store.get('first', 'agent', lead.id)).toBeDefined()
  253. })
  254. it.each(['archive', 'delete'] as const)('blocks %s for a group administrator without removing other memberships', async action => {
  255. const store = runtime.workspace
  256. const bot = store.createAgent('first', { name: '群管理者', profile: 'default' })
  257. const other = store.createAgent('first', { name: '其他成员', profile: 'default' })
  258. const direct = store.list<any>('first', 'conversation').find(c => c.kind === 'direct' && c.memberIds[0] === bot.id)
  259. const regular = store.createGroup('first', { name: '普通群', memberIds: [bot.id, other.id], administratorId: other.id })
  260. const managed = store.createGroup('first', { name: '管理群', memberIds: [bot.id, other.id], administratorId: bot.id })
  261. const path = `/api/app/conversations/${direct.id}/lifecycle`
  262. const preview = (await req('get', path).expect(200)).body
  263. const cursor = store.cursor('first')
  264. const result = await req('post', path).send({ action, confirmationToken: preview.confirmationToken }).expect(409)
  265. expect(result.body.code).toBe('agent_group_administrator')
  266. expect(result.body.error).toContain('管理群')
  267. expect(store.require<any>('first', 'conversation', regular.id).memberIds).toContain(bot.id)
  268. expect(store.require<any>('first', 'conversation', managed.id).administratorId).toBe(bot.id)
  269. expect(store.require<any>('first', 'agent', bot.id).archived).toBe(false)
  270. expect(store.cursor('first')).toBe(cursor)
  271. })
  272. it.each(['archive', 'delete'] as const)('%s detaches only the selected Bot from its automatic shared computer', async action => {
  273. const store = runtime.workspace
  274. const bot = store.createAgent('first', { name: '待移除共享成员', profile: 'default' })
  275. const other = store.createAgent('first', { name: '继续使用电脑', profile: 'default' })
  276. const shared = shareComputer(bot, other)
  277. const otherBefore = store.require('first', 'agent', other.id)
  278. const direct = store.list<any>('first', 'conversation').find(c => c.kind === 'direct' && c.memberIds[0] === bot.id)
  279. const path = `/api/app/conversations/${direct.id}/lifecycle`
  280. const preview = (await req('get', path).expect(200)).body
  281. // Another member's running task must not prevent removing this idle Bot.
  282. store.put('first', 'turn', 'other-running', { id: 'other-running', agentId: other.id, status: 'running' })
  283. await req('post', path).send({ action, confirmationToken: preview.confirmationToken }).expect(200)
  284. expect(store.require('first', 'shared-computer', shared.id)).toEqual({ ...shared, memberIds: [other.id] })
  285. expect(store.require('first', 'agent', other.id)).toEqual(otherBefore)
  286. if (action === 'delete') expect(store.get('first', 'agent', bot.id)).toBeUndefined()
  287. else {
  288. const archived = store.require<WorkspaceAgent>('first', 'agent', bot.id)
  289. expect(archived.archived).toBe(true)
  290. expect(archived.computerEnvironmentId).toBeUndefined()
  291. expect(archived.computerEnvironmentName).toBeUndefined()
  292. }
  293. store.remove('first', 'turn', 'other-running')
  294. })
  295. it('keeps shared membership intact while the Bot is busy or its computer is under human control', async () => {
  296. const store = runtime.workspace
  297. const bot = store.createAgent('first', { name: '电脑成员', profile: 'default' })
  298. const shared = shareComputer(bot)
  299. const direct = store.list<any>('first', 'conversation').find(c => c.memberIds[0] === bot.id)
  300. const path = `/api/app/conversations/${direct.id}/lifecycle`
  301. const preview = (await req('get', path).expect(200)).body
  302. for (const status of ['queued', 'running', 'waiting', 'uncertain', 'cancelling']) {
  303. store.put('first', 'turn', 'busy', { id: 'busy', agentId: bot.id, status })
  304. expect((await req('post', path).send({ action: 'delete', confirmationToken: preview.confirmationToken }).expect(409)).body.code).toBe('agent_running')
  305. }
  306. store.remove('first', 'turn', 'busy')
  307. store.put('_system', 'computer-control', 'human', { owner: 'first', agentId: randomUUID(), environmentId: shared.id, expiresAt: Date.now() + 30_000 })
  308. expect((await req('post', path).send({ action: 'delete', confirmationToken: preview.confirmationToken }).expect(409)).body.code).toBe('agent_execution_busy')
  309. expect(store.require('first', 'shared-computer', shared.id)).toEqual(shared)
  310. expect(store.require('first', 'agent', bot.id)).toEqual(bot)
  311. store.remove('_system', 'computer-control', 'human')
  312. await req('patch', `/api/app/agents/${bot.id}`).send({ archived: true }).expect(200)
  313. expect(store.require('first', 'shared-computer', shared.id)).toMatchObject({ archived: true, memberIds: [] })
  314. expect(store.require<WorkspaceAgent>('first', 'agent', bot.id).computerEnvironmentId).toBeUndefined()
  315. })
  316. it.each(['manual', 'compose', 'missing'] as const)('deletes a legacy archived Bot with a %s computer binding', async mode => {
  317. const store = runtime.workspace
  318. const bot = store.createAgent('first', { name: '旧版归档成员', profile: 'default' })
  319. const shared = shareComputer(bot)
  320. const direct = store.list<any>('first', 'conversation').find(c => c.memberIds[0] === bot.id)
  321. store.put('first', 'agent', bot.id, { ...bot, archived: true })
  322. store.put('first', 'conversation', direct.id, { ...direct, archived: true })
  323. if (mode === 'missing') store.remove('first', 'shared-computer', shared.id)
  324. else store.put('first', 'shared-computer', shared.id, { ...shared, managedLocalVm: undefined, managedCompose: mode === 'compose' })
  325. await req('delete', `/api/app/agents/${bot.id}`).expect(200)
  326. expect(store.get('first', 'agent', bot.id)).toBeUndefined()
  327. expect(store.get('first', 'conversation', direct.id)).toBeUndefined()
  328. if (mode !== 'missing') expect(store.require('first', 'shared-computer', shared.id)).toMatchObject({ archived: true, memberIds: [] })
  329. })
  330. it('rejects a stale group confirmation and rolls back membership on a later deletion failure', async () => {
  331. const store = runtime.workspace
  332. const lead = store.createAgent('first', { name: '负责人', profile: 'default' })
  333. const bot = store.createAgent('first', { name: '成员', profile: 'default' })
  334. const shared = shareComputer(bot, lead)
  335. const direct = store.list<any>('first', 'conversation').find(c => c.kind === 'direct' && c.memberIds[0] === bot.id)
  336. const path = `/api/app/conversations/${direct.id}/lifecycle`
  337. const old = (await req('get', path).expect(200)).body
  338. const group = store.createGroup('first', { name: '后来加入的群', memberIds: [lead.id, bot.id], administratorId: lead.id })
  339. expect((await req('post', path).send({ action: 'delete', confirmationToken: old.confirmationToken }).expect(409)).body.code).toBe('lifecycle_confirmation_stale')
  340. const current = (await req('get', path).expect(200)).body
  341. store.put('first', 'turn', 'pending', { id: 'pending', agentId: bot.id, conversationId: group.id, status: 'uncertain' })
  342. await req('post', path).send({ action: 'archive', confirmationToken: current.confirmationToken }).expect(409)
  343. store.remove('first', 'turn', 'pending')
  344. const cursor = store.cursor('first')
  345. const failure = vi.spyOn(store, 'deleteAgent').mockImplementation(() => { throw new Error('模拟写入失败') })
  346. await req('post', path).send({ action: 'delete', confirmationToken: current.confirmationToken }).expect(500)
  347. failure.mockRestore()
  348. expect(store.require<any>('first', 'conversation', group.id).memberIds).toContain(bot.id)
  349. expect(store.require<any>('first', 'agent', bot.id).archived).toBe(false)
  350. expect(store.require<any>('first', 'conversation', direct.id).archived).toBe(false)
  351. expect(store.require('first', 'shared-computer', shared.id)).toEqual(shared)
  352. expect(store.require<WorkspaceAgent>('first', 'agent', bot.id).computerEnvironmentId).toBe(shared.id)
  353. expect(store.cursor('first')).toBe(cursor)
  354. })
  355. it('retries remote cleanup through either delete endpoint after the local Bot and chat are gone',async()=>{
  356. const store=runtime.workspace,bot=store.createAgent('first',{name:'远端清理重试',profile:'default'})
  357. const direct=store.list<WorkspaceConversation>('first','conversation').find(c=>c.kind==='direct'&&c.memberIds[0]===bot.id)!
  358. const path=`/api/app/conversations/${direct.id}/lifecycle`,preview=(await req('get',path).expect(200)).body
  359. const cleanup=vi.spyOn(runtime.workspaceRuntime,'cleanupAgent').mockRejectedValueOnce(new Error('模拟远端清理失败')).mockResolvedValue(undefined)
  360. await req('delete',`/api/app/agents/${bot.id}`).expect(409)
  361. expect(cleanup).not.toHaveBeenCalled()
  362. await req('post',path).send({action:'delete',confirmationToken:preview.confirmationToken}).expect(500)
  363. expect(store.get('first','agent',bot.id)).toBeUndefined()
  364. expect(store.get('first','conversation',direct.id)).toBeUndefined()
  365. expect(store.get('first','agent-deletion',bot.id)).toBeTruthy()
  366. await req('post',path).send({action:'delete',confirmationToken:preview.confirmationToken}).expect(200)
  367. await req('delete',`/api/app/agents/${bot.id}`).expect(200)
  368. expect(cleanup).toHaveBeenCalledTimes(3)
  369. await req('delete',`/api/app/agents/${bot.id}`,'another').expect(404)
  370. cleanup.mockRestore()
  371. })
  372. it('deletes an unarchived group while preserving its member Bots', async () => {
  373. const store = runtime.workspace
  374. const a = store.createAgent('first', { name: '甲', profile: 'default' }), b = store.createAgent('first', { name: '乙', profile: 'default' })
  375. const group = store.createGroup('first', { name: '待删除群', memberIds: [a.id, b.id], administratorId: a.id })
  376. const path = `/api/app/conversations/${group.id}/lifecycle`
  377. const preview = (await req('get', path).expect(200)).body
  378. await req('post', path).send({ action: 'delete', confirmationToken: preview.confirmationToken }).expect(200)
  379. expect(store.get('first', 'conversation', group.id)).toBeUndefined()
  380. expect(store.get('first', 'agent', a.id)).toBeDefined()
  381. expect(store.get('first', 'agent', b.id)).toBeDefined()
  382. })
  383. it('deletes only archived owned chats, clears their records, and preserves library files and members', async () => {
  384. const store = runtime.workspace
  385. const lead = store.createAgent('first', { name: '负责人', profile: 'default' })
  386. const member = store.createAgent('first', { name: '成员', profile: 'default' })
  387. const group = store.createGroup('first', { name: '待删除群聊', memberIds: [lead.id, member.id], administratorId: lead.id })
  388. const task = store.tasks('first', group.id)[0]!
  389. const path = `/api/app/conversations/${group.id}`
  390. await req('delete', path).expect(409)
  391. store.updateConversation('first', group.id, { archived: true })
  392. store.put('second', 'conversation', group.id, group)
  393. for (const kind of ['message', 'run', 'turn', 'interaction', 'interaction-binding', 'binding', 'assignment']) {
  394. store.put('first', kind, kind, { id: kind, conversationId: group.id, conversationTaskId: task.id, status: 'complete' })
  395. store.put('second', kind, kind, { id: kind, conversationId: group.id })
  396. }
  397. store.put('first', 'context', task.id, { used: 5 })
  398. const bindingKey = `${group.id}:${task.id}:${lead.id}`
  399. store.put('first', 'binding', bindingKey, { conversationTaskId: task.id, sessionId: 'session' })
  400. store.put('first', 'interaction-binding', 'legacy-interaction', { key: bindingKey, taskId: 'turn' })
  401. store.put('second', 'binding', bindingKey, { sessionId: 'other-session' })
  402. store.put('first', 'file', 'file', { id: 'file', conversationId: group.id, messageId: 'message', name: '保留.txt' })
  403. await req('delete', path, 'third').expect(404)
  404. await req('delete', path).set('X-CSRF-Token', 'invalid').expect(403)
  405. await req('delete', path).expect(200)
  406. await req('get', path).expect(404)
  407. expect(store.get('first', 'context', task.id)).toBeUndefined()
  408. expect(store.get('first', 'conversation-task', task.id)).toBeUndefined()
  409. expect(store.list('first', 'message')).toEqual([])
  410. expect(store.list('first', 'run')).toEqual([])
  411. expect(store.list('first', 'binding')).toEqual([])
  412. expect(store.list('first', 'interaction-binding')).toEqual([])
  413. expect(store.get('second', 'binding', bindingKey)).toEqual({ sessionId: 'other-session' })
  414. expect(store.get('first', 'file', 'file')).toEqual({ id: 'file', name: '保留.txt' })
  415. expect(store.list('first', 'agent')).toHaveLength(2)
  416. expect(store.get('second', 'conversation', group.id)).toEqual(group)
  417. expect(store.get('second', 'message', 'message')).toBeDefined()
  418. expect((await req('get', '/api/app/events')).body.events.some((e: any) => e.type === 'conversation.deleted' && e.conversationId === group.id)).toBe(true)
  419. })
  420. it('deletes an archived Bot and its direct chat only after group references are removed', async () => {
  421. const store = runtime.workspace
  422. const bot = store.createAgent('first', { name: '归档 Bot', profile: 'default' })
  423. const member = store.createAgent('first', { name: '成员', profile: 'default' })
  424. const direct = store.list<any>('first', 'conversation').find(c => c.memberIds[0] === bot.id)!
  425. const group = store.createGroup('first', { name: '关联群', memberIds: [bot.id, member.id], administratorId: member.id })
  426. const path = `/api/app/agents/${bot.id}`
  427. await req('delete', path).expect(409)
  428. store.updateAgent('first', bot.id, { archived: true })
  429. await req('delete', `/api/app/conversations/${direct.id}`).expect(400)
  430. expect((await req('delete', path).expect(409)).body.code).toBe('agent_in_group')
  431. expect(store.get('first', 'agent', bot.id)).toBeDefined()
  432. store.updateConversation('first', group.id, { memberIds: [member.id] })
  433. await req('delete', path, 'second').expect(404)
  434. await req('delete', path).expect(200)
  435. expect(store.get('first', 'agent', bot.id)).toBeUndefined()
  436. expect(store.get('first', 'conversation', direct.id)).toBeUndefined()
  437. expect(store.get('first', 'conversation', group.id)).toBeDefined()
  438. expect(store.get('first', 'agent', member.id)).toBeDefined()
  439. })
  440. it('keeps archived chats intact while runs or delegated goals are unresolved', async () => {
  441. const store = runtime.workspace
  442. const bot = store.createAgent('first', { name: '运行中', profile: 'default' })
  443. const direct = store.list<any>('first', 'conversation')[0]!
  444. store.updateAgent('first', bot.id, { archived: true })
  445. store.put('first', 'run', 'pending', { id: 'pending', conversationId: direct.id, status: 'uncertain' })
  446. const path = `/api/app/agents/${bot.id}`
  447. await req('delete', path).expect(409)
  448. expect(store.get('first', 'conversation', direct.id)).toBeDefined()
  449. store.remove('first', 'run', 'pending')
  450. store.put('first', 'goal', 'delegated', { id: 'delegated', conversationId: 'another-chat', origin: { conversationId: direct.id }, status: 'waiting' })
  451. await req('delete', path).expect(409)
  452. expect(store.get('first', 'agent', bot.id)).toBeDefined()
  453. })
  454. it('resumes a stopped goal from a real user request without duplicating its run',async()=>{
  455. vi.spyOn(runtime.workspaceRuntime,'wake').mockImplementation(()=>{})
  456. vi.spyOn(runtime.workspaceRuntime.teamTools,'requireAvailable').mockResolvedValue()
  457. const lead=runtime.workspace.createAgent('first',{name:'任务负责人',profile:'default',canManageTeam:true})
  458. const member=runtime.workspace.createAgent('first',{name:'成员',profile:'default'})
  459. const source=runtime.workspace.list<any>('first','conversation').find(c=>c.kind==='direct'&&c.memberIds[0]===lead.id)!
  460. const original=runtime.workspaceRuntime.send('first',source.id,{requestId:randomUUID(),content:'完成任务'})
  461. const team=runtime.workspace.createGroup('first',{name:'任务组',memberIds:[lead.id,member.id],administratorId:lead.id})
  462. const task=runtime.workspace.tasks('first',team.id)[0]!
  463. runtime.workspaceRuntime.tasks.begin('first',task,lead,'完成任务',{conversationId:source.id,runId:original.id,agentId:lead.id})
  464. await req('post',`/api/app/conversations/${team.id}/tasks/${task.id}/stop`).send({}).expect(200)
  465. const input={requestId:randomUUID()}
  466. const resumed=await req('post',`/api/app/conversations/${team.id}/tasks/${task.id}/resume`).send(input).expect(200)
  467. expect(resumed.body.goal.status).toBe('running')
  468. const repeated=await req('post',`/api/app/conversations/${team.id}/tasks/${task.id}/resume`).send(input).expect(200)
  469. expect(repeated.body.run.id).toBe(resumed.body.run.id)
  470. await req('post',`/api/app/conversations/${team.id}/tasks/${task.id}/resume`,'second').send({requestId:randomUUID()}).expect(404)
  471. })
  472. it('starts an explicit delivery and lets only its owner edit versioned acceptance criteria',async()=>{
  473. vi.spyOn(runtime.workspaceRuntime,'wake').mockImplementation(()=>{})
  474. vi.spyOn(runtime.workspaceRuntime.teamTools,'requireAvailable').mockResolvedValue()
  475. const lead=runtime.workspace.createAgent('first',{name:'负责人',profile:'default',canManageTeam:true})
  476. const member=runtime.workspace.createAgent('first',{name:'成员',profile:'default'})
  477. const team=runtime.workspace.createGroup('first',{name:'交付群',memberIds:[lead.id,member.id],administratorId:lead.id})
  478. const task=runtime.workspace.tasks('first',team.id)[0]!
  479. const path=`/api/app/conversations/${team.id}`
  480. const input={requestId:randomUUID(),taskId:task.id,content:'完成并交付报告',mode:'goal'}
  481. const sent=await req('post',`${path}/messages`).send(input).expect(202)
  482. expect(sent.body.run.goalId).toBe(task.id)
  483. expect((await req('post',`${path}/messages`).send(input).expect(202)).body.run.id).toBe(sent.body.run.id)
  484. expect((await req('get',`${path}/tasks/${task.id}/plan`).expect(200)).body.assignments).toEqual([])
  485. const update={requestId:randomUUID(),expectedRevision:1,acceptanceCriteria:['包含三种方案的比较']}
  486. const edited=await req('patch',`${path}/tasks/${task.id}/plan`).send(update).expect(200)
  487. expect(edited.body.goal).toMatchObject({acceptanceRevision:2,acceptanceCriteria:update.acceptanceCriteria})
  488. await req('patch',`${path}/tasks/${task.id}/plan`,'second').send({...update,requestId:randomUUID()}).expect(404)
  489. expect((await req('patch',`${path}/tasks/${task.id}/plan`).send({...update,requestId:randomUUID()}).expect(409)).body.code).toBe('goal_criteria_changed')
  490. })
  491. it('creates a bot with team tools on by default and does not require the bridge', async () => {
  492. bridgeReady = false
  493. const created = await req('post','/api/app/agents').send({name:'老板',profile:'default'})
  494. expect(created.status, JSON.stringify(created.body)).toBe(201)
  495. const agent = created.body.agent
  496. expect(agent.canManageTeam).toBe(true)
  497. await req('patch',`/api/app/agents/${agent.id}`,'second').send({name:'别人改的'}).expect(404)
  498. expect((await req('get','/api/app/agents')).body.agents[0].canManageTeam).toBe(true)
  499. })
  500. it('accepts only child pairing, hides credentials, and scopes address edits to the owner', async () => {
  501. const code = new URL('yaoyao://pair')
  502. 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)
  503. await req('post','/api/app/nodes').send({name:'legacy',url:'http://child.test:9119',username:'user',password:'password'}).expect(400)
  504. await req('post','/api/app/nodes').send({name:'child',qrPayload:code.href.replace('://pair','://login')}).expect(400)
  505. await req('post','/api/app/nodes').send({name:'child',qrPayload:code.href}).expect(201)
  506. const listing=await req('get','/api/app/nodes').expect(200), node=listing.body.nodes[0]
  507. expect(node.transport).toBe('paired-web'); expect(JSON.stringify(listing.body)).not.toContain('delegated-token'); expect(node.secret).toBeUndefined()
  508. expect((await req('get','/api/app/nodes','second').expect(200)).body.nodes).toEqual([])
  509. await req('patch',`/api/app/nodes/${node.id}`,'second').send({name:'other',url:'http://new-ip.test:15300'}).expect(404)
  510. await req('patch',`/api/app/nodes/${node.id}`).send({name:'new name',url:'http://new-ip.test:15300'}).expect(200)
  511. const updated=(await req('get','/api/app/nodes').expect(200)).body.nodes[0]
  512. expect(updated.id).toBe(node.id); expect(updated.url).toBe('http://new-ip.test:15300/')
  513. const sources=(await req('get','/api/app/agents/sources').expect(200)).body.sources
  514. // Pairing still manages the node; retired remote Profiles are not Bot sources.
  515. expect(sources.some((s:any)=>s.nodeId===node.id)).toBe(false)
  516. })
  517. it('archives native-chat uploads through the standard file API with user ownership', async () => {
  518. saveFileAccess(home, { mode: 'all', folders: [] })
  519. const assets = new WorkspaceAssets(runtime.workspace, runtime.workspaceRuntime.nodes, home)
  520. await assets.archiveText(
  521. 'first',
  522. '{"path":"/tmp/native-upload.txt"}',
  523. 'local',
  524. 'default',
  525. 'native-session',
  526. 'native-message',
  527. 'user',
  528. )
  529. const page = await req('get', '/api/app/files').expect(200)
  530. expect(page.body.items[0]).toMatchObject({
  531. name: 'native-upload.txt',
  532. sender: 'user',
  533. profile: 'default',
  534. })
  535. expect(upstream).toContain('/api/files/download')
  536. expect((await req('get', '/api/app/files', 'second')).body.items).toEqual([])
  537. expect(upstream.some((p) => p.includes('/plugins/'))).toBe(false)
  538. })
  539. it('works without plugin discovery, installation, or any plugin HTTP request', async () => {
  540. const capabilities = (await req('get', '/api/app/capabilities').expect(200)).body.features
  541. expect(capabilities).toContain('editableGroups')
  542. expect(capabilities).not.toContain('immutableGroups')
  543. await req('get', '/api/app/files').expect(200)
  544. await req('get', '/api/app/voice/runtime').expect(200)
  545. await req('get', '/api/app/system/update/status').expect(200)
  546. await req('post', '/api/app/plugins/yaoyao/reconcile').send({}).expect(410)
  547. await req('get', '/api/plugins/yaoyao/v1/capabilities').expect(410)
  548. expect(upstream.some((p) => p.includes('/plugins/'))).toBe(false)
  549. })
  550. it('changes members over HTTP while protecting the administrator and ownership', async () => {
  551. const a = (
  552. await req('post', '/api/app/agents').send({ name: '编辑', profile: 'default' }).expect(201)
  553. ).body.agent
  554. const b = (
  555. await req('post', '/api/app/agents').send({ name: '审查', profile: 'default' }).expect(201)
  556. ).body.agent
  557. const c = (
  558. await req('post', '/api/app/conversations')
  559. .send({ name: '团队', memberIds: [a.id, b.id], administratorId: a.id })
  560. .expect(201)
  561. ).body.conversation
  562. const rows = await req('get', '/api/app/conversations').expect(200)
  563. expect(rows.body.conversations).toHaveLength(3)
  564. await req('patch', `/api/app/conversations/${c.id}`)
  565. .send({ memberIds: [b.id], administratorId: b.id })
  566. .expect(400)
  567. await req('patch', `/api/app/conversations/${c.id}`).send({ memberIds: [a.id] }).expect(200)
  568. expect((await req('get', `/api/app/conversations/${c.id}`)).body.conversation.memberIds).toEqual([a.id])
  569. await req('patch', `/api/app/conversations/${c.id}`).send({ memberIds: [a.id, b.id] }).expect(200)
  570. await req('get', `/api/app/conversations/${c.id}`, 'second').expect(404)
  571. await req('patch', `/api/app/agents/${a.id}`, 'second').send({ name: '入侵' }).expect(404)
  572. expect((await req('get', '/api/app/events', 'second')).body.events).toEqual([])
  573. expect(upstream.some((p) => p.includes('sessions'))).toBe(false)
  574. })
  575. it('creates, lists, renames, selects, and deletes group tasks without changing remote members', async () => {
  576. const a = (
  577. await req('post', '/api/app/agents').send({ name: '本机管理员', profile: 'default' }).expect(201)
  578. ).body.agent
  579. const b = (
  580. await req('post', '/api/app/agents').send({ name: '远程成员', nodeId: 'local', profile: 'default' }).expect(201)
  581. ).body.agent
  582. const conversation = (
  583. await req('post', '/api/app/conversations')
  584. .send({ name: '多任务团队', memberIds: [a.id, b.id], administratorId: a.id })
  585. .expect(201)
  586. ).body.conversation
  587. const initial = (await req('get', `/api/app/conversations/${conversation.id}/tasks`).expect(200)).body.tasks
  588. expect(initial).toHaveLength(1)
  589. expect(initial[0]).toMatchObject({
  590. conversationId: conversation.id,
  591. title: '新任务',
  592. titleSource: 'automatic',
  593. messageCount: 0,
  594. })
  595. const task = (
  596. await req('post', `/api/app/conversations/${conversation.id}/tasks`)
  597. .send({ title: '远程 Agent 调研' })
  598. .expect(201)
  599. ).body.task
  600. expect(task).toMatchObject({ title: '远程 Agent 调研', titleSource: 'user' })
  601. const renamed = (
  602. await req('patch', `/api/app/conversations/${conversation.id}/tasks/${task.id}`)
  603. .send({ title: '远程 Agent 复核' })
  604. .expect(200)
  605. ).body.task
  606. expect(renamed).toMatchObject({ title: '远程 Agent 复核', titleSource: 'user' })
  607. const detail = (await req('get', `/api/app/conversations/${conversation.id}?taskId=${task.id}`).expect(200)).body
  608. expect(detail.task.id).toBe(task.id)
  609. expect(detail.tasks.map((row: { id: string }) => row.id)).toContain(task.id)
  610. expect(detail.messages).toEqual([])
  611. expect(detail.conversation).toMatchObject({ memberIds: [a.id, b.id], administratorId: a.id })
  612. expect((await req('put', `/api/app/conversations/${conversation.id}/tasks/${task.id}/read`).send({ seq: 100 }).expect(200)).body.task)
  613. .toMatchObject({ readSeq: 0, lastSeq: 0, unreadCount: 0 })
  614. await req('get', `/api/app/conversations/${conversation.id}/tasks`, 'second').expect(404)
  615. await req('delete', `/api/app/conversations/${conversation.id}/tasks/${task.id}`).expect(200)
  616. const remaining = (await req('get', `/api/app/conversations/${conversation.id}/tasks`).expect(200)).body.tasks
  617. expect(remaining.map((row: { id: string }) => row.id)).not.toContain(task.id)
  618. expect((await req('get', `/api/app/conversations/${conversation.id}`)).body.conversation)
  619. .toMatchObject({ memberIds: [a.id, b.id], administratorId: a.id })
  620. await req('delete', `/api/app/conversations/${conversation.id}/tasks/${initial[0].id}`).expect(200)
  621. const replacement = (await req('get', `/api/app/conversations/${conversation.id}/tasks`).expect(200)).body.tasks
  622. expect(replacement).toHaveLength(1)
  623. expect(replacement[0].id).not.toBe(initial[0].id)
  624. })
  625. it('archives files on the Web server, preserves native library fields, and blocks cross-user downloads', async () => {
  626. const f = (
  627. await req('post', '/api/app/uploads')
  628. .attach('files', Buffer.from('hello'), { filename: 'hello.txt', contentType: 'text/plain' })
  629. .expect(201)
  630. ).body.files[0]
  631. expect(f.path).toBeUndefined()
  632. expect(runtime.uploads.cleanupUncommitted(0)).toBe(0)
  633. const list = await req('get', '/api/app/files').expect(200),
  634. item = list.body.items[0]
  635. expect(typeof item.id).toBe('number')
  636. expect(item.path).toBe(`/api/app/files/${f.id}/download`)
  637. expect(item).toMatchObject({ name: 'hello.txt', size: 5, exists: true, archiveStatus: 'ready' })
  638. expect((await req('get', item.path).expect(200)).text).toBe('hello')
  639. await req('get', item.path, 'second').expect(404)
  640. await req('get', `/api/app/files/${item.id}/download`, 'second').expect(404)
  641. expect((await req('get', '/api/app/files', 'second')).body.total).toBe(0)
  642. expect(upstream.some((p) => p.includes('/files'))).toBe(false)
  643. })
  644. it('does not serve uploaded HTML or SVG as executable same-origin previews', async () => {
  645. const f = (
  646. await req('post', '/api/app/uploads')
  647. .attach('files', Buffer.from('<svg onload="alert(1)"/>'), {
  648. filename: 'unsafe.svg',
  649. contentType: 'image/svg+xml',
  650. })
  651. .expect(201)
  652. ).body.files[0]
  653. const response = await req('get', `/api/app/files/${f.id}/preview`).expect(200)
  654. expect(response.headers['content-type']).toContain('application/octet-stream')
  655. expect(response.headers['content-disposition']).toContain('attachment')
  656. })
  657. it('persists encrypted voice credentials while giving each user their own selected voice', async () => {
  658. await req('put', '/api/app/admin/duplex-voice')
  659. .send({
  660. apiKey: 'private-test-key',
  661. voices: [
  662. { id: 'a', name: '甲' },
  663. { id: 'b', name: '乙' },
  664. ],
  665. currentVoiceId: 'a',
  666. })
  667. .expect(200)
  668. const publicResponse = await req('get', '/api/app/admin/duplex-voice').expect(200)
  669. expect(publicResponse.body.hasApiKey).toBe(true)
  670. expect(publicResponse.body.apiKey).toBeUndefined()
  671. await req('put', '/api/app/voice/current-voice', 'second')
  672. .send({ currentVoiceId: 'b' })
  673. .expect(200)
  674. expect((await req('get', '/api/app/voice/runtime')).body.currentVoiceId).toBe('a')
  675. expect((await req('get', '/api/app/voice/runtime', 'second')).body.currentVoiceId).toBe('b')
  676. expect(
  677. readFileSync(join(home, 'workspace.sqlite3')).includes(Buffer.from('private-test-key')),
  678. ).toBe(false)
  679. })
  680. it('stores monotonic profile-scoped context snapshots without a plugin', async () => {
  681. const path = '/api/app/session-context/session-one?profile=default'
  682. const b = { usedTokens: 200, limitTokens: 1000, percent: 20, observedAt: 20 }
  683. await req('put', path).send(b).expect(200)
  684. await req('put', path)
  685. .send({ ...b, usedTokens: 10, observedAt: 10 })
  686. .expect(200)
  687. expect((await req('get', path)).body.snapshot).toMatchObject({ ...b, sessionId: 'session-one' })
  688. expect((await req('get', path, 'second')).body.snapshot).toBeNull()
  689. expect(
  690. (await req('get', '/api/app/session-context/session-one?profile=other')).body.snapshot,
  691. ).toBeNull()
  692. })
  693. it('protects internal Hermes session IDs on native HTTP endpoints', async () => {
  694. runtime.workspace.put('first', 'binding', 'binding', {
  695. storedId: 'internal-session',
  696. runtimeId: 'internal-runtime',
  697. aliases: ['old-id'],
  698. })
  699. await req('get', '/api/app/sessions/internal-session/messages').expect(404)
  700. await req('get', '/api/sessions/old-id/messages', 'second').expect(404)
  701. expect(upstream.some((p) => p.includes('internal-session') || p.includes('old-id'))).toBe(false)
  702. })
  703. })
  704. it('prepares CSRF with capabilities and returns an idempotent committed send receipt', async () => {
  705. const caps = await req('get', '/api/app/capabilities').expect(200)
  706. expect(caps.body.csrfToken).toBe(csrf)
  707. expect(caps.headers['cache-control']).toBe('no-store')
  708. const store = runtime.workspace
  709. store.createAgent('first', { name: '回执测试', profile: 'default' })
  710. const conversation = store.list<any>('first', 'conversation')[0]
  711. const input = { requestId: randomUUID(), content: '确认后立即恢复' }
  712. const send = () => req('post', `/api/app/conversations/${conversation.id}/messages`).send(input).expect(202)
  713. const a = (await send()).body, b = (await send()).body
  714. expect(a.requestId).toBe(input.requestId)
  715. expect(a.message.id).toBe(a.run.messageId)
  716. expect(a.conversation.id).toBe(conversation.id)
  717. expect(a.cursor).toBeGreaterThan(0)
  718. expect(b.message.id).toBe(a.message.id)
  719. expect(b.run.id).toBe(a.run.id)
  720. expect(store.messages('first', conversation.id).filter(m => m.role === 'user')).toHaveLength(1)
  721. })
  722. it('aggregates per-agent daily token usage for today, month and lifetime', async () => {
  723. const store = runtime.workspace
  724. const agent = store.createAgent('first', { name: '用量统计', profile: 'default' })
  725. const other = store.createAgent('first', { name: '用量其他', profile: 'default' })
  726. const now = new Date(),
  727. pad = (n: number) => String(n).padStart(2, '0'),
  728. today = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}`,
  729. month = today.slice(0, 7),
  730. older = `${month}-01`
  731. const seed = (agentId: string, date: string, input: number, output: number) =>
  732. store.put('first', 'agent-token-day', `${agentId}:${date}`, { agentId, date, input, output, total: input + output, updatedAt: 1 })
  733. seed(agent.id, today, 300, 100)
  734. seed(agent.id, older, 2000, 1000)
  735. seed(other.id, today, 99999, 99999)
  736. const usage = (await req('get', `/api/app/agents/${agent.id}/usage`).expect(200)).body
  737. expect(usage.today).toBe(today)
  738. expect(usage.todayUsage).toEqual({ input: 300, output: 100, total: 400 })
  739. expect(usage.monthUsage).toEqual({ input: 2300, output: 1100, total: 3400 })
  740. expect(usage.totalUsage).toEqual({ input: 2300, output: 1100, total: 3400 })
  741. expect(usage.daily.map((d: any) => d.date)).toEqual([today, older])
  742. await req('get', `/api/app/agents/${randomUUID()}/usage`).expect(404)
  743. })
  744. function stubBotModels(warning: string | null = null, duringResolve?: () => void) {
  745. const original=runtime.upstreamSession.request.bind(runtime.upstreamSession)
  746. return vi.spyOn(runtime.upstreamSession,'request').mockImplementation(async (path, options) => {
  747. const defaults={provider:'openai',model:'model-a',reasoningEffort:'medium',fastMode:'normal'}
  748. if(path.endsWith('/model-options'))return {status:200,headers:new Headers(),body:Buffer.from(JSON.stringify({version:1,defaults,models:[{provider:'openai',model:'model-a',name:'A',reasoningEfforts:['none','medium','high'],reasoningKnown:true,fastModes:['normal','fast','auto','cold'],api_key:'must-not-leak'}]}))}
  749. if(path.endsWith('/model-settings/resolve')){
  750. duringResolve?.()
  751. const settings=(options?.body as any)?.settings??{}
  752. return {status:200,headers:new Headers(),body:Buffer.from(JSON.stringify({version:1,effective:{...defaults,...Object.fromEntries(Object.entries(settings).filter(([,v])=>v!==null))},confirmationMessage:warning}))}
  753. }
  754. return original(path,options)
  755. })
  756. }
  757. it('exposes owned Bot model capabilities and saves settings without altering its peers or Profile', async () => {
  758. stubBotModels()
  759. const a=runtime.workspace.createAgent('first',{name:'模型甲',profile:'default'}),b=runtime.workspace.createAgent('first',{name:'模型乙',profile:'default'})
  760. const path=`/api/app/agents/${a.id}`
  761. const options=(await req('get',`${path}/model-options`).expect(200)).body
  762. expect(options).toMatchObject({revision:1,settings:null,defaults:{model:'model-a'}})
  763. expect(JSON.stringify(options)).not.toContain('must-not-leak')
  764. await req('get',`${path}/model-options`,'second').expect(404)
  765. const modelSettings={provider:'openai',model:'model-a',reasoningEffort:'none',fastMode:'auto'}
  766. const saved=(await req('patch',path).send({modelSettings,expectedRevision:1}).expect(200)).body.agent
  767. expect(saved.modelSettings).toEqual(modelSettings)
  768. expect(runtime.workspace.require<any>('first','agent',b.id).modelSettings).toBeUndefined()
  769. await req('patch',path).send({name:'改名'}).expect(200)
  770. expect(runtime.workspace.require<any>('first','agent',a.id).modelSettings).toEqual(modelSettings)
  771. await req('patch',path).send({modelSettings:null,expectedRevision:1}).expect(409)
  772. expect(upstream.some(p=>p.includes('/model/set'))).toBe(false)
  773. })
  774. it('requires model confirmation before saving and binds it to the resolved selection', async () => {
  775. stubBotModels('费用较高,请确认')
  776. const a=runtime.workspace.createAgent('first',{name:'确认模型',profile:'default'}),path=`/api/app/agents/${a.id}`
  777. const body={expectedRevision:1,modelSettings:{provider:'openai',model:'model-a',reasoningEffort:null,fastMode:null}}
  778. const confirmation=(await req('patch',path).send(body).expect(200)).body
  779. expect(confirmation.confirmationRequired).toBe(true)
  780. expect(runtime.workspace.require<any>('first','agent',a.id).revision).toBe(1)
  781. const result=(await req('patch',path).send({...body,confirmedModel:confirmation.confirmationTarget}).expect(200)).body.agent
  782. expect(result.modelSettingsConfirmation).toBe('["openai","model-a"]')
  783. const changed=(await req('patch',path).send({...body,expectedRevision:2,modelSettings:{...body.modelSettings,model:'model-b'},confirmedModel:confirmation.confirmationTarget}).expect(200)).body
  784. expect(changed.confirmationTarget).toBe('["openai","model-b"]')
  785. expect(runtime.workspace.require<any>('first','agent',a.id).revision).toBe(2)
  786. })
  787. it('detects a concurrent edit after asynchronous model validation without overwriting the new record', async () => {
  788. const a=runtime.workspace.createAgent('first',{name:'并发编辑',profile:'default'})
  789. stubBotModels(null,()=>runtime.workspace.updateAgent('first',a.id,{name:'另一端的新名称'}))
  790. await req('patch',`/api/app/agents/${a.id}`).send({expectedRevision:1,modelSettings:null}).expect(409)
  791. expect(runtime.workspace.require<any>('first','agent',a.id)).toMatchObject({name:'另一端的新名称',revision:2})
  792. expect(runtime.workspace.require<any>('first','agent',a.id).modelSettings).toBeUndefined()
  793. })
  794. it('preserves ordinary Bot editing when the installed bridge predates model settings', async () => {
  795. const a=runtime.workspace.createAgent('first',{name:'旧工具桥',profile:'default'}),path=`/api/app/agents/${a.id}`
  796. expect((await req('get',`${path}/model-options`).expect(409)).body.code).toBe('model_settings_upgrade_required')
  797. await req('patch',path).send({instructions:'新规则'}).expect(200)
  798. await req('patch',path).send({modelSettings:{provider:'openai',model:null,reasoningEffort:null,fastMode:null},expectedRevision:2}).expect(400)
  799. })
  800. it('confirms a session-dependent native warning in the profile save flow',async()=>{
  801. stubBotModels()
  802. const a=runtime.workspace.createAgent('first',{name:'长上下文切换',profile:'default'}),path=`/api/app/agents/${a.id}`
  803. runtime.workspace.put('first','agent',a.id,{...a,modelSettingsPendingConfirmation:{target:'["openai","model-a"]',message:'切换长上下文将增加费用'}})
  804. const body={expectedRevision:1,modelSettings:null}
  805. const warning=(await req('patch',path).send(body).expect(200)).body
  806. expect(warning.confirmationMessage).toContain('长上下文')
  807. const saved=(await req('patch',path).send({...body,confirmedModel:warning.confirmationTarget}).expect(200)).body.agent
  808. expect(saved.modelSettingsConfirmation).toBe('["openai","model-a"]')
  809. expect(saved.modelSettingsPendingConfirmation).toBeUndefined()
  810. })
  811. it('saves a new base Profile before reloading and validating its model catalogue',async()=>{
  812. const a=runtime.workspace.createAgent('first',{name:'换来源',profile:'other'}),path=`/api/app/agents/${a.id}`
  813. runtime.workspace.updateAgent('first',a.id,{modelSettings:{provider:'old-provider',model:'old-model',reasoningEffort:'high',fastMode:'cold'}})
  814. // Even an old bridge must allow source-only edits, preserving the draft values.
  815. const saved=(await req('patch',path).send({profile:'default'}).expect(200)).body.agent
  816. expect(saved.profile).toBe('default');expect(saved.modelSettings.model).toBe('old-model')
  817. stubBotModels()
  818. expect((await req('get',`${path}/model-options`).expect(200)).body).toMatchObject({revision:saved.revision,settings:saved.modelSettings})
  819. })