gateway.client.spec.ts 107 KB

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