workspace.test.ts 106 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685
  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 {HttpError} from '../../src/server/errors'
  10. import {WorkspaceAssets} from '../../src/server/workspaceAssets'
  11. import { WorkspaceStore } from '../../src/server/workspaceStore'
  12. import { WorkspaceRuntime, mentionedAgents } from '../../src/server/workspaceRuntime'
  13. import type { Work } from '../../src/server/workspaceScheduler'
  14. import { REPEATED_RELAY_NOTICE } from '../../src/server/workspaceRelay'
  15. import { WorkspaceNodes, WorkspaceGateway, type GatewayTarget } from '../../src/server/workspaceGateway'
  16. import { UploadStore } from '../../src/server/uploads'
  17. import type {
  18. WorkspaceConversation,
  19. WorkspaceRun,
  20. WorkspaceMessage,
  21. WorkspaceInteraction,
  22. } from '../../src/shared/workspace'
  23. let home: string,
  24. store: WorkspaceStore,
  25. uploads: UploadStore,
  26. runtime: WorkspaceRuntime,
  27. server: WebSocketServer
  28. let requests: Array<{ method: string; params: Record<string, any> }>,
  29. reply: (socket: WebSocket, params: Record<string, any>) => void
  30. let nodes: WorkspaceNodes
  31. let configuredCwds: Map<string, string>
  32. let rejectPrompt: string | undefined
  33. let rejectedInterrupts: number
  34. let recoveryHistory: Array<{ role: string; content: string; tool_calls?: unknown }>
  35. let storedByRuntime: Map<string, string>, recoveryByStored: Map<string, Array<{ role: string; content: string }>>
  36. const owner = 'first-user',
  37. other = 'second-user'
  38. beforeEach(async () => {
  39. home = mkdtempSync(join(tmpdir(), 'yaoyao-workspace-test-'))
  40. store = new WorkspaceStore(home)
  41. uploads = new UploadStore(home)
  42. requests = []
  43. configuredCwds = new Map()
  44. recoveryHistory = []
  45. storedByRuntime = new Map(); recoveryByStored = new Map()
  46. rejectPrompt = undefined
  47. rejectedInterrupts = 0
  48. server = new WebSocketServer({ port: 0, host: '127.0.0.1' })
  49. await new Promise<void>((resolve) => server.once('listening', resolve))
  50. const address = server.address() as { port: number }
  51. const target = {
  52. url: new URL(`http://127.0.0.1:${address.port}`),
  53. client: { directAgent: undefined },
  54. session: {
  55. webSocketCredential: async () => ({ name: 'ticket', value: 'test' }),
  56. request: async (path: string, options?: {search?: URLSearchParams}) => ({
  57. status: 200,
  58. body: Buffer.from(JSON.stringify(path === '/api/config'
  59. ? { terminal: { cwd: configuredCwds.get(options?.search?.get('profile') ?? '') } }
  60. : { 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) })() })),
  61. }),
  62. },
  63. }
  64. nodes = { requireSource: () => {}, target: () => target } as unknown as WorkspaceNodes
  65. runtime = new WorkspaceRuntime(store, nodes, uploads)
  66. reply = (socket, p) =>
  67. setTimeout(
  68. () =>
  69. socket.send(
  70. JSON.stringify({
  71. method: 'event',
  72. params: {
  73. type: 'message.complete',
  74. session_id: p.session_id,
  75. payload: { text: '完成', status: 'complete' },
  76. },
  77. }),
  78. ),
  79. 5,
  80. )
  81. server.on('connection', (socket) => {
  82. socket.send(JSON.stringify({ method: 'event', params: { type: 'gateway.ready' } }))
  83. socket.on('message', (data) => {
  84. const frame = JSON.parse(String(data))
  85. requests.push(frame)
  86. const respond = (result: unknown) => socket.send(JSON.stringify({ id: frame.id, result }))
  87. if (frame.method === 'session.create' || frame.method === 'session.resume') {
  88. const runtimeId = randomUUID(), storedId = frame.method === 'session.resume' ? frame.params.session_id : randomUUID()
  89. storedByRuntime.set(runtimeId, storedId)
  90. respond({ session_id: runtimeId, stored_session_id: storedId, running: false, info: { profile_name: frame.params.profile } })
  91. }
  92. else if (frame.method === 'session.cwd.set') respond({ cwd: frame.params.cwd })
  93. else if (frame.method === 'prompt.submit') {
  94. if (rejectPrompt) { socket.send(JSON.stringify({id:frame.id,error:{code:4006,message:rejectPrompt}})); return }
  95. respond({ status: 'streaming' })
  96. reply(socket, frame.params)
  97. } else if (frame.method === 'session.usage') respond({ context_used: 400, context_max: 1000 })
  98. else if (frame.method === 'session.interrupt' && rejectedInterrupts-- > 0) socket.send(JSON.stringify({id:frame.id,error:{code:500,message:'暂时不能中断'}}))
  99. else respond({ ok: true, status: 'interrupted' })
  100. })
  101. })
  102. })
  103. afterEach(async () => {
  104. runtime.close()
  105. await new Promise((resolve) => setTimeout(resolve, 10))
  106. for (const client of server.clients) client.terminate()
  107. await new Promise<void>((resolve) => server.close(() => resolve()))
  108. uploads.close()
  109. store.close()
  110. rmSync(home, { recursive: true, force: true })
  111. })
  112. function agent(name: string, user = owner) {
  113. return store.createAgent(user, { name, profile: 'default', instructions: `规则:你是${name}` })
  114. }
  115. it('executes a structured assignment on its actual worker and leaves acceptance to its coordinator', async () => {
  116. const lead = store.updateAgent(owner, agent('负责人').id, { canManageTeam: true })
  117. const worker = agent('研究成员')
  118. const source = direct(lead.id)
  119. const original = runtime.send(owner, source.id, { requestId: randomUUID(), content: '完成研究' })
  120. for (const work of store.list<any>(owner, 'turn').filter(w => w.runId === original.id))
  121. store.put(owner, 'turn', work.id, { ...work, status: 'complete', planned: true })
  122. original.status = 'complete';store.saveRun(owner, original)
  123. const team = store.createGroup(owner, { name: '研究团队', memberIds: [lead.id,worker.id], administratorId: lead.id })
  124. const goal = runtime.tasks.begin(owner, store.tasks(owner, team.id)[0]!, lead, '研究事实', { conversationId: source.id, runId: original.id, agentId: lead.id })
  125. const assignment = runtime.tasks.createAssignment(owner, lead.id, { requestId: randomUUID(), goalId: goal.id, agentId: worker.id, title: '核对事实', brief: '提交核对结果' })
  126. await vi.waitFor(() => expect(store.get<any>(owner,'assignment',assignment.id)?.status).toBe('review'), { timeout: 5000 })
  127. const submitted = requests.find(r => r.method === 'prompt.submit' && String(r.params.text).includes('核对事实'))!
  128. expect(submitted.params.text).toContain('你是 研究成员')
  129. expect(submitted.params.text).toContain('执行子任务')
  130. expect(store.get<any>(owner,'goal',goal.id)?.status).not.toBe('complete')
  131. })
  132. it('keeps structured goal coordination on the lead and does not relay mention text as duplicate work', async () => {
  133. const lead=store.updateAgent(owner,agent('交付负责人').id,{canManageTeam:true}),worker=agent('研究成员')
  134. const target=nodes.target(owner,'local'), request=target.session.request.bind(target.session)
  135. vi.spyOn(target.session,'request').mockImplementation(async(path,options)=>path.startsWith('/api/plugins/yaoyao-bot-bridge/')
  136. ? {status:200,body:Buffer.from(JSON.stringify({ok:true,version:1,ready:true,in_process:true,native_tools:true})),headers:new Headers()}
  137. : request(path,options))
  138. const team=store.createGroup(owner,{name:'自由协作交付',memberIds:[lead.id,worker.id],administratorId:lead.id,mode:'free',autoReplyIds:[worker.id]})
  139. reply=(socket,p)=>socket.send(JSON.stringify({method:'event',params:{type:'message.complete',session_id:p.session_id,payload:{text:'@研究成员 请核对资料',status:'complete'}}}))
  140. const run=runtime.send(owner,team.id,{requestId:randomUUID(),content:'交付研究报告',mode:'goal'})
  141. await vi.waitFor(()=>expect(['complete','failed']).toContain(store.require<WorkspaceRun>(owner,'run',run.id).status))
  142. const settled=store.require<WorkspaceRun>(owner,'run',run.id)
  143. expect(settled.status,settled.error).toBe('complete')
  144. const work=store.list<Work>(owner,'turn').filter(w=>w.runId===run.id)
  145. expect(work.map(w=>w.agentId)).toEqual([lead.id])
  146. expect(runtime.tasks.assignments(owner,run.goalId!)).toEqual([])
  147. expect(requests.filter(r=>r.method==='prompt.submit').every(r=>!String(r.params.text).startsWith('你是 研究成员'))).toBe(true)
  148. })
  149. function direct(id: string, user = owner) {
  150. return store
  151. .list<WorkspaceConversation>(user, 'conversation')
  152. .find((c) => c.kind === 'direct' && c.memberIds[0] === id)!
  153. }
  154. function defaultTask(conversationId: string, user = owner) {
  155. return store.tasks(user, conversationId)[0]!
  156. }
  157. async function finished(id: string) {
  158. await vi.waitFor(() =>
  159. expect(store.require<WorkspaceRun>(owner, 'run', id).status).toBe('complete'),
  160. )
  161. return store.require<WorkspaceRun>(owner, 'run', id)
  162. }
  163. describe('Web-owned workspace', () => {
  164. it('restores recent user and assistant context when moving a completed conversation to another runner',async()=>{
  165. const a=agent('移动成员'),c=direct(a.id)
  166. await finished(runtime.send(owner,c.id,{requestId:randomUUID(),content:'保存研究结论'}).id)
  167. const binding=store.list<any>(owner,'binding')[0]!
  168. store.put(owner,'binding',binding.id,{...binding,runnerId:'previous-runner'})
  169. const before=requests.length
  170. await finished(runtime.send(owner,c.id,{requestId:randomUUID(),content:'继续后续分析'}).id)
  171. const next=requests.slice(before)
  172. expect(next.some(r=>r.method==='session.resume')).toBe(false)
  173. const text=next.find(r=>r.method==='prompt.submit')!.params.text
  174. expect(text).toContain('执行节点已切换')
  175. expect(text).toContain('保存研究结论')
  176. expect(text).toContain('移动成员(complete):完成')
  177. expect(text).toContain('继续后续分析')
  178. })
  179. it('uses each base profile cwd and replaces historical cwd before the next Bot turn', async () => {
  180. configuredCwds.set('default', '/profile/first')
  181. configuredCwds.set('other', '/profile/other')
  182. const a = agent('主助手'), c = direct(a.id)
  183. await finished(runtime.send(owner, c.id, { requestId: randomUUID(), content: 'first' }).id)
  184. expect(requests.find(r => r.method === 'session.create')?.params.cwd).toBe('/profile/first')
  185. expect(requests.find(r => r.method === 'session.cwd.set')?.params.cwd).toBe('/profile/first')
  186. configuredCwds.set('default', '/profile/changed')
  187. const before = requests.length
  188. await finished(runtime.send(owner, c.id, { requestId: randomUUID(), content: 'second' }).id)
  189. // The prior turn's asynchronous usage refresh can arrive after completion.
  190. // This assertion concerns the next turn's execution RPCs, not telemetry.
  191. const next = requests.slice(before).filter(r => r.method !== 'session.usage')
  192. expect(next[0].method).toBe('session.resume')
  193. expect(next.find(r => r.method === 'session.cwd.set')?.params.cwd).toBe('/profile/changed')
  194. expect(next.findIndex(r => r.method === 'session.cwd.set')).toBeLessThan(next.findIndex(r => r.method === 'prompt.submit'))
  195. const b = store.createAgent(owner, { name: '其他 Profile', profile: 'other' })
  196. await finished(runtime.send(owner, direct(b.id).id, { requestId: randomUUID(), content: 'third' }).id)
  197. expect(requests.filter(r => r.method === 'session.create').at(-1)?.params.cwd).toBe('/profile/other')
  198. })
  199. it('flushes a paused delta before completion and cancels pending flush on finish', async () => {
  200. let upstream: { socket: WebSocket; params: Record<string, any> } | undefined
  201. reply = (socket, params) => {
  202. upstream = { socket, params }
  203. const event = (type: string, payload: Record<string, unknown>) => socket.send(JSON.stringify({
  204. method: 'event', params: { type, session_id: params.session_id, payload },
  205. }))
  206. event('message.start', {})
  207. event('message.delta', { text: '# 流式标题' })
  208. }
  209. const bot = agent('流式助手'), conversation = direct(bot.id)
  210. const run = runtime.send(owner, conversation.id, { requestId: randomUUID(), content: '验证暂停分片' })
  211. const assistant = () => store.list<WorkspaceMessage>(owner, 'message').find(m => m.runId === run.id && m.role === 'assistant')
  212. await vi.waitFor(() => expect(assistant()?.content).toBe('# 流式标题'))
  213. expect(assistant()?.status).toBe('streaming')
  214. expect(store.require<WorkspaceRun>(owner, 'run', run.id).status).not.toBe('complete')
  215. const { socket, params } = upstream!
  216. socket.send(JSON.stringify({ method: 'event', params: { type: 'message.delta', session_id: params.session_id, payload: { text: '\n\n最后一段' } } }))
  217. completeReply(socket, params, '# 最终正文')
  218. await finished(run.id)
  219. await new Promise(resolve => setTimeout(resolve, 150))
  220. expect(assistant()?.content).toBe('# 最终正文')
  221. expect(assistant()?.status).toBe('complete')
  222. })
  223. it('backfills legacy group history into the initial task instead of leaving a new empty task', () => {
  224. const legacyHome = mkdtempSync(join(tmpdir(), 'yaoyao-workspace-task-migration-'))
  225. let seededStore: WorkspaceStore | undefined = new WorkspaceStore(legacyHome)
  226. let migratedStore: WorkspaceStore | undefined
  227. try {
  228. const administrator = seededStore.createAgent(owner, { name: '历史管理员', profile: 'default' }),
  229. member = seededStore.createAgent(owner, { name: '历史成员', profile: 'default' }),
  230. conversation = seededStore.createGroup(owner, {
  231. name: '公众号文案团队',
  232. memberIds: [administrator.id, member.id],
  233. administratorId: administrator.id,
  234. }),
  235. initialTask = seededStore.tasks(owner, conversation.id)[0]!,
  236. userAt = 1_788_000_000_000,
  237. assistantAt = userAt + 60_000
  238. seededStore.put(owner, 'message', 'legacy-user', {
  239. id: 'legacy-user', conversationId: conversation.id, seq: 1, role: 'user',
  240. content: '请继续完成公众号文案', reasoning: '', status: 'complete',
  241. attachments: [], tools: [], createdAt: userAt,
  242. } satisfies WorkspaceMessage)
  243. seededStore.put(owner, 'message', 'legacy-assistant', {
  244. id: 'legacy-assistant', conversationId: conversation.id, seq: 2, role: 'assistant',
  245. agentId: administrator.id, agentName: '历史管理员', content: '旧内容已经完成。',
  246. reasoning: '', status: 'complete', attachments: [], tools: [], createdAt: assistantAt,
  247. } satisfies WorkspaceMessage)
  248. seededStore.put(owner, 'conversation', conversation.id, {
  249. ...conversation,
  250. readSeq: 1,
  251. lastSeq: 2,
  252. preview: '旧内容已经完成。',
  253. lastMessageAt: assistantAt,
  254. updatedAt: assistantAt,
  255. })
  256. seededStore.put(owner, 'run', 'legacy-run', {
  257. id: 'legacy-run', conversationId: conversation.id, messageId: 'legacy-user',
  258. mentionIds: [], status: 'complete', round: 1, createdAt: userAt, updatedAt: assistantAt,
  259. } satisfies WorkspaceRun)
  260. seededStore.put(owner, 'turn', 'legacy-turn', {
  261. id: 'legacy-turn', runId: 'legacy-run', conversationId: conversation.id,
  262. agentId: administrator.id, messageId: 'legacy-user', status: 'complete', createdAt: userAt,
  263. })
  264. seededStore.put(owner, 'interaction', 'legacy-interaction', {
  265. id: 'legacy-interaction', conversationId: conversation.id, runId: 'legacy-run',
  266. agentId: administrator.id, kind: 'clarification', message: '补充说明',
  267. choices: [], resolved: true,
  268. } satisfies WorkspaceInteraction)
  269. seededStore.put(owner, 'interaction-binding', 'legacy-interaction', {
  270. key: `${conversation.id}:${administrator.id}`,
  271. upstreamId: 'upstream-interaction', taskId: 'legacy-turn',
  272. })
  273. seededStore.put(owner, 'binding', `${conversation.id}:${administrator.id}`, {
  274. nodeId: 'local', profile: 'default', storedId: 'stored-legacy',
  275. runtimeId: 'runtime-legacy', aliases: [], runId: 'legacy-run',
  276. messageId: 'legacy-user', taskId: 'legacy-turn',
  277. })
  278. seededStore.put(owner, 'context', conversation.id, {
  279. usedTokens: 100, limitTokens: 1_000, observedAt: assistantAt,
  280. })
  281. seededStore.db.prepare('DELETE FROM workspace_migrations WHERE id=?')
  282. .run('conversation-task-history-v1')
  283. seededStore.close()
  284. seededStore = undefined
  285. migratedStore = new WorkspaceStore(legacyHome)
  286. const tasks = migratedStore.tasks(owner, conversation.id)
  287. expect(tasks).toHaveLength(1)
  288. expect(tasks[0]).toMatchObject({
  289. id: initialTask.id,
  290. title: '请继续完成公众号文案',
  291. titleSource: 'automatic',
  292. messageCount: 2,
  293. readSeq: 1,
  294. lastSeq: 2,
  295. unreadCount: 1,
  296. lastMessageAt: assistantAt,
  297. createdAt: userAt,
  298. updatedAt: assistantAt,
  299. })
  300. expect(
  301. migratedStore.messages(
  302. owner, conversation.id, Number.MAX_SAFE_INTEGER, 100, false, initialTask.id,
  303. ).map(message => message.id),
  304. ).toEqual(['legacy-user', 'legacy-assistant'])
  305. expect(migratedStore.require<WorkspaceRun>(owner, 'run', 'legacy-run').conversationTaskId)
  306. .toBe(initialTask.id)
  307. expect(migratedStore.require<{ conversationTaskId: string }>(owner, 'turn', 'legacy-turn').conversationTaskId)
  308. .toBe(initialTask.id)
  309. expect(migratedStore.require<WorkspaceInteraction>(owner, 'interaction', 'legacy-interaction').conversationTaskId)
  310. .toBe(initialTask.id)
  311. expect(migratedStore.get(owner, 'binding', `${conversation.id}:${administrator.id}`)).toBeUndefined()
  312. expect(migratedStore.get(owner, 'binding', `${conversation.id}:${initialTask.id}:${administrator.id}`))
  313. .toMatchObject({ conversationTaskId: initialTask.id })
  314. expect(migratedStore.get(owner, 'context', conversation.id)).toBeUndefined()
  315. expect(migratedStore.get(owner, 'context', initialTask.id))
  316. .toMatchObject({ conversationTaskId: initialTask.id })
  317. } finally {
  318. seededStore?.close()
  319. migratedStore?.close()
  320. rmSync(legacyHome, { recursive: true, force: true })
  321. }
  322. })
  323. it('runs one Agent across group tasks concurrently while keeping messages, sessions and context isolated', async () => {
  324. const administrator = store.createAgent(owner, { name: '多任务远程管理员', profile: 'remote-profile', nodeId: 'remote-node' }),
  325. member = agent('多任务成员'),
  326. conversation = store.createGroup(owner, {
  327. name: '多任务群聊',
  328. memberIds: [administrator.id, member.id],
  329. administratorId: administrator.id,
  330. }),
  331. firstTask = defaultTask(conversation.id),
  332. secondTask = store.createTask(owner, conversation.id, { title: '显式标题' })
  333. const pending: Array<{ socket: WebSocket; params: Record<string, any> }> = []
  334. reply = (socket, params) => {
  335. pending.push({ socket, params })
  336. }
  337. const complete = (item: typeof pending[number]) => {
  338. const text = item.params.text.includes('第一项工作') ? '第一项结果' : '第二项结果'
  339. setTimeout(() => item.socket.send(JSON.stringify({
  340. method: 'event',
  341. params: { type: 'message.complete', session_id: item.params.session_id, payload: { text, status: 'complete' } },
  342. })), 5)
  343. }
  344. const firstRun = runtime.send(owner, conversation.id, { requestId: randomUUID(), taskId: firstTask.id, content: '第一项工作' }),
  345. secondRun = runtime.send(owner, conversation.id, { requestId: randomUUID(), taskId: secondTask.id, content: '第二项工作' })
  346. await vi.waitFor(()=>expect(pending).toHaveLength(2))
  347. expect(store.require<WorkspaceRun>(owner,'run',firstRun.id).status).toBe('running')
  348. expect(store.require<WorkspaceRun>(owner,'run',secondRun.id).status).toBe('running')
  349. complete(pending.find(item => item.params.text.includes('第二项工作'))!)
  350. await finished(secondRun.id)
  351. expect(store.require<WorkspaceRun>(owner,'run',firstRun.id).status).toBe('running')
  352. complete(pending.find(item => item.params.text.includes('第一项工作'))!)
  353. await finished(firstRun.id)
  354. const firstMessages = store.messages(owner, conversation.id, Number.MAX_SAFE_INTEGER, 100, false, firstTask.id),
  355. secondMessages = store.messages(owner, conversation.id, Number.MAX_SAFE_INTEGER, 100, false, secondTask.id)
  356. expect(firstMessages.map(message => message.content)).toEqual(['第一项工作', '第一项结果'])
  357. expect(secondMessages.map(message => message.content)).toEqual(['第二项工作', '第二项结果'])
  358. expect(firstMessages.every(message => message.conversationTaskId === firstTask.id)).toBe(true)
  359. expect(secondMessages.every(message => message.conversationTaskId === secondTask.id)).toBe(true)
  360. const prompts = requests.filter(request => request.method === 'prompt.submit').map(request => String(request.params.text))
  361. expect(prompts.find(prompt => prompt.includes('第一项工作'))).not.toContain('第二项工作')
  362. expect(prompts.find(prompt => prompt.includes('第二项工作'))).not.toContain('第一项工作')
  363. const bindings = store.list<any>(owner, 'binding')
  364. expect(bindings.map(binding => binding.conversationTaskId).sort()).toEqual([firstTask.id, secondTask.id].sort())
  365. expect(bindings.every(binding => binding.nodeId === 'remote-node' && binding.profile === 'remote-profile')).toBe(true)
  366. expect(new Set(bindings.map(binding => binding.storedId)).size).toBe(2)
  367. expect(store.get<any>(owner, 'context', firstTask.id)).toMatchObject({ conversationTaskId: firstTask.id, percent: 40 })
  368. expect(store.get<any>(owner, 'context', secondTask.id)).toMatchObject({ conversationTaskId: secondTask.id, percent: 40 })
  369. const firstSummary = store.require<any>(owner, 'conversation-task', firstTask.id)
  370. expect(firstSummary).toMatchObject({ title: '第一项工作', titleSource: 'automatic', messageCount: 2, unread: true, unreadCount: 1 })
  371. expect(store.require<any>(owner, 'conversation-task', secondTask.id)).toMatchObject({ title: '显式标题', titleSource: 'user', messageCount: 2 })
  372. expect(store.markTaskRead(owner, conversation.id, firstTask.id, firstSummary.lastSeq).unreadCount).toBe(0)
  373. store.deleteTask(owner, conversation.id, firstTask.id)
  374. expect(store.list<WorkspaceMessage>(owner, 'message').some(message => message.conversationTaskId === firstTask.id)).toBe(false)
  375. expect(store.list<any>(owner, 'binding').some(binding => binding.conversationTaskId === firstTask.id)).toBe(false)
  376. expect(store.get(owner, 'context', firstTask.id)).toBeUndefined()
  377. expect(store.messages(owner, conversation.id, Number.MAX_SAFE_INTEGER, 100, false, secondTask.id).map(message => message.content))
  378. .toEqual(['第二项工作', '第二项结果'])
  379. })
  380. it('admits ten active conversation tasks for one Agent and rejects the eleventh without stopping them', async () => {
  381. const administrator = agent('并发任务管理员'),
  382. member = agent('并发任务成员'),
  383. conversation = store.createGroup(owner, {
  384. name: '并发任务群聊',
  385. memberIds: [administrator.id, member.id],
  386. administratorId: administrator.id,
  387. }),
  388. tasks = [defaultTask(conversation.id), ...Array.from({ length: 10 }, (_, index) => store.createTask(owner, conversation.id, { title: `任务 ${index + 2}` }))]
  389. reply = () => {}
  390. for (const [index, task] of tasks.slice(0, 10).entries())
  391. runtime.send(owner, conversation.id, { requestId: randomUUID(), taskId: task.id, content: `执行 ${index + 1}` })
  392. expect(store.activeTaskCount(owner, conversation.id)).toBe(10)
  393. await vi.waitFor(() => expect(requests.filter(r => r.method === 'prompt.submit')).toHaveLength(10))
  394. expect(new Set(requests.filter(r => r.method === 'prompt.submit').map(r => r.params.session_id)).size).toBe(10)
  395. expect(() => runtime.send(owner, conversation.id, { requestId: randomUUID(), taskId: tasks[10]!.id, content: '第十一项' }))
  396. .toThrow('最多同时运行 10 个任务')
  397. expect(requests.filter(r => r.method === 'session.interrupt')).toHaveLength(0)
  398. await Promise.all(tasks.slice(0, 10).map(task => runtime.stopTask(owner, conversation.id, task.id)))
  399. })
  400. it('keeps same-named upstream interactions scoped to their conversation task', async () => {
  401. const administrator = agent('交互隔离管理员'),
  402. member = agent('交互隔离成员'),
  403. conversation = store.createGroup(owner, {
  404. name: '交互隔离群聊',
  405. memberIds: [administrator.id, member.id],
  406. administratorId: administrator.id,
  407. }),
  408. firstTask = defaultTask(conversation.id),
  409. secondTask = store.createTask(owner, conversation.id, {})
  410. const pending: Array<{socket:WebSocket;params:Record<string,any>}> = []
  411. reply = (socket, params) => { pending.push({socket,params});setTimeout(() => socket.send(JSON.stringify({
  412. method: 'event',
  413. params: {
  414. type: 'approval.request',
  415. session_id: params.session_id,
  416. payload: { request_id: 'same-upstream-id', message: '允许执行吗?' },
  417. },
  418. })), 5) }
  419. const firstRun=runtime.send(owner, conversation.id, { requestId: randomUUID(), taskId: firstTask.id, content: '任务甲' })
  420. // Different tasks admitted in the same millisecond need not win a lane in
  421. // insertion order. Establish the active task before testing its isolation.
  422. await vi.waitFor(() => expect(pending).toHaveLength(1))
  423. const secondRun=runtime.send(owner, conversation.id, { requestId: randomUUID(), taskId: secondTask.id, content: '任务乙' })
  424. await vi.waitFor(() => expect(store.list<WorkspaceInteraction>(owner, 'interaction').filter(interaction => !interaction.resolved)).toHaveLength(2))
  425. const first=store.list<WorkspaceInteraction>(owner,'interaction').find(i=>i.conversationTaskId===firstTask.id)!
  426. expect(store.require<any>(owner, 'conversation-task', firstTask.id).activeRunStatus).toBe('waiting')
  427. expect(store.require<WorkspaceRun>(owner,'run',secondRun.id).status).toBe('waiting')
  428. await runtime.respond(owner, first.id, 'once')
  429. expect(requests.filter(r => r.method === 'approval.respond').map(r => r.params.session_id)).toEqual([pending[0]!.params.session_id])
  430. pending[0]!.socket.send(JSON.stringify({method:'event',params:{type:'message.complete',session_id:pending[0]!.params.session_id,payload:{text:'任务甲完成',status:'complete'}}}))
  431. await finished(firstRun.id)
  432. await vi.waitFor(()=>expect(store.list<WorkspaceInteraction>(owner,'interaction')).toHaveLength(2))
  433. const second=store.list<WorkspaceInteraction>(owner,'interaction').find(i=>i.conversationTaskId===secondTask.id)!
  434. expect(second.id).not.toBe(first.id)
  435. expect(store.require<any>(owner, 'conversation-task', secondTask.id).activeRunStatus).toBe('waiting')
  436. await runtime.respond(owner,first.id,'once')
  437. expect(store.require<WorkspaceInteraction>(owner, 'interaction', first.id).resolved).toBe(true)
  438. expect(store.require<WorkspaceInteraction>(owner, 'interaction', second.id).resolved).toBe(false)
  439. await Promise.all([runtime.stopTask(owner, conversation.id, firstTask.id), runtime.stopTask(owner, conversation.id, secondTask.id)])
  440. })
  441. it('persists a visible failure when a fixed member loses its source node',async()=>{
  442. const a=agent('不可用成员'),c=direct(a.id)
  443. runtime.close()
  444. runtime=new WorkspaceRuntime(store,{requireSource: () => {},target:()=>{throw new Error('基础节点不可用')}} as unknown as WorkspaceNodes,uploads)
  445. const run=runtime.send(owner,c.id,{requestId:randomUUID(),content:'执行任务'})
  446. await vi.waitFor(()=>expect(store.require<WorkspaceRun>(owner,'run',run.id).status).toBe('failed'))
  447. expect(store.messages(owner,c.id).at(-1)).toMatchObject({role:'system',status:'failed',content:'执行失败:基础节点不可用'})
  448. expect(store.require<WorkspaceConversation>(owner,'conversation',c.id).activeRunId).toBeUndefined()
  449. })
  450. it('interprets a reply against its launch-time roster when names or mode change mid-turn', async () => {
  451. const a = agent('管理员'),
  452. b = agent('执行者')
  453. const c = store.createGroup(owner, {
  454. name: '配置更新',
  455. memberIds: [a.id, b.id],
  456. administratorId: a.id,
  457. maxReplyRounds: 3,
  458. })
  459. let count = 0
  460. reply = (socket, p) => {
  461. let text = '已完成'
  462. if (count++ === 0) {
  463. store.updateAgent(owner, b.id, { name: '新名字', instructions: '新规则' })
  464. store.updateConversation(owner, c.id, { mode: 'free', administratorId: b.id })
  465. text = '请继续 @执行者'
  466. }
  467. setTimeout(
  468. () =>
  469. socket.send(
  470. JSON.stringify({
  471. method: 'event',
  472. params: { type: 'message.complete', session_id: p.session_id, payload: { text } },
  473. }),
  474. ),
  475. 5,
  476. )
  477. }
  478. await finished(runtime.send(owner, c.id, { requestId: randomUUID(), content: '开始' }).id)
  479. expect(
  480. store
  481. .messages(owner, c.id)
  482. .filter((m) => m.role === 'assistant')
  483. .map((m) => m.agentId),
  484. ).toEqual([a.id, b.id])
  485. expect(requests.filter((r) => r.method === 'prompt.submit').at(-1)!.params.text).toContain(
  486. '新规则',
  487. )
  488. })
  489. it('rejects unscoped and foreign-session completion events', async () => {
  490. const a = agent('会话隔离'),
  491. c = direct(a.id)
  492. reply = (socket, p) => {
  493. for (const session_id of [undefined, 'another-session'])
  494. socket.send(
  495. JSON.stringify({
  496. method: 'event',
  497. params: { type: 'message.complete', session_id, payload: { text: '别人的结果' } },
  498. }),
  499. )
  500. setTimeout(
  501. () =>
  502. socket.send(
  503. JSON.stringify({
  504. method: 'event',
  505. params: {
  506. type: 'message.complete',
  507. session_id: p.session_id,
  508. payload: { text: '本轮结果' },
  509. },
  510. }),
  511. ),
  512. 15,
  513. )
  514. }
  515. const run = runtime.send(owner, c.id, { requestId: randomUUID(), content: '执行' })
  516. await finished(run.id)
  517. expect(store.messages(owner, c.id).at(-1)?.content).toBe('本轮结果')
  518. expect(store.get<{ percent: number }>(owner, 'context', c.id)?.percent).toBe(40)
  519. })
  520. it('resumes a persisted uncertain run by inspecting history, without resending the prompt', async () => {
  521. const a = agent('恢复测试'),
  522. c = direct(a.id)
  523. reply = (socket, p) => {
  524. recoveryHistory = [
  525. { role: 'user', content: p.text },
  526. { role: 'assistant', content: '已经执行完成' },
  527. ]
  528. socket.terminate()
  529. }
  530. const run = runtime.send(owner, c.id, { requestId: randomUUID(), content: '修改一次' })
  531. await vi.waitFor(() =>
  532. expect(store.require<WorkspaceRun>(owner, 'run', run.id).status).toBe('uncertain'),
  533. )
  534. runtime.close()
  535. runtime = new WorkspaceRuntime(store, nodes, uploads)
  536. await runtime.reconcile(owner, run.id)
  537. await finished(run.id)
  538. expect(requests.filter((r) => r.method === 'prompt.submit')).toHaveLength(1)
  539. expect(store.messages(owner, c.id).map((m) => m.content)).toEqual(['修改一次', '已经执行完成'])
  540. })
  541. it('routes approvals and clarifications to the owning run and ignores optional push failures', async () => {
  542. const a = agent('交互测试'),
  543. c = direct(a.id)
  544. runtime.onNotify = () => {
  545. throw new Error('push storage unavailable')
  546. }
  547. let kind = 'approval'
  548. server.on('connection', (socket) =>
  549. socket.on('message', (data) => {
  550. const f = JSON.parse(String(data))
  551. if (['approval.respond', 'clarify.respond'].includes(f.method))
  552. socket.send(
  553. JSON.stringify({
  554. method: 'event',
  555. params: {
  556. type: 'message.complete',
  557. session_id: f.params.session_id,
  558. payload: { text: '确认后完成' },
  559. },
  560. }),
  561. )
  562. }),
  563. )
  564. reply = (socket, p) =>
  565. socket.send(
  566. JSON.stringify({
  567. method: 'event',
  568. params: {
  569. type: `${kind}.request`,
  570. session_id: p.session_id,
  571. payload: { request_id: 'upstream-interaction', message: '请确认' },
  572. },
  573. }),
  574. )
  575. for (kind of ['approval', 'clarify']) {
  576. const run = runtime.send(owner, c.id, { requestId: randomUUID(), content: '继续' })
  577. await vi.waitFor(() =>
  578. expect(store.require<WorkspaceRun>(owner, 'run', run.id).status).toBe('waiting'),
  579. )
  580. const interaction = store
  581. .list<WorkspaceInteraction>(owner, 'interaction')
  582. .find((i) => !i.resolved)!
  583. await expect(runtime.respond(other, interaction.id, 'once')).rejects.toThrow('记录不存在')
  584. await runtime.respond(owner, interaction.id, kind === 'approval' ? 'once' : '补充说明')
  585. await finished(run.id)
  586. expect(
  587. store.require<WorkspaceInteraction>(owner, 'interaction', interaction.id).resolved,
  588. ).toBe(true)
  589. }
  590. expect(
  591. requests
  592. .filter((r) => r.method === 'approval.respond' || r.method === 'clarify.respond')
  593. .map((r) => r.params.request_id),
  594. ).toEqual(['upstream-interaction', 'upstream-interaction'])
  595. })
  596. it('creates one direct chat without importing a native profile session', () => {
  597. const a = agent('编辑')
  598. expect(direct(a.id).kind).toBe('direct')
  599. expect(store.list(other, 'agent')).toEqual([])
  600. expect(() => store.require(other, 'conversation', direct(a.id).id)).toThrow('记录不存在')
  601. expect(requests).toEqual([])
  602. })
  603. it('protects the current administrator and validates member ownership', () => {
  604. const a = agent('甲'),
  605. b = agent('乙'),
  606. foreign = agent('外部', other)
  607. const c = store.createGroup(owner, {
  608. name: '团队',
  609. memberIds: [a.id, b.id],
  610. administratorId: a.id,
  611. })
  612. expect(() => store.updateConversation(owner, c.id, { memberIds: [b.id] })).toThrow('当前管理员不能移除')
  613. expect(() => store.updateConversation(owner, c.id, { memberIds: [b.id], administratorId: b.id })).toThrow('当前管理员不能移除')
  614. expect(() => store.updateConversation(owner, c.id, { memberIds: [a.id, foreign.id] })).toThrow('记录不存在')
  615. expect(() => store.updateConversation(owner, c.id, { memberIds: [a.id, a.id] })).toThrow('群成员或管理员无效')
  616. expect(() =>
  617. store.createGroup(owner, {
  618. name: '越权',
  619. memberIds: [a.id, foreign.id],
  620. administratorId: a.id,
  621. }),
  622. ).toThrow()
  623. store.updateAgent(owner, b.id, { archived: true })
  624. expect(store.require<WorkspaceConversation>(owner, 'conversation', c.id).memberIds).toEqual([
  625. a.id,
  626. b.id,
  627. ])
  628. expect(() =>
  629. store.createGroup(owner, { name: '新群', memberIds: [a.id, b.id], administratorId: a.id }),
  630. ).toThrow('已归档')
  631. expect(store.updateConversation(owner, c.id, { memberIds: [a.id] }).memberIds).toEqual([a.id])
  632. expect(() => store.updateConversation(owner, c.id, { memberIds: [a.id, b.id] })).toThrow('已归档')
  633. })
  634. it('adds and removes members, cleans automatic replies, and permits removal after administrator transfer', async () => {
  635. const a = agent('管理员'), b = agent('旧成员'), added = agent('新成员')
  636. const c = store.createGroup(owner, { name: '成员维护', memberIds: [a.id, b.id], administratorId: a.id, autoReplyIds: [b.id] })
  637. await finished(runtime.send(owner, c.id, { requestId: randomUUID(), content: '保留这条历史' }).id)
  638. const before = store.require<WorkspaceConversation>(owner, 'conversation', c.id)
  639. const history = store.messages(owner, c.id)
  640. const changed = store.updateConversation(owner, c.id, { memberIds: [a.id, added.id] })
  641. expect(changed.memberIds).toEqual([a.id, added.id])
  642. expect(changed.autoReplyIds).toEqual([])
  643. expect(changed.lastMessageAt).toBe(before.lastMessageAt)
  644. expect(store.messages(owner, c.id)).toEqual(history)
  645. expect(store.events(owner, 0).at(-1)).toMatchObject({ type: 'conversation.changed', data: { memberIds: [a.id, added.id] } })
  646. store.updateConversation(owner, c.id, { administratorId: added.id })
  647. expect(store.updateConversation(owner, c.id, { memberIds: [added.id] }).memberIds).toEqual([added.id])
  648. expect(() => store.updateConversation(owner, c.id, { memberIds: [a.id] })).toThrow('当前管理员不能移除')
  649. })
  650. it('skips removed queued members and accepts a newly added member on the next request', async () => {
  651. const a = agent('管理员'), b = agent('待回复'), added = agent('新成员')
  652. const c = store.createGroup(owner, { name: '队列维护', memberIds: [a.id, b.id], administratorId: a.id, mode: 'free', autoReplyIds: [a.id, b.id] })
  653. reply = (socket, p) => {
  654. socket.send(JSON.stringify({ method: 'event', params: { type: 'message.complete', session_id: p.session_id, payload: { text: '请@待回复继续' } } }))
  655. }
  656. const queued = runtime.send(owner, c.id, { requestId: randomUUID(), content: '开始' })
  657. store.updateConversation(owner, c.id, { memberIds: [a.id, added.id] })
  658. await finished(queued.id)
  659. expect(store.messages(owner, c.id).filter(m => m.role === 'assistant').map(m => m.agentId)).toEqual([a.id])
  660. await finished(runtime.send(owner, c.id, { requestId: randomUUID(), content: '请@新成员继续' }).id)
  661. expect(store.messages(owner, c.id).filter(m => m.role === 'assistant').map(m => m.agentId)).toEqual([a.id, added.id, a.id])
  662. })
  663. it('finishes an in-flight removed member reply without scheduling it again', async () => {
  664. const a = agent('管理员'), b = agent('正在回复')
  665. const c = store.createGroup(owner, { name: '回复中移除', memberIds: [a.id, b.id], administratorId: a.id })
  666. let turns = 0
  667. reply = (socket, p) => {
  668. if (turns++ === 1) store.updateConversation(owner, c.id, { memberIds: [a.id] })
  669. socket.send(JSON.stringify({ method: 'event', params: { type: 'message.complete', session_id: p.session_id, payload: { text: turns === 1 ? '请@正在回复继续' : '已完成' } } }))
  670. }
  671. await finished(runtime.send(owner, c.id, { requestId: randomUUID(), content: '@正在回复 开始' }).id)
  672. expect(store.messages(owner, c.id).filter(m => m.role === 'assistant').map(m => m.agentId)).toEqual([a.id, b.id, a.id])
  673. expect(() => runtime.send(owner, c.id, { requestId: randomUUID(), content: '继续', mentionIds: [b.id] })).toThrow('只能 @ 群内成员')
  674. })
  675. it('dispatches a request exactly once across retries and rejects payload reuse', async () => {
  676. const a = agent('编辑'),
  677. c = direct(a.id),
  678. requestId = randomUUID(),
  679. payload = { requestId, content: '检查代码' }
  680. const run = runtime.send(owner, c.id, payload)
  681. expect(runtime.send(owner, c.id, payload).id).toBe(run.id)
  682. expect(() => runtime.send(owner, c.id, { ...payload, content: '另一件事' })).toThrow('请求编号')
  683. await finished(run.id)
  684. expect(requests.filter((r) => r.method === 'prompt.submit')).toHaveLength(1)
  685. expect(store.messages(owner, c.id).map((m) => m.role)).toEqual(['user', 'assistant'])
  686. })
  687. it('keeps template responsibilities inside their group and follows Agent identity after rename', async () => {
  688. const a = agent('现有甲'), b = agent('现有乙')
  689. const before = store.require<WorkspaceAgent>(owner, 'agent', a.id)
  690. const c = store.createGroup(owner, { name: '模板群', memberIds: [a.id, b.id], administratorId: a.id, memberRoles: {
  691. [a.id]: { name: '调研负责人', description: '汇总可信结论' },
  692. [b.id]: { name: '事实核验', description: '交叉验证来源' },
  693. } })
  694. expect(store.require<WorkspaceAgent>(owner, 'agent', a.id)).toEqual(before)
  695. store.updateAgent(owner, a.id, { name: '改名后的甲' })
  696. await finished(runtime.send(owner, c.id, { requestId: randomUUID(), content: '开始调研' }).id)
  697. const groupPrompt = requests.filter(r => r.method === 'prompt.submit').at(-1)!.params.text
  698. expect(groupPrompt).toContain('@改名后的甲:调研负责人;汇总可信结论')
  699. expect(groupPrompt).toContain('@现有乙:事实核验;交叉验证来源')
  700. await finished(runtime.send(owner, direct(a.id).id, { requestId: randomUUID(), content: '单聊' }).id)
  701. expect(requests.filter(r => r.method === 'prompt.submit').at(-1)!.params.text).not.toContain('汇总可信结论')
  702. const changed = store.updateConversation(owner, c.id, { memberIds: [a.id] })
  703. expect(changed.memberRoles).toEqual({ [a.id]: { name: '调研负责人', description: '汇总可信结论' } })
  704. expect(() => store.updateConversation(owner, c.id, { memberRoles: { [b.id]: { name: '已移除', description: '' } } })).toThrow('群成员或管理员无效')
  705. })
  706. it('isolates roles over the same profile and applies edited rules on the next turn', async () => {
  707. const a = agent('编辑'),
  708. b = agent('审查'),
  709. ca = direct(a.id),
  710. cb = direct(b.id)
  711. const first = runtime.send(owner, ca.id, { requestId: randomUUID(), content: '编辑任务' })
  712. const second = runtime.send(owner, cb.id, { requestId: randomUUID(), content: '审查任务' })
  713. await Promise.all([finished(first.id), finished(second.id)])
  714. expect(requests.filter((r) => r.method === 'session.create')).toHaveLength(2)
  715. expect(store.messages(owner, ca.id).some((m) => m.content === '审查任务')).toBe(false)
  716. store.updateAgent(owner, a.id, { instructions: '最新规则:先给证据' })
  717. await finished(runtime.send(owner, ca.id, { requestId: randomUUID(), content: '继续' }).id)
  718. expect(requests.filter((r) => r.method === 'prompt.submit').at(-1)!.params.text).toContain(
  719. '最新规则:先给证据',
  720. )
  721. expect(requests.some((r) => r.method === 'profiles.configure')).toBe(false)
  722. expect(
  723. requests
  724. .filter((r) => r.method === 'session.create')
  725. .every((r) => r.params.hidden && r.params.source === 'yaoyao_workspace'),
  726. ).toBe(true)
  727. })
  728. it('executes bounded administrator delegation and keeps group sessions separate from direct chat', async () => {
  729. const a = agent('管理员'),
  730. b = agent('开发者'),
  731. c = store.createGroup(owner, {
  732. name: '开发',
  733. memberIds: [a.id, b.id],
  734. administratorId: a.id,
  735. maxReplyRounds: 3,
  736. })
  737. let turns = 0
  738. reply = (socket, p) => {
  739. const text = turns++ === 0 ? '我已整理需求,现在请@开发者继续实现。' : '任务完成'
  740. setTimeout(
  741. () =>
  742. socket.send(
  743. JSON.stringify({
  744. method: 'event',
  745. params: { type: 'message.complete', session_id: p.session_id, payload: { text } },
  746. }),
  747. ),
  748. 5,
  749. )
  750. }
  751. await finished(runtime.send(owner, c.id, { requestId: randomUUID(), content: '实现功能' }).id)
  752. expect(
  753. store
  754. .messages(owner, c.id)
  755. .filter((m) => m.role === 'assistant')
  756. .map((m) => m.agentId),
  757. ).toEqual([a.id, b.id, a.id])
  758. expect(store.messages(owner, direct(a.id).id)).toHaveLength(0)
  759. expect(turns).toBe(3)
  760. })
  761. it('does not trigger delegation from quoted text or code blocks', () => {
  762. const a = agent('甲'),
  763. b = agent('乙')
  764. expect(mentionedAgents('> @乙\n```\n@甲\n```\n`@all`', [a, b])).toEqual([])
  765. expect(mentionedAgents('请处理 @乙。', [a, b])).toEqual([b.id])
  766. })
  767. it('keeps uncertain submissions blocked instead of executing tools twice', async () => {
  768. const a = agent('执行者'),
  769. c = direct(a.id)
  770. reply = (socket) => socket.terminate()
  771. const run = runtime.send(owner, c.id, { requestId: randomUUID(), content: '修改文件' })
  772. await vi.waitFor(() =>
  773. expect(store.require<WorkspaceRun>(owner, 'run', run.id).status).toBe('uncertain'),
  774. )
  775. const queued = runtime.send(owner, c.id, { requestId: randomUUID(), content: '后续请求' })
  776. expect(queued.status).toBe('queued')
  777. expect(requests.filter((r) => r.method === 'prompt.submit')).toHaveLength(1)
  778. await runtime.stopConversation(owner, c.id)
  779. expect(
  780. store.require<WorkspaceConversation>(owner, 'conversation', c.id).activeRunId,
  781. ).toBeUndefined()
  782. })
  783. it('publishes durable ordered events only after commit and rolls back failed transactions', () => {
  784. const a = agent('甲'),
  785. c = direct(a.id),
  786. cursor = store.cursor(owner)
  787. expect(() =>
  788. store.atomic(() => {
  789. store.event(owner, 'test', {})
  790. throw new Error('rollback')
  791. }),
  792. ).toThrow('rollback')
  793. expect(store.cursor(owner)).toBe(cursor)
  794. store.updateAgent(owner, a.id, { name: '乙' })
  795. expect(store.events(owner, cursor).map((e) => e.type)).toEqual([
  796. 'agent.changed',
  797. 'conversation.changed',
  798. ])
  799. expect(store.events(other, 0)).toEqual([])
  800. expect(store.require<WorkspaceConversation>(owner, 'conversation', c.id).name).toBe('乙')
  801. })
  802. })
  803. it('pins a direct chat without injecting or clearing optional profile fields', () => {
  804. const avatar = encodeAgentAvatar({...defaultAgentIdentity('reviewer'),shape:'triangle',color:'#00b9ac',expression:'curious'})
  805. const agent = store.createAgent(owner, { name: '审查员', profile: 'default', avatar })
  806. const chat = store.list<WorkspaceConversation>(owner, 'conversation')[0]!
  807. expect(store.updateConversation(owner, chat.id, { pinned: true }).pinned).toBe(true)
  808. expect(store.updateConversation(owner, chat.id, { pinned: false }).pinned).toBe(false)
  809. expect(store.require<WorkspaceConversation>(owner, 'conversation', chat.id).avatar).toBe(avatar)
  810. expect(store.updateAgent(owner, agent.id, { instructions: '请检查边界' }).avatar).toBe(avatar)
  811. expect(decodeAgentAvatar(store.updateAgent(owner, agent.id, { avatar: '' }).avatar)).toMatchObject({shape:'circle',color:'#00c875'})
  812. })
  813. it('accepts the existing cross-client mascot and team avatar formats', () => {
  814. const a = store.createAgent(owner, { name: '设计', profile: 'default', avatar: 'yaoyao-mascot:v1:square:377fe6:friendly' })
  815. const b = store.createAgent(owner, { name: '开发', profile: 'default' })
  816. const group = store.createGroup(owner, { name: '产品团队', memberIds: [a.id, b.id], administratorId: a.id, avatar: 'builtin:team-animal:fox' })
  817. expect(group.avatar).toBe('builtin:team-animal:fox')
  818. expect(() => store.updateAgent(owner, a.id, { avatar: 'javascript:alert(1)' })).toThrow()
  819. })
  820. it('assigns a random v2 avatar only when a new Agent omits its avatar', () => {
  821. const random = vi.spyOn(Math, 'random').mockReturnValue(0)
  822. const created = store.createAgent(owner, { name: '随机头像', profile: 'default' })
  823. expect(decodeAgentAvatar(created.avatar)).toMatchObject({ shape: 'circle', color: '#000000', expression: 'idle' })
  824. expect(created.avatar).not.toBe(encodeAgentAvatar(defaultAgentIdentity(created.id, created.name)))
  825. random.mockRestore()
  826. })
  827. it('keeps the last message time independent of pinning and metadata edits', () => {
  828. const agent=store.createAgent(owner,{name:'时间验收',profile:'default'})
  829. const c=store.list<WorkspaceConversation>(owner,'conversation')[0]!
  830. const message: WorkspaceMessage={id:randomUUID(),conversationId:c.id,seq:0,role:'user',content:'历史消息',reasoning:'',status:'complete',attachments:[],tools:[],createdAt:Date.now()-600_000}
  831. store.saveMessage(owner,message)
  832. const pinned=store.updateConversation(owner,c.id,{pinned:true})
  833. expect(store.conversationSummary(owner,pinned).lastMessageAt).toBe(message.createdAt)
  834. store.updateAgent(owner,agent.id,{name:'改名之后'})
  835. expect(store.conversationSummary(owner,store.require(owner,'conversation',c.id)).lastMessageAt).toBe(message.createdAt)
  836. // Existing records without the summary field still use their transcript time.
  837. const previous={...pinned}; delete previous.lastMessageAt
  838. expect(store.conversationSummary(owner,previous).lastMessageAt).toBe(message.createdAt)
  839. })
  840. it('publishes only the executing member and clears avatar activity when stopped', async () => {
  841. const a=store.createAgent(owner,{name:'管理员头像',profile:'default'})
  842. const b=store.createAgent(owner,{name:'执行者头像',profile:'default'})
  843. const c=store.createGroup(owner,{name:'头像状态',memberIds:[a.id,b.id],administratorId:a.id})
  844. reply=(socket,p)=>socket.send(JSON.stringify({method:'event',params:{type:'approval.request',session_id:p.session_id,payload:{request_id:'approval-avatar',message:'需要确认'}}}))
  845. const run=runtime.send(owner,c.id,{requestId:randomUUID(),content:'处理任务',mentionIds:[b.id]})
  846. await vi.waitFor(()=>expect(store.require<WorkspaceRun>(owner,'run',run.id).status).toBe('waiting'))
  847. expect(store.require<WorkspaceConversation>(owner,'conversation',c.id)).toMatchObject({activeAgentId:a.id,activeRunStatus:'waiting'})
  848. await runtime.stop(owner,run.id)
  849. const stopped=store.require<WorkspaceConversation>(owner,'conversation',c.id)
  850. expect(stopped.activeAgentId).toBeUndefined()
  851. expect(stopped.activeRunStatus).toBeUndefined()
  852. })
  853. it('stores the expanded avatar shapes for cross-client role settings', () => {
  854. const agent=store.createAgent(owner,{name:'扩展头像验收',profile:'default'})
  855. for(const shape of ['ellipse','capsule','hexagon','cloud','droplet'] as const) {
  856. const avatar=encodeAgentAvatar({...defaultAgentIdentity('bot'),shape,color:'#f52ba5',expression:'curious'})
  857. expect(store.updateAgent(owner,agent.id,{avatar}).avatar).toBe(avatar)
  858. }
  859. })
  860. it('automatically reconciles lost completion without submitting the prompt again', async () => {
  861. const a=agent('自动恢复'),c=direct(a.id)
  862. reply=(socket,p)=>{recoveryHistory=[{role:'user',content:p.text},{role:'assistant',content:'已完成一次'}];socket.terminate()}
  863. const run=runtime.send(owner,c.id,{requestId:randomUUID(),content:'执行一次'})
  864. await vi.waitFor(()=>expect(store.require<WorkspaceRun>(owner,'run',run.id).status).toBe('complete'),{timeout:5000})
  865. expect(requests.filter(r=>r.method==='prompt.submit')).toHaveLength(1)
  866. expect(store.messages(owner,c.id).at(-1)).toMatchObject({content:'已完成一次',status:'complete'})
  867. })
  868. it('reports a rejected prompt as failed instead of leaving it uncertain', async () => {
  869. rejectPrompt='本轮请求被明确拒绝'
  870. const a=agent('拒绝测试'),c=direct(a.id)
  871. const run=runtime.send(owner,c.id,{requestId:randomUUID(),content:'执行'})
  872. await vi.waitFor(()=>expect(store.require<WorkspaceRun>(owner,'run',run.id).status).toBe('failed'))
  873. expect(store.require<WorkspaceConversation>(owner,'conversation',c.id).activeRunId).toBeUndefined()
  874. expect(store.messages(owner,c.id).some(m=>m.status==='uncertain')).toBe(false)
  875. })
  876. it('keeps an unconfirmed turn separate from a later reply and retries history without resubmitting', async () => {
  877. const a = agent('恢复边界'), c = direct(a.id)
  878. let prompt = ''
  879. reply = (socket, p) => {
  880. prompt = p.text
  881. recoveryHistory = [{ role: 'user', content: prompt }, { role: 'user', content: '另一个请求' }, { role: 'assistant', content: '另一轮回复' }]
  882. socket.terminate()
  883. }
  884. const run = runtime.send(owner, c.id, { requestId: randomUUID(), content: '只执行一次' })
  885. await vi.waitFor(() => expect(requests.filter(r => r.method === 'session.resume').length).toBeGreaterThanOrEqual(1), { timeout: 3000 })
  886. expect(store.require<WorkspaceRun>(owner, 'run', run.id).status).toBe('uncertain')
  887. expect(store.messages(owner, c.id).at(-1)?.content).not.toBe('另一轮回复')
  888. recoveryHistory = [{ role: 'user', content: prompt }, { role: 'assistant', content: '本轮结果' }]
  889. await vi.waitFor(() => expect(store.require<WorkspaceRun>(owner, 'run', run.id).status).toBe('complete'), { timeout: 4000 })
  890. expect(requests.filter(r => r.method === 'prompt.submit')).toHaveLength(1)
  891. expect(store.messages(owner, c.id).at(-1)).toMatchObject({ content: '本轮结果', status: 'complete' })
  892. })
  893. it('uses one generated avatar for the agent and its direct conversation',()=>{
  894. const a=agent('默认头像'),c=direct(a.id)
  895. expect(decodeAgentAvatar(a.avatar)).toMatchObject({version:2,avatarMode:'mascot'})
  896. expect(store.agentSummary(a).avatar).toBe(store.conversationSummary(owner,c).avatar)
  897. const changed=store.updateAgent(owner,a.id,{name:'换个名称'})
  898. expect(store.agentSummary(changed).avatar).toBe(store.agentSummary(a).avatar)
  899. })
  900. it('recognizes mentions inside Chinese sentences and ignores quoted code and emails',()=>{
  901. const a=agent('瑶儿'),b=agent('竹儿'),c=agent('瑶儿助手'),d=agent('Ann')
  902. const roster=[a,b,c,d]
  903. expect(mentionedAgents('先整理,再请@瑶儿帮忙,最后由(@竹儿)复核。',roster)).toEqual([a.id,b.id])
  904. expect(mentionedAgents('请**@瑶儿助手**继续',roster)).toEqual([c.id])
  905. expect(mentionedAgents('mail@Ann.com https://site/@竹儿 `@瑶儿` <quoted_message>@瑶儿</quoted_message>',roster)).toEqual([])
  906. expect(mentionedAgents('@Anna',roster)).toEqual([])
  907. })
  908. function completeReply(socket: WebSocket, p: Record<string, any>, text: string, status = 'complete') {
  909. socket.send(JSON.stringify({ method: 'event', params: { type: 'message.complete', session_id: p.session_id, payload: { text, status, ...(status === 'failed' ? { error: text } : {}) } } }))
  910. }
  911. const speaker = (p: Record<string, any>) => /^你是 (.*?)。/.exec(p.text)?.[1]
  912. describe('automatic relay termination', () => {
  913. const receipt = '收到 @审核 终审维持通过。\n\n交付状态(不变):入草稿箱 Media ID `draft-123`,发布目录 `/work/final/`。\n等民哥群发指令。'
  914. const review = '@竹儿 维持通过,等民哥群发指令。无新事实、无新派工,本轮不重复核验。'
  915. const promptCount = () => requests.filter(r => r.method === 'prompt.submit').length
  916. async function idle(runId: string, conversationId: string) {
  917. await finished(runId)
  918. const count = promptCount()
  919. await new Promise(resolve => setTimeout(resolve, 80))
  920. expect(promptCount()).toBe(count)
  921. expect(store.list<Work>(owner, 'turn').filter(w => w.runId === runId && (!w.planned || !['complete', 'failed', 'interrupted'].includes(w.status)))).toEqual([])
  922. const summary = store.conversationSummary(owner, store.require(owner, 'conversation', conversationId))
  923. expect(summary.activeRunId).toBeUndefined()
  924. expect(summary.queuedMessageCount ?? 0).toBe(0)
  925. }
  926. it('finishes the observed host receipt cycle in exactly three calls and accepts a new user message', async () => {
  927. const a = agent('竹儿'), b = agent('审核')
  928. const g = store.createGroup(owner, { name: '收尾验收', memberIds: [a.id, b.id], administratorId: a.id, maxReplyRounds: -1 })
  929. let admin = 0
  930. reply = (socket, p) => completeReply(socket, p, speaker(p) === a.name ? admin++ === 0 ? '@审核 请审核文案' : receipt : review)
  931. const root = runtime.send(owner, g.id, { requestId: randomUUID(), content: '请完成文案' })
  932. await idle(root.id, g.id)
  933. expect(promptCount()).toBe(3)
  934. expect(store.messages(owner, g.id).map(m => m.content)).toEqual(['请完成文案', '@审核 请审核文案', review, receipt])
  935. expect(store.list<Work>(owner, 'turn').find(w => w.reviewOf)?.relay?.suppressed[b.id]).toBe('acknowledgement')
  936. const next = runtime.send(owner, g.id, { requestId: randomUUID(), content: '好的。' })
  937. await idle(next.id, g.id)
  938. expect(promptCount()).toBe(4)
  939. })
  940. it.each(['感谢 @审核,等待用户指令。', '收到,等待用户指令。'])('does not turn a free-mode receipt into an automatic broadcast: %s', content => {
  941. const a = agent('竹儿'), b = agent('审核')
  942. const g = store.createGroup(owner, { name: '自动收尾', memberIds: [a.id, b.id], administratorId: a.id, mode: 'free', autoReplyIds: [b.id], maxReplyRounds: -1 })
  943. reply = (socket, p) => completeReply(socket, p, content)
  944. return (async () => {
  945. const root = runtime.send(owner, g.id, { requestId: randomUUID(), content: '@竹儿 请处理' })
  946. await idle(root.id, g.id)
  947. expect(promptCount()).toBe(1)
  948. const next = runtime.send(owner, g.id, { requestId: randomUUID(), content: '感谢 @审核' })
  949. await idle(next.id, g.id)
  950. expect(speaker(requests.filter(r => r.method === 'prompt.submit').at(-1)!.params)).toBe(b.name)
  951. })()
  952. })
  953. it.each([
  954. ['host', 2, 5], ['host', 3, 7], ['free', 2, 4], ['free', 3, 5],
  955. ] as const)('bounds unchanged %s cooperation with %i members at %i calls', async (mode, size, expected) => {
  956. const members = [agent('甲'), agent('乙'), ...(size === 3 ? [agent('丙')] : [])]
  957. const g = store.createGroup(owner, { name: '重复往返', memberIds: members.map(a => a.id), administratorId: members[0]!.id, mode, maxReplyRounds: -1 })
  958. let count = 0
  959. reply = (socket, p) => {
  960. const index = members.findIndex(a => a.name === speaker(p)), whitespace = count++ % 2 ? ' ' : ' '
  961. const text = mode === 'host' ? index === 0 ? members.slice(1).map(a => `@${a.name}${whitespace}再检查一次`).join(',') : '检查结果相同'
  962. : `@${members[(index + 1) % members.length]!.name}${whitespace}再检查一次`
  963. completeReply(socket, p, count > 20 ? '完成' : text)
  964. completeReply(socket, p, count > 20 ? '完成' : text) // Duplicate completion must not double-plan.
  965. }
  966. const root = runtime.send(owner, g.id, { requestId: randomUUID(), content: '@甲 开始' })
  967. await idle(root.id, g.id)
  968. expect(count).toBe(expected)
  969. expect(store.messages(owner, g.id).filter(m => m.content === REPEATED_RELAY_NOTICE)).toHaveLength(1)
  970. expect(store.list<Work>(owner, 'turn').some(w => Object.values(w.relay?.suppressed ?? {}).includes('repeated'))).toBe(true)
  971. })
  972. it.each(['result', 'tool', 'attachment', 'interaction'] as const)('allows repeated instructions with new %s evidence beyond thirteen calls', async kind => {
  973. const a = agent('负责人'), b = agent('审核')
  974. const g = store.createGroup(owner, { name: '持续推进', memberIds: [a.id, b.id], administratorId: a.id, maxReplyRounds: -1 })
  975. let admin = 0, worker = 0
  976. reply = (socket, p) => {
  977. if (speaker(p) === a.name) completeReply(socket, p, admin++ < 7 ? '感谢 @审核,请重新检查第二段' : '完成')
  978. else { worker++; completeReply(socket, p, kind === 'result' ? `第 ${worker} 版结果` : '本次检查结果') }
  979. }
  980. runtime.onMessage = async (_owner, message) => {
  981. if (message.agentId !== b.id) return
  982. if (kind === 'tool') message.tools = [{ id: randomUUID(), name: 'verify', status: 'tool.complete', result: { revision: worker } }]
  983. if (kind === 'attachment') message.attachments = [{ id: randomUUID(), name: 'revision.txt', mimeType: 'text/plain', size: 10, createdAt: Date.now() }]
  984. if (kind === 'interaction') {
  985. const id = randomUUID()
  986. store.put(owner, 'interaction', id, { id, runId: message.runId, conversationId: g.id, conversationTaskId: message.conversationTaskId, agentId: b.id, kind: 'clarification', message: '继续重试?', answer: '继续', responseState: 'sent', resolved: true })
  987. store.put(owner, 'interaction-binding', id, { taskId: message.taskId })
  988. }
  989. store.saveMessage(owner, message)
  990. }
  991. const root = runtime.send(owner, g.id, { requestId: randomUUID(), content: '反复改进' })
  992. await idle(root.id, g.id)
  993. expect(promptCount()).toBe(15)
  994. expect(store.messages(owner, g.id).some(m => m.content === REPEATED_RELAY_NOTICE)).toBe(false)
  995. })
  996. it('ends only the repeating free-mode branch while an independent member finishes', async () => {
  997. const a = agent('甲'), b = agent('乙'), c = agent('独立成员')
  998. const g = store.createGroup(owner, { name: '分支隔离', memberIds: [a.id, b.id, c.id], administratorId: a.id, mode: 'free', maxReplyRounds: -1 })
  999. let pending: { socket: WebSocket; p: Record<string, any> } | undefined, loops = 0
  1000. reply = (socket, p) => {
  1001. if (speaker(p) === c.name) { pending = { socket, p }; return }
  1002. completeReply(socket, p, ++loops > 15 ? '完成' : speaker(p) === a.name ? '@乙 再检查' : '@甲 再检查')
  1003. }
  1004. const root = runtime.send(owner, g.id, { requestId: randomUUID(), content: '@甲 @独立成员 请分别处理' })
  1005. await vi.waitFor(() => expect(store.messages(owner, g.id).some(m => m.content === REPEATED_RELAY_NOTICE)).toBe(true))
  1006. expect(store.require<WorkspaceRun>(owner, 'run', root.id).status).toBe('running')
  1007. expect(store.list<Work>(owner, 'turn').filter(w => w.cancelRequested)).toEqual([])
  1008. expect(loops).toBe(4)
  1009. completeReply(pending!.socket, pending!.p, '完成')
  1010. await idle(root.id, g.id)
  1011. expect(store.messages(owner, g.id).find(m => m.agentId === c.id)).toMatchObject({ content: '完成', status: 'complete' })
  1012. })
  1013. it('checks each target independently when a new automatic member joins the same repeated reply', async () => {
  1014. const a = agent('甲'), b = agent('乙'), c = agent('丙')
  1015. const g = store.createGroup(owner, { name: '目标隔离', memberIds: [a.id, b.id, c.id], administratorId: a.id, mode: 'free', autoReplyIds: [a.id], maxReplyRounds: -1 })
  1016. let calls = 0, admin = 0
  1017. reply = (socket, p) => { calls++; completeReply(socket, p, calls > 15 ? '完成' : speaker(p) === a.name ? '@乙 再检查' : speaker(p) === b.name ? '继续检查' : '完成') }
  1018. runtime.onMessage = async (_owner, message) => {
  1019. if (message.agentId === b.id && ++admin === 2) store.updateConversation(owner, g.id, { autoReplyIds: [a.id, c.id] })
  1020. }
  1021. const root = runtime.send(owner, g.id, { requestId: randomUUID(), content: '@甲 开始' })
  1022. await idle(root.id, g.id)
  1023. expect(calls).toBe(5)
  1024. const blocked = store.list<Work>(owner, 'turn').find(w => w.relay?.suppressed[a.id] === 'repeated')!
  1025. expect(blocked.relay?.suppressed[c.id]).toBeUndefined()
  1026. expect(store.list<Work>(owner, 'turn').find(w => w.batchId === blocked.id && w.agentId === c.id)?.status).toBe('complete')
  1027. })
  1028. it('starts fresh for identical new requests in the same task and a different task', async () => {
  1029. const a = agent('甲'), b = agent('乙')
  1030. const g = store.createGroup(owner, { name: '任务隔离', memberIds: [a.id, b.id], administratorId: a.id, mode: 'free', maxReplyRounds: -1 })
  1031. let calls = 0
  1032. reply = (socket, p) => { calls++; completeReply(socket, p, calls > 20 ? '完成' : speaker(p) === a.name ? '@乙 再检查' : '@甲 再检查') }
  1033. const originalTask = defaultTask(g.id), secondTask = store.createTask(owner, g.id, { title: '另一个任务' })
  1034. for (const [index, task] of [originalTask, originalTask, secondTask].entries()) {
  1035. const root = runtime.send(owner, g.id, { requestId: randomUUID(), taskId: task.id, content: '@甲 开始' })
  1036. await idle(root.id, g.id)
  1037. expect(calls).toBe((index + 1) * 4)
  1038. expect(store.messages(owner, g.id, Number.MAX_SAFE_INTEGER, 100, false, task.id).filter(m => m.runId === root.id && m.content === REPEATED_RELAY_NOTICE)).toHaveLength(1)
  1039. }
  1040. })
  1041. it.each([false, true])('recovers repeat suppression across restart before planning (legacy=%s)', async legacy => {
  1042. const a = agent('负责人'), b = agent('成员')
  1043. const g = store.createGroup(owner, { name: '循环恢复', memberIds: [a.id, b.id], administratorId: a.id, maxReplyRounds: -1 })
  1044. let calls = 0
  1045. reply = (socket, p) => { calls++; completeReply(socket, p, calls > 15 ? '完成' : speaker(p) === a.name ? '@成员 再检查' : '结果相同') }
  1046. runtime.onMessage = async () => { if (calls === 5) runtime.close() }
  1047. const root = runtime.send(owner, g.id, { requestId: randomUUID(), content: '开始' })
  1048. await vi.waitFor(() => expect(store.list<Work>(owner, 'turn').filter(w => w.status === 'complete')).toHaveLength(5))
  1049. if (legacy) for (const work of store.list<Work>(owner, 'turn')) { delete work.relay; store.put(owner, 'turn', work.id, work) }
  1050. runtime = new WorkspaceRuntime(store, nodes, uploads); runtime.start()
  1051. await idle(root.id, g.id)
  1052. expect(calls).toBe(5)
  1053. expect(store.messages(owner, g.id).filter(m => m.content === REPEATED_RELAY_NOTICE)).toHaveLength(1)
  1054. runtime.close(); runtime = new WorkspaceRuntime(store, nodes, uploads); runtime.start()
  1055. await idle(root.id, g.id)
  1056. expect(calls).toBe(5)
  1057. expect(store.messages(owner, g.id).filter(m => m.content === REPEATED_RELAY_NOTICE)).toHaveLength(1)
  1058. })
  1059. })
  1060. it('starts with the administrator, executes a batch concurrently, and reviews failures once without spending a round', async () => {
  1061. const a = agent('管理员'), b = agent('成员乙'), c = agent('成员丙')
  1062. const group = store.createGroup(owner, { name: '并行验收', memberIds: [a.id,b.id,c.id], administratorId: a.id, maxReplyRounds: 2 })
  1063. const pending = new Map<string, { socket: WebSocket; p: Record<string, any> }>()
  1064. let admin = 0, review = ''
  1065. reply = (socket,p) => {
  1066. if (speaker(p) === a.name) { if (admin++ === 0) completeReply(socket,p,'请@成员乙检查接口,@成员丙检查数据'); else { review=p.text; completeReply(socket,p,'汇总完成') } }
  1067. else pending.set(speaker(p)!, {socket,p})
  1068. }
  1069. const root = runtime.send(owner,group.id,{requestId:randomUUID(),content:'@成员乙 请处理'})
  1070. await vi.waitFor(()=>expect(pending.size).toBe(2))
  1071. expect(admin).toBe(1)
  1072. expect(store.require<WorkspaceConversation>(owner,'conversation',group.id).activeAgentStates).toEqual({[b.id]:'running',[c.id]:'running'})
  1073. completeReply(pending.get(c.name)!.socket,pending.get(c.name)!.p,'数据检查失败','failed')
  1074. await vi.waitFor(()=>expect(store.messages(owner,group.id).some(m=>m.status==='failed')).toBe(true))
  1075. expect(admin).toBe(1)
  1076. completeReply(pending.get(b.name)!.socket,pending.get(b.name)!.p,'接口正常')
  1077. await finished(root.id)
  1078. expect(admin).toBe(2)
  1079. expect(review).toContain('数据检查失败')
  1080. expect(review).toContain('接口正常')
  1081. expect(store.require<WorkspaceRun>(owner,'run',root.id).round).toBe(1)
  1082. })
  1083. it('allows successive dependent delegations and does not charge administrator reviews against the limit', async () => {
  1084. const a=agent('负责人'),b=agent('先做'),c=agent('后做')
  1085. const g=store.createGroup(owner,{name:'串行依赖',memberIds:[a.id,b.id,c.id],administratorId:a.id,maxReplyRounds:3})
  1086. const order:string[]=[];let admin=0
  1087. reply=(socket,p)=>{const name=speaker(p)!;order.push(name);completeReply(socket,p,name===a.name ? ['@先做 第一步','@后做 第二步','完成'][admin++]! : '结果已提交')}
  1088. await finished(runtime.send(owner,g.id,{requestId:randomUUID(),content:'执行'}).id)
  1089. expect(order).toEqual([a.name,b.name,a.name,c.name,a.name])
  1090. })
  1091. it('continues free discussion automatically and hides irrelevant automatic replies', async () => {
  1092. const a=agent('公开管理员'),b=agent('自动成员')
  1093. const g=store.createGroup(owner,{name:'自由讨论',memberIds:[a.id,b.id],administratorId:a.id,mode:'free',autoReplyIds:[b.id],maxReplyRounds:3})
  1094. reply=(socket,p)=>completeReply(socket,p,speaker(p)===a.name?'我来回答':'[[YAOYAO_NO_REPLY_V1]]')
  1095. const root=runtime.send(owner,g.id,{requestId:randomUUID(),content:'一个问题'})
  1096. await finished(root.id)
  1097. expect(requests.filter(r=>r.method==='prompt.submit'&&speaker(r.params)===b.name)).toHaveLength(2)
  1098. expect(store.messages(owner,g.id).map(m=>m.content)).toEqual(['一个问题','我来回答'])
  1099. expect(store.conversationSummary(owner,store.require(owner,'conversation',g.id))).toMatchObject({unread:true, unreadCount:1})
  1100. expect(store.hiddenMessageIds(owner,g.id)).toHaveLength(2)
  1101. })
  1102. it('requires a public administrator reply when the model tries to remain silent', async () => {
  1103. const a=agent('必须答复'),b=agent('旁观者'),g=store.createGroup(owner,{name:'公开答复',memberIds:[a.id,b.id],administratorId:a.id})
  1104. reply=(socket,p)=>completeReply(socket,p,'[[YAOYAO_NO_REPLY_V1]]')
  1105. await finished(runtime.send(owner,g.id,{requestId:randomUUID(),content:'帮助我'}).id)
  1106. const answer=store.messages(owner,g.id).at(-1)!
  1107. expect(answer.content).toContain('请补充具体目标')
  1108. expect(answer.content).not.toContain('YAOYAO_')
  1109. })
  1110. it('queues later user requests durably without leaking them into the preceding collaboration', async () => {
  1111. const a=agent('排队管理员'),b=agent('排队执行者'),g=store.createGroup(owner,{name:'消息排队',memberIds:[a.id,b.id],administratorId:a.id})
  1112. let first: {socket:WebSocket;p:Record<string,any>}|undefined
  1113. let admin=0;const prompts:string[]=[]
  1114. reply=(socket,p)=>{prompts.push(p.text);if(speaker(p)===a.name&&admin++===0)first={socket,p};else completeReply(socket,p,'已完成')}
  1115. const one=runtime.send(owner,g.id,{requestId:randomUUID(),content:'第一条任务'})
  1116. await vi.waitFor(()=>expect(first).toBeDefined())
  1117. const two=runtime.send(owner,g.id,{requestId:randomUUID(),content:'之后才处理的秘密标记'})
  1118. expect(two.status).toBe('queued')
  1119. expect(store.require<WorkspaceConversation>(owner,'conversation',g.id).activeRunId).toBe(one.id)
  1120. completeReply(first!.socket,first!.p,'请@排队执行者继续')
  1121. await finished(one.id);await finished(two.id)
  1122. expect(prompts).toHaveLength(4)
  1123. expect(prompts.slice(0,3).every(p=>!p.includes('之后才处理的秘密标记'))).toBe(true)
  1124. expect(prompts[3]).toContain('之后才处理的秘密标记')
  1125. })
  1126. it('stops one member while keeping its sibling running and returns the interrupted result for review', async () => {
  1127. const a=agent('停止管理员'),b=agent('停止乙'),c=agent('继续丙'),g=store.createGroup(owner,{name:'独立停止',memberIds:[a.id,b.id,c.id],administratorId:a.id})
  1128. const pending=new Map<string,{socket:WebSocket;p:Record<string,any>}>();let admin=0,review=''
  1129. 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})}
  1130. const root=runtime.send(owner,g.id,{requestId:randomUUID(),content:'开始'})
  1131. await vi.waitFor(()=>expect(pending.size).toBe(2))
  1132. await runtime.stopAgent(owner,g.id,b.id)
  1133. expect(admin).toBe(1)
  1134. expect(store.require<WorkspaceConversation>(owner,'conversation',g.id).activeAgentStates?.[c.id]).toBe('running')
  1135. completeReply(pending.get(c.name)!.socket,pending.get(c.name)!.p,'丙完成')
  1136. await finished(root.id)
  1137. expect(review).toContain('interrupted')
  1138. expect(review).toContain('丙完成')
  1139. })
  1140. it('recovers a partially completed parallel batch after restart without resubmitting members or duplicating review', async () => {
  1141. const a=agent('恢复管理员'),b=agent('恢复乙'),c=agent('恢复丙'),g=store.createGroup(owner,{name:'批次恢复',memberIds:[a.id,b.id,c.id],administratorId:a.id})
  1142. let admin=0;const pending=new Map<string,{socket:WebSocket;p:Record<string,any>}>()
  1143. reply=(socket,p)=>{if(speaker(p)===a.name)completeReply(socket,p,admin++===0?'@恢复乙 @恢复丙':'复核完成');else pending.set(speaker(p)!,{socket,p})}
  1144. const root=runtime.send(owner,g.id,{requestId:randomUUID(),content:'并行执行'})
  1145. await vi.waitFor(()=>expect(pending.size).toBe(2))
  1146. completeReply(pending.get(b.name)!.socket,pending.get(b.name)!.p,'乙已完成')
  1147. const last=pending.get(c.name)!
  1148. recoveryByStored.set(storedByRuntime.get(last.p.session_id)!,[{role:'user',content:last.p.text},{role:'assistant',content:'丙已完成'}])
  1149. last.socket.terminate()
  1150. await vi.waitFor(()=>expect(store.require<WorkspaceRun>(owner,'run',root.id).status).toBe('uncertain'))
  1151. runtime.close();runtime=new WorkspaceRuntime(store,nodes,uploads);runtime.start()
  1152. await finished(root.id)
  1153. expect(admin).toBe(2)
  1154. expect(requests.filter(r=>r.method==='prompt.submit')).toHaveLength(4)
  1155. expect(store.list<any>(owner,'turn').filter(t=>t.reviewOf)).toHaveLength(1)
  1156. })
  1157. it('persists the next delegation when restarted between reply completion and cascade planning', async () => {
  1158. const a=agent('记录管理员'),b=agent('记录成员'),g=store.createGroup(owner,{name:'计划恢复',memberIds:[a.id,b.id],administratorId:a.id})
  1159. let admin=0
  1160. reply=(socket,p)=>completeReply(socket,p,speaker(p)===a.name&&admin++===0?'@记录成员 执行':'完成')
  1161. runtime.onMessage=async()=>{runtime.close()}
  1162. const root=runtime.send(owner,g.id,{requestId:randomUUID(),content:'执行一次'})
  1163. await vi.waitFor(()=>expect(store.list<any>(owner,'turn')[0]?.status).toBe('complete'))
  1164. runtime=new WorkspaceRuntime(store,nodes,uploads);runtime.start()
  1165. await finished(root.id)
  1166. expect(requests.filter(r=>r.method==='prompt.submit')).toHaveLength(3)
  1167. })
  1168. it('bounds long context while preserving the task beginning and ending', async () => {
  1169. const a=agent('长上下文'),b=agent('辅助'),g=store.createGroup(owner,{name:'上下文边界',memberIds:[a.id,b.id],administratorId:a.id})
  1170. const text='任务开始标记'+ '文'.repeat(60_000)+'任务结束标记'
  1171. await finished(runtime.send(owner,g.id,{requestId:randomUUID(),content:text}).id)
  1172. const prompt=requests.find(r=>r.method==='prompt.submit')!.params.text
  1173. expect(prompt).toContain('任务开始标记');expect(prompt).toContain('任务结束标记')
  1174. expect(prompt).toContain('保留首尾片段');expect(prompt.length).toBeLessThan(32_000)
  1175. })
  1176. it('serializes a session and stops only that task while the same Agent keeps replying elsewhere', async () => {
  1177. const a=agent('同一机器人'), b=agent('旁观成员')
  1178. const c=store.createGroup(owner,{name:'会话隔离',memberIds:[a.id,b.id],administratorId:a.id})
  1179. const first=defaultTask(c.id), second=store.createTask(owner,c.id,{})
  1180. const pending:Array<{socket:WebSocket;p:Record<string,any>}>=[]
  1181. reply=(socket,p)=>pending.push({socket,p})
  1182. const one=runtime.send(owner,c.id,{requestId:randomUUID(),taskId:first.id,content:'第一话题开始'})
  1183. await vi.waitFor(()=>expect(pending).toHaveLength(1))
  1184. const queued=runtime.send(owner,c.id,{requestId:randomUUID(),taskId:first.id,content:'第一话题追问'})
  1185. const other=runtime.send(owner,c.id,{requestId:randomUUID(),taskId:second.id,content:'第二话题独立执行'})
  1186. await vi.waitFor(()=>expect(pending).toHaveLength(2))
  1187. expect(store.require<WorkspaceRun>(owner,'run',queued.id).status).toBe('queued')
  1188. completeReply(pending[0]!.socket,pending[0]!.p,'第一话题首轮结果')
  1189. await finished(one.id)
  1190. await vi.waitFor(()=>expect(pending).toHaveLength(3))
  1191. const firstBinding=store.get<any>(owner,'binding',`${c.id}:${first.id}:${a.id}`)!
  1192. expect(requests.filter(r=>r.method==='session.resume').map(r=>r.params.session_id)).toEqual([firstBinding.storedId])
  1193. expect(pending[2]!.p.text).not.toContain('第二话题独立执行')
  1194. await runtime.stopTask(owner,c.id,first.id)
  1195. expect(requests.filter(r=>r.method==='session.interrupt').map(r=>r.params.session_id)).toEqual([pending[2]!.p.session_id])
  1196. expect(store.require<WorkspaceRun>(owner,'run',other.id).status).toBe('running')
  1197. expect(store.require<any>(owner,'conversation-task',second.id).activeRunStatus).toBe('running')
  1198. completeReply(pending[1]!.socket,pending[1]!.p,'第二话题独立完成')
  1199. await finished(other.id)
  1200. expect(store.messages(owner,c.id,Number.MAX_SAFE_INTEGER,100,false,second.id).map(m=>m.content)).toEqual(['第二话题独立执行','第二话题独立完成'])
  1201. expect(store.require<WorkspaceRun>(owner,'run',queued.id).status).toBe('interrupted')
  1202. })
  1203. it('recovers simultaneous sessions for one Agent after restart without replaying either prompt', async () => {
  1204. const a=agent('恢复机器人'),b=agent('恢复旁观者')
  1205. const c=store.createGroup(owner,{name:'并发恢复',memberIds:[a.id,b.id],administratorId:a.id})
  1206. const tasks=[defaultTask(c.id),store.createTask(owner,c.id,{})]
  1207. reply=(_socket,p)=>recoveryByStored.set(storedByRuntime.get(p.session_id)!,[
  1208. {role:'user',content:p.text},{role:'assistant',content:p.text.includes('恢复甲')?'甲的最终结果':'乙的最终结果'},
  1209. ])
  1210. const runs=tasks.map((task,i)=>runtime.send(owner,c.id,{requestId:randomUUID(),taskId:task.id,content:i===0?'恢复甲':'恢复乙'}))
  1211. await vi.waitFor(()=>expect(requests.filter(r=>r.method==='prompt.submit')).toHaveLength(2))
  1212. runtime.close();runtime=new WorkspaceRuntime(store,nodes,uploads);runtime.start()
  1213. await Promise.all(runs.map(r=>finished(r.id)))
  1214. expect(requests.filter(r=>r.method==='prompt.submit')).toHaveLength(2)
  1215. expect(requests.filter(r=>r.method==='session.interrupt')).toHaveLength(0)
  1216. expect(tasks.map(task=>store.messages(owner,c.id,Number.MAX_SAFE_INTEGER,100,false,task.id).at(-1)?.content)).toEqual(['甲的最终结果','乙的最终结果'])
  1217. })
  1218. it('enforces three turns per topic and ten globally while preserving queued work', async () => {
  1219. const agents=Array.from({length:12},(_,i)=>agent(`并发成员${i}`))
  1220. 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})
  1221. const pending=new Map<string,{socket:WebSocket;p:Record<string,any>}>()
  1222. reply=(socket,p)=>pending.set(speaker(p)!,{socket,p})
  1223. const one=runtime.send(owner,group.id,{requestId:randomUUID(),content:'并发测试'})
  1224. await vi.waitFor(()=>expect(pending.size).toBe(3))
  1225. const others=agents.slice(4).map(a=>runtime.send(owner,direct(a.id).id,{requestId:randomUUID(),content:'另一群'}))
  1226. await vi.waitFor(()=>expect(pending.size).toBe(10))
  1227. expect(Object.keys(store.require<WorkspaceConversation>(owner,'conversation',group.id).activeAgentStates!)).toHaveLength(3)
  1228. expect(store.list<any>(owner,'turn').filter(t=>t.status==='running')).toHaveLength(10)
  1229. expect(store.list<any>(owner,'turn').filter(t=>t.status==='queued')).toHaveLength(2)
  1230. expect(requests.filter(r=>r.method==='session.interrupt')).toHaveLength(0)
  1231. const released=[...pending.values()]
  1232. for(const v of released) completeReply(v.socket,v.p,'完成')
  1233. await vi.waitFor(()=>expect(pending.size).toBe(12))
  1234. expect(store.list<any>(owner,'turn').filter(t=>t.status==='running').length).toBeLessThanOrEqual(10)
  1235. for(const v of pending.values()) if(!released.includes(v)) completeReply(v.socket,v.p,'完成')
  1236. await finished(one.id);await Promise.all(others.map(r=>finished(r.id)))
  1237. })
  1238. it('supports unlimited rounds beyond the finite limit and still permits stopping', async () => {
  1239. 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})
  1240. let count=0
  1241. reply=(socket,p)=>{
  1242. 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,'继续讨论')}
  1243. else completeReply(socket,p,'[[YAOYAO_NO_REPLY_V1]]')
  1244. }
  1245. const root=runtime.send(owner,g.id,{requestId:randomUUID(),content:'@不限乙 开始'})
  1246. await finished(root.id)
  1247. expect(count).toBe(2)
  1248. expect(store.require<WorkspaceRun>(owner,'run',root.id).round).toBe(101)
  1249. expect(()=>store.updateConversation(owner,g.id,{maxReplyRounds:0})).toThrow()
  1250. })
  1251. it('applies independent Bot approval choices on the same Profile and does not replay automatic answers', async () => {
  1252. const ask = agent('手动审批')
  1253. const { approvalPolicy: _policy, ...legacyAsk } = ask
  1254. store.put(owner, 'agent', ask.id, legacyAsk)
  1255. const allow = store.updateAgent(owner, agent('允许审批').id, { approvalPolicy: 'allow' })
  1256. const deny = store.updateAgent(owner, agent('拒绝审批').id, { approvalPolicy: 'deny' })
  1257. const bots = [ask, allow, deny]
  1258. expect(bots.every(bot => bot.profile === ask.profile)).toBe(true)
  1259. const notified: string[] = []
  1260. runtime.onNotify = (_owner, _conversation, _run, _message, interaction) => { if (interaction) notified.push(interaction.agentId) }
  1261. server.on('connection', socket => socket.on('message', raw => {
  1262. const frame = JSON.parse(String(raw))
  1263. if (frame.method === 'approval.respond') completeReply(socket, frame.params, '审批已处理')
  1264. }))
  1265. reply = (socket, params) => {
  1266. const frame = JSON.stringify({ method: 'event', params: { type: 'approval.request', session_id: params.session_id, payload: { request_id: 'same-id', message: '是否执行?' } } })
  1267. socket.send(frame); socket.send(frame)
  1268. }
  1269. const runs = bots.map(bot => runtime.send(owner, direct(bot.id).id, { requestId: randomUUID(), content: '执行任务' }))
  1270. await finished(runs[1]!.id); await finished(runs[2]!.id)
  1271. const interactions = store.list<WorkspaceInteraction & { answer?: string }>(owner, 'interaction')
  1272. expect(interactions).toHaveLength(3)
  1273. expect(interactions.find(item => item.agentId === ask.id)).toMatchObject({ resolved: false })
  1274. expect(interactions.find(item => item.agentId === allow.id)).toMatchObject({ resolved: true, answer: 'once' })
  1275. expect(interactions.find(item => item.agentId === deny.id)).toMatchObject({ resolved: true, answer: 'deny' })
  1276. expect(requests.filter(frame => frame.method === 'approval.respond')).toHaveLength(2)
  1277. expect(notified).toEqual([ask.id])
  1278. await runtime.respond(owner, interactions.find(item => item.agentId === ask.id)!.id, 'deny')
  1279. await finished(runs[0]!.id)
  1280. })
  1281. it('automatically allows this request and the next one while persisting only the owning Bot preference', async () => {
  1282. const bot = agent('选择自动允许'), peer = agent('同一基础机器人')
  1283. reply = (socket, params) => socket.send(JSON.stringify({ method: 'event', params: { type: 'approval.request', session_id: params.session_id, payload: { request_id: 'first-approval', message: '生成图片' } } }))
  1284. server.on('connection', socket => socket.on('message', raw => {
  1285. const frame = JSON.parse(String(raw))
  1286. if (frame.method !== 'approval.respond') return
  1287. if (frame.params.request_id === 'first-approval') socket.send(JSON.stringify({ method: 'event', params: { type: 'approval.request', session_id: frame.params.session_id, payload: { request_id: 'next-approval', message: '保存图片' } } }))
  1288. else completeReply(socket, frame.params, '自动完成')
  1289. }))
  1290. const run = runtime.send(owner, direct(bot.id).id, { requestId: randomUUID(), content: '生成图片' })
  1291. await vi.waitFor(() => expect(store.list<WorkspaceInteraction>(owner, 'interaction')).toHaveLength(1))
  1292. const request = store.list<WorkspaceInteraction>(owner, 'interaction')[0]!
  1293. await expect(runtime.respond(other, request.id, 'auto')).rejects.toThrow('记录不存在')
  1294. expect(store.require<any>(owner, 'agent', bot.id).approvalPolicy).toBe('ask')
  1295. await runtime.respond(owner, request.id, 'auto')
  1296. await finished(run.id)
  1297. expect(requests.filter(frame => frame.method === 'approval.respond').map(frame => frame.params.choice)).toEqual(['once', 'once'])
  1298. expect(store.require<any>(owner, 'agent', bot.id).approvalPolicy).toBe('allow')
  1299. expect(store.require<any>(owner, 'agent', peer.id).approvalPolicy).toBe('ask')
  1300. store.updateAgent(owner, bot.id, { approvalPolicy: 'ask' })
  1301. await runtime.respond(owner, request.id, 'auto')
  1302. expect(store.require<any>(owner, 'agent', bot.id).approvalPolicy).toBe('ask')
  1303. expect(requests.filter(frame => frame.method === 'approval.respond')).toHaveLength(2)
  1304. })
  1305. it('preserves current team grants for approval-only edits without reviving revoked grants', () => {
  1306. const bot = agent('有效工具授权')
  1307. store.put(owner, 'turn', 'valid-grant', { id: 'valid-grant', agentId: bot.id, status: 'waiting', teamManagementRevision: bot.revision })
  1308. store.put(owner, 'turn', 'revoked-grant', { id: 'revoked-grant', agentId: bot.id, status: 'running', teamManagementRevision: bot.revision - 1 })
  1309. const updated = store.updateAgent(owner, bot.id, { approvalPolicy: 'allow' })
  1310. expect(store.require<any>(owner, 'turn', 'valid-grant').teamManagementRevision).toBe(updated.revision)
  1311. expect(store.require<any>(owner, 'turn', 'revoked-grant').teamManagementRevision).toBe(bot.revision - 1)
  1312. store.updateAgent(owner, bot.id, { instructions: '新规则' })
  1313. expect(store.require<any>(owner, 'turn', 'valid-grant').teamManagementRevision).toBe(updated.revision)
  1314. })
  1315. it('keeps an explicit automatic preference but reports an unconfirmed reply without retrying it', async () => {
  1316. const bot = agent('自动设置与答复状态')
  1317. reply = (socket, params) => socket.send(JSON.stringify({ method: 'event', params: { type: 'approval.request', session_id: params.session_id, payload: { request_id: 'uncertain-auto', message: '需要确认' } } }))
  1318. runtime.send(owner, direct(bot.id).id, { requestId: randomUUID(), content: '继续' })
  1319. await vi.waitFor(() => expect(store.list<WorkspaceInteraction>(owner, 'interaction')).toHaveLength(1))
  1320. const interaction = store.list<WorkspaceInteraction>(owner, 'interaction')[0]!
  1321. const rpc = WorkspaceGateway.prototype.rpc
  1322. const spy = vi.spyOn(WorkspaceGateway.prototype, 'rpc').mockImplementation(function (this: WorkspaceGateway, method, params) {
  1323. return method === 'approval.respond' ? Promise.reject(new Error('connection lost')) : rpc.call(this, method, params)
  1324. })
  1325. try {
  1326. await expect(runtime.respond(owner, interaction.id, 'auto')).rejects.toMatchObject({ code: 'approval_auto_response_failed' })
  1327. expect(store.require<any>(owner, 'agent', bot.id).approvalPolicy).toBe('allow')
  1328. expect(store.require<any>(owner, 'interaction', interaction.id)).toMatchObject({ resolved: false, responseState: 'uncertain', answer: 'auto' })
  1329. await expect(runtime.respond(owner, interaction.id, 'auto')).rejects.toMatchObject({ code: 'interaction_uncertain' })
  1330. expect(spy.mock.calls.filter(call => call[0] === 'approval.respond')).toHaveLength(1)
  1331. } finally { spy.mockRestore() }
  1332. })
  1333. it('leaves clarifications and already pending approvals for the user after a policy change', async () => {
  1334. const bot = agent('更改审批')
  1335. let kind = 'approval'
  1336. server.on('connection', socket => socket.on('message', raw => {
  1337. const frame = JSON.parse(String(raw))
  1338. if (['approval.respond', 'clarify.respond'].includes(frame.method)) completeReply(socket, frame.params, '已答复')
  1339. }))
  1340. reply = (socket, params) => socket.send(JSON.stringify({ method: 'event', params: { type: `${kind}.request`, session_id: params.session_id, payload: { request_id: 'pending', message: '请确认' } } }))
  1341. for (kind of ['approval', 'clarify']) {
  1342. const run = runtime.send(owner, direct(bot.id).id, { requestId: randomUUID(), content: '继续任务' })
  1343. await vi.waitFor(() => expect(store.require<WorkspaceRun>(owner, 'run', run.id).status).toBe('waiting'))
  1344. store.updateAgent(owner, bot.id, { approvalPolicy: 'allow' })
  1345. const interaction = store.list<WorkspaceInteraction>(owner, 'interaction').find(item => !item.resolved)!
  1346. expect(requests.filter(frame => ['approval.respond', 'clarify.respond'].includes(frame.method))).toHaveLength(kind === 'approval' ? 0 : 1)
  1347. await runtime.respond(owner, interaction.id, kind === 'approval' ? 'once' : '下一步')
  1348. await finished(run.id)
  1349. }
  1350. })
  1351. it('defaults legacy and newly created Bots to manual approval and prevents autonomous grants', () => {
  1352. const parent = agent('创建者')
  1353. expect(parent.approvalPolicy).toBe('ask')
  1354. const child = store.createAgent(owner, { name: '子成员', profile: parent.profile, approvalPolicy: 'allow' }, { createdByAgentId: parent.id, createdFromRunId: randomUUID() })
  1355. expect(child.approvalPolicy).toBe('ask')
  1356. expect(() => store.updateAgent(owner, child.id, { approvalPolicy: 'always' })).toThrow('approvalPolicy')
  1357. store.put(owner, 'agent', child.id, { ...child, remoteAgentId: randomUUID() })
  1358. expect(store.updateAgent(owner, child.id, { approvalPolicy: 'deny' }).approvalPolicy).toBe('deny')
  1359. expect(() => store.updateAgent(owner, child.id, { name: '不能改远端资料' })).toThrow('远端管理')
  1360. })
  1361. it('keeps a failed automatic approval pending and does not retry a replayed request', async () => {
  1362. const bot = store.updateAgent(owner, agent('审批失败').id, { approvalPolicy: 'allow' })
  1363. const rpc = WorkspaceGateway.prototype.rpc
  1364. let attempts = 0
  1365. const spy = vi.spyOn(WorkspaceGateway.prototype, 'rpc').mockImplementation(function (this: WorkspaceGateway, method, params) {
  1366. if (method === 'approval.respond' && attempts++ === 0) return Promise.reject(new HttpError(409, '暂时拒绝答复', 'gateway_rejected'))
  1367. return rpc.call(this, method, params)
  1368. })
  1369. try {
  1370. const notify = vi.fn()
  1371. runtime.onNotify = notify
  1372. reply = (socket, params) => {
  1373. const frame = JSON.stringify({ method: 'event', params: { type: 'approval.request', session_id: params.session_id, payload: { request_id: 'failure', message: '确认操作' } } })
  1374. socket.send(frame); socket.send(frame)
  1375. }
  1376. server.on('connection', socket => socket.on('message', raw => {
  1377. const frame = JSON.parse(String(raw))
  1378. if (frame.method === 'approval.respond') completeReply(socket, frame.params, '手动处理完成')
  1379. }))
  1380. const run = runtime.send(owner, direct(bot.id).id, { requestId: randomUUID(), content: '继续' })
  1381. await vi.waitFor(() => expect(notify.mock.calls.some(call => call[4]?.kind === 'approval')).toBe(true))
  1382. expect(attempts).toBe(1)
  1383. const interaction = store.list<WorkspaceInteraction>(owner, 'interaction').find(item => !item.resolved)!
  1384. expect(store.require<WorkspaceRun>(owner, 'run', run.id).status).toBe('waiting')
  1385. await runtime.respond(owner, interaction.id, 'deny')
  1386. await finished(run.id)
  1387. } finally { spy.mockRestore() }
  1388. })
  1389. it('keeps parallel approval cards scoped to their member and deduplicates replayed requests and answers', async () => {
  1390. const a=agent('审批管理员'),b=agent('审批乙'),c=agent('审批丙'),g=store.createGroup(owner,{name:'并发审批',memberIds:[a.id,b.id,c.id],administratorId:a.id})
  1391. let admin=0
  1392. server.on('connection',socket=>socket.on('message',raw=>{const f=JSON.parse(String(raw));if(f.method==='approval.respond')completeReply(socket,f.params,'已确认')}))
  1393. reply=(socket,p)=>{
  1394. if(speaker(p)===a.name){completeReply(socket,p,admin++===0?'@审批乙 @审批丙':'汇总');return}
  1395. const frame=JSON.stringify({method:'event',params:{type:'approval.request',session_id:p.session_id,payload:{request_id:'same-request',message:'是否继续'}}})
  1396. socket.send(frame);socket.send(frame)
  1397. }
  1398. const root=runtime.send(owner,g.id,{requestId:randomUUID(),content:'开始'})
  1399. await vi.waitFor(()=>expect(store.list<WorkspaceInteraction>(owner,'interaction').filter(i=>!i.resolved)).toHaveLength(2))
  1400. const interactions=store.list<WorkspaceInteraction>(owner,'interaction')
  1401. expect(store.require<WorkspaceConversation>(owner,'conversation',g.id).activeAgentStates).toEqual({[b.id]:'waiting',[c.id]:'waiting'})
  1402. await runtime.respond(owner,interactions[0]!.id,'once')
  1403. await runtime.respond(owner,interactions[0]!.id,'once')
  1404. await expect(runtime.respond(owner,interactions[0]!.id,'deny')).rejects.toThrow('其他答复')
  1405. expect(admin).toBe(1)
  1406. await runtime.respond(owner,interactions[1]!.id,'once')
  1407. await finished(root.id)
  1408. expect(requests.filter(r=>r.method==='approval.respond')).toHaveLength(2)
  1409. expect(admin).toBe(2)
  1410. })
  1411. it('retries a rolled-back cascade plan without losing or duplicating delegation', async () => {
  1412. const a=agent('事务管理员'),b=agent('事务成员'),g=store.createGroup(owner,{name:'调度事务',memberIds:[a.id,b.id],administratorId:a.id})
  1413. const original=store.put.bind(store);let failed=false,admin=0
  1414. 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)}
  1415. reply=(socket,p)=>completeReply(socket,p,speaker(p)===a.name&&admin++===0?'@事务成员 继续':'完成')
  1416. const root=runtime.send(owner,g.id,{requestId:randomUUID(),content:'开始'})
  1417. await vi.waitFor(()=>expect(store.require<WorkspaceRun>(owner,'run',root.id).status).toBe('complete'),{timeout:4000})
  1418. expect(failed).toBe(true)
  1419. expect(store.list<any>(owner,'turn').filter(t=>t.agentId===b.id)).toHaveLength(1)
  1420. expect(requests.filter(r=>r.method==='prompt.submit')).toHaveLength(3)
  1421. })
  1422. it('upgrades an admitted v0.3.7 execution without submitting its prompt again', async () => {
  1423. const a=agent('升级执行'),c=direct(a.id)
  1424. reply=(socket,p)=>{recoveryHistory=[{role:'user',content:p.text},{role:'assistant',content:'升级前已完成'}];socket.terminate()}
  1425. const root=runtime.send(owner,c.id,{requestId:randomUUID(),content:'只执行一次'})
  1426. await vi.waitFor(()=>expect(store.require<WorkspaceRun>(owner,'run',root.id).status).toBe('uncertain'))
  1427. runtime.close()
  1428. const old=store.list<any>(owner,'turn')[0]!
  1429. for(const task of store.list<any>(owner,'turn'))store.remove(owner,'turn',task.id)
  1430. const legacy=store.require<any>(owner,'run',root.id)
  1431. Object.assign(legacy,{queue:[a.id],next:[],hostReturn:false,currentMessageId:old.currentMessageId,turnConfiguration:old.turnConfiguration})
  1432. store.put(owner,'run',root.id,legacy)
  1433. const binding=store.get<any>(owner,'binding',`${c.id}:${a.id}`)!
  1434. delete binding.taskId;store.put(owner,'binding',binding.id,binding)
  1435. runtime=new WorkspaceRuntime(store,nodes,uploads);runtime.start()
  1436. await finished(root.id)
  1437. expect(requests.filter(r=>r.method==='prompt.submit')).toHaveLength(1)
  1438. expect(store.messages(owner,c.id).at(-1)?.content).toBe('升级前已完成')
  1439. })
  1440. it('does not read unrelated or orphaned historical runs when projecting a group prompt', async () => {
  1441. const a=agent('上下文隔离'),b=agent('组内成员'),g=store.createGroup(owner,{name:'干净群',memberIds:[a.id,b.id],administratorId:a.id})
  1442. store.put(owner,'run','historical-orphan',{id:'historical-orphan',conversationId:'unrelated-conversation',messageId:'missing-history',mentionIds:[],status:'complete',round:0,createdAt:1,updatedAt:1})
  1443. await finished(runtime.send(owner,g.id,{requestId:randomUUID(),content:'当前群任务'}).id)
  1444. expect(requests.filter(r=>r.method==='prompt.submit')).toHaveLength(1)
  1445. })
  1446. it('pages backwards to find a long-running turn marker and never mistakes a tool call for a final answer', async () => {
  1447. const a=agent('分页恢复'),c=direct(a.id)
  1448. reply=(socket,p)=>{
  1449. recoveryHistory=[{role:'user',content:p.text},...Array.from({length:600},()=>({role:'tool',content:'工具结果'})),{role:'assistant',content:'最终结果'}]
  1450. socket.terminate()
  1451. }
  1452. await finished(runtime.send(owner,c.id,{requestId:randomUUID(),content:'长时间执行'}).id)
  1453. expect(store.messages(owner,c.id).at(-1)?.content).toBe('最终结果')
  1454. let submitted=''
  1455. reply=(socket,p)=>{submitted=p.text;recoveryHistory=[{role:'user',content:submitted},{role:'assistant',content:'准备调用工具',tool_calls:[{id:'tool'}]},{role:'tool',content:'工具输出'}];socket.terminate()}
  1456. const root=runtime.send(owner,c.id,{requestId:randomUUID(),content:'不要把过程当结论'})
  1457. await vi.waitFor(()=>expect(store.require<WorkspaceRun>(owner,'run',root.id).status).toBe('uncertain'))
  1458. await runtime.reconcile(owner,root.id)
  1459. await new Promise(resolve=>setTimeout(resolve,100))
  1460. expect(store.require<WorkspaceRun>(owner,'run',root.id).status).toBe('uncertain')
  1461. recoveryHistory.push({role:'assistant',content:'真正完成'})
  1462. await runtime.reconcile(owner,root.id)
  1463. await finished(root.id)
  1464. expect(requests.filter(r=>r.method==='prompt.submit')).toHaveLength(2)
  1465. })
  1466. it('keeps explicit replies visible and emits one notice when the configured cascade limit is reached', async () => {
  1467. const a=agent('轮数管理员'),b=agent('轮数成员'),g=store.createGroup(owner,{name:'有限轮次',memberIds:[a.id,b.id],administratorId:a.id,maxReplyRounds:2})
  1468. reply=(socket,p)=>completeReply(socket,p,speaker(p)===a.name?'@轮数成员 继续':'已完成本步')
  1469. const root=runtime.send(owner,g.id,{requestId:randomUUID(),content:'开始'})
  1470. await finished(root.id)
  1471. expect(requests.filter(r=>r.method==='prompt.submit')).toHaveLength(3)
  1472. expect(store.messages(owner,g.id).filter(m=>m.content.includes('轮数上限'))).toHaveLength(1)
  1473. store.updateConversation(owner,g.id,{mode:'free',autoReplyIds:[]})
  1474. reply=(socket,p)=>completeReply(socket,p,'[[YAOYAO_NO_REPLY_V1]]')
  1475. await finished(runtime.send(owner,g.id,{requestId:randomUUID(),content:'@轮数成员 显示这个字符串'}).id)
  1476. expect(store.messages(owner,g.id).at(-1)?.content).toBe('[[YAOYAO_NO_REPLY_V1]]')
  1477. })
  1478. it('retries a failed stop of a live task without falsely completing it or resubmitting work', async () => {
  1479. const a=agent('停止恢复'),c=direct(a.id)
  1480. reply=()=>{}
  1481. const root=runtime.send(owner,c.id,{requestId:randomUUID(),content:'等待停止'})
  1482. await vi.waitFor(()=>expect(requests.filter(r=>r.method==='prompt.submit')).toHaveLength(1))
  1483. rejectedInterrupts=1
  1484. await runtime.stop(owner,root.id)
  1485. expect(store.require<WorkspaceRun>(owner,'run',root.id).status).toBe('uncertain')
  1486. await vi.waitFor(()=>expect(store.require<WorkspaceRun>(owner,'run',root.id).status).toBe('interrupted'),{timeout:3000})
  1487. expect(requests.filter(r=>r.method==='session.interrupt')).toHaveLength(2)
  1488. expect(requests.filter(r=>r.method==='prompt.submit')).toHaveLength(1)
  1489. })
  1490. it('marks a stopped administrator as interrupted without sending a false completion notification', async () => {
  1491. const a=agent('管理员停止'),b=agent('普通成员'),g=store.createGroup(owner,{name:'停止管理员',memberIds:[a.id,b.id],administratorId:a.id})
  1492. reply=()=>{}
  1493. const notifications: string[]=[]
  1494. runtime.onNotify=(_owner,_c,run)=>notifications.push(run.status)
  1495. const root=runtime.send(owner,g.id,{requestId:randomUUID(),content:'等待'})
  1496. await vi.waitFor(()=>expect(requests.filter(r=>r.method==='prompt.submit')).toHaveLength(1))
  1497. await runtime.stopAgent(owner,g.id,a.id)
  1498. await vi.waitFor(()=>expect(store.require<WorkspaceRun>(owner,'run',root.id).status).toBe('interrupted'))
  1499. expect(notifications).toEqual([])
  1500. })
  1501. it('randomizes old default avatars once while preserving photos, custom v2 settings and direct snapshots',()=>{
  1502. const a=store.createAgent(owner,{name:'旧头像',profile:'default',instructions:'保留规则'})
  1503. const photo='data:image/png;base64,aGVsbG8='
  1504. const b=store.createAgent(owner,{name:'照片',profile:'default',avatar:photo})
  1505. store.put(owner,'agent',a.id,{...a,avatar:'yaoyao-mascot:v1:triangle:ff0000:friendly'})
  1506. store.put(owner,'agent',b.id,{...b,avatar:photo})
  1507. store.db.prepare("DELETE FROM workspace_migrations WHERE id IN ('avatar-v2','avatar-random-default-v1')").run()
  1508. const random=vi.spyOn(Math,'random').mockReturnValue(0)
  1509. const migrated=new WorkspaceStore(home)
  1510. random.mockRestore()
  1511. const next=migrated.require<any>(owner,'agent',a.id)
  1512. expect(next.instructions).toBe('保留规则')
  1513. expect(decodeAgentAvatar(next.avatar)).toMatchObject({avatarMode:'mascot'})
  1514. expect(next.avatar).not.toBe(encodeAgentAvatar(defaultAgentIdentity(a.id,a.name)))
  1515. const image=migrated.require<any>(owner,'agent',b.id)
  1516. expect(decodeAgentAvatar(image.avatar)).toMatchObject({avatarMode:'image',imageDataURL:photo,imageCrop:'rounded'})
  1517. for(const c of migrated.list<WorkspaceConversation>(owner,'conversation')) expect(c.avatar).toBe(migrated.require<any>(owner,'agent',c.memberIds[0]!).avatar)
  1518. const customized=encodeAgentAvatar({...defaultAgentIdentity('bot'),bodyId:'star',expression:'proud',color:'#1488ff'})
  1519. migrated.updateAgent(owner,a.id,{avatar:customized})
  1520. migrated.close()
  1521. const reopened=new WorkspaceStore(home)
  1522. expect(reopened.require<any>(owner,'agent',a.id).avatar).toBe(customized)
  1523. expect(reopened.db.prepare("SELECT count(*) AS count FROM workspace_migrations WHERE id='avatar-random-default-v1'").get()!.count).toBe(1)
  1524. reopened.close()
  1525. })
  1526. // A member can have a queued follow-up while their current task needs approval.
  1527. it('keeps active avatar state ahead of queued work and publishes only recent outcomes', () => {
  1528. const a=agent('状态优先级'), c=direct(a.id), now=Date.now()
  1529. const run: WorkspaceRun={id:'avatar-run',conversationId:c.id,messageId:'unused',mentionIds:[],status:'complete',round:1,createdAt:now,updatedAt:now}
  1530. for (const [id,status] of [['current','waiting'],['next','queued']] as const)
  1531. store.put(owner,'turn',id,{id,conversationId:c.id,agentId:a.id,status,planned:true,updatedAt:now})
  1532. store.put(owner,'turn','result',{id:'result',conversationId:c.id,agentId:a.id,status:'failed',updatedAt:now})
  1533. store.saveRun(owner,run)
  1534. let summary=store.require<WorkspaceConversation>(owner,'conversation',c.id)
  1535. expect(summary.activeAgentStates).toEqual({[a.id]:'waiting'})
  1536. expect(summary.avatarSignals?.[a.id]).toMatchObject({id:'result',state:'failure'})
  1537. store.put(owner,'turn','result',{id:'result',conversationId:c.id,agentId:a.id,status:'complete',updatedAt:now-3000})
  1538. store.saveRun(owner,run)
  1539. expect(store.require<WorkspaceConversation>(owner,'conversation',c.id).avatarSignals).toEqual({})
  1540. })
  1541. it('queues an unsubmitted turn while computer capacity is unavailable and submits it once after recovery',async()=>{
  1542. const a=agent('等候电脑'),c=direct(a.id),target=nodes.target(owner,'local')
  1543. vi.spyOn(target.session,'request').mockRejectedValueOnce(new HttpError(429,'资源不足','computer_quota'))
  1544. const run=runtime.send(owner,c.id,{requestId:randomUUID(),content:'等待资源后执行'})
  1545. await vi.waitFor(()=>expect(store.list<any>(owner,'turn').find(work=>work.runId===run.id)?.resourceWait).toBe(true))
  1546. expect(store.require<WorkspaceRun>(owner,'run',run.id).status).toBe('queued')
  1547. await vi.waitFor(()=>expect(store.require<WorkspaceRun>(owner,'run',run.id).status).toBe('complete'),{timeout:5000})
  1548. expect(requests.filter(request=>request.method==='prompt.submit')).toHaveLength(1)
  1549. })
  1550. it('fails an unsubmitted turn immediately when the computer runner is offline',async()=>{
  1551. const a=store.updateAgent(owner,agent('离线电脑').id,{execution:'computer',computer:'vm'}),c=direct(a.id)
  1552. nodes.targetForAgent=vi.fn(()=>{throw new HttpError(503,'执行节点未连接,请启动 Runner 后重试','runner_offline')})
  1553. const run=runtime.send(owner,c.id,{requestId:randomUUID(),content:'不能无声等待'})
  1554. await vi.waitFor(()=>expect(store.require<WorkspaceRun>(owner,'run',run.id).status).toBe('failed'))
  1555. const work=store.list<Work>(owner,'turn').find(work=>work.runId===run.id)!
  1556. expect(work.resourceWait).toBe(false)
  1557. expect(work.error).toBe('执行节点未连接,请启动 Runner 后重试')
  1558. expect(store.messages(owner,c.id).at(-1)?.content).toBe('执行失败:执行节点未连接,请启动 Runner 后重试')
  1559. })
  1560. it('can stop an unsubmitted turn that is waiting for computer capacity',async()=>{
  1561. const a=store.updateAgent(owner,agent('可停止等候').id,{execution:'computer',computer:'vm'}),c=direct(a.id)
  1562. nodes.targetForAgent=vi.fn(()=>{throw new HttpError(429,'资源不足','computer_quota')})
  1563. const run=runtime.send(owner,c.id,{requestId:randomUUID(),content:'等待中停止'})
  1564. const work=await vi.waitFor(()=>{
  1565. const current=store.list<Work>(owner,'turn').find(work=>work.runId===run.id)
  1566. expect(current?.resourceWait).toBe(true)
  1567. return current!
  1568. })
  1569. await runtime.stop(owner,run.id)
  1570. await vi.waitFor(()=>expect(store.require<Work>(owner,'turn',work.id).status).toBe('interrupted'))
  1571. })
  1572. it('forwards a generated artifact to a new task without changing its original provenance',async()=>{
  1573. const a=agent('产物接收者'),c=direct(a.id)
  1574. const first=runtime.send(owner,c.id,{requestId:randomUUID(),content:'first'})
  1575. await finished(first.id)
  1576. const message=store.messages(owner,c.id).find(message=>message.role==='assistant')!
  1577. const assets=new WorkspaceAssets(store,nodes,home)
  1578. const file=assets.publish(owner,message,a,'review.txt',Buffer.from('verified artifact'))
  1579. const sent=runtime.dispatch(owner,c.id,{requestId:randomUUID(),content:'复核附件',fileIds:[file.id]},{agentId:a.id,kind:'task_review'})
  1580. await finished(sent.id)
  1581. const attached=requests.find(request=>request.method==='file.attach')!
  1582. expect(Buffer.from(attached.params.data_url.split(',')[1],'base64').toString()).toBe('verified artifact')
  1583. expect(store.require<any>(owner,'file',file.id).messageId).toBe(message.id)
  1584. expect(store.require<WorkspaceMessage>(owner,'message',sent.messageId).attachments.map(file=>file.id)).toEqual([file.id])
  1585. assets.close()
  1586. })
  1587. it('migrates an old VM conversation into Hermes once, carries prior messages, and resumes the new session afterwards',async()=>{
  1588. const a=store.updateAgent(owner,agent('迁移测试').id,{execution:'computer',computer:'vm'}),c=direct(a.id)
  1589. const native=nodes.target(owner,'local')
  1590. const target:GatewayTarget={...native,runner:{id:'migration-runner',computer:true,hermesComputer:false,
  1591. open:async(onEvent,onDisconnect)=>{
  1592. const gateway=new WorkspaceGateway(native);gateway.onEvent=onEvent;gateway.onDisconnect=onDisconnect
  1593. await gateway.connect();return {rpc:(method,params)=>gateway.rpc(method,params),close:()=>gateway.close()}
  1594. },lease:async()=>{throw new Error('unexpected lease')},
  1595. }}
  1596. nodes.targetForAgent=()=>target
  1597. const first=runtime.send(owner,c.id,{requestId:randomUUID(),content:'已确认的原会话事实'})
  1598. await vi.waitFor(()=>expect(store.require<WorkspaceRun>(owner,'run',first.id).status).toBe('complete'))
  1599. const key=`${c.id}:${a.id}`,old=store.get<any>(owner,'binding',key)!
  1600. target.runner!.hermesComputer=true
  1601. const second=runtime.send(owner,c.id,{requestId:randomUUID(),content:'继续这次任务'})
  1602. await vi.waitFor(()=>expect(store.require<WorkspaceRun>(owner,'run',second.id).status).toBe('complete'))
  1603. const migrated=store.get<any>(owner,'binding',key)!
  1604. expect(migrated.hermesComputer).toBe(true);expect(migrated.storedId).not.toBe(old.storedId)
  1605. expect(requests.filter(r=>r.method==='session.create')).toHaveLength(2)
  1606. expect(requests.filter(r=>r.method==='session.resume')).toHaveLength(0)
  1607. expect(requests.filter(r=>r.method==='prompt.submit')[1].params.text).toContain('已确认的原会话事实')
  1608. const third=runtime.send(owner,c.id,{requestId:randomUUID(),content:'再次继续'})
  1609. await vi.waitFor(()=>expect(store.require<WorkspaceRun>(owner,'run',third.id).status).toBe('complete'))
  1610. expect(requests.filter(r=>r.method==='session.resume')).toHaveLength(1)
  1611. expect(requests.filter(r=>r.method==='session.resume')[0].params.session_id).toBe(migrated.storedId)
  1612. expect(requests.filter(r=>r.method==='prompt.submit')).toHaveLength(3)
  1613. })
  1614. it('keeps memory flags out of session.create and grants scoped memory through the bridge',async()=>{
  1615. const a=agent('独立记忆'),c=direct(a.id),target=nodes.target(owner,'local'),request=target.session.request.bind(target.session),bindings:any[]=[]
  1616. vi.spyOn(target.session,'request').mockImplementation(async(path,options)=>{
  1617. if(path.endsWith('/capabilities'))return {status:200,headers:new Headers(),body:Buffer.from(JSON.stringify({ready:true,native_tools:true,in_process:true,memory_isolation:true}))}
  1618. if(path.endsWith('/bind')){bindings.push(options?.body);return {status:200,headers:new Headers(),body:Buffer.from(JSON.stringify({ok:true,native_tools:true,workspace_memory:true}))}}
  1619. if(path.endsWith('/unbind'))return {status:200,headers:new Headers(),body:Buffer.from('{"ok":true}')}
  1620. return request(path,options)
  1621. })
  1622. await finished(runtime.send(owner,c.id,{requestId:randomUUID(),content:'验证完整创建链路'}).id)
  1623. const create=requests.find(r=>r.method==='session.create')!
  1624. expect(create.params).not.toHaveProperty('skip_memory')
  1625. expect(create.params).not.toHaveProperty('workspace_memory')
  1626. expect(bindings).toContainEqual(expect.objectContaining({workspace_memory:true}))
  1627. })