fixture.client.spec.ts 76 KB

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