fixture.spec.ts 55 KB

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