fixture.spec.ts 54 KB

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