gateway.client.spec.ts 103 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631
  1. import { RemoteError } from '@deepseek-ai/dsh-typert-protocol'
  2. import { Context, Service } from '@deepseek-ai/cordis'
  3. import type { Fiber } from '@deepseek-ai/cordis'
  4. import { describe, expect, expectTypeOf, it, vi } from 'vitest'
  5. import { z } from 'zod'
  6. import {
  7. apply as applyConnection,
  8. type ConnectionGeneration,
  9. type ConnectionGenerationSource,
  10. type ConnectionHandle,
  11. } from '@deepseek-ai/dsh-client-connection/client'
  12. import type {
  13. InvocationDescriptor,
  14. RemoteResult,
  15. TypertContextMap,
  16. TypertContextWire,
  17. TypertContext,
  18. TypertLookup,
  19. TypertRemoteScopeApi,
  20. TypertRemoteNamespace,
  21. } from '@deepseek-ai/dsh-typert-protocol'
  22. import TypertRegistry from '@deepseek-ai/dsh-typert-registry'
  23. import type { ClientRemote } from '../src/client/index.ts'
  24. import { apply, inject, RemoteStream } from '../src/client/index.ts'
  25. import {
  26. RemoteStreamCarrierError,
  27. RemoteStreamMuxClient,
  28. } from '../src/client/stream-client.ts'
  29. type FixtureApprovalOutcome = 'allowed' | 'unavailable'
  30. const fixtureContextTag = Symbol('fixture-context-tag')
  31. type AgentWireId = TypertContextWire<TypertContextMap['agent']>
  32. const agentId = (value: string): AgentWireId => value as AgentWireId
  33. interface FixtureAgent {
  34. readonly agentId: string
  35. }
  36. declare module '@deepseek-ai/cordis' {
  37. interface Events {
  38. /**
  39. * Test-only forwarded Host event.
  40. * @param namespace - marker payload recorded by listeners.
  41. */
  42. 'fixture/changed'(namespace: string): void
  43. /**
  44. * Test-only forwarded Host event nobody subscribes to.
  45. * @param count - marker payload never observed.
  46. */
  47. 'fixture/idle'(count: number): void
  48. /**
  49. * Test-only scoped waterfall forwarded through the existing Remote Event stream.
  50. * @param request - JSON-safe request payload.
  51. * @param next - delegates to the next Client listener or Host waterfall.
  52. * @returns the claimed or delegated outcome.
  53. */
  54. 'fixture/approval'(
  55. this: Context,
  56. request: {
  57. readonly prompt: string
  58. readonly agent: FixtureAgent
  59. readonly signal?: AbortSignal
  60. },
  61. next: () => Promise<FixtureApprovalOutcome>,
  62. ): Promise<FixtureApprovalOutcome>
  63. /**
  64. * Test-only event the Host assembly does not forward.
  65. * @param flag - marker payload never delivered.
  66. */
  67. 'fixture/unselected'(flag: boolean): void
  68. }
  69. }
  70. declare module '@deepseek-ai/dsh-typert-protocol' {
  71. interface TypertRemoteEventSelection extends
  72. Record<'fixture/changed' | 'fixture/idle' | 'fixture/approval', true> {}
  73. interface TypertContextMap {
  74. fixture: TypertContext<string>
  75. }
  76. interface TypertLookupMap {
  77. fixture: TypertLookup<FixtureAgent, string>
  78. }
  79. interface TypertRemoteMap {
  80. 'probe/create': (
  81. agentId: string,
  82. request: { readonly objective: string },
  83. signal?: AbortSignal,
  84. ) => Promise<RemoteResult<{ readonly ref: string }>>
  85. 'probe/maybe': (value: string | null | undefined) => Promise<RemoteResult<string | null | undefined>>
  86. 'probe/watch': (topic: string, signal?: AbortSignal) => AsyncIterable<string>
  87. }
  88. interface TypertRemoteScopeMap {
  89. 'fixture:probe/create': (
  90. request: { readonly objective: string },
  91. signal?: AbortSignal,
  92. ) => Promise<RemoteResult<{ readonly ref: string }>>
  93. 'fixture:probe/rename': (
  94. request: { readonly objective: string },
  95. ) => Promise<RemoteResult<{ readonly renamed: boolean }>>
  96. }
  97. interface TypertRemoteNamespaceMap {
  98. probe: TypertRemoteNamespace<'probe'>
  99. }
  100. }
  101. type FixtureContext = Omit<Context, 'remote'> & {
  102. readonly remote: ClientRemote & TypertRemoteScopeApi<'fixture'>
  103. }
  104. // Compile-time contract of `$on`: the key face is the forwarding selection and
  105. // the listener signature is the owning package's own Cordis declaration.
  106. function remoteEventContracts(remote: ClientRemote): void {
  107. remote.$on('fixture/changed', (namespace) => { void namespace })
  108. remote.$on('fixture/approval', async function (request, next) {
  109. expectTypeOf(this).toEqualTypeOf<Context>()
  110. expectTypeOf(request.agent).toEqualTypeOf<Context>()
  111. expectTypeOf(request.signal).toEqualTypeOf<AbortSignal | undefined>()
  112. return request.prompt === '' ? next() : 'allowed'
  113. })
  114. // @ts-expect-error -- declared in Events but outside the forwarding selection.
  115. remote.$on('fixture/unselected', () => {})
  116. // @ts-expect-error -- not declared in Events at all.
  117. remote.$on('fixture/absent', () => {})
  118. // @ts-expect-error -- the listener signature comes from the event declaration.
  119. remote.$on('fixture/changed', (count: number) => { void count })
  120. }
  121. void remoteEventContracts
  122. const idSchema = z.string().min(1)
  123. const requestSchema = z.object({ objective: z.string().min(1) })
  124. const createResultSchema = z.object({ ref: z.string().min(1) })
  125. const renameResultSchema = z.object({ renamed: z.boolean() })
  126. function directDescriptor(): InvocationDescriptor {
  127. return {
  128. id: '@fixture/probe#probe/create',
  129. service: 'probe',
  130. namespace: 'probe',
  131. method: 'create',
  132. invocation: { kind: 'direct' },
  133. scope: { context: 'fixture', wire: 'agentId' },
  134. parameters: [{
  135. name: 'agent',
  136. wire: 'agentId',
  137. source: 'lookup',
  138. lookup: 'fixture',
  139. codec: { mode: 'strict', typeSymbol: '@fixture#AgentId', schema: idSchema },
  140. }, {
  141. name: 'request',
  142. wire: 'request',
  143. source: 'json',
  144. codec: { mode: 'strict', typeSymbol: '@fixture#CreateRequest', schema: requestSchema },
  145. }],
  146. cancellation: { parameter: 'signal' },
  147. result: { mode: 'strict', typeSymbol: '@fixture#CreateResult', schema: createResultSchema },
  148. }
  149. }
  150. function contextDescriptor(): InvocationDescriptor {
  151. return {
  152. id: '@fixture/probe#probe/rename',
  153. service: 'probe',
  154. namespace: 'probe',
  155. method: 'rename',
  156. invocation: {
  157. kind: 'context',
  158. context: 'fixture',
  159. wire: 'agentId',
  160. codec: { mode: 'strict', typeSymbol: '@fixture#AgentId', schema: idSchema },
  161. },
  162. parameters: [{
  163. name: 'request',
  164. wire: 'request',
  165. source: 'json',
  166. codec: { mode: 'strict', typeSymbol: '@fixture#RenameRequest', schema: requestSchema },
  167. }],
  168. result: { mode: 'strict', typeSymbol: '@fixture#RenameResult', schema: renameResultSchema },
  169. }
  170. }
  171. function maybeDescriptor(): InvocationDescriptor {
  172. const schema = z.union([z.string(), z.null(), z.undefined()])
  173. return {
  174. id: '@fixture/probe#probe/maybe',
  175. service: 'probe',
  176. namespace: 'probe',
  177. method: 'maybe',
  178. invocation: { kind: 'direct' },
  179. parameters: [{
  180. name: 'value',
  181. wire: 'value',
  182. source: 'json',
  183. acceptsUndefined: true,
  184. codec: { mode: 'strict', typeSymbol: '@fixture#MaybeValue', schema },
  185. }],
  186. result: { mode: 'strict', typeSymbol: '@fixture#MaybeValue', schema },
  187. }
  188. }
  189. function streamDescriptor(): InvocationDescriptor {
  190. return {
  191. id: '@fixture/probe#probe/watch',
  192. service: 'probe',
  193. namespace: 'probe',
  194. method: 'watch',
  195. mode: 'stream',
  196. invocation: { kind: 'direct' },
  197. parameters: [{
  198. name: 'topic',
  199. wire: 'topic',
  200. source: 'json',
  201. codec: { mode: 'strict', typeSymbol: '@fixture#Topic', schema: z.string().min(1) },
  202. }],
  203. cancellation: { parameter: 'signal' },
  204. result: { mode: 'strict', typeSymbol: '@fixture#WatchItem', schema: z.string().min(1) },
  205. }
  206. }
  207. type WebSocketGlobal = { WebSocket?: typeof WebSocket }
  208. class FakeWebSocket extends EventTarget {
  209. static readonly CONNECTING = 0
  210. static readonly OPEN = 1
  211. static readonly CLOSING = 2
  212. static readonly CLOSED = 3
  213. static readonly sockets: FakeWebSocket[] = []
  214. static autoOpen = true
  215. static dispatchClose = true
  216. readonly url: string
  217. readonly sent: string[] = []
  218. readonly closedWith: { readonly code?: number; readonly reason?: string }[] = []
  219. readyState = FakeWebSocket.CONNECTING
  220. constructor(url: string | URL) {
  221. super()
  222. this.url = String(url)
  223. FakeWebSocket.sockets.push(this)
  224. queueMicrotask(() => {
  225. if (FakeWebSocket.autoOpen) this.open()
  226. })
  227. }
  228. open(): void {
  229. if (this.readyState !== FakeWebSocket.CONNECTING) return
  230. this.readyState = FakeWebSocket.OPEN
  231. this.dispatchEvent(new Event('open'))
  232. }
  233. fail(): void {
  234. this.dispatchEvent(new Event('error'))
  235. }
  236. send(data: string): void {
  237. if (this.readyState !== FakeWebSocket.OPEN) throw new Error('fixture socket is not open')
  238. this.sent.push(data)
  239. }
  240. close(code?: number, reason?: string): void {
  241. this.closedWith.push({
  242. ...(code === undefined ? {} : { code }),
  243. ...(reason === undefined ? {} : { reason }),
  244. })
  245. if (this.readyState === FakeWebSocket.CLOSED) return
  246. if (!FakeWebSocket.dispatchClose) {
  247. this.readyState = FakeWebSocket.CLOSING
  248. return
  249. }
  250. this.drop()
  251. }
  252. drop(): void {
  253. if (this.readyState === FakeWebSocket.CLOSED) return
  254. this.readyState = FakeWebSocket.CLOSED
  255. this.dispatchEvent(new Event('close'))
  256. }
  257. receive(value: unknown): void {
  258. this.receiveRaw(typeof value === 'string' ? value : JSON.stringify(value))
  259. }
  260. receiveRaw(data: unknown): void {
  261. this.dispatchEvent(new MessageEvent('message', {
  262. data,
  263. }))
  264. }
  265. }
  266. async function bench(
  267. call: ConnectionHandle['rpc']['call'],
  268. carrier: 'in-process' | 'web' = 'in-process',
  269. ): Promise<Context> {
  270. const { ctx } = await benchFiber(call, carrier)
  271. return ctx
  272. }
  273. async function benchFiber(
  274. call: ConnectionHandle['rpc']['call'],
  275. carrier: 'in-process' | 'web' = 'in-process',
  276. open: NonNullable<ConnectionHandle['rpc']['open']> = () => unexpectedInProcessStream(),
  277. ): Promise<{
  278. readonly ctx: Context
  279. readonly client: Fiber
  280. readonly generation: GenerationHarness
  281. readonly start: ReturnType<typeof vi.fn<ConnectionHandle['start']>>
  282. }> {
  283. const ctx = new Context()
  284. await ctx.plugin(TypertRegistry)
  285. const rpc = carrier === 'web'
  286. ? { call }
  287. : { call, open }
  288. const generation = new GenerationHarness()
  289. const start = vi.fn<ConnectionHandle['start']>(() => ({ stop: () => {} }))
  290. ctx.provide('connection', {
  291. rpc,
  292. registerGenerationSource: generation.register,
  293. start,
  294. } as unknown as ConnectionHandle)
  295. const client = ctx.plugin({ inject, apply })
  296. await client
  297. return { ctx, client, generation, start }
  298. }
  299. async function *unexpectedInProcessStream(): AsyncGenerator<never> {
  300. throw new Error('fixture did not install an in-process stream')
  301. }
  302. interface GenerationRun {
  303. readonly signal: AbortSignal
  304. readonly ready: Promise<void>
  305. readonly done: Promise<void>
  306. abort(reason?: unknown): void
  307. }
  308. class GenerationHarness {
  309. private source: ConnectionGenerationSource | undefined
  310. private active: AbortController | undefined
  311. readonly register = (source: ConnectionGenerationSource): (() => void) => {
  312. if (this.source !== undefined) throw new Error('fixture generation source already registered')
  313. this.source = source
  314. return () => {
  315. if (this.source !== source) return
  316. this.source = undefined
  317. this.active?.abort(new Error('fixture generation source removed'))
  318. this.active = undefined
  319. }
  320. }
  321. start(): GenerationRun {
  322. if (this.source === undefined) throw new Error('fixture generation source is not registered')
  323. if (this.active !== undefined) throw new Error('fixture generation is already active')
  324. const source = this.source
  325. const controller = new AbortController()
  326. this.active = controller
  327. let reportReady!: () => void
  328. const ready = new Promise<void>((resolve) => { reportReady = resolve })
  329. const done = Promise.resolve()
  330. .then(() => source(controller.signal, reportReady))
  331. .finally(() => {
  332. if (this.active === controller) this.active = undefined
  333. })
  334. void done.catch(() => undefined)
  335. return {
  336. signal: controller.signal,
  337. ready,
  338. done,
  339. abort: (reason) => { controller.abort(reason) },
  340. }
  341. }
  342. startOverlapping(): GenerationRun {
  343. if (this.source === undefined) throw new Error('fixture generation source is not registered')
  344. const controller = new AbortController()
  345. let reportReady!: () => void
  346. const ready = new Promise<void>((resolve) => { reportReady = resolve })
  347. const done = Promise.resolve().then(() => this.source?.(controller.signal, reportReady))
  348. .then(() => undefined)
  349. void done.catch(() => undefined)
  350. return {
  351. signal: controller.signal,
  352. ready,
  353. done,
  354. abort: (reason) => { controller.abort(reason) },
  355. }
  356. }
  357. }
  358. function deferredReadiness(): {
  359. readonly promise: Promise<void>
  360. readonly resolve: () => void
  361. readonly reject: (error: unknown) => void
  362. } {
  363. let resolve!: () => void
  364. let reject!: (error: unknown) => void
  365. const promise = new Promise<void>((accept, decline) => {
  366. resolve = accept
  367. reject = decline
  368. })
  369. return { promise, resolve, reject }
  370. }
  371. async function loaderReadinessBench(
  372. readiness: Promise<unknown>,
  373. carrier: 'in-process' | 'web' = 'in-process',
  374. ): Promise<{
  375. readonly client: Fiber
  376. readonly start: ReturnType<typeof vi.fn<ConnectionHandle['start']>>
  377. readonly stop: ReturnType<typeof vi.fn<() => void>>
  378. }> {
  379. const ctx = new Context()
  380. await ctx.plugin(TypertRegistry)
  381. const generation = new GenerationHarness()
  382. const stop = vi.fn<() => void>()
  383. const start = vi.fn<ConnectionHandle['start']>(() => ({ stop }))
  384. const call = vi.fn<ConnectionHandle['rpc']['call']>()
  385. ctx.provide('connection', {
  386. rpc: carrier === 'web' ? { call } : { call, open: () => unexpectedInProcessStream() },
  387. registerGenerationSource: generation.register,
  388. start,
  389. } as unknown as ConnectionHandle)
  390. ctx.provide('loader', { await: () => readiness })
  391. const client = ctx.plugin({ inject, apply })
  392. await client
  393. return { client, start, stop }
  394. }
  395. type EventStreamItem =
  396. | { readonly kind: 'frame'; readonly value: unknown }
  397. | { readonly kind: 'end' }
  398. | { readonly kind: 'fail'; readonly error: unknown }
  399. interface EventStreamConnection {
  400. readonly items: EventStreamItem[]
  401. wake: (() => void) | undefined
  402. }
  403. class RemoteEventCarrier {
  404. readonly calls: {
  405. readonly channel: string
  406. readonly endpoint: string
  407. readonly payload: unknown
  408. readonly signal: AbortSignal
  409. }[] = []
  410. private readonly connections = new Set<EventStreamConnection>()
  411. private nextClient = 1
  412. get activeConnections(): number {
  413. return this.connections.size
  414. }
  415. readonly open: NonNullable<ConnectionHandle['rpc']['open']> = (channel, endpoint, payload, signal) => {
  416. this.calls.push({ channel, endpoint, payload, signal })
  417. return this.iterate(signal)
  418. }
  419. emit(value: unknown): void {
  420. this.feed({ kind: 'frame', value })
  421. }
  422. end(): void {
  423. this.feed({ kind: 'end' })
  424. }
  425. fail(error: unknown): void {
  426. this.feed({ kind: 'fail', error })
  427. }
  428. private feed(item: EventStreamItem): void {
  429. for (const connection of this.connections) {
  430. connection.items.push(item)
  431. connection.wake?.()
  432. }
  433. }
  434. private async *iterate(signal: AbortSignal): AsyncGenerator {
  435. signal.throwIfAborted()
  436. const clientId = `event-client-${String(this.nextClient++)}`
  437. const connection: EventStreamConnection = { items: [], wake: undefined }
  438. this.connections.add(connection)
  439. const abort = (): void => { connection.wake?.() }
  440. signal.addEventListener('abort', abort, { once: true })
  441. try {
  442. yield { type: 'ready', clientId, host: { home: '/home/fixture' } }
  443. while (!signal.aborted) {
  444. while (connection.items.length > 0) {
  445. const item = connection.items.shift() as EventStreamItem
  446. if (item.kind === 'end') return
  447. if (item.kind === 'fail') throw item.error
  448. yield item.value
  449. }
  450. if (signal.aborted) return
  451. await new Promise<void>((resolve) => { connection.wake = resolve })
  452. connection.wake = undefined
  453. }
  454. } finally {
  455. signal.removeEventListener('abort', abort)
  456. this.connections.delete(connection)
  457. }
  458. }
  459. }
  460. async function eventBench(
  461. call: ConnectionHandle['rpc']['call'] = vi.fn<ConnectionHandle['rpc']['call']>()
  462. .mockResolvedValue({ ok: true, value: undefined }),
  463. ): Promise<{
  464. readonly ctx: Context
  465. readonly client: Fiber
  466. readonly carrier: RemoteEventCarrier
  467. readonly generation: GenerationHarness
  468. readonly run: GenerationRun
  469. readonly call: ConnectionHandle['rpc']['call']
  470. }> {
  471. const carrier = new RemoteEventCarrier()
  472. const { ctx, client, generation } = await benchFiber(
  473. call,
  474. 'in-process',
  475. carrier.open,
  476. )
  477. const run = generation.start()
  478. await run.ready
  479. return { ctx, client, carrier, generation, run, call }
  480. }
  481. function approvalFrame(eventId: string, agentId: string, prompt: string): object {
  482. return {
  483. type: 'waterfall',
  484. event: 'fixture/approval',
  485. eventId,
  486. agentId,
  487. request: { prompt },
  488. }
  489. }
  490. describe('Client Remote transport readiness', () => {
  491. it('creates logical stream supervisors against the installed Connection', async () => {
  492. const { ctx, client } = await benchFiber(vi.fn<ConnectionHandle['rpc']['call']>())
  493. const stream = ctx.remote.$stream({
  494. name: 'fixture stream',
  495. open: () => unexpectedInProcessStream(),
  496. ended: () => new Error('fixture stream ended'),
  497. })
  498. expect(stream).toBeInstanceOf(RemoteStream)
  499. await stream.dispose()
  500. await client.dispose()
  501. })
  502. it('reports Host facts as plain reads and keeps them through Connection withdrawal', async () => {
  503. const ctx = new Context()
  504. await ctx.plugin(TypertRegistry)
  505. const generation = new GenerationHarness()
  506. const live: { snapshot: ConnectionGeneration | undefined } = { snapshot: undefined }
  507. const handle = {
  508. isLoopback: true,
  509. generation: { getSnapshot: () => live.snapshot, subscribe: () => () => {} },
  510. rpc: {
  511. call: vi.fn<ConnectionHandle['rpc']['call']>(),
  512. open: () => unexpectedInProcessStream(),
  513. },
  514. registerGenerationSource: generation.register,
  515. start: () => ({ stop: () => {} }),
  516. } as unknown as ConnectionHandle
  517. const withdraw = ctx.provide('connection', handle)
  518. const client = ctx.plugin({ inject, apply })
  519. await client
  520. const remote = ctx.remote
  521. const beforeReady = remote.$host
  522. expect(beforeReady).toEqual({ home: undefined, isLoopback: true })
  523. expect(remote.$host).toBe(beforeReady)
  524. live.snapshot = { id: 1, host: { home: '/hosts/primary' } }
  525. const afterReady = remote.$host
  526. expect(afterReady).toEqual({ home: '/hosts/primary', isLoopback: true })
  527. expect(afterReady).not.toBe(beforeReady)
  528. expect(remote.$host).toBe(afterReady)
  529. withdraw()
  530. expect(ctx.get('connection')).toBeUndefined()
  531. expect(remote.$host).toBe(afterReady)
  532. })
  533. it('forwards each connection retry to the browser WebSocket owner', async () => {
  534. await withFakeWebSocket('https://harness.example', async () => {
  535. FakeWebSocket.autoOpen = false
  536. const { client, start } = await benchFiber(
  537. vi.fn<ConnectionHandle['rpc']['call']>(),
  538. 'web',
  539. )
  540. try {
  541. expect(FakeWebSocket.sockets).toHaveLength(1)
  542. start.mock.calls[0]![0].onReconnectRequested?.()
  543. await vi.waitFor(() => { expect(FakeWebSocket.sockets).toHaveLength(2) })
  544. } finally {
  545. await client.dispose()
  546. }
  547. })
  548. })
  549. it.each([false, true])('replaces a stalled carrier and restores events (socket opened: %s)', async (autoOpen) => {
  550. await withFakeWebSocket('https://harness.example', async () => {
  551. vi.useFakeTimers()
  552. vi.stubGlobal('__DSH_CONNECTION_RECOVERY__', {
  553. backoffBaseMs: 10, backoffMaxMs: 10, generationReadyTimeoutMs: 100,
  554. })
  555. Object.assign(globalThis.location, { hostname: 'harness.example', search: '' })
  556. const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
  557. FakeWebSocket.autoOpen = autoOpen
  558. const ctx = new Context()
  559. const reset = vi.fn()
  560. ctx.on('connection/reset', reset)
  561. try {
  562. await ctx.plugin(TypertRegistry)
  563. await ctx.plugin({ inject: [], apply: applyConnection })
  564. await ctx.plugin({ inject, apply })
  565. await vi.advanceTimersByTimeAsync(0)
  566. const connection = ctx.get('connection') as ConnectionHandle
  567. expect(FakeWebSocket.sockets).toHaveLength(1)
  568. expect(connection.generation.getSnapshot()).toBeUndefined()
  569. await vi.advanceTimersByTimeAsync(110)
  570. expect(FakeWebSocket.sockets).toHaveLength(2)
  571. expect(FakeWebSocket.sockets[0]?.readyState).toBe(FakeWebSocket.CLOSED)
  572. expect(FakeWebSocket.sockets[0]?.closedWith).toHaveLength(1)
  573. expect(reset).not.toHaveBeenCalled()
  574. const replacement = FakeWebSocket.sockets[1]!
  575. replacement.open()
  576. await vi.advanceTimersByTimeAsync(0)
  577. const opening = JSON.parse(replacement.sent[0]!) as { streamId: string }
  578. replacement.receive({
  579. type: 'item', streamId: opening.streamId,
  580. value: { type: 'ready', clientId: 'recovered-client', host: { home: '/recovered' } },
  581. })
  582. await vi.advanceTimersByTimeAsync(0)
  583. expect(connection.state.getSnapshot()).toBe('connected')
  584. expect(connection.generation.getSnapshot()?.host.home).toBe('/recovered')
  585. expect(reset).toHaveBeenCalledOnce()
  586. expect(vi.getTimerCount()).toBe(0)
  587. } finally {
  588. await ctx.fiber.dispose()
  589. await vi.advanceTimersByTimeAsync(0)
  590. warnSpy.mockRestore()
  591. vi.unstubAllGlobals()
  592. vi.useRealTimers()
  593. }
  594. })
  595. })
  596. it('does not replace an in-process carrier when Connection retries', async () => {
  597. const { client, start } = await benchFiber(
  598. vi.fn<ConnectionHandle['rpc']['call']>(),
  599. 'in-process',
  600. )
  601. try {
  602. expect(() => { start.mock.calls[0]![0].onReconnectRequested?.() }).not.toThrow()
  603. } finally {
  604. await client.dispose()
  605. }
  606. })
  607. it('starts after Loader settlement and stops the owned loop on disposal', async () => {
  608. const readiness = deferredReadiness()
  609. const { client, start, stop } = await loaderReadinessBench(readiness.promise)
  610. expect(start).not.toHaveBeenCalled()
  611. readiness.resolve()
  612. await vi.waitFor(() => { expect(start).toHaveBeenCalledTimes(1) })
  613. await client.dispose()
  614. expect(stop).toHaveBeenCalledTimes(1)
  615. })
  616. it('starts a fresh WebSocket attempt when Loader settles after the eager attempt failed', async () => {
  617. await withFakeWebSocket('https://harness.example', async () => {
  618. FakeWebSocket.autoOpen = false
  619. const readiness = deferredReadiness()
  620. const { client, start } = await loaderReadinessBench(readiness.promise, 'web')
  621. expect(FakeWebSocket.sockets).toHaveLength(1)
  622. FakeWebSocket.sockets[0]!.fail()
  623. readiness.resolve()
  624. await vi.waitFor(() => { expect(FakeWebSocket.sockets).toHaveLength(2) })
  625. expect(start).toHaveBeenCalledOnce()
  626. await client.dispose()
  627. })
  628. })
  629. it('does not start when disposal wins the Loader-settlement race', async () => {
  630. const readiness = deferredReadiness()
  631. const { client, start, stop } = await loaderReadinessBench(readiness.promise)
  632. await client.dispose()
  633. readiness.resolve()
  634. await Promise.resolve()
  635. expect(start).not.toHaveBeenCalled()
  636. expect(stop).not.toHaveBeenCalled()
  637. })
  638. it('leaves the transport stopped when Loader settlement rejects', async () => {
  639. const readiness = deferredReadiness()
  640. const { client, start, stop } = await loaderReadinessBench(readiness.promise)
  641. readiness.reject(new Error('fixture Loader failed'))
  642. await Promise.resolve()
  643. await Promise.resolve()
  644. expect(start).not.toHaveBeenCalled()
  645. await client.dispose()
  646. expect(stop).not.toHaveBeenCalled()
  647. })
  648. })
  649. describe('Client Typert API', () => {
  650. it('mounts concrete direct methods, validates inputs, and withdraws retained handles', async () => {
  651. const call = vi.fn<ConnectionHandle['rpc']['call']>()
  652. .mockResolvedValue({ ok: true, value: { ref: 'goal-1' } })
  653. const ctx = await bench(call)
  654. const businessProbe = { owner: 'host business service' }
  655. const disposeBusinessProbe = ctx.provide('probe', businessProbe)
  656. const assembly = ctx.plugin(Object.assign(
  657. (scope: Context) => scope.remote.$mount({ package: '@fixture/probe', descriptors: [directDescriptor()] }),
  658. { inject: ['remote'] },
  659. ))
  660. await assembly
  661. const retained = ctx.remote.probe.create
  662. await expect(ctx.remote.probe.create('agent-1', { objective: 'ship' }))
  663. .resolves.toEqual({ ok: true, value: { ref: 'goal-1' } })
  664. expect(call).toHaveBeenCalledWith(
  665. '/api',
  666. 'probe/create',
  667. { args: { agentId: 'agent-1', request: { objective: 'ship' } } },
  668. expect.any(AbortSignal),
  669. )
  670. const callerAbort = new AbortController()
  671. await expect(ctx.remote.probe.create(
  672. 'agent-1',
  673. { objective: 'cancel me' },
  674. callerAbort.signal,
  675. )).resolves.toEqual({ ok: true, value: { ref: 'goal-1' } })
  676. const combinedSignal = call.mock.calls.at(-1)?.[3]
  677. expect(combinedSignal).toBeInstanceOf(AbortSignal)
  678. expect(combinedSignal).not.toBe(callerAbort.signal)
  679. const cancellation = new Error('caller cancelled')
  680. callerAbort.abort(cancellation)
  681. expect(combinedSignal?.aborted).toBe(true)
  682. expect(combinedSignal?.reason).toBe(cancellation)
  683. await expect(ctx.remote.probe.create('', { objective: 'ship' })).rejects.toThrow('rejected "agentId"')
  684. call.mockResolvedValueOnce({ ok: true, value: { ref: 1 } })
  685. await expect(ctx.remote.probe.create('agent-1', { objective: 'ship' })).resolves.toEqual({
  686. ok: true,
  687. value: { ref: 1 },
  688. })
  689. await assembly.dispose()
  690. expect((ctx.remote as unknown as Record<string, unknown>).probe).toBeUndefined()
  691. expect(ctx.get('remote.probe')).toBeUndefined()
  692. expect(ctx.get('probe')).toBe(businessProbe)
  693. expect(ctx.typert.remotes.list()).toEqual([])
  694. await expect(retained?.('agent-1', { objective: 'ship' })).resolves.toMatchObject({
  695. ok: false,
  696. error: {
  697. code: 'gateway/internal',
  698. message: 'client api: Remote method probe/create is no longer mounted',
  699. details: {},
  700. },
  701. })
  702. disposeBusinessProbe()
  703. })
  704. it('encodes declared undefined as an omitted argument and distinguishes it from null results', async () => {
  705. const call = vi.fn<ConnectionHandle['rpc']['call']>()
  706. .mockResolvedValueOnce({ ok: true, value: undefined })
  707. .mockResolvedValueOnce({ ok: true, value: null })
  708. const ctx = await bench(call)
  709. const dispose = await ctx.remote.$mount({
  710. package: '@fixture/maybe',
  711. descriptors: [maybeDescriptor()],
  712. })
  713. await expect(ctx.remote.probe.maybe(undefined)).resolves.toStrictEqual({ ok: true, value: undefined })
  714. expect(call).toHaveBeenNthCalledWith(
  715. 1,
  716. '/api',
  717. 'probe/maybe',
  718. { args: {} },
  719. expect.any(AbortSignal),
  720. )
  721. await expect(ctx.remote.probe.maybe(null)).resolves.toStrictEqual({ ok: true, value: null })
  722. expect(call).toHaveBeenNthCalledWith(
  723. 2,
  724. '/api',
  725. 'probe/maybe',
  726. { args: { value: null } },
  727. expect.any(AbortSignal),
  728. )
  729. await dispose()
  730. })
  731. it('projects one direct lookup descriptor onto an Agent-scoped alias', async () => {
  732. const call = vi.fn<ConnectionHandle['rpc']['call']>()
  733. .mockResolvedValue({ ok: true, value: { ref: 'goal-2' } })
  734. const ctx = await bench(call)
  735. const agentCtx = ctx.extend({ fixtureId: 'agent-2' }) as FixtureContext
  736. ctx.typert.contexts.registerClient('fixture', {
  737. identity: candidate => (candidate as Context & { fixtureId?: string }).fixtureId,
  738. resolve: id => id === 'agent-2' ? agentCtx : undefined,
  739. })
  740. const assembly = ctx.plugin(Object.assign(
  741. (scope: Context) => scope.remote.$mount({ package: '@fixture/probe', descriptors: [directDescriptor()] }),
  742. { inject: ['remote'] },
  743. ))
  744. await assembly
  745. await expect(agentCtx.remote.probe.create({ objective: 'ship scoped' }))
  746. .resolves.toEqual({ ok: true, value: { ref: 'goal-2' } })
  747. expect(call).toHaveBeenCalledWith(
  748. '/api',
  749. 'probe/create',
  750. { args: { agentId: 'agent-2', request: { objective: 'ship scoped' } } },
  751. expect.any(AbortSignal),
  752. )
  753. await expect((ctx as FixtureContext).remote.probe.create({ objective: 'wrong scope' }))
  754. .rejects.toThrow('expected 2 business argument(s)')
  755. await assembly.dispose()
  756. expect((ctx.remote as unknown as Record<string, unknown>).probe).toBeUndefined()
  757. expect(ctx.get('remote.probe')).toBeUndefined()
  758. })
  759. it('uses the caller Context identity for scoped namespace methods', async () => {
  760. const call = vi.fn<ConnectionHandle['rpc']['call']>()
  761. .mockResolvedValue({ ok: true, value: { renamed: true } })
  762. const ctx = await bench(call)
  763. const agentCtx = ctx.extend({ fixtureId: 'agent-2' }) as FixtureContext
  764. ctx.typert.contexts.registerClient('fixture', {
  765. identity: candidate => (candidate as Context & { fixtureId?: string }).fixtureId,
  766. resolve: id => id === 'agent-2' ? agentCtx : undefined,
  767. })
  768. const assembly = ctx.plugin(Object.assign(
  769. (scope: Context) => scope.remote.$mount({ package: '@fixture/probe', descriptors: [contextDescriptor()] }),
  770. { inject: ['remote'] },
  771. ))
  772. await assembly
  773. await expect(agentCtx.remote.probe.rename({ objective: 'land' }))
  774. .resolves.toEqual({ ok: true, value: { renamed: true } })
  775. expect(call).toHaveBeenCalledWith(
  776. '/api',
  777. 'probe/rename',
  778. { args: { agentId: 'agent-2', request: { objective: 'land' } } },
  779. expect.any(AbortSignal),
  780. )
  781. await expect((ctx as FixtureContext).remote.probe.rename({ objective: 'land' }))
  782. .rejects.toThrow('requires a "fixture" Context')
  783. await assembly.dispose()
  784. expect(ctx.get('remote.probe')).toBeUndefined()
  785. })
  786. it('accepts weak result codecs and rejects namespace collisions before registration', async () => {
  787. const ctx = await bench(vi.fn<ConnectionHandle['rpc']['call']>())
  788. const weak: InvocationDescriptor = {
  789. ...directDescriptor(),
  790. result: { mode: 'src-json' },
  791. }
  792. const disposeWeak = await ctx.remote.$mount({ package: '@fixture/weak', descriptors: [weak] })
  793. await disposeWeak()
  794. await expect(ctx.remote.$mount({
  795. package: '@fixture/conflict',
  796. descriptors: [{ ...directDescriptor(), namespace: '$mount' }],
  797. })).rejects.toThrow('conflicts with the Remote service')
  798. expect(ctx.typert.remotes.list()).toEqual([])
  799. })
  800. it('rejects duplicate, live, scoped-service, and Context namespace collisions', async () => {
  801. const call = vi.fn<ConnectionHandle['rpc']['call']>()
  802. .mockResolvedValue({ ok: true, value: { renamed: true } })
  803. const ctx = await bench(call)
  804. const agentCtx = ctx.extend({ fixtureId: 'agent-remounted' }) as FixtureContext
  805. ctx.typert.contexts.registerClient('fixture', {
  806. identity: candidate => (candidate as Context & { fixtureId?: string }).fixtureId,
  807. resolve: id => id === 'agent-remounted' ? agentCtx : undefined,
  808. })
  809. const direct = directDescriptor()
  810. const context = contextDescriptor()
  811. await expect(ctx.remote.$mount({
  812. package: '@fixture/direct-duplicates',
  813. descriptors: [direct, { ...direct, id: '@fixture/probe#probe/create-again' }],
  814. })).rejects.toThrow('repeats direct method')
  815. await expect(ctx.remote.$mount({
  816. package: '@fixture/scoped-duplicates',
  817. descriptors: [context, { ...context, id: '@fixture/probe#probe/rename-again' }],
  818. })).rejects.toThrow('repeats scoped method')
  819. const disposeDirect = await ctx.remote.$mount({ package: '@fixture/direct-live', descriptors: [direct] })
  820. await expect(ctx.remote.$mount({
  821. package: '@fixture/direct-conflict', descriptors: [{ ...direct, id: '@fixture/other#probe/create' }],
  822. })).rejects.toThrow('direct method probe/create is already mounted')
  823. await disposeDirect()
  824. const disposeScoped = await ctx.remote.$mount({ package: '@fixture/scoped-live', descriptors: [context] })
  825. await expect(ctx.remote.$mount({
  826. package: '@fixture/scoped-conflict', descriptors: [{ ...context, id: '@fixture/other#probe/rename' }],
  827. })).rejects.toThrow('scoped method probe/rename is already mounted')
  828. await expect(ctx.remote.$mount({
  829. package: '@fixture/service-method-conflict',
  830. descriptors: [{ ...context, id: '@fixture/probe#probe/remove', method: 'remove' }],
  831. })).rejects.toThrow('conflicts with its namespace service')
  832. const scopedService = ctx.get('remote.probe') as unknown as object
  833. Object.defineProperty(scopedService, 'custom', { configurable: true, value: () => undefined })
  834. await expect(ctx.remote.$mount({
  835. package: '@fixture/service-own-property-conflict',
  836. descriptors: [{ ...direct, id: '@fixture/probe#probe/custom', method: 'custom' }],
  837. })).rejects.toThrow('conflicts with its namespace service')
  838. Reflect.deleteProperty(scopedService, 'custom')
  839. await disposeScoped()
  840. const disposeRemoteTypert = ctx.reflect.provide('remote.typert', { owner: 'fixture' })
  841. await expect(ctx.remote.$mount({
  842. package: '@fixture/context-property-conflict',
  843. descriptors: [{ ...context, namespace: 'typert' }],
  844. })).rejects.toThrow('conflicts with an existing Remote namespace')
  845. await disposeRemoteTypert()
  846. const disposeMultipleScoped = await ctx.remote.$mount({
  847. package: '@fixture/multiple-scoped',
  848. descriptors: [directDescriptor(), contextDescriptor()],
  849. })
  850. await expect(agentCtx.remote.probe.rename({ objective: 'remounted' }))
  851. .resolves.toEqual({ ok: true, value: { renamed: true } })
  852. expect(call).toHaveBeenLastCalledWith(
  853. '/api',
  854. 'probe/rename',
  855. { args: { agentId: 'agent-remounted', request: { objective: 'remounted' } } },
  856. expect.any(AbortSignal),
  857. )
  858. await disposeMultipleScoped()
  859. })
  860. it('rolls back earlier descriptors when a later descriptor fails to install', async () => {
  861. const ctx = await bench(vi.fn<ConnectionHandle['rpc']['call']>())
  862. const { scope: _scope, ...first } = directDescriptor()
  863. const second: InvocationDescriptor = {
  864. ...first,
  865. id: '@fixture/probe#probe/archive',
  866. method: 'archive',
  867. }
  868. const defineProperty = Object.defineProperty
  869. const spy = vi.spyOn(Object, 'defineProperty').mockImplementation((target, key, attributes) => {
  870. if (key === 'archive') throw new Error('fixture later-descriptor failure')
  871. return defineProperty(target, key, attributes)
  872. })
  873. try {
  874. await expect(ctx.remote.$mount({ package: '@fixture/failing-batch', descriptors: [first, second] }))
  875. .rejects.toThrow('fixture later-descriptor failure')
  876. } finally {
  877. spy.mockRestore()
  878. }
  879. expect((ctx.remote as unknown as Record<string, unknown>).probe).toBeUndefined()
  880. await vi.waitFor(() => { expect(ctx.typert.remotes.list()).toEqual([]) })
  881. const retry = await ctx.remote.$mount({ package: '@fixture/retry-batch', descriptors: [first, second] })
  882. expect(ctx.remote.probe.create).toBeTypeOf('function')
  883. expect((ctx.remote.probe as unknown as Record<string, unknown>).archive).toBeTypeOf('function')
  884. await retry()
  885. })
  886. it('rolls back earlier namespaces when a later namespace fails to install', async () => {
  887. const ctx = await bench(vi.fn<ConnectionHandle['rpc']['call']>())
  888. const { scope: _scope, ...first } = directDescriptor()
  889. const second: InvocationDescriptor = {
  890. ...first,
  891. id: '@fixture/archive#archive/store',
  892. namespace: 'archive',
  893. method: 'store',
  894. }
  895. const defineProperty = Object.defineProperty
  896. const spy = vi.spyOn(Object, 'defineProperty').mockImplementation((target, key, attributes) => {
  897. if (key === 'store') throw new Error('fixture later-namespace failure')
  898. return defineProperty(target, key, attributes)
  899. })
  900. try {
  901. await expect(ctx.remote.$mount({
  902. package: '@fixture/failing-namespaces',
  903. descriptors: [first, second],
  904. })).rejects.toThrow('fixture later-namespace failure')
  905. } finally {
  906. spy.mockRestore()
  907. }
  908. expect((ctx.remote as unknown as Record<string, unknown>).probe).toBeUndefined()
  909. expect((ctx.remote as unknown as Record<string, unknown>).archive).toBeUndefined()
  910. await vi.waitFor(() => { expect(ctx.typert.remotes.list()).toEqual([]) })
  911. const retry = await ctx.remote.$mount({
  912. package: '@fixture/retry-namespaces',
  913. descriptors: [first, second],
  914. })
  915. expect(ctx.remote.probe.create).toBeTypeOf('function')
  916. expect((ctx.remote as unknown as Record<string, Record<string, unknown>>).archive?.store).toBeTypeOf('function')
  917. await retry()
  918. })
  919. it('rolls back a direct projection when its scoped projection fails to install', async () => {
  920. const ctx = await bench(vi.fn<ConnectionHandle['rpc']['call']>())
  921. const disposeContext = await ctx.remote.$mount({
  922. package: '@fixture/context-anchor',
  923. descriptors: [contextDescriptor()],
  924. })
  925. const namespace = ctx.get('remote.probe') as unknown as {
  926. installScoped: (...args: unknown[]) => void
  927. readonly create?: unknown
  928. }
  929. const installScoped = vi.spyOn(namespace, 'installScoped').mockImplementation(() => {
  930. throw new Error('fixture scoped projection failure')
  931. })
  932. try {
  933. await expect(ctx.remote.$mount({
  934. package: '@fixture/direct-projection-failure',
  935. descriptors: [directDescriptor()],
  936. })).rejects.toThrow('fixture scoped projection failure')
  937. } finally {
  938. installScoped.mockRestore()
  939. }
  940. expect(namespace.create).toBeUndefined()
  941. await disposeContext()
  942. })
  943. it('unwinds an already-installed namespace when a later namespace fails to install', async () => {
  944. const ctx = await bench(vi.fn<ConnectionHandle['rpc']['call']>())
  945. const { scope: _scope, ...probe } = directDescriptor()
  946. const vault: InvocationDescriptor = {
  947. ...probe,
  948. id: '@fixture/vault#vault/seal',
  949. service: 'vault',
  950. namespace: 'vault',
  951. method: 'seal',
  952. }
  953. const defineProperty = Object.defineProperty
  954. const spy = vi.spyOn(Object, 'defineProperty').mockImplementation((target, key, attributes) => {
  955. if (key === 'seal') throw new Error('fixture later-namespace failure')
  956. return defineProperty(target, key, attributes)
  957. })
  958. try {
  959. await expect(ctx.remote.$mount({ package: '@fixture/two-namespaces', descriptors: [probe, vault] }))
  960. .rejects.toThrow('fixture later-namespace failure')
  961. } finally {
  962. spy.mockRestore()
  963. }
  964. expect((ctx.remote as unknown as Record<string, unknown>).probe).toBeUndefined()
  965. expect((ctx.remote as unknown as Record<string, unknown>).vault).toBeUndefined()
  966. await vi.waitFor(() => { expect(ctx.typert.remotes.list()).toEqual([]) })
  967. })
  968. it('rolls back an earlier scoped projection when a later descriptor fails to install', async () => {
  969. const ctx = await bench(vi.fn<ConnectionHandle['rpc']['call']>())
  970. const { scope: _scope, ...direct } = directDescriptor()
  971. const failing: InvocationDescriptor = {
  972. ...direct,
  973. id: '@fixture/probe#probe/archive',
  974. method: 'archive',
  975. }
  976. const defineProperty = Object.defineProperty
  977. const spy = vi.spyOn(Object, 'defineProperty').mockImplementation((target, key, attributes) => {
  978. if (key === 'archive') throw new Error('fixture trailing failure')
  979. return defineProperty(target, key, attributes)
  980. })
  981. try {
  982. await expect(ctx.remote.$mount({
  983. package: '@fixture/scoped-then-failing',
  984. descriptors: [contextDescriptor(), failing],
  985. })).rejects.toThrow('fixture trailing failure')
  986. } finally {
  987. spy.mockRestore()
  988. }
  989. expect((ctx.remote as unknown as Record<string, unknown>).probe).toBeUndefined()
  990. await vi.waitFor(() => { expect(ctx.typert.remotes.list()).toEqual([]) })
  991. })
  992. it('keeps a namespace another contribution still populates when a group leaves', async () => {
  993. const call = vi.fn<ConnectionHandle['rpc']['call']>()
  994. .mockResolvedValue({ ok: true, value: { renamed: true } })
  995. const ctx = await bench(call)
  996. const { scope: _scope, ...direct } = directDescriptor()
  997. const disposeDirect = await ctx.remote.$mount({ package: '@fixture/direct-owner', descriptors: [direct] })
  998. const disposeScoped = await ctx.remote.$mount({ package: '@fixture/scoped-owner', descriptors: [contextDescriptor()] })
  999. await disposeDirect()
  1000. // The namespace survives its first group: the second contribution still owns methods on it.
  1001. const surviving = ctx.get('remote.probe') as unknown as Record<string, unknown> | undefined
  1002. expect(surviving).toBeDefined()
  1003. expect(surviving?.create).toBeUndefined()
  1004. await disposeScoped()
  1005. expect(ctx.get('remote.probe')).toBeUndefined()
  1006. })
  1007. it('unparks a namespace dependent only after its contribution methods exist', async () => {
  1008. const ctx = await bench(vi.fn<ConnectionHandle['rpc']['call']>())
  1009. const { scope: _scope, ...direct } = directDescriptor()
  1010. let observed: string | undefined
  1011. // Parked before the mount: the unpark moment is the observation — the
  1012. // atomic-visibility guarantee says the service never appears methodless.
  1013. const parked = ctx.inject(['remote.probe'], (probeCtx) => {
  1014. observed = typeof (probeCtx.get('remote.probe') as { create?: unknown } | undefined)?.create
  1015. })
  1016. const dispose = await ctx.remote.$mount({ package: '@fixture/atomic-visibility', descriptors: [direct] })
  1017. await parked
  1018. expect(observed).toBe('function')
  1019. await dispose()
  1020. })
  1021. it('rejects weak parameter and Context codecs plus malformed scope projections', async () => {
  1022. const ctx = await bench(vi.fn<ConnectionHandle['rpc']['call']>())
  1023. const direct = directDescriptor()
  1024. const context = contextDescriptor()
  1025. await expect(ctx.remote.$mount({
  1026. package: '@fixture/weak-parameter',
  1027. descriptors: [{
  1028. ...direct,
  1029. parameters: direct.parameters.map((parameter, index) => index === 0
  1030. ? { ...parameter, codec: { mode: 'src-json' } }
  1031. : parameter),
  1032. }],
  1033. })).rejects.toThrow('has no strict codec')
  1034. await expect(ctx.remote.$mount({
  1035. package: '@fixture/weak-context',
  1036. descriptors: [{
  1037. ...context,
  1038. invocation: { ...context.invocation, codec: { mode: 'src-json' } },
  1039. } as InvocationDescriptor],
  1040. })).rejects.toThrow('has no strict codec')
  1041. await expect(ctx.remote.$mount({
  1042. package: '@fixture/malformed-scope',
  1043. descriptors: [{ ...direct, scope: { context: 'fixture', wire: 'missingId' } }],
  1044. })).rejects.toThrow('scope must select its only lookup parameter')
  1045. await expect(ctx.remote.$mount({
  1046. package: '@fixture/ambiguous-scope',
  1047. descriptors: [{
  1048. ...direct,
  1049. parameters: [...direct.parameters, {
  1050. name: 'other', wire: 'otherId', source: 'lookup', lookup: 'fixture',
  1051. codec: { mode: 'strict', typeSymbol: '@fixture#AgentId', schema: idSchema },
  1052. }],
  1053. }],
  1054. })).rejects.toThrow('scope must select its only lookup parameter')
  1055. })
  1056. it('validates invocation arity, required adapters, live Connection, and mutable descriptor codecs', async () => {
  1057. const call = vi.fn<ConnectionHandle['rpc']['call']>()
  1058. .mockResolvedValue({ ok: true, value: { ref: 'goal-1' } })
  1059. const ctx = await bench(call)
  1060. const descriptor = directDescriptor()
  1061. const dispose = await ctx.remote.$mount({
  1062. package: '@fixture/probe',
  1063. descriptors: [descriptor, contextDescriptor()],
  1064. })
  1065. const create = ctx.remote.probe.create as unknown as (...args: unknown[]) => Promise<unknown>
  1066. const probe = (ctx as FixtureContext).remote.probe
  1067. const rename = probe.rename as unknown as (...args: unknown[]) => Promise<unknown>
  1068. await expect(create('agent-1')).rejects.toThrow('expected 2 business argument(s) plus an optional AbortSignal, got 1')
  1069. await expect(create('agent-1', { objective: 'ship' }, undefined, 'extra'))
  1070. .rejects.toThrow('got 4')
  1071. await expect(rename.call(probe)).rejects.toThrow('expected 1 argument(s), got 0')
  1072. await expect((ctx as FixtureContext).remote.probe.create({ objective: 'ship' }))
  1073. .rejects.toThrow('expected 2 business argument(s)')
  1074. await expect((ctx as FixtureContext).remote.probe.rename({ objective: 'ship' }))
  1075. .rejects.toThrow('no Client Context adapter')
  1076. ;(descriptor.parameters[0] as { codec: { mode: string } }).codec.mode = 'src-json'
  1077. await expect(ctx.remote.probe.create('agent-1', { objective: 'ship' })).rejects.toThrow('has no strict codec')
  1078. ;(descriptor.parameters[0] as { codec: { mode: string } }).codec.mode = 'strict'
  1079. ctx.set('connection', undefined)
  1080. await expect(ctx.remote.probe.create('agent-1', { objective: 'ship' })).rejects.toThrow('no active Connection')
  1081. await dispose()
  1082. })
  1083. it('withdraws a pending invocation and preserves a direct namespace until its last method leaves', async () => {
  1084. let resolveCall!: (result: Awaited<ReturnType<ConnectionHandle['rpc']['call']>>) => void
  1085. const pending = new Promise<Awaited<ReturnType<ConnectionHandle['rpc']['call']>>>((resolve) => {
  1086. resolveCall = resolve
  1087. })
  1088. const call = vi.fn<ConnectionHandle['rpc']['call']>().mockReturnValue(pending)
  1089. const ctx = await bench(call)
  1090. const { scope: _scope, ...first } = directDescriptor()
  1091. const second: InvocationDescriptor = {
  1092. ...first,
  1093. id: '@fixture/probe#probe/archive',
  1094. method: 'archive',
  1095. }
  1096. const dispose = await ctx.remote.$mount({ package: '@fixture/probe', descriptors: [first, second] })
  1097. const invocation = ctx.remote.probe.create('agent-1', { objective: 'ship' })
  1098. await vi.waitFor(() => { expect(call).toHaveBeenCalledTimes(1) })
  1099. await dispose()
  1100. resolveCall({ ok: true, value: { ref: 'goal-1' } })
  1101. await expect(invocation).resolves.toMatchObject({
  1102. ok: false,
  1103. error: {
  1104. code: 'gateway/internal',
  1105. message: 'client api: Remote method probe/create is no longer mounted',
  1106. details: {},
  1107. },
  1108. })
  1109. expect((ctx.remote as unknown as Record<string, unknown>).probe).toBeUndefined()
  1110. })
  1111. it('keeps a namespace while another contribution still owns a method', async () => {
  1112. const ctx = await bench(vi.fn<ConnectionHandle['rpc']['call']>())
  1113. const disposeCreate = await ctx.remote.$mount({
  1114. package: '@fixture/create-contribution',
  1115. descriptors: [directDescriptor()],
  1116. })
  1117. const disposeMaybe = await ctx.remote.$mount({
  1118. package: '@fixture/maybe-contribution',
  1119. descriptors: [maybeDescriptor()],
  1120. })
  1121. const namespace = ctx.get('remote.probe') as unknown as Record<string, unknown>
  1122. await disposeCreate()
  1123. expect(ctx.get('remote.probe') !== undefined).toBe(true)
  1124. expect(namespace.create).toBeUndefined()
  1125. expect(namespace.maybe).toBeTypeOf('function')
  1126. await disposeMaybe()
  1127. expect(ctx.get('remote.probe')).toBeUndefined()
  1128. })
  1129. it('fails a method obtained from a withdrawn namespace getter', async () => {
  1130. const ctx = await bench(vi.fn<ConnectionHandle['rpc']['call']>())
  1131. const dispose = await ctx.remote.$mount({ package: '@fixture/probe', descriptors: [directDescriptor()] })
  1132. const namespace = ctx.get('remote.probe') as unknown as object
  1133. const getWithdrawn = Object.getOwnPropertyDescriptor(namespace, 'create')?.get?.bind(namespace)
  1134. await dispose()
  1135. expect(getWithdrawn).toBeTypeOf('function')
  1136. const withdrawn = getWithdrawn?.() as (...args: unknown[]) => Promise<unknown>
  1137. expect(() => withdrawn('agent-1', { objective: 'ship' }))
  1138. .toThrow('Remote method is no longer mounted')
  1139. })
  1140. it('preserves a __proto__ wire parameter as an own named argument', async () => {
  1141. const call = vi.fn<ConnectionHandle['rpc']['call']>()
  1142. .mockResolvedValue({ ok: true, value: { ref: 'goal-1' } })
  1143. const ctx = await bench(call)
  1144. const { scope: _scope, ...base } = directDescriptor()
  1145. const descriptor: InvocationDescriptor = {
  1146. ...base,
  1147. id: '@fixture/probe#probe/prototype',
  1148. method: 'prototype',
  1149. parameters: [{
  1150. name: 'value',
  1151. wire: '__proto__',
  1152. source: 'json',
  1153. codec: { mode: 'strict', typeSymbol: '@fixture#PrototypeValue', schema: z.string() },
  1154. }],
  1155. }
  1156. const dispose = await ctx.remote.$mount({ package: '@fixture/prototype', descriptors: [descriptor] })
  1157. const method = (ctx.remote.probe as unknown as Record<string, (...args: unknown[]) => Promise<unknown>>).prototype
  1158. await expect(method?.('wire-value')).resolves.toEqual({ ok: true, value: { ref: 'goal-1' } })
  1159. const payload = call.mock.calls[0]?.[2] as { readonly args: Record<string, unknown> }
  1160. expect(Object.getPrototypeOf(payload.args)).toBeNull()
  1161. expect(Object.hasOwn(payload.args, '__proto__')).toBe(true)
  1162. expect(payload.args.__proto__).toBe('wire-value')
  1163. await dispose()
  1164. })
  1165. it('rolls back Remote registration when namespace Service startup fails', async () => {
  1166. const ctx = await bench(vi.fn<ConnectionHandle['rpc']['call']>())
  1167. const defineProperty = Object.defineProperty
  1168. const spy = vi.spyOn(Object, 'defineProperty').mockImplementation((target, key, attributes) => {
  1169. if (key === Service.tracker) throw new Error('fixture namespace startup failure')
  1170. return defineProperty(target, key, attributes)
  1171. })
  1172. try {
  1173. await expect(ctx.remote.$mount({ package: '@fixture/probe', descriptors: [directDescriptor()] }))
  1174. .rejects.toThrow('fixture namespace startup failure')
  1175. await vi.waitFor(() => { expect(ctx.typert.remotes.list()).toEqual([]) })
  1176. } finally {
  1177. spy.mockRestore()
  1178. }
  1179. const retry = await ctx.remote.$mount({ package: '@fixture/probe-retry', descriptors: [directDescriptor()] })
  1180. expect(ctx.remote.probe.create).toBeTypeOf('function')
  1181. await retry()
  1182. })
  1183. it('withdraws a fresh direct namespace when its first method fails to install', async () => {
  1184. const ctx = await bench(vi.fn<ConnectionHandle['rpc']['call']>())
  1185. const defineProperty = Object.defineProperty
  1186. const spy = vi.spyOn(Object, 'defineProperty').mockImplementation((target, key, attributes) => {
  1187. if (key === 'create') throw new Error('fixture direct method installation failure')
  1188. return defineProperty(target, key, attributes)
  1189. })
  1190. try {
  1191. await expect(ctx.remote.$mount({
  1192. package: '@fixture/direct-method-failure',
  1193. descriptors: [directDescriptor()],
  1194. })).rejects.toThrow('fixture direct method installation failure')
  1195. } finally {
  1196. spy.mockRestore()
  1197. }
  1198. expect((ctx.remote as unknown as Record<string, unknown>).probe).toBeUndefined()
  1199. await vi.waitFor(() => { expect(ctx.typert.remotes.list()).toEqual([]) })
  1200. const retry = await ctx.remote.$mount({
  1201. package: '@fixture/direct-method-retry',
  1202. descriptors: [directDescriptor()],
  1203. })
  1204. expect(ctx.remote.probe.create).toBeTypeOf('function')
  1205. await retry()
  1206. })
  1207. it('withdraws a fresh scoped Service when its first method fails to install', async () => {
  1208. const ctx = await bench(vi.fn<ConnectionHandle['rpc']['call']>())
  1209. const defineProperty = Object.defineProperty
  1210. const spy = vi.spyOn(Object, 'defineProperty').mockImplementation((target, key, attributes) => {
  1211. if (key === 'rename') throw new Error('fixture scoped installation failure')
  1212. return defineProperty(target, key, attributes)
  1213. })
  1214. try {
  1215. await expect(ctx.remote.$mount({ package: '@fixture/scoped-failure', descriptors: [contextDescriptor()] }))
  1216. .rejects.toThrow('fixture scoped installation failure')
  1217. } finally {
  1218. spy.mockRestore()
  1219. }
  1220. expect(ctx.get('remote.probe')).toBeUndefined()
  1221. await vi.waitFor(() => { expect(ctx.typert.remotes.list()).toEqual([]) })
  1222. const retry = await ctx.remote.$mount({ package: '@fixture/scoped-retry', descriptors: [contextDescriptor()] })
  1223. expect((ctx.get('remote.probe') as unknown as Record<string, unknown>).rename).toBeTypeOf('function')
  1224. await retry()
  1225. })
  1226. it('unregisters an empty scoped namespace so another provider can claim its name', async () => {
  1227. const ctx = await bench(vi.fn<ConnectionHandle['rpc']['call']>())
  1228. const dispose = await ctx.remote.$mount({ package: '@fixture/scoped', descriptors: [contextDescriptor()] })
  1229. expect(ctx.get('remote.probe')).toBeDefined()
  1230. await dispose()
  1231. expect(ctx.get('remote.probe')).toBeUndefined()
  1232. const replacement = { owner: 'replacement' }
  1233. const disposeReplacement = ctx.reflect.provide('remote.probe', replacement)
  1234. expect(ctx.get('remote.probe')).toBe(replacement)
  1235. await disposeReplacement()
  1236. })
  1237. it('delivers an RPC failure in the error branch with the Host error verbatim', async () => {
  1238. const rpcError = { code: 'gateway/internal' as const, message: 'host failed', details: {} }
  1239. const ctx = await bench(vi.fn<ConnectionHandle['rpc']['call']>().mockResolvedValue({ ok: false, error: rpcError }))
  1240. await ctx.remote.$mount({ package: '@fixture/probe', descriptors: [directDescriptor()] })
  1241. const outcome = await ctx.remote.probe.create('agent-1', { objective: 'ship' })
  1242. expect(outcome.ok).toBe(false)
  1243. if (outcome.ok) throw new Error('expected the Client API invocation to report a failure')
  1244. expect(outcome.error).toMatchObject(rpcError)
  1245. })
  1246. it('folds a transport throw into the error branch', async () => {
  1247. const ctx = await bench(vi.fn<ConnectionHandle['rpc']['call']>()
  1248. .mockRejectedValue(new Error('carrier offline')))
  1249. await ctx.remote.$mount({ package: '@fixture/probe', descriptors: [directDescriptor()] })
  1250. await expect(ctx.remote.probe.create('agent-1', { objective: 'ship' })).resolves.toMatchObject({
  1251. ok: false,
  1252. error: {
  1253. code: 'gateway/internal',
  1254. message: 'client api: probe/create failed: carrier offline',
  1255. details: {},
  1256. },
  1257. })
  1258. })
  1259. it('folds a carrier throw that is not an Error into the error branch', async () => {
  1260. const ctx = await bench(vi.fn<ConnectionHandle['rpc']['call']>()
  1261. .mockRejectedValue('carrier exploded'))
  1262. await ctx.remote.$mount({ package: '@fixture/probe', descriptors: [directDescriptor()] })
  1263. await expect(ctx.remote.probe.create('agent-1', { objective: 'ship' })).resolves.toMatchObject({
  1264. ok: false,
  1265. error: {
  1266. code: 'gateway/internal',
  1267. message: 'client api: probe/create failed: carrier exploded',
  1268. details: {},
  1269. },
  1270. })
  1271. })
  1272. it('classifies a carrier throw under a caller-aborted signal as gateway/cancelled', async () => {
  1273. const controller = new AbortController()
  1274. const ctx = await bench(vi.fn<ConnectionHandle['rpc']['call']>().mockImplementation(async () => {
  1275. controller.abort()
  1276. throw new Error('carrier aborted mid-flight')
  1277. }))
  1278. await ctx.remote.$mount({ package: '@fixture/probe', descriptors: [directDescriptor()] })
  1279. await expect(ctx.remote.probe.create('agent-1', { objective: 'ship' }, controller.signal))
  1280. .resolves.toMatchObject({
  1281. ok: false,
  1282. error: {
  1283. code: 'gateway/cancelled',
  1284. message: 'client api: Remote invocation "probe/create" was aborted',
  1285. details: {},
  1286. },
  1287. })
  1288. })
  1289. it('keeps a carrier throw under an unaborted caller signal in the internal branch', async () => {
  1290. const controller = new AbortController()
  1291. const ctx = await bench(vi.fn<ConnectionHandle['rpc']['call']>()
  1292. .mockRejectedValue(new Error('carrier offline')))
  1293. await ctx.remote.$mount({ package: '@fixture/probe', descriptors: [directDescriptor()] })
  1294. await expect(ctx.remote.probe.create('agent-1', { objective: 'ship' }, controller.signal))
  1295. .resolves.toMatchObject({
  1296. ok: false,
  1297. error: {
  1298. code: 'gateway/internal',
  1299. message: 'client api: probe/create failed: carrier offline',
  1300. details: {},
  1301. },
  1302. })
  1303. })
  1304. it('owns each $on subscription in the calling fiber', async () => {
  1305. const { ctx, client, carrier } = await eventBench()
  1306. const seen: string[] = []
  1307. const subscriber = ctx.plugin(Object.assign(
  1308. (scope: Context) => { scope.remote.$on('fixture/changed', (namespace) => { seen.push(namespace) }) },
  1309. { inject: ['remote'] },
  1310. ))
  1311. await subscriber
  1312. expect(carrier.calls).toEqual([expect.objectContaining({
  1313. channel: '/api', endpoint: '$events', payload: { args: {} },
  1314. })])
  1315. carrier.emit({ type: 'emit', event: 'fixture/changed', args: ['settings'] })
  1316. await vi.waitFor(() => { expect(seen).toEqual(['settings']) })
  1317. await subscriber.dispose()
  1318. carrier.emit({ type: 'emit', event: 'fixture/changed', args: ['after fiber disposal'] })
  1319. await Promise.resolve()
  1320. expect(seen).toEqual(['settings'])
  1321. await client.dispose()
  1322. expect(ctx.get('remote')).toBeUndefined()
  1323. })
  1324. it('isolates throwing and rejected notification listeners', async () => {
  1325. const { ctx, client, carrier } = await eventBench()
  1326. const consoleError = vi.spyOn(console, 'error').mockImplementation(() => undefined)
  1327. const seen: string[] = []
  1328. const failingListener = (namespace: string): unknown => {
  1329. if (namespace === 'sync') throw new Error('fixture listener failure')
  1330. return Promise.reject(new Error('fixture async failure'))
  1331. }
  1332. const disposeThrowing = ctx.remote.$on('fixture/changed', failingListener)
  1333. ctx.remote.$on('fixture/changed', (namespace) => { seen.push(namespace) })
  1334. try {
  1335. carrier.emit({ type: 'emit', event: 'fixture/changed', args: ['sync'] })
  1336. await vi.waitFor(() => { expect(seen).toEqual(['sync']) })
  1337. carrier.emit({ type: 'emit', event: 'fixture/changed', args: ['async'] })
  1338. await vi.waitFor(() => { expect(seen).toEqual(['sync', 'async']) })
  1339. expect(consoleError).toHaveBeenCalledTimes(2)
  1340. disposeThrowing()
  1341. carrier.emit({ type: 'emit', event: 'fixture/changed', args: ['survivor'] })
  1342. await vi.waitFor(() => { expect(seen).toEqual(['sync', 'async', 'survivor']) })
  1343. } finally {
  1344. consoleError.mockRestore()
  1345. await client.dispose()
  1346. }
  1347. })
  1348. it('retires only its own registration when one listener subscribes twice', async () => {
  1349. const { ctx, client, carrier } = await eventBench()
  1350. const seen: string[] = []
  1351. const listener = (namespace: string): void => { seen.push(namespace) }
  1352. const disposeFirst = ctx.remote.$on('fixture/changed', listener)
  1353. ctx.remote.$on('fixture/changed', listener)
  1354. carrier.emit({ type: 'emit', event: 'fixture/changed', args: ['both'] })
  1355. await vi.waitFor(() => { expect(seen).toEqual(['both', 'both']) })
  1356. disposeFirst()
  1357. carrier.emit({ type: 'emit', event: 'fixture/changed', args: ['survivor'] })
  1358. await vi.waitFor(() => { expect(seen).toEqual(['both', 'both', 'survivor']) })
  1359. disposeFirst()
  1360. carrier.emit({ type: 'emit', event: 'fixture/changed', args: ['still here'] })
  1361. await vi.waitFor(() => {
  1362. expect(seen).toEqual(['both', 'both', 'survivor', 'still here'])
  1363. })
  1364. await client.dispose()
  1365. })
  1366. it('keeps the carrier handoff private', () => {
  1367. expectTypeOf<ClientRemote>().toHaveProperty('$on')
  1368. expectTypeOf<'$dispatch' extends keyof ClientRemote ? true : false>().toEqualTypeOf<false>()
  1369. })
  1370. it('drops an unobserved notification and accepts a null-prototype frame', async () => {
  1371. const { ctx, client, carrier } = await eventBench()
  1372. const seen: string[] = []
  1373. ctx.remote.$on('fixture/changed', (namespace) => { seen.push(namespace) })
  1374. carrier.emit({ type: 'emit', event: 'fixture/idle', args: [1] })
  1375. carrier.emit(Object.assign(Object.create(null) as Record<string, unknown>, {
  1376. type: 'emit',
  1377. event: 'fixture/changed',
  1378. args: ['null prototype'],
  1379. }))
  1380. await vi.waitFor(() => { expect(seen).toEqual(['null prototype']) })
  1381. await client.dispose()
  1382. })
  1383. it('delegates immediately when the Agent adapter or Context is unavailable', async () => {
  1384. const { ctx, client, carrier, call } = await eventBench()
  1385. carrier.emit(approvalFrame('event-no-adapter', 'agent-late', 'no adapter'))
  1386. await vi.waitFor(() => { expect(call).toHaveBeenCalledTimes(1) })
  1387. const target = ctx.extend()
  1388. const resolve = vi.fn((id: unknown) => id === 'agent-found' ? target : undefined)
  1389. ctx.typert.contexts.registerClient('agent', {
  1390. identity: candidate => candidate === target ? agentId('agent-found') : undefined,
  1391. resolve,
  1392. })
  1393. carrier.emit(approvalFrame('event-missing-context', 'agent-missing', 'missing'))
  1394. carrier.emit(approvalFrame('event-no-listener', 'agent-found', 'delegate'))
  1395. await vi.waitFor(() => { expect(call).toHaveBeenCalledTimes(3) })
  1396. expect(resolve).toHaveBeenCalledTimes(2)
  1397. for (const eventId of ['event-no-adapter', 'event-missing-context', 'event-no-listener']) {
  1398. expect(call).toHaveBeenCalledWith(
  1399. '/api',
  1400. '$events/result',
  1401. { args: { clientId: 'event-client-1', eventId, outcome: { kind: 'next' } } },
  1402. expect.any(AbortSignal),
  1403. )
  1404. }
  1405. await client.dispose()
  1406. })
  1407. it('reports Agent Context resolution failures and delegates', async () => {
  1408. const { ctx, client, carrier, call } = await eventBench()
  1409. ctx.typert.contexts.registerClient('agent', {
  1410. identity: () => undefined,
  1411. resolve: () => { throw new Error('fixture Context lookup failed') },
  1412. })
  1413. const consoleError = vi.spyOn(console, 'error').mockImplementation(() => undefined)
  1414. try {
  1415. carrier.emit(approvalFrame('event-resolve-error', 'agent-error', 'resolve'))
  1416. await vi.waitFor(() => { expect(call).toHaveBeenCalledTimes(1) })
  1417. expect(consoleError).toHaveBeenCalledWith(
  1418. 'client api: Remote event "fixture/approval" listener threw:',
  1419. expect.objectContaining({ message: 'fixture Context lookup failed' }),
  1420. )
  1421. expect(call).toHaveBeenCalledWith(
  1422. '/api',
  1423. '$events/result',
  1424. {
  1425. args: {
  1426. clientId: 'event-client-1',
  1427. eventId: 'event-resolve-error',
  1428. outcome: { kind: 'next' },
  1429. },
  1430. },
  1431. expect.any(AbortSignal),
  1432. )
  1433. } finally {
  1434. consoleError.mockRestore()
  1435. await client.dispose()
  1436. }
  1437. })
  1438. it('normalizes undefined waterfall results and rejects non-JSON results', async () => {
  1439. const { ctx, client, carrier, call } = await eventBench()
  1440. const target = ctx.extend()
  1441. ctx.typert.contexts.registerClient('agent', {
  1442. identity: candidate => candidate === target ? agentId('agent-results') : undefined,
  1443. resolve: id => id === 'agent-results' ? target : undefined,
  1444. })
  1445. target.remote.$on('fixture/approval', async request => request.prompt === 'undefined'
  1446. ? undefined as unknown as FixtureApprovalOutcome
  1447. : Symbol('not JSON') as unknown as FixtureApprovalOutcome)
  1448. carrier.emit(approvalFrame('event-undefined', 'agent-results', 'undefined'))
  1449. carrier.emit(approvalFrame('event-invalid', 'agent-results', 'invalid'))
  1450. await vi.waitFor(() => { expect(call).toHaveBeenCalledTimes(2) })
  1451. expect(call).toHaveBeenCalledWith(
  1452. '/api',
  1453. '$events/result',
  1454. { args: { clientId: 'event-client-1', eventId: 'event-undefined', outcome: { kind: 'result' } } },
  1455. expect.any(AbortSignal),
  1456. )
  1457. expect(call).toHaveBeenCalledWith(
  1458. '/api',
  1459. '$events/result',
  1460. {
  1461. args: {
  1462. clientId: 'event-client-1',
  1463. eventId: 'event-invalid',
  1464. outcome: {
  1465. kind: 'rejected',
  1466. error: {
  1467. name: 'TypeError',
  1468. message: 'Remote event listener result is not lossless JSON data',
  1469. },
  1470. },
  1471. },
  1472. },
  1473. expect.any(AbortSignal),
  1474. )
  1475. await client.dispose()
  1476. })
  1477. it('fails the Connection generation when a result RPC is rejected', async () => {
  1478. const call = vi.fn<ConnectionHandle['rpc']['call']>().mockResolvedValue({
  1479. ok: false,
  1480. error: { code: 'gateway/internal', message: 'fixture result rejected', details: {} },
  1481. })
  1482. const { client, carrier, run } = await eventBench(call)
  1483. carrier.emit(approvalFrame('event-result-rejected', 'agent-missing', 'respond'))
  1484. await expect(run.done).rejects.toThrow('fixture result rejected')
  1485. await client.dispose()
  1486. })
  1487. it('filters scoped waterfall listeners and returns the first claimed result', async () => {
  1488. const call = vi.fn<ConnectionHandle['rpc']['call']>()
  1489. .mockResolvedValue({ ok: true, value: undefined })
  1490. const { ctx, client, carrier } = await eventBench(call)
  1491. const target = ctx.extend({
  1492. [Context.filter](candidate: Context): boolean {
  1493. const tag = (candidate as Context & { [fixtureContextTag]?: string })[fixtureContextTag]
  1494. return tag === undefined || tag === 'agent-1'
  1495. },
  1496. })
  1497. ctx.typert.contexts.registerClient('agent', {
  1498. identity: candidate => candidate === target ? agentId('agent-1') : undefined,
  1499. resolve: id => id === 'agent-1' ? target : undefined,
  1500. })
  1501. const matching = ctx.extend({ [fixtureContextTag]: 'agent-1' })
  1502. const excluded = ctx.extend({ [fixtureContextTag]: 'agent-2' })
  1503. const seen: string[] = []
  1504. ctx.remote.$on('fixture/approval', async function (request, next) {
  1505. expect(this).toBe(target)
  1506. expect(request.agent).toBe(target)
  1507. expect(request.signal).toBeInstanceOf(AbortSignal)
  1508. seen.push('root')
  1509. return next()
  1510. })
  1511. matching.remote.$on('fixture/approval', async (_request, next) => {
  1512. seen.push('matching-next')
  1513. return next()
  1514. })
  1515. excluded.remote.$on('fixture/approval', async () => {
  1516. seen.push('excluded')
  1517. return 'unavailable'
  1518. })
  1519. matching.remote.$on('fixture/approval', async () => {
  1520. seen.push('matching-result')
  1521. return 'allowed'
  1522. })
  1523. carrier.emit(approvalFrame('event-1', 'agent-1', 'ship'))
  1524. await vi.waitFor(() => { expect(call).toHaveBeenCalledTimes(1) })
  1525. expect(seen).toEqual(['root', 'matching-next', 'matching-result'])
  1526. expect(call).toHaveBeenCalledWith(
  1527. '/api',
  1528. '$events/result',
  1529. {
  1530. args: {
  1531. clientId: 'event-client-1',
  1532. eventId: 'event-1',
  1533. outcome: { kind: 'result', value: 'allowed' },
  1534. },
  1535. },
  1536. expect.any(AbortSignal),
  1537. )
  1538. await client.dispose()
  1539. })
  1540. it('returns a scoped listener rejection to the Host', async () => {
  1541. const call = vi.fn<ConnectionHandle['rpc']['call']>()
  1542. .mockResolvedValue({ ok: true, value: undefined })
  1543. const { ctx, client, carrier } = await eventBench(call)
  1544. const target = ctx.extend()
  1545. ctx.typert.contexts.registerClient('agent', {
  1546. identity: candidate => candidate === target ? agentId('agent-rejected') : undefined,
  1547. resolve: id => id === 'agent-rejected' ? target : undefined,
  1548. })
  1549. const rejection = Object.assign(new Error('the user cancelled ask_user_question'), {
  1550. name: 'UserQuestionError',
  1551. code: 'ASK_CANCELLED',
  1552. details: { questionId: 'question-1' },
  1553. })
  1554. target.remote.$on('fixture/approval', () => Promise.reject(rejection))
  1555. carrier.emit(approvalFrame('event-rejected', 'agent-rejected', 'gateway/cancelled'))
  1556. await vi.waitFor(() => { expect(call).toHaveBeenCalledTimes(1) })
  1557. expect(call).toHaveBeenCalledWith(
  1558. '/api',
  1559. '$events/result',
  1560. {
  1561. args: {
  1562. clientId: 'event-client-1',
  1563. eventId: 'event-rejected',
  1564. outcome: {
  1565. kind: 'rejected',
  1566. error: {
  1567. name: 'UserQuestionError',
  1568. message: 'the user cancelled ask_user_question',
  1569. code: 'ASK_CANCELLED',
  1570. details: { questionId: 'question-1' },
  1571. },
  1572. },
  1573. },
  1574. },
  1575. expect.any(AbortSignal),
  1576. )
  1577. await client.dispose()
  1578. })
  1579. it('returns Context-filter failures as rejections', async () => {
  1580. const call = vi.fn<ConnectionHandle['rpc']['call']>()
  1581. .mockResolvedValue({ ok: true, value: undefined })
  1582. const { ctx, client, carrier } = await eventBench(call)
  1583. const target = ctx.extend({
  1584. [Context.filter](): boolean {
  1585. throw new Error('fixture Context filter failed')
  1586. },
  1587. })
  1588. ctx.typert.contexts.registerClient('agent', {
  1589. identity: candidate => candidate === target ? agentId('agent-filter-failure') : undefined,
  1590. resolve: id => id === 'agent-filter-failure' ? target : undefined,
  1591. })
  1592. ctx.remote.$on('fixture/approval', async (_request, next) => next())
  1593. carrier.emit(approvalFrame('event-filter-failure', 'agent-filter-failure', 'filter'))
  1594. await vi.waitFor(() => { expect(call).toHaveBeenCalledTimes(1) })
  1595. expect(call).toHaveBeenCalledWith(
  1596. '/api',
  1597. '$events/result',
  1598. {
  1599. args: {
  1600. clientId: 'event-client-1',
  1601. eventId: 'event-filter-failure',
  1602. outcome: {
  1603. kind: 'rejected',
  1604. error: {
  1605. name: 'Error',
  1606. message: 'fixture Context filter failed',
  1607. },
  1608. },
  1609. },
  1610. },
  1611. expect.any(AbortSignal),
  1612. )
  1613. await client.dispose()
  1614. })
  1615. it('cancels a pending Client listener without returning a late result', async () => {
  1616. const { ctx, client, carrier, call } = await eventBench()
  1617. const target = ctx.extend()
  1618. ctx.typert.contexts.registerClient('agent', {
  1619. identity: candidate => candidate === target ? agentId('agent-cancel') : undefined,
  1620. resolve: id => id === 'agent-cancel' ? target : undefined,
  1621. })
  1622. const entered = Promise.withResolvers<AbortSignal>()
  1623. target.remote.$on('fixture/approval', async (request) => {
  1624. const signal = request.signal as AbortSignal
  1625. entered.resolve(signal)
  1626. await new Promise<void>((resolve) => {
  1627. if (signal.aborted) resolve()
  1628. else signal.addEventListener('abort', () => { resolve() }, { once: true })
  1629. })
  1630. return 'allowed'
  1631. })
  1632. carrier.emit(approvalFrame('event-cancel', 'agent-cancel', 'wait'))
  1633. const deliverySignal = await entered.promise
  1634. carrier.emit({ type: 'cancel', eventId: 'event-cancel' })
  1635. await vi.waitFor(() => { expect(deliverySignal.aborted).toBe(true) })
  1636. await Promise.resolve()
  1637. expect(call).not.toHaveBeenCalled()
  1638. await client.dispose()
  1639. })
  1640. it('drops a settled listener result when cancellation wins before reply', async () => {
  1641. const { ctx, client, carrier, call } = await eventBench()
  1642. const target = ctx.extend()
  1643. ctx.typert.contexts.registerClient('agent', {
  1644. identity: candidate => candidate === target ? agentId('agent-cancel-race') : undefined,
  1645. resolve: id => id === 'agent-cancel-race' ? target : undefined,
  1646. })
  1647. const entered = Promise.withResolvers<AbortSignal>()
  1648. const release = Promise.withResolvers<undefined>()
  1649. target.remote.$on('fixture/approval', async (request) => {
  1650. entered.resolve(request.signal as AbortSignal)
  1651. await release.promise
  1652. return 'allowed'
  1653. })
  1654. carrier.emit(approvalFrame('event-cancel-race', 'agent-cancel-race', 'wait'))
  1655. const deliverySignal = await entered.promise
  1656. release.resolve(undefined)
  1657. carrier.emit({ type: 'cancel', eventId: 'event-cancel-race' })
  1658. await vi.waitFor(() => { expect(deliverySignal.aborted).toBe(true) })
  1659. await Promise.resolve()
  1660. expect(call).not.toHaveBeenCalled()
  1661. await client.dispose()
  1662. })
  1663. it('cancels pending listener work when the generation ends', async () => {
  1664. const { ctx, client, carrier, run, call } = await eventBench()
  1665. const target = ctx.extend()
  1666. ctx.typert.contexts.registerClient('agent', {
  1667. identity: candidate => candidate === target ? agentId('agent-generation') : undefined,
  1668. resolve: id => id === 'agent-generation' ? target : undefined,
  1669. })
  1670. const entered = Promise.withResolvers<AbortSignal>()
  1671. target.remote.$on('fixture/approval', async (request) => {
  1672. const signal = request.signal as AbortSignal
  1673. entered.resolve(signal)
  1674. await new Promise<void>((resolve) => {
  1675. if (signal.aborted) resolve()
  1676. else signal.addEventListener('abort', () => { resolve() }, { once: true })
  1677. })
  1678. return 'allowed'
  1679. })
  1680. carrier.emit(approvalFrame('event-generation', 'agent-generation', 'wait'))
  1681. const deliverySignal = await entered.promise
  1682. run.abort(new Error('fixture generation ended'))
  1683. await expect(run.done).resolves.toBeUndefined()
  1684. expect(deliverySignal.aborted).toBe(true)
  1685. expect(call).not.toHaveBeenCalled()
  1686. await client.dispose()
  1687. })
  1688. it('contains a result transport failure after the generation is cancelled', async () => {
  1689. const response = Promise.withResolvers<never>()
  1690. const call = vi.fn<ConnectionHandle['rpc']['call']>(() => response.promise)
  1691. const { client, carrier, run } = await eventBench(call)
  1692. carrier.emit(approvalFrame('event-late-result', 'agent-missing', 'respond'))
  1693. await vi.waitFor(() => { expect(call).toHaveBeenCalledOnce() })
  1694. run.abort(new Error('fixture generation cancelled'))
  1695. response.reject(new Error('fixture late result failure'))
  1696. await expect(run.done).resolves.toBeUndefined()
  1697. await client.dispose()
  1698. })
  1699. it('normalizes a non-Error result transport failure', async () => {
  1700. const call = vi.fn<ConnectionHandle['rpc']['call']>().mockRejectedValue('fixture transport failure')
  1701. const { client, carrier, run } = await eventBench(call)
  1702. carrier.emit(approvalFrame('event-result-throw', 'agent-missing', 'respond'))
  1703. await expect(run.done).rejects.toMatchObject({
  1704. message: 'client api: Remote event result delivery failed',
  1705. cause: 'fixture transport failure',
  1706. })
  1707. await client.dispose()
  1708. })
  1709. it('keeps the newer generation tracked when an overlapping generation settles', async () => {
  1710. const { client, generation, run } = await eventBench()
  1711. const overlapping = generation.startOverlapping()
  1712. await overlapping.ready
  1713. run.abort(new Error('fixture older generation ended'))
  1714. await expect(run.done).resolves.toBeUndefined()
  1715. overlapping.abort(new Error('fixture newer generation ended'))
  1716. await expect(overlapping.done).resolves.toBeUndefined()
  1717. await client.dispose()
  1718. })
  1719. it('opens the forwarded-event stream on the browser Remote mux', async () => {
  1720. await withFakeWebSocket('https://harness.example', async () => {
  1721. const call = vi.fn<ConnectionHandle['rpc']['call']>()
  1722. .mockResolvedValue({ ok: true, value: undefined })
  1723. const { ctx, client, generation } = await benchFiber(call, 'web')
  1724. const seen: string[] = []
  1725. const target = ctx.extend()
  1726. ctx.typert.contexts.registerClient('agent', {
  1727. identity: candidate => candidate === target ? agentId('agent-browser') : undefined,
  1728. resolve: id => id === 'agent-browser' ? target : undefined,
  1729. })
  1730. ctx.remote.$on('fixture/changed', (namespace) => { seen.push(namespace) })
  1731. target.remote.$on('fixture/approval', async function (request) {
  1732. expect(this).toBe(target)
  1733. expect(request.agent).toBe(this)
  1734. expect(request.signal).toBeInstanceOf(AbortSignal)
  1735. return 'allowed'
  1736. })
  1737. const run = generation.start()
  1738. await vi.waitFor(() => { expect(FakeWebSocket.sockets[0]?.sent).toHaveLength(1) })
  1739. const socket = FakeWebSocket.sockets[0]!
  1740. const opened = JSON.parse(socket.sent[0]!) as { streamId: string }
  1741. expect(opened).toMatchObject({
  1742. type: 'open', endpoint: '$events', payload: { args: {} },
  1743. })
  1744. socket.receive({
  1745. type: 'item',
  1746. streamId: opened.streamId,
  1747. value: { type: 'ready', clientId: 'browser-client', host: { home: '/home/browser' } },
  1748. })
  1749. await run.ready
  1750. socket.receive({
  1751. type: 'item',
  1752. streamId: opened.streamId,
  1753. value: { type: 'emit', event: 'fixture/changed', args: ['browser'] },
  1754. })
  1755. await vi.waitFor(() => { expect(seen).toEqual(['browser']) })
  1756. socket.receive({
  1757. type: 'item',
  1758. streamId: opened.streamId,
  1759. value: {
  1760. type: 'waterfall',
  1761. event: 'fixture/approval',
  1762. eventId: 'event-browser',
  1763. agentId: 'agent-browser',
  1764. request: { prompt: 'browser approval' },
  1765. },
  1766. })
  1767. await vi.waitFor(() => { expect(call).toHaveBeenCalledTimes(1) })
  1768. expect(socket.sent).toHaveLength(1)
  1769. expect(call).toHaveBeenCalledWith(
  1770. '/api',
  1771. '$events/result',
  1772. {
  1773. args: {
  1774. clientId: 'browser-client',
  1775. eventId: 'event-browser',
  1776. outcome: { kind: 'result', value: 'allowed' },
  1777. },
  1778. },
  1779. expect.any(AbortSignal),
  1780. )
  1781. await client.dispose()
  1782. })
  1783. })
  1784. it('publishes the Fixture Host facts after Remote events report ready', async () => {
  1785. const locationDescriptor = Object.getOwnPropertyDescriptor(globalThis, 'location')
  1786. Object.defineProperty(globalThis, 'location', {
  1787. configurable: true,
  1788. value: { hostname: '127.0.0.1', search: '?fixture' },
  1789. })
  1790. const ctx = new Context()
  1791. try {
  1792. await ctx.plugin(TypertRegistry)
  1793. await ctx.plugin({ inject: [], apply: applyConnection })
  1794. await ctx.plugin({ inject, apply })
  1795. const connection = ctx.get('connection') as ConnectionHandle | undefined
  1796. if (connection === undefined) throw new Error('fixture Connection service is unavailable')
  1797. await vi.waitFor(() => {
  1798. expect(connection.generation.getSnapshot()?.host.home).toBe('/home/fixture')
  1799. })
  1800. } finally {
  1801. await ctx.fiber.dispose()
  1802. if (locationDescriptor === undefined) Reflect.deleteProperty(globalThis, 'location')
  1803. else Object.defineProperty(globalThis, 'location', locationDescriptor)
  1804. }
  1805. })
  1806. it.each([
  1807. null,
  1808. [],
  1809. {},
  1810. { type: 'pending' },
  1811. { type: 'ready' },
  1812. { type: 'ready', clientId: '' },
  1813. { type: 'ready', clientId: 'client', extra: true },
  1814. { type: 'ready', clientId: 'client', host: null },
  1815. { type: 'ready', clientId: 'client', host: {} },
  1816. { type: 'ready', clientId: 'client', host: { home: 1 } },
  1817. { type: 'ready', clientId: 'client', host: { home: '/home', extra: true } },
  1818. { type: 'emit', event: 'fixture/changed', args: ['too early'] },
  1819. ])('rejects malformed forwarded-event readiness item %#', async (opening) => {
  1820. const open: NonNullable<ConnectionHandle['rpc']['open']> = () => (async function *() {
  1821. yield opening
  1822. })()
  1823. const { client, generation } = await benchFiber(
  1824. vi.fn<ConnectionHandle['rpc']['call']>(),
  1825. 'in-process',
  1826. open,
  1827. )
  1828. const run = generation.start()
  1829. try {
  1830. await expect(run.done).rejects.toThrow('forwarded Remote event stream did not begin with ready')
  1831. } finally {
  1832. await client.dispose()
  1833. }
  1834. })
  1835. it('propagates physical carrier failure and opens events for the replacement generation', async () => {
  1836. const { ctx, client, carrier, generation, run } = await eventBench()
  1837. const seen: string[] = []
  1838. ctx.remote.$on('fixture/changed', (namespace) => { seen.push(namespace) })
  1839. expect(carrier.calls).toHaveLength(1)
  1840. carrier.fail(new RemoteStreamCarrierError('fixture generation lost'))
  1841. await expect(run.done).rejects.toThrow('fixture generation lost')
  1842. const replacement = generation.start()
  1843. await replacement.ready
  1844. await vi.waitFor(() => { expect(carrier.calls).toHaveLength(2) })
  1845. carrier.emit({ type: 'emit', event: 'fixture/changed', args: ['replacement'] })
  1846. await vi.waitFor(() => { expect(seen).toEqual(['replacement']) })
  1847. await client.dispose()
  1848. })
  1849. it.each([
  1850. {
  1851. name: 'Host failure',
  1852. stop: (carrier: RemoteEventCarrier) => {
  1853. carrier.fail(new RemoteError('gateway/internal', 'fixture Host failed', {}))
  1854. },
  1855. message: 'fixture Host failed',
  1856. },
  1857. {
  1858. name: 'normal end',
  1859. stop: (carrier: RemoteEventCarrier) => { carrier.end() },
  1860. message: 'forwarded Remote event stream ended unexpectedly',
  1861. },
  1862. ])('fails the active generation after $name', async ({ stop, message }) => {
  1863. const { ctx, client, carrier, run } = await eventBench()
  1864. const seen: string[] = []
  1865. ctx.remote.$on('fixture/changed', (namespace) => { seen.push(namespace) })
  1866. stop(carrier)
  1867. await expect(run.done).rejects.toThrow(message)
  1868. carrier.emit({ type: 'emit', event: 'fixture/changed', args: ['too late'] })
  1869. await Promise.resolve()
  1870. expect(carrier.calls).toHaveLength(1)
  1871. expect(seen).toEqual([])
  1872. await client.dispose()
  1873. })
  1874. it.each([
  1875. 'not an object',
  1876. null,
  1877. [],
  1878. {},
  1879. { type: 'unknown' },
  1880. { type: 'emit', event: 'fixture/changed' },
  1881. { type: 'emit', event: 'fixture/changed', args: [], extra: true },
  1882. { type: 'emit', event: 1, args: [] },
  1883. { type: 'emit', event: '', args: [] },
  1884. { type: 'emit', event: 'fixture/changed', args: {} },
  1885. { type: 'emit', event: 'fixture/changed', args: [1n] },
  1886. { type: 'waterfall', event: 'fixture/approval', eventId: '', agentId: 'agent-1', request: {} },
  1887. { type: 'waterfall', event: 'fixture/approval', eventId: 'event-1', agentId: '', request: {} },
  1888. {
  1889. type: 'waterfall', event: 'fixture/approval', eventId: 'event-1', agentId: 'agent-1', request: { agent: null },
  1890. },
  1891. {
  1892. type: 'waterfall', event: 'fixture/approval', eventId: 'event-1', agentId: 'agent-1', request: { signal: null },
  1893. },
  1894. { type: 'cancel', eventId: '' },
  1895. { type: 'cancel', eventId: 'event-1', extra: true },
  1896. ])('rejects malformed forwarded-event frame %# and stops that stream', async (frame) => {
  1897. const { ctx, client, carrier, run } = await eventBench()
  1898. const seen: string[] = []
  1899. ctx.remote.$on('fixture/changed', (namespace) => { seen.push(namespace) })
  1900. carrier.emit(frame)
  1901. await expect(run.done).rejects.toThrow('client api: invalid forwarded Remote event frame')
  1902. carrier.emit({ type: 'emit', event: 'fixture/changed', args: ['too late'] })
  1903. await Promise.resolve()
  1904. expect(carrier.calls).toHaveLength(1)
  1905. expect(seen).toEqual([])
  1906. await client.dispose()
  1907. })
  1908. it('aborts and awaits forwarded-event delivery during disposal', async () => {
  1909. const { ctx, client, carrier, run } = await eventBench()
  1910. ctx.remote.$on('fixture/changed', () => {})
  1911. expect(carrier.activeConnections).toBe(1)
  1912. const signal = carrier.calls[0]?.signal
  1913. await client.dispose()
  1914. await expect(run.done).resolves.toBeUndefined()
  1915. expect(signal?.aborted).toBe(true)
  1916. expect(carrier.activeConnections).toBe(0)
  1917. expect(ctx.get('remote')).toBeUndefined()
  1918. })
  1919. it('rejects a generation when its Connection has been withdrawn', async () => {
  1920. const carrier = new RemoteEventCarrier()
  1921. const { ctx, client, generation } = await benchFiber(
  1922. vi.fn<ConnectionHandle['rpc']['call']>(),
  1923. 'in-process',
  1924. carrier.open,
  1925. )
  1926. ctx.set('connection', undefined)
  1927. const run = generation.start()
  1928. await expect(run.done).rejects.toThrow('$events has no active Connection')
  1929. expect(carrier.calls).toEqual([])
  1930. await client.dispose()
  1931. })
  1932. it('guards stream iteration across mount and Connection withdrawal', async () => {
  1933. const call = vi.fn<ConnectionHandle['rpc']['call']>()
  1934. const ctx = await bench(call)
  1935. const firstDispose = await ctx.remote.$mount({
  1936. package: '@fixture/stream-first', descriptors: [streamDescriptor()],
  1937. })
  1938. const withdrawn = ctx.remote.probe.watch('withdrawn')[Symbol.asyncIterator]()
  1939. await firstDispose()
  1940. await expect(withdrawn.next()).rejects.toThrow('Remote method probe/watch is no longer mounted')
  1941. const secondDispose = await ctx.remote.$mount({
  1942. package: '@fixture/stream-second', descriptors: [streamDescriptor()],
  1943. })
  1944. ctx.set('connection', undefined)
  1945. await expect(ctx.remote.probe.watch('offline')[Symbol.asyncIterator]().next())
  1946. .rejects.toThrow('probe/watch has no active Connection')
  1947. let release!: () => void
  1948. const released = new Promise<void>((resolve) => { release = resolve })
  1949. let markStarted!: () => void
  1950. const started = new Promise<void>((resolve) => { markStarted = resolve })
  1951. const source = async function *(): AsyncIterable<string> {
  1952. markStarted()
  1953. await released
  1954. yield 'late item'
  1955. }
  1956. ctx.set('connection', {
  1957. rpc: { call, open: () => source() },
  1958. } as unknown as ConnectionHandle)
  1959. const active = ctx.remote.probe.watch('active')[Symbol.asyncIterator]()
  1960. const pending = active.next()
  1961. await started
  1962. await secondDispose()
  1963. release()
  1964. await expect(pending).rejects.toThrow('Remote method probe/watch is no longer mounted')
  1965. })
  1966. it('publishes a namespace only after every contributed method is installed', async () => {
  1967. const ctx = await bench(vi.fn<ConnectionHandle['rpc']['call']>())
  1968. let visible: string[] | undefined
  1969. const consumer = ctx.plugin({
  1970. inject: ['remote.probe'],
  1971. apply(scope) {
  1972. const namespace = scope.get('remote.probe') as unknown as Record<string, unknown>
  1973. visible = [typeof namespace.watch, typeof namespace.archive]
  1974. },
  1975. })
  1976. const archive: InvocationDescriptor = {
  1977. ...streamDescriptor(),
  1978. id: '@fixture/probe#probe/archive',
  1979. method: 'archive',
  1980. }
  1981. const dispose = await ctx.remote.$mount({
  1982. package: '@fixture/atomic-namespace',
  1983. descriptors: [streamDescriptor(), archive],
  1984. })
  1985. await consumer.await()
  1986. expect(visible).toEqual(['function', 'function'])
  1987. await dispose()
  1988. })
  1989. it('normalizes worker-local structural stream failures without sharing class identity', async () => {
  1990. const cases = [{
  1991. failure: Object.assign(new Error('fixture Host rejected the stream'), {
  1992. dshRemoteStreamFailure: {
  1993. kind: 'remote' as const,
  1994. code: 'fixture/rejected',
  1995. details: { retry: false },
  1996. },
  1997. }),
  1998. assert: (error: unknown) => {
  1999. expect(error).toBeInstanceOf(RemoteError)
  2000. expect(error).toMatchObject({
  2001. code: 'fixture/rejected',
  2002. message: 'fixture Host rejected the stream',
  2003. details: { retry: false },
  2004. })
  2005. },
  2006. }, {
  2007. failure: Object.assign(new Error('worker carrier stopped'), {
  2008. dshRemoteStreamFailure: { kind: 'carrier' as const },
  2009. }),
  2010. assert: (error: unknown) => {
  2011. expect(error).toBeInstanceOf(RemoteStreamCarrierError)
  2012. expect(error).toMatchObject({ message: 'worker carrier stopped' })
  2013. },
  2014. }, {
  2015. failure: 'caller abort sentinel',
  2016. assert: (error: unknown) => { expect(error).toBe('caller abort sentinel') },
  2017. }]
  2018. for (const testCase of cases) {
  2019. const open: NonNullable<ConnectionHandle['rpc']['open']> = () => (async function *(): AsyncGenerator {
  2020. throw testCase.failure
  2021. })()
  2022. const { ctx, client } = await benchFiber(
  2023. vi.fn<ConnectionHandle['rpc']['call']>(),
  2024. 'in-process',
  2025. open,
  2026. )
  2027. const dispose = await ctx.remote.$mount({ package: '@fixture/worker-stream', descriptors: [streamDescriptor()] })
  2028. try {
  2029. const error = await ctx.remote.probe.watch('failure')[Symbol.asyncIterator]().next()
  2030. .then(() => undefined, (reason: unknown) => reason)
  2031. testCase.assert(error)
  2032. } finally {
  2033. await dispose()
  2034. await client.dispose()
  2035. }
  2036. }
  2037. })
  2038. it('multiplexes Remote streams without using the Connection RPC caller', async () => {
  2039. const originalWebSocket = globalThis.WebSocket
  2040. const locationDescriptor = Object.getOwnPropertyDescriptor(globalThis, 'location')
  2041. ;(globalThis as WebSocketGlobal).WebSocket = FakeWebSocket as unknown as typeof WebSocket
  2042. Object.defineProperty(globalThis, 'location', {
  2043. configurable: true,
  2044. value: { origin: 'https://harness.example' },
  2045. })
  2046. FakeWebSocket.sockets.length = 0
  2047. const call = vi.fn<ConnectionHandle['rpc']['call']>()
  2048. const ctx = await bench(call, 'web')
  2049. expect(FakeWebSocket.sockets).toHaveLength(1)
  2050. const dispose = await ctx.remote.$mount({ package: '@fixture/stream', descriptors: [streamDescriptor()] })
  2051. try {
  2052. const first = ctx.remote.probe.watch('alpha')[Symbol.asyncIterator]()
  2053. const firstItem = first.next()
  2054. await vi.waitFor(() => { expect(FakeWebSocket.sockets[0]?.sent).toHaveLength(1) })
  2055. const socket = FakeWebSocket.sockets[0]!
  2056. expect(socket.url).toBe('wss://harness.example/api/remote.mux')
  2057. const opened = JSON.parse(socket.sent[0]!) as { streamId: string }
  2058. expect(opened).toMatchObject({
  2059. type: 'open',
  2060. endpoint: 'probe/watch',
  2061. payload: { args: { topic: 'alpha' } },
  2062. })
  2063. socket.receive({ type: 'item', streamId: opened.streamId, value: 'alpha:one' })
  2064. await expect(firstItem).resolves.toEqual({ done: false, value: 'alpha:one' })
  2065. const firstEnd = first.next()
  2066. socket.receive({ type: 'end', streamId: opened.streamId })
  2067. await expect(firstEnd).resolves.toEqual({ done: true, value: undefined })
  2068. const failed = ctx.remote.probe.watch('failure')[Symbol.asyncIterator]()
  2069. const failedItem = failed.next()
  2070. await vi.waitFor(() => { expect(socket.sent).toHaveLength(2) })
  2071. const failedOpen = JSON.parse(socket.sent[1]!) as { streamId: string }
  2072. socket.receive({
  2073. type: 'error',
  2074. streamId: failedOpen.streamId,
  2075. error: {
  2076. code: 'gateway/lookup-unavailable',
  2077. message: 'fixture stream failed',
  2078. details: { lookup: 'missing' },
  2079. },
  2080. })
  2081. await expect(failedItem).rejects.toMatchObject({
  2082. name: 'RemoteError',
  2083. code: 'gateway/lookup-unavailable',
  2084. message: 'fixture stream failed',
  2085. details: { lookup: 'missing' },
  2086. })
  2087. const abort = new AbortController()
  2088. const cancelled = ctx.remote.probe.watch('cancel', abort.signal)[Symbol.asyncIterator]()
  2089. const cancelledItem = cancelled.next()
  2090. await vi.waitFor(() => { expect(socket.sent).toHaveLength(3) })
  2091. const cancelledOpen = JSON.parse(socket.sent[2]!) as { streamId: string }
  2092. const cancellation = new Error('caller cancelled')
  2093. socket.receive({ type: 'item', streamId: cancelledOpen.streamId, value: 'already queued' })
  2094. abort.abort(cancellation)
  2095. socket.receive({ type: 'item', streamId: cancelledOpen.streamId, value: 'after cancellation' })
  2096. await expect(cancelledItem).rejects.toBe(cancellation)
  2097. await vi.waitFor(() => {
  2098. expect(socket.sent.map(text => JSON.parse(text) as unknown)).toContainEqual({
  2099. type: 'cancel', streamId: cancelledOpen.streamId,
  2100. })
  2101. })
  2102. expect(call).not.toHaveBeenCalled()
  2103. } finally {
  2104. await dispose()
  2105. await ctx.fiber.dispose()
  2106. FakeWebSocket.sockets.length = 0
  2107. FakeWebSocket.autoOpen = true
  2108. FakeWebSocket.dispatchClose = true
  2109. if (originalWebSocket === undefined) delete (globalThis as WebSocketGlobal).WebSocket
  2110. else globalThis.WebSocket = originalWebSocket
  2111. if (locationDescriptor === undefined) Reflect.deleteProperty(globalThis, 'location')
  2112. else Object.defineProperty(globalThis, 'location', locationDescriptor)
  2113. }
  2114. })
  2115. })
  2116. describe('Remote stream client carrier lifecycle', () => {
  2117. it('requires the transport owner to start the physical carrier', async () => {
  2118. const client = new RemoteStreamMuxClient()
  2119. await expect(client.open('feed/follow', {}, new AbortController().signal)
  2120. [Symbol.asyncIterator]().next()).rejects.toThrow('Remote stream client not started')
  2121. await client.close()
  2122. })
  2123. it('connects without a logical stream, waits for owner-driven retries, and stops permanently', async () => {
  2124. await withFakeWebSocket('https://harness.example', async () => {
  2125. FakeWebSocket.autoOpen = false
  2126. const client = new RemoteStreamMuxClient()
  2127. client.start()
  2128. client.start()
  2129. expect(FakeWebSocket.sockets).toHaveLength(1)
  2130. const failed = FakeWebSocket.sockets[0]!
  2131. failed.fail()
  2132. await Promise.resolve()
  2133. expect(FakeWebSocket.sockets).toHaveLength(1)
  2134. client.reconnect()
  2135. await vi.waitFor(() => { expect(FakeWebSocket.sockets).toHaveLength(2) })
  2136. const connected = FakeWebSocket.sockets[1]!
  2137. connected.open()
  2138. await Promise.resolve()
  2139. client.start()
  2140. expect(FakeWebSocket.sockets).toHaveLength(2)
  2141. expect(connected.sent).toEqual([])
  2142. connected.fail()
  2143. await Promise.resolve()
  2144. expect(FakeWebSocket.sockets).toHaveLength(2)
  2145. client.reconnect()
  2146. await vi.waitFor(() => { expect(FakeWebSocket.sockets).toHaveLength(3) })
  2147. const final = FakeWebSocket.sockets[2]!
  2148. final.open()
  2149. await client.close()
  2150. await client.close()
  2151. client.start()
  2152. await expect(client.open('feed/follow', {}, new AbortController().signal)
  2153. [Symbol.asyncIterator]().next()).rejects.toThrow('Remote stream client disposed')
  2154. expect(FakeWebSocket.sockets).toHaveLength(3)
  2155. expect(final.closedWith).toContainEqual({ code: 1000, reason: 'disposed' })
  2156. const stopping = new RemoteStreamMuxClient()
  2157. stopping.start()
  2158. const racing = FakeWebSocket.sockets[3]!
  2159. racing.open()
  2160. racing.drop()
  2161. await stopping.close()
  2162. expect(FakeWebSocket.sockets).toHaveLength(4)
  2163. })
  2164. })
  2165. it('mints a new wire stream id when the same endpoint opens on a replacement socket', async () => {
  2166. await withFakeWebSocket('https://harness.example', async () => {
  2167. const client = new RemoteStreamMuxClient()
  2168. client.start()
  2169. const first = client.open('feed/follow', { label: 'same' }, new AbortController().signal)
  2170. [Symbol.asyncIterator]()
  2171. const firstPending = first.next()
  2172. await vi.waitFor(() => { expect(FakeWebSocket.sockets[0]?.sent).toHaveLength(1) })
  2173. const firstSocket = FakeWebSocket.sockets[0]!
  2174. const firstOpen = JSON.parse(firstSocket.sent[0]!) as { streamId: string }
  2175. firstSocket.receive({ type: 'end', streamId: firstOpen.streamId })
  2176. await expect(firstPending).resolves.toEqual({ done: true, value: undefined })
  2177. client.reconnect()
  2178. await vi.waitFor(() => { expect(FakeWebSocket.sockets).toHaveLength(2) })
  2179. const second = client.open('feed/follow', { label: 'same' }, new AbortController().signal)
  2180. [Symbol.asyncIterator]()
  2181. const secondPending = second.next()
  2182. const secondSocket = FakeWebSocket.sockets[1]!
  2183. await vi.waitFor(() => { expect(secondSocket.sent).toHaveLength(1) })
  2184. const secondOpen = JSON.parse(secondSocket.sent[0]!) as { streamId: string }
  2185. expect(secondOpen.streamId).not.toBe(firstOpen.streamId)
  2186. secondSocket.receive({ type: 'end', streamId: secondOpen.streamId })
  2187. await expect(secondPending).resolves.toEqual({ done: true, value: undefined })
  2188. await client.close()
  2189. })
  2190. })
  2191. it('replaces an in-flight candidate and an open socket on reconnect', async () => {
  2192. await withFakeWebSocket('https://harness.example', async () => {
  2193. FakeWebSocket.autoOpen = false
  2194. const client = new RemoteStreamMuxClient()
  2195. client.start()
  2196. const candidate = FakeWebSocket.sockets[0]!
  2197. client.reconnect()
  2198. const replacementPending = client.open(
  2199. 'feed/follow',
  2200. { label: 'replacement' },
  2201. new AbortController().signal,
  2202. )[Symbol.asyncIterator]().next()
  2203. await vi.waitFor(() => { expect(FakeWebSocket.sockets).toHaveLength(2) })
  2204. expect(candidate.closedWith).toContainEqual({})
  2205. const connected = FakeWebSocket.sockets[1]!
  2206. connected.open()
  2207. await vi.waitFor(() => { expect(connected.sent).toHaveLength(1) })
  2208. const opened = JSON.parse(connected.sent[0]!) as { streamId: string }
  2209. connected.receive({ type: 'end', streamId: opened.streamId })
  2210. await expect(replacementPending).resolves.toEqual({ done: true, value: undefined })
  2211. client.reconnect()
  2212. await vi.waitFor(() => { expect(FakeWebSocket.sockets).toHaveLength(3) })
  2213. expect(connected.closedWith).toContainEqual({ code: 4000, reason: 'reconnect requested' })
  2214. await client.close()
  2215. client.reconnect()
  2216. await Promise.resolve()
  2217. expect(FakeWebSocket.sockets).toHaveLength(3)
  2218. })
  2219. })
  2220. it('coalesces repeated candidate replacements and drops one queued after close', async () => {
  2221. await withFakeWebSocket('https://harness.example', async () => {
  2222. FakeWebSocket.autoOpen = false
  2223. const client = new RemoteStreamMuxClient()
  2224. client.start()
  2225. const first = FakeWebSocket.sockets[0]!
  2226. client.reconnect()
  2227. client.reconnect()
  2228. await vi.waitFor(() => { expect(FakeWebSocket.sockets).toHaveLength(2) })
  2229. expect(first.closedWith).toContainEqual({})
  2230. client.reconnect()
  2231. await client.close()
  2232. await Promise.resolve()
  2233. expect(FakeWebSocket.sockets).toHaveLength(2)
  2234. })
  2235. })
  2236. it('shares an in-flight connection and uses the internal ws URL without a browser origin', async () => {
  2237. await withFakeWebSocket(undefined, async () => {
  2238. FakeWebSocket.autoOpen = false
  2239. const client = new RemoteStreamMuxClient()
  2240. client.start()
  2241. const first = client.open('feed/follow', { label: 'first' }, new AbortController().signal)
  2242. [Symbol.asyncIterator]()
  2243. const second = client.open('feed/follow', { label: 'second' }, new AbortController().signal)
  2244. [Symbol.asyncIterator]()
  2245. const firstPending = first.next()
  2246. const secondPending = second.next()
  2247. expect(FakeWebSocket.sockets).toHaveLength(1)
  2248. const socket = FakeWebSocket.sockets[0]!
  2249. expect(socket.url).toBe('ws://dsh.internal/api/remote.mux')
  2250. socket.open()
  2251. await vi.waitFor(() => { expect(socket.sent).toHaveLength(2) })
  2252. const streamIds = socket.sent.map(text => (JSON.parse(text) as { streamId: string }).streamId)
  2253. socket.receive({ type: 'end', streamId: streamIds[0] })
  2254. socket.receive({ type: 'end', streamId: streamIds[1] })
  2255. await expect(firstPending).resolves.toEqual({ done: true, value: undefined })
  2256. await expect(secondPending).resolves.toEqual({ done: true, value: undefined })
  2257. await client.close()
  2258. })
  2259. })
  2260. it('fails waiters with one socket attempt and lets the owner start the next attempt', async () => {
  2261. await withFakeWebSocket('null', async () => {
  2262. FakeWebSocket.autoOpen = false
  2263. const closedClient = new RemoteStreamMuxClient()
  2264. closedClient.start()
  2265. const closed = closedClient.open('feed/follow', {}, new AbortController().signal)
  2266. [Symbol.asyncIterator]().next()
  2267. FakeWebSocket.sockets[0]!.drop()
  2268. await expect(closed).rejects.toThrow('Remote stream WebSocket closed before opening')
  2269. closedClient.reconnect()
  2270. const replacementStream = closedClient.open('feed/follow', {}, new AbortController().signal)
  2271. [Symbol.asyncIterator]().next()
  2272. await vi.waitFor(() => { expect(FakeWebSocket.sockets).toHaveLength(2) })
  2273. const replacement = FakeWebSocket.sockets[1]!
  2274. replacement.open()
  2275. await vi.waitFor(() => { expect(replacement.sent).toHaveLength(1) })
  2276. const { streamId } = JSON.parse(replacement.sent[0]!) as { streamId: string }
  2277. replacement.receive({ type: 'end', streamId })
  2278. await expect(replacementStream).resolves.toEqual({ done: true, value: undefined })
  2279. await closedClient.close()
  2280. const disposedClient = new RemoteStreamMuxClient()
  2281. disposedClient.start()
  2282. const disposed = disposedClient.open('feed/follow', {}, new AbortController().signal)
  2283. [Symbol.asyncIterator]().next()
  2284. await disposedClient.close()
  2285. await expect(disposed).rejects.toThrow('Remote stream client disposed')
  2286. const abortedClient = new RemoteStreamMuxClient()
  2287. abortedClient.start()
  2288. const abort = new AbortController()
  2289. const aborted = abortedClient.open('feed/follow', {}, abort.signal)[Symbol.asyncIterator]().next()
  2290. abort.abort('cancelled while connecting')
  2291. await expect(aborted).rejects.toBe('cancelled while connecting')
  2292. await abortedClient.close()
  2293. expect(FakeWebSocket.sockets[3]?.url).toBe('ws://dsh.internal/api/remote.mux')
  2294. })
  2295. })
  2296. it('fails active streams on an invalid frame and ignores later frames', async () => {
  2297. await withFakeWebSocket('https://harness.example', async () => {
  2298. const client = new RemoteStreamMuxClient()
  2299. client.start()
  2300. const stream = client.open('feed/follow', {}, new AbortController().signal)[Symbol.asyncIterator]()
  2301. const pending = stream.next()
  2302. await vi.waitFor(() => { expect(FakeWebSocket.sockets[0]?.sent).toHaveLength(1) })
  2303. const socket = FakeWebSocket.sockets[0]!
  2304. const { streamId } = JSON.parse(socket.sent[0]!) as { streamId: string }
  2305. FakeWebSocket.dispatchClose = false
  2306. socket.receiveRaw(new Uint8Array([1, 2, 3]))
  2307. socket.receive({ type: 'item', streamId, value: 'too late' })
  2308. socket.drop()
  2309. await expect(pending).rejects.toMatchObject({
  2310. name: 'RemoteStreamCarrierError', message: 'api gateway: invalid Remote stream frame',
  2311. })
  2312. expect(socket.closedWith).toContainEqual({ code: 4002, reason: 'invalid Remote stream frame' })
  2313. await client.close()
  2314. })
  2315. })
  2316. it('completes a stream and drops a frame racing with cancellation', async () => {
  2317. await withFakeWebSocket('https://harness.example', async () => {
  2318. const client = new RemoteStreamMuxClient()
  2319. client.start()
  2320. const completed = client.open('feed/follow', {}, new AbortController().signal)
  2321. [Symbol.asyncIterator]()
  2322. const completedPending = completed.next()
  2323. await vi.waitFor(() => { expect(FakeWebSocket.sockets[0]?.sent).toHaveLength(1) })
  2324. const socket = FakeWebSocket.sockets[0]!
  2325. const completedOpen = JSON.parse(socket.sent[0]!) as { streamId: string }
  2326. socket.receive({ type: 'end', streamId: completedOpen.streamId })
  2327. await expect(completedPending).resolves.toEqual({ done: true, value: undefined })
  2328. const abort = new AbortController()
  2329. const cancelled = client.open('feed/follow', {}, abort.signal)[Symbol.asyncIterator]().next()
  2330. await vi.waitFor(() => { expect(socket.sent).toHaveLength(2) })
  2331. const cancelledOpen = JSON.parse(socket.sent[1]!) as { streamId: string }
  2332. const reason = new Error('fixture cancellation race')
  2333. abort.abort(reason)
  2334. socket.receive({ type: 'item', streamId: cancelledOpen.streamId, value: 'too late' })
  2335. await expect(cancelled).rejects.toBe(reason)
  2336. await client.close()
  2337. })
  2338. })
  2339. it('contains non-Error cancellation reasons and late socket close events', async () => {
  2340. await withFakeWebSocket('http://harness.example', async () => {
  2341. const cancelledClient = new RemoteStreamMuxClient()
  2342. cancelledClient.start()
  2343. const abort = new AbortController()
  2344. const cancelled = cancelledClient.open('feed/follow', {}, abort.signal)[Symbol.asyncIterator]().next()
  2345. await vi.waitFor(() => { expect(FakeWebSocket.sockets[0]?.sent).toHaveLength(1) })
  2346. abort.abort('caller cancelled')
  2347. await expect(cancelled).rejects.toThrow('caller cancelled')
  2348. await cancelledClient.close()
  2349. FakeWebSocket.dispatchClose = false
  2350. const disposedClient = new RemoteStreamMuxClient()
  2351. disposedClient.start()
  2352. const disposed = disposedClient.open('feed/follow', {}, new AbortController().signal)
  2353. [Symbol.asyncIterator]().next()
  2354. await vi.waitFor(() => { expect(FakeWebSocket.sockets[1]?.sent).toHaveLength(1) })
  2355. const disposedSocket = FakeWebSocket.sockets[1]!
  2356. await disposedClient.close()
  2357. disposedSocket.receive({ type: 'end', streamId: 'stale' })
  2358. disposedSocket.drop()
  2359. await expect(disposed).rejects.toThrow('Remote stream client disposed')
  2360. })
  2361. })
  2362. })
  2363. async function withFakeWebSocket(
  2364. origin: string | undefined,
  2365. run: () => Promise<void>,
  2366. ): Promise<void> {
  2367. const originalWebSocket = globalThis.WebSocket
  2368. const locationDescriptor = Object.getOwnPropertyDescriptor(globalThis, 'location')
  2369. ;(globalThis as WebSocketGlobal).WebSocket = FakeWebSocket as unknown as typeof WebSocket
  2370. if (origin === undefined) Reflect.deleteProperty(globalThis, 'location')
  2371. else Object.defineProperty(globalThis, 'location', { configurable: true, value: { origin } })
  2372. FakeWebSocket.sockets.length = 0
  2373. FakeWebSocket.autoOpen = true
  2374. FakeWebSocket.dispatchClose = true
  2375. try {
  2376. await run()
  2377. } finally {
  2378. FakeWebSocket.sockets.length = 0
  2379. FakeWebSocket.autoOpen = true
  2380. FakeWebSocket.dispatchClose = true
  2381. if (originalWebSocket === undefined) delete (globalThis as WebSocketGlobal).WebSocket
  2382. else globalThis.WebSocket = originalWebSocket
  2383. if (locationDescriptor === undefined) Reflect.deleteProperty(globalThis, 'location')
  2384. else Object.defineProperty(globalThis, 'location', locationDescriptor)
  2385. }
  2386. }