fixture.spec.ts 59 KB

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