11// Gateway server integration tests cover startup, auth, device pairing, session
22// routing, OpenAI-compatible paths, and environment isolation for local servers.
33import fs from "node:fs/promises" ;
4+ import { createServer } from "node:http" ;
45import os from "node:os" ;
56import path from "node:path" ;
67import { afterEach , beforeAll , beforeEach , describe , expect , it , vi } from "vitest" ;
@@ -11,6 +12,13 @@ import {
1112 writeConfigFile ,
1213} from "../config/config.js" ;
1314import { resetConfigOverrides , setConfigOverride } from "../config/runtime-overrides.js" ;
15+ import { resolveStorePath } from "../config/sessions/paths.js" ;
16+ import {
17+ appendTranscriptMessage ,
18+ loadSessionEntry ,
19+ loadTranscriptEventsSync ,
20+ upsertSessionEntry ,
21+ } from "../config/sessions/session-accessor.js" ;
1422import { clearSessionStoreCacheForTest } from "../config/sessions/store-writer-state.js" ;
1523import type { GatewayAuthConfig , GatewayTailscaleConfig } from "../config/types.gateway.js" ;
1624import type { OpenClawConfig } from "../config/types.openclaw.js" ;
@@ -543,6 +551,257 @@ describe("gateway e2e", () => {
543551 }
544552 } ) ;
545553
554+ it (
555+ "applies a hot-reloaded compaction model to automatic chat preflight without restarting" ,
556+ { timeout : GATEWAY_E2E_TIMEOUT_MS } ,
557+ async ( ) => {
558+ const { envSnapshot, tempHome, workspaceDir } = await setupGatewayTempHome ( {
559+ prefix : "openclaw-gw-compaction-hot-reload-" ,
560+ } ) ;
561+ const token = nextGatewayId ( "compaction-hot-reload-token" ) ;
562+ setTestEnvValue ( "OPENCLAW_GATEWAY_TOKEN" , token ) ;
563+
564+ const providerRequests : Array < { model : string } > = [ ] ;
565+ const summaryByModel = new Map < string , string > ( ) ;
566+ const providerServer = createServer ( ( request , response ) => {
567+ void ( async ( ) => {
568+ const chunks : Buffer [ ] = [ ] ;
569+ for await ( const chunk of request ) {
570+ chunks . push ( Buffer . isBuffer ( chunk ) ? chunk : Buffer . from ( chunk ) ) ;
571+ }
572+ if ( request . method !== "POST" || request . url !== "/v1/responses" ) {
573+ response . writeHead ( 404 ) . end ( ) ;
574+ return ;
575+ }
576+ const body = JSON . parse ( Buffer . concat ( chunks ) . toString ( "utf8" ) ) as { model ?: string } ;
577+ const model = body . model ?? "" ;
578+ providerRequests . push ( { model } ) ;
579+ const text = summaryByModel . get ( model ) ?? "Primary assistant answer." ;
580+ const message = {
581+ type : "message" ,
582+ id : nextGatewayId ( "provider-message" ) ,
583+ role : "assistant" ,
584+ status : "completed" ,
585+ content : [ { type : "output_text" , text, annotations : [ ] } ] ,
586+ } ;
587+ const events = [
588+ {
589+ type : "response.output_item.added" ,
590+ item : { ...message , status : "in_progress" , content : [ ] } ,
591+ } ,
592+ { type : "response.output_item.done" , item : message } ,
593+ {
594+ type : "response.completed" ,
595+ response : {
596+ status : "completed" ,
597+ usage : { input_tokens : 10 , output_tokens : 10 , total_tokens : 20 } ,
598+ } ,
599+ } ,
600+ ] ;
601+ response . writeHead ( 200 , { "content-type" : "text/event-stream" } ) ;
602+ for ( const event of events ) {
603+ response . write ( `data: ${ JSON . stringify ( event ) } \n\n` ) ;
604+ }
605+ response . end ( "data: [DONE]\n\n" ) ;
606+ } ) ( ) . catch ( ( error : unknown ) => {
607+ response . writeHead ( 500 ) . end ( error instanceof Error ? error . message : String ( error ) ) ;
608+ } ) ;
609+ } ) ;
610+
611+ let gateway : Awaited < ReturnType < typeof startGatewayWithClient > > | undefined ;
612+ try {
613+ await new Promise < void > ( ( resolve , reject ) => {
614+ providerServer . once ( "error" , reject ) ;
615+ providerServer . listen ( 0 , "127.0.0.1" , resolve ) ;
616+ } ) ;
617+ const providerAddress = providerServer . address ( ) ;
618+ if ( ! providerAddress || typeof providerAddress === "string" ) {
619+ throw new Error ( "mock OpenAI Responses server did not bind a loopback port" ) ;
620+ }
621+ const baseUrl = `http://127.0.0.1:${ providerAddress . port } /v1` ;
622+ const primaryModel = buildMockOpenAiResponsesProvider ( baseUrl , "gpt-primary" ) ;
623+ const oldCompactionModel = buildMockOpenAiResponsesProvider ( baseUrl , "gpt-old-summary" ) ;
624+ const newCompactionModel = buildMockOpenAiResponsesProvider ( baseUrl , "gpt-new-summary" ) ;
625+ const newSummary = "HOT_RELOAD_COMPACTION_SUMMARY" ;
626+ summaryByModel . set ( oldCompactionModel . modelId , "STALE_COMPACTION_SUMMARY" ) ;
627+ summaryByModel . set ( newCompactionModel . modelId , newSummary ) ;
628+
629+ const initialConfig = {
630+ agents : {
631+ defaults : {
632+ workspace : workspaceDir ,
633+ skipBootstrap : true ,
634+ model : { primary : primaryModel . modelRef } ,
635+ models : {
636+ [ primaryModel . modelRef ] : { params : { transport : "sse" , openaiWsWarmup : false } } ,
637+ [ oldCompactionModel . modelRef ] : {
638+ params : { transport : "sse" , openaiWsWarmup : false } ,
639+ } ,
640+ [ newCompactionModel . modelRef ] : {
641+ params : { transport : "sse" , openaiWsWarmup : false } ,
642+ } ,
643+ } ,
644+ compaction : {
645+ model : oldCompactionModel . modelRef ,
646+ maxActiveTranscriptBytes : "1mb" ,
647+ keepRecentTokens : 1 ,
648+ recentTurnsPreserve : 1 ,
649+ qualityGuard : { enabled : false } ,
650+ memoryFlush : { enabled : false } ,
651+ } ,
652+ } ,
653+ entries : { dev : { default : true } } ,
654+ } ,
655+ models : {
656+ mode : "replace" ,
657+ providers : {
658+ [ primaryModel . providerId ] : {
659+ ...primaryModel . config ,
660+ models : [ primaryModel , oldCompactionModel , newCompactionModel ] . map ( ( { config } ) => ( {
661+ ...config . models [ 0 ] ,
662+ input : [ ...config . models [ 0 ] . input ] ,
663+ } ) ) ,
664+ } ,
665+ } ,
666+ } ,
667+ gateway : { auth : { mode : "token" , token } } ,
668+ } satisfies OpenClawConfig ;
669+
670+ const configPath = await createGatewayConfigPath ( tempHome ) ;
671+ gateway = await startGatewayWithClient ( {
672+ cfg : initialConfig ,
673+ configPath,
674+ token,
675+ clientDisplayName : "vitest-compaction-hot-reload" ,
676+ } ) ;
677+ const gatewayClient = gateway . client ;
678+ const sessionKey = "agent:dev:main" ;
679+ const sessionId = nextGatewayId ( "existing-compaction-session" ) ;
680+ const scope = {
681+ agentId : "dev" ,
682+ sessionId,
683+ sessionKey,
684+ storePath : resolveStorePath ( undefined , { agentId : "dev" } ) ,
685+ } ;
686+ await upsertSessionEntry ( scope , {
687+ sessionId,
688+ updatedAt : Date . now ( ) ,
689+ compactionCount : 0 ,
690+ modelProvider : primaryModel . providerId ,
691+ model : primaryModel . modelId ,
692+ totalTokens : 20 ,
693+ totalTokensFresh : true ,
694+ } ) ;
695+ for ( let turn = 0 ; turn < 6 ; turn += 1 ) {
696+ const timestamp = Date . now ( ) + turn ;
697+ await appendTranscriptMessage ( scope , {
698+ message : {
699+ role : "user" ,
700+ content : `Historical request ${ turn } : ${ "persisted conversation " . repeat ( 24 ) } ` ,
701+ timestamp,
702+ } ,
703+ now : timestamp ,
704+ } ) ;
705+ await appendTranscriptMessage ( scope , {
706+ message : {
707+ role : "assistant" ,
708+ content : [
709+ {
710+ type : "text" ,
711+ text : `Historical answer ${ turn } : ${ "durable model context " . repeat ( 24 ) } ` ,
712+ } ,
713+ ] ,
714+ api : "openai-responses" ,
715+ provider : primaryModel . providerId ,
716+ model : primaryModel . modelId ,
717+ usage : {
718+ input : 10 ,
719+ output : 10 ,
720+ cacheRead : 0 ,
721+ cacheWrite : 0 ,
722+ totalTokens : 20 ,
723+ cost : { input : 0 , output : 0 , cacheRead : 0 , cacheWrite : 0 , total : 0 } ,
724+ } ,
725+ stopReason : "stop" ,
726+ timestamp,
727+ } ,
728+ now : timestamp ,
729+ } ) ;
730+ }
731+ expect ( loadTranscriptEventsSync ( scope ) . length ) . toBeGreaterThan ( 10 ) ;
732+
733+ const sendChatAndWait = async ( message : string ) => {
734+ const started = await gatewayClient . request < { runId : string ; status : string } > (
735+ "chat.send" ,
736+ { sessionKey, message, idempotencyKey : nextGatewayId ( "compaction-chat" ) } ,
737+ ) ;
738+ expect ( started . status ) . toBe ( "started" ) ;
739+ const completed = await gatewayClient . request < { status : string } > (
740+ "agent.wait" ,
741+ { runId : started . runId , timeoutMs : 30_000 } ,
742+ { timeoutMs : 35_000 } ,
743+ ) ;
744+ expect ( completed . status ) . toBe ( "ok" ) ;
745+ } ;
746+
747+ await sendChatAndWait ( "Warm the existing prepared model runtime." ) ;
748+ expect ( providerRequests . map ( ( { model } ) => model ) ) . toContain ( primaryModel . modelId ) ;
749+ expect ( loadSessionEntry ( scope ) ?. compactionCount ?? 0 ) . toBe ( 0 ) ;
750+
751+ await writeConfigFile ( {
752+ ...initialConfig ,
753+ agents : {
754+ ...initialConfig . agents ,
755+ defaults : {
756+ ...initialConfig . agents . defaults ,
757+ compaction : {
758+ ...initialConfig . agents . defaults . compaction ,
759+ model : newCompactionModel . modelRef ,
760+ maxActiveTranscriptBytes : "10b" ,
761+ } ,
762+ } ,
763+ } ,
764+ } ) ;
765+ await expect
766+ . poll ( ( ) => getRuntimeConfig ( ) . agents ?. defaults ?. compaction ?. model , {
767+ timeout : 5_000 ,
768+ interval : 50 ,
769+ } )
770+ . toBe ( newCompactionModel . modelRef ) ;
771+ await expect
772+ . poll ( ( ) => getRuntimeConfig ( ) . agents ?. defaults ?. compaction ?. maxActiveTranscriptBytes , {
773+ timeout : 5_000 ,
774+ interval : 50 ,
775+ } )
776+ . toBe ( "10b" ) ;
777+
778+ const requestsBeforeCompaction = providerRequests . length ;
779+ await sendChatAndWait ( "Compact the existing conversation before answering." ) ;
780+
781+ const newRequests = providerRequests . slice ( requestsBeforeCompaction ) ;
782+ expect ( newRequests . map ( ( { model } ) => model ) ) . toContain ( newCompactionModel . modelId ) ;
783+ expect ( newRequests . map ( ( { model } ) => model ) ) . not . toContain ( oldCompactionModel . modelId ) ;
784+ expect ( loadSessionEntry ( scope ) ?. compactionCount ) . toBe ( 1 ) ;
785+ expect ( loadTranscriptEventsSync ( scope ) ) . toContainEqual (
786+ expect . objectContaining ( {
787+ type : "compaction" ,
788+ summary : expect . stringContaining ( newSummary ) ,
789+ } ) ,
790+ ) ;
791+ await expect ( gatewayClient . request ( "health" , { } ) ) . resolves . toEqual ( expect . any ( Object ) ) ;
792+ } finally {
793+ if ( gateway ) {
794+ await disconnectGatewayClient ( gateway . client ) ;
795+ await gateway . server . close ( { reason : "compaction hot reload integration test complete" } ) ;
796+ }
797+ providerServer . closeAllConnections ( ) ;
798+ await new Promise < void > ( ( resolve ) => providerServer . close ( ( ) => resolve ( ) ) ) ;
799+ await removeGatewayTempHome ( tempHome ) ;
800+ envSnapshot . restore ( ) ;
801+ }
802+ } ,
803+ ) ;
804+
546805 it (
547806 "accepts a gateway agent request over ws and returns a run id" ,
548807 { timeout : GATEWAY_E2E_TIMEOUT_MS } ,
0 commit comments