fixture.client.spec.ts 75 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676
  1. import { afterEach, describe, expect, it, vi } from 'vitest'
  2. import type {
  3. ModelSelection,
  4. RpcMessage,
  5. RpcRequest,
  6. RpcResponse,
  7. RpcResult,
  8. SessionEvent,
  9. SessionId,
  10. } from '../src/client/api.ts'
  11. import { RpcId } from '../src/client/api.ts'
  12. import {
  13. FixtureApiClient,
  14. createFixtureFaces,
  15. type FixtureOptions,
  16. } from '../src/client/fixture.ts'
  17. import type {
  18. ClientConnectionRpc,
  19. } from '../src/rpc.ts'
  20. const sid = (id: string): SessionId => id as SessionId
  21. type WorkspaceId = string & { readonly __fixtureWorkspaceId: 'WorkspaceId' }
  22. const req = <P>(payload: P): RpcRequest<P> => ({ rpcId: RpcId(`t-${Math.abs(Math.sin(reqCount++)).toString(36).slice(2, 10)}`), payload })
  23. let reqCount = 0
  24. interface FixtureSessionSummary {
  25. sessionId: SessionId
  26. updatedAt: number
  27. running: boolean
  28. blank: boolean
  29. parentSessionId?: SessionId
  30. origin?: 'subagent'
  31. cwd?: string
  32. agentPreset?: string
  33. }
  34. interface FixtureHistoryEntry {
  35. readonly event: SessionEvent
  36. }
  37. interface FixturePage {
  38. readonly events: readonly FixtureHistoryEntry[]
  39. readonly hasMore: boolean
  40. }
  41. type FixtureFollowFrame =
  42. | {
  43. readonly type: 'snapshot'
  44. readonly cursor: number
  45. readonly events: readonly FixtureHistoryEntry[]
  46. readonly hasMore: boolean
  47. readonly projections: {
  48. readonly asOfSeq: number
  49. readonly values: Readonly<Record<string, unknown>>
  50. }
  51. }
  52. | ({ readonly type: 'event' } & FixtureHistoryEntry)
  53. type FixtureControlFrame =
  54. | {
  55. readonly type: 'baseline'
  56. readonly value: {
  57. readonly queues: Readonly<Record<string, readonly unknown[]>>
  58. readonly jobs: Readonly<Record<string, readonly unknown[]>>
  59. readonly approvals: readonly unknown[]
  60. readonly questions: readonly unknown[]
  61. readonly projections: Readonly<Record<string, {
  62. readonly asOfSeq: number
  63. readonly values: Readonly<Record<string, unknown>>
  64. }>>
  65. }
  66. }
  67. | {
  68. readonly type: 'projection'
  69. readonly sessionId: SessionId
  70. readonly key: string
  71. readonly value: unknown
  72. readonly seq: number
  73. }
  74. interface FixtureSessionRequests {
  75. list: { readonly cursor?: string }
  76. search: { readonly query: string }
  77. create: {
  78. readonly workspaceId?: WorkspaceId
  79. readonly cwd?: string
  80. readonly sessionId?: SessionId
  81. readonly agentPreset?: string
  82. }
  83. history: {
  84. readonly sessionId: SessionId
  85. readonly beforeSeq?: number
  86. readonly maxMessages?: number
  87. }
  88. selectModel: {
  89. readonly sessionId: SessionId
  90. readonly provider: string
  91. readonly model: string
  92. readonly reasoningEffort?: string
  93. }
  94. prompt: {
  95. readonly sessionId: SessionId
  96. readonly mode: 'queue' | 'steer'
  97. readonly content: readonly ({ readonly type: 'text'; readonly text: string } | {
  98. readonly type: 'image'
  99. readonly mediaType: 'image/png' | 'image/jpeg' | 'image/webp' | 'image/gif'
  100. readonly data: string
  101. readonly name?: string
  102. })[]
  103. }
  104. cancel: { readonly sessionId: SessionId }
  105. rename: { readonly sessionId: SessionId; readonly title: string }
  106. }
  107. interface FixtureSessionValues {
  108. list: { readonly items: FixtureSessionSummary[] }
  109. search: { readonly items: readonly { readonly sessionId: SessionId; readonly snippet: string }[]; readonly hasMore: boolean }
  110. create: { readonly sessionId: SessionId }
  111. history: FixturePage
  112. selectModel: { readonly selected: ModelSelection }
  113. prompt: { readonly accepted: true }
  114. cancel: Record<never, never>
  115. rename: { readonly title: string; readonly seq: number }
  116. }
  117. type FixtureSessionApi = {
  118. [K in keyof FixtureSessionRequests]: (
  119. request: RpcRequest<FixtureSessionRequests[K]>,
  120. signal?: AbortSignal,
  121. ) => Promise<RpcResponse<FixtureSessionValues[K]>>
  122. }
  123. type FixtureSessionClient = {
  124. [K in keyof FixtureSessionRequests]: (
  125. request: FixtureSessionRequests[K],
  126. signal?: AbortSignal,
  127. ) => Promise<RpcResponse<FixtureSessionValues[K]>>
  128. }
  129. interface FixtureSessionRemote {
  130. follow(sessionId: SessionId, signal: AbortSignal): AsyncIterable<FixtureFollowFrame>
  131. control(signal: AbortSignal): AsyncIterable<FixtureControlFrame>
  132. }
  133. interface FixtureWorkspaceView {
  134. readonly workspaceId: WorkspaceId
  135. readonly path: string
  136. readonly title: string
  137. readonly sessionIds: readonly SessionId[]
  138. readonly createdAt: string
  139. readonly updatedAt: string
  140. }
  141. interface FixtureWorkspaceRequests {
  142. create: { readonly path: string }
  143. rename: { readonly workspaceId: WorkspaceId; readonly title: string }
  144. delete: { readonly workspaceId: WorkspaceId }
  145. insertBefore: { readonly workspaceId: WorkspaceId; readonly beforeWorkspaceId?: WorkspaceId }
  146. insertSessionBefore: {
  147. readonly workspaceId: WorkspaceId
  148. readonly sessionId: SessionId
  149. readonly beforeSessionId?: SessionId
  150. }
  151. archiveSession: { readonly sessionId: SessionId }
  152. }
  153. interface FixtureWorkspaceValues {
  154. create: { readonly workspace: FixtureWorkspaceView; readonly created: boolean }
  155. rename: { readonly workspace: FixtureWorkspaceView }
  156. delete: { readonly deleted: true }
  157. insertBefore: { readonly workspaceIds: readonly WorkspaceId[] }
  158. insertSessionBefore: { readonly workspace: FixtureWorkspaceView }
  159. archiveSession: { readonly archivedSessionIds: readonly SessionId[] }
  160. }
  161. type FixtureWorkspaceApi = {
  162. [K in keyof FixtureWorkspaceRequests]: (
  163. request: RpcRequest<FixtureWorkspaceRequests[K]>,
  164. signal?: AbortSignal,
  165. ) => Promise<RpcResponse<FixtureWorkspaceValues[K]>>
  166. }
  167. type FixtureWorkspaceClient = {
  168. [K in keyof FixtureWorkspaceRequests]: (
  169. request: FixtureWorkspaceRequests[K],
  170. signal?: AbortSignal,
  171. ) => Promise<RpcResponse<FixtureWorkspaceValues[K]>>
  172. }
  173. type FixtureWorkspaceFrame =
  174. | {
  175. readonly type: 'baseline'
  176. readonly value: {
  177. readonly items: readonly FixtureWorkspaceView[]
  178. readonly archivedSessionIds: readonly SessionId[]
  179. }
  180. }
  181. | { readonly type: 'upsert'; readonly workspace: FixtureWorkspaceView }
  182. | { readonly type: 'remove'; readonly workspaceId: WorkspaceId }
  183. | { readonly type: 'order'; readonly workspaceIds: readonly WorkspaceId[] }
  184. | { readonly type: 'archived'; readonly archivedSessionIds: readonly SessionId[] }
  185. interface FixtureWorkspaceRemote {
  186. follow(signal: AbortSignal): AsyncIterable<FixtureWorkspaceFrame>
  187. }
  188. interface FixtureRemoteEventNotificationFrame {
  189. readonly type: 'emit'
  190. readonly event: string
  191. readonly args: readonly unknown[]
  192. }
  193. interface FixtureRemoteEventRequestFrame {
  194. readonly type: 'waterfall'
  195. readonly event: string
  196. readonly eventId: string
  197. readonly agentId: SessionId
  198. readonly request: Readonly<Record<string, unknown>>
  199. }
  200. interface FixtureRemoteEventCancellationFrame {
  201. readonly type: 'cancel'
  202. readonly eventId: string
  203. }
  204. type FixtureRemoteEventFrame =
  205. | FixtureRemoteEventNotificationFrame
  206. | FixtureRemoteEventRequestFrame
  207. | FixtureRemoteEventCancellationFrame
  208. interface FixtureRemoteEventResult {
  209. readonly clientId: string
  210. readonly eventId: string
  211. readonly outcome:
  212. | { readonly kind: 'next' }
  213. | { readonly kind: 'result'; readonly value?: unknown }
  214. | {
  215. readonly kind: 'rejected'
  216. readonly error: {
  217. readonly name: string
  218. readonly message: string
  219. readonly code?: string
  220. readonly details?: unknown
  221. }
  222. }
  223. }
  224. interface FixtureRemoteEventStream extends AsyncIterable<FixtureRemoteEventFrame> {
  225. readonly clientId: Promise<string>
  226. }
  227. type FixtureTestApi = ReturnType<typeof createFixtureFaces>['api'] & {
  228. readonly sessions: FixtureSessionApi
  229. readonly sessionRemote: FixtureSessionRemote
  230. readonly workspace: FixtureWorkspaceApi
  231. readonly workspaceRemote: FixtureWorkspaceRemote
  232. readonly remoteEvents: (signal: AbortSignal) => FixtureRemoteEventStream
  233. readonly answerRemoteEvent: (result: FixtureRemoteEventResult) => Promise<unknown>
  234. }
  235. /** Keep existing fixture assertions compact while driving only the new Session Remote endpoints. */
  236. function createFixtureApi(options: FixtureOptions = {}): FixtureTestApi {
  237. const { api, rpc } = createFixtureFaces(options)
  238. return Object.assign(api, {
  239. sessions: createSessionApi(rpc),
  240. sessionRemote: createSessionRemote(rpc),
  241. workspace: createWorkspaceApi(rpc),
  242. workspaceRemote: createWorkspaceRemote(rpc),
  243. remoteEvents: (signal: AbortSignal) => openFixtureRemoteEvents(rpc, signal),
  244. answerRemoteEvent: (result: FixtureRemoteEventResult) =>
  245. rpc.call('/api', '$events/result', { args: result }),
  246. })
  247. }
  248. function openFixtureRemoteEvents(
  249. rpc: ClientConnectionRpc,
  250. signal: AbortSignal,
  251. ): FixtureRemoteEventStream {
  252. const ready = Promise.withResolvers<string>()
  253. const source = (async function* (): AsyncGenerator<FixtureRemoteEventFrame> {
  254. const stream = rpc.open?.('/api', '$events', { args: {} }, signal)
  255. if (stream === undefined) throw new Error('fixture forwarded-event stream is unavailable')
  256. let opened = false
  257. for await (const value of stream) {
  258. if (!opened) {
  259. expect(value).toMatchObject({ type: 'ready' })
  260. const clientId: unknown = Reflect.get(value as object, 'clientId')
  261. if (typeof clientId !== 'string') throw new Error('fixture forwarded-event stream omitted its Client id')
  262. ready.resolve(clientId)
  263. opened = true
  264. continue
  265. }
  266. yield value as FixtureRemoteEventFrame
  267. }
  268. })()
  269. return Object.assign(source, { clientId: ready.promise })
  270. }
  271. function createSessionApi(rpc: ClientConnectionRpc): FixtureSessionApi {
  272. const call = async <K extends keyof FixtureSessionRequests>(
  273. endpoint: K,
  274. request: RpcRequest<FixtureSessionRequests[K]>,
  275. signal?: AbortSignal,
  276. ): Promise<RpcResponse<FixtureSessionValues[K]>> => {
  277. const page = endpoint === 'history'
  278. ? request.payload as FixtureSessionRequests['history']
  279. : undefined
  280. const args = endpoint === 'list'
  281. ? { _request: request.payload }
  282. : endpoint === 'history'
  283. ? {
  284. request: {
  285. address: { kind: 'session', sessionId: page?.sessionId },
  286. ...page?.beforeSeq === undefined ? {} : { beforeSeq: page.beforeSeq },
  287. ...page?.maxMessages === undefined ? {} : { maxMessages: page.maxMessages },
  288. },
  289. }
  290. : { request: request.payload }
  291. const remoteEndpoint = endpoint === 'history' ? 'page' : endpoint
  292. const result = await rpc.call('/api', `session/${remoteEndpoint}`, { args }, signal)
  293. return {
  294. rpcId: request.rpcId,
  295. result: result as unknown as RpcResult<FixtureSessionValues[K]>,
  296. }
  297. }
  298. return {
  299. list: (request, signal) => call('list', request, signal),
  300. search: (request, signal) => call('search', request, signal),
  301. create: (request, signal) => call('create', request, signal),
  302. history: (request, signal) => call('history', request, signal),
  303. selectModel: (request, signal) => call('selectModel', request, signal),
  304. prompt: (request, signal) => call('prompt', request, signal),
  305. cancel: (request, signal) => call('cancel', request, signal),
  306. rename: (request, signal) => call('rename', request, signal),
  307. }
  308. }
  309. function createSessionClient(rpc: ClientConnectionRpc): FixtureSessionClient {
  310. const api = createSessionApi(rpc)
  311. return {
  312. list: (request, signal) => api.list(req(request), signal),
  313. search: (request, signal) => api.search(req(request), signal),
  314. create: (request, signal) => api.create(req(request), signal),
  315. history: (request, signal) => api.history(req(request), signal),
  316. selectModel: (request, signal) => api.selectModel(req(request), signal),
  317. prompt: (request, signal) => api.prompt(req(request), signal),
  318. cancel: (request, signal) => api.cancel(req(request), signal),
  319. rename: (request, signal) => api.rename(req(request), signal),
  320. }
  321. }
  322. function createSessionRemote(rpc: ClientConnectionRpc): FixtureSessionRemote {
  323. const open = <F>(endpoint: string, args: object, signal: AbortSignal): AsyncIterable<F> => {
  324. const stream = rpc.open?.('/api', endpoint, { args }, signal)
  325. if (stream === undefined) throw new Error(`fixture ${endpoint} stream is unavailable`)
  326. return stream as AsyncIterable<F>
  327. }
  328. return {
  329. follow: (sessionId, signal) => open<FixtureFollowFrame>('session/follow', {
  330. request: { address: { kind: 'session', sessionId } },
  331. }, signal),
  332. control: signal => open<FixtureControlFrame>('session/control', {}, signal),
  333. }
  334. }
  335. function createWorkspaceApi(rpc: ClientConnectionRpc): FixtureWorkspaceApi {
  336. const call = async <K extends keyof FixtureWorkspaceRequests>(
  337. endpoint: K,
  338. request: RpcRequest<FixtureWorkspaceRequests[K]>,
  339. signal?: AbortSignal,
  340. ): Promise<RpcResponse<FixtureWorkspaceValues[K]>> => {
  341. const result = await rpc.call('/api', `workspace/${endpoint}`, {
  342. args: { request: request.payload },
  343. }, signal)
  344. return {
  345. rpcId: request.rpcId,
  346. result: result as unknown as RpcResult<FixtureWorkspaceValues[K]>,
  347. }
  348. }
  349. return {
  350. create: (request, signal) => call('create', request, signal),
  351. rename: (request, signal) => call('rename', request, signal),
  352. delete: (request, signal) => call('delete', request, signal),
  353. insertBefore: (request, signal) => call('insertBefore', request, signal),
  354. insertSessionBefore: (request, signal) => call('insertSessionBefore', request, signal),
  355. archiveSession: (request, signal) => call('archiveSession', request, signal),
  356. }
  357. }
  358. function createWorkspaceClient(rpc: ClientConnectionRpc): FixtureWorkspaceClient {
  359. const api = createWorkspaceApi(rpc)
  360. return {
  361. create: (request, signal) => api.create(req(request), signal),
  362. rename: (request, signal) => api.rename(req(request), signal),
  363. delete: (request, signal) => api.delete(req(request), signal),
  364. insertBefore: (request, signal) => api.insertBefore(req(request), signal),
  365. insertSessionBefore: (request, signal) => api.insertSessionBefore(req(request), signal),
  366. archiveSession: (request, signal) => api.archiveSession(req(request), signal),
  367. }
  368. }
  369. function createWorkspaceRemote(rpc: ClientConnectionRpc): FixtureWorkspaceRemote {
  370. return {
  371. follow(signal) {
  372. const stream = rpc.open?.('/api', 'workspace/follow', { args: {} }, signal)
  373. if (stream === undefined) throw new Error('fixture workspace/follow stream is unavailable')
  374. return stream as AsyncIterable<FixtureWorkspaceFrame>
  375. },
  376. }
  377. }
  378. interface TimingHooks {
  379. setHistoryDelay(ms: number): void
  380. failNextHistory(): void
  381. appendUser(id: string, msg: string): void
  382. appendTitle(id: string, title: string): void
  383. startReasoningChunkStorm(id: string, chunkCount: number, chunksPerInterval: number, intervalMs: number): string
  384. reasoningChunkStormState(): {
  385. sessionId: string
  386. chunkCount: number
  387. chunksPerInterval: number
  388. intervalMs: number
  389. emitted: number
  390. marker: string
  391. emitting: boolean
  392. } | null
  393. beginModelRetry(id: string): void
  394. scheduleModelRetry(id: string, retry?: number, delayMs?: number): void
  395. cancelModelRetryDuringBackoff(id: string, delayMs?: number): void
  396. completeModelRetry(id: string): void
  397. appendSilent(id: string, msg: string): void
  398. breakStreams(): void
  399. }
  400. const timing = (): TimingHooks => (globalThis as Record<string, unknown>).__fxTiming as TimingHooks
  401. /** Collect value-stream frames until the predicate or a soft cap; abort ends the stream. */
  402. async function collectValues<F>(stream: AsyncIterable<F>, abort: AbortController, done: (frames: F[]) => boolean): Promise<F[]> {
  403. const frames: F[] = []
  404. for await (const frame of stream) {
  405. frames.push(frame)
  406. if (done(frames) || frames.length > 500) {
  407. abort.abort()
  408. break
  409. }
  410. }
  411. return frames
  412. }
  413. async function readControlBaseline(remote: FixtureSessionRemote): Promise<Extract<FixtureControlFrame, { type: 'baseline' }>> {
  414. const abort = new AbortController()
  415. for await (const frame of remote.control(abort.signal)) {
  416. if (frame.type !== 'baseline') continue
  417. abort.abort()
  418. return frame
  419. }
  420. throw new Error('fixture control baseline missing')
  421. }
  422. function isRemoteEventRequest(frame: FixtureRemoteEventFrame): frame is FixtureRemoteEventRequestFrame {
  423. return frame.type === 'waterfall'
  424. }
  425. function isRemoteEventCancellation(frame: FixtureRemoteEventFrame): frame is FixtureRemoteEventCancellationFrame {
  426. return frame.type === 'cancel'
  427. }
  428. async function readResidentRemoteEvents(
  429. api: FixtureTestApi,
  430. count: number,
  431. ): Promise<FixtureRemoteEventRequestFrame[]> {
  432. const abort = new AbortController()
  433. const frames = await collectValues(
  434. api.remoteEvents(abort.signal),
  435. abort,
  436. seen => seen.filter(isRemoteEventRequest).length >= count,
  437. )
  438. return frames.filter(isRemoteEventRequest)
  439. }
  440. async function nextRemoteEvent(
  441. iterator: AsyncIterator<FixtureRemoteEventFrame>,
  442. predicate: (frame: FixtureRemoteEventFrame) => boolean,
  443. ): Promise<FixtureRemoteEventFrame> {
  444. for (;;) {
  445. const item = await iterator.next()
  446. if (item.done) throw new Error('fixture Remote Event stream ended before the expected frame')
  447. if (predicate(item.value)) return item.value
  448. }
  449. }
  450. async function readOpeningCursor(remote: FixtureSessionRemote, sessionId: SessionId): Promise<number> {
  451. const abort = new AbortController()
  452. for await (const frame of remote.follow(sessionId, abort.signal)) {
  453. if (frame.type !== 'snapshot') continue
  454. abort.abort()
  455. return frame.cursor
  456. }
  457. throw new Error('fixture follow opening cursor missing')
  458. }
  459. async function readWorkspaceBaseline(
  460. remote: FixtureWorkspaceRemote,
  461. ): Promise<Extract<FixtureWorkspaceFrame, { type: 'baseline' }>['value']> {
  462. const abort = new AbortController()
  463. for await (const frame of remote.follow(abort.signal)) {
  464. if (frame.type !== 'baseline') continue
  465. abort.abort()
  466. return frame.value
  467. }
  468. throw new Error('fixture Workspace baseline missing')
  469. }
  470. describe('createFixtureApi', () => {
  471. it('serves the session list sorted by updatedAt desc and echoes rpcIds on every unary', async () => {
  472. const api = createFixtureApi()
  473. const request = req({})
  474. const response = await api.sessions.list(request)
  475. expect(response.rpcId).toBe(request.rpcId)
  476. if (!response.result.ok) throw new Error('list failed')
  477. expect(response.result.value.items.map(s => s.sessionId)).toEqual(['fx-alpha', 'fx-beta', 'fx-gamma'])
  478. expect(response.result.value.items[1]?.parentSessionId).toBe('fx-alpha') // lineage material
  479. })
  480. it('searches current message text with literal unicode61-style token phrases', async () => {
  481. const api = createFixtureApi()
  482. const signal = new AbortController().signal
  483. const phrase = await api.sessions.search(req({ query: 'FIXTURE 历史消息' }), signal)
  484. expect(phrase.result).toMatchObject({
  485. ok: true,
  486. value: {
  487. items: [{ sessionId: 'fx-alpha' }],
  488. hasMore: false,
  489. },
  490. })
  491. if (!phrase.result.ok) throw new Error('search failed')
  492. expect(phrase.result.value.items[0]?.snippet).toContain('fixture 历史消息')
  493. timing().appendUser(
  494. 'fx-alpha',
  495. `${'leading context '.repeat(20)}late café token${' trailing context'.repeat(20)}`,
  496. )
  497. const late = await api.sessions.search(req({ query: 'LATE CAFE TOKEN' }), signal)
  498. if (!late.result.ok) throw new Error('late search failed')
  499. const lateSnippet = late.result.value.items[0]?.snippet ?? ''
  500. expect(lateSnippet).toContain('late café token')
  501. expect(lateSnippet.startsWith('…')).toBe(true)
  502. expect(lateSnippet.endsWith('…')).toBe(true)
  503. expect(Array.from(lateSnippet).length).toBeLessThanOrEqual(120)
  504. timing().appendUser('fx-alpha', 'Greek final sigma: ος')
  505. const finalSigma = await api.sessions.search(req({ query: 'ΟΣ' }), signal)
  506. if (!finalSigma.result.ok) throw new Error('final sigma search failed')
  507. expect(finalSigma.result.value.items[0]?.snippet).toContain('ος')
  508. const substring = await api.sessions.search(req({ query: 'ixtur' }), signal)
  509. expect(substring.result).toEqual({
  510. ok: true,
  511. value: { items: [], hasMore: false },
  512. })
  513. const punctuationOnly = await api.sessions.search(req({ query: '*' }), signal)
  514. expect(punctuationOnly.result).toEqual({
  515. ok: true,
  516. value: { items: [], hasMore: false },
  517. })
  518. const reasoningOnly = await api.sessions.search(req({ query: '思考过程' }), signal)
  519. expect(reasoningOnly.result).toEqual({
  520. ok: true,
  521. value: { items: [], hasMore: false },
  522. })
  523. const aborted = new AbortController()
  524. aborted.abort()
  525. await expect(api.sessions.search(req({ query: 'fixture' }), aborted.signal))
  526. .resolves.toMatchObject({ result: { ok: false, error: { code: 'cancelled' } } })
  527. })
  528. it('pages history backwards on message-boundary cuts with seq-contiguous stitching', async () => {
  529. const api = createFixtureApi()
  530. const tail = await api.sessions.history(req({ sessionId: sid('fx-alpha'), maxMessages: 10 }))
  531. if (!tail.result.ok) throw new Error('history failed')
  532. const tailPage = tail.result.value
  533. expect(tailPage.hasMore).toBe(true)
  534. expect(tailPage.events[0]?.event.type).toBe('turn/start') // cut lands on a turn boundary
  535. const boundary = tailPage.events[0]?.event.seq ?? 0
  536. expect(boundary).toBeGreaterThan(0)
  537. const older = await api.sessions.history(req({ sessionId: sid('fx-alpha'), beforeSeq: boundary, maxMessages: 10 }))
  538. if (!older.result.ok) throw new Error('older failed')
  539. const olderTail = older.result.value.events.at(-1)?.event
  540. expect((olderTail?.seq ?? -1) + 1).toBe(boundary) // pages stitch with no hole/overlap
  541. // Out-of-range beforeSeq clamps instead of exploding.
  542. const clamped = await api.sessions.history(req({ sessionId: sid('fx-alpha'), beforeSeq: -5, maxMessages: 10 }))
  543. if (!clamped.result.ok) throw new Error('clamped failed')
  544. expect(clamped.result.value.events).toEqual([])
  545. // Unknown session: empty page, not an error (history of a bare id).
  546. const empty = await api.sessions.history(req({ sessionId: sid('no-such'), maxMessages: 10 }))
  547. if (!empty.result.ok) throw new Error('empty failed')
  548. expect(empty.result.value).toEqual({ events: [], hasMore: false })
  549. })
  550. it('serves raw history entries with replayable tool-result metadata', async () => {
  551. const api = createFixtureApi()
  552. const response = await api.sessions.history(req({ sessionId: sid('fx-alpha'), maxMessages: 200 }))
  553. if (!response.result.ok) throw new Error('history failed')
  554. const entries = response.result.value.events
  555. expect(entries.every(entry => !Object.hasOwn(entry, 'view'))).toBe(true)
  556. const results = entries
  557. .map(entry => entry.event)
  558. .filter(event => event.type === 'tool/result')
  559. expect(results.find(event => event.data.turn === 64)).toMatchObject({
  560. data: {
  561. meta: {
  562. diffs: [
  563. { path: 'src/config.ts', oldText: 'const timeout = 30', newText: 'const timeout = 60' },
  564. { path: 'src/config.ts', oldText: 'retries: 1', newText: 'retries: 3' },
  565. ],
  566. },
  567. },
  568. })
  569. expect(results.find(event => event.data.turn === 67)).toMatchObject({
  570. data: { meta: { shape: 'matches', truncated: true, total: 42 } },
  571. })
  572. expect(results.find(event => event.data.turn === 69)).toMatchObject({
  573. data: { meta: { path: 'packages/client/ui-primitives/src/ReadBlock.tsx', offset: 41, totalLines: 180 } },
  574. })
  575. const webSearch = results.find(event => event.data.turn === 70)
  576. expect(webSearch).toHaveProperty('data.meta.truncated', true)
  577. expect(webSearch).toHaveProperty('data.meta.sources', expect.arrayContaining([
  578. expect.objectContaining({ url: 'https://github.com/deepseek-ai/deepseek-harness' }),
  579. ]))
  580. expect(results.find(event => event.data.turn === 71)).toMatchObject({
  581. data: { meta: { url: 'https://www.deepseek.com/blog/harness-architecture', statusCode: 200 } },
  582. })
  583. const terminal = results.find(event => event.data.turn === 66)
  584. expect(terminal).toHaveProperty('data.message.content.0.content.0.type', 'text')
  585. expect(terminal).toHaveProperty(
  586. 'data.message.content.0.content.0.text',
  587. expect.stringContaining('\n[exit code: 1]'),
  588. )
  589. })
  590. it('serves grouped models and keeps a selection for later history and fixture requests', async () => {
  591. const api = createFixtureApi()
  592. const sessionId = sid('fx-alpha')
  593. const catalog = await api.llm.models(req({}))
  594. if (!catalog.result.ok) throw new Error('models failed')
  595. expect(catalog.result.value.groups.map(group => group.name)).toEqual(['DeepSeek', 'OpenAI'])
  596. expect(catalog.result.value.groups[0]?.models.map(model => model.id))
  597. .toEqual(['deepseek-v4-flash', 'deepseek-v4-pro'])
  598. const selected = await api.sessions.selectModel(req({
  599. sessionId,
  600. provider: 'openai',
  601. model: 'gpt-5',
  602. }))
  603. if (!selected.result.ok) throw new Error('selection failed')
  604. expect(selected.result.value.selected).toEqual({ provider: 'openai', model: 'gpt-5' })
  605. const history = await api.sessions.history(req({ sessionId }))
  606. if (!history.result.ok) throw new Error('history failed')
  607. const prompt = await api.sessions.prompt(req({
  608. sessionId,
  609. mode: 'queue',
  610. content: [{ type: 'text', text: 'report model' }],
  611. }))
  612. expect(prompt.result.ok).toBe(true)
  613. await new Promise(resolve => setTimeout(resolve, 600))
  614. const after = await api.sessions.history(req({ sessionId }))
  615. if (!after.result.ok) throw new Error('history failed')
  616. expect(JSON.stringify(after.result.value.events)).toContain('openai/gpt-5')
  617. })
  618. it('serves configured DeepSeek readiness and keeps credential values write-only', async () => {
  619. const api = createFixtureApi()
  620. const settings = await api.settings.describe(req({}))
  621. if (!settings.result.ok) throw new Error('settings describe failed')
  622. expect(settings.result.value.namespaces).toMatchObject([{
  623. ns: 'llm-deepseek',
  624. value: { apiKeyEnv: 'DEEPSEEK_API_KEY' },
  625. secrets: [{ path: ['apiKey'], set: false }],
  626. }])
  627. const initial = await api.credentials.describe(req({ refs: ['DEEPSEEK_API_KEY', 'TEST_API_KEY'] }))
  628. if (!initial.result.ok) throw new Error('credential describe failed')
  629. expect(initial.result.value.credentials).toEqual({
  630. DEEPSEEK_API_KEY: { configured: true, source: 'file', writable: true },
  631. TEST_API_KEY: { configured: false, writable: true },
  632. })
  633. await api.credentials.set(req({ ref: 'TEST_API_KEY', value: 'write-only-fixture-secret' }))
  634. const configured = await api.credentials.describe(req({ refs: ['TEST_API_KEY'] }))
  635. if (!configured.result.ok) throw new Error('credential describe failed')
  636. expect(configured.result.value.credentials.TEST_API_KEY).toEqual({
  637. configured: true,
  638. source: 'file',
  639. writable: true,
  640. })
  641. await api.credentials.unset(req({ ref: 'TEST_API_KEY' }))
  642. const cleared = await api.credentials.describe(req({ refs: ['TEST_API_KEY'] }))
  643. if (!cleared.result.ok) throw new Error('credential describe failed')
  644. expect(cleared.result.value.credentials.TEST_API_KEY).toEqual({ configured: false, writable: true })
  645. })
  646. it('emits the todo/write snapshot at the real tool boundary: between tool/call and tool/result, timestamps monotonic', async () => {
  647. const api = createFixtureApi()
  648. const tail = await api.sessions.history(req({ sessionId: sid('fx-alpha'), maxMessages: 10 }))
  649. if (!tail.result.ok) throw new Error('history failed')
  650. const events = tail.result.value.events.map(e => e.event)
  651. const todoAt = events.findIndex(e => e.type === 'todo/write')
  652. expect(todoAt).toBeGreaterThan(0)
  653. // Production ordering (the tool appends mid-execution): call → snapshot → result.
  654. expect(events[todoAt - 1]?.type).toBe('tool/call')
  655. expect(events[todoAt + 1]?.type).toBe('tool/result')
  656. const times = events.slice(todoAt - 1, todoAt + 2).map(e => e.time)
  657. expect(times[0]).toBeLessThanOrEqual(times[1] ?? 0)
  658. expect(times[1]).toBeLessThanOrEqual(times[2] ?? 0)
  659. // The sample is a parallel plan: this fixture chooses the parallel policy,
  660. // so the surfaces fed from here face more than one active item.
  661. const snapshot = events[todoAt] as { data: { todos: { status: string }[] } }
  662. expect(snapshot.data.todos.filter(t => t.status === 'in_progress')).toHaveLength(2)
  663. })
  664. it('create adds a session and announces it through the Host Remote event stream', async () => {
  665. const api = createFixtureApi()
  666. const abort = new AbortController()
  667. const seen: FixtureRemoteEventNotificationFrame[] = []
  668. const consuming = (async () => {
  669. for await (const frame of api.remoteEvents(abort.signal)) {
  670. if (frame.type !== 'emit' || frame.event !== 'api-session/added') continue
  671. seen.push(frame)
  672. abort.abort()
  673. break
  674. }
  675. })()
  676. await new Promise(resolve => setTimeout(resolve, 10)) // let the stream register
  677. const created = await api.sessions.create(req({}))
  678. if (!created.result.ok) throw new Error('create failed')
  679. await consuming
  680. if (!created.result.ok) throw new Error('create failed')
  681. const createdId = created.result.value.sessionId
  682. expect(seen).toHaveLength(1)
  683. const added = seen[0]
  684. expect(added).toMatchObject({
  685. event: 'api-session/added',
  686. args: [{ sessionId: createdId, blank: true, cwd: '/tmp/fixture' }],
  687. })
  688. const list = await api.sessions.list(req({}))
  689. if (!list.result.ok) throw new Error('list failed')
  690. expect(list.result.value.items.some(s => s.sessionId === createdId)).toBe(true)
  691. })
  692. it('prompt replays a full streamed turn and cancel mid-replay freezes with (已中断)', async () => {
  693. const api = createFixtureApi()
  694. const created = await api.sessions.create(req({}))
  695. if (!created.result.ok) throw new Error('create failed')
  696. const id = created.result.value.sessionId
  697. const followAbort = new AbortController()
  698. const controlAbort = new AbortController()
  699. const controlFrames: FixtureControlFrame[] = []
  700. const followPromise = collectValues(
  701. api.sessionRemote.follow(id, followAbort.signal),
  702. followAbort,
  703. frames => frames.some(frame => frame.type === 'event' && frame.event.type === 'turn/end'),
  704. )
  705. const controlPromise = (async () => {
  706. for await (const frame of api.sessionRemote.control(controlAbort.signal)) controlFrames.push(frame)
  707. })()
  708. await new Promise(resolve => setTimeout(resolve, 10))
  709. // Unknown session → session-not-found with the id echoed in details.
  710. const missing = await api.sessions.prompt(req({ sessionId: sid('ghost'), mode: 'queue' as const, content: [{ type: 'text' as const, text: 'x' }] }))
  711. expect(missing.result).toMatchObject({ ok: false, error: { code: 'session-not-found', details: { sessionId: 'ghost' } } })
  712. // Real prompt: replay starts (running flips true), cancel freezes it.
  713. const accepted = await api.sessions.prompt(req({ sessionId: id, mode: 'queue' as const, content: [{ type: 'text' as const, text: 'render markdown' }] }))
  714. expect(accepted.result).toMatchObject({ ok: true, value: { accepted: true } })
  715. await new Promise(resolve => setTimeout(resolve, 120)) // a couple of typewriter ticks
  716. await api.sessions.cancel(req({ sessionId: id }))
  717. const frames = await followPromise
  718. const types = frames.flatMap(frame => frame.type === 'event' ? [frame.event.type] : [])
  719. expect(types).toContain('turn/start')
  720. expect(types).toContain('user/message')
  721. expect(types).toContain('assistant/chunk')
  722. expect(types).toContain('assistant/message')
  723. expect(types.at(-1)).toBe('turn/end')
  724. // Capacity is durable log state, not a transient frame: the prompt path
  725. // records request/context and the projection carries it to the client.
  726. expect(types).toContain('request/context')
  727. await vi.waitFor(() => {
  728. expect(controlFrames.some(frame =>
  729. frame.type === 'projection'
  730. && frame.key === 'contextBreakdown'
  731. && (frame.value as { messageTokens?: number }).messageTokens! > 0)).toBe(true)
  732. })
  733. expect(controlFrames.some(frame =>
  734. frame.type === 'projection'
  735. && frame.key === 'tokenUsage'
  736. && (frame.value as { outputTokens?: number }).outputTokens === 8)).toBe(true)
  737. expect(controlFrames.some(frame =>
  738. frame.type === 'projection'
  739. && frame.key === 'contextPressure'
  740. && (frame.value as { contextWindow?: number }).contextWindow === 128_000)).toBe(true)
  741. const finalize = frames.find(frame => frame.type === 'event' && frame.event.type === 'assistant/message')
  742. if (finalize?.type !== 'event') throw new Error('assistant final event missing')
  743. expect(JSON.stringify(finalize?.event.data)).toContain('(已中断)')
  744. controlAbort.abort()
  745. await controlPromise
  746. // Idle cancel: no replay in flight, must not explode; running flips false.
  747. const idleCancel = await api.sessions.cancel(req({ sessionId: id }))
  748. expect(idleCancel.result).toMatchObject({ ok: true })
  749. })
  750. it('steer during a replay lands a user/message inside the current turn and the replay continues', async () => {
  751. const api = createFixtureApi()
  752. const created = await api.sessions.create(req({}))
  753. if (!created.result.ok) throw new Error('create failed')
  754. const id = created.result.value.sessionId
  755. const abort = new AbortController()
  756. const framesPromise = collectValues(api.sessionRemote.follow(id, abort.signal), abort,
  757. frames => frames.some(frame => frame.type === 'event' && frame.event.type === 'turn/end'))
  758. await new Promise(resolve => setTimeout(resolve, 10))
  759. await api.sessions.prompt(req({ sessionId: id, mode: 'queue' as const, content: [{ type: 'text' as const, text: '短' }] }))
  760. await api.sessions.prompt(req({ sessionId: id, mode: 'steer' as const, content: [{ type: 'text' as const, text: '插话' }] }))
  761. const frames = await framesPromise
  762. const types = frames.flatMap(frame => frame.type === 'event' ? [frame.event.type] : [])
  763. expect(JSON.stringify(frames)).toContain('插话')
  764. expect(types.at(-1)).toBe('turn/end') // steer did not restart the turn
  765. })
  766. it('control replays projections while resident Remote Events retain ids across reconnects', async () => {
  767. const api = createFixtureApi()
  768. const first = await readControlBaseline(api.sessionRemote)
  769. const second = await readControlBaseline(api.sessionRemote)
  770. expect(first.value.approvals).toEqual([])
  771. expect(first.value.questions).toEqual([])
  772. const alpha = first.value.projections['fx-alpha']
  773. expect(alpha?.asOfSeq).toBeGreaterThan(0)
  774. expect(alpha?.values).toMatchObject({
  775. title: 'Fixture 历史会话',
  776. plan: { active: false, pending: false },
  777. goal: null,
  778. imageLimits: { maxImagesPerMessage: 20, maxImageBytes: 5 * 1024 * 1024 },
  779. })
  780. expect((alpha?.values['contextBreakdown'] as { messageTokens: number }).messageTokens).toBeGreaterThan(0)
  781. expect((alpha?.values['sessionStats'] as { steps: number }).steps).toBeGreaterThan(0)
  782. expect(second.value.projections['fx-alpha']).toEqual(alpha)
  783. const firstEvents = await readResidentRemoteEvents(api, 2)
  784. const secondEvents = await readResidentRemoteEvents(api, 2)
  785. const firstApproval = firstEvents.find(frame => frame.event === 'approval/request')
  786. const firstQuestion = firstEvents.find(frame => frame.event === 'user-questions/request')
  787. const secondApproval = secondEvents.find(frame => frame.event === 'approval/request')
  788. const secondQuestion = secondEvents.find(frame => frame.event === 'user-questions/request')
  789. expect(firstApproval).toMatchObject({
  790. type: 'waterfall',
  791. request: { toolName: 'dangerous_tool' },
  792. agentId: 'fx-alpha',
  793. })
  794. expect(firstQuestion).toMatchObject({
  795. type: 'waterfall',
  796. agentId: 'fx-alpha',
  797. })
  798. expect(Array.isArray(firstQuestion?.request.questions)).toBe(true)
  799. expect(secondApproval?.eventId).toBe(firstApproval?.eventId)
  800. expect(secondQuestion?.eventId).toBe(firstQuestion?.eventId)
  801. expect(await readOpeningCursor(api.sessionRemote, sid('fx-alpha'))).toBeGreaterThan(0)
  802. })
  803. it('steer with no replay in flight falls through to a fresh queued turn; non-text blocks stringify empty', async () => {
  804. const api = createFixtureApi()
  805. const created = await api.sessions.create(req({}))
  806. if (!created.result.ok) throw new Error('create failed')
  807. const abort = new AbortController()
  808. const framesPromise = collectValues(
  809. api.sessionRemote.follow(created.result.value.sessionId, abort.signal),
  810. abort,
  811. frames => frames.some(frame => frame.type === 'event' && frame.event.type === 'turn/end'),
  812. )
  813. await new Promise(resolve => setTimeout(resolve, 10))
  814. // steer while idle + a non-text content block (covers the '' arm of the text join).
  815. await api.sessions.prompt(req({
  816. sessionId: created.result.value.sessionId, mode: 'steer' as const,
  817. content: [{ type: 'text' as const, text: '短' }, { type: 'image', data: 'x' } as never],
  818. }))
  819. const frames = await framesPromise
  820. const types = frames.flatMap(frame => frame.type === 'event' ? [frame.event.type] : [])
  821. expect(types[0]).toBe('turn/start') // idle steer degraded to a queued turn, not an in-turn insert
  822. })
  823. it('gamma interval flip emits a Remote status event and its empty follow source opens at -1', async () => {
  824. vi.useFakeTimers()
  825. try {
  826. const api = createFixtureApi()
  827. const abort = new AbortController()
  828. const hostSeen: FixtureRemoteEventFrame[] = []
  829. const consuming = (async () => {
  830. for await (const frame of api.remoteEvents(abort.signal)) hostSeen.push(frame)
  831. })()
  832. await vi.advanceTimersByTimeAsync(5001) // interval fires: fx-gamma flips running=true (no log exists)
  833. expect(hostSeen).toContainEqual({
  834. type: 'emit',
  835. event: 'api-session/status',
  836. args: [sid('fx-gamma'), true],
  837. })
  838. expect(await readOpeningCursor(api.sessionRemote, sid('fx-gamma'))).toBe(-1)
  839. abort.abort()
  840. await vi.advanceTimersByTimeAsync(10)
  841. await consuming
  842. } finally {
  843. vi.useRealTimers()
  844. }
  845. })
  846. it('answers a resident question through its Remote Event id and stops replaying it', async () => {
  847. const api = createFixtureApi()
  848. const abort = new AbortController()
  849. const stream = api.remoteEvents(abort.signal)
  850. const iterator = stream[Symbol.asyncIterator]()
  851. const question = await nextRemoteEvent(
  852. iterator,
  853. frame => isRemoteEventRequest(frame) && frame.event === 'user-questions/request',
  854. )
  855. if (!isRemoteEventRequest(question)) throw new Error('fixture question Remote Event missing')
  856. const clientId = await stream.clientId
  857. await expect(api.answerRemoteEvent({
  858. clientId,
  859. eventId: 'unrelated',
  860. outcome: { kind: 'result', value: {} },
  861. })).resolves.toEqual({ ok: true, value: undefined })
  862. await expect(api.answerRemoteEvent({
  863. clientId,
  864. eventId: question.eventId,
  865. outcome: { kind: 'result', value: { answers: {} } },
  866. })).resolves.toEqual({ ok: true, value: undefined })
  867. const cancelled = await nextRemoteEvent(
  868. iterator,
  869. frame => isRemoteEventCancellation(frame) && frame.eventId === question.eventId,
  870. )
  871. expect(cancelled).toEqual({ type: 'cancel', eventId: question.eventId })
  872. abort.abort()
  873. await iterator.return?.()
  874. await expect(api.answerRemoteEvent({
  875. clientId,
  876. eventId: question.eventId,
  877. outcome: { kind: 'result', value: { answers: {} } },
  878. })).resolves.toMatchObject({ ok: false, error: { code: 'invocation-unavailable' } })
  879. const remaining = await readResidentRemoteEvents(api, 1)
  880. expect(remaining.map(frame => frame.event)).toEqual(['approval/request'])
  881. const cancelledApi = createFixtureApi()
  882. const cancelAbort = new AbortController()
  883. const cancelStream = cancelledApi.remoteEvents(cancelAbort.signal)
  884. const cancelIterator = cancelStream[Symbol.asyncIterator]()
  885. const cancelQuestion = await nextRemoteEvent(
  886. cancelIterator,
  887. frame => isRemoteEventRequest(frame) && frame.event === 'user-questions/request',
  888. )
  889. if (!isRemoteEventRequest(cancelQuestion)) throw new Error('fixture cancellation question missing')
  890. await expect(cancelledApi.answerRemoteEvent({
  891. clientId: await cancelStream.clientId,
  892. eventId: cancelQuestion.eventId,
  893. outcome: {
  894. kind: 'rejected',
  895. error: { name: 'UserQuestionError', message: 'skip', code: 'ASK_CANCELLED' },
  896. },
  897. })).resolves.toEqual({ ok: true, value: undefined })
  898. cancelAbort.abort()
  899. await cancelIterator.return?.()
  900. const afterCancellation = await readResidentRemoteEvents(cancelledApi, 1)
  901. expect(afterCancellation.map(frame => frame.event)).toEqual(['approval/request'])
  902. })
  903. it('answers a resident approval and broadcasts cancellation to its active delivery', async () => {
  904. const api = createFixtureApi()
  905. const abort = new AbortController()
  906. const stream = api.remoteEvents(abort.signal)
  907. const iterator = stream[Symbol.asyncIterator]()
  908. const approval = await nextRemoteEvent(
  909. iterator,
  910. frame => isRemoteEventRequest(frame) && frame.event === 'approval/request',
  911. )
  912. if (!isRemoteEventRequest(approval)) throw new Error('fixture approval Remote Event missing')
  913. await expect(api.answerRemoteEvent({
  914. clientId: await stream.clientId,
  915. eventId: approval.eventId,
  916. outcome: { kind: 'result', value: 'allowed-once' },
  917. })).resolves.toEqual({ ok: true, value: undefined })
  918. const cancelled = await nextRemoteEvent(
  919. iterator,
  920. frame => isRemoteEventCancellation(frame) && frame.eventId === approval.eventId,
  921. )
  922. expect(cancelled).toEqual({ type: 'cancel', eventId: approval.eventId })
  923. abort.abort()
  924. await iterator.return?.()
  925. await expect(api.answerRemoteEvent({
  926. clientId: await stream.clientId,
  927. eventId: approval.eventId,
  928. outcome: { kind: 'next' },
  929. })).resolves.toMatchObject({ ok: false, error: { code: 'invocation-unavailable' } })
  930. const remaining = await readResidentRemoteEvents(api, 1)
  931. expect(remaining.map(frame => frame.event)).toEqual(['user-questions/request'])
  932. })
  933. it('describe answers the fixture identity', async () => {
  934. const api = createFixtureApi()
  935. const response = await api.host.describe(req({}))
  936. expect(response.result).toMatchObject({
  937. ok: true, value: { version: '0.0.0-fixture', attachedSessions: 1, home: '/home/fixture' },
  938. })
  939. const empty = await createFixtureApi({ empty: true }).host.describe(req({}))
  940. expect(empty.result).toMatchObject({ ok: true, value: { attachedSessions: 0 } })
  941. })
  942. it('createDirectory under the root mints /name whose listing and crumbs share the identity', async () => {
  943. const api = createFixtureApi()
  944. const created = await api.host.createDirectory(req({ path: '/', name: 'srv' }))
  945. if (!created.result.ok) throw new Error('create failed')
  946. expect(created.result.value.path).toBe('/srv')
  947. const listed = await api.host.listDirectory(req({ path: '/srv' }), new AbortController().signal)
  948. if (!listed.result.ok) throw new Error('list failed')
  949. expect(listed.result.value.crumbs).toEqual([
  950. { name: '/', path: '/', hidden: false },
  951. { name: 'srv', path: '/srv', hidden: false },
  952. ])
  953. const root = await api.host.listDirectory(req({ path: '/' }), new AbortController().signal)
  954. if (!root.result.ok) throw new Error('root list failed')
  955. expect(root.result.value.entries).toContainEqual({ name: 'srv', path: '/srv', hidden: false })
  956. })
  957. it('workspace/follow serves the resident baseline and create reuses on path collision', async () => {
  958. const api = createFixtureApi()
  959. const baseline = await readWorkspaceBaseline(api.workspaceRemote)
  960. expect(baseline.items).toEqual([
  961. expect.objectContaining({
  962. workspaceId: 'fx-ws-fixture', path: '/tmp/fixture', title: 'fixture',
  963. sessionIds: ['fx-alpha', 'fx-beta', 'fx-gamma'],
  964. }),
  965. expect.objectContaining({
  966. workspaceId: 'fx-ws-home', path: '/home/fixture/Documents/project', title: 'project',
  967. sessionIds: [],
  968. }),
  969. ])
  970. // path collision → the existing entity comes back, created:false, no frame.
  971. const reused = await api.workspace.create(req({ path: '/tmp/fixture' }))
  972. if (!reused.result.ok) throw new Error('reuse failed')
  973. expect(reused.result.value).toMatchObject({ created: false, workspace: { workspaceId: 'fx-ws-fixture' } })
  974. })
  975. it('workspace.create on a fresh path mints a new entity and pushes an upsert', async () => {
  976. const api = createFixtureApi()
  977. const abort = new AbortController()
  978. const consuming = collectValues(
  979. api.workspaceRemote.follow(abort.signal),
  980. abort,
  981. frames => frames.some(frame => frame.type === 'upsert'
  982. && frame.workspace.path === '/tmp/fixture-workspaces/nova'),
  983. )
  984. await new Promise(resolve => setTimeout(resolve, 10))
  985. const created = await api.workspace.create(req({ path: '/tmp/fixture-workspaces/nova' }))
  986. if (!created.result.ok) throw new Error('create failed')
  987. expect(created.result.value.created).toBe(true)
  988. expect(created.result.value.workspace).toMatchObject({
  989. path: '/tmp/fixture-workspaces/nova', title: 'nova', sessionIds: [],
  990. })
  991. const frames = await consuming
  992. expect(frames.at(-1)).toEqual({ type: 'upsert', workspace: created.result.value.workspace })
  993. // A basename-less path serves as its own title.
  994. const rootPath = await api.workspace.create(req({ path: '/' }))
  995. if (!rootPath.result.ok) throw new Error('rootPath failed')
  996. expect(rootPath.result.value.workspace.title).toBe('/')
  997. })
  998. it('workspace.rename covers not-found, conflict, no-op, and the changed frame', async () => {
  999. const api = createFixtureApi()
  1000. const abort = new AbortController()
  1001. const consuming = collectValues(
  1002. api.workspaceRemote.follow(abort.signal),
  1003. abort,
  1004. frames => frames.filter(frame => frame.type === 'upsert').length >= 2,
  1005. )
  1006. await new Promise(resolve => setTimeout(resolve, 10))
  1007. const wsid = 'fx-ws-fixture' as WorkspaceId
  1008. const missing = await api.workspace.rename(req({ workspaceId: 'fx-ws-void' as WorkspaceId, title: 'x' }))
  1009. expect(missing.result).toMatchObject({ ok: false, error: { code: 'workspace-not-found', details: { workspaceId: 'fx-ws-void' } } })
  1010. await api.workspace.create(req({ path: '/tmp/fixture-workspaces/occupied' }))
  1011. const conflict = await api.workspace.rename(req({ workspaceId: wsid, title: ' occupied ' }))
  1012. expect(conflict.result).toMatchObject({ ok: false, error: { code: 'workspace-name-conflict', details: { name: 'occupied' } } })
  1013. const noop = await api.workspace.rename(req({ workspaceId: wsid, title: ' fixture ' }))
  1014. if (!noop.result.ok) throw new Error('no-op rename failed')
  1015. expect(noop.result.value.workspace.title).toBe('fixture')
  1016. const renamed = await api.workspace.rename(req({ workspaceId: wsid, title: 'renamed' }))
  1017. if (!renamed.result.ok) throw new Error('rename failed')
  1018. expect(renamed.result.value.workspace.title).toBe('renamed')
  1019. const frames = await consuming
  1020. // Only the create and the effective rename emit frames; the no-op stays silent.
  1021. const upserts = frames.filter(frame => frame.type === 'upsert')
  1022. expect(upserts).toHaveLength(2)
  1023. expect(upserts[1]).toMatchObject({ workspace: { workspaceId: wsid, title: 'renamed' } })
  1024. })
  1025. it('session.rename covers not-found, blank title, and the accepted append + title frame', async () => {
  1026. const api = createFixtureApi()
  1027. const followAbort = new AbortController()
  1028. const controlAbort = new AbortController()
  1029. const followPromise = collectValues(
  1030. api.sessionRemote.follow(sid('fx-alpha'), followAbort.signal),
  1031. followAbort,
  1032. frames => frames.some(frame => frame.type === 'event'
  1033. && (frame.event as { type: string }).type === 'session/title'),
  1034. )
  1035. const controlPromise = collectValues(
  1036. api.sessionRemote.control(controlAbort.signal),
  1037. controlAbort,
  1038. frames => frames.some(frame => frame.type === 'projection' && frame.key === 'title' && frame.value === '重命名'),
  1039. )
  1040. await new Promise(resolve => setTimeout(resolve, 10))
  1041. const missing = await api.sessions.rename(req({ sessionId: sid('fx-void'), title: 'x' }))
  1042. expect(missing.result).toMatchObject({ ok: false, error: { code: 'session-not-found', details: { sessionId: 'fx-void' } } })
  1043. const blank = await api.sessions.rename(req({ sessionId: sid('fx-alpha'), title: ' ' }))
  1044. expect(blank.result).toMatchObject({ ok: false, error: { code: 'title-invalid', details: { sessionId: 'fx-alpha' } } })
  1045. const renamed = await api.sessions.rename(req({ sessionId: sid('fx-alpha'), title: ' 重命名 ' }))
  1046. if (!renamed.result.ok) throw new Error('rename failed')
  1047. expect(renamed.result.value.title).toBe('重命名')
  1048. const acceptedSeq = renamed.result.value.seq
  1049. // The response seq addresses the appended title event (the client plane
  1050. // has no session/title in its event union — titles ride the projection —
  1051. // so the event is located by seq and its payload checked structurally).
  1052. const history = await api.sessions.history(req({ sessionId: sid('fx-alpha'), maxMessages: 100 }))
  1053. if (!history.result.ok) throw new Error('history failed')
  1054. const appended = history.result.value.events.find(entry => entry.event.seq === acceptedSeq)
  1055. expect(appended?.event).toMatchObject({
  1056. type: 'session/title',
  1057. data: { title: '重命名', messageSeqs: [], source: { kind: 'user' } },
  1058. })
  1059. const followed = await followPromise
  1060. expect(followed.some(frame => frame.type === 'event'
  1061. && frame.event.seq === acceptedSeq
  1062. && (frame.event as { readonly type: string }).type === 'session/title')).toBe(true)
  1063. const frames = await controlPromise
  1064. const titleFrames = frames.filter(frame =>
  1065. frame.type === 'projection'
  1066. && frame.key === 'title'
  1067. && frame.sessionId === sid('fx-alpha')
  1068. && frame.value === '重命名')
  1069. expect(titleFrames).toHaveLength(1)
  1070. expect(titleFrames[0]).toMatchObject({ seq: acceptedSeq })
  1071. })
  1072. it('workspace.insertSessionBefore moves, appends, no-ops, and rejects invalid ids', async () => {
  1073. const api = createFixtureApi()
  1074. const wsid = 'fx-ws-fixture' as WorkspaceId
  1075. const missing = await api.workspace.insertSessionBefore(req({ workspaceId: 'fx-ws-void' as WorkspaceId, sessionId: sid('fx-alpha') }))
  1076. expect(missing.result).toMatchObject({ ok: false, error: { code: 'workspace-not-found' } })
  1077. const ghost = await api.workspace.insertSessionBefore(req({ workspaceId: wsid, sessionId: sid('fx-ghost') }))
  1078. expect(ghost.result).toMatchObject({ ok: false, error: { code: 'workspace-move-invalid', details: { sessionId: 'fx-ghost' } } })
  1079. const badAnchor = await api.workspace.insertSessionBefore(req({ workspaceId: wsid, sessionId: sid('fx-alpha'), beforeSessionId: sid('fx-ghost') }))
  1080. expect(badAnchor.result).toMatchObject({ ok: false, error: { code: 'workspace-move-invalid', details: { beforeSessionId: 'fx-ghost' } } })
  1081. const moved = await api.workspace.insertSessionBefore(req({ workspaceId: wsid, sessionId: sid('fx-gamma'), beforeSessionId: sid('fx-beta') }))
  1082. if (!moved.result.ok) throw new Error('move failed')
  1083. expect(moved.result.value.workspace.sessionIds).toEqual(['fx-alpha', 'fx-gamma', 'fx-beta'])
  1084. const appended = await api.workspace.insertSessionBefore(req({ workspaceId: wsid, sessionId: sid('fx-alpha') }))
  1085. if (!appended.result.ok) throw new Error('append failed')
  1086. expect(appended.result.value.workspace.sessionIds).toEqual(['fx-gamma', 'fx-beta', 'fx-alpha'])
  1087. const before = appended.result.value.workspace.updatedAt
  1088. const noop = await api.workspace.insertSessionBefore(req({ workspaceId: wsid, sessionId: sid('fx-alpha') }))
  1089. if (!noop.result.ok) throw new Error('no-op move failed')
  1090. expect(noop.result.value.workspace.sessionIds).toEqual(['fx-gamma', 'fx-beta', 'fx-alpha'])
  1091. expect(noop.result.value.workspace.updatedAt).toBe(before)
  1092. })
  1093. it('workspace.delete removes only the Workspace row and emits the removal frame', async () => {
  1094. const api = createFixtureApi()
  1095. const abort = new AbortController()
  1096. const consuming = collectValues(
  1097. api.workspaceRemote.follow(abort.signal),
  1098. abort,
  1099. frames => frames.some(frame => frame.type === 'remove'),
  1100. )
  1101. await new Promise(resolve => setTimeout(resolve, 10))
  1102. const missing = await api.workspace.delete(req({ workspaceId: 'fx-ws-void' as WorkspaceId }))
  1103. expect(missing.result).toMatchObject({ ok: false, error: { code: 'workspace-not-found' } })
  1104. const deleted = await api.workspace.delete(req({ workspaceId: 'fx-ws-fixture' as WorkspaceId }))
  1105. expect(deleted.result).toEqual({ ok: true, value: { deleted: true } })
  1106. const frames = await consuming
  1107. expect(frames.at(-1)).toEqual({ type: 'remove', workspaceId: 'fx-ws-fixture' })
  1108. const baseline = await readWorkspaceBaseline(api.workspaceRemote)
  1109. expect(baseline.items.some(workspace => workspace.workspaceId === 'fx-ws-fixture')).toBe(false)
  1110. const sessions = await api.sessions.list(req({}))
  1111. if (!sessions.result.ok) throw new Error('session list failed')
  1112. expect(sessions.result.value.items.map(session => session.sessionId)).toContain('fx-alpha')
  1113. })
  1114. it('session.create({workspaceId}) lands on the account and unknown ids error', async () => {
  1115. const api = createFixtureApi()
  1116. const hostAbort = new AbortController()
  1117. const workspaceAbort = new AbortController()
  1118. const seen: FixtureRemoteEventNotificationFrame[] = []
  1119. const consuming = (async () => {
  1120. for await (const frame of api.remoteEvents(hostAbort.signal)) {
  1121. if (frame.type !== 'emit' || frame.event !== 'api-session/added') continue
  1122. seen.push(frame)
  1123. hostAbort.abort()
  1124. break
  1125. }
  1126. })()
  1127. const workspaceFrames = collectValues(
  1128. api.workspaceRemote.follow(workspaceAbort.signal),
  1129. workspaceAbort,
  1130. frames => frames.some(frame => frame.type === 'upsert'
  1131. && frame.workspace.sessionIds.length === 4),
  1132. )
  1133. await new Promise(resolve => setTimeout(resolve, 10))
  1134. const missing = await api.sessions.create(req({ workspaceId: 'fx-ws-void' as WorkspaceId }))
  1135. expect(missing.result).toMatchObject({ ok: false, error: { code: 'workspace-not-found', details: { workspaceId: 'fx-ws-void' } } })
  1136. const created = await api.sessions.create(req({ workspaceId: 'fx-ws-fixture' as WorkspaceId }))
  1137. if (!created.result.ok) throw new Error('create failed')
  1138. const id = created.result.value.sessionId
  1139. await consuming
  1140. const added = seen[0]
  1141. expect(added).toMatchObject({
  1142. event: 'api-session/added',
  1143. args: [{ sessionId: id, blank: true, cwd: '/tmp/fixture' }],
  1144. })
  1145. expect((await workspaceFrames).at(-1)).toMatchObject({
  1146. type: 'upsert',
  1147. workspace: {
  1148. workspaceId: 'fx-ws-fixture',
  1149. sessionIds: [id, 'fx-alpha', 'fx-beta', 'fx-gamma'],
  1150. },
  1151. })
  1152. })
  1153. it('supports an empty baseline, preallocated ids, independent streams, and idempotent retry', async () => {
  1154. const api = createFixtureApi({ empty: true, createFrameOrder: 'workspace-first' })
  1155. const initialSessions = await api.sessions.list(req({}))
  1156. expect(initialSessions.result).toMatchObject({ ok: true, value: { items: [] } })
  1157. expect(await readWorkspaceBaseline(api.workspaceRemote)).toEqual({
  1158. items: [],
  1159. archivedSessionIds: [],
  1160. })
  1161. const made = await api.workspace.create(req({ path: '/tmp/fixture-workspaces/nova' }))
  1162. if (!made.result.ok) throw new Error('workspace create failed')
  1163. const hostAbort = new AbortController()
  1164. const workspaceAbort = new AbortController()
  1165. const hostFrames = collectValues(
  1166. api.remoteEvents(hostAbort.signal),
  1167. hostAbort,
  1168. frames => frames.length === 1,
  1169. )
  1170. const workspaceFrames = collectValues(
  1171. api.workspaceRemote.follow(workspaceAbort.signal),
  1172. workspaceAbort,
  1173. frames => frames.some(frame => frame.type === 'upsert'
  1174. && frame.workspace.sessionIds.includes(sid('fx-preallocated'))),
  1175. )
  1176. await new Promise(resolve => setTimeout(resolve, 10))
  1177. const preallocated = sid('fx-preallocated')
  1178. const created = await api.sessions.create(req({
  1179. workspaceId: made.result.value.workspace.workspaceId,
  1180. sessionId: preallocated,
  1181. }))
  1182. expect(created.result).toEqual({ ok: true, value: { sessionId: preallocated } })
  1183. expect((await workspaceFrames).at(-1)).toMatchObject({
  1184. type: 'upsert', workspace: { sessionIds: [preallocated] },
  1185. })
  1186. const added = (await hostFrames)[0]
  1187. expect(added).toMatchObject({
  1188. event: 'api-session/added',
  1189. args: [{
  1190. sessionId: preallocated,
  1191. blank: true,
  1192. cwd: made.result.value.workspace.path,
  1193. }],
  1194. })
  1195. const retried = await api.sessions.create(req({
  1196. workspaceId: made.result.value.workspace.workspaceId,
  1197. sessionId: preallocated,
  1198. }))
  1199. expect(retried.result).toEqual({ ok: true, value: { sessionId: preallocated } })
  1200. const listed = await api.sessions.list(req({}))
  1201. if (!listed.result.ok) throw new Error('session list failed')
  1202. expect(listed.result.value.items.filter(item => item.sessionId === preallocated)).toHaveLength(1)
  1203. const conflict = await api.sessions.create(req({ sessionId: preallocated, cwd: '/elsewhere' }))
  1204. expect(conflict.result).toMatchObject({
  1205. ok: false,
  1206. error: { code: 'session-conflict', details: { sessionId: preallocated, requestedCwd: '/elsewhere' } },
  1207. })
  1208. })
  1209. it('attaches an existing ungrouped Session to a matching Workspace', async () => {
  1210. const api = createFixtureApi()
  1211. const sessionId = sid('fx-existing-ungrouped')
  1212. await expect(api.sessions.create(req({ sessionId, cwd: '/tmp/fixture' }))).resolves.toMatchObject({
  1213. result: { ok: true, value: { sessionId } },
  1214. })
  1215. await expect(api.sessions.create(req({
  1216. sessionId,
  1217. workspaceId: 'fx-ws-fixture' as WorkspaceId,
  1218. }))).resolves.toMatchObject({ result: { ok: true, value: { sessionId } } })
  1219. const workspaces = await readWorkspaceBaseline(api.workspaceRemote)
  1220. expect(workspaces.items[0]?.sessionIds).toContain(sessionId)
  1221. })
  1222. it('reports a conflict without an existing cwd detail for an unrecorded cwd', async () => {
  1223. const api = createFixtureApi()
  1224. const listed = await api.sessions.list(req({}))
  1225. if (!listed.result.ok) throw new Error('session list failed')
  1226. const existing = listed.result.value.items.find(item => item.sessionId === sid('fx-alpha'))
  1227. if (existing === undefined) throw new Error('fixture Session missing')
  1228. delete existing.cwd
  1229. const conflict = await api.sessions.create(req({ sessionId: existing.sessionId }))
  1230. expect(conflict.result).toEqual({
  1231. ok: false,
  1232. error: {
  1233. code: 'session-conflict',
  1234. message: `session ${existing.sessionId} already uses no cwd`,
  1235. details: { sessionId: existing.sessionId, requestedCwd: '/tmp/fixture' },
  1236. },
  1237. })
  1238. })
  1239. it('publishes an ungrouped Session when Workspace attachment fails', async () => {
  1240. const api = createFixtureApi({ failWorkspaceAttach: true })
  1241. const sessionId = sid('fx-partial')
  1242. const created = await api.sessions.create(req({
  1243. workspaceId: 'fx-ws-fixture' as WorkspaceId,
  1244. sessionId,
  1245. }))
  1246. expect(created.result).toMatchObject({
  1247. ok: false,
  1248. error: { code: 'workspace-attach-failed', details: { sessionId, workspaceId: 'fx-ws-fixture' } },
  1249. })
  1250. const listed = await api.sessions.list(req({}))
  1251. const workspaces = await readWorkspaceBaseline(api.workspaceRemote)
  1252. if (!listed.result.ok) throw new Error('list failed')
  1253. expect(listed.result.value.items.filter(item => item.sessionId === sessionId)).toHaveLength(1)
  1254. expect(workspaces.items[0]?.sessionIds).not.toContain(sessionId)
  1255. const retried = await api.sessions.create(req({
  1256. workspaceId: 'fx-ws-fixture' as WorkspaceId,
  1257. sessionId,
  1258. }))
  1259. expect(retried.result).toMatchObject({ ok: false, error: { code: 'workspace-attach-failed' } })
  1260. const afterRetry = await api.sessions.list(req({}))
  1261. if (!afterRetry.result.ok) throw new Error('list failed')
  1262. expect(afterRetry.result.value.items.filter(item => item.sessionId === sessionId)).toHaveLength(1)
  1263. })
  1264. it('reconciles a dropped create response and can reject a prompt before acceptance', async () => {
  1265. const sessionId = sid('fx-lost-response')
  1266. const dropped = createFixtureApi({ dropSessionCreateResponse: true })
  1267. await expect(Promise.resolve().then(() => dropped.sessions.create(req({
  1268. workspaceId: 'fx-ws-fixture' as WorkspaceId,
  1269. sessionId,
  1270. })))).rejects.toThrow(/dropped session\.create response/)
  1271. const listed = await dropped.sessions.list(req({}))
  1272. const workspaces = await readWorkspaceBaseline(dropped.workspaceRemote)
  1273. if (!listed.result.ok) throw new Error('list failed')
  1274. expect(listed.result.value.items.some(item => item.sessionId === sessionId)).toBe(true)
  1275. expect(workspaces.items[0]?.sessionIds).toContain(sessionId)
  1276. await expect(dropped.sessions.create(req({
  1277. workspaceId: 'fx-ws-fixture' as WorkspaceId,
  1278. sessionId,
  1279. }))).resolves.toMatchObject({ result: { ok: true, value: { sessionId } } })
  1280. const rejecting = createFixtureApi({ empty: true, rejectPrompt: true })
  1281. const real = await rejecting.sessions.create(req({ sessionId: sid('fx-rejected') }))
  1282. if (!real.result.ok) throw new Error('session create failed')
  1283. const prompt = await rejecting.sessions.prompt(req({
  1284. sessionId: real.result.value.sessionId,
  1285. mode: 'queue' as const,
  1286. content: [{ type: 'text' as const, text: 'keep me' }],
  1287. }))
  1288. expect(prompt.result).toMatchObject({ ok: false, error: { code: 'agent-busy' } })
  1289. const imagePrompt = await rejecting.sessions.prompt(req({
  1290. sessionId: real.result.value.sessionId,
  1291. mode: 'queue' as const,
  1292. content: [{ type: 'image' as const, mediaType: 'image/png' as const, data: 'iVBORw0KGgo=' }],
  1293. }))
  1294. expect(imagePrompt.result).toMatchObject({
  1295. ok: false,
  1296. error: { code: 'attachment-error', details: { reason: 'IMAGE_DIMENSION_TOO_LARGE' } },
  1297. })
  1298. })
  1299. it('timing hooks: history delay + one-shot failure, silent append, and breakStreams end open generators', async () => {
  1300. const api = createFixtureApi()
  1301. const hooks = timing()
  1302. // One-shot transport failure after transit delay.
  1303. hooks.setHistoryDelay(5)
  1304. hooks.failNextHistory()
  1305. await expect(api.sessions.history(req({ sessionId: sid('fx-alpha'), maxMessages: 5 }))).rejects.toThrow(/simulated history transport failure/)
  1306. hooks.setHistoryDelay(0)
  1307. // The failure was one-shot: the next call succeeds.
  1308. const ok = await api.sessions.history(req({ sessionId: sid('fx-alpha'), maxMessages: 5 }))
  1309. expect(ok.result.ok).toBe(true)
  1310. // A durable append without a live frame creates a detectable seq gap.
  1311. const gapAbort = new AbortController()
  1312. const gapIterator = api.sessionRemote.follow(sid('fx-alpha'), gapAbort.signal)[Symbol.asyncIterator]()
  1313. const opening = await gapIterator.next()
  1314. if (opening.done || opening.value.type !== 'snapshot') throw new Error('follow opening snapshot missing')
  1315. hooks.appendSilent('fx-alpha', '静默丢帧')
  1316. hooks.appendUser('fx-alpha', '正常直播')
  1317. await expect(gapIterator.next()).rejects.toThrow(/stream skipped seq/)
  1318. // Reopening replaces the window with a complete snapshot containing both durable events.
  1319. const followAbort = new AbortController()
  1320. const controlAbort = new AbortController()
  1321. const followed: FixtureFollowFrame[] = []
  1322. const controlled: FixtureControlFrame[] = []
  1323. const following = (async () => {
  1324. for await (const frame of api.sessionRemote.follow(sid('fx-alpha'), followAbort.signal)) {
  1325. followed.push(frame)
  1326. }
  1327. })()
  1328. const controlling = (async () => {
  1329. for await (const frame of api.sessionRemote.control(controlAbort.signal)) controlled.push(frame)
  1330. })()
  1331. await new Promise(resolve => setTimeout(resolve, 10))
  1332. await vi.waitFor(() => {
  1333. const snapshot = followed.find(frame => frame.type === 'snapshot')
  1334. expect(snapshot?.events.some(entry => JSON.stringify(entry.event.data).includes('静默丢帧'))).toBe(true)
  1335. expect(snapshot?.events.some(entry => JSON.stringify(entry.event.data).includes('正常直播'))).toBe(true)
  1336. })
  1337. hooks.appendTitle('fx-alpha', 'Fixture 修订标题')
  1338. hooks.beginModelRetry('fx-alpha')
  1339. hooks.scheduleModelRetry('fx-alpha')
  1340. hooks.completeModelRetry('fx-alpha')
  1341. hooks.beginModelRetry('fx-alpha')
  1342. hooks.cancelModelRetryDuringBackoff('fx-alpha')
  1343. await vi.waitFor(() => {
  1344. expect(followed.some(frame => frame.type === 'event' && (frame.event as { type: string }).type === 'llm/retry')).toBe(true)
  1345. expect(followed.some(frame => frame.type === 'event' && JSON.stringify(frame.event.data).includes('重试后的完整回复'))).toBe(true)
  1346. expect(followed.some(frame => frame.type === 'event'
  1347. && frame.event.type === 'turn/end'
  1348. && frame.event.data.reason.kind === 'aborted')).toBe(true)
  1349. expect(controlled.some(frame => frame.type === 'projection'
  1350. && frame.key === 'title'
  1351. && frame.value === 'Fixture 修订标题')).toBe(true)
  1352. })
  1353. expect(followed.some(frame => frame.type === 'event' && (frame.event as { type: string }).type === 'session/title')).toBe(true)
  1354. // Paging and resumed follow agree on the recovered durable event.
  1355. const repull = await api.sessions.history(req({ sessionId: sid('fx-alpha'), maxMessages: 5 }))
  1356. if (!repull.result.ok) throw new Error('repull failed')
  1357. expect(JSON.stringify(repull.result.value.events)).toContain('静默丢帧')
  1358. // breakStreams force-ends follow and control without client aborts.
  1359. await new Promise(resolve => setTimeout(resolve, 10))
  1360. hooks.breakStreams()
  1361. await following
  1362. await controlling
  1363. expect(followAbort.signal.aborted).toBe(false)
  1364. expect(controlAbort.signal.aborted).toBe(false)
  1365. })
  1366. it('paces the opt-in reasoning stress hook from an external interval', async () => {
  1367. vi.useFakeTimers()
  1368. vi.setSystemTime(0)
  1369. const api = createFixtureApi()
  1370. const hooks = timing()
  1371. expect(hooks.reasoningChunkStormState()).toBeNull()
  1372. expect(() => hooks.startReasoningChunkStorm('fx-alpha', 0, 1, 16)).toThrow(/chunk count/)
  1373. expect(() => hooks.startReasoningChunkStorm('fx-alpha', 1, 0, 16)).toThrow(/chunks per interval/)
  1374. expect(() => hooks.startReasoningChunkStorm('fx-alpha', 1, 1, 0)).toThrow(/reasoning interval/)
  1375. const abort = new AbortController()
  1376. try {
  1377. const streamed = collectValues(api.sessionRemote.follow(sid('fx-alpha'), abort.signal), abort, frames => frames.some(frame => (
  1378. frame.type === 'event'
  1379. && frame.event.type === 'assistant/chunk'
  1380. && frame.event.data.chunk.type === 'reasoning-delta'
  1381. && frame.event.data.chunk.text.includes('REASONING_STRESS_COMPLETE')
  1382. )))
  1383. const marker = hooks.startReasoningChunkStorm('fx-alpha', 3, 2, 16)
  1384. expect(() => hooks.startReasoningChunkStorm('fx-alpha', 1, 1, 16)).toThrow(/already running/)
  1385. expect(hooks.reasoningChunkStormState()).toMatchObject({ emitted: 0, emitting: true, marker })
  1386. await vi.advanceTimersByTimeAsync(0)
  1387. expect(hooks.reasoningChunkStormState()).toMatchObject({ emitted: 2, emitting: true })
  1388. await vi.advanceTimersByTimeAsync(16)
  1389. expect(hooks.reasoningChunkStormState()).toEqual({
  1390. sessionId: 'fx-alpha', chunkCount: 3, chunksPerInterval: 2, intervalMs: 16,
  1391. emitted: 3, marker, emitting: false,
  1392. })
  1393. const frames = await streamed
  1394. const deltas = frames.flatMap(frame => (
  1395. frame.type === 'event'
  1396. && frame.event.type === 'assistant/chunk'
  1397. && frame.event.data.chunk.type === 'reasoning-delta'
  1398. ? [frame.event.data.chunk.text]
  1399. : []
  1400. ))
  1401. expect(deltas).toEqual(['推理', '推理', `\n${marker}`])
  1402. } finally {
  1403. abort.abort()
  1404. vi.useRealTimers()
  1405. }
  1406. })
  1407. })
  1408. describe('FixtureApiClient (protocol-level fake carrier)', () => {
  1409. afterEach(() => {
  1410. vi.restoreAllMocks()
  1411. vi.unstubAllGlobals()
  1412. })
  1413. it('doFetch is an unreachable tripwire (all protocol paths overridden)', () => {
  1414. const client = new FixtureApiClient()
  1415. // Protected at compile time only; reach it directly to pin the tripwire message.
  1416. expect(() => (client as unknown as { doFetch(): Promise<Response> }).doFetch()).toThrow(/doFetch must be unreachable/)
  1417. })
  1418. it('mints request ids and taps unary request/response envelopes without touching doFetch', async () => {
  1419. const client = new FixtureApiClient()
  1420. const tapped: RpcMessage[] = []
  1421. client.subscribeEnvelopes(batch => tapped.push(...batch))
  1422. const response = await client.host.describe({})
  1423. expect(response.result.ok).toBe(true)
  1424. await vi.waitFor(() => {
  1425. const kinds = tapped.map(m => m.type)
  1426. expect(kinds).toContain('client-request')
  1427. expect(kinds).toContain('server-response')
  1428. })
  1429. const request = tapped.find(m => m.type === 'client-request')
  1430. const reply = tapped.find(m => m.type === 'server-response')
  1431. expect(request?.rpcId).toBe(reply?.rpcId) // echo discipline holds through the fake carrier
  1432. })
  1433. it('covers the whole unary dispatch table', async () => {
  1434. const client = new FixtureApiClient()
  1435. const sessions = createSessionClient(client.rpc)
  1436. const workspaces = createWorkspaceClient(client.rpc)
  1437. expect((await sessions.search(
  1438. { query: 'fixture' },
  1439. new AbortController().signal,
  1440. )).result.ok).toBe(true)
  1441. const created = await sessions.create({})
  1442. if (!created.result.ok) throw new Error('create failed')
  1443. const id = created.result.value.sessionId
  1444. expect((await sessions.history({ sessionId: id })).result.ok).toBe(true)
  1445. expect((await sessions.prompt({ sessionId: id, mode: 'queue', content: [{ type: 'text', text: '嗨' }] })).result.ok).toBe(true)
  1446. expect((await sessions.cancel({ sessionId: id })).result.ok).toBe(true)
  1447. expect((await client.host.describe({})).result.ok).toBe(true)
  1448. expect((await readWorkspaceBaseline(createWorkspaceRemote(client.rpc))).items).not.toHaveLength(0)
  1449. const workspace = await workspaces.create({ path: '/tmp/fixture-workspaces/via-client' })
  1450. if (!workspace.result.ok) throw new Error('workspace create failed')
  1451. expect(workspace.result.value.workspace.title).toBe('via-client')
  1452. const wsid = workspace.result.value.workspace.workspaceId
  1453. const renamed = await workspaces.rename({ workspaceId: wsid, title: 'via-client-2' })
  1454. if (!renamed.result.ok) throw new Error('workspace rename failed')
  1455. expect(renamed.result.value.workspace.title).toBe('via-client-2')
  1456. const attached = await sessions.create({ workspaceId: wsid })
  1457. if (!attached.result.ok) throw new Error('attached create failed')
  1458. const moved = await workspaces.insertSessionBefore({ workspaceId: wsid, sessionId: attached.result.value.sessionId })
  1459. if (!moved.result.ok) throw new Error('workspace move failed')
  1460. expect(moved.result.value.workspace.sessionIds).toEqual([attached.result.value.sessionId])
  1461. // Goal lifecycle over the fixture fold: create → edit → pause → resume → complete → clear;
  1462. // every mutation acknowledges with the NEW CAS ref (state rides the projection frames).
  1463. const goalCreated = await client.goals.create({ sessionId: id, objective: 'ship it' })
  1464. if (!goalCreated.result.ok) throw new Error('goal create failed')
  1465. let ref = goalCreated.result.value.ref
  1466. expect(ref.revision).toBe(1)
  1467. const edited = await client.goals.edit({ sessionId: id, ref, objective: 'ship it v2' })
  1468. if (!edited.result.ok) throw new Error('goal edit failed')
  1469. ref = edited.result.value.ref
  1470. const paused = await client.goals.pause({ sessionId: id, ref })
  1471. if (!paused.result.ok) throw new Error('goal pause failed')
  1472. ref = paused.result.value.ref
  1473. const resumed = await client.goals.resume({ sessionId: id, ref })
  1474. if (!resumed.result.ok) throw new Error('goal resume failed')
  1475. ref = resumed.result.value.ref
  1476. // A stale ref loses the CAS check.
  1477. expect((await client.goals.pause({ sessionId: id, ref: { ...ref, revision: 1 } })).result.ok).toBe(false)
  1478. const completed = await client.goals.complete({ sessionId: id, ref })
  1479. if (!completed.result.ok) throw new Error('goal complete failed')
  1480. ref = completed.result.value.ref
  1481. // complete → complete is an invalid transition.
  1482. expect((await client.goals.complete({ sessionId: id, ref })).result.ok).toBe(false)
  1483. expect((await client.goals.clear({ sessionId: id, ref })).result).toEqual({ ok: true, value: { cleared: true } })
  1484. const goalHistory = await sessions.history({ sessionId: id })
  1485. if (!goalHistory.result.ok) throw new Error('goal history failed')
  1486. const goalEvents = goalHistory.result.value.events.map(entry => entry.event as unknown as {
  1487. type: string
  1488. data: {
  1489. operation?: string
  1490. source?: { kind?: string; round?: number }
  1491. }
  1492. })
  1493. const goalChanges = goalEvents.filter(event => event.type === 'goal/change')
  1494. expect(goalChanges.map(event => event.data.operation))
  1495. .toEqual(['create', 'edit', 'pause', 'resume', 'complete', 'clear'])
  1496. expect(goalEvents.some(event => event.type === 'user/message'
  1497. && event.data.source?.kind === 'goal' && event.data.source.round === 0)).toBe(false)
  1498. })
  1499. it('maps empty, prompt-reject, and workspace-first query scenarios', async () => {
  1500. vi.stubGlobal('location', {
  1501. search: '?fixture=empty&fixturePrompt=reject&fixtureFrames=workspace-first',
  1502. })
  1503. const client = new FixtureApiClient()
  1504. const sessions = createSessionClient(client.rpc)
  1505. const workspaces = createWorkspaceClient(client.rpc)
  1506. const workspaceRemote = createWorkspaceRemote(client.rpc)
  1507. await expect(sessions.list({})).resolves.toMatchObject({ result: { ok: true, value: { items: [] } } })
  1508. const made = await workspaces.create({ path: '/tmp/fixture-workspaces/query-workspace' })
  1509. if (!made.result.ok) throw new Error('workspace create failed')
  1510. const hostAbort = new AbortController()
  1511. const workspaceAbort = new AbortController()
  1512. const hostFrames = collectValues(
  1513. openFixtureRemoteEvents(client.rpc, hostAbort.signal),
  1514. hostAbort,
  1515. frames => frames.length === 1,
  1516. )
  1517. const workspaceFrames = collectValues(
  1518. workspaceRemote.follow(workspaceAbort.signal),
  1519. workspaceAbort,
  1520. frames => frames.some(frame => frame.type === 'upsert'
  1521. && frame.workspace.sessionIds.includes(sid('fx-query-session'))),
  1522. )
  1523. await new Promise(resolve => setTimeout(resolve, 10))
  1524. const sessionId = sid('fx-query-session')
  1525. const created = await sessions.create({
  1526. workspaceId: made.result.value.workspace.workspaceId,
  1527. sessionId,
  1528. })
  1529. expect(created.result).toMatchObject({ ok: true, value: { sessionId } })
  1530. expect((await workspaceFrames).at(-1)).toMatchObject({
  1531. type: 'upsert',
  1532. workspace: { sessionIds: [sessionId] },
  1533. })
  1534. expect((await hostFrames)[0]).toMatchObject({
  1535. event: 'api-session/added',
  1536. })
  1537. const rejected = await sessions.prompt({
  1538. sessionId,
  1539. mode: 'queue',
  1540. content: [{ type: 'text', text: 'retain' }],
  1541. })
  1542. expect(rejected.result).toMatchObject({ ok: false, error: { code: 'agent-busy' } })
  1543. })
  1544. it('maps attach-failure and dropped-response query scenarios', async () => {
  1545. vi.stubGlobal('location', { search: '?fixture&fixtureAttach=fail' })
  1546. const partial = new FixtureApiClient()
  1547. const partialResult = await createSessionClient(partial.rpc).create({
  1548. workspaceId: 'fx-ws-fixture' as WorkspaceId,
  1549. sessionId: sid('fx-query-partial'),
  1550. })
  1551. expect(partialResult.result).toMatchObject({
  1552. ok: false,
  1553. error: { code: 'workspace-attach-failed', details: { sessionId: 'fx-query-partial' } },
  1554. })
  1555. vi.stubGlobal('location', { search: '?fixture&fixtureSessionCreate=drop-response' })
  1556. const dropped = new FixtureApiClient()
  1557. await expect(createSessionClient(dropped.rpc).create({
  1558. workspaceId: 'fx-ws-fixture' as WorkspaceId,
  1559. sessionId: sid('fx-query-dropped'),
  1560. })).rejects.toThrow(/dropped session\.create response/)
  1561. })
  1562. })