workspace.test.ts 68 KB

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