fixture.spec.ts 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697
  1. /**
  2. * Fixture impl semantics: the demo data source must honor the same contract
  3. * shapes as the real host (paging boundaries, rpcId echo, replay lifecycle,
  4. * baseline replay, timing hooks) — this is the vitest-side drift detector for
  5. * the hand-written fixture/host parallel implementations.
  6. */
  7. import { afterEach, describe, expect, it, vi } from 'vitest'
  8. import type { SessionId, WorkspaceId } from '../src/client/api.ts'
  9. import { RpcId } from '../src/client/api.ts'
  10. import type { HostFrame, MuxFrame, RpcMessage, RpcRequest } from '../src/client/api.ts'
  11. import { FixtureApiClient, createFixtureApi } from '../src/client/fixture.ts'
  12. const sid = (id: string): SessionId => id as SessionId
  13. const req = <P>(payload: P): RpcRequest<P> => ({ rpcId: RpcId(`t-${Math.abs(Math.sin(reqCount++)).toString(36).slice(2, 10)}`), payload })
  14. let reqCount = 0
  15. interface TimingHooks {
  16. setHistoryDelay(ms: number): void
  17. failNextHistory(): void
  18. appendUser(id: string, msg: string): void
  19. appendTitle(id: string, title: string): void
  20. appendSilent(id: string, msg: string): void
  21. breakStreams(): void
  22. }
  23. const timing = (): TimingHooks => (globalThis as Record<string, unknown>).__fxTiming as TimingHooks
  24. /** Collect stream frames until the predicate or a soft cap; abort ends the stream. */
  25. async function collect<F>(stream: AsyncIterable<RpcRequest<F>>, abort: AbortController, done: (frames: F[]) => boolean): Promise<F[]> {
  26. const frames: F[] = []
  27. for await (const envelope of stream) {
  28. frames.push(envelope.payload)
  29. if (done(frames) || frames.length > 500) {
  30. abort.abort()
  31. break
  32. }
  33. }
  34. return frames
  35. }
  36. describe('createFixtureApi', () => {
  37. it('serves the session list sorted by updatedAt desc and echoes rpcIds on every unary', async () => {
  38. const api = createFixtureApi()
  39. const request = req({})
  40. const response = await api.sessions.list(request)
  41. expect(response.rpcId).toBe(request.rpcId)
  42. if (!response.result.ok) throw new Error('list failed')
  43. expect(response.result.value.items.map(s => s.sessionId)).toEqual(['fx-alpha', 'fx-beta', 'fx-gamma'])
  44. expect(response.result.value.items[1]?.parentSessionId).toBe('fx-alpha') // lineage material
  45. })
  46. it('pages history backwards on message-boundary cuts with seq-contiguous stitching', async () => {
  47. const api = createFixtureApi()
  48. const tail = await api.sessions.history(req({ sessionId: sid('fx-alpha'), maxMessages: 10 }))
  49. if (!tail.result.ok) throw new Error('history failed')
  50. const tailPage = tail.result.value
  51. expect(tailPage.hasMore).toBe(true)
  52. expect(tailPage.events[0]?.event.type).toBe('turn/start') // cut lands on a turn boundary
  53. const boundary = tailPage.events[0]?.event.seq ?? 0
  54. expect(boundary).toBeGreaterThan(0)
  55. const older = await api.sessions.history(req({ sessionId: sid('fx-alpha'), beforeSeq: boundary, maxMessages: 10 }))
  56. if (!older.result.ok) throw new Error('older failed')
  57. const olderTail = older.result.value.events.at(-1)?.event
  58. expect((olderTail?.seq ?? -1) + 1).toBe(boundary) // pages stitch with no hole/overlap
  59. // Out-of-range beforeSeq clamps instead of exploding.
  60. const clamped = await api.sessions.history(req({ sessionId: sid('fx-alpha'), beforeSeq: -5, maxMessages: 10 }))
  61. if (!clamped.result.ok) throw new Error('clamped failed')
  62. expect(clamped.result.value.events).toEqual([])
  63. // Unknown session: empty page, not an error (history of a bare id).
  64. const empty = await api.sessions.history(req({ sessionId: sid('no-such'), maxMessages: 10 }))
  65. if (!empty.result.ok) throw new Error('empty failed')
  66. expect(empty.result.value).toEqual({ events: [], hasMore: false })
  67. })
  68. it('create adds a session and pushes host/session-added to open host streams', async () => {
  69. const api = createFixtureApi()
  70. const abort = new AbortController()
  71. const seen: HostFrame[] = []
  72. const consuming = (async () => {
  73. for await (const envelope of api.events.host(req({}), abort.signal)) {
  74. seen.push(envelope.payload)
  75. if (seen.length >= 1) abort.abort()
  76. }
  77. })()
  78. await new Promise(resolve => setTimeout(resolve, 10)) // let the stream register
  79. const created = await api.sessions.create(req({}))
  80. if (!created.result.ok) throw new Error('create failed')
  81. await consuming
  82. if (!created.result.ok) throw new Error('create failed')
  83. const createdId = created.result.value.sessionId
  84. expect(seen).toEqual([{ type: 'host/session-added', sessionId: createdId, cwd: '/tmp/fixture' }])
  85. const list = await api.sessions.list(req({}))
  86. if (!list.result.ok) throw new Error('list failed')
  87. expect(list.result.value.items.some(s => s.sessionId === createdId)).toBe(true)
  88. })
  89. it('prompt replays a full streamed turn and cancel mid-replay freezes with (已中断)', async () => {
  90. const api = createFixtureApi()
  91. const created = await api.sessions.create(req({}))
  92. if (!created.result.ok) throw new Error('create failed')
  93. const id = created.result.value.sessionId
  94. const abort = new AbortController()
  95. const frames: MuxFrame[] = []
  96. const consuming = (async () => {
  97. for await (const envelope of api.events.mux(req({}), abort.signal)) {
  98. frames.push(envelope.payload)
  99. const last = envelope.payload
  100. if (last.type === 'session/event' && last.event.type === 'turn/end') {
  101. abort.abort()
  102. }
  103. }
  104. })()
  105. await new Promise(resolve => setTimeout(resolve, 10))
  106. // Unknown session → session-not-found with the id echoed in details.
  107. const missing = await api.sessions.prompt(req({ sessionId: sid('ghost'), mode: 'queue' as const, content: [{ type: 'text' as const, text: 'x' }] }))
  108. expect(missing.result).toMatchObject({ ok: false, error: { code: 'session-not-found', details: { sessionId: 'ghost' } } })
  109. // Real prompt: replay starts (running flips true), cancel freezes it.
  110. const accepted = await api.sessions.prompt(req({ sessionId: id, mode: 'queue' as const, content: [{ type: 'text' as const, text: 'render markdown' }] }))
  111. expect(accepted.result).toMatchObject({ ok: true, value: { accepted: true } })
  112. await new Promise(resolve => setTimeout(resolve, 120)) // a couple of typewriter ticks
  113. await api.sessions.cancel(req({ sessionId: id }))
  114. await consuming
  115. const types = frames.filter((f): f is Extract<MuxFrame, { type: 'session/event' }> => f.type === 'session/event').map(f => f.event.type)
  116. expect(types).toContain('turn/start')
  117. expect(types).toContain('user/message')
  118. expect(types).toContain('assistant/chunk')
  119. expect(types).toContain('assistant/message')
  120. expect(types.at(-1)).toBe('turn/end')
  121. const finalize = frames.find((f): f is Extract<MuxFrame, { type: 'session/event' }> => f.type === 'session/event' && f.event.type === 'assistant/message')
  122. expect(JSON.stringify(finalize?.event.data)).toContain('(已中断)')
  123. // Idle cancel: no replay in flight, must not explode; running flips false.
  124. const idleCancel = await api.sessions.cancel(req({ sessionId: id }))
  125. expect(idleCancel.result).toMatchObject({ ok: true })
  126. })
  127. it('steer during a replay inserts a steering message and the replay continues to completion', async () => {
  128. const api = createFixtureApi()
  129. const created = await api.sessions.create(req({}))
  130. if (!created.result.ok) throw new Error('create failed')
  131. const id = created.result.value.sessionId
  132. const abort = new AbortController()
  133. const framesPromise = collect<MuxFrame>(api.events.mux(req({}), abort.signal), abort,
  134. frames => frames.some(f => f.type === 'session/event' && f.event.type === 'turn/end'))
  135. await new Promise(resolve => setTimeout(resolve, 10))
  136. await api.sessions.prompt(req({ sessionId: id, mode: 'queue' as const, content: [{ type: 'text' as const, text: '短' }] }))
  137. await api.sessions.prompt(req({ sessionId: id, mode: 'steer' as const, content: [{ type: 'text' as const, text: '插话' }] }))
  138. const frames = await framesPromise
  139. const types = frames.filter((f): f is Extract<MuxFrame, { type: 'session/event' }> => f.type === 'session/event').map(f => f.event.type)
  140. expect(types).toContain('steering/message')
  141. expect(types.at(-1)).toBe('turn/end') // steer did not restart the turn
  142. })
  143. it('mux open replays subscribed sessions and resident interactions with stable rpcIds', async () => {
  144. const api = createFixtureApi()
  145. const openOnce = async (): Promise<RpcRequest<MuxFrame>[]> => {
  146. const abort = new AbortController()
  147. const envelopes: RpcRequest<MuxFrame>[] = []
  148. for await (const envelope of api.events.mux(req({}), abort.signal)) {
  149. envelopes.push(envelope)
  150. if (envelopes.length >= 4) abort.abort()
  151. }
  152. return envelopes
  153. }
  154. const first = await openOnce()
  155. const second = await openOnce()
  156. expect(first[0]?.payload).toMatchObject({ type: 'session/subscribed', sessionId: 'fx-alpha' })
  157. expect((first[0]?.payload as { lastSeq: number }).lastSeq).toBeGreaterThan(0)
  158. expect(first[1]?.payload).toMatchObject({ type: 'session/title', sessionId: 'fx-alpha', title: 'Fixture 历史会话' })
  159. expect(first[2]?.payload).toMatchObject({ type: 'approval/requested', toolName: 'dangerous_tool' })
  160. expect(second[2]?.rpcId).toBe(first[2]?.rpcId) // stable rpcId across replays (host replay semantics)
  161. expect(first[3]?.payload).toMatchObject({ type: 'question/requested', sessionId: 'fx-alpha' })
  162. expect(second[3]?.rpcId).toBe(first[3]?.rpcId)
  163. })
  164. it('steer with no replay in flight falls through to a fresh queued turn; non-text blocks stringify empty', async () => {
  165. const api = createFixtureApi()
  166. const abort = new AbortController()
  167. const framesPromise = collect<MuxFrame>(api.events.mux(req({}), abort.signal), abort,
  168. frames => frames.some(f => f.type === 'session/event' && f.event.type === 'turn/end'))
  169. await new Promise(resolve => setTimeout(resolve, 10))
  170. const created = await api.sessions.create(req({}))
  171. if (!created.result.ok) throw new Error('create failed')
  172. // steer while idle + a non-text content block (covers the '' arm of the text join).
  173. await api.sessions.prompt(req({
  174. sessionId: created.result.value.sessionId, mode: 'steer' as const,
  175. content: [{ type: 'text' as const, text: '短' }, { type: 'image', data: 'x' } as never],
  176. }))
  177. const frames = await framesPromise
  178. const types = frames.filter((f): f is Extract<MuxFrame, { type: 'session/event' }> => f.type === 'session/event').map(f => f.event.type)
  179. expect(types[0]).toBe('turn/start') // idle steer degraded to a queued turn, not a steering insert
  180. })
  181. it('gamma interval flip emits host/session-status and a running log-less session subscribes at lastSeq -1', async () => {
  182. vi.useFakeTimers()
  183. try {
  184. const api = createFixtureApi()
  185. const abort = new AbortController()
  186. const hostSeen: HostFrame[] = []
  187. const consuming = (async () => {
  188. for await (const envelope of api.events.host(req({}), abort.signal)) hostSeen.push(envelope.payload)
  189. })()
  190. await vi.advanceTimersByTimeAsync(5001) // interval fires: fx-gamma flips running=true (no log exists)
  191. expect(hostSeen).toContainEqual({ type: 'host/session-status', sessionId: sid('fx-gamma'), running: true })
  192. // A mux stream opened now sees gamma in the baseline with lastSeq = -1 (empty log arm).
  193. const mabort = new AbortController()
  194. const baseline: MuxFrame[] = []
  195. const muxConsuming = (async () => {
  196. for await (const envelope of api.events.mux(req({}), mabort.signal)) {
  197. baseline.push(envelope.payload)
  198. if (baseline.length >= 3) mabort.abort()
  199. }
  200. })()
  201. await vi.advanceTimersByTimeAsync(10)
  202. mabort.abort()
  203. await muxConsuming
  204. expect(baseline).toContainEqual({ type: 'session/subscribed', sessionId: sid('fx-gamma'), lastSeq: -1 })
  205. abort.abort()
  206. await vi.advanceTimersByTimeAsync(10)
  207. await consuming
  208. } finally {
  209. vi.useRealTimers()
  210. }
  211. })
  212. it('respond resolves the resident question once and rejects duplicate or unrelated ids', async () => {
  213. const api = createFixtureApi()
  214. expect(await api.respond({ type: 'client-response', rpcId: RpcId('x'), result: { ok: true, value: {} } })).toEqual({ accepted: false, reason: 'not-pending' })
  215. const abort = new AbortController()
  216. let question: RpcRequest<MuxFrame> | undefined
  217. for await (const envelope of api.events.mux(req({}), abort.signal)) {
  218. if (envelope.payload.type !== 'question/requested') continue
  219. question = envelope
  220. abort.abort()
  221. }
  222. if (question === undefined) throw new Error('fixture question missing')
  223. const response = { type: 'client-response' as const, rpcId: question.rpcId, result: { ok: true as const, value: {} } }
  224. expect(await api.respond(response)).toEqual({ accepted: true })
  225. expect(await api.respond(response)).toEqual({ accepted: false, reason: 'not-pending' })
  226. const replayAbort = new AbortController()
  227. const replayed = await collect(api.events.mux(req({}), replayAbort.signal), replayAbort, frames => frames.length === 2)
  228. expect(replayed.every(frame => frame.type !== 'question/requested')).toBe(true)
  229. const cancelledApi = createFixtureApi()
  230. const cancelAbort = new AbortController()
  231. let cancelQuestion: RpcRequest<MuxFrame> | undefined
  232. for await (const envelope of cancelledApi.events.mux(req({}), cancelAbort.signal)) {
  233. if (envelope.payload.type !== 'question/requested') continue
  234. cancelQuestion = envelope
  235. cancelAbort.abort()
  236. }
  237. if (cancelQuestion === undefined) throw new Error('fixture cancellation question missing')
  238. expect(await cancelledApi.respond({
  239. type: 'client-response', rpcId: cancelQuestion.rpcId,
  240. result: { ok: false, error: { code: 'cancelled', message: 'skip', details: {} } },
  241. })).toEqual({ accepted: true })
  242. })
  243. it('describe answers the fixture identity', async () => {
  244. const api = createFixtureApi()
  245. const response = await api.host.describe(req({}))
  246. expect(response.result).toMatchObject({ ok: true, value: { version: '0.0.0-fixture', attachedSessions: 1 } })
  247. const empty = await createFixtureApi({ empty: true }).host.describe(req({}))
  248. expect(empty.result).toMatchObject({ ok: true, value: { attachedSessions: 0 } })
  249. })
  250. it('workspace.list serves the resident account and create reuses on path collision', async () => {
  251. const api = createFixtureApi()
  252. const listed = await api.workspace.list(req({}))
  253. if (!listed.result.ok) throw new Error('list failed')
  254. expect(listed.result.value.items).toEqual([expect.objectContaining({
  255. workspaceId: 'fx-ws-fixture', path: '/tmp/fixture', title: 'fixture',
  256. sessionIds: ['fx-alpha', 'fx-beta', 'fx-gamma'],
  257. })])
  258. // path collision → the existing entity comes back, created:false, no frame.
  259. const reused = await api.workspace.create(req({ path: '/tmp/fixture' }))
  260. if (!reused.result.ok) throw new Error('reuse failed')
  261. expect(reused.result.value).toMatchObject({ created: false, workspace: { workspaceId: 'fx-ws-fixture' } })
  262. })
  263. it('workspace.create by name mints a new entity and pushes host/workspace-changed', async () => {
  264. const api = createFixtureApi()
  265. const abort = new AbortController()
  266. const seen: HostFrame[] = []
  267. const consuming = (async () => {
  268. for await (const envelope of api.events.host(req({}), abort.signal)) {
  269. seen.push(envelope.payload)
  270. abort.abort()
  271. }
  272. })()
  273. await new Promise(resolve => setTimeout(resolve, 10))
  274. const created = await api.workspace.create(req({ name: 'nova' }))
  275. if (!created.result.ok) throw new Error('create failed')
  276. expect(created.result.value.created).toBe(true)
  277. expect(created.result.value.workspace).toMatchObject({
  278. path: '/tmp/fixture-workspaces/nova', title: 'nova', sessionIds: [],
  279. })
  280. await consuming
  281. expect(seen).toEqual([{ type: 'host/workspace-changed', workspace: created.result.value.workspace }])
  282. // path spelling falls back to the basename when no title/name rides along.
  283. const pathOnly = await api.workspace.create(req({ path: '/tmp/fixture-elsewhere/base' }))
  284. if (!pathOnly.result.ok) throw new Error('pathOnly failed')
  285. expect(pathOnly.result.value.workspace.title).toBe('base')
  286. // Degenerate spellings reach the impl unfiltered (the fixture carrier has
  287. // no schema gate): both-absent falls back to the bucket dir, and a
  288. // basename-less path serves as its own title.
  289. const bare = await api.workspace.create(req({}))
  290. if (!bare.result.ok) throw new Error('bare failed')
  291. expect(bare.result.value.workspace).toMatchObject({ path: '/tmp/fixture-workspaces/', title: 'fixture-workspaces' })
  292. const rootPath = await api.workspace.create(req({ path: '/' }))
  293. if (!rootPath.result.ok) throw new Error('rootPath failed')
  294. expect(rootPath.result.value.workspace.title).toBe('/')
  295. })
  296. it('workspace.rename covers not-found, conflict, no-op, and the changed frame', async () => {
  297. const api = createFixtureApi()
  298. const abort = new AbortController()
  299. const seen: HostFrame[] = []
  300. const consuming = (async () => {
  301. for await (const envelope of api.events.host(req({}), abort.signal)) {
  302. seen.push(envelope.payload)
  303. if (seen.length >= 2) abort.abort()
  304. }
  305. })()
  306. await new Promise(resolve => setTimeout(resolve, 10))
  307. const wsid = 'fx-ws-fixture' as WorkspaceId
  308. const missing = await api.workspace.rename(req({ workspaceId: 'fx-ws-void' as WorkspaceId, title: 'x' }))
  309. expect(missing.result).toMatchObject({ ok: false, error: { code: 'workspace-not-found', details: { workspaceId: 'fx-ws-void' } } })
  310. await api.workspace.create(req({ name: 'occupied' }))
  311. const conflict = await api.workspace.rename(req({ workspaceId: wsid, title: ' occupied ' }))
  312. expect(conflict.result).toMatchObject({ ok: false, error: { code: 'workspace-name-conflict', details: { name: 'occupied' } } })
  313. const noop = await api.workspace.rename(req({ workspaceId: wsid, title: ' fixture ' }))
  314. if (!noop.result.ok) throw new Error('no-op rename failed')
  315. expect(noop.result.value.workspace.title).toBe('fixture')
  316. const renamed = await api.workspace.rename(req({ workspaceId: wsid, title: 'renamed' }))
  317. if (!renamed.result.ok) throw new Error('rename failed')
  318. expect(renamed.result.value.workspace.title).toBe('renamed')
  319. await consuming
  320. // Only the create and the effective rename emit frames; the no-op stays silent.
  321. expect(seen.map(f => f.type)).toEqual(['host/workspace-changed', 'host/workspace-changed'])
  322. })
  323. it('workspace.insertSessionBefore moves, appends, no-ops, and rejects invalid ids', async () => {
  324. const api = createFixtureApi()
  325. const wsid = 'fx-ws-fixture' as WorkspaceId
  326. const missing = await api.workspace.insertSessionBefore(req({ workspaceId: 'fx-ws-void' as WorkspaceId, sessionId: sid('fx-alpha') }))
  327. expect(missing.result).toMatchObject({ ok: false, error: { code: 'workspace-not-found' } })
  328. const ghost = await api.workspace.insertSessionBefore(req({ workspaceId: wsid, sessionId: sid('fx-ghost') }))
  329. expect(ghost.result).toMatchObject({ ok: false, error: { code: 'workspace-move-invalid', details: { sessionId: 'fx-ghost' } } })
  330. const badAnchor = await api.workspace.insertSessionBefore(req({ workspaceId: wsid, sessionId: sid('fx-alpha'), beforeSessionId: sid('fx-ghost') }))
  331. expect(badAnchor.result).toMatchObject({ ok: false, error: { code: 'workspace-move-invalid', details: { beforeSessionId: 'fx-ghost' } } })
  332. const moved = await api.workspace.insertSessionBefore(req({ workspaceId: wsid, sessionId: sid('fx-gamma'), beforeSessionId: sid('fx-beta') }))
  333. if (!moved.result.ok) throw new Error('move failed')
  334. expect(moved.result.value.workspace.sessionIds).toEqual(['fx-alpha', 'fx-gamma', 'fx-beta'])
  335. const appended = await api.workspace.insertSessionBefore(req({ workspaceId: wsid, sessionId: sid('fx-alpha') }))
  336. if (!appended.result.ok) throw new Error('append failed')
  337. expect(appended.result.value.workspace.sessionIds).toEqual(['fx-gamma', 'fx-beta', 'fx-alpha'])
  338. const before = appended.result.value.workspace.updatedAt
  339. const noop = await api.workspace.insertSessionBefore(req({ workspaceId: wsid, sessionId: sid('fx-alpha') }))
  340. if (!noop.result.ok) throw new Error('no-op move failed')
  341. expect(noop.result.value.workspace.sessionIds).toEqual(['fx-gamma', 'fx-beta', 'fx-alpha'])
  342. expect(noop.result.value.workspace.updatedAt).toBe(before)
  343. })
  344. it('session.create({workspaceId}) lands on the account and unknown ids error', async () => {
  345. const api = createFixtureApi()
  346. const abort = new AbortController()
  347. const seen: HostFrame[] = []
  348. const consuming = (async () => {
  349. for await (const envelope of api.events.host(req({}), abort.signal)) {
  350. seen.push(envelope.payload)
  351. if (seen.length >= 2) abort.abort()
  352. }
  353. })()
  354. await new Promise(resolve => setTimeout(resolve, 10))
  355. const missing = await api.sessions.create(req({ workspaceId: 'fx-ws-void' as WorkspaceId }))
  356. expect(missing.result).toMatchObject({ ok: false, error: { code: 'workspace-not-found', details: { workspaceId: 'fx-ws-void' } } })
  357. const created = await api.sessions.create(req({ workspaceId: 'fx-ws-fixture' as WorkspaceId }))
  358. if (!created.result.ok) throw new Error('create failed')
  359. const id = created.result.value.sessionId
  360. await consuming
  361. // The session lands with the workspace's path as cwd, and the account
  362. // write pushes the fresh workspace snapshot after session-added.
  363. expect(seen[0]).toEqual({ type: 'host/session-added', sessionId: id, cwd: '/tmp/fixture' })
  364. expect(seen[1]).toMatchObject({
  365. type: 'host/workspace-changed',
  366. workspace: { workspaceId: 'fx-ws-fixture', sessionIds: [id, 'fx-alpha', 'fx-beta', 'fx-gamma'] },
  367. })
  368. })
  369. it('supports an empty baseline, preallocated ids, workspace-first frames, and idempotent retry', async () => {
  370. const api = createFixtureApi({ empty: true, createFrameOrder: 'workspace-first' })
  371. const initialSessions = await api.sessions.list(req({}))
  372. const initialWorkspaces = await api.workspace.list(req({}))
  373. expect(initialSessions.result).toMatchObject({ ok: true, value: { items: [] } })
  374. expect(initialWorkspaces.result).toMatchObject({ ok: true, value: { items: [] } })
  375. const made = await api.workspace.create(req({ name: 'nova' }))
  376. if (!made.result.ok) throw new Error('workspace create failed')
  377. const abort = new AbortController()
  378. const framesPromise = collect(api.events.host(req({}), abort.signal), abort, frames => frames.length === 2)
  379. await new Promise(resolve => setTimeout(resolve, 10))
  380. const preallocated = sid('fx-preallocated')
  381. const created = await api.sessions.create(req({
  382. workspaceId: made.result.value.workspace.workspaceId,
  383. sessionId: preallocated,
  384. }))
  385. expect(created.result).toEqual({ ok: true, value: { sessionId: preallocated } })
  386. const frames = await framesPromise
  387. expect(frames[0]).toMatchObject({
  388. type: 'host/workspace-changed', workspace: { sessionIds: [preallocated] },
  389. })
  390. expect(frames[1]).toEqual({ type: 'host/session-added', sessionId: preallocated, cwd: made.result.value.workspace.path })
  391. const retried = await api.sessions.create(req({
  392. workspaceId: made.result.value.workspace.workspaceId,
  393. sessionId: preallocated,
  394. }))
  395. expect(retried.result).toEqual({ ok: true, value: { sessionId: preallocated } })
  396. const listed = await api.sessions.list(req({}))
  397. if (!listed.result.ok) throw new Error('session list failed')
  398. expect(listed.result.value.items.filter(item => item.sessionId === preallocated)).toHaveLength(1)
  399. const conflict = await api.sessions.create(req({ sessionId: preallocated, cwd: '/elsewhere' }))
  400. expect(conflict.result).toMatchObject({
  401. ok: false,
  402. error: { code: 'session-conflict', details: { sessionId: preallocated, requestedCwd: '/elsewhere' } },
  403. })
  404. })
  405. it('attaches an existing ungrouped Session to a matching Workspace', async () => {
  406. const api = createFixtureApi()
  407. const sessionId = sid('fx-existing-ungrouped')
  408. await expect(api.sessions.create(req({ sessionId, cwd: '/tmp/fixture' }))).resolves.toMatchObject({
  409. result: { ok: true, value: { sessionId } },
  410. })
  411. await expect(api.sessions.create(req({
  412. sessionId,
  413. workspaceId: 'fx-ws-fixture' as WorkspaceId,
  414. }))).resolves.toMatchObject({ result: { ok: true, value: { sessionId } } })
  415. const workspaces = await api.workspace.list(req({}))
  416. if (!workspaces.result.ok) throw new Error('workspace list failed')
  417. expect(workspaces.result.value.items[0]?.sessionIds).toContain(sessionId)
  418. })
  419. it('reports a conflict without an existing cwd detail for an unrecorded cwd', async () => {
  420. const api = createFixtureApi()
  421. const listed = await api.sessions.list(req({}))
  422. if (!listed.result.ok) throw new Error('session list failed')
  423. const existing = listed.result.value.items.find(item => item.sessionId === sid('fx-alpha'))
  424. if (existing === undefined) throw new Error('fixture Session missing')
  425. delete existing.cwd
  426. const conflict = await api.sessions.create(req({ sessionId: existing.sessionId }))
  427. expect(conflict.result).toEqual({
  428. ok: false,
  429. error: {
  430. code: 'session-conflict',
  431. message: `session ${existing.sessionId} already uses no cwd`,
  432. details: { sessionId: existing.sessionId, requestedCwd: '/tmp/fixture' },
  433. },
  434. })
  435. })
  436. it('publishes an ungrouped Session when Workspace attachment fails', async () => {
  437. const api = createFixtureApi({ failWorkspaceAttach: true })
  438. const sessionId = sid('fx-partial')
  439. const created = await api.sessions.create(req({
  440. workspaceId: 'fx-ws-fixture' as WorkspaceId,
  441. sessionId,
  442. }))
  443. expect(created.result).toMatchObject({
  444. ok: false,
  445. error: { code: 'workspace-attach-failed', details: { sessionId, workspaceId: 'fx-ws-fixture' } },
  446. })
  447. const listed = await api.sessions.list(req({}))
  448. const workspaces = await api.workspace.list(req({}))
  449. if (!listed.result.ok || !workspaces.result.ok) throw new Error('list failed')
  450. expect(listed.result.value.items.filter(item => item.sessionId === sessionId)).toHaveLength(1)
  451. expect(workspaces.result.value.items[0]?.sessionIds).not.toContain(sessionId)
  452. const retried = await api.sessions.create(req({
  453. workspaceId: 'fx-ws-fixture' as WorkspaceId,
  454. sessionId,
  455. }))
  456. expect(retried.result).toMatchObject({ ok: false, error: { code: 'workspace-attach-failed' } })
  457. const afterRetry = await api.sessions.list(req({}))
  458. if (!afterRetry.result.ok) throw new Error('list failed')
  459. expect(afterRetry.result.value.items.filter(item => item.sessionId === sessionId)).toHaveLength(1)
  460. })
  461. it('reconciles a dropped create response and can reject a prompt before acceptance', async () => {
  462. const sessionId = sid('fx-lost-response')
  463. const dropped = createFixtureApi({ dropSessionCreateResponse: true })
  464. await expect(Promise.resolve().then(() => dropped.sessions.create(req({
  465. workspaceId: 'fx-ws-fixture' as WorkspaceId,
  466. sessionId,
  467. })))).rejects.toThrow(/dropped session\.create response/)
  468. const listed = await dropped.sessions.list(req({}))
  469. const workspaces = await dropped.workspace.list(req({}))
  470. if (!listed.result.ok || !workspaces.result.ok) throw new Error('list failed')
  471. expect(listed.result.value.items.some(item => item.sessionId === sessionId)).toBe(true)
  472. expect(workspaces.result.value.items[0]?.sessionIds).toContain(sessionId)
  473. await expect(dropped.sessions.create(req({
  474. workspaceId: 'fx-ws-fixture' as WorkspaceId,
  475. sessionId,
  476. }))).resolves.toMatchObject({ result: { ok: true, value: { sessionId } } })
  477. const rejecting = createFixtureApi({ empty: true, rejectPrompt: true })
  478. const real = await rejecting.sessions.create(req({ sessionId: sid('fx-rejected') }))
  479. if (!real.result.ok) throw new Error('session create failed')
  480. const prompt = await rejecting.sessions.prompt(req({
  481. sessionId: real.result.value.sessionId,
  482. mode: 'queue' as const,
  483. content: [{ type: 'text' as const, text: 'keep me' }],
  484. }))
  485. expect(prompt.result).toMatchObject({ ok: false, error: { code: 'agent-busy' } })
  486. })
  487. it('timing hooks: history delay + one-shot failure, silent append, and breakStreams end open generators', async () => {
  488. const api = createFixtureApi()
  489. const hooks = timing()
  490. // One-shot transport failure after transit delay.
  491. hooks.setHistoryDelay(5)
  492. hooks.failNextHistory()
  493. await expect(api.sessions.history(req({ sessionId: sid('fx-alpha'), maxMessages: 5 }))).rejects.toThrow(/simulated history transport failure/)
  494. hooks.setHistoryDelay(0)
  495. // The failure was one-shot: the next call succeeds.
  496. const ok = await api.sessions.history(req({ sessionId: sid('fx-alpha'), maxMessages: 5 }))
  497. expect(ok.result.ok).toBe(true)
  498. // appendUser emits on the mux stream; appendSilent only lands in the log (lost frame).
  499. const abort = new AbortController()
  500. const seen: MuxFrame[] = []
  501. const consuming = (async () => {
  502. for await (const envelope of api.events.mux(req({}), abort.signal)) seen.push(envelope.payload)
  503. })()
  504. await new Promise(resolve => setTimeout(resolve, 10))
  505. hooks.appendSilent('fx-alpha', '静默丢帧')
  506. hooks.appendUser('fx-alpha', '正常直播')
  507. hooks.appendTitle('fx-alpha', 'Fixture 修订标题')
  508. await vi.waitFor(() => {
  509. expect(seen.some(f => f.type === 'session/event' && JSON.stringify(f.event.data).includes('正常直播'))).toBe(true)
  510. expect(seen.some(f => f.type === 'session/title' && f.title === 'Fixture 修订标题')).toBe(true)
  511. })
  512. expect(seen.some(f => f.type === 'session/event' && JSON.stringify(f.event.data).includes('静默丢帧'))).toBe(false)
  513. const rawTitleIndex = seen.findIndex(f => f.type === 'session/event' && (f.event as { type: string }).type === 'session/title')
  514. const titleControlIndex = seen.findIndex(f => f.type === 'session/title' && f.title === 'Fixture 修订标题')
  515. expect(titleControlIndex).toBe(rawTitleIndex + 1)
  516. // But history serves the silent event (the client's repull finds it).
  517. const repull = await api.sessions.history(req({ sessionId: sid('fx-alpha'), maxMessages: 5 }))
  518. if (!repull.result.ok) throw new Error('repull failed')
  519. expect(JSON.stringify(repull.result.value.events)).toContain('静默丢帧')
  520. // breakStreams force-ends BOTH stream kinds without the client abort.
  521. const habort = new AbortController()
  522. const hostConsuming = (async () => {
  523. for await (const _ of api.events.host(req({}), habort.signal)) { /* drain */ }
  524. })()
  525. await new Promise(resolve => setTimeout(resolve, 10))
  526. hooks.breakStreams()
  527. await consuming // returns because the stream broke, not because we aborted
  528. await hostConsuming
  529. expect(abort.signal.aborted).toBe(false)
  530. expect(habort.signal.aborted).toBe(false)
  531. })
  532. })
  533. describe('FixtureApiClient (protocol-level fake carrier)', () => {
  534. afterEach(() => {
  535. vi.restoreAllMocks()
  536. vi.unstubAllGlobals()
  537. })
  538. it('doFetch is an unreachable tripwire (all protocol paths overridden)', () => {
  539. const client = new FixtureApiClient()
  540. // Protected at compile time only; reach it directly to pin the tripwire message.
  541. expect(() => (client as unknown as { doFetch(): Promise<Response> }).doFetch()).toThrow(/doFetch must be unreachable/)
  542. })
  543. it('mints request ids, taps all four full forms, and never touches doFetch', async () => {
  544. const client = new FixtureApiClient()
  545. const tapped: RpcMessage[] = []
  546. client.subscribeEnvelopes(batch => tapped.push(...batch))
  547. const response = await client.sessions.list({})
  548. expect(response.result.ok).toBe(true)
  549. await client.respond({ type: 'client-response', rpcId: RpcId('r-x'), result: { ok: true, value: {} } })
  550. await vi.waitFor(() => {
  551. const kinds = tapped.map(m => m.type)
  552. expect(kinds).toContain('client-request')
  553. expect(kinds).toContain('server-response')
  554. expect(kinds).toContain('client-response')
  555. })
  556. const request = tapped.find(m => m.type === 'client-request')
  557. const reply = tapped.find(m => m.type === 'server-response')
  558. expect(request?.rpcId).toBe(reply?.rpcId) // echo discipline holds through the fake carrier
  559. })
  560. it('covers the whole unary dispatch table', async () => {
  561. const client = new FixtureApiClient()
  562. const created = await client.sessions.create({})
  563. if (!created.result.ok) throw new Error('create failed')
  564. const id = created.result.value.sessionId
  565. expect((await client.sessions.history({ sessionId: id })).result.ok).toBe(true)
  566. expect((await client.sessions.prompt({ sessionId: id, mode: 'queue', content: [{ type: 'text', text: '嗨' }] })).result.ok).toBe(true)
  567. expect((await client.sessions.cancel({ sessionId: id })).result.ok).toBe(true)
  568. expect((await client.host.describe({})).result.ok).toBe(true)
  569. expect((await client.workspace.list({})).result.ok).toBe(true)
  570. const workspace = await client.workspace.create({ name: 'via-client' })
  571. if (!workspace.result.ok) throw new Error('workspace create failed')
  572. expect(workspace.result.value.workspace.title).toBe('via-client')
  573. const wsid = workspace.result.value.workspace.workspaceId
  574. const renamed = await client.workspace.rename({ workspaceId: wsid, title: 'via-client-2' })
  575. if (!renamed.result.ok) throw new Error('workspace rename failed')
  576. expect(renamed.result.value.workspace.title).toBe('via-client-2')
  577. const attached = await client.sessions.create({ workspaceId: wsid })
  578. if (!attached.result.ok) throw new Error('attached create failed')
  579. const moved = await client.workspace.insertSessionBefore({ workspaceId: wsid, sessionId: attached.result.value.sessionId })
  580. if (!moved.result.ok) throw new Error('workspace move failed')
  581. expect(moved.result.value.workspace.sessionIds).toEqual([attached.result.value.sessionId])
  582. })
  583. it('maps empty, prompt-reject, and workspace-first query scenarios', async () => {
  584. vi.stubGlobal('location', {
  585. search: '?fixture=empty&fixturePrompt=reject&fixtureFrames=workspace-first',
  586. })
  587. const client = new FixtureApiClient()
  588. await expect(client.sessions.list({})).resolves.toMatchObject({ result: { ok: true, value: { items: [] } } })
  589. const made = await client.workspace.create({ name: 'query-workspace' })
  590. if (!made.result.ok) throw new Error('workspace create failed')
  591. const abort = new AbortController()
  592. const framesPromise = collect(client.events.host({}, abort.signal), abort, frames => frames.length === 2)
  593. await new Promise(resolve => setTimeout(resolve, 10))
  594. const sessionId = sid('fx-query-session')
  595. const created = await client.sessions.create({
  596. workspaceId: made.result.value.workspace.workspaceId,
  597. sessionId,
  598. })
  599. expect(created.result).toMatchObject({ ok: true, value: { sessionId } })
  600. const frames = await framesPromise
  601. expect(frames.map(frame => frame.type)).toEqual(['host/workspace-changed', 'host/session-added'])
  602. const rejected = await client.sessions.prompt({
  603. sessionId,
  604. mode: 'queue',
  605. content: [{ type: 'text', text: 'retain' }],
  606. })
  607. expect(rejected.result).toMatchObject({ ok: false, error: { code: 'agent-busy' } })
  608. })
  609. it('maps attach-failure and dropped-response query scenarios', async () => {
  610. vi.stubGlobal('location', { search: '?fixture&fixtureAttach=fail' })
  611. const partial = new FixtureApiClient()
  612. const partialResult = await partial.sessions.create({
  613. workspaceId: 'fx-ws-fixture' as WorkspaceId,
  614. sessionId: sid('fx-query-partial'),
  615. })
  616. expect(partialResult.result).toMatchObject({
  617. ok: false,
  618. error: { code: 'workspace-attach-failed', details: { sessionId: 'fx-query-partial' } },
  619. })
  620. vi.stubGlobal('location', { search: '?fixture&fixtureSessionCreate=drop-response' })
  621. const dropped = new FixtureApiClient()
  622. await expect(dropped.sessions.create({
  623. workspaceId: 'fx-ws-fixture' as WorkspaceId,
  624. sessionId: sid('fx-query-dropped'),
  625. })).rejects.toThrow(/dropped session\.create response/)
  626. })
  627. it('fires onOpen at stream-iteration start and taps server-request full forms', async () => {
  628. const client = new FixtureApiClient()
  629. const tapped: RpcMessage[] = []
  630. client.subscribeEnvelopes(batch => tapped.push(...batch))
  631. const order: string[] = []
  632. const abort = new AbortController()
  633. for await (const envelope of client.events.mux({}, abort.signal, () => order.push('open'))) {
  634. order.push(envelope.payload.type)
  635. abort.abort()
  636. }
  637. expect(order[0]).toBe('open')
  638. expect(order[1]).toBe('session/subscribed')
  639. await vi.waitFor(() => {
  640. expect(tapped.some(m => m.type === 'server-request')).toBe(true)
  641. })
  642. // Host stream side of the pair (same tap path).
  643. const habort = new AbortController()
  644. const hostOrder: string[] = []
  645. const hostIterator = client.events.host({}, habort.signal, () => hostOrder.push('open'))[Symbol.asyncIterator]()
  646. const raced = await Promise.race([hostIterator.next(), new Promise<'idle'>(resolve => setTimeout(() => { resolve('idle') }, 50))])
  647. expect(hostOrder).toEqual(['open']) // established even though the host stream stays silent
  648. habort.abort()
  649. if (raced === 'idle') await hostIterator.return?.(undefined)
  650. })
  651. })