client-apply.client.spec.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620
  1. /**
  2. * Connection plugin browser-half apply: ctx.connection handle mounting,
  3. * explicit carrier selection, and single-consumer connection-loop ownership.
  4. */
  5. import { Context } from '@deepseek-ai/cordis'
  6. import { afterEach, describe, expect, it, vi } from 'vitest'
  7. import {
  8. apply,
  9. type ClientConnectionRpc,
  10. type ClientTransportHooks,
  11. type ConnectionGenerationSource,
  12. type RpcFetch,
  13. type ConnectionHandle,
  14. type ConnectionState,
  15. } from '../src/client/index.ts'
  16. type Win = {
  17. location?: { hostname: string; origin?: string }
  18. __DSH_TRANSPORT__?: ClientTransportHooks
  19. }
  20. afterEach(() => {
  21. delete (globalThis as Win).location
  22. delete (globalThis as Win).__DSH_TRANSPORT__
  23. vi.unstubAllGlobals()
  24. vi.useRealTimers()
  25. })
  26. class BrowserNetworkProbe extends EventTarget {
  27. readonly navigator = { onLine: true }
  28. setOnline(online: boolean): void {
  29. this.navigator.onLine = online
  30. this.dispatchEvent(new Event(online ? 'online' : 'offline'))
  31. }
  32. }
  33. class GenerationProbe {
  34. private readonly active = new Set<() => void>()
  35. readonly source: ConnectionGenerationSource = (signal, ready) => new Promise<void>((resolve) => {
  36. let settled = false
  37. const finish = (): void => {
  38. if (settled) return
  39. settled = true
  40. signal.removeEventListener('abort', finish)
  41. this.active.delete(finish)
  42. resolve()
  43. }
  44. this.active.add(finish)
  45. signal.addEventListener('abort', finish, { once: true })
  46. ready({ home: '/h' })
  47. if (signal.aborted) finish()
  48. })
  49. end(): void {
  50. for (const finish of [...this.active]) finish()
  51. }
  52. }
  53. function installGeneration(handle: ConnectionHandle): GenerationProbe {
  54. const probe = new GenerationProbe()
  55. handle.registerGenerationSource(probe.source)
  56. return probe
  57. }
  58. async function mount(): Promise<ConnectionHandle> {
  59. const ctx = new Context()
  60. await ctx.plugin({ apply, inject: [] })
  61. const handle = ctx.get('connection') as ConnectionHandle | undefined
  62. if (handle === undefined) throw new Error('ctx.connection not provided')
  63. return handle
  64. }
  65. describe('connection client apply', () => {
  66. it('uses Host bootstrap timing when Gateway starts without overrides', async () => {
  67. vi.useFakeTimers()
  68. vi.stubGlobal('__DSH_CONNECTION_RECOVERY__', {
  69. backoffBaseMs: 10, backoffMaxMs: 10, generationReadyTimeoutMs: 20,
  70. })
  71. const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
  72. const handle = await mount()
  73. const signals: AbortSignal[] = []
  74. handle.registerGenerationSource(signal => new Promise<void>((resolve) => {
  75. signals.push(signal)
  76. signal.addEventListener('abort', () => { resolve() }, { once: true })
  77. }))
  78. const loop = handle.start({})
  79. try {
  80. await vi.advanceTimersByTimeAsync(20)
  81. expect(signals[0]?.aborted).toBe(true)
  82. expect(handle.state.getSnapshot()).toBe('connecting')
  83. await vi.advanceTimersByTimeAsync(10)
  84. expect(signals).toHaveLength(2)
  85. } finally {
  86. loop.stop()
  87. await vi.advanceTimersByTimeAsync(0)
  88. warnSpy.mockRestore()
  89. }
  90. })
  91. it.each([{ generationReadyTimeoutMs: 0 }, { backoffFactor: NaN }])('rejects malformed bootstrap recovery before publishing the service: %j', (recovery) => {
  92. vi.stubGlobal('__DSH_CONNECTION_RECOVERY__', recovery)
  93. const ctx = new Context()
  94. expect(() => { apply(ctx) }).toThrow()
  95. expect(ctx.get('connection')).toBeUndefined()
  96. })
  97. it('rejects a NaN start override without acquiring the generation source', async () => {
  98. const handle = await mount()
  99. const source = vi.fn<ConnectionGenerationSource>()
  100. const unregister = handle.registerGenerationSource(source)
  101. try {
  102. expect(() => handle.start({}, { backoffFactor: NaN })).toThrow(/backoffFactor.*finite/)
  103. expect(source).not.toHaveBeenCalled()
  104. } finally {
  105. unregister()
  106. }
  107. })
  108. it('treats a runtime without browser location as local', async () => {
  109. delete (globalThis as Win).location
  110. expect((await mount()).isLoopback).toBe(true)
  111. })
  112. it('mounts ctx.connection and identifies a loopback page', async () => {
  113. ;(globalThis as Win).location = { hostname: 'localhost' }
  114. const handle = await mount()
  115. expect(handle.isLoopback).toBe(true)
  116. })
  117. it('reports non-loopback page authority through the connection handle', async () => {
  118. ;(globalThis as Win).location = { hostname: '192.0.2.20' }
  119. expect((await mount()).isLoopback).toBe(false)
  120. })
  121. it('requires one generation source and ignores a stale source disposer', async () => {
  122. ;(globalThis as Win).location = { hostname: 'localhost' }
  123. const handle = await mount()
  124. const first = new GenerationProbe()
  125. const second = new GenerationProbe()
  126. expect(() => handle.start({})).toThrow('no generation source is registered')
  127. const unregisterFirst = handle.registerGenerationSource(first.source)
  128. expect(() => { handle.registerGenerationSource(second.source) })
  129. .toThrow('a generation source is already registered')
  130. unregisterFirst()
  131. const unregisterSecond = handle.registerGenerationSource(second.source)
  132. unregisterFirst()
  133. const loop = handle.start({})
  134. await vi.waitFor(() => {
  135. expect(handle.generation.getSnapshot()?.host.home).toBe('/h')
  136. })
  137. unregisterSecond()
  138. expect(handle.generation.getSnapshot()).toBeUndefined()
  139. loop.stop()
  140. })
  141. it('start() hands out one loop, rejects a second consumer, and stop() aborts the generation', async () => {
  142. ;(globalThis as Win).location = { hostname: 'localhost' }
  143. const handle = await mount()
  144. installGeneration(handle)
  145. const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined)
  146. const generations: Array<string | undefined> = []
  147. const stopThrowing = handle.generation.subscribe(() => { throw new Error('subscriber bug') })
  148. const stopGeneration = handle.generation.subscribe(() => {
  149. generations.push(handle.generation.getSnapshot()?.host.home)
  150. })
  151. expect(handle.generation.getSnapshot()).toBeUndefined()
  152. let connected = 0
  153. const loop = handle.start({ onConnected: () => { connected++ } })
  154. expect(() => handle.start({})).toThrow(/already owned by another consumer/)
  155. await vi.waitFor(() => {
  156. expect(handle.generation.getSnapshot()?.host.home).toBe('/h')
  157. })
  158. loop.stop() // teardown must not throw; the fixture streams abort quietly
  159. expect(handle.generation.getSnapshot()).toBeUndefined()
  160. expect(generations).toEqual(['/h', undefined])
  161. expect(connected).toBe(1)
  162. expect(errorSpy).toHaveBeenCalledTimes(2)
  163. stopThrowing()
  164. stopGeneration()
  165. errorSpy.mockRestore()
  166. })
  167. it('does not notify state subscribers when a pre-ready loop stops', async () => {
  168. ;(globalThis as Win).location = { hostname: 'localhost' }
  169. const handle = await mount()
  170. handle.registerGenerationSource(signal => new Promise<void>((resolve) => {
  171. signal.addEventListener('abort', () => { resolve() }, { once: true })
  172. }))
  173. const listener = vi.fn()
  174. const unsubscribe = handle.state.subscribe(listener)
  175. const loop = handle.start({})
  176. loop.stop()
  177. expect(handle.state.getSnapshot()).toBeUndefined()
  178. expect(listener).not.toHaveBeenCalled()
  179. unsubscribe()
  180. })
  181. it('allows a replacement owner and ignores the previous owner handle', async () => {
  182. ;(globalThis as Win).location = { hostname: 'localhost' }
  183. const handle = await mount()
  184. const generation = installGeneration(handle)
  185. const first = handle.start({})
  186. await vi.waitFor(() => {
  187. expect(handle.generation.getSnapshot()?.host.home).toBe('/h')
  188. })
  189. first.stop()
  190. expect(handle.generation.getSnapshot()).toBeUndefined()
  191. const second = handle.start({})
  192. await vi.waitFor(() => {
  193. expect(handle.generation.getSnapshot()?.host.home).toBe('/h')
  194. })
  195. first.stop()
  196. expect(handle.generation.getSnapshot()?.host.home).toBe('/h')
  197. second.stop()
  198. generation.end()
  199. })
  200. it('lets the connection service force only its current owner to reconnect', async () => {
  201. ;(globalThis as Win).location = { hostname: 'localhost' }
  202. const handle = await mount()
  203. installGeneration(handle)
  204. const requested = vi.fn()
  205. const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
  206. const loop = handle.start({ onReconnectRequested: requested }, {
  207. backoffBaseMs: 60_000,
  208. backoffFactor: 2,
  209. backoffMaxMs: 120_000,
  210. generationReadyTimeoutMs: 500,
  211. })
  212. try {
  213. await vi.waitFor(() => { expect(handle.generation.getSnapshot()?.id).toBe(1) })
  214. handle.reconnect()
  215. await vi.waitFor(() => { expect(handle.generation.getSnapshot()?.id).toBe(2) })
  216. expect(requested).toHaveBeenCalledOnce()
  217. loop.stop()
  218. handle.reconnect()
  219. expect(requested).toHaveBeenCalledOnce()
  220. } finally {
  221. loop.stop()
  222. warnSpy.mockRestore()
  223. }
  224. })
  225. it('ignores a non-browser window shim without navigator state', async () => {
  226. vi.stubGlobal('window', new EventTarget())
  227. ;(globalThis as Win).location = { hostname: 'localhost' }
  228. const handle = await mount()
  229. installGeneration(handle)
  230. const loop = handle.start({})
  231. try {
  232. await vi.waitFor(() => { expect(handle.state.getSnapshot()).toBe('connected') })
  233. } finally {
  234. loop.stop()
  235. }
  236. })
  237. it('feeds browser offline and online events into the owned retry loop', async () => {
  238. vi.useFakeTimers()
  239. const randomSpy = vi.spyOn(Math, 'random').mockReturnValue(0)
  240. const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
  241. const browser = new BrowserNetworkProbe()
  242. vi.stubGlobal('window', browser)
  243. ;(globalThis as Win).location = { hostname: 'localhost' }
  244. const handle = await mount()
  245. let calls = 0
  246. const source: ConnectionGenerationSource = (signal, ready) => new Promise<void>((resolve) => {
  247. calls++
  248. ready({ home: '/h' })
  249. signal.addEventListener('abort', () => { resolve() }, { once: true })
  250. })
  251. handle.registerGenerationSource(source)
  252. const states: Array<ConnectionState | undefined> = []
  253. const unsubscribe = handle.state.subscribe(() => { states.push(handle.state.getSnapshot()) })
  254. const loop = handle.start({}, {
  255. backoffBaseMs: 100,
  256. backoffFactor: 2,
  257. backoffMaxMs: 1_000,
  258. generationReadyTimeoutMs: 500,
  259. })
  260. try {
  261. await vi.advanceTimersByTimeAsync(0)
  262. expect(handle.state.getSnapshot()).toBe('connected')
  263. expect(calls).toBe(1)
  264. browser.setOnline(false)
  265. expect(handle.state.getSnapshot()).toBe('disconnected')
  266. await vi.advanceTimersByTimeAsync(10_000)
  267. expect(calls).toBe(1)
  268. browser.setOnline(true)
  269. expect(handle.state.getSnapshot()).toBe('connecting')
  270. await vi.advanceTimersByTimeAsync(49)
  271. expect(calls).toBe(1)
  272. await vi.advanceTimersByTimeAsync(1)
  273. expect(calls).toBe(2)
  274. expect(handle.state.getSnapshot()).toBe('connected')
  275. expect(states).toEqual(['connected', 'disconnected', 'connecting', 'connected'])
  276. } finally {
  277. unsubscribe()
  278. loop.stop()
  279. randomSpy.mockRestore()
  280. warnSpy.mockRestore()
  281. }
  282. })
  283. it('does not announce a generation synchronously stopped by a generation subscriber', async () => {
  284. ;(globalThis as Win).location = { hostname: 'localhost' }
  285. const handle = await mount()
  286. installGeneration(handle)
  287. const owner: { loop?: ReturnType<ConnectionHandle['start']> } = {}
  288. let sawGeneration = false
  289. const stopGeneration = handle.generation.subscribe(() => {
  290. if (handle.generation.getSnapshot() === undefined) return
  291. sawGeneration = true
  292. owner.loop?.stop()
  293. })
  294. const connected = vi.fn()
  295. const loop = handle.start({ onConnected: connected })
  296. owner.loop = loop
  297. try {
  298. await vi.waitFor(() => { expect(sawGeneration).toBe(true) })
  299. expect(handle.generation.getSnapshot()).toBeUndefined()
  300. expect(connected).not.toHaveBeenCalled()
  301. } finally {
  302. stopGeneration()
  303. loop.stop()
  304. }
  305. })
  306. it('retracts the generation while connecting and publishes the next generation', async () => {
  307. ;(globalThis as Win).location = { hostname: 'localhost' }
  308. const handle = await mount()
  309. const generation = installGeneration(handle)
  310. const generations: Array<string | undefined> = []
  311. const reconnectSnapshots: Array<string | undefined> = []
  312. const stopGeneration = handle.generation.subscribe(() => {
  313. generations.push(handle.generation.getSnapshot()?.host.home)
  314. })
  315. const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
  316. const loop = handle.start({
  317. onStateChange: (state) => {
  318. if (state === 'connecting') {
  319. reconnectSnapshots.push(handle.generation.getSnapshot()?.host.home)
  320. }
  321. },
  322. }, { backoffBaseMs: 10, backoffFactor: 2, backoffMaxMs: 80, generationReadyTimeoutMs: 500 })
  323. try {
  324. await vi.waitFor(() => {
  325. expect(handle.generation.getSnapshot()?.host.home).toBe('/h')
  326. })
  327. generation.end()
  328. await vi.waitFor(() => { expect(reconnectSnapshots).toEqual([undefined]) })
  329. await vi.waitFor(() => { expect(generations).toEqual(['/h', undefined, '/h']) })
  330. expect(handle.generation.getSnapshot()?.host.home).toBe('/h')
  331. } finally {
  332. stopGeneration()
  333. loop.stop()
  334. warnSpy.mockRestore()
  335. }
  336. })
  337. it('publishes connection state directly on the service and isolates subscribers', async () => {
  338. ;(globalThis as Win).location = { hostname: 'localhost' }
  339. const handle = await mount()
  340. const generation = installGeneration(handle)
  341. const snapshots: Array<ConnectionState | undefined> = []
  342. const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined)
  343. const unsubscribe = handle.state.subscribe(() => { snapshots.push(handle.state.getSnapshot()) })
  344. const stopThrowing = handle.state.subscribe(() => { throw new Error('state subscriber failed') })
  345. expect(handle.state.getSnapshot()).toBeUndefined()
  346. const loop = handle.start({}, {
  347. backoffBaseMs: 10,
  348. backoffFactor: 2,
  349. backoffMaxMs: 80,
  350. generationReadyTimeoutMs: 500,
  351. })
  352. try {
  353. await vi.waitFor(() => { expect(handle.state.getSnapshot()).toBe('connected') })
  354. const connected = handle.state.getSnapshot()
  355. expect(handle.state.getSnapshot()).toBe(connected)
  356. generation.end()
  357. await vi.waitFor(() => {
  358. expect(snapshots).toEqual([
  359. 'connected',
  360. 'connecting',
  361. 'connected',
  362. ])
  363. })
  364. expect(errorSpy).toHaveBeenCalledWith('[connection] state listener threw:', expect.any(Error))
  365. } finally {
  366. unsubscribe()
  367. stopThrowing()
  368. loop.stop()
  369. errorSpy.mockRestore()
  370. }
  371. expect(handle.state.getSnapshot()).toBeUndefined()
  372. })
  373. it('does not announce disconnection after a generation subscriber stops the loop', async () => {
  374. ;(globalThis as Win).location = { hostname: 'localhost' }
  375. const handle = await mount()
  376. const generation = installGeneration(handle)
  377. const owner: { loop?: ReturnType<ConnectionHandle['start']> } = {}
  378. let stoppedOnRetraction = false
  379. const stopGeneration = handle.generation.subscribe(() => {
  380. if (handle.generation.getSnapshot() !== undefined || owner.loop === undefined) return
  381. stoppedOnRetraction = true
  382. owner.loop.stop()
  383. })
  384. const states: ConnectionState[] = []
  385. const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
  386. const loop = handle.start({
  387. onStateChange: (state) => { states.push(state) },
  388. }, { backoffBaseMs: 10, backoffFactor: 2, backoffMaxMs: 80, generationReadyTimeoutMs: 500 })
  389. owner.loop = loop
  390. try {
  391. await vi.waitFor(() => {
  392. expect(handle.generation.getSnapshot()?.host.home).toBe('/h')
  393. })
  394. generation.end()
  395. await vi.waitFor(() => { expect(stoppedOnRetraction).toBe(true) })
  396. expect(handle.generation.getSnapshot()).toBeUndefined()
  397. expect(states).toEqual(['connected'])
  398. } finally {
  399. stopGeneration()
  400. loop.stop()
  401. warnSpy.mockRestore()
  402. }
  403. })
  404. it('carries RPC calls without requiring secure-context randomUUID', async () => {
  405. ;(globalThis as Win).location = { hostname: 'localhost' }
  406. vi.stubGlobal('crypto', {
  407. getRandomValues(bytes: Uint8Array) {
  408. return bytes.fill(0)
  409. },
  410. })
  411. const handle = await mount()
  412. const original = globalThis.fetch
  413. const seen: { url: string; body: unknown }[] = []
  414. globalThis.fetch = async (input: URL | RequestInfo, init?: RequestInit) => {
  415. const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url
  416. if (typeof init?.body !== 'string') throw new TypeError('expected a JSON string request body')
  417. const body = JSON.parse(init.body) as { rpcId: string }
  418. seen.push({ url, body })
  419. return Response.json({
  420. type: 'server-response',
  421. rpcId: body.rpcId,
  422. result: { ok: true, value: { ref: 'goal-1' } },
  423. })
  424. }
  425. try {
  426. await expect(handle.rpc.call('/api', 'goals/create', { args: { agentId: 'agent-1' } }))
  427. .resolves.toEqual({ ok: true, value: { ref: 'goal-1' } })
  428. } finally {
  429. globalThis.fetch = original
  430. vi.unstubAllGlobals()
  431. }
  432. expect(seen).toHaveLength(1)
  433. expect(seen[0]?.url).toBe('http://dsh.internal/api/goals/create')
  434. expect(seen[0]?.body).toMatchObject({
  435. type: 'client-request',
  436. rpcId: '00000000-0000-4000-8000-000000000000',
  437. method: 'goals/create',
  438. payload: { args: { agentId: 'agent-1' } },
  439. })
  440. })
  441. it('uses an already decoded rpc carrier from the transport hooks instead of the HTTP caller', async () => {
  442. ;(globalThis as Win).location = { hostname: 'preview.example' }
  443. const rpc: ClientConnectionRpc = {
  444. call: vi.fn(async (_channel: string, endpoint: string, payload: unknown) => ({ ok: true as const, value: { endpoint, payload } })),
  445. open: vi.fn((_channel: string, endpoint: string) => (async function *(): AsyncGenerator { yield endpoint })()),
  446. }
  447. ;(globalThis as Win).__DSH_TRANSPORT__ = { rpc }
  448. const handle = await mount()
  449. expect(handle.rpc).toBe(rpc)
  450. await expect(handle.rpc.call('/api', 'session/list', { args: [] })).resolves.toEqual({
  451. ok: true, value: { endpoint: 'session/list', payload: { args: [] } },
  452. })
  453. })
  454. it('exposes a worker-local Gateway stream through connection.rpc.open', async () => {
  455. ;(globalThis as Win).location = { hostname: 'preview.example' }
  456. const openStream = vi.fn<NonNullable<ClientTransportHooks['openStream']>>(
  457. (endpoint, payload, signal) => (async function *(): AsyncGenerator {
  458. signal.throwIfAborted()
  459. yield { endpoint, payload }
  460. })(),
  461. )
  462. ;(globalThis as Win).__DSH_TRANSPORT__ = {
  463. fetch: vi.fn<RpcFetch>(),
  464. openStream,
  465. ownsHost: true,
  466. }
  467. const handle = await mount()
  468. const abort = new AbortController()
  469. const open = handle.rpc.open
  470. if (open === undefined) throw new Error('worker-local stream carrier was not installed')
  471. const values = []
  472. for await (const value of open('/api', 'session/follow', { args: { sessionId: 'session-1' } }, abort.signal)) {
  473. values.push(value)
  474. }
  475. expect(values).toEqual([{
  476. endpoint: 'session/follow', payload: { args: { sessionId: 'session-1' } },
  477. }])
  478. expect(openStream).toHaveBeenCalledWith(
  479. 'session/follow',
  480. { args: { sessionId: 'session-1' } },
  481. abort.signal,
  482. )
  483. expect(handle.isLoopback).toBe(true)
  484. expect(() => open('/rpc', 'session/follow', {}, abort.signal))
  485. .toThrow('worker-local streams require the /api channel')
  486. expect(() => open('/api/path', 'session/follow', {}, abort.signal))
  487. .toThrow('invalid RPC target')
  488. })
  489. it('validates generic RPC transport failures, correlation, and targets', async () => {
  490. ;(globalThis as Win).location = {
  491. hostname: 'harness.example', origin: 'https://harness.example',
  492. }
  493. const handle = await mount()
  494. const original = globalThis.fetch
  495. const abort = new AbortController()
  496. globalThis.fetch = vi.fn().mockResolvedValue(new Response('unavailable', { status: 503 }))
  497. try {
  498. await expect(handle.rpc.call('/api', 'goals/create', {}, abort.signal))
  499. .rejects.toThrow('HTTP 503')
  500. expect(globalThis.fetch).toHaveBeenCalledWith(
  501. new URL('https://harness.example/api/goals/create'),
  502. expect.objectContaining({ signal: abort.signal }),
  503. )
  504. ;(globalThis as Win).location = { hostname: 'localhost', origin: 'null' }
  505. globalThis.fetch = vi.fn().mockResolvedValue(Response.json({
  506. type: 'server-response',
  507. rpcId: 'different-rpc',
  508. result: { ok: true, value: null },
  509. }))
  510. await expect(handle.rpc.call('/api', 'goals/create', {})).rejects.toThrow('rpcId mismatch')
  511. const fetch = vi.mocked(globalThis.fetch)
  512. expect(fetch.mock.calls[0]?.[0]).toEqual(new URL('http://dsh.internal/api/goals/create'))
  513. expect(fetch.mock.calls[0]?.[1]).not.toHaveProperty('signal')
  514. const respond = (result: unknown): void => {
  515. globalThis.fetch = async (_input: URL | RequestInfo, init?: RequestInit) => {
  516. if (typeof init?.body !== 'string') throw new TypeError('expected a JSON request body')
  517. const request = JSON.parse(init.body) as { rpcId: string }
  518. return Response.json({ type: 'server-response', rpcId: request.rpcId, result })
  519. }
  520. }
  521. for (const envelope of [
  522. null,
  523. { type: 'other', rpcId: 'rpc', result: { ok: true } },
  524. { type: 'server-response', rpcId: 1, result: { ok: true } },
  525. ]) {
  526. globalThis.fetch = vi.fn().mockResolvedValue(Response.json(envelope))
  527. await expect(handle.rpc.call('/api', 'goals/create', {}))
  528. .rejects.toThrow('invalid server-response envelope')
  529. }
  530. respond(null)
  531. await expect(handle.rpc.call('/api', 'goals/create', {}))
  532. .rejects.toThrow('invalid server-response result')
  533. respond({ ok: 'yes' })
  534. await expect(handle.rpc.call('/api', 'goals/create', {}))
  535. .rejects.toThrow('invalid server-response result')
  536. respond({ ok: false, error: null })
  537. await expect(handle.rpc.call('/api', 'goals/create', {}))
  538. .rejects.toThrow('invalid server-response result')
  539. for (const error of [
  540. { code: 1, message: 'failed', details: {} },
  541. { code: 'failed', message: 1, details: {} },
  542. { code: 'failed', message: 'failed', details: [] },
  543. ]) {
  544. respond({ ok: false, error })
  545. await expect(handle.rpc.call('/api', 'goals/create', {}))
  546. .rejects.toThrow('invalid server-response failure')
  547. }
  548. respond({
  549. ok: false,
  550. error: { code: 'fixture-failed', message: 'fixture rejected the call', details: { retry: false } },
  551. })
  552. await expect(handle.rpc.call('/api', 'goals/create', {})).resolves.toEqual({
  553. ok: false,
  554. error: { code: 'fixture-failed', message: 'fixture rejected the call', details: { retry: false } },
  555. })
  556. } finally {
  557. globalThis.fetch = original
  558. }
  559. for (const [channel, endpoint] of [
  560. ['api2', 'goals/create'],
  561. ['/api/path', 'goals/create'],
  562. ['/api', ''],
  563. ['/api', '.'],
  564. ['/api', '..'],
  565. ['/api', 'goals//create'],
  566. ['/api', 'goals/create?unsafe'],
  567. ] as const) {
  568. await expect(handle.rpc.call(channel, endpoint, {})).rejects.toThrow('invalid RPC target')
  569. }
  570. })
  571. })