workspace.test.ts 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151
  1. // @vitest-environment node
  2. import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
  3. import { mkdtempSync, rmSync } from 'node:fs'
  4. import { tmpdir } from 'node:os'
  5. import { join } from 'node:path'
  6. import { randomUUID } from 'node:crypto'
  7. import { WebSocketServer, type WebSocket } from 'ws'
  8. import { defaultAgentIdentity, encodeAgentAvatar, decodeAgentAvatar } from '../../src/shared/agentIdentity'
  9. import { WorkspaceStore } from '../../src/server/workspaceStore'
  10. import { WorkspaceRuntime, mentionedAgents } from '../../src/server/workspaceRuntime'
  11. import { WorkspaceNodes } from '../../src/server/workspaceGateway'
  12. import { UploadStore } from '../../src/server/uploads'
  13. import type {
  14. WorkspaceConversation,
  15. WorkspaceRun,
  16. WorkspaceMessage,
  17. WorkspaceInteraction,
  18. } from '../../src/shared/workspace'
  19. let home: string,
  20. store: WorkspaceStore,
  21. uploads: UploadStore,
  22. runtime: WorkspaceRuntime,
  23. server: WebSocketServer
  24. let requests: Array<{ method: string; params: Record<string, any> }>,
  25. reply: (socket: WebSocket, params: Record<string, any>) => void
  26. let nodes: WorkspaceNodes
  27. let rejectPrompt: string | undefined
  28. let rejectedInterrupts: number
  29. let recoveryHistory: Array<{ role: string; content: string; tool_calls?: unknown }>
  30. let storedByRuntime: Map<string, string>, recoveryByStored: Map<string, Array<{ role: string; content: string }>>
  31. const owner = 'first-user',
  32. other = 'second-user'
  33. beforeEach(async () => {
  34. home = mkdtempSync(join(tmpdir(), 'yaoyao-workspace-test-'))
  35. store = new WorkspaceStore(home)
  36. uploads = new UploadStore(home)
  37. requests = []
  38. recoveryHistory = []
  39. storedByRuntime = new Map(); recoveryByStored = new Map()
  40. rejectPrompt = undefined
  41. rejectedInterrupts = 0
  42. server = new WebSocketServer({ port: 0, host: '127.0.0.1' })
  43. await new Promise<void>((resolve) => server.once('listening', resolve))
  44. const address = server.address() as { port: number }
  45. const target = {
  46. url: new URL(`http://127.0.0.1:${address.port}`),
  47. client: { directAgent: undefined },
  48. session: {
  49. webSocketCredential: async () => ({ name: 'ticket', value: 'test' }),
  50. request: async (path: string, options?: {search?: URLSearchParams}) => ({
  51. status: 200,
  52. body: Buffer.from(JSON.stringify({ messages: (() => { const all = recoveryByStored.get(decodeURIComponent(path.split('/')[3]!)) ?? recoveryHistory; const offset = Number(options?.search?.get('offset') ?? 0); return all.slice(Math.max(0,all.length-offset-500), all.length-offset) })() })),
  53. }),
  54. },
  55. }
  56. nodes = { requireSource: () => {}, target: () => target } as unknown as WorkspaceNodes
  57. runtime = new WorkspaceRuntime(store, nodes, uploads)
  58. reply = (socket, p) =>
  59. setTimeout(
  60. () =>
  61. socket.send(
  62. JSON.stringify({
  63. method: 'event',
  64. params: {
  65. type: 'message.complete',
  66. session_id: p.session_id,
  67. payload: { text: '完成', status: 'complete' },
  68. },
  69. }),
  70. ),
  71. 5,
  72. )
  73. server.on('connection', (socket) => {
  74. socket.send(JSON.stringify({ method: 'event', params: { type: 'gateway.ready' } }))
  75. socket.on('message', (data) => {
  76. const frame = JSON.parse(String(data))
  77. requests.push(frame)
  78. const respond = (result: unknown) => socket.send(JSON.stringify({ id: frame.id, result }))
  79. if (frame.method === 'session.create' || frame.method === 'session.resume') {
  80. const runtimeId = randomUUID(), storedId = frame.method === 'session.resume' ? frame.params.session_id : randomUUID()
  81. storedByRuntime.set(runtimeId, storedId)
  82. respond({ session_id: runtimeId, stored_session_id: storedId, running: false, info: { profile_name: frame.params.profile } })
  83. }
  84. else if (frame.method === 'prompt.submit') {
  85. if (rejectPrompt) { socket.send(JSON.stringify({id:frame.id,error:{code:4006,message:rejectPrompt}})); return }
  86. respond({ status: 'streaming' })
  87. reply(socket, frame.params)
  88. } else if (frame.method === 'session.usage') respond({ context_used: 400, context_max: 1000 })
  89. else if (frame.method === 'session.interrupt' && rejectedInterrupts-- > 0) socket.send(JSON.stringify({id:frame.id,error:{code:500,message:'暂时不能中断'}}))
  90. else respond({ ok: true, status: 'interrupted' })
  91. })
  92. })
  93. })
  94. afterEach(async () => {
  95. runtime.close()
  96. await new Promise((resolve) => setTimeout(resolve, 10))
  97. for (const client of server.clients) client.terminate()
  98. await new Promise<void>((resolve) => server.close(() => resolve()))
  99. uploads.close()
  100. store.close()
  101. rmSync(home, { recursive: true, force: true })
  102. })
  103. function agent(name: string, user = owner) {
  104. return store.createAgent(user, { name, profile: 'default', instructions: `规则:你是${name}` })
  105. }
  106. function direct(id: string, user = owner) {
  107. return store
  108. .list<WorkspaceConversation>(user, 'conversation')
  109. .find((c) => c.kind === 'direct' && c.memberIds[0] === id)!
  110. }
  111. function defaultTask(conversationId: string, user = owner) {
  112. return store.tasks(user, conversationId)[0]!
  113. }
  114. async function finished(id: string) {
  115. await vi.waitFor(() =>
  116. expect(store.require<WorkspaceRun>(owner, 'run', id).status).toBe('complete'),
  117. )
  118. return store.require<WorkspaceRun>(owner, 'run', id)
  119. }
  120. describe('Web-owned workspace', () => {
  121. it('flushes a paused delta before completion and cancels pending flush on finish', async () => {
  122. let upstream: { socket: WebSocket; params: Record<string, any> } | undefined
  123. reply = (socket, params) => {
  124. upstream = { socket, params }
  125. const event = (type: string, payload: Record<string, unknown>) => socket.send(JSON.stringify({
  126. method: 'event', params: { type, session_id: params.session_id, payload },
  127. }))
  128. event('message.start', {})
  129. event('message.delta', { text: '# 流式标题' })
  130. }
  131. const bot = agent('流式助手'), conversation = direct(bot.id)
  132. const run = runtime.send(owner, conversation.id, { requestId: randomUUID(), content: '验证暂停分片' })
  133. const assistant = () => store.list<WorkspaceMessage>(owner, 'message').find(m => m.runId === run.id && m.role === 'assistant')
  134. await vi.waitFor(() => expect(assistant()?.content).toBe('# 流式标题'))
  135. expect(assistant()?.status).toBe('streaming')
  136. expect(store.require<WorkspaceRun>(owner, 'run', run.id).status).not.toBe('complete')
  137. const { socket, params } = upstream!
  138. socket.send(JSON.stringify({ method: 'event', params: { type: 'message.delta', session_id: params.session_id, payload: { text: '\n\n最后一段' } } }))
  139. completeReply(socket, params, '# 最终正文')
  140. await finished(run.id)
  141. await new Promise(resolve => setTimeout(resolve, 150))
  142. expect(assistant()?.content).toBe('# 最终正文')
  143. expect(assistant()?.status).toBe('complete')
  144. })
  145. it('backfills legacy group history into the initial task instead of leaving a new empty task', () => {
  146. const legacyHome = mkdtempSync(join(tmpdir(), 'yaoyao-workspace-task-migration-'))
  147. let seededStore: WorkspaceStore | undefined = new WorkspaceStore(legacyHome)
  148. let migratedStore: WorkspaceStore | undefined
  149. try {
  150. const administrator = seededStore.createAgent(owner, { name: '历史管理员', profile: 'default' }),
  151. member = seededStore.createAgent(owner, { name: '历史成员', profile: 'default' }),
  152. conversation = seededStore.createGroup(owner, {
  153. name: '公众号文案团队',
  154. memberIds: [administrator.id, member.id],
  155. administratorId: administrator.id,
  156. }),
  157. initialTask = seededStore.tasks(owner, conversation.id)[0]!,
  158. userAt = 1_788_000_000_000,
  159. assistantAt = userAt + 60_000
  160. seededStore.put(owner, 'message', 'legacy-user', {
  161. id: 'legacy-user', conversationId: conversation.id, seq: 1, role: 'user',
  162. content: '请继续完成公众号文案', reasoning: '', status: 'complete',
  163. attachments: [], tools: [], createdAt: userAt,
  164. } satisfies WorkspaceMessage)
  165. seededStore.put(owner, 'message', 'legacy-assistant', {
  166. id: 'legacy-assistant', conversationId: conversation.id, seq: 2, role: 'assistant',
  167. agentId: administrator.id, agentName: '历史管理员', content: '旧内容已经完成。',
  168. reasoning: '', status: 'complete', attachments: [], tools: [], createdAt: assistantAt,
  169. } satisfies WorkspaceMessage)
  170. seededStore.put(owner, 'conversation', conversation.id, {
  171. ...conversation,
  172. readSeq: 1,
  173. lastSeq: 2,
  174. preview: '旧内容已经完成。',
  175. lastMessageAt: assistantAt,
  176. updatedAt: assistantAt,
  177. })
  178. seededStore.put(owner, 'run', 'legacy-run', {
  179. id: 'legacy-run', conversationId: conversation.id, messageId: 'legacy-user',
  180. mentionIds: [], status: 'complete', round: 1, createdAt: userAt, updatedAt: assistantAt,
  181. } satisfies WorkspaceRun)
  182. seededStore.put(owner, 'turn', 'legacy-turn', {
  183. id: 'legacy-turn', runId: 'legacy-run', conversationId: conversation.id,
  184. agentId: administrator.id, messageId: 'legacy-user', status: 'complete', createdAt: userAt,
  185. })
  186. seededStore.put(owner, 'interaction', 'legacy-interaction', {
  187. id: 'legacy-interaction', conversationId: conversation.id, runId: 'legacy-run',
  188. agentId: administrator.id, kind: 'clarification', message: '补充说明',
  189. choices: [], resolved: true,
  190. } satisfies WorkspaceInteraction)
  191. seededStore.put(owner, 'interaction-binding', 'legacy-interaction', {
  192. key: `${conversation.id}:${administrator.id}`,
  193. upstreamId: 'upstream-interaction', taskId: 'legacy-turn',
  194. })
  195. seededStore.put(owner, 'binding', `${conversation.id}:${administrator.id}`, {
  196. nodeId: 'local', profile: 'default', storedId: 'stored-legacy',
  197. runtimeId: 'runtime-legacy', aliases: [], runId: 'legacy-run',
  198. messageId: 'legacy-user', taskId: 'legacy-turn',
  199. })
  200. seededStore.put(owner, 'context', conversation.id, {
  201. usedTokens: 100, limitTokens: 1_000, observedAt: assistantAt,
  202. })
  203. seededStore.db.prepare('DELETE FROM workspace_migrations WHERE id=?')
  204. .run('conversation-task-history-v1')
  205. seededStore.close()
  206. seededStore = undefined
  207. migratedStore = new WorkspaceStore(legacyHome)
  208. const tasks = migratedStore.tasks(owner, conversation.id)
  209. expect(tasks).toHaveLength(1)
  210. expect(tasks[0]).toMatchObject({
  211. id: initialTask.id,
  212. title: '请继续完成公众号文案',
  213. titleSource: 'automatic',
  214. messageCount: 2,
  215. readSeq: 1,
  216. lastSeq: 2,
  217. unreadCount: 1,
  218. lastMessageAt: assistantAt,
  219. createdAt: userAt,
  220. updatedAt: assistantAt,
  221. })
  222. expect(
  223. migratedStore.messages(
  224. owner, conversation.id, Number.MAX_SAFE_INTEGER, 100, false, initialTask.id,
  225. ).map(message => message.id),
  226. ).toEqual(['legacy-user', 'legacy-assistant'])
  227. expect(migratedStore.require<WorkspaceRun>(owner, 'run', 'legacy-run').conversationTaskId)
  228. .toBe(initialTask.id)
  229. expect(migratedStore.require<{ conversationTaskId: string }>(owner, 'turn', 'legacy-turn').conversationTaskId)
  230. .toBe(initialTask.id)
  231. expect(migratedStore.require<WorkspaceInteraction>(owner, 'interaction', 'legacy-interaction').conversationTaskId)
  232. .toBe(initialTask.id)
  233. expect(migratedStore.get(owner, 'binding', `${conversation.id}:${administrator.id}`)).toBeUndefined()
  234. expect(migratedStore.get(owner, 'binding', `${conversation.id}:${initialTask.id}:${administrator.id}`))
  235. .toMatchObject({ conversationTaskId: initialTask.id })
  236. expect(migratedStore.get(owner, 'context', conversation.id)).toBeUndefined()
  237. expect(migratedStore.get(owner, 'context', initialTask.id))
  238. .toMatchObject({ conversationTaskId: initialTask.id })
  239. } finally {
  240. seededStore?.close()
  241. migratedStore?.close()
  242. rmSync(legacyHome, { recursive: true, force: true })
  243. }
  244. })
  245. it('isolates messages, Hermes sessions, bindings, and context between concurrent group tasks', async () => {
  246. const administrator = store.createAgent(owner, { name: '多任务远程管理员', profile: 'remote-profile', nodeId: 'remote-node' }),
  247. member = agent('多任务成员'),
  248. conversation = store.createGroup(owner, {
  249. name: '多任务群聊',
  250. memberIds: [administrator.id, member.id],
  251. administratorId: administrator.id,
  252. }),
  253. firstTask = defaultTask(conversation.id),
  254. secondTask = store.createTask(owner, conversation.id, { title: '显式标题' })
  255. const pending: Array<{ socket: WebSocket; params: Record<string, any> }> = []
  256. reply = (socket, params) => {
  257. pending.push({ socket, params })
  258. if (pending.length !== 2) return
  259. for (const item of pending) {
  260. const text = item.params.text.includes('第一项工作') ? '第一项结果' : '第二项结果'
  261. setTimeout(() => item.socket.send(JSON.stringify({
  262. method: 'event',
  263. params: { type: 'message.complete', session_id: item.params.session_id, payload: { text, status: 'complete' } },
  264. })), 5)
  265. }
  266. }
  267. const firstRun = runtime.send(owner, conversation.id, { requestId: randomUUID(), taskId: firstTask.id, content: '第一项工作' }),
  268. secondRun = runtime.send(owner, conversation.id, { requestId: randomUUID(), taskId: secondTask.id, content: '第二项工作' })
  269. await Promise.all([finished(firstRun.id), finished(secondRun.id)])
  270. const firstMessages = store.messages(owner, conversation.id, Number.MAX_SAFE_INTEGER, 100, false, firstTask.id),
  271. secondMessages = store.messages(owner, conversation.id, Number.MAX_SAFE_INTEGER, 100, false, secondTask.id)
  272. expect(firstMessages.map(message => message.content)).toEqual(['第一项工作', '第一项结果'])
  273. expect(secondMessages.map(message => message.content)).toEqual(['第二项工作', '第二项结果'])
  274. expect(firstMessages.every(message => message.conversationTaskId === firstTask.id)).toBe(true)
  275. expect(secondMessages.every(message => message.conversationTaskId === secondTask.id)).toBe(true)
  276. const prompts = requests.filter(request => request.method === 'prompt.submit').map(request => String(request.params.text))
  277. expect(prompts.find(prompt => prompt.includes('第一项工作'))).not.toContain('第二项工作')
  278. expect(prompts.find(prompt => prompt.includes('第二项工作'))).not.toContain('第一项工作')
  279. const bindings = store.list<any>(owner, 'binding')
  280. expect(bindings.map(binding => binding.conversationTaskId).sort()).toEqual([firstTask.id, secondTask.id].sort())
  281. expect(bindings.every(binding => binding.nodeId === 'remote-node' && binding.profile === 'remote-profile')).toBe(true)
  282. expect(new Set(bindings.map(binding => binding.storedId)).size).toBe(2)
  283. expect(store.get<any>(owner, 'context', firstTask.id)).toMatchObject({ conversationTaskId: firstTask.id, percent: 40 })
  284. expect(store.get<any>(owner, 'context', secondTask.id)).toMatchObject({ conversationTaskId: secondTask.id, percent: 40 })
  285. const firstSummary = store.require<any>(owner, 'conversation-task', firstTask.id)
  286. expect(firstSummary).toMatchObject({ title: '第一项工作', titleSource: 'automatic', messageCount: 2, unreadCount: 2 })
  287. expect(store.require<any>(owner, 'conversation-task', secondTask.id)).toMatchObject({ title: '显式标题', titleSource: 'user', messageCount: 2 })
  288. expect(store.markTaskRead(owner, conversation.id, firstTask.id, firstSummary.lastSeq).unreadCount).toBe(0)
  289. store.deleteTask(owner, conversation.id, firstTask.id)
  290. expect(store.list<WorkspaceMessage>(owner, 'message').some(message => message.conversationTaskId === firstTask.id)).toBe(false)
  291. expect(store.list<any>(owner, 'binding').some(binding => binding.conversationTaskId === firstTask.id)).toBe(false)
  292. expect(store.get(owner, 'context', firstTask.id)).toBeUndefined()
  293. expect(store.messages(owner, conversation.id, Number.MAX_SAFE_INTEGER, 100, false, secondTask.id).map(message => message.content))
  294. .toEqual(['第二项工作', '第二项结果'])
  295. })
  296. it('limits a group to four active conversation tasks while retaining the global scheduler limit', async () => {
  297. const administrator = agent('并发任务管理员'),
  298. member = agent('并发任务成员'),
  299. conversation = store.createGroup(owner, {
  300. name: '并发任务群聊',
  301. memberIds: [administrator.id, member.id],
  302. administratorId: administrator.id,
  303. }),
  304. tasks = [defaultTask(conversation.id), ...Array.from({ length: 4 }, (_, index) => store.createTask(owner, conversation.id, { title: `任务 ${index + 2}` }))]
  305. reply = () => {}
  306. for (const [index, task] of tasks.slice(0, 4).entries())
  307. runtime.send(owner, conversation.id, { requestId: randomUUID(), taskId: task.id, content: `执行 ${index + 1}` })
  308. expect(store.activeTaskCount(owner, conversation.id)).toBe(4)
  309. expect(() => runtime.send(owner, conversation.id, { requestId: randomUUID(), taskId: tasks[4]!.id, content: '第五项' }))
  310. .toThrow('最多同时运行 4 个任务')
  311. await Promise.all(tasks.slice(0, 4).map(task => runtime.stopTask(owner, conversation.id, task.id)))
  312. })
  313. it('keeps same-named upstream interactions scoped to their conversation task', async () => {
  314. const administrator = agent('交互隔离管理员'),
  315. member = agent('交互隔离成员'),
  316. conversation = store.createGroup(owner, {
  317. name: '交互隔离群聊',
  318. memberIds: [administrator.id, member.id],
  319. administratorId: administrator.id,
  320. }),
  321. firstTask = defaultTask(conversation.id),
  322. secondTask = store.createTask(owner, conversation.id, {})
  323. reply = (socket, params) => setTimeout(() => socket.send(JSON.stringify({
  324. method: 'event',
  325. params: {
  326. type: 'approval.request',
  327. session_id: params.session_id,
  328. payload: { request_id: 'same-upstream-id', message: '允许执行吗?' },
  329. },
  330. })), 5)
  331. runtime.send(owner, conversation.id, { requestId: randomUUID(), taskId: firstTask.id, content: '任务甲' })
  332. runtime.send(owner, conversation.id, { requestId: randomUUID(), taskId: secondTask.id, content: '任务乙' })
  333. await vi.waitFor(() => expect(store.list<WorkspaceInteraction>(owner, 'interaction').filter(interaction => !interaction.resolved)).toHaveLength(2))
  334. const interactions = store.list<WorkspaceInteraction>(owner, 'interaction'),
  335. first = interactions.find(interaction => interaction.conversationTaskId === firstTask.id)!,
  336. second = interactions.find(interaction => interaction.conversationTaskId === secondTask.id)!
  337. expect(store.require<any>(owner, 'conversation-task', firstTask.id).activeRunStatus).toBe('waiting')
  338. expect(store.require<any>(owner, 'conversation-task', secondTask.id).activeRunStatus).toBe('waiting')
  339. await runtime.respond(owner, first.id, 'once')
  340. expect(store.require<WorkspaceInteraction>(owner, 'interaction', first.id).resolved).toBe(true)
  341. expect(store.require<WorkspaceInteraction>(owner, 'interaction', second.id).resolved).toBe(false)
  342. await Promise.all([runtime.stopTask(owner, conversation.id, firstTask.id), runtime.stopTask(owner, conversation.id, secondTask.id)])
  343. })
  344. it('persists a visible failure when a fixed member loses its source node',async()=>{
  345. const a=agent('不可用成员'),c=direct(a.id)
  346. runtime.close()
  347. runtime=new WorkspaceRuntime(store,{requireSource: () => {},target:()=>{throw new Error('基础节点不可用')}} as unknown as WorkspaceNodes,uploads)
  348. const run=runtime.send(owner,c.id,{requestId:randomUUID(),content:'执行任务'})
  349. await vi.waitFor(()=>expect(store.require<WorkspaceRun>(owner,'run',run.id).status).toBe('failed'))
  350. expect(store.messages(owner,c.id).at(-1)).toMatchObject({role:'system',status:'failed',content:'执行失败:基础节点不可用'})
  351. expect(store.require<WorkspaceConversation>(owner,'conversation',c.id).activeRunId).toBeUndefined()
  352. })
  353. it('interprets a reply against its launch-time roster when names or mode change mid-turn', async () => {
  354. const a = agent('管理员'),
  355. b = agent('执行者')
  356. const c = store.createGroup(owner, {
  357. name: '配置更新',
  358. memberIds: [a.id, b.id],
  359. administratorId: a.id,
  360. maxReplyRounds: 3,
  361. })
  362. let count = 0
  363. reply = (socket, p) => {
  364. let text = '已完成'
  365. if (count++ === 0) {
  366. store.updateAgent(owner, b.id, { name: '新名字', instructions: '新规则' })
  367. store.updateConversation(owner, c.id, { mode: 'free', administratorId: b.id })
  368. text = '请继续 @执行者'
  369. }
  370. setTimeout(
  371. () =>
  372. socket.send(
  373. JSON.stringify({
  374. method: 'event',
  375. params: { type: 'message.complete', session_id: p.session_id, payload: { text } },
  376. }),
  377. ),
  378. 5,
  379. )
  380. }
  381. await finished(runtime.send(owner, c.id, { requestId: randomUUID(), content: '开始' }).id)
  382. expect(
  383. store
  384. .messages(owner, c.id)
  385. .filter((m) => m.role === 'assistant')
  386. .map((m) => m.agentId),
  387. ).toEqual([a.id, b.id])
  388. expect(requests.filter((r) => r.method === 'prompt.submit').at(-1)!.params.text).toContain(
  389. '新规则',
  390. )
  391. })
  392. it('rejects unscoped and foreign-session completion events', async () => {
  393. const a = agent('会话隔离'),
  394. c = direct(a.id)
  395. reply = (socket, p) => {
  396. for (const session_id of [undefined, 'another-session'])
  397. socket.send(
  398. JSON.stringify({
  399. method: 'event',
  400. params: { type: 'message.complete', session_id, payload: { text: '别人的结果' } },
  401. }),
  402. )
  403. setTimeout(
  404. () =>
  405. socket.send(
  406. JSON.stringify({
  407. method: 'event',
  408. params: {
  409. type: 'message.complete',
  410. session_id: p.session_id,
  411. payload: { text: '本轮结果' },
  412. },
  413. }),
  414. ),
  415. 15,
  416. )
  417. }
  418. const run = runtime.send(owner, c.id, { requestId: randomUUID(), content: '执行' })
  419. await finished(run.id)
  420. expect(store.messages(owner, c.id).at(-1)?.content).toBe('本轮结果')
  421. expect(store.get<{ percent: number }>(owner, 'context', c.id)?.percent).toBe(40)
  422. })
  423. it('resumes a persisted uncertain run by inspecting history, without resending the prompt', async () => {
  424. const a = agent('恢复测试'),
  425. c = direct(a.id)
  426. reply = (socket, p) => {
  427. recoveryHistory = [
  428. { role: 'user', content: p.text },
  429. { role: 'assistant', content: '已经执行完成' },
  430. ]
  431. socket.terminate()
  432. }
  433. const run = runtime.send(owner, c.id, { requestId: randomUUID(), content: '修改一次' })
  434. await vi.waitFor(() =>
  435. expect(store.require<WorkspaceRun>(owner, 'run', run.id).status).toBe('uncertain'),
  436. )
  437. runtime.close()
  438. runtime = new WorkspaceRuntime(store, nodes, uploads)
  439. await runtime.reconcile(owner, run.id)
  440. await finished(run.id)
  441. expect(requests.filter((r) => r.method === 'prompt.submit')).toHaveLength(1)
  442. expect(store.messages(owner, c.id).map((m) => m.content)).toEqual(['修改一次', '已经执行完成'])
  443. })
  444. it('routes approvals and clarifications to the owning run and ignores optional push failures', async () => {
  445. const a = agent('交互测试'),
  446. c = direct(a.id)
  447. runtime.onNotify = () => {
  448. throw new Error('push storage unavailable')
  449. }
  450. let kind = 'approval'
  451. server.on('connection', (socket) =>
  452. socket.on('message', (data) => {
  453. const f = JSON.parse(String(data))
  454. if (['approval.respond', 'clarify.respond'].includes(f.method))
  455. socket.send(
  456. JSON.stringify({
  457. method: 'event',
  458. params: {
  459. type: 'message.complete',
  460. session_id: f.params.session_id,
  461. payload: { text: '确认后完成' },
  462. },
  463. }),
  464. )
  465. }),
  466. )
  467. reply = (socket, p) =>
  468. socket.send(
  469. JSON.stringify({
  470. method: 'event',
  471. params: {
  472. type: `${kind}.request`,
  473. session_id: p.session_id,
  474. payload: { request_id: 'upstream-interaction', message: '请确认' },
  475. },
  476. }),
  477. )
  478. for (kind of ['approval', 'clarify']) {
  479. const run = runtime.send(owner, c.id, { requestId: randomUUID(), content: '继续' })
  480. await vi.waitFor(() =>
  481. expect(store.require<WorkspaceRun>(owner, 'run', run.id).status).toBe('waiting'),
  482. )
  483. const interaction = store
  484. .list<WorkspaceInteraction>(owner, 'interaction')
  485. .find((i) => !i.resolved)!
  486. await expect(runtime.respond(other, interaction.id, 'once')).rejects.toThrow('记录不存在')
  487. await runtime.respond(owner, interaction.id, kind === 'approval' ? 'once' : '补充说明')
  488. await finished(run.id)
  489. expect(
  490. store.require<WorkspaceInteraction>(owner, 'interaction', interaction.id).resolved,
  491. ).toBe(true)
  492. }
  493. expect(
  494. requests
  495. .filter((r) => r.method === 'approval.respond' || r.method === 'clarify.respond')
  496. .map((r) => r.params.request_id),
  497. ).toEqual(['upstream-interaction', 'upstream-interaction'])
  498. })
  499. it('creates one direct chat without importing a native profile session', () => {
  500. const a = agent('编辑')
  501. expect(direct(a.id).kind).toBe('direct')
  502. expect(store.list(other, 'agent')).toEqual([])
  503. expect(() => store.require(other, 'conversation', direct(a.id).id)).toThrow('记录不存在')
  504. expect(requests).toEqual([])
  505. })
  506. it('protects the current administrator and validates member ownership', () => {
  507. const a = agent('甲'),
  508. b = agent('乙'),
  509. foreign = agent('外部', other)
  510. const c = store.createGroup(owner, {
  511. name: '团队',
  512. memberIds: [a.id, b.id],
  513. administratorId: a.id,
  514. })
  515. expect(() => store.updateConversation(owner, c.id, { memberIds: [b.id] })).toThrow('当前管理员不能移除')
  516. expect(() => store.updateConversation(owner, c.id, { memberIds: [b.id], administratorId: b.id })).toThrow('当前管理员不能移除')
  517. expect(() => store.updateConversation(owner, c.id, { memberIds: [a.id, foreign.id] })).toThrow('记录不存在')
  518. expect(() => store.updateConversation(owner, c.id, { memberIds: [a.id, a.id] })).toThrow('群成员或管理员无效')
  519. expect(() =>
  520. store.createGroup(owner, {
  521. name: '越权',
  522. memberIds: [a.id, foreign.id],
  523. administratorId: a.id,
  524. }),
  525. ).toThrow()
  526. store.updateAgent(owner, b.id, { archived: true })
  527. expect(store.require<WorkspaceConversation>(owner, 'conversation', c.id).memberIds).toEqual([
  528. a.id,
  529. b.id,
  530. ])
  531. expect(() =>
  532. store.createGroup(owner, { name: '新群', memberIds: [a.id, b.id], administratorId: a.id }),
  533. ).toThrow('已归档')
  534. expect(store.updateConversation(owner, c.id, { memberIds: [a.id] }).memberIds).toEqual([a.id])
  535. expect(() => store.updateConversation(owner, c.id, { memberIds: [a.id, b.id] })).toThrow('已归档')
  536. })
  537. it('adds and removes members, cleans automatic replies, and permits removal after administrator transfer', async () => {
  538. const a = agent('管理员'), b = agent('旧成员'), added = agent('新成员')
  539. const c = store.createGroup(owner, { name: '成员维护', memberIds: [a.id, b.id], administratorId: a.id, autoReplyIds: [b.id] })
  540. await finished(runtime.send(owner, c.id, { requestId: randomUUID(), content: '保留这条历史' }).id)
  541. const before = store.require<WorkspaceConversation>(owner, 'conversation', c.id)
  542. const history = store.messages(owner, c.id)
  543. const changed = store.updateConversation(owner, c.id, { memberIds: [a.id, added.id] })
  544. expect(changed.memberIds).toEqual([a.id, added.id])
  545. expect(changed.autoReplyIds).toEqual([])
  546. expect(changed.lastMessageAt).toBe(before.lastMessageAt)
  547. expect(store.messages(owner, c.id)).toEqual(history)
  548. expect(store.events(owner, 0).at(-1)).toMatchObject({ type: 'conversation.changed', data: { memberIds: [a.id, added.id] } })
  549. store.updateConversation(owner, c.id, { administratorId: added.id })
  550. expect(store.updateConversation(owner, c.id, { memberIds: [added.id] }).memberIds).toEqual([added.id])
  551. expect(() => store.updateConversation(owner, c.id, { memberIds: [a.id] })).toThrow('当前管理员不能移除')
  552. })
  553. it('skips removed queued members and accepts a newly added member on the next request', async () => {
  554. const a = agent('管理员'), b = agent('待回复'), added = agent('新成员')
  555. const c = store.createGroup(owner, { name: '队列维护', memberIds: [a.id, b.id], administratorId: a.id, mode: 'free', autoReplyIds: [a.id, b.id] })
  556. reply = (socket, p) => {
  557. socket.send(JSON.stringify({ method: 'event', params: { type: 'message.complete', session_id: p.session_id, payload: { text: '请@待回复继续' } } }))
  558. }
  559. const queued = runtime.send(owner, c.id, { requestId: randomUUID(), content: '开始' })
  560. store.updateConversation(owner, c.id, { memberIds: [a.id, added.id] })
  561. await finished(queued.id)
  562. expect(store.messages(owner, c.id).filter(m => m.role === 'assistant').map(m => m.agentId)).toEqual([a.id])
  563. await finished(runtime.send(owner, c.id, { requestId: randomUUID(), content: '请@新成员继续' }).id)
  564. expect(store.messages(owner, c.id).filter(m => m.role === 'assistant').map(m => m.agentId)).toEqual([a.id, added.id, a.id])
  565. })
  566. it('finishes an in-flight removed member reply without scheduling it again', async () => {
  567. const a = agent('管理员'), b = agent('正在回复')
  568. const c = store.createGroup(owner, { name: '回复中移除', memberIds: [a.id, b.id], administratorId: a.id })
  569. let turns = 0
  570. reply = (socket, p) => {
  571. if (turns++ === 1) store.updateConversation(owner, c.id, { memberIds: [a.id] })
  572. socket.send(JSON.stringify({ method: 'event', params: { type: 'message.complete', session_id: p.session_id, payload: { text: turns === 1 ? '请@正在回复继续' : '已完成' } } }))
  573. }
  574. await finished(runtime.send(owner, c.id, { requestId: randomUUID(), content: '@正在回复 开始' }).id)
  575. expect(store.messages(owner, c.id).filter(m => m.role === 'assistant').map(m => m.agentId)).toEqual([a.id, b.id, a.id])
  576. expect(() => runtime.send(owner, c.id, { requestId: randomUUID(), content: '继续', mentionIds: [b.id] })).toThrow('只能 @ 群内成员')
  577. })
  578. it('dispatches a request exactly once across retries and rejects payload reuse', async () => {
  579. const a = agent('编辑'),
  580. c = direct(a.id),
  581. requestId = randomUUID(),
  582. payload = { requestId, content: '检查代码' }
  583. const run = runtime.send(owner, c.id, payload)
  584. expect(runtime.send(owner, c.id, payload).id).toBe(run.id)
  585. expect(() => runtime.send(owner, c.id, { ...payload, content: '另一件事' })).toThrow('请求编号')
  586. await finished(run.id)
  587. expect(requests.filter((r) => r.method === 'prompt.submit')).toHaveLength(1)
  588. expect(store.messages(owner, c.id).map((m) => m.role)).toEqual(['user', 'assistant'])
  589. })
  590. it('keeps template responsibilities inside their group and follows Agent identity after rename', async () => {
  591. const a = agent('现有甲'), b = agent('现有乙')
  592. const before = store.require<WorkspaceAgent>(owner, 'agent', a.id)
  593. const c = store.createGroup(owner, { name: '模板群', memberIds: [a.id, b.id], administratorId: a.id, memberRoles: {
  594. [a.id]: { name: '调研负责人', description: '汇总可信结论' },
  595. [b.id]: { name: '事实核验', description: '交叉验证来源' },
  596. } })
  597. expect(store.require<WorkspaceAgent>(owner, 'agent', a.id)).toEqual(before)
  598. store.updateAgent(owner, a.id, { name: '改名后的甲' })
  599. await finished(runtime.send(owner, c.id, { requestId: randomUUID(), content: '开始调研' }).id)
  600. const groupPrompt = requests.filter(r => r.method === 'prompt.submit').at(-1)!.params.text
  601. expect(groupPrompt).toContain('@改名后的甲:调研负责人;汇总可信结论')
  602. expect(groupPrompt).toContain('@现有乙:事实核验;交叉验证来源')
  603. await finished(runtime.send(owner, direct(a.id).id, { requestId: randomUUID(), content: '单聊' }).id)
  604. expect(requests.filter(r => r.method === 'prompt.submit').at(-1)!.params.text).not.toContain('汇总可信结论')
  605. const changed = store.updateConversation(owner, c.id, { memberIds: [a.id] })
  606. expect(changed.memberRoles).toEqual({ [a.id]: { name: '调研负责人', description: '汇总可信结论' } })
  607. expect(() => store.updateConversation(owner, c.id, { memberRoles: { [b.id]: { name: '已移除', description: '' } } })).toThrow('群成员或管理员无效')
  608. })
  609. it('isolates roles over the same profile and applies edited rules on the next turn', async () => {
  610. const a = agent('编辑'),
  611. b = agent('审查'),
  612. ca = direct(a.id),
  613. cb = direct(b.id)
  614. const first = runtime.send(owner, ca.id, { requestId: randomUUID(), content: '编辑任务' })
  615. const second = runtime.send(owner, cb.id, { requestId: randomUUID(), content: '审查任务' })
  616. await Promise.all([finished(first.id), finished(second.id)])
  617. expect(requests.filter((r) => r.method === 'session.create')).toHaveLength(2)
  618. expect(store.messages(owner, ca.id).some((m) => m.content === '审查任务')).toBe(false)
  619. store.updateAgent(owner, a.id, { instructions: '最新规则:先给证据' })
  620. await finished(runtime.send(owner, ca.id, { requestId: randomUUID(), content: '继续' }).id)
  621. expect(requests.filter((r) => r.method === 'prompt.submit').at(-1)!.params.text).toContain(
  622. '最新规则:先给证据',
  623. )
  624. expect(requests.some((r) => r.method === 'profiles.configure')).toBe(false)
  625. expect(
  626. requests
  627. .filter((r) => r.method === 'session.create')
  628. .every((r) => r.params.hidden && r.params.source === 'yaoyao_workspace'),
  629. ).toBe(true)
  630. })
  631. it('executes bounded administrator delegation and keeps group sessions separate from direct chat', async () => {
  632. const a = agent('管理员'),
  633. b = agent('开发者'),
  634. c = store.createGroup(owner, {
  635. name: '开发',
  636. memberIds: [a.id, b.id],
  637. administratorId: a.id,
  638. maxReplyRounds: 3,
  639. })
  640. let turns = 0
  641. reply = (socket, p) => {
  642. const text = turns++ === 0 ? '我已整理需求,现在请@开发者继续实现。' : '任务完成'
  643. setTimeout(
  644. () =>
  645. socket.send(
  646. JSON.stringify({
  647. method: 'event',
  648. params: { type: 'message.complete', session_id: p.session_id, payload: { text } },
  649. }),
  650. ),
  651. 5,
  652. )
  653. }
  654. await finished(runtime.send(owner, c.id, { requestId: randomUUID(), content: '实现功能' }).id)
  655. expect(
  656. store
  657. .messages(owner, c.id)
  658. .filter((m) => m.role === 'assistant')
  659. .map((m) => m.agentId),
  660. ).toEqual([a.id, b.id, a.id])
  661. expect(store.messages(owner, direct(a.id).id)).toHaveLength(0)
  662. expect(turns).toBe(3)
  663. })
  664. it('does not trigger delegation from quoted text or code blocks', () => {
  665. const a = agent('甲'),
  666. b = agent('乙')
  667. expect(mentionedAgents('> @乙\n```\n@甲\n```\n`@all`', [a, b])).toEqual([])
  668. expect(mentionedAgents('请处理 @乙。', [a, b])).toEqual([b.id])
  669. })
  670. it('keeps uncertain submissions blocked instead of executing tools twice', async () => {
  671. const a = agent('执行者'),
  672. c = direct(a.id)
  673. reply = (socket) => socket.terminate()
  674. const run = runtime.send(owner, c.id, { requestId: randomUUID(), content: '修改文件' })
  675. await vi.waitFor(() =>
  676. expect(store.require<WorkspaceRun>(owner, 'run', run.id).status).toBe('uncertain'),
  677. )
  678. const queued = runtime.send(owner, c.id, { requestId: randomUUID(), content: '后续请求' })
  679. expect(queued.status).toBe('queued')
  680. expect(requests.filter((r) => r.method === 'prompt.submit')).toHaveLength(1)
  681. await runtime.stopConversation(owner, c.id)
  682. expect(
  683. store.require<WorkspaceConversation>(owner, 'conversation', c.id).activeRunId,
  684. ).toBeUndefined()
  685. })
  686. it('publishes durable ordered events only after commit and rolls back failed transactions', () => {
  687. const a = agent('甲'),
  688. c = direct(a.id),
  689. cursor = store.cursor(owner)
  690. expect(() =>
  691. store.atomic(() => {
  692. store.event(owner, 'test', {})
  693. throw new Error('rollback')
  694. }),
  695. ).toThrow('rollback')
  696. expect(store.cursor(owner)).toBe(cursor)
  697. store.updateAgent(owner, a.id, { name: '乙' })
  698. expect(store.events(owner, cursor).map((e) => e.type)).toEqual([
  699. 'agent.changed',
  700. 'conversation.changed',
  701. ])
  702. expect(store.events(other, 0)).toEqual([])
  703. expect(store.require<WorkspaceConversation>(owner, 'conversation', c.id).name).toBe('乙')
  704. })
  705. })
  706. it('pins a direct chat without injecting or clearing optional profile fields', () => {
  707. const avatar = encodeAgentAvatar({...defaultAgentIdentity('reviewer'),shape:'triangle',color:'#00b9ac',expression:'curious'})
  708. const agent = store.createAgent(owner, { name: '审查员', profile: 'default', avatar })
  709. const chat = store.list<WorkspaceConversation>(owner, 'conversation')[0]!
  710. expect(store.updateConversation(owner, chat.id, { pinned: true }).pinned).toBe(true)
  711. expect(store.updateConversation(owner, chat.id, { pinned: false }).pinned).toBe(false)
  712. expect(store.require<WorkspaceConversation>(owner, 'conversation', chat.id).avatar).toBe(avatar)
  713. expect(store.updateAgent(owner, agent.id, { instructions: '请检查边界' }).avatar).toBe(avatar)
  714. expect(decodeAgentAvatar(store.updateAgent(owner, agent.id, { avatar: '' }).avatar)).toMatchObject({shape:'circle',color:'#00c875'})
  715. })
  716. it('accepts the existing cross-client mascot and team avatar formats', () => {
  717. const a = store.createAgent(owner, { name: '设计', profile: 'default', avatar: 'yaoyao-mascot:v1:square:377fe6:friendly' })
  718. const b = store.createAgent(owner, { name: '开发', profile: 'default' })
  719. const group = store.createGroup(owner, { name: '产品团队', memberIds: [a.id, b.id], administratorId: a.id, avatar: 'builtin:team-animal:fox' })
  720. expect(group.avatar).toBe('builtin:team-animal:fox')
  721. expect(() => store.updateAgent(owner, a.id, { avatar: 'javascript:alert(1)' })).toThrow()
  722. })
  723. it('assigns a random v2 avatar only when a new Agent omits its avatar', () => {
  724. const random = vi.spyOn(Math, 'random').mockReturnValue(0)
  725. const created = store.createAgent(owner, { name: '随机头像', profile: 'default' })
  726. expect(decodeAgentAvatar(created.avatar)).toMatchObject({ shape: 'circle', color: '#000000', expression: 'idle' })
  727. expect(created.avatar).not.toBe(encodeAgentAvatar(defaultAgentIdentity(created.id, created.name)))
  728. random.mockRestore()
  729. })
  730. it('keeps the last message time independent of pinning and metadata edits', () => {
  731. const agent=store.createAgent(owner,{name:'时间验收',profile:'default'})
  732. const c=store.list<WorkspaceConversation>(owner,'conversation')[0]!
  733. const message: WorkspaceMessage={id:randomUUID(),conversationId:c.id,seq:0,role:'user',content:'历史消息',reasoning:'',status:'complete',attachments:[],tools:[],createdAt:Date.now()-600_000}
  734. store.saveMessage(owner,message)
  735. const pinned=store.updateConversation(owner,c.id,{pinned:true})
  736. expect(store.conversationSummary(owner,pinned).lastMessageAt).toBe(message.createdAt)
  737. store.updateAgent(owner,agent.id,{name:'改名之后'})
  738. expect(store.conversationSummary(owner,store.require(owner,'conversation',c.id)).lastMessageAt).toBe(message.createdAt)
  739. // Existing records without the summary field still use their transcript time.
  740. const previous={...pinned}; delete previous.lastMessageAt
  741. expect(store.conversationSummary(owner,previous).lastMessageAt).toBe(message.createdAt)
  742. })
  743. it('publishes only the executing member and clears avatar activity when stopped', async () => {
  744. const a=store.createAgent(owner,{name:'管理员头像',profile:'default'})
  745. const b=store.createAgent(owner,{name:'执行者头像',profile:'default'})
  746. const c=store.createGroup(owner,{name:'头像状态',memberIds:[a.id,b.id],administratorId:a.id})
  747. reply=(socket,p)=>socket.send(JSON.stringify({method:'event',params:{type:'approval.request',session_id:p.session_id,payload:{request_id:'approval-avatar',message:'需要确认'}}}))
  748. const run=runtime.send(owner,c.id,{requestId:randomUUID(),content:'处理任务',mentionIds:[b.id]})
  749. await vi.waitFor(()=>expect(store.require<WorkspaceRun>(owner,'run',run.id).status).toBe('waiting'))
  750. expect(store.require<WorkspaceConversation>(owner,'conversation',c.id)).toMatchObject({activeAgentId:a.id,activeRunStatus:'waiting'})
  751. await runtime.stop(owner,run.id)
  752. const stopped=store.require<WorkspaceConversation>(owner,'conversation',c.id)
  753. expect(stopped.activeAgentId).toBeUndefined()
  754. expect(stopped.activeRunStatus).toBeUndefined()
  755. })
  756. it('stores the expanded avatar shapes for cross-client role settings', () => {
  757. const agent=store.createAgent(owner,{name:'扩展头像验收',profile:'default'})
  758. for(const shape of ['ellipse','capsule','hexagon','cloud','droplet'] as const) {
  759. const avatar=encodeAgentAvatar({...defaultAgentIdentity('bot'),shape,color:'#f52ba5',expression:'curious'})
  760. expect(store.updateAgent(owner,agent.id,{avatar}).avatar).toBe(avatar)
  761. }
  762. })
  763. it('automatically reconciles lost completion without submitting the prompt again', async () => {
  764. const a=agent('自动恢复'),c=direct(a.id)
  765. reply=(socket,p)=>{recoveryHistory=[{role:'user',content:p.text},{role:'assistant',content:'已完成一次'}];socket.terminate()}
  766. const run=runtime.send(owner,c.id,{requestId:randomUUID(),content:'执行一次'})
  767. await vi.waitFor(()=>expect(store.require<WorkspaceRun>(owner,'run',run.id).status).toBe('complete'),{timeout:5000})
  768. expect(requests.filter(r=>r.method==='prompt.submit')).toHaveLength(1)
  769. expect(store.messages(owner,c.id).at(-1)).toMatchObject({content:'已完成一次',status:'complete'})
  770. })
  771. it('reports a rejected prompt as failed instead of leaving it uncertain', async () => {
  772. rejectPrompt='本轮请求被明确拒绝'
  773. const a=agent('拒绝测试'),c=direct(a.id)
  774. const run=runtime.send(owner,c.id,{requestId:randomUUID(),content:'执行'})
  775. await vi.waitFor(()=>expect(store.require<WorkspaceRun>(owner,'run',run.id).status).toBe('failed'))
  776. expect(store.require<WorkspaceConversation>(owner,'conversation',c.id).activeRunId).toBeUndefined()
  777. expect(store.messages(owner,c.id).some(m=>m.status==='uncertain')).toBe(false)
  778. })
  779. it('keeps an unconfirmed turn separate from a later reply and retries history without resubmitting', async () => {
  780. const a = agent('恢复边界'), c = direct(a.id)
  781. let prompt = ''
  782. reply = (socket, p) => {
  783. prompt = p.text
  784. recoveryHistory = [{ role: 'user', content: prompt }, { role: 'user', content: '另一个请求' }, { role: 'assistant', content: '另一轮回复' }]
  785. socket.terminate()
  786. }
  787. const run = runtime.send(owner, c.id, { requestId: randomUUID(), content: '只执行一次' })
  788. await vi.waitFor(() => expect(requests.filter(r => r.method === 'session.resume').length).toBeGreaterThanOrEqual(1), { timeout: 3000 })
  789. expect(store.require<WorkspaceRun>(owner, 'run', run.id).status).toBe('uncertain')
  790. expect(store.messages(owner, c.id).at(-1)?.content).not.toBe('另一轮回复')
  791. recoveryHistory = [{ role: 'user', content: prompt }, { role: 'assistant', content: '本轮结果' }]
  792. await vi.waitFor(() => expect(store.require<WorkspaceRun>(owner, 'run', run.id).status).toBe('complete'), { timeout: 4000 })
  793. expect(requests.filter(r => r.method === 'prompt.submit')).toHaveLength(1)
  794. expect(store.messages(owner, c.id).at(-1)).toMatchObject({ content: '本轮结果', status: 'complete' })
  795. })
  796. it('uses one generated avatar for the agent and its direct conversation',()=>{
  797. const a=agent('默认头像'),c=direct(a.id)
  798. expect(decodeAgentAvatar(a.avatar)).toMatchObject({version:2,avatarMode:'mascot'})
  799. expect(store.agentSummary(a).avatar).toBe(store.conversationSummary(owner,c).avatar)
  800. const changed=store.updateAgent(owner,a.id,{name:'换个名称'})
  801. expect(store.agentSummary(changed).avatar).toBe(store.agentSummary(a).avatar)
  802. })
  803. it('recognizes mentions inside Chinese sentences and ignores quoted code and emails',()=>{
  804. const a=agent('瑶儿'),b=agent('竹儿'),c=agent('瑶儿助手'),d=agent('Ann')
  805. const roster=[a,b,c,d]
  806. expect(mentionedAgents('先整理,再请@瑶儿帮忙,最后由(@竹儿)复核。',roster)).toEqual([a.id,b.id])
  807. expect(mentionedAgents('请**@瑶儿助手**继续',roster)).toEqual([c.id])
  808. expect(mentionedAgents('mail@Ann.com https://site/@竹儿 `@瑶儿` <quoted_message>@瑶儿</quoted_message>',roster)).toEqual([])
  809. expect(mentionedAgents('@Anna',roster)).toEqual([])
  810. })
  811. function completeReply(socket: WebSocket, p: Record<string, any>, text: string, status = 'complete') {
  812. socket.send(JSON.stringify({ method: 'event', params: { type: 'message.complete', session_id: p.session_id, payload: { text, status, ...(status === 'failed' ? { error: text } : {}) } } }))
  813. }
  814. const speaker = (p: Record<string, any>) => /^你是 (.*?)。/.exec(p.text)?.[1]
  815. it('starts with the administrator, executes a batch concurrently, and reviews failures once without spending a round', async () => {
  816. const a = agent('管理员'), b = agent('成员乙'), c = agent('成员丙')
  817. const group = store.createGroup(owner, { name: '并行验收', memberIds: [a.id,b.id,c.id], administratorId: a.id, maxReplyRounds: 2 })
  818. const pending = new Map<string, { socket: WebSocket; p: Record<string, any> }>()
  819. let admin = 0, review = ''
  820. reply = (socket,p) => {
  821. if (speaker(p) === a.name) { if (admin++ === 0) completeReply(socket,p,'请@成员乙检查接口,@成员丙检查数据'); else { review=p.text; completeReply(socket,p,'汇总完成') } }
  822. else pending.set(speaker(p)!, {socket,p})
  823. }
  824. const root = runtime.send(owner,group.id,{requestId:randomUUID(),content:'@成员乙 请处理'})
  825. await vi.waitFor(()=>expect(pending.size).toBe(2))
  826. expect(admin).toBe(1)
  827. expect(store.require<WorkspaceConversation>(owner,'conversation',group.id).activeAgentStates).toEqual({[b.id]:'running',[c.id]:'running'})
  828. completeReply(pending.get(c.name)!.socket,pending.get(c.name)!.p,'数据检查失败','failed')
  829. await vi.waitFor(()=>expect(store.messages(owner,group.id).some(m=>m.status==='failed')).toBe(true))
  830. expect(admin).toBe(1)
  831. completeReply(pending.get(b.name)!.socket,pending.get(b.name)!.p,'接口正常')
  832. await finished(root.id)
  833. expect(admin).toBe(2)
  834. expect(review).toContain('数据检查失败')
  835. expect(review).toContain('接口正常')
  836. expect(store.require<WorkspaceRun>(owner,'run',root.id).round).toBe(1)
  837. })
  838. it('allows successive dependent delegations and does not charge administrator reviews against the limit', async () => {
  839. const a=agent('负责人'),b=agent('先做'),c=agent('后做')
  840. const g=store.createGroup(owner,{name:'串行依赖',memberIds:[a.id,b.id,c.id],administratorId:a.id,maxReplyRounds:3})
  841. const order:string[]=[];let admin=0
  842. reply=(socket,p)=>{const name=speaker(p)!;order.push(name);completeReply(socket,p,name===a.name ? ['@先做 第一步','@后做 第二步','完成'][admin++]! : '结果已提交')}
  843. await finished(runtime.send(owner,g.id,{requestId:randomUUID(),content:'执行'}).id)
  844. expect(order).toEqual([a.name,b.name,a.name,c.name,a.name])
  845. })
  846. it('continues free discussion automatically and hides irrelevant automatic replies', async () => {
  847. const a=agent('公开管理员'),b=agent('自动成员')
  848. const g=store.createGroup(owner,{name:'自由讨论',memberIds:[a.id,b.id],administratorId:a.id,mode:'free',autoReplyIds:[b.id],maxReplyRounds:3})
  849. reply=(socket,p)=>completeReply(socket,p,speaker(p)===a.name?'我来回答':'[[YAOYAO_NO_REPLY_V1]]')
  850. const root=runtime.send(owner,g.id,{requestId:randomUUID(),content:'一个问题'})
  851. await finished(root.id)
  852. expect(requests.filter(r=>r.method==='prompt.submit'&&speaker(r.params)===b.name)).toHaveLength(2)
  853. expect(store.messages(owner,g.id).map(m=>m.content)).toEqual(['一个问题','我来回答'])
  854. expect(store.conversationSummary(owner,store.require(owner,'conversation',g.id)).unreadCount).toBe(2)
  855. expect(store.hiddenMessageIds(owner,g.id)).toHaveLength(2)
  856. })
  857. it('requires a public administrator reply when the model tries to remain silent', async () => {
  858. const a=agent('必须答复'),b=agent('旁观者'),g=store.createGroup(owner,{name:'公开答复',memberIds:[a.id,b.id],administratorId:a.id})
  859. reply=(socket,p)=>completeReply(socket,p,'[[YAOYAO_NO_REPLY_V1]]')
  860. await finished(runtime.send(owner,g.id,{requestId:randomUUID(),content:'帮助我'}).id)
  861. const answer=store.messages(owner,g.id).at(-1)!
  862. expect(answer.content).toContain('请补充具体目标')
  863. expect(answer.content).not.toContain('YAOYAO_')
  864. })
  865. it('queues later user requests durably without leaking them into the preceding collaboration', async () => {
  866. const a=agent('排队管理员'),b=agent('排队执行者'),g=store.createGroup(owner,{name:'消息排队',memberIds:[a.id,b.id],administratorId:a.id})
  867. let first: {socket:WebSocket;p:Record<string,any>}|undefined
  868. let admin=0;const prompts:string[]=[]
  869. reply=(socket,p)=>{prompts.push(p.text);if(speaker(p)===a.name&&admin++===0)first={socket,p};else completeReply(socket,p,'已完成')}
  870. const one=runtime.send(owner,g.id,{requestId:randomUUID(),content:'第一条任务'})
  871. await vi.waitFor(()=>expect(first).toBeDefined())
  872. const two=runtime.send(owner,g.id,{requestId:randomUUID(),content:'之后才处理的秘密标记'})
  873. expect(two.status).toBe('queued')
  874. expect(store.require<WorkspaceConversation>(owner,'conversation',g.id).activeRunId).toBe(one.id)
  875. completeReply(first!.socket,first!.p,'请@排队执行者继续')
  876. await finished(one.id);await finished(two.id)
  877. expect(prompts).toHaveLength(4)
  878. expect(prompts.slice(0,3).every(p=>!p.includes('之后才处理的秘密标记'))).toBe(true)
  879. expect(prompts[3]).toContain('之后才处理的秘密标记')
  880. })
  881. it('stops one member while keeping its sibling running and returns the interrupted result for review', async () => {
  882. const a=agent('停止管理员'),b=agent('停止乙'),c=agent('继续丙'),g=store.createGroup(owner,{name:'独立停止',memberIds:[a.id,b.id,c.id],administratorId:a.id})
  883. const pending=new Map<string,{socket:WebSocket;p:Record<string,any>}>();let admin=0,review=''
  884. reply=(socket,p)=>{if(speaker(p)===a.name){if(admin++===0)completeReply(socket,p,'@停止乙 @继续丙');else {review=p.text;completeReply(socket,p,'已汇总')}}else pending.set(speaker(p)!,{socket,p})}
  885. const root=runtime.send(owner,g.id,{requestId:randomUUID(),content:'开始'})
  886. await vi.waitFor(()=>expect(pending.size).toBe(2))
  887. await runtime.stopAgent(owner,g.id,b.id)
  888. expect(admin).toBe(1)
  889. expect(store.require<WorkspaceConversation>(owner,'conversation',g.id).activeAgentStates?.[c.id]).toBe('running')
  890. completeReply(pending.get(c.name)!.socket,pending.get(c.name)!.p,'丙完成')
  891. await finished(root.id)
  892. expect(review).toContain('interrupted')
  893. expect(review).toContain('丙完成')
  894. })
  895. it('recovers a partially completed parallel batch after restart without resubmitting members or duplicating review', async () => {
  896. const a=agent('恢复管理员'),b=agent('恢复乙'),c=agent('恢复丙'),g=store.createGroup(owner,{name:'批次恢复',memberIds:[a.id,b.id,c.id],administratorId:a.id})
  897. let admin=0;const pending=new Map<string,{socket:WebSocket;p:Record<string,any>}>()
  898. reply=(socket,p)=>{if(speaker(p)===a.name)completeReply(socket,p,admin++===0?'@恢复乙 @恢复丙':'复核完成');else pending.set(speaker(p)!,{socket,p})}
  899. const root=runtime.send(owner,g.id,{requestId:randomUUID(),content:'并行执行'})
  900. await vi.waitFor(()=>expect(pending.size).toBe(2))
  901. completeReply(pending.get(b.name)!.socket,pending.get(b.name)!.p,'乙已完成')
  902. const last=pending.get(c.name)!
  903. recoveryByStored.set(storedByRuntime.get(last.p.session_id)!,[{role:'user',content:last.p.text},{role:'assistant',content:'丙已完成'}])
  904. last.socket.terminate()
  905. await vi.waitFor(()=>expect(store.require<WorkspaceRun>(owner,'run',root.id).status).toBe('uncertain'))
  906. runtime.close();runtime=new WorkspaceRuntime(store,nodes,uploads);runtime.start()
  907. await finished(root.id)
  908. expect(admin).toBe(2)
  909. expect(requests.filter(r=>r.method==='prompt.submit')).toHaveLength(4)
  910. expect(store.list<any>(owner,'turn').filter(t=>t.reviewOf)).toHaveLength(1)
  911. })
  912. it('persists the next delegation when restarted between reply completion and cascade planning', async () => {
  913. const a=agent('记录管理员'),b=agent('记录成员'),g=store.createGroup(owner,{name:'计划恢复',memberIds:[a.id,b.id],administratorId:a.id})
  914. let admin=0
  915. reply=(socket,p)=>completeReply(socket,p,speaker(p)===a.name&&admin++===0?'@记录成员 执行':'完成')
  916. runtime.onMessage=async()=>{runtime.close()}
  917. const root=runtime.send(owner,g.id,{requestId:randomUUID(),content:'执行一次'})
  918. await vi.waitFor(()=>expect(store.list<any>(owner,'turn')[0]?.status).toBe('complete'))
  919. runtime=new WorkspaceRuntime(store,nodes,uploads);runtime.start()
  920. await finished(root.id)
  921. expect(requests.filter(r=>r.method==='prompt.submit')).toHaveLength(3)
  922. })
  923. it('bounds long context while preserving the task beginning and ending', async () => {
  924. const a=agent('长上下文'),b=agent('辅助'),g=store.createGroup(owner,{name:'上下文边界',memberIds:[a.id,b.id],administratorId:a.id})
  925. const text='任务开始标记'+ '文'.repeat(60_000)+'任务结束标记'
  926. await finished(runtime.send(owner,g.id,{requestId:randomUUID(),content:text}).id)
  927. const prompt=requests.find(r=>r.method==='prompt.submit')!.params.text
  928. expect(prompt).toContain('任务开始标记');expect(prompt).toContain('任务结束标记')
  929. expect(prompt).toContain('保留首尾片段');expect(prompt.length).toBeLessThan(32_000)
  930. })
  931. it('enforces three tasks per group and four globally while preserving queued work', async () => {
  932. const agents=['并发甲','并发乙','并发丙','并发丁','其他群'].map(n=>agent(n))
  933. const group=store.createGroup(owner,{name:'并发限制',memberIds:agents.slice(0,4).map(a=>a.id),administratorId:agents[0]!.id,mode:'free',autoReplyIds:agents.slice(0,4).map(a=>a.id),maxReplyRounds:1})
  934. const pending=new Map<string,{socket:WebSocket;p:Record<string,any>}>()
  935. reply=(socket,p)=>pending.set(speaker(p)!,{socket,p})
  936. const one=runtime.send(owner,group.id,{requestId:randomUUID(),content:'并发测试'})
  937. const two=runtime.send(owner,direct(agents[4]!.id).id,{requestId:randomUUID(),content:'另一群'})
  938. await vi.waitFor(()=>expect(pending.size).toBe(4))
  939. expect(Object.keys(store.require<WorkspaceConversation>(owner,'conversation',group.id).activeAgentStates!)).toHaveLength(3)
  940. expect(store.list<any>(owner,'turn').filter(t=>t.status==='running')).toHaveLength(4)
  941. const released=[...pending.values()].find(v=>speaker(v.p)!==agents[4]!.name)!
  942. completeReply(released.socket,released.p,'完成')
  943. await vi.waitFor(()=>expect(pending.size).toBe(5))
  944. expect(store.list<any>(owner,'turn').filter(t=>t.status==='running').length).toBeLessThanOrEqual(4)
  945. for(const v of pending.values()) if(v!==released) completeReply(v.socket,v.p,'完成')
  946. await finished(one.id);await finished(two.id)
  947. })
  948. it('supports unlimited rounds beyond the finite limit and still permits stopping', async () => {
  949. const a=agent('不限甲'),b=agent('不限乙'),g=store.createGroup(owner,{name:'不限轮次',memberIds:[a.id,b.id],administratorId:a.id,mode:'free',autoReplyIds:[a.id],maxReplyRounds:-1})
  950. let count=0
  951. reply=(socket,p)=>{
  952. if(count++===0){const work=store.list<any>(owner,'turn').find(t=>t.status==='running')!;work.depth=100;store.put(owner,'turn',work.id,work);completeReply(socket,p,'继续讨论')}
  953. else completeReply(socket,p,'[[YAOYAO_NO_REPLY_V1]]')
  954. }
  955. const root=runtime.send(owner,g.id,{requestId:randomUUID(),content:'@不限乙 开始'})
  956. await finished(root.id)
  957. expect(count).toBe(2)
  958. expect(store.require<WorkspaceRun>(owner,'run',root.id).round).toBe(101)
  959. expect(()=>store.updateConversation(owner,g.id,{maxReplyRounds:0})).toThrow()
  960. })
  961. it('keeps parallel approval cards scoped to their member and deduplicates replayed requests and answers', async () => {
  962. const a=agent('审批管理员'),b=agent('审批乙'),c=agent('审批丙'),g=store.createGroup(owner,{name:'并发审批',memberIds:[a.id,b.id,c.id],administratorId:a.id})
  963. let admin=0
  964. server.on('connection',socket=>socket.on('message',raw=>{const f=JSON.parse(String(raw));if(f.method==='approval.respond')completeReply(socket,f.params,'已确认')}))
  965. reply=(socket,p)=>{
  966. if(speaker(p)===a.name){completeReply(socket,p,admin++===0?'@审批乙 @审批丙':'汇总');return}
  967. const frame=JSON.stringify({method:'event',params:{type:'approval.request',session_id:p.session_id,payload:{request_id:'same-request',message:'是否继续'}}})
  968. socket.send(frame);socket.send(frame)
  969. }
  970. const root=runtime.send(owner,g.id,{requestId:randomUUID(),content:'开始'})
  971. await vi.waitFor(()=>expect(store.list<WorkspaceInteraction>(owner,'interaction').filter(i=>!i.resolved)).toHaveLength(2))
  972. const interactions=store.list<WorkspaceInteraction>(owner,'interaction')
  973. expect(store.require<WorkspaceConversation>(owner,'conversation',g.id).activeAgentStates).toEqual({[b.id]:'waiting',[c.id]:'waiting'})
  974. await runtime.respond(owner,interactions[0]!.id,'once')
  975. await runtime.respond(owner,interactions[0]!.id,'once')
  976. await expect(runtime.respond(owner,interactions[0]!.id,'deny')).rejects.toThrow('其他答复')
  977. expect(admin).toBe(1)
  978. await runtime.respond(owner,interactions[1]!.id,'once')
  979. await finished(root.id)
  980. expect(requests.filter(r=>r.method==='approval.respond')).toHaveLength(2)
  981. expect(admin).toBe(2)
  982. })
  983. it('retries a rolled-back cascade plan without losing or duplicating delegation', async () => {
  984. const a=agent('事务管理员'),b=agent('事务成员'),g=store.createGroup(owner,{name:'调度事务',memberIds:[a.id,b.id],administratorId:a.id})
  985. const original=store.put.bind(store);let failed=false,admin=0
  986. store.put=(user,kind,id,value)=>{if(!failed&&kind==='turn'&&(value as any).agentId===b.id){failed=true;throw new Error('模拟一次写入失败')}original(user,kind,id,value)}
  987. reply=(socket,p)=>completeReply(socket,p,speaker(p)===a.name&&admin++===0?'@事务成员 继续':'完成')
  988. const root=runtime.send(owner,g.id,{requestId:randomUUID(),content:'开始'})
  989. await vi.waitFor(()=>expect(store.require<WorkspaceRun>(owner,'run',root.id).status).toBe('complete'),{timeout:4000})
  990. expect(failed).toBe(true)
  991. expect(store.list<any>(owner,'turn').filter(t=>t.agentId===b.id)).toHaveLength(1)
  992. expect(requests.filter(r=>r.method==='prompt.submit')).toHaveLength(3)
  993. })
  994. it('upgrades an admitted v0.3.7 execution without submitting its prompt again', async () => {
  995. const a=agent('升级执行'),c=direct(a.id)
  996. reply=(socket,p)=>{recoveryHistory=[{role:'user',content:p.text},{role:'assistant',content:'升级前已完成'}];socket.terminate()}
  997. const root=runtime.send(owner,c.id,{requestId:randomUUID(),content:'只执行一次'})
  998. await vi.waitFor(()=>expect(store.require<WorkspaceRun>(owner,'run',root.id).status).toBe('uncertain'))
  999. runtime.close()
  1000. const old=store.list<any>(owner,'turn')[0]!
  1001. for(const task of store.list<any>(owner,'turn'))store.remove(owner,'turn',task.id)
  1002. const legacy=store.require<any>(owner,'run',root.id)
  1003. Object.assign(legacy,{queue:[a.id],next:[],hostReturn:false,currentMessageId:old.currentMessageId,turnConfiguration:old.turnConfiguration})
  1004. store.put(owner,'run',root.id,legacy)
  1005. const binding=store.get<any>(owner,'binding',`${c.id}:${a.id}`)!
  1006. delete binding.taskId;store.put(owner,'binding',binding.id,binding)
  1007. runtime=new WorkspaceRuntime(store,nodes,uploads);runtime.start()
  1008. await finished(root.id)
  1009. expect(requests.filter(r=>r.method==='prompt.submit')).toHaveLength(1)
  1010. expect(store.messages(owner,c.id).at(-1)?.content).toBe('升级前已完成')
  1011. })
  1012. it('does not read unrelated or orphaned historical runs when projecting a group prompt', async () => {
  1013. const a=agent('上下文隔离'),b=agent('组内成员'),g=store.createGroup(owner,{name:'干净群',memberIds:[a.id,b.id],administratorId:a.id})
  1014. store.put(owner,'run','historical-orphan',{id:'historical-orphan',conversationId:'unrelated-conversation',messageId:'missing-history',mentionIds:[],status:'complete',round:0,createdAt:1,updatedAt:1})
  1015. await finished(runtime.send(owner,g.id,{requestId:randomUUID(),content:'当前群任务'}).id)
  1016. expect(requests.filter(r=>r.method==='prompt.submit')).toHaveLength(1)
  1017. })
  1018. it('pages backwards to find a long-running turn marker and never mistakes a tool call for a final answer', async () => {
  1019. const a=agent('分页恢复'),c=direct(a.id)
  1020. reply=(socket,p)=>{
  1021. recoveryHistory=[{role:'user',content:p.text},...Array.from({length:600},()=>({role:'tool',content:'工具结果'})),{role:'assistant',content:'最终结果'}]
  1022. socket.terminate()
  1023. }
  1024. await finished(runtime.send(owner,c.id,{requestId:randomUUID(),content:'长时间执行'}).id)
  1025. expect(store.messages(owner,c.id).at(-1)?.content).toBe('最终结果')
  1026. let submitted=''
  1027. reply=(socket,p)=>{submitted=p.text;recoveryHistory=[{role:'user',content:submitted},{role:'assistant',content:'准备调用工具',tool_calls:[{id:'tool'}]},{role:'tool',content:'工具输出'}];socket.terminate()}
  1028. const root=runtime.send(owner,c.id,{requestId:randomUUID(),content:'不要把过程当结论'})
  1029. await vi.waitFor(()=>expect(store.require<WorkspaceRun>(owner,'run',root.id).status).toBe('uncertain'))
  1030. await runtime.reconcile(owner,root.id)
  1031. await new Promise(resolve=>setTimeout(resolve,100))
  1032. expect(store.require<WorkspaceRun>(owner,'run',root.id).status).toBe('uncertain')
  1033. recoveryHistory.push({role:'assistant',content:'真正完成'})
  1034. await runtime.reconcile(owner,root.id)
  1035. await finished(root.id)
  1036. expect(requests.filter(r=>r.method==='prompt.submit')).toHaveLength(2)
  1037. })
  1038. it('keeps explicit replies visible and emits one notice when the configured cascade limit is reached', async () => {
  1039. const a=agent('轮数管理员'),b=agent('轮数成员'),g=store.createGroup(owner,{name:'有限轮次',memberIds:[a.id,b.id],administratorId:a.id,maxReplyRounds:2})
  1040. reply=(socket,p)=>completeReply(socket,p,speaker(p)===a.name?'@轮数成员 继续':'已完成本步')
  1041. const root=runtime.send(owner,g.id,{requestId:randomUUID(),content:'开始'})
  1042. await finished(root.id)
  1043. expect(requests.filter(r=>r.method==='prompt.submit')).toHaveLength(3)
  1044. expect(store.messages(owner,g.id).filter(m=>m.content.includes('轮数上限'))).toHaveLength(1)
  1045. store.updateConversation(owner,g.id,{mode:'free',autoReplyIds:[]})
  1046. reply=(socket,p)=>completeReply(socket,p,'[[YAOYAO_NO_REPLY_V1]]')
  1047. await finished(runtime.send(owner,g.id,{requestId:randomUUID(),content:'@轮数成员 显示这个字符串'}).id)
  1048. expect(store.messages(owner,g.id).at(-1)?.content).toBe('[[YAOYAO_NO_REPLY_V1]]')
  1049. })
  1050. it('retries a failed stop of a live task without falsely completing it or resubmitting work', async () => {
  1051. const a=agent('停止恢复'),c=direct(a.id)
  1052. reply=()=>{}
  1053. const root=runtime.send(owner,c.id,{requestId:randomUUID(),content:'等待停止'})
  1054. await vi.waitFor(()=>expect(requests.filter(r=>r.method==='prompt.submit')).toHaveLength(1))
  1055. rejectedInterrupts=1
  1056. await runtime.stop(owner,root.id)
  1057. expect(store.require<WorkspaceRun>(owner,'run',root.id).status).toBe('uncertain')
  1058. await vi.waitFor(()=>expect(store.require<WorkspaceRun>(owner,'run',root.id).status).toBe('interrupted'),{timeout:3000})
  1059. expect(requests.filter(r=>r.method==='session.interrupt')).toHaveLength(2)
  1060. expect(requests.filter(r=>r.method==='prompt.submit')).toHaveLength(1)
  1061. })
  1062. it('marks a stopped administrator as interrupted without sending a false completion notification', async () => {
  1063. const a=agent('管理员停止'),b=agent('普通成员'),g=store.createGroup(owner,{name:'停止管理员',memberIds:[a.id,b.id],administratorId:a.id})
  1064. reply=()=>{}
  1065. const notifications: string[]=[]
  1066. runtime.onNotify=(_owner,_c,run)=>notifications.push(run.status)
  1067. const root=runtime.send(owner,g.id,{requestId:randomUUID(),content:'等待'})
  1068. await vi.waitFor(()=>expect(requests.filter(r=>r.method==='prompt.submit')).toHaveLength(1))
  1069. await runtime.stopAgent(owner,g.id,a.id)
  1070. await vi.waitFor(()=>expect(store.require<WorkspaceRun>(owner,'run',root.id).status).toBe('interrupted'))
  1071. expect(notifications).toEqual([])
  1072. })
  1073. it('randomizes old default avatars once while preserving photos, custom v2 settings and direct snapshots',()=>{
  1074. const a=store.createAgent(owner,{name:'旧头像',profile:'default',instructions:'保留规则'})
  1075. const photo='data:image/png;base64,aGVsbG8='
  1076. const b=store.createAgent(owner,{name:'照片',profile:'default',avatar:photo})
  1077. store.put(owner,'agent',a.id,{...a,avatar:'yaoyao-mascot:v1:triangle:ff0000:friendly'})
  1078. store.put(owner,'agent',b.id,{...b,avatar:photo})
  1079. store.db.prepare("DELETE FROM workspace_migrations WHERE id IN ('avatar-v2','avatar-random-default-v1')").run()
  1080. const random=vi.spyOn(Math,'random').mockReturnValue(0)
  1081. const migrated=new WorkspaceStore(home)
  1082. random.mockRestore()
  1083. const next=migrated.require<any>(owner,'agent',a.id)
  1084. expect(next.instructions).toBe('保留规则')
  1085. expect(decodeAgentAvatar(next.avatar)).toMatchObject({avatarMode:'mascot'})
  1086. expect(next.avatar).not.toBe(encodeAgentAvatar(defaultAgentIdentity(a.id,a.name)))
  1087. const image=migrated.require<any>(owner,'agent',b.id)
  1088. expect(decodeAgentAvatar(image.avatar)).toMatchObject({avatarMode:'image',imageDataURL:photo,imageCrop:'rounded'})
  1089. for(const c of migrated.list<WorkspaceConversation>(owner,'conversation')) expect(c.avatar).toBe(migrated.require<any>(owner,'agent',c.memberIds[0]!).avatar)
  1090. const customized=encodeAgentAvatar({...defaultAgentIdentity('bot'),bodyId:'star',expression:'proud',color:'#1488ff'})
  1091. migrated.updateAgent(owner,a.id,{avatar:customized})
  1092. migrated.close()
  1093. const reopened=new WorkspaceStore(home)
  1094. expect(reopened.require<any>(owner,'agent',a.id).avatar).toBe(customized)
  1095. expect(reopened.db.prepare("SELECT count(*) AS count FROM workspace_migrations WHERE id='avatar-random-default-v1'").get()!.count).toBe(1)
  1096. reopened.close()
  1097. })
  1098. // A member can have a queued follow-up while their current task needs approval.
  1099. it('keeps active avatar state ahead of queued work and publishes only recent outcomes', () => {
  1100. const a=agent('状态优先级'), c=direct(a.id), now=Date.now()
  1101. const run: WorkspaceRun={id:'avatar-run',conversationId:c.id,messageId:'unused',mentionIds:[],status:'complete',round:1,createdAt:now,updatedAt:now}
  1102. for (const [id,status] of [['current','waiting'],['next','queued']] as const)
  1103. store.put(owner,'turn',id,{id,conversationId:c.id,agentId:a.id,status,planned:true,updatedAt:now})
  1104. store.put(owner,'turn','result',{id:'result',conversationId:c.id,agentId:a.id,status:'failed',updatedAt:now})
  1105. store.saveRun(owner,run)
  1106. let summary=store.require<WorkspaceConversation>(owner,'conversation',c.id)
  1107. expect(summary.activeAgentStates).toEqual({[a.id]:'waiting'})
  1108. expect(summary.avatarSignals?.[a.id]).toMatchObject({id:'result',state:'failure'})
  1109. store.put(owner,'turn','result',{id:'result',conversationId:c.id,agentId:a.id,status:'complete',updatedAt:now-3000})
  1110. store.saveRun(owner,run)
  1111. expect(store.require<WorkspaceConversation>(owner,'conversation',c.id).avatarSignals).toEqual({})
  1112. })