🤯 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(chat): route Android Codex device runs through Agent Gateway (#18717)
Yuzhong Zhang47a19e1e3092
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/agentDispatcher.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/agentDispatcher.test.tsindex 99b0ea244b2..3c00b9c95ae 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/agentDispatcher.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/agentDispatcher.test.ts@@ -23,6 +23,7 @@ const codexApiHeteroProvider = {};const remoteHeteroProvider = { type: 'openclaw' as const };const remoteHeteroProviderHermes = { type: 'hermes' as const };+const codexCliProvider = { command: 'codex', type: 'codex' as const };describe('selectRuntimeType', () => {describe('on web (isDesktop = false)', () => {@@ -59,6 +60,33 @@ describe('selectRuntimeType', () => {),).toBe('gateway');});++ it('routes Codex device execution to gateway on Android (isDesktop=false)', () => {+ // Android cannot spawn the CLI in-process. A bound macOS device must go+ // through Agent Gateway — never the Provider API (`client`).+ expect(+ selectRuntimeType(+ {+ boundDeviceId: 'macos-device',+ executionTarget: 'device',+ heterogeneousProvider: codexCliProvider,+ isGatewayMode: false,+ },+ opts,+ ),+ ).toBe('gateway');+ expect(+ selectRuntimeType(+ {+ boundDeviceId: 'macos-device',+ executionTarget: 'device',+ heterogeneousProvider: codexCliProvider,+ isGatewayMode: true,+ },+ opts,+ ),+ ).toBe('gateway');+ });});describe('on desktop (isDesktop = true)', () => {diff --git a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.tsindex 857c2d169de..dd269f18b53 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts@@ -3783,6 +3783,92 @@ describe('ConversationLifecycle actions', () => {expect(result.current.executeClientAgent).not.toHaveBeenCalled();});+ it('routes Android Codex device execution to the gateway instead of the Provider API', async () => {+ // Regression: Android (isDesktop=false) selected a remote macOS device+ // for a Codex agent whose agencyConfig only carried the legacy+ // `model: 'codex'` identity. Without recovering the hetero provider,+ // selectRuntimeType fell through to `client` and POST /webapi/chat/codex+ // returned InvalidProviderAPIKey.+ mockConstEnv.isDesktop = false;+ setupMockSelectors({+ agentConfig: {+ agencyConfig: {+ boundDeviceId: 'macos-device',+ executionTarget: 'device',+ },+ model: 'codex',+ },+ });++ const executeGatewayAgent = vi.fn().mockImplementation(async (params) => {+ useChatStore.getState().completeOperation(params.parentOperationId);+ return {+ assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,+ operationId: 'gateway-operation',+ userMessageId: TEST_IDS.USER_MESSAGE_ID,+ };+ });+ act(() => {+ useChatStore.setState({+ executeGatewayAgent,+ isGatewayModeEnabled: () => false,+ });+ });++ const { result } = renderHook(() => useChatStore());+ await act(async () => {+ await result.current.sendMessage({+ message: TEST_CONTENT.USER_MESSAGE,+ context: createTestContext(),+ });+ });++ expect(executeGatewayAgent).toHaveBeenCalledTimes(1);+ expect(executeHeterogeneousAgentMock).not.toHaveBeenCalled();+ expect(result.current.executeClientAgent).not.toHaveBeenCalled();+ });++ it('routes Android Codex with a configured heterogeneousProvider to the gateway', async () => {+ mockConstEnv.isDesktop = false;+ setupMockSelectors({+ agentConfig: {+ agencyConfig: {+ boundDeviceId: 'macos-device',+ executionTarget: 'device',+ heterogeneousProvider: { command: 'codex', type: 'codex' },+ },+ model: 'codex',+ },+ });++ const executeGatewayAgent = vi.fn().mockImplementation(async (params) => {+ useChatStore.getState().completeOperation(params.parentOperationId);+ return {+ assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,+ operationId: 'gateway-operation',+ userMessageId: TEST_IDS.USER_MESSAGE_ID,+ };+ });+ act(() => {+ useChatStore.setState({+ executeGatewayAgent,+ isGatewayModeEnabled: () => false,+ });+ });++ const { result } = renderHook(() => useChatStore());+ await act(async () => {+ await result.current.sendMessage({+ message: TEST_CONTENT.USER_MESSAGE,+ context: createTestContext(),+ });+ });++ expect(executeGatewayAgent).toHaveBeenCalledTimes(1);+ expect(executeHeterogeneousAgentMock).not.toHaveBeenCalled();+ expect(result.current.executeClientAgent).not.toHaveBeenCalled();+ });+it('runs a workspace Codex local-device override in the desktop heterogeneous runtime', async () => {mockConstEnv.isDesktop = true;setupMockSelectors({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.tsindex e325c0f712a..6c8421c350d 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@@ -4,6 +4,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import type * as ConstVersion from '@/const/version';import { aiAgentService } from '@/services/aiAgent';import { messageService } from '@/services/message';+import * as serverConfigStore from '@/store/serverConfig';import { GatewayActionImpl } from '../transports/gateway/gateway';import { getGatewayMux, resetGatewayMuxRegistry } from '../transports/gateway/muxRegistry';@@ -362,6 +363,27 @@ describe('GatewayActionImpl (enableGatewayMux lab)', () => {expect(Object.keys(state.gatewayFeed)).toEqual(['op-feed']);});+ it.each([true, false])(+ 'warms up from module config when mode is %s without window',+ (enabled) => {+ const { action, mux } = createTestAction();+ Reflect.deleteProperty(globalThis, 'window');+ vi.spyOn(serverConfigStore, 'getServerConfigStoreState').mockReturnValue({+ serverConfig: { agentGatewayUrl: GATEWAY_URL, enableGatewayMode: enabled },+ } as ReturnType<typeof serverConfigStore.getServerConfigStoreState>);++ action.warmupGatewayMux();++ if (enabled) {+ expect(action.resolveGatewayMux).toHaveBeenCalledWith({ gatewayUrl: GATEWAY_URL });+ expect(mux.connect).toHaveBeenCalledOnce();+ } else {+ expect(action.resolveGatewayMux).not.toHaveBeenCalled();+ expect(mux.connect).not.toHaveBeenCalled();+ }+ },+ );+it('is a no-op when the lab flag is off or gateway mode is unavailable', () => {withServerConfig({ agentGatewayUrl: GATEWAY_URL, enableGatewayMode: true });mockLab.enableGatewayMux = false;diff --git a/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.tsindex 1b4bc7c0188..90a734797c4 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts@@ -8,6 +8,7 @@ import { messageService } from '@/services/message';import { shareChatService } from '@/services/shareChat';import { topicService } from '@/services/topic';import { messageMapKey } from '@/store/chat/utils/messageMapKey';+import * as serverConfigStore from '@/store/serverConfig';import type { ChatTopic } from '@/types/topic';import type { GatewayConnection } from '../transports/gateway/gateway';@@ -256,6 +257,21 @@ describe('GatewayActionImpl', () => {expect(action.isGatewayModeEnabled('agent-1')).toBe(false);});++ it('reads serverConfig from the module store when window.global_serverConfigStore is missing', () => {+ // Android / React Native hydrates createServerConfigStore but does not+ // always attach it to `window`. Dispatch must still see ENABLE_AGENT_GATEWAY.+ const { action } = createTestAction();+ (globalThis as any).window = {};+ vi.spyOn(serverConfigStore, 'getServerConfigStoreState').mockReturnValue({+ serverConfig: {+ agentGatewayUrl: 'wss://gateway.test.com',+ enableGatewayMode: true,+ },+ } as ReturnType<typeof serverConfigStore.getServerConfigStoreState>);++ expect(action.isGatewayModeEnabled('agent-1')).toBe(true);+ });});describe('connectToGateway', () => {@@ -633,6 +649,184 @@ describe('GatewayActionImpl', () => {delete (globalThis as any).window;});+ it.each([+ {+ expectedEnabled: true,+ expectedUrl: 'https://module-gateway.test.com',+ hasWindow: true,+ moduleEnabled: true,+ name: 'module config without a window store',+ },+ {+ expectedEnabled: true,+ expectedUrl: 'https://module-gateway.test.com',+ hasWindow: false,+ moduleEnabled: true,+ name: 'module config without window',+ },+ {+ expectedEnabled: true,+ expectedUrl: 'https://window-gateway.test.com',+ hasWindow: true,+ moduleEnabled: false,+ name: 'enabled window config over disabled module config',+ windowConfig: {+ agentGatewayUrl: 'https://window-gateway.test.com',+ enableGatewayMode: true,+ },+ },+ {+ expectedEnabled: false,+ expectedUrl: 'https://window-gateway.test.com',+ hasWindow: true,+ moduleEnabled: true,+ name: 'explicit execution with disabled window config',+ windowConfig: {+ agentGatewayUrl: 'https://window-gateway.test.com',+ enableGatewayMode: false,+ },+ },+ {+ expectedEnabled: false,+ expectedUrl: 'https://module-gateway.test.com',+ hasWindow: true,+ moduleEnabled: false,+ name: 'explicit execution with disabled module config',+ },+ {+ disableGatewayMode: true,+ expectedEnabled: false,+ expectedUrl: 'https://module-gateway.test.com',+ hasWindow: true,+ moduleEnabled: true,+ name: 'explicit execution with the user default disabled',+ },+ ])(+ 'executes and reconnects using $name',+ async ({+ disableGatewayMode,+ expectedEnabled,+ expectedUrl,+ hasWindow,+ moduleEnabled,+ windowConfig,+ }) => {+ const { action, connectToGateway, mockClient, state } = createExecuteTestAction();+ state.messagesMap = {};+ connectToGateway.mockImplementation(action.connectToGateway);+ if (hasWindow) {+ Reflect.set(globalThis, 'window', {+ global_serverConfigStore: windowConfig+ ? { getState: () => ({ serverConfig: windowConfig }) }+ : undefined,+ });+ } else Reflect.deleteProperty(globalThis, 'window');+ mockUserDefaultConfig.disableGatewayMode = disableGatewayMode;+ vi.spyOn(serverConfigStore, 'getServerConfigStoreState').mockReturnValue({+ serverConfig: {+ agentGatewayUrl: 'https://module-gateway.test.com',+ enableGatewayMode: moduleEnabled,+ },+ } as ReturnType<typeof serverConfigStore.getServerConfigStoreState>);+ vi.mocked(aiAgentService.execAgentTask).mockResolvedValue({+ agentId: 'agent-1',+ assistantMessageId: 'ast-1',+ autoStarted: true,+ createdAt: new Date().toISOString(),+ message: 'ok',+ operationId: 'server-op-1',+ status: 'created',+ success: true,+ timestamp: new Date().toISOString(),+ token: 'execute-token',+ topicId: 'topic-1',+ userMessageId: 'usr-1',+ });+ vi.mocked(aiAgentService.refreshGatewayToken).mockResolvedValue({ token: 'resume-token' });++ expect(action.isGatewayModeEnabled('agent-1')).toBe(expectedEnabled);+ await action.executeGatewayAgent({+ context: { agentId: 'agent-1', scope: 'main', threadId: null, topicId: 'topic-1' },+ message: 'Run Codex on the bound device',+ });++ expect(aiAgentService.execAgentTask).toHaveBeenCalledOnce();+ expect(action.createClient).toHaveBeenLastCalledWith({+ gatewayUrl: expectedUrl,+ operationId: 'server-op-1',+ resumeOnConnect: undefined,+ token: 'execute-token',+ });+ expect(mockClient.connect).toHaveBeenCalledOnce();++ action.disconnectFromGateway('server-op-1');+ await action.reconnectToGatewayOperation({+ agentId: 'agent-1',+ assistantMessageId: 'ast-1',+ operationId: 'server-op-1',+ topicId: 'topic-1',+ });++ expect(aiAgentService.refreshGatewayToken).toHaveBeenCalledWith('topic-1');+ expect(action.createClient).toHaveBeenLastCalledWith({+ gatewayUrl: expectedUrl,+ operationId: 'server-op-1',+ resumeOnConnect: true,+ token: 'resume-token',+ });+ expect(mockClient.connect).toHaveBeenCalledTimes(2);+ },+ );++ it.each(['no config', 'window config without URL'])(+ 'fails before execution and skips reconnect with %s',+ async (source) => {+ const { action, connectToGateway, startOperation } = createExecuteTestAction();+ connectToGateway.mockImplementation(action.connectToGateway);+ const getModuleState = vi.spyOn(serverConfigStore, 'getServerConfigStoreState');+ if (source === 'no config') {+ Reflect.deleteProperty(globalThis, 'window');+ getModuleState.mockReturnValue(undefined);+ } else {+ Reflect.set(globalThis, 'window', {+ global_serverConfigStore: {+ getState: () => ({ serverConfig: { enableGatewayMode: true } }),+ },+ });+ getModuleState.mockReturnValue({+ serverConfig: {+ agentGatewayUrl: 'https://module-gateway.test.com',+ enableGatewayMode: true,+ },+ } as ReturnType<typeof serverConfigStore.getServerConfigStoreState>);+ }++ expect(action.isGatewayModeEnabled('agent-1')).toBe(false);+ await expect(+ action.executeGatewayAgent({+ context: { agentId: 'agent-1', scope: 'main', threadId: null, topicId: 'topic-1' },+ message: 'Run Codex on the bound device',+ }),+ ).rejects.toThrow(+ '[Gateway] Cannot execute agent: serverConfig.agentGatewayUrl is missing',+ );+ await expect(+ action.reconnectToGatewayOperation({+ agentId: 'agent-1',+ assistantMessageId: 'ast-1',+ operationId: 'server-op-1',+ topicId: 'topic-1',+ }),+ ).resolves.toBeUndefined();++ expect(aiAgentService.execAgentTask).not.toHaveBeenCalled();+ expect(aiAgentService.refreshGatewayToken).not.toHaveBeenCalled();+ expect(startOperation).not.toHaveBeenCalled();+ expect(action.createClient).not.toHaveBeenCalled();+ expect(topicService.settleRunningOperation).not.toHaveBeenCalled();+ },+ );+it('should forward parentMessageId to execAgentTask for regeneration', async () => {const { action } = createExecuteTestAction();diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.tsindex bd67ca72b5e..073bb5ee810 100644--- a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts+++ b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts@@ -459,12 +459,12 @@ export class ConversationLifecycleActionImpl {);const isGatewayMode = this.#get().isGatewayModeEnabled(agentId);// Legacy agents may only carry `model: '<cli-type>'`. Keep gateway routing- // unchanged when it is available, but recover the provider before the- // desktop-only local fallback so both runtime selection and the executor- // receive the same heterogeneous identity.+ // unchanged when it is available. Recover the provider when gateway mode is+ // off so desktop can still spawn locally and non-desktop (Android/web) still+ // routes through Gateway instead of the Provider API.const heterogeneousProvider =agencyConfig?.heterogeneousProvider ??- (isDesktop && !isGatewayMode && isHeterogeneousAgentModelId(agentConfig?.model)+ (!isGatewayMode && isHeterogeneousAgentModelId(agentConfig?.model)? { type: agentConfig.model }: undefined);const runtimeType = selectRuntimeType({diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.tsindex 7c717b9d81a..4347f8adf29 100644--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts@@ -45,6 +45,7 @@ import type { ChatStore } from '@/store/chat/store';import { messageMapKey } from '@/store/chat/utils/messageMapKey';import { topicMapKey } from '@/store/chat/utils/topicMapKey';import { getFileStoreState } from '@/store/file/store';+import { getServerConfigStoreState } from '@/store/serverConfig';import type { StoreSetter } from '@/store/types';import { useUserStore } from '@/store/user';import {@@ -65,6 +66,11 @@ import { createGatewayMemberStreamHandler } from './gatewayMemberStreamHandler';import { type GatewayMuxIdentity, getGatewayMux } from './muxRegistry';import { flagQueuedMessagesOnRunStart, syncQueuedMessagesFlag } from './queuedMessagesFlag';+const getGatewayServerConfig = () =>+ (typeof window !== 'undefined'+ ? window.global_serverConfigStore?.getState()?.serverConfig+ : undefined) ?? getServerConfigStoreState()?.serverConfig;+/*** Interrupts a gateway operation and rejects when its physical shutdown is unconfirmed.*@@ -575,7 +581,7 @@ export class GatewayActionImpl {*/warmupGatewayMux = (): void => {if (!labPreferSelectors.enableGatewayMux(useUserStore.getState())) return;- const serverConfig = window.global_serverConfigStore?.getState()?.serverConfig;+ const serverConfig = getGatewayServerConfig();if (!serverConfig?.agentGatewayUrl || !serverConfig.enableGatewayMode) return;const mux = this.resolveGatewayMux({ gatewayUrl: serverConfig.agentGatewayUrl });@@ -587,7 +593,7 @@ export class GatewayActionImpl {};isGatewayModeEnabled = (agentId?: string): boolean => {- const serverConfig = window.global_serverConfigStore?.getState()?.serverConfig;+ const serverConfig = getGatewayServerConfig();const agentState = getAgentStoreState();const resolvedAgentId = agentId ?? agentState.activeAgentId;const agentDisableGatewayMode = resolvedAgentId@@ -606,7 +612,7 @@ export class GatewayActionImpl {/*** Execute agent task via Gateway WebSocket.- * Call isGatewayModeEnabled() first to check availability.+ * The dispatcher can select this transport for device execution even when Gateway mode is off.*//*** Execute agent task via Gateway WebSocket.@@ -730,8 +736,10 @@ export class GatewayActionImpl {tempMessageIds,} = params;- const agentGatewayUrl =- window.global_serverConfigStore!.getState().serverConfig.agentGatewayUrl!;+ const agentGatewayUrl = getGatewayServerConfig()?.agentGatewayUrl;+ if (!agentGatewayUrl) {+ throw new Error('[Gateway] Cannot execute agent: serverConfig.agentGatewayUrl is missing');+ }// The EXECUTION context decides whether the server creates a topic. The// message context can already carry the client-minted topic id (the send@@ -1271,8 +1279,7 @@ export class GatewayActionImpl {const { agentShareId, assistantMessageId, heteroType, operationId, topicId, scope, threadId } =params;- const agentGatewayUrl =- window.global_serverConfigStore?.getState()?.serverConfig?.agentGatewayUrl;+ const agentGatewayUrl = getGatewayServerConfig()?.agentGatewayUrl;if (!agentGatewayUrl) return;// Skip reconnect if the gateway action already established (or is establishing)