Skip to content

🀯 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.

πŸ› fix(gateway): retire a run whose stream ends without its terminal frame (#20550)

Arvin Xuf14a4be04737
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/gateway.mux.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/gateway.mux.test.ts
index 1e4e3f0bc4d..185c770e14b 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/gateway.mux.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/gateway.mux.test.ts
@@ -33,6 +33,7 @@ vi.mock('@/services/message', () => ({
vi.mock('@/services/topic', () => ({
topicService: {
+ getTopicDetail: vi.fn().mockResolvedValue(null),
settleRunningOperation: vi.fn().mockResolvedValue(undefined),
updateTopicMetadata: vi.fn().mockResolvedValue(undefined),
},
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts
index f3df7252797..75f173c40a5 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts
@@ -31,6 +31,7 @@ vi.mock('@/services/aiAgent', () => ({
vi.mock('@/services/shareChat', () => ({
shareChatService: {
execAgentTask: vi.fn(),
+ getTopics: vi.fn().mockResolvedValue([]),
interruptTask: vi.fn(),
refreshGatewayToken: vi.fn(),
},
@@ -44,6 +45,9 @@ vi.mock('@/services/message', () => ({
vi.mock('@/services/topic', () => ({
topicService: {
+ // Defaults to "no detail readable" so the silent-end reconcile stays
+ // fail-safe unless a test opts in by returning a row.
+ getTopicDetail: vi.fn().mockResolvedValue(null),
settleRunningOperation: vi.fn().mockResolvedValue(undefined),
updateTopicMetadata: vi.fn().mockResolvedValue(undefined),
},
@@ -186,6 +190,7 @@ function createTestAction() {
describe('GatewayActionImpl', () => {
beforeEach(() => {
moveChatContextSelections.mockClear();
+ vi.mocked(topicService.getTopicDetail).mockResolvedValue(null as never);
vi.mocked(topicService.settleRunningOperation).mockResolvedValue(undefined as never);
mockAgentStore.state = { activeAgentId: undefined, agentMap: {} };
mockUserDefaultConfig.disableGatewayMode = undefined;
@@ -360,6 +365,283 @@ describe('GatewayActionImpl', () => {
expect(state.gatewayConnections['op-1']).toBeUndefined();
});
+ // A socket that ends without the op's terminal frame is the one end the
+ // transport cannot read: the run may still be alive (a drop that will
+ // reconnect) or already over with its terminal lost. Completing the op
+ // unconditionally would settle live runs; doing nothing left the local
+ // operation stuck `running` forever. So the transport defers to the caller.
+ describe('silent end (disconnected without a terminal frame)', () => {
+ it('leaves the op running while the caller reports the run still alive', async () => {
+ const { action, mockClient } = createTestAction();
+ const onComplete = vi.fn();
+ const onSilentEnd = vi.fn(() => false);
+
+ action.connectToGateway({
+ gatewayUrl: 'https://gateway.test.com',
+ onSessionComplete: onComplete,
+ onSilentEnd,
+ operationId: 'op-1',
+ token: 'test-token',
+ topicId: TEST_TOPIC_ID,
+ });
+
+ mockClient.emitEvent('disconnected');
+ await vi.waitFor(() => expect(onSilentEnd).toHaveBeenCalledOnce());
+
+ expect(onComplete).not.toHaveBeenCalled();
+ });
+
+ it('fires the terminal-missing onSessionComplete once the caller proves the run is over', async () => {
+ const { action, mockClient } = createTestAction();
+ const onComplete = vi.fn();
+
+ action.connectToGateway({
+ gatewayUrl: 'https://gateway.test.com',
+ onSessionComplete: onComplete,
+ onSilentEnd: () => true,
+ operationId: 'op-1',
+ token: 'test-token',
+ topicId: TEST_TOPIC_ID,
+ });
+
+ mockClient.emitEvent('disconnected');
+
+ await vi.waitFor(() =>
+ expect(onComplete).toHaveBeenCalledWith({
+ authFailed: false,
+ completion: undefined,
+ succeeded: false,
+ terminalReceived: false,
+ }),
+ );
+ });
+
+ it('keeps waiting when the reconcile itself fails', async () => {
+ const { action, mockClient } = createTestAction();
+ const onComplete = vi.fn();
+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const onSilentEnd = vi.fn(() => {
+ throw new Error('read failed');
+ });
+
+ action.connectToGateway({
+ gatewayUrl: 'https://gateway.test.com',
+ onSessionComplete: onComplete,
+ onSilentEnd,
+ operationId: 'op-1',
+ token: 'test-token',
+ topicId: TEST_TOPIC_ID,
+ });
+
+ mockClient.emitEvent('disconnected');
+ await vi.waitFor(() => expect(consoleError).toHaveBeenCalled());
+
+ expect(onComplete).not.toHaveBeenCalled();
+ });
+
+ it('skips the reconcile when the terminal frame already arrived', () => {
+ const { action, mockClient } = createTestAction();
+ const onComplete = vi.fn();
+ const onSilentEnd = vi.fn(() => true);
+
+ action.connectToGateway({
+ gatewayUrl: 'https://gateway.test.com',
+ onSessionComplete: onComplete,
+ onSilentEnd,
+ operationId: 'op-1',
+ token: 'test-token',
+ topicId: TEST_TOPIC_ID,
+ });
+
+ mockClient.emitEvent('agent_event', {
+ data: { reason: 'done' },
+ operationId: 'op-1',
+ stepIndex: 0,
+ timestamp: Date.now(),
+ type: 'agent_runtime_end',
+ } satisfies AgentStreamEvent);
+ mockClient.emitEvent('disconnected');
+
+ expect(onSilentEnd).not.toHaveBeenCalled();
+ expect(onComplete).toHaveBeenCalledWith(
+ expect.objectContaining({ terminalReceived: true }),
+ );
+ });
+
+ // A per-op `disconnected` follows terminal completion, auth failure or an
+ // explicit unsubscribe β€” never an unintentional socket loss. v1 takes its
+ // `reconnecting` branch on a close and the mux only broadcasts a per-op
+ // `reconnecting` / `status_changed` while it backs off, so hooking
+ // `disconnected` alone left the reconcile unreachable for every case the
+ // fix targets: the local op stayed `running` forever.
+ it('reconciles on the `reconnecting` signal an unintentional socket loss emits', async () => {
+ const { action, mockClient, state } = createTestAction();
+ const onComplete = vi.fn();
+ const onEvent = vi.fn();
+ const onSilentEnd = vi.fn(() => true);
+
+ action.connectToGateway({
+ gatewayUrl: 'https://gateway.test.com',
+ onEvent,
+ onSessionComplete: onComplete,
+ onSilentEnd,
+ operationId: 'op-1',
+ token: 'test-token',
+ topicId: TEST_TOPIC_ID,
+ });
+
+ mockClient.emitEvent('reconnecting', 1000);
+
+ await vi.waitFor(() => expect(onSilentEnd).toHaveBeenCalledOnce());
+ await vi.waitFor(() =>
+ expect(onComplete).toHaveBeenCalledWith(
+ expect.objectContaining({ succeeded: false, terminalReceived: false }),
+ ),
+ );
+
+ // The missed terminal is the path that applies the run's final state, so
+ // the retire must ask the handler to re-read the DB β€” otherwise the last
+ // text/tool state stays stale, and the teardown below cancels the reconnect
+ // that could have replayed it.
+ expect(onEvent).toHaveBeenCalledWith(
+ expect.objectContaining({ data: { reason: 'silent_end' }, type: 'notify_update' }),
+ );
+
+ // A retired run must not leave its transport running: dropping the store
+ // handle alone leaves a v1 reconnect timer opening sockets and a mux
+ // operation subscribed for a run nobody will ever read.
+ await vi.waitFor(() => expect(mockClient.disconnect).toHaveBeenCalled());
+ expect(state.gatewayConnections['op-1']).toBeUndefined();
+ });
+
+ it('reconciles when the mux broadcasts a per-op status_changed(disconnected)', async () => {
+ const { action, mockClient } = createTestAction();
+ const onSilentEnd = vi.fn(() => false);
+
+ action.connectToGateway({
+ gatewayUrl: 'https://gateway.test.com',
+ onSessionComplete: vi.fn(),
+ onSilentEnd,
+ operationId: 'op-1',
+ token: 'test-token',
+ topicId: TEST_TOPIC_ID,
+ });
+
+ // A redial in progress is not yet the end.
+ mockClient.emitEvent('status_changed', 'reconnecting');
+ expect(onSilentEnd).not.toHaveBeenCalled();
+ expect(mockClient.disconnect).not.toHaveBeenCalled();
+
+ mockClient.emitEvent('status_changed', 'disconnected');
+ await vi.waitFor(() => expect(onSilentEnd).toHaveBeenCalledOnce());
+ // The caller answered "still running", so the transport stays up.
+ expect(mockClient.disconnect).not.toHaveBeenCalled();
+ });
+
+ it('stops reconciling once the run has been retired', async () => {
+ const { action, mockClient } = createTestAction();
+ const onSilentEnd = vi.fn(() => true);
+
+ action.connectToGateway({
+ gatewayUrl: 'https://gateway.test.com',
+ onSessionComplete: vi.fn(),
+ onSilentEnd,
+ operationId: 'op-1',
+ token: 'test-token',
+ topicId: TEST_TOPIC_ID,
+ });
+
+ mockClient.emitEvent('reconnecting', 1000);
+ await vi.waitFor(() => expect(onSilentEnd).toHaveBeenCalledOnce());
+
+ mockClient.emitEvent('reconnecting', 2000);
+ await new Promise((resolve) => setTimeout(resolve, 0));
+
+ expect(onSilentEnd).toHaveBeenCalledOnce();
+ });
+
+ // A loss-time read can fail outright (offline while the dial backs off), and
+ // the dial that then succeeds emits no further loss signal β€” so nothing else
+ // would ever re-check and the op would stay `running`.
+ it('re-checks once the transport reconnects after a "not over" answer', async () => {
+ const { action, mockClient } = createTestAction();
+ const onComplete = vi.fn();
+ const onSilentEnd = vi.fn().mockResolvedValueOnce(false).mockResolvedValueOnce(true);
+
+ action.connectToGateway({
+ gatewayUrl: 'https://gateway.test.com',
+ onSessionComplete: onComplete,
+ onSilentEnd,
+ operationId: 'op-1',
+ token: 'test-token',
+ topicId: TEST_TOPIC_ID,
+ });
+
+ mockClient.emitEvent('reconnecting', 1000);
+ await vi.waitFor(() => expect(onSilentEnd).toHaveBeenCalledTimes(1));
+
+ mockClient.emitEvent('connected');
+ await vi.waitFor(() => expect(onSilentEnd).toHaveBeenCalledTimes(2));
+ await vi.waitFor(() =>
+ expect(onComplete).toHaveBeenCalledWith(
+ expect.objectContaining({ terminalReceived: false }),
+ ),
+ );
+ });
+
+ it('does not read the topic on a plain initial connect', async () => {
+ const { action, mockClient } = createTestAction();
+ const onSilentEnd = vi.fn(() => false);
+
+ action.connectToGateway({
+ gatewayUrl: 'https://gateway.test.com',
+ onSessionComplete: vi.fn(),
+ onSilentEnd,
+ operationId: 'op-1',
+ token: 'test-token',
+ topicId: TEST_TOPIC_ID,
+ });
+
+ mockClient.emitEvent('connected');
+ await new Promise((resolve) => setTimeout(resolve, 0));
+
+ expect(onSilentEnd).not.toHaveBeenCalled();
+ });
+
+ it('leaves a replacement transport alone when a stale reconcile resolves', async () => {
+ const { action, mockClient, set, state } = createTestAction();
+ let resolveRunOver: ((value: boolean) => void) | undefined;
+ const onSilentEnd = vi.fn(
+ () =>
+ new Promise<boolean>((resolve) => {
+ resolveRunOver = resolve;
+ }),
+ );
+
+ action.connectToGateway({
+ gatewayUrl: 'https://gateway.test.com',
+ onSessionComplete: vi.fn(),
+ onSilentEnd,
+ operationId: 'op-1',
+ token: 'test-token',
+ topicId: TEST_TOPIC_ID,
+ });
+
+ mockClient.emitEvent('reconnecting', 1000);
+ await vi.waitFor(() => expect(onSilentEnd).toHaveBeenCalledOnce());
+
+ // The mux β†’ v1 fallback re-enters `connectToGateway` under the SAME
+ // operation id while this read is still in flight.
+ const replacement = createMockClient();
+ set({ gatewayConnections: { 'op-1': { client: replacement, status: 'connecting' } } });
+
+ resolveRunOver!(true);
+ await vi.waitFor(() => expect(mockClient.disconnect).toHaveBeenCalled());
+
+ expect(state.gatewayConnections['op-1']?.client).toBe(replacement);
+ });
+ });
+
it('should cleanup on auth_failed', () => {
const { action, mockClient, state } = createTestAction();
@@ -3474,6 +3756,10 @@ describe('GatewayActionImpl', () => {
return { action, connectToGateway, getCancelHandler: () => cancelHandler, startOperation };
}
+ beforeEach(() => {
+ vi.mocked(shareChatService.getTopics).mockReset().mockResolvedValue([]);
+ });
+
afterEach(() => {
delete (globalThis as any).window;
});
@@ -3540,6 +3826,68 @@ describe('GatewayActionImpl', () => {
);
expect(aiAgentService.interruptTask).not.toHaveBeenCalled();
});
+
+ // The silent-end reconcile must read the topic through the share surface
+ // too: `topic.getTopicDetail` resolves with `findOwnTopicById`, so a
+ // visitor's read cannot see the creator-owned row and the reconcile would
+ // always answer "still running" β€” leaving a terminal-less share run stuck
+ // exactly like the owner path this fix repairs.
+ async function runSilentEnd(action: GatewayActionImpl, connectToGateway: any) {
+ await action.reconnectToGatewayOperation({
+ agentShareId: 'share-1',
+ assistantMessageId: 'ast-1',
+ heteroType: null,
+ operationId: 'server-op-1',
+ topicId: 'topic-1',
+ });
+
+ return connectToGateway.mock.calls[0]![0].onSilentEnd as () => Promise<boolean>;
+ }
+
+ it('reads the visitor topic through the share-authorized list, not the owner-scoped read', async () => {
+ const { action, connectToGateway } = createShareReconnectTestAction({
+ createdAt: 1,
+ id: 'ast-1',
+ });
+ vi.mocked(topicService.getTopicDetail).mockClear();
+ vi.mocked(shareChatService.getTopics).mockResolvedValue([
+ { id: 'topic-1', runningOperation: null },
+ ] as any);
+
+ const onSilentEnd = await runSilentEnd(action, connectToGateway);
+
+ await expect(onSilentEnd()).resolves.toBe(true);
+ expect(shareChatService.getTopics).toHaveBeenCalledWith('share-1');
+ expect(topicService.getTopicDetail).not.toHaveBeenCalled();
+ });
+
+ it('keeps waiting while the share projection still names a run on the topic', async () => {
+ const { action, connectToGateway } = createShareReconnectTestAction({
+ createdAt: 1,
+ id: 'ast-1',
+ });
+ vi.mocked(shareChatService.getTopics).mockResolvedValue([
+ { id: 'topic-1', runningOperation: { operationId: 'server-op-1' } },
+ ] as any);
+
+ const onSilentEnd = await runSilentEnd(action, connectToGateway);
+
+ await expect(onSilentEnd()).resolves.toBe(false);
+ });
+
+ it('keeps waiting when the share read itself fails', async () => {
+ const { action, connectToGateway } = createShareReconnectTestAction({
+ createdAt: 1,
+ id: 'ast-1',
+ });
+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
+ vi.mocked(shareChatService.getTopics).mockRejectedValue(new Error('offline'));
+
+ const onSilentEnd = await runSilentEnd(action, connectToGateway);
+
+ await expect(onSilentEnd()).resolves.toBe(false);
+ expect(consoleError).toHaveBeenCalled();
+ });
});
// Captures the onSessionComplete handed to connectToGateway so we can drive
@@ -3839,9 +4187,13 @@ describe('GatewayActionImpl', () => {
// internal_dispatchTopic + connectToGateway capture, so we can assert the local
// store clear on both the NOT_FOUND refresh path and onSessionComplete.
function createSeededReconnectHarness() {
- const captured: { onSessionComplete?: (p: any) => void } = {};
+ const captured: {
+ onSessionComplete?: (p: any) => void;
+ onSilentEnd?: () => boolean | Promise<boolean>;
+ } = {};
const connectToGateway = vi.fn((params: any) => {
captured.onSessionComplete = params.onSessionComplete;
+ captured.onSilentEnd = params.onSilentEnd;
});
const internalDispatchTopic = vi.fn();
const completeOperation = vi.fn();
@@ -3899,6 +4251,7 @@ describe('GatewayActionImpl', () => {
connectToGateway,
internalDispatchTopic,
startOperation,
+ state,
};
}
@@ -4044,5 +4397,181 @@ describe('GatewayActionImpl', () => {
expect(internalDispatchTopic).not.toHaveBeenCalled();
});
+
+ // ─── Silent-end reconcile ───
+ //
+ // `disconnected` without the run's terminal frame is the one end the
+ // transport cannot read. These pin the decision the reconnect hands back:
+ // retire the op only when the server's own reservation of the topic proves
+ // the run is over, and otherwise keep waiting (never guess from silence).
+ describe('silent-end reconcile', () => {
+ const readSilentEnd = (captured: { onSilentEnd?: any }) => captured.onSilentEnd!();
+
+ it('reports the run over once the server no longer reserves the topic for it', async () => {
+ const { action, captured } = createSeededReconnectHarness();
+ vi.mocked(topicService.getTopicDetail).mockResolvedValue({
+ id: 'topic-1',
+ metadata: { runningOperation: null },
+ } as never);
+
+ await action.reconnectToGatewayOperation({
+ assistantMessageId: 'ast-1',
+ heteroType: null,
+ operationId: 'server-op-1',
+ topicId: 'topic-1',
+ });
+
+ await expect(readSilentEnd(captured)).resolves.toBe(true);
+ });
+
+ it('keeps the run alive while the server still reserves the topic for it', async () => {
+ const { action, captured } = createSeededReconnectHarness();
+ vi.mocked(topicService.getTopicDetail).mockResolvedValue({
+ id: 'topic-1',
+ metadata: {
+ runningOperation: { assistantMessageId: 'ast-1', operationId: 'server-op-1' },
+ },
+ } as never);
+
+ await action.reconnectToGatewayOperation({
+ assistantMessageId: 'ast-1',
+ heteroType: null,
+ operationId: 'server-op-1',
+ topicId: 'topic-1',
+ });
+
+ await expect(readSilentEnd(captured)).resolves.toBe(false);
+ });
+
+ // A newer run replacing the marker means THIS run no longer owns the topic β€”
+ // it is over, and its spinner must not outlive the newer run's.
+ it('reports the run over once a newer operation owns the topic', async () => {
+ const { action, captured } = createSeededReconnectHarness();
+ vi.mocked(topicService.getTopicDetail).mockResolvedValue({
+ id: 'topic-1',
+ metadata: {
+ runningOperation: { assistantMessageId: 'ast-2', operationId: 'server-op-2' },
+ },
+ } as never);
+
+ await action.reconnectToGatewayOperation({
+ assistantMessageId: 'ast-1',
+ heteroType: null,
+ operationId: 'server-op-1',
+ topicId: 'topic-1',
+ });
+
+ await expect(readSilentEnd(captured)).resolves.toBe(true);
+ });
+
+ // Regression: this branch used to return early whenever a newer turn in the
+ // same tab owned the topic, skipping the authoritative read β€” and the
+ // transport is torn down right after, so no later loss signal ever retried
+ // and the superseded operation stayed locally `running` forever. The
+ // completion path is ownership-guarded, so the read must still run.
+ it('still reads the server row when a newer local turn owns the topic', async () => {
+ const { action, captured, state } = createSeededReconnectHarness();
+ state.operations = {
+ 'op-newer': {
+ context: { topicId: 'topic-1' },
+ metadata: {},
+ status: 'running',
+ type: 'execServerAgentRuntime',
+ },
+ };
+ state.operationsByType = { execServerAgentRuntime: ['op-newer'] };
+ vi.mocked(topicService.getTopicDetail).mockResolvedValue({
+ id: 'topic-1',
+ metadata: {
+ runningOperation: { assistantMessageId: 'ast-2', operationId: 'server-op-2' },
+ },
+ } as never);
+
+ await action.reconnectToGatewayOperation({
+ assistantMessageId: 'ast-1',
+ heteroType: null,
+ operationId: 'server-op-1',
+ topicId: 'topic-1',
+ });
+
+ await expect(readSilentEnd(captured)).resolves.toBe(true);
+ });
+
+ it('keeps waiting when the topic read fails', async () => {
+ const { action, captured } = createSeededReconnectHarness();
+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
+ vi.mocked(topicService.getTopicDetail).mockRejectedValueOnce(new Error('network down'));
+
+ await action.reconnectToGatewayOperation({
+ assistantMessageId: 'ast-1',
+ heteroType: null,
+ operationId: 'server-op-1',
+ topicId: 'topic-1',
+ });
+
+ await expect(readSilentEnd(captured)).resolves.toBe(false);
+ expect(consoleError).toHaveBeenCalled();
+ });
+
+ // An external hetero producer's output never travelled over this socket, so
+ // no transport observation can prove it stopped β€” same guard as the
+ // terminal path, and it must not even read the topic.
+ it('never reconciles a heterogeneous producer', async () => {
+ const { action, captured } = createSeededReconnectHarness();
+
+ await action.reconnectToGatewayOperation({
+ assistantMessageId: 'ast-1',
+ heteroType: 'claude-code',
+ operationId: 'server-op-1',
+ topicId: 'topic-1',
+ });
+
+ await expect(readSilentEnd(captured)).resolves.toBe(false);
+ expect(topicService.getTopicDetail).not.toHaveBeenCalled();
+ });
+
+ // An older server that omits `heteroType` cannot be told apart from a hetero
+ // producer, so the rolling-deploy fallback stays fail-safe.
+ it('keeps waiting when the marker omits heteroType', async () => {
+ const { action, captured } = createSeededReconnectHarness();
+ vi.mocked(topicService.getTopicDetail).mockResolvedValue({
+ id: 'topic-1',
+ metadata: { runningOperation: null },
+ } as never);
+
+ await action.reconnectToGatewayOperation({
+ assistantMessageId: 'ast-1',
+ operationId: 'server-op-1',
+ topicId: 'topic-1',
+ });
+
+ await expect(readSilentEnd(captured)).resolves.toBe(false);
+ expect(topicService.getTopicDetail).not.toHaveBeenCalled();
+ });
+
+ // A member continuation rides the supervisor's root marker instead of owning
+ // one, so a root marker naming another op is not proof that this member ended.
+ it('keeps the run alive while the supervisor still lists it as a child operation', async () => {
+ const { action, captured } = createSeededReconnectHarness();
+ vi.mocked(topicService.getTopicDetail).mockResolvedValue({
+ id: 'topic-1',
+ metadata: {
+ runningOperation: {
+ childOperations: [{ operationId: 'server-op-1' }],
+ operationId: 'server-op-root',
+ },
+ },
+ } as never);
+
+ await action.reconnectToGatewayOperation({
+ assistantMessageId: 'ast-1',
+ heteroType: null,
+ operationId: 'server-op-1',
+ topicId: 'topic-1',
+ });
+
+ await expect(readSilentEnd(captured)).resolves.toBe(false);
+ });
+ });
});
});
diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
index 8194845a3c3..9dfcd9773be 100644
--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
@@ -292,6 +292,26 @@ export interface ConnectGatewayParams {
succeeded: boolean;
terminalReceived: boolean;
}) => void;
+ /**
+ * Called when this operation's subscription ends WITHOUT its terminal frame
+ * ("silent end") β€” the socket dropped and will not redial, the DO's event
+ * buffer hibernated away, or a resumed op never replied with a status. The
+ * transport cannot tell that apart from a transient drop that will reconnect
+ * and finish, so it defers to the caller, which reconciles against the server's
+ * own reservation of the topic.
+ *
+ * Return `true` once the run is provably over: the transport then fires the
+ * terminal-missing `onSessionComplete`, so the op, the input state and the
+ * topic row settle through the one shared path. Return `false` (or omit the
+ * callback) to keep waiting β€” a reconnect or a later terminal frame will finish
+ * the run.
+ *
+ * A run retired this way settles as a NON-clean completion, exactly like the
+ * `auth_failed` close: without the terminal frame its outcome is unknown, so
+ * the topic is retired to `active` rather than `unread`. Losing a possible
+ * unread mark is the accepted price for never leaving the op stuck `running`.
+ */
+ onSilentEnd?: () => boolean | Promise<boolean>;
/**
* The operation ID returned by execAgent
*/
@@ -503,6 +523,7 @@ export class GatewayActionImpl {
lastEventId,
onEvent,
onSessionComplete,
+ onSilentEnd,
resumeOnConnect,
} = params;
@@ -658,15 +679,122 @@ export class GatewayActionImpl {
fireSessionComplete({ completion });
});
- // Handle disconnection β€” only fire session complete if a terminal agent event
- // was received (agent_runtime_end / error). Explicit disconnect() and other
- // non-terminal disconnects should NOT trigger onSessionComplete.
+ // Guards overlapping reconciles for a single teardown (a v1 socket can emit
+ // `disconnected` twice for one close). Cleared once the reconcile settles, so
+ // a silent end after a redial reconciles again.
+ let silentEndReconciling = false;
+ // Set when a reconcile answered "not over" β€” the read may simply have failed,
+ // or outrun the server's own settlement. See the `connected` hook below.
+ let silentEndRetryArmed = false;
+
+ // Drop the store's handle for this operation, but only while it still belongs
+ // to THIS client. Re-entering `connectToGateway` (the mux β†’ v1 fallback)
+ // installs a replacement under the same operation id while this connection's
+ // teardown is still in flight, and an id-only cleanup would delete the
+ // replacement's handle while its transport stays alive and untracked.
+ const cleanupOwnConnection = (): void => {
+ if (this.#get().gatewayConnections[operationId]?.client !== client) return;
+ this.internal_cleanupGatewayConnection(operationId);
+ };
+
+ // Reconcile a stream that ended without the run's terminal frame.
+ //
+ // A terminal agent event has already told the shared run lifecycle to complete
+ // the op, and a session we already fired for has nothing left to settle β€” both
+ // bail. Otherwise the transport cannot read the end: the socket may merely have
+ // dropped (a reconnect finishes the run), or the run may already be over with
+ // its terminal lost (a hibernated DO buffer, a resumed op that never replied
+ // with its status). Guessing "over" here would settle live runs, and treating
+ // it as "still running" left the local operation stuck `running` forever β€” the
+ // input stop button never cleared and the status tray kept counting, with
+ // nothing on the server able to repair it because its own marker was already
+ // gone. So defer to the caller, which reads the server's reservation of the
+ // topic and retires the run only once the server proves it ended, through the
+ // terminal-missing `onSessionComplete`.
+ //
+ // Retiring also tears the transport down, in the same order
+ // `disconnectFromGateway` uses: `internal_cleanupGatewayConnection` only drops
+ // store state, so without the `disconnect()` the discarded handle left a v1
+ // reconnect timer opening sockets and a mux operation still subscribed for a
+ // run nobody will ever read. It also keeps a finished run from reading as
+ // `connecting`/`reconnecting` β€” `reconnectToGatewayOperation` skips any status
+ // other than `disconnected`. Completion is fired first so the `disconnected`
+ // the teardown provokes is a no-op.
+ const reconcileSilentEnd = (): void => {
+ if (receivedTerminalEvent || sessionCompleted) return;
+ if (!onSilentEnd || silentEndReconciling) return;
+ silentEndReconciling = true;
+ void Promise.resolve()
+ .then(() => onSilentEnd())
+ .then((runOver) => {
+ if (!runOver) {
+ silentEndRetryArmed = true;
+ return;
+ }
+ silentEndRetryArmed = false;
+ // The terminal event is the path that applies the run's canonical final
+ // state β€” its `uiMessages` snapshot, or a refetch β€” while the
+ // terminal-missing completion only closes the op and settles the topic.
+ // Retiring without it leaves the last text/tool state stale or absent,
+ // and tearing the transport down cancels the reconnect that could have
+ // replayed it. Ride the `notify_update` path the gapped resume already
+ // uses: the DB is the complete record, and the synthetic event lands in
+ // the handler's sequential queue under its snapshot-generation guard.
+ eventBuffer.push({
+ data: { reason: 'silent_end' },
+ operationId,
+ stepIndex: 0,
+ timestamp: Date.now(),
+ type: 'notify_update',
+ });
+ fireSessionComplete();
+ client.disconnect();
+ cleanupOwnConnection();
+ })
+ .catch((error) => {
+ console.error('[Gateway] Silent-end reconcile failed:', error);
+ })
+ .finally(() => {
+ silentEndReconciling = false;
+ });
+ };
+
+ // Handle disconnection. A terminal agent event has already told the shared run
+ // lifecycle to complete the op, so the close is pure cleanup.
// (auth_failed is handled separately below β€” it's also session-terminal.)
client.on('disconnected', () => {
- this.internal_cleanupGatewayConnection(operationId);
+ cleanupOwnConnection();
if (receivedTerminalEvent) {
fireSessionComplete();
+ return;
}
+ reconcileSilentEnd();
+ });
+
+ // A loss-time read can fail outright β€” the tab is offline while the dial is
+ // still backing off β€” and a socket that then reconnects emits no further loss
+ // signal, so nothing else would re-check. `useGatewayReconnect` cannot rescue
+ // it either: its SWR fetcher already resolved and reconnect revalidation is
+ // off. Re-check once the transport is back, for the runs whose loss-time
+ // answer was "not over".
+ client.on('connected', () => {
+ if (!silentEndRetryArmed) return;
+ reconcileSilentEnd();
+ });
+
+ // `disconnected` is NOT the signal an unintentional loss produces, so hooking
+ // it alone left the reconcile unreachable for the very cases it targets:
+ // v1 takes its `reconnecting` branch on a socket close
+ // (`packages/agent-gateway-client/src/client.ts`), and the mux only broadcasts
+ // a per-op `status_changed` / `reconnecting` while it backs off
+ // (`packages/agent-gateway-client/src/mux/GatewayMuxClient.ts`). A per-op
+ // `disconnected` instead follows terminal completion, auth failure or an
+ // explicit unsubscribe. Ride the loss signals the transports actually emit;
+ // the backoff retries re-check, so a drop that reconnects reads a row still
+ // naming this run and keeps waiting.
+ client.on('reconnecting', () => reconcileSilentEnd());
+ client.on('status_changed', (status) => {
+ if (status === 'disconnected') reconcileSilentEnd();
});
// Handle auth failures β€” server-side terminal: the op no longer exists on
@@ -1482,6 +1610,16 @@ export class GatewayActionImpl {
executor: true,
gatewayUrl: agentGatewayUrl,
onEvent: eventRouter,
+ // A silent end (subscription gone, no terminal frame) means the run is
+ // either still alive on the server or already over with its terminal lost.
+ // Only the server can tell those apart β€” see `#isRunOverAfterSilentEnd`.
+ onSilentEnd: () =>
+ this.#isRunOverAfterSilentEnd({
+ agentShareId,
+ heteroType: result.heteroType,
+ serverOperationId: result.operationId,
+ topicId: result.topicId,
+ }),
onSessionComplete: ({ authFailed, completion, succeeded, terminalReceived }) => {
// The gateway event handler already completed the op via the shared run
// lifecycle on `agent_runtime_end` / `error`. Only complete here as the
@@ -1824,6 +1962,16 @@ export class GatewayActionImpl {
executor: false,
gatewayUrl: agentGatewayUrl,
onEvent: eventRouter,
+ // Same silent-end reconcile as the primary path: a reconnect that never
+ // receives a terminal frame must still retire its local op once the server
+ // proves the run is over β€” otherwise the reloaded tab spins forever.
+ onSilentEnd: () =>
+ this.#isRunOverAfterSilentEnd({
+ agentShareId,
+ heteroType,
+ serverOperationId: operationId,
+ topicId,
+ }),
onSessionComplete: ({ authFailed, completion, succeeded, terminalReceived }) => {
// A reconnect-local operation has no remaining work once the session
// completion callback fires. Real streamed terminals are completed by
@@ -2011,6 +2159,93 @@ export class GatewayActionImpl {
return !!owner && owner !== operationId;
};
+ /**
+ * Whether a silently-ended gateway run is over, judged from the server's own
+ * reservation of the topic.
+ *
+ * `disconnected` fires whenever this operation's subscription ends β€” including
+ * the case where it ends without the run's terminal frame. The transport cannot
+ * read that case (a transient drop and a finished-but-unannounced run look
+ * identical), so the decision belongs here, against authoritative state.
+ *
+ * `metadata.runningOperation` is that state: the server's own `finish` clears it
+ * before it publishes the terminal event, and a newer run replaces it. A
+ * refreshed row that no longer names THIS operation therefore proves the run is
+ * over; a row that still names it proves the run is alive (a drop that will
+ * reconnect, or a run parked on a tool/approval) and must be left alone.
+ *
+ * Deliberately false when the row cannot be read: an unreadable row is not
+ * evidence that the run ended, and "never guess completion from silence" is the
+ * whole point of this guard.
+ *
+ * Local only β€” the server settles its own row (same contract as
+ * {@link #settleLocalTopicAfterConfirmedStop}). An external hetero producer is
+ * excluded: its output never travelled over this socket, so no transport
+ * observation can prove it stopped.
+ */
+ #isRunOverAfterSilentEnd = async (params: {
+ agentShareId?: string;
+ heteroType?: string | null;
+ serverOperationId: string;
+ topicId?: string;
+ }): Promise<boolean> => {
+ const { agentShareId, heteroType, serverOperationId, topicId } = params;
+ // Only a run that declares itself an ordinary server run may be retired from
+ // here. `undefined` (an older marker that omits the field, mid rolling deploy)
+ // stays fail-safe: unknown is not proof that it ran on the server.
+ if (!topicId || heteroType !== null) return false;
+
+ // A newer turn in THIS tab may own the topic by now. That is not a reason to
+ // skip the read β€” the server naming another operation is exactly what proves
+ // THIS one ended β€” and the completion path is already ownership-guarded:
+ // `settleRunningOperation` compares the operation id, `clearLocalRunningOperation`
+ // checks the marker, and only this local operation is completed. Skipping the
+ // read instead left a superseded operation locally `running` forever: its
+ // transport is torn down, so no later loss signal ever retries.
+
+ // A share visitor cannot read the creator-owned topic through the owner-scoped
+ // `topicService` β€” `topic.getTopicDetail` resolves with `findOwnTopicById`, so
+ // a visitor's read fails and reconciliation would always return false, leaving
+ // a terminal-less share run stuck. Read the visitor's own topic through the
+ // share-authorized list instead: it is the same read the share surface already
+ // hands `useGatewayReconnect`, carrying the sanitized `runningOperation`
+ // projection. That projection has no `childOperations` (they describe
+ // creator-side dispatch a visitor must not see), so a marker naming a
+ // different operation is not proof THIS run ended β€” keep waiting rather than
+ // risk retiring a live run.
+ if (agentShareId) {
+ try {
+ const topics = await shareChatService.getTopics(agentShareId);
+ // The row is gone, or the share-authorized projection names no run on the
+ // topic: both prove this run is over.
+ return !topics?.find((topic) => topic.id === topicId)?.runningOperation;
+ } catch (error) {
+ console.error('[Gateway] Silent-end share topic read failed:', error);
+ return false;
+ }
+ }
+
+ let detail: ChatTopic | null;
+ try {
+ detail = await topicService.getTopicDetail(topicId);
+ } catch (error) {
+ console.error('[Gateway] Silent-end topic read failed:', error);
+ return false;
+ }
+ if (!detail) return false;
+
+ const runningOperation = detail.metadata?.runningOperation;
+ if (!runningOperation) return true;
+ if (runningOperation.operationId === serverOperationId) return false;
+
+ // A member continuation rides the supervisor's root marker instead of owning
+ // one: while the run still lists this operation as its child, the run is alive.
+ // Same ownership test the server's own settle uses.
+ return !runningOperation.childOperations?.some(
+ (child) => child.operationId === serverOperationId,
+ );
+ };
+
/**
* Retire the local topic row once the server has confirmed a stop.
*