π€― 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
β‘οΈ perf(device): preset local device on first LLM request for ζ¬ζΊ target (#15435)
Arvin Xu7a93df9e448d
diff --git a/src/store/chat/slices/aiChat/actions/__tests__/gateway.test.ts b/src/store/chat/slices/aiChat/actions/__tests__/gateway.test.tsindex 1de3ef0b66f..9e12c3a42e5 100644--- a/src/store/chat/slices/aiChat/actions/__tests__/gateway.test.ts+++ b/src/store/chat/slices/aiChat/actions/__tests__/gateway.test.ts@@ -2,6 +2,7 @@ import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';import { RequestTrigger } from '@lobechat/types';import { afterEach, describe, expect, it, vi } from 'vitest';+import type * as ConstVersion from '@/const/version';import { aiAgentService } from '@/services/aiAgent';import type { GatewayConnection } from '../gateway';@@ -33,6 +34,35 @@ vi.mock('@/store/user', () => ({},}));+// βββ Local-device activation (ζ¬ζΊ) test seams βββ+// Controlled per-test; default off so the rest of the suite runs as web (no+// device resolution, no electron IPC).+const mockEnv = vi.hoisted(() => ({ isDesktop: false }));+const mockGateway = vi.hoisted(() => ({ getDeviceInfo: vi.fn() }));+// Effective runtime mode === 'local' (what isLocalSystemEnabledById returns).+const mockRuntime = vi.hoisted(() => ({ isLocal: false }));++vi.mock('@/const/version', async (importOriginal) => {+ const actual = await importOriginal<typeof ConstVersion>();+ return {+ ...actual,+ get isDesktop() {+ return mockEnv.isDesktop;+ },+ };+});++vi.mock('@/services/electron/gatewayConnection', () => ({+ gatewayConnectionService: { getDeviceInfo: mockGateway.getDeviceInfo },+}));++vi.mock('@/store/agent', () => ({ getAgentStoreState: () => ({}) }));++vi.mock('@/store/agent/selectors', () => ({+ agentSelectors: { currentAgentWorkingDirectory: () => undefined },+ chatConfigByIdSelectors: { isLocalSystemEnabledById: () => () => mockRuntime.isLocal },+}));+// βββ Mock Client Factory βββfunction createMockClient(): GatewayConnection['client'] & {@@ -749,5 +779,84 @@ describe('GatewayActionImpl', () => {topicId: 'topic-1',});});++ // When the desktop runs against ζ¬ζΊ (effective runtime mode 'local'), the+ // client must forward this machine's own gateway deviceId so the server can+ // preset activeDeviceId and inject lobe-local-system into the first LLM+ // payload β skipping the activateDevice round-trip. It must NOT do so for a+ // cloud/none run, otherwise that run would be wrongly routed to the device.+ describe('local device activation (ζ¬ζΊ)', () => {+ const successResult = {+ agentId: 'agent-1',+ assistantMessageId: 'ast-1',+ autoStarted: true,+ createdAt: new Date().toISOString(),+ message: 'ok',+ operationId: 'server-op-1',+ status: 'created' as const,+ success: true,+ timestamp: new Date().toISOString(),+ token: 'test-token',+ topicId: 'topic-1',+ userMessageId: 'usr-1',+ };++ afterEach(() => {+ mockEnv.isDesktop = false;+ mockRuntime.isLocal = false;+ mockGateway.getDeviceInfo.mockReset();+ });++ const send = async () => {+ const { action } = createExecuteTestAction();+ vi.mocked(aiAgentService.execAgentTask).mockResolvedValue(successResult);+ await action.executeGatewayAgent({+ context: { agentId: 'agent-1', scope: 'main', threadId: null, topicId: 'topic-1' },+ message: 'list files in cwd',+ });+ };++ it('forwards this desktop deviceId when local execution is selected', async () => {+ mockEnv.isDesktop = true;+ mockRuntime.isLocal = true;+ mockGateway.getDeviceInfo.mockResolvedValue({ deviceId: 'device-local-1' });++ await send();++ expect(aiAgentService.execAgentTask).toHaveBeenCalledWith(+ expect.objectContaining({ deviceId: 'device-local-1' }),+ expect.anything(),+ );+ });++ // Regression guard: the legacy ModeSelector writes only runtimeMode, so an+ // explicit cloud/none run leaves executionTarget unset. Gating on the+ // effective runtime mode (not the unset target) keeps it off the device.+ it('does not resolve a deviceId when a non-local runtime mode is selected', async () => {+ mockEnv.isDesktop = true;+ mockRuntime.isLocal = false;++ await send();++ expect(mockGateway.getDeviceInfo).not.toHaveBeenCalled();+ expect(aiAgentService.execAgentTask).toHaveBeenCalledWith(+ expect.objectContaining({ deviceId: undefined }),+ expect.anything(),+ );+ });++ it('never resolves a deviceId off desktop, even when local mode is set', async () => {+ mockEnv.isDesktop = false;+ mockRuntime.isLocal = true;++ await send();++ expect(mockGateway.getDeviceInfo).not.toHaveBeenCalled();+ expect(aiAgentService.execAgentTask).toHaveBeenCalledWith(+ expect.objectContaining({ deviceId: undefined }),+ expect.anything(),+ );+ });+ });});});diff --git a/src/store/chat/slices/aiChat/actions/gateway.ts b/src/store/chat/slices/aiChat/actions/gateway.tsindex af10c3195ea..742dec5f894 100644--- a/src/store/chat/slices/aiChat/actions/gateway.ts+++ b/src/store/chat/slices/aiChat/actions/gateway.ts@@ -8,11 +8,12 @@ import type { ConversationContext, ExecAgentResult, MessageMetadata } from '@lobimport { isDesktop } from '@/const/version';import { aiAgentService, type ResumeApprovalParam } from '@/services/aiAgent';+import { gatewayConnectionService } from '@/services/electron/gatewayConnection';import { localFileService } from '@/services/electron/localFileService';import { messageService } from '@/services/message';import { topicService } from '@/services/topic';import { getAgentStoreState } from '@/store/agent';-import { agentSelectors } from '@/store/agent/selectors';+import { agentSelectors, chatConfigByIdSelectors } from '@/store/agent/selectors';import { consumePendingTopicRepos, getPendingTopicRepos } from '@/store/chat/pendingTopicRepos';import { topicSelectors } from '@/store/chat/selectors';import type { ChatStore } from '@/store/chat/store';@@ -53,6 +54,40 @@ const resolveProjectSkills = async (}};+/**+ * When the agent runs against the local machine ("ζ¬ζΊ"), resolve this desktop's+ * own gateway deviceId so it can be passed as the run's `deviceId`. The server+ * then presets `activeDeviceId` and injects `lobe-local-system` into the very+ * first LLM payload β skipping the extra `activateDevice` round-trip the model+ * is otherwise forced to make whenever more than one device is online (with a+ * single device the server's heuristic already covered it).+ *+ * Gated on the effective runtime mode (`isLocalSystemEnabledById`), NOT on+ * `agencyConfig.executionTarget`: the latter is only written by the newer+ * HeteroDeviceSwitcher, whereas the legacy ModeSelector writes just+ * `runtimeMode`. Resolving a device whenever the target is unset would override+ * an explicit `cloud` / `none` choice and wrongly route a cloud run to the+ * local machine. `runtimeMode` is the single source of truth both selectors+ * agree on (and what the server gates CloudSandbox on).+ *+ * Desktop-only and best-effort: any failure falls back to the server-side+ * device-resolution heuristics. We don't pre-check online status here β an+ * offline id simply fails the server's `onlineDevices` guard and stays unrouted.+ */+const resolveLocalDeviceId = async (agentId?: string): Promise<string | undefined> => {+ if (!isDesktop || !agentId) return undefined;++ const isLocal = chatConfigByIdSelectors.isLocalSystemEnabledById(agentId)(getAgentStoreState());+ if (!isLocal) return undefined;++ try {+ const info = await gatewayConnectionService.getDeviceInfo();+ return info?.deviceId;+ } catch {+ return undefined;+ }+};+type Setter = StoreSetter<ChatStore>;// βββ Types βββ@@ -353,7 +388,10 @@ export class GatewayActionImpl {? this.#get().getOperationAbortSignal(parentOperationId): undefined;- const projectSkills = await resolveProjectSkills(this.#get);+ const [projectSkills, localDeviceId] = await Promise.all([+ resolveProjectSkills(this.#get),+ resolveLocalDeviceId(context.agentId),+ ]);const result = await aiAgentService.execAgentTask({@@ -369,6 +407,7 @@ export class GatewayActionImpl {threadId: context.threadId,topicId: context.topicId,},+ deviceId: localDeviceId,fileIds,parentMessageId,projectSkills,