fixture.client.spec.ts 60 KB

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