client-apply.client.spec.ts 23 KB

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