workspace.test.ts 71 KB

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