fixture.spec.ts 43 KB

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