fixture.spec.ts 57 KB

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