workspaceRoutes.test.ts 52 KB

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