fixture.spec.ts 41 KB

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