π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix(agent-gateway-client): drive resume completion off authoritative DO status (#15919)
Arvin Xuc10be159c34b
diff --git a/packages/agent-gateway-client/src/client.test.ts b/packages/agent-gateway-client/src/client.test.tsindex e65143b2032..78c86c451a0 100644--- a/packages/agent-gateway-client/src/client.test.ts+++ b/packages/agent-gateway-client/src/client.test.ts@@ -159,7 +159,7 @@ describe('AgentStreamClient', () => {// First message is auth, second is resumeexpect(ws.sent).toHaveLength(2);- expect(JSON.parse(ws.sent[1])).toEqual({ lastEventId: '', type: 'resume' });+ expect(JSON.parse(ws.sent[1])).toEqual({ lastEventId: '', type: 'resume', wantStatus: true });});it('should not connect if already connected', async () => {@@ -267,7 +267,7 @@ describe('AgentStreamClient', () => {// Resume should use the tracked lastEventIdconst resumeMsg = JSON.parse(ws2.sent[1]);- expect(resumeMsg).toEqual({ lastEventId: 'evt-5', type: 'resume' });+ expect(resumeMsg).toEqual({ lastEventId: 'evt-5', type: 'resume', wantStatus: true });});it('should disconnect on agent_runtime_end', async () => {@@ -319,6 +319,109 @@ describe('AgentStreamClient', () => {});});+ // Regression guard for LOBE-10443: a fresh subscriber (no lastEventId) on a+ // hibernated DO replays zero events. The client must NOT guess "completed"+ // from silence (the old 3s timeout did, which cleared the shared+ // runningOperation and cancelled the run on every device). Completion is now+ // driven purely by the DO's authoritative `resume_complete` status.+ describe('resume_complete (authoritative status)', () => {+ async function connectAndAuthResume(client: AgentStreamClient): Promise<MockWebSocket> {+ client.connect();+ await vi.advanceTimersByTimeAsync(1);+ const ws = getLatestWs();+ ws.simulateMessage({ type: 'auth_success' });+ return ws;+ }++ it('never auto-completes from silence β no resume_complete, no events', async () => {+ const client = createClient({ resumeOnConnect: true });+ const onComplete = vi.fn();+ client.on('session_complete', onComplete);++ await connectAndAuthResume(client);+ // DO is silent (hibernated buffer, slow status). Far past the old 3s window.+ await vi.advanceTimersByTimeAsync(30_000);++ expect(onComplete).not.toHaveBeenCalled();+ expect(client.connectionStatus).toBe('connected');+ });++ it('does NOT complete when DO reports status running', async () => {+ const client = createClient({ resumeOnConnect: true });+ const onComplete = vi.fn();+ client.on('session_complete', onComplete);++ const ws = await connectAndAuthResume(client);+ // DO replayed nothing (hibernated buffer) but tells us the run is alive.+ ws.simulateMessage({ status: 'running', type: 'resume_complete' });++ await vi.advanceTimersByTimeAsync(5000);++ expect(onComplete).not.toHaveBeenCalled();+ expect(client.connectionStatus).toBe('connected');+ });++ it('still streams live events after a running resume_complete', async () => {+ const client = createClient({ resumeOnConnect: true });+ const events: any[] = [];+ client.on('agent_event', (e) => events.push(e));++ const ws = await connectAndAuthResume(client);+ ws.simulateMessage({ status: 'running', type: 'resume_complete' });++ ws.simulateMessage({+ event: {+ data: { content: 'live' },+ operationId: 'op-123',+ stepIndex: 0,+ timestamp: 1,+ type: 'stream_chunk',+ },+ id: 'evt-9',+ type: 'agent_event',+ });++ expect(events).toHaveLength(1);+ expect(events[0].data.content).toBe('live');+ });++ it('completes when DO reports a terminal status', async () => {+ const client = createClient({ resumeOnConnect: true });+ const onComplete = vi.fn();+ client.on('session_complete', onComplete);++ const ws = await connectAndAuthResume(client);+ ws.simulateMessage({ status: 'completed', type: 'resume_complete' });++ expect(onComplete).toHaveBeenCalledOnce();+ expect(client.connectionStatus).toBe('disconnected');+ });++ it('flushes replayed events before completing on a terminal status', async () => {+ const client = createClient({ resumeOnConnect: true });+ const events: any[] = [];+ const order: string[] = [];+ client.on('agent_event', (e) => {+ events.push(e);+ order.push('event');+ });+ client.on('session_complete', () => order.push('complete'));++ const ws = await connectAndAuthResume(client);+ // Buffered during resume replayβ¦+ ws.simulateMessage({+ event: { data: {}, operationId: 'op-123', stepIndex: 0, timestamp: 1, type: 'step_start' },+ id: 'evt-1',+ type: 'agent_event',+ });+ // β¦then the terminal authoritative status.+ ws.simulateMessage({ status: 'completed', type: 'resume_complete' });++ expect(events).toHaveLength(1);+ expect(order).toEqual(['event', 'complete']);+ });+ });+describe('heartbeat', () => {it('should send heartbeats at 30s intervals', async () => {const client = createClient();diff --git a/packages/agent-gateway-client/src/client.ts b/packages/agent-gateway-client/src/client.tsindex 93f49f83952..e8411134e64 100644--- a/packages/agent-gateway-client/src/client.ts+++ b/packages/agent-gateway-client/src/client.ts@@ -15,7 +15,6 @@ const INITIAL_RECONNECT_DELAY = 1000; // 1sconst MAX_RECONNECT_DELAY = 30_000; // 30sconst MAX_MISSED_HEARTBEATS = 3;const RESUME_FLUSH_DELAY = 500; // 500ms debounce after last resume event-const RESUME_TIMEOUT = 3000; // 3s: if no events after resume request, session is already done// βββ Typed Event Emitter (browser-compatible, no node:events) βββ@@ -235,24 +234,29 @@ export class AgentStreamClient extends TypedEmitter {// Enter resume mode only for explicit reconnect scenarios (page reload).// Buffer all events until resume replay completes, then deduplicate and emit.// This is NOT enabled for normal first-connect to avoid delaying live streaming.+ //+ // The replay is terminated by an authoritative `resume_complete` (the+ // DO's stored status, which survives hibernation) β that message is+ // what exits resume mode and decides completion. We deliberately do+ // NOT arm a timeout to guess completion from silence: an empty replay+ // no longer means "finished" (the DO may simply have hibernated its+ // event buffer), and guessing was exactly the LOBE-10443 multi-device+ // false-cancel bug. If `resume_complete` never arrives (e.g. a+ // rolled-back DO that predates LOBE-10443), we just keep waiting β a+ // safe, recoverable state, with heartbeat loss still forcing reconnect+ // β instead of cancelling a live run.if (this.resumeOnConnect && !this.lastEventId) {this.resumeMode = true;this.resumeBuffer = [];-- // Safety timeout: if no events arrive after resume, the session has already- // completed and the DO has nothing to replay. Exit resume mode and signal completion.- this.resumeFlushTimer = setTimeout(() => {- if (this.resumeMode && this.resumeBuffer.length === 0) {- this.resumeMode = false;- this.sessionEnded = true;- this.emit('session_complete');- this.disconnect();- }- }, RESUME_TIMEOUT);}- // Request all buffered events (covers events pushed before WS connected)- this.sendMessage({ lastEventId: this.lastEventId, type: 'resume' });+ // Request all buffered events (covers events pushed before WS connected).+ // `wantStatus` opts into the authoritative `resume_complete` reply+ // (LOBE-10443): this client knows how to consume it, so a current+ // gateway will hand back the real session status. Legacy gateways+ // ignore the flag and just replay β we then rely on live events, never+ // guessing completion from silence.+ this.sendMessage({ lastEventId: this.lastEventId, type: 'resume', wantStatus: true });this.emit('connected');break;}@@ -303,6 +307,37 @@ export class AgentStreamClient extends TypedEmitter {break;}+ case 'resume_complete': {+ // Authoritative status from the DO, sent right after resume replay+ // (LOBE-10443) β this is the definitive end-of-replay marker, so+ // cancel the pending debounce flush and act on it immediately.+ if (this.resumeFlushTimer) {+ clearTimeout(this.resumeFlushTimer);+ this.resumeFlushTimer = null;+ }++ // Emit any events buffered during resume, in order, before deciding.+ if (this.resumeMode) {+ this.flushResumeBuffer();+ }++ const terminal =+ message.status === 'completed' ||+ message.status === 'error' ||+ message.status === 'interrupted';++ if (terminal) {+ this.sessionEnded = true;+ this.emit('session_complete');+ this.disconnect();+ }+ // Non-terminal (running / waiting_input / waiting_confirmation): the+ // run is alive. Stay connected and keep streaming live events β do NOT+ // fire session_complete. This is the core fix: a fresh subscriber on a+ // hibernated DO no longer false-completes and clears runningOperation.+ break;+ }+case 'session_complete': {this.sessionEnded = true;// Flush any buffered resume events before disconnectingdiff --git a/packages/agent-gateway-client/src/types.ts b/packages/agent-gateway-client/src/types.tsindex 46ac9f44c35..3b27c6c1cc7 100644--- a/packages/agent-gateway-client/src/types.ts+++ b/packages/agent-gateway-client/src/types.ts@@ -162,6 +162,12 @@ export interface AuthMessage {export interface ResumeMessage {lastEventId: string;type: 'resume';+ /**+ * Opt into the authoritative `resume_complete` reply (LOBE-10443). Set by+ * this client so a current gateway hands back the stored session status;+ * legacy gateways ignore it and replay only.+ */+ wantStatus?: boolean;}export interface HeartbeatMessage {@@ -229,12 +235,37 @@ export interface SessionCompleteMessage {type: 'session_complete';}+/**+ * Authoritative session status. Mirrors the gateway DO's `SessionStatus`.+ */+export type SessionStatus =+ | 'running'+ | 'waiting_input'+ | 'waiting_confirmation'+ | 'completed'+ | 'error'+ | 'interrupted';++/**+ * Server β Client: sent right after a `resume` replay, carrying the DO's+ * authoritative `status` from storage. Because the DO's in-memory event buffer+ * is wiped by hibernation, an empty replay is ambiguous β the run may still be+ * alive. This message resolves that ambiguity so the client never guesses+ * "completed" from silence (which would clear the shared `runningOperation` and+ * cancel the run on every device). See LOBE-10443.+ */+export interface ResumeCompleteMessage {+ status: SessionStatus;+ type: 'resume_complete';+}+export type ServerMessage =| AgentEventMessage| AuthExpiredMessage| AuthFailedMessage| AuthSuccessMessage| HeartbeatAckMessage+ | ResumeCompleteMessage| SessionCompleteMessage;// βββ Connection Status βββ