fixture.spec.ts 47 KB

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