11// Real Gateway WebSocket proof for agent delivery fallback, response ordering, and idempotency.
22import { afterAll , beforeAll , beforeEach , describe , expect , test , vi } from "vitest" ;
3- import type { WebSocket } from "ws" ;
3+ import type { RawData , WebSocket } from "ws" ;
4+ import { rawDataToString } from "../infra/ws.js" ;
45import { createDeferred } from "../shared/deferred.js" ;
56import { startGatewayServerHarness , type GatewayServerHarness } from "./server.e2e-ws-harness.js" ;
67import { agentCommand , installGatewayTestHooks , onceMessage } from "./test-helpers.js" ;
@@ -62,6 +63,14 @@ describe("gateway agent RPC contracts", () => {
6263
6364 const idempotencyKey = "gateway-agent-rpc-contract" ;
6465 const first = await harness . openClient ( ) ;
66+ const orderedResponses : AgentResponse [ ] = [ ] ;
67+ const recordResponse = ( data : RawData ) => {
68+ const frame = JSON . parse ( rawDataToString ( data ) ) as AgentResponse ;
69+ if ( frame . type === "res" && frame . id === "agent-contract" ) {
70+ orderedResponses . push ( frame ) ;
71+ }
72+ } ;
73+ first . ws . on ( "message" , recordResponse ) ;
6574 const acceptedPromise = onceMessage < AgentResponse > (
6675 first . ws ,
6776 ( frame ) =>
@@ -84,7 +93,7 @@ describe("gateway agent RPC contracts", () => {
8493 message : "prove the gateway agent RPC contract" ,
8594 } ) ;
8695
87- const accepted = await acceptedPromise ;
96+ await acceptedPromise ;
8897 await vi . waitFor ( ( ) => expect ( agentCommand ) . toHaveBeenCalledTimes ( 1 ) ) ;
8998 expect ( vi . mocked ( agentCommand ) . mock . calls [ 0 ] ?. [ 0 ] ) . toMatchObject ( {
9099 runId : idempotencyKey ,
@@ -96,6 +105,9 @@ describe("gateway agent RPC contracts", () => {
96105
97106 runCompletion . resolve ( ) ;
98107 const terminal = await terminalPromise ;
108+ first . ws . off ( "message" , recordResponse ) ;
109+ expect ( orderedResponses . map ( ( frame ) => frame . payload ?. status ) ) . toEqual ( [ "accepted" , "ok" ] ) ;
110+ const accepted = orderedResponses [ 0 ] ;
99111 expect ( accepted ) . toMatchObject ( {
100112 type : "res" ,
101113 id : "agent-contract" ,
0 commit comments