@@ -85,28 +85,49 @@ export async function readOutput(args: unknown): Promise<ServerResult> {
8585 let timeoutReached = false ;
8686 try {
8787 // Create a promise that resolves when new output is available or when timeout is reached
88- const outputPromise :Promise < string > = new Promise < string > ( ( resolve ) => {
88+ const outputPromise : Promise < string > = new Promise < string > ( ( resolve ) => {
8989 // Check for initial output
9090 const initialOutput = terminalManager . getNewOutput ( pid ) ;
9191 if ( initialOutput && initialOutput . length > 0 ) {
9292 resolve ( initialOutput ) ;
9393 return ;
9494 }
9595
96+ let resolved = false ;
97+ let interval : NodeJS . Timeout | null = null ;
98+ let timeout : NodeJS . Timeout | null = null ;
99+
100+ const cleanup = ( ) => {
101+ if ( interval ) {
102+ clearInterval ( interval ) ;
103+ interval = null ;
104+ }
105+ if ( timeout ) {
106+ clearTimeout ( timeout ) ;
107+ timeout = null ;
108+ }
109+ } ;
110+
111+ const resolveOnce = ( value : string , isTimeout = false ) => {
112+ if ( resolved ) return ;
113+ resolved = true ;
114+ cleanup ( ) ;
115+ if ( isTimeout ) timeoutReached = true ;
116+ resolve ( value ) ;
117+ } ;
118+
96119 // Setup an interval to poll for output
97- const interval = setInterval ( ( ) => {
120+ interval = setInterval ( ( ) => {
98121 const newOutput = terminalManager . getNewOutput ( pid ) ;
99122 if ( newOutput && newOutput . length > 0 ) {
100- clearInterval ( interval ) ;
101- resolve ( newOutput ) ;
123+ resolveOnce ( newOutput ) ;
102124 }
103125 } , 300 ) ; // Check every 300ms
104126
105- // Set a timeout to stop waiting
106- setTimeout ( ( ) => {
107- clearInterval ( interval ) ;
108- timeoutReached = true ;
109- resolve ( terminalManager . getNewOutput ( pid ) || "" ) ;
127+ // Set a timeout to stop waiting
128+ timeout = setTimeout ( ( ) => {
129+ const finalOutput = terminalManager . getNewOutput ( pid ) || "" ;
130+ resolveOnce ( finalOutput , true ) ;
110131 } , timeout_ms ) ;
111132 } ) ;
112133
0 commit comments