@@ -4,15 +4,23 @@ import type { ILogger } from "channel.base";
44import { AgentServerMessageType , type AgentServerMessage } from "./protocol" ;
55import { RemoteAgentConnection } from "./RemoteAgentConnection" ;
66
7+ /**
8+ * 一轮 chat 允许多久没有任何事件。会话把消息投进队列就返回,正常收尾靠 done 事件;
9+ * 消息被意图过滤或消息合并吞掉时永远等不到 done,没有兜底连接会一直挂着,客户端也一直在等。
10+ */
11+ const IDLE_TIMEOUT_MS = 30 * 60_000 ;
12+
713/** One long-lived HTTP chat response, streamed to the client as SSE. */
814export class RemoteHttpAgentConnection extends RemoteAgentConnection {
915 readonly requestId = randomUUID ( ) ;
1016 private closed = false ;
17+ private idleTimer ?: ReturnType < typeof setTimeout > ;
1118
1219 constructor ( private readonly response : ServerResponse , logger ?: ILogger ) {
1320 super ( logger ) ;
1421 response . on ( "close" , ( ) => {
1522 this . closed = true ;
23+ clearTimeout ( this . idleTimer ) ;
1624 this . failAllPending ( "外部客户端连接已关闭" ) ;
1725 } ) ;
1826 }
@@ -34,12 +42,26 @@ export class RemoteHttpAgentConnection extends RemoteAgentConnection {
3442 close ( ) : void {
3543 if ( ! this . alive ) return ;
3644 this . closed = true ;
45+ clearTimeout ( this . idleTimer ) ;
3746 this . failAllPending ( "外部客户端连接已关闭" ) ;
3847 this . response . end ( ) ;
3948 }
4049
4150 protected send ( message : AgentServerMessage ) : void {
4251 this . response . write ( `event: ${ message . type } \ndata: ${ JSON . stringify ( message . data ?? { } ) } \n\n` ) ;
43- if ( message . type === AgentServerMessageType . Done ) this . close ( ) ;
52+ // done 和 error 都算本轮收尾:请求校验失败只发 error,没有后续的 done。
53+ if ( message . type === AgentServerMessageType . Done || message . type === AgentServerMessageType . Error ) {
54+ return this . close ( ) ;
55+ }
56+ this . resetIdleTimer ( ) ;
57+ }
58+
59+ /** 每发出一个事件就重新计时;超时说明本轮已经没人推进了,给客户端一个 error 再收尾。 */
60+ private resetIdleTimer ( ) : void {
61+ clearTimeout ( this . idleTimer ) ;
62+ this . idleTimer = setTimeout ( ( ) => {
63+ this . logger ?. warn ( `Remote-agent HTTP chat idle for ${ IDLE_TIMEOUT_MS / 60_000 } minutes, closing requestId=${ this . requestId } ` ) ;
64+ this . emit ( AgentServerMessageType . Error , { message : "本轮处理长时间没有进展,连接已关闭" } ) ;
65+ } , IDLE_TIMEOUT_MS ) ;
4466 }
4567}
0 commit comments