realtimeBroker.test.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. import { mkdtempSync, readFileSync } from 'node:fs'
  2. import { join } from 'node:path'
  3. import { tmpdir } from 'node:os'
  4. import { once } from 'node:events'
  5. import { WebSocketServer, type WebSocket } from 'ws'
  6. import { afterEach, describe, expect, it, vi } from 'vitest'
  7. import { RealtimeBroker, type RealtimeActivity, type RealtimePrincipal, type StreamEntry } from '../../src/server/realtimeBroker.js'
  8. import { RealtimeReceipts } from '../../src/server/realtimeReceipts.js'
  9. const cleanup: Array<() => void> = []
  10. afterEach(() => cleanup.splice(0).reverse().forEach(f => f()))
  11. async function fixture() {
  12. const home = mkdtempSync(join(tmpdir(), 'yaoyao-realtime-test-'))
  13. const ws = new WebSocketServer({ port: 0, host: '127.0.0.1' })
  14. await once(ws, 'listening')
  15. cleanup.push(() => { for (const c of ws.clients) c.terminate(); ws.close() })
  16. const commands: any[] = []
  17. let count = 0
  18. let seq = 0, truncate = false, dropPrompt = false
  19. let cwd = '/old-session', busy = false, rejectCwd = false
  20. const history: any[] = []
  21. let peer: WebSocket
  22. ws.on('connection', socket => {
  23. peer = socket; count++
  24. socket.send(JSON.stringify({ method: 'event', params: { type: 'gateway.ready', payload: { replay_epoch: 'test' } } }))
  25. socket.on('message', raw => {
  26. const f = JSON.parse(raw.toString()); commands.push(f)
  27. if (f.method === 'prompt.submit' && dropPrompt) { socket.terminate(); return }
  28. if (f.method === 'profiles.list') {
  29. socket.send(JSON.stringify({id:f.id,result:{profiles:[{name:'default',ui_meta:{'hermes-bots':{chat:'stored-1'}}}]}}))
  30. } else if (f.method === 'session.events.since') {
  31. socket.send(JSON.stringify({ id: f.id, result: { epoch: 'test', truncated: truncate,
  32. events: history.filter(e => e.seq > f.params.last_seen) } }))
  33. } else if (f.method === 'session.branch') {
  34. socket.send(JSON.stringify({ id: f.id, result: { session_id: 'runtime-branch', stored_session_id: 'stored-branch' } }))
  35. } else if (f.method === 'session.create' || f.method === 'session.resume') {
  36. if (f.method === 'session.create' && f.params.cwd) cwd = f.params.cwd
  37. socket.send(JSON.stringify({ id: f.id, result: { session_id: 'runtime-1', stored_session_id: 'stored-1', running: busy, info: { cwd } } }))
  38. } else if (f.method === 'session.cwd.set') {
  39. if (rejectCwd) socket.send(JSON.stringify({ id: f.id, error: { message: 'working directory does not exist' } }))
  40. else { cwd = f.params.cwd; socket.send(JSON.stringify({ id: f.id, result: { cwd } })) }
  41. } else {
  42. setTimeout(() => socket.send(JSON.stringify({ id: f.id, result: { status: 'submitted' } })), 20)
  43. }
  44. })
  45. })
  46. let now = Date.now()
  47. const activities: RealtimeActivity[] = []
  48. const broker = new RealtimeBroker(home, () => now, change => activities.push(change))
  49. cleanup.push(() => broker.close())
  50. const principal = (key: string): RealtimePrincipal => ({ key, upstreamKey: 'one-service', paired: false,
  51. valid: () => true, url: async () => new URL(`ws://127.0.0.1:${(ws.address() as any).port}`) })
  52. return { home, broker, principal, commands, activities, count: () => count, advance: (n: number) => { now += n },
  53. cwd: () => cwd, busy: () => { busy = true }, rejectCwd: () => { rejectCwd = true },
  54. disconnect: () => peer!.terminate(), truncate: () => { truncate = true }, dropPrompt: () => { dropPrompt = true },
  55. emit: (type: string, payload: unknown) => {
  56. const params = { type, session_id: 'runtime-1', seq: ++seq, payload }; history.push(params)
  57. if (peer!.readyState === 1) peer!.send(JSON.stringify({ method: 'event', params }))
  58. } }
  59. }
  60. const resume = { method: 'session.resume', params: { session_id: 'stored-1', profile: 'default' } }
  61. describe('realtime broker', () => {
  62. it.each([
  63. { source: 'web', paired: false }, { source: 'ios', paired: false }, { source: 'ios', paired: true },
  64. ])('uses the profile terminal.cwd for $source (paired=$paired), ignoring client cwd', async ({ source, paired }) => {
  65. const f = await fixture()
  66. const read = vi.fn(async (_profile: string) => '/Hermes/配置目录')
  67. const principal = { ...f.principal('alice'), paired, configuredWorkingDirectory: read }
  68. const channel = await f.broker.create(principal, 'chat')
  69. const created = await f.broker.command(channel, 'create', {
  70. method: 'session.create', params: { profile: 'work', source, cwd: '/client/override' },
  71. })
  72. expect(created.state).toBe('confirmed')
  73. expect(f.commands[0].params.cwd).toBe('/Hermes/配置目录')
  74. const sent = await f.broker.command(channel, 'send', {
  75. method: 'prompt.submit', params: { session_id: 'runtime-1', text: 'run' },
  76. })
  77. expect(sent.state).toBe('confirmed')
  78. expect(read.mock.calls.every(([profile]) => profile === 'work')).toBe(true)
  79. expect(f.commands.map(x => x.method)).toEqual(['session.create', 'prompt.submit'])
  80. expect(f.cwd()).toBe('/Hermes/配置目录')
  81. })
  82. it('corrects an old cwd before attachments and follows config changes on the next turn', async () => {
  83. const f = await fixture()
  84. let configured = '/configured/first'
  85. const channel = await f.broker.create({ ...f.principal('alice'),
  86. configuredWorkingDirectory: async () => configured }, 'chat')
  87. await f.broker.command(channel, 'resume', resume)
  88. expect(f.cwd()).toBe('/old-session')
  89. await f.broker.command(channel, 'attach', {
  90. method: 'file.attach', params: { session_id: 'runtime-1', data_url: 'data:text/plain;base64,eA==' },
  91. })
  92. expect(f.cwd()).toBe('/configured/first')
  93. await f.broker.command(channel, 'send', { method: 'prompt.submit', params: { session_id: 'runtime-1', text: 'one' } })
  94. expect(f.commands.filter(x => x.method === 'session.cwd.set')).toHaveLength(1)
  95. configured = '/configured/second'
  96. const events: StreamEntry[] = []
  97. f.broker.subscribe(channel, undefined, entry => events.push(entry))
  98. f.emit('message.complete', {})
  99. await vi.waitFor(() => expect(events.some(e => e.data.includes('message.complete'))).toBe(true))
  100. await f.broker.command(channel, 'send-next', { method: 'prompt.submit', params: { session_id: 'runtime-1', text: 'two' } })
  101. expect(f.cwd()).toBe('/configured/second')
  102. expect(f.commands.filter(x => x.method === 'session.cwd.set')).toHaveLength(2)
  103. expect(f.commands.some(x => x.method === 'config.set')).toBe(false)
  104. })
  105. it('does not switch a running session when another client resumes or queues a message', async () => {
  106. const f = await fixture(); f.busy()
  107. const read = vi.fn(async () => '/configured')
  108. const channel = await f.broker.create({ ...f.principal('alice'), configuredWorkingDirectory: read }, 'chat')
  109. await f.broker.command(channel, 'resume', resume)
  110. await f.broker.command(channel, 'queued', { method: 'prompt.submit', params: { session_id: 'runtime-1', text: 'next', queued: true } })
  111. expect(read).not.toHaveBeenCalled()
  112. expect(f.commands.map(x => x.method)).toEqual(['session.resume', 'prompt.submit'])
  113. })
  114. it('does not submit a prompt when Hermes rejects the configured directory', async () => {
  115. const f = await fixture(); f.rejectCwd()
  116. const channel = await f.broker.create({ ...f.principal('alice'), configuredWorkingDirectory: async () => '/missing' }, 'chat')
  117. await f.broker.command(channel, 'resume', resume)
  118. const sent = await f.broker.command(channel, 'send', { method: 'prompt.submit', params: { session_id: 'runtime-1', text: 'run' } })
  119. expect(sent).toMatchObject({ state: 'rejected', response: { error: { code: 'working_directory_rejected' } } })
  120. expect(f.commands.some(x => x.method === 'prompt.submit')).toBe(false)
  121. })
  122. it('checks revocation again after loading the configured directory', async () => {
  123. const f = await fixture()
  124. let valid = true
  125. const channel = await f.broker.create({ ...f.principal('alice'), valid: () => valid,
  126. configuredWorkingDirectory: async () => { valid = false; return '/configured' } }, 'chat')
  127. await f.broker.command(channel, 'resume', resume)
  128. const sent = await f.broker.command(channel, 'send', { method: 'prompt.submit', params: { session_id: 'runtime-1', text: 'run' } })
  129. expect(sent).toMatchObject({ state: 'rejected', response: { error: { code: 'authentication_required' } } })
  130. expect(f.commands.map(x => x.method)).toEqual(['session.resume'])
  131. })
  132. it('rejects resuming a history-only session before opening an upstream route', async () => {
  133. const f = await fixture()
  134. const routes: string[] = []
  135. f.broker.onNativeRoute = (_owner, _profile, stored) => routes.push(stored)
  136. const principal = { ...f.principal('alice'), canResume: async () => false }
  137. const channel = await f.broker.create(principal, 'chat')
  138. const receipt = await f.broker.command(channel, 'history-resume', resume)
  139. expect(receipt).toMatchObject({ state: 'rejected', response: { error: { code: 'history_session_read_only' } } })
  140. expect(f.commands).toEqual([])
  141. expect(routes).toEqual([])
  142. })
  143. it('allows only a native Bots configured chat without claiming arbitrary history', async () => {
  144. const f = await fixture()
  145. const principal = {...f.principal('native:user:alice:1'), nativeBot:true, canResume:async()=>false}
  146. const channel = await f.broker.create(principal,'chat')
  147. expect(await f.broker.command(channel,'native-canonical',resume)).toMatchObject({state:'confirmed'})
  148. expect(await f.broker.command(channel,'wrong-profile',{...resume,params:{...resume.params,profile:'other'}}))
  149. .toMatchObject({state:'rejected',response:{error:{code:'history_session_read_only'}}})
  150. expect(await f.broker.command(channel,'arbitrary-history',{...resume,params:{...resume.params,session_id:'history-2'}}))
  151. .toMatchObject({state:'rejected',response:{error:{code:'history_session_read_only'}}})
  152. expect(f.commands.filter(c=>c.method==='session.resume')).toHaveLength(1)
  153. })
  154. it('registers and resumes sessions only within one stable device owner', async () => {
  155. const f = await fixture()
  156. const owned = new Set<string>()
  157. const commands: Array<{ owner: string; stored: string; method: string }> = []
  158. const events: Array<{ owner: string; stored: string; type: string }> = []
  159. const ownershipKey = (owner: string, profile: string, stored: string) =>
  160. `${owner}\u0000${profile}\u0000${stored}`
  161. f.broker.onNativeRoute = (owner, profile, stored) => {
  162. owned.add(ownershipKey(owner, profile, stored))
  163. }
  164. f.broker.onNativeCommand = (owner, _profile, stored, method) => {
  165. commands.push({ owner, stored, method })
  166. }
  167. f.broker.onNativeEvent = (owner, _profile, stored, frame) => {
  168. events.push({ owner, stored, type: String(frame.type) })
  169. }
  170. const device = (id: string): RealtimePrincipal => ({
  171. ...f.principal(`device:${id}`),
  172. upstreamKey: `device-service:${id}`,
  173. paired: true,
  174. canResume: async (profile, stored) =>
  175. owned.has(ownershipKey(`device:${id}`, profile, stored)),
  176. })
  177. const deviceA = device('device-a')
  178. const first = await f.broker.create(deviceA, 'chat')
  179. const created = await f.broker.command(first, 'device-create', {
  180. method: 'session.create', params: { profile: 'default', source: 'web' },
  181. })
  182. expect(created.state).toBe('confirmed')
  183. expect(owned).toContain(ownershipKey('device:device-a', 'default', 'stored-1'))
  184. expect(commands).toContainEqual({ owner: 'device:device-a', stored: 'stored-1', method: 'session.create' })
  185. f.emit('message.delta', { text: 'device event' })
  186. await vi.waitFor(() => expect(events).toContainEqual({
  187. owner: 'device:device-a', stored: 'stored-1', type: 'message.delta',
  188. }))
  189. const sameDevice = await f.broker.create(device('device-a'), 'chat')
  190. expect((await f.broker.command(sameDevice, 'same-device-resume', resume)).state).toBe('confirmed')
  191. const unowned = await f.broker.command(sameDevice, 'source-web-unowned', {
  192. method: 'session.resume', params: { session_id: 'unowned-source-web', profile: 'default' },
  193. })
  194. expect(unowned).toMatchObject({ state: 'rejected', response: { error: { code: 'history_session_read_only' } } })
  195. const anotherDevice = await f.broker.create(device('device-b'), 'chat')
  196. expect(await f.broker.command(anotherDevice, 'other-device-resume', resume))
  197. .toMatchObject({ state: 'rejected', response: { error: { code: 'history_session_read_only' } } })
  198. const user = {
  199. ...f.principal('user:alice:1'),
  200. upstreamKey: 'user-service',
  201. canResume: async (profile: string, stored: string) =>
  202. owned.has(ownershipKey('alice', profile, stored)),
  203. }
  204. const userChannel = await f.broker.create(user, 'chat')
  205. expect(await f.broker.command(userChannel, 'user-resume-device-session', resume))
  206. .toMatchObject({ state: 'rejected', response: { error: { code: 'history_session_read_only' } } })
  207. })
  208. it('broadcasts a route title as an owner-scoped session list change', async () => {
  209. const f = await fixture()
  210. const globalOwners: string[] = []
  211. f.broker.onNativeGlobalEvent = (owner, type) => {
  212. if (type === 'sessions.changed') globalOwners.push(owner)
  213. }
  214. const routedPrincipal = { ...f.principal('user:alice:1'), canResume: async () => true }
  215. const routed = await f.broker.create(routedPrincipal, 'chat')
  216. const listOnly = await f.broker.create(f.principal('user:alice:1'), 'chat')
  217. const anotherUser = await f.broker.create(f.principal('user:bob:1'), 'chat')
  218. await f.broker.command(routed, 'owner-title-route', resume)
  219. const listFrames: StreamEntry[] = []
  220. const otherFrames: StreamEntry[] = []
  221. f.broker.subscribe(listOnly, undefined, entry => listFrames.push(entry))
  222. f.broker.subscribe(anotherUser, undefined, entry => otherFrames.push(entry))
  223. f.emit('session.title', { session_id: 'stored-1', title: '跨端标题' })
  224. await vi.waitFor(() => expect(listFrames.some(entry =>
  225. entry.data.includes('sessions.changed'))).toBe(true))
  226. expect(otherFrames.some(entry => entry.data.includes('sessions.changed'))).toBe(false)
  227. expect(globalOwners).toEqual(['alice'])
  228. })
  229. it('preserves restricted create provenance and never forwards source on resume', async () => {
  230. const f = await fixture()
  231. const channel = await f.broker.create(f.principal('alice'), 'chat')
  232. await f.broker.command(channel, 'create-ios', {
  233. method: 'session.create', params: { profile: 'default', source: 'ios' },
  234. })
  235. await f.broker.command(channel, 'create-web-default', {
  236. method: 'session.create', params: { profile: 'default' },
  237. })
  238. await f.broker.command(channel, 'resume-with-client-source', {
  239. method: 'session.resume', params: { session_id: 'stored-1', profile: 'default', source: 'ios' },
  240. })
  241. const openFrames = f.commands.filter(frame => frame.method === 'session.create' || frame.method === 'session.resume')
  242. expect(openFrames[0]?.params.source).toBe('ios')
  243. expect(openFrames[1]?.params.source).toBe('web')
  244. expect(openFrames[2]?.params).not.toHaveProperty('source')
  245. expect(() => f.broker.command(channel, 'create-invalid-source', {
  246. method: 'session.create', params: { profile: 'default', source: 'telegram' },
  247. })).toThrow(/source must be web or ios/)
  248. })
  249. it('shares upstream across subscribers and isolates unregistered routes', async () => {
  250. const f = await fixture()
  251. const a = await f.broker.create(f.principal('alice'), 'chat')
  252. const b = await f.broker.create(f.principal('bob'), 'chat')
  253. const c = await f.broker.create(f.principal('alice'), 'chat')
  254. await f.broker.command(a, 'resume-a', resume)
  255. await f.broker.command(c, 'resume-c', resume)
  256. const seenA: StreamEntry[] = [], seenB: StreamEntry[] = [], seenC: StreamEntry[] = []
  257. f.broker.subscribe(a, undefined, x => seenA.push(x)); f.broker.subscribe(b, undefined, x => seenB.push(x)); f.broker.subscribe(c, undefined, x => seenC.push(x))
  258. f.emit('message.delta', { text: '你好' })
  259. await new Promise(r => setTimeout(r, 30))
  260. expect(f.count()).toBe(1)
  261. expect(seenA.some(x => x.data.includes('你好'))).toBe(true)
  262. expect(seenC.some(x => x.data.includes('你好'))).toBe(true)
  263. expect(seenB.some(x => x.data.includes('你好'))).toBe(false)
  264. expect(() => f.broker.get(f.principal('bob'), a.id)).toThrow('Channel not found')
  265. })
  266. it('deduplicates simultaneous commands and rejects a changed payload', async () => {
  267. const f = await fixture(), p = f.principal('alice')
  268. const c = await f.broker.create(p, 'chat')
  269. await f.broker.command(c, 'open', resume)
  270. const prompt = { method: 'prompt.submit', params: { session_id: 'runtime-1', text: 'secret prompt' } }
  271. const [one, two] = await Promise.all([f.broker.command(c, 'outbox-1', prompt), f.broker.command(c, 'outbox-1', prompt)])
  272. expect(one).toEqual(two); expect(one.state).toBe('confirmed')
  273. expect(f.commands.filter(x => x.method === 'prompt.submit')).toHaveLength(1)
  274. expect(() => f.broker.command(c, 'outbox-1', { ...prompt, params: { ...prompt.params, text: 'different' } })).toThrow('conflict')
  275. expect(() => f.broker.receipt(f.principal('bob'), 'outbox-1')).toThrow('Receipt not found')
  276. for (const file of ['realtime-receipts.sqlite3', 'realtime-receipts.sqlite3-wal']) expect(readFileSync(join(f.home, file)).includes(Buffer.from('secret prompt'))).toBe(false)
  277. })
  278. it('keeps upstream alive after downstream detach and replays exact cursor', async () => {
  279. const f = await fixture(), p = f.principal('alice')
  280. const c = await f.broker.create(p, 'chat')
  281. await f.broker.command(c, 'open', resume)
  282. const entries: StreamEntry[] = []
  283. const off = f.broker.subscribe(c, undefined, x => entries.push(x))
  284. const cursor = entries.at(-1)!.id
  285. off(); f.emit('message.start', {}); f.emit('message.delta', { text: 'background' })
  286. await new Promise(r => setTimeout(r, 30))
  287. const replay: StreamEntry[] = []
  288. f.broker.subscribe(c, cursor, x => replay.push(x))
  289. expect(replay).toHaveLength(2); expect(f.count()).toBe(1)
  290. f.advance(600_001)
  291. expect(() => f.broker.subscribe(c, cursor, () => {})).toThrow('Replay window expired')
  292. })
  293. it('does not execute runtime commands without a route subscription', async () => {
  294. const f = await fixture()
  295. const c = await f.broker.create(f.principal('alice'), 'chat')
  296. const result = await f.broker.command(c, 'forbidden', { method: 'session.interrupt', params: { session_id: 'guessed' } })
  297. expect(result.state).toBe('rejected'); expect(f.commands).toHaveLength(0)
  298. })
  299. it('marks write-ahead admissions unknown after a process restart', () => {
  300. const home = mkdtempSync(join(tmpdir(), 'yaoyao-receipts-test-'))
  301. const a = new RealtimeReceipts(home)
  302. a.reserve('alice', 'submitted', '{"text":"private"}'); a.close()
  303. const b = new RealtimeReceipts(home)
  304. expect(b.reserve('alice', 'submitted', '{"text":"private"}')).toMatchObject({ state: 'unknown' })
  305. b.close()
  306. })
  307. it('registers branch identities without losing the original subscription', async () => {
  308. const f = await fixture()
  309. const ownershipCommands: Array<{ owner: string; stored: string; method: string }> = []
  310. f.broker.onNativeCommand = (owner, _profile, stored, method) => {
  311. ownershipCommands.push({ owner, stored, method })
  312. }
  313. const c = await f.broker.create(f.principal('user:alice:1'), 'chat')
  314. await f.broker.command(c, 'open', resume)
  315. const branch = await f.broker.command(c, 'branch', { method: 'session.branch', params: { session_id: 'runtime-1' } })
  316. expect(branch.state).toBe('confirmed')
  317. const sent = await f.broker.command(c, 'branched-prompt', { method: 'prompt.submit', params: { session_id: 'runtime-branch', text: 'branch' } })
  318. expect(sent.state).toBe('confirmed')
  319. expect(c.routes.size).toBe(2)
  320. expect(ownershipCommands).toContainEqual({ owner: 'alice', stored: 'stored-branch', method: 'session.branch' })
  321. })
  322. it('does not let guessed approval IDs escape a subscribed session', async () => {
  323. const f = await fixture(), c = await f.broker.create(f.principal('alice'), 'chat')
  324. await f.broker.command(c, 'open', resume)
  325. const result = await f.broker.command(c, 'approval', { method: 'approval.respond', params: { session_id: 'runtime-1', request_id: 'another-users-approval', approved: true } })
  326. expect(result).toMatchObject({ state: 'rejected', response: { error: { code: 'interaction_forbidden' } } })
  327. expect(f.commands.filter(x => x.method === 'approval.respond')).toHaveLength(0)
  328. })
  329. it('page reloads cannot exhaust live-stream capacity with detached handles', async () => {
  330. const f = await fixture(), p = f.principal('alice')
  331. for (let i = 0; i < 40; i++) await f.broker.create(p, 'chat')
  332. expect(f.broker.channels.size).toBe(32)
  333. expect(f.count()).toBe(1)
  334. })
  335. it('recovers the upstream replay ring without losing offline deltas', async () => {
  336. const f = await fixture(), c = await f.broker.create(f.principal('alice'), 'chat')
  337. await f.broker.command(c, 'open', resume)
  338. const received: StreamEntry[] = []
  339. f.broker.subscribe(c, undefined, e => received.push(e))
  340. f.emit('message.delta', { text: 'before' })
  341. await vi.waitFor(() => expect(received.some(e => e.data.includes('before'))).toBe(true))
  342. f.disconnect(); f.emit('message.delta', { text: 'offline' })
  343. await vi.waitFor(() => expect(received.filter(e => e.data.includes('offline'))).toHaveLength(1), { timeout: 2500 })
  344. expect(f.count()).toBe(2)
  345. expect(received.filter(e => e.event === 'reset')).toHaveLength(0)
  346. })
  347. it('reports reset when upstream history was truncated', async () => {
  348. const f = await fixture(), c = await f.broker.create(f.principal('alice'), 'chat')
  349. await f.broker.command(c, 'open', resume)
  350. const received: StreamEntry[] = []
  351. f.broker.subscribe(c, undefined, e => received.push(e))
  352. f.truncate(); f.disconnect()
  353. await vi.waitFor(() => expect(received.some(e => e.event === 'reset')).toBe(true), { timeout: 2500 })
  354. })
  355. it('never repeats a prompt when the upstream acceptance reply is lost', async () => {
  356. const f = await fixture(), c = await f.broker.create(f.principal('alice'), 'chat')
  357. await f.broker.command(c, 'open', resume)
  358. f.dropPrompt()
  359. const prompt = { method: 'prompt.submit', params: { session_id: 'runtime-1', text: 'do once' } }
  360. const result = await f.broker.command(c, 'lost-ack', prompt)
  361. expect(result.state).toBe('unknown')
  362. expect((await f.broker.command(c, 'lost-ack', prompt)).state).toBe('unknown')
  363. expect(f.commands.filter(f => f.method === 'prompt.submit')).toHaveLength(1)
  364. })
  365. it('invalidates read snapshots before/after mutation and before delivering live events', async () => {
  366. const f = await fixture(), c = await f.broker.create(f.principal('alice'), 'chat')
  367. await f.broker.command(c, 'open', resume)
  368. await f.broker.command(c, 'send', { method: 'prompt.submit', params: { session_id: 'runtime-1', text: 'once' } })
  369. expect(f.activities.filter(c => c.kind === 'command' && c.name === 'prompt.submit')).toEqual([
  370. { kind: 'command', name: 'prompt.submit', sessionId: 'stored-1' },
  371. { kind: 'command', name: 'prompt.submit', sessionId: 'stored-1' },
  372. ])
  373. const seen: StreamEntry[] = []
  374. f.broker.subscribe(c, undefined, entry => {
  375. if (entry.data.includes('message.delta')) expect(f.activities.at(-1)).toMatchObject({ kind: 'event', name: 'message.delta', sessionId: 'stored-1' })
  376. seen.push(entry)
  377. })
  378. f.emit('message.delta', { text: 'fresh' })
  379. await vi.waitFor(() => expect(seen.some(e => e.data.includes('fresh'))).toBe(true))
  380. })
  381. })