π€― 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
β¨ feat: support local device binding in lh agent run (#13277)
Rylan Caieb086b84563d
diff --git a/apps/cli/src/api/http.ts b/apps/cli/src/api/http.tsindex 43b47082a55..c3f2ba05b0e 100644--- a/apps/cli/src/api/http.ts+++ b/apps/cli/src/api/http.ts@@ -57,3 +57,39 @@ export async function getAuthInfo(): Promise<AuthInfo> {serverUrl,};}++export async function getAgentStreamAuthInfo(): Promise<Pick<AuthInfo, 'headers' | 'serverUrl'>> {+ const serverUrl = resolveServerUrl();++ const envJwt = process.env.LOBEHUB_JWT;+ if (envJwt) {+ return {+ headers: { 'Oidc-Auth': envJwt },+ serverUrl,+ };+ }++ const envApiKey = process.env[CLI_API_KEY_ENV];+ if (envApiKey) {+ return {+ headers: { 'X-API-Key': envApiKey },+ serverUrl,+ };+ }++ const result = await getValidToken();+ if (!result) {+ log.error(`No authentication found. Run 'lh login' first, or set ${CLI_API_KEY_ENV}.`);+ process.exit(1);++ return {+ headers: {},+ serverUrl,+ };+ }++ return {+ headers: { 'Oidc-Auth': result.credentials.accessToken },+ serverUrl,+ };+}diff --git a/apps/cli/src/commands/agent.test.ts b/apps/cli/src/commands/agent.test.tsindex 27e54262a8b..46141c6a1f0 100644--- a/apps/cli/src/commands/agent.test.ts+++ b/apps/cli/src/commands/agent.test.ts@@ -27,6 +27,9 @@ const { mockTrpcClient } = vi.hoisted(() => ({execAgent: { mutate: vi.fn() },getOperationStatus: { query: vi.fn() },},+ device: {+ listDevices: { query: vi.fn() },+ },},}));@@ -38,13 +41,18 @@ const { mockStreamAgentEvents } = vi.hoisted(() => ({mockStreamAgentEvents: vi.fn(),}));-const { mockGetAuthInfo } = vi.hoisted(() => ({- mockGetAuthInfo: vi.fn(),+const { mockGetAgentStreamAuthInfo } = vi.hoisted(() => ({+ mockGetAgentStreamAuthInfo: vi.fn(),+}));++const { mockResolveLocalDeviceId } = vi.hoisted(() => ({+ mockResolveLocalDeviceId: vi.fn(),}));vi.mock('../api/client', () => ({ getTrpcClient: mockGetTrpcClient }));-vi.mock('../api/http', () => ({ getAuthInfo: mockGetAuthInfo }));+vi.mock('../api/http', () => ({ getAgentStreamAuthInfo: mockGetAgentStreamAuthInfo }));vi.mock('../utils/agentStream', () => ({ streamAgentEvents: mockStreamAgentEvents }));+vi.mock('../utils/device', () => ({ resolveLocalDeviceId: mockResolveLocalDeviceId }));vi.mock('../utils/logger', () => ({log: { debug: vi.fn(), error: vi.fn(), heartbeat: vi.fn(), info: vi.fn(), warn: vi.fn() },setVerbose: vi.fn(),@@ -58,12 +66,12 @@ describe('agent command', () => {exitSpy = vi.spyOn(process, 'exit').mockImplementation((() => {}) as any);consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});mockGetTrpcClient.mockResolvedValue(mockTrpcClient);- mockGetAuthInfo.mockResolvedValue({- accessToken: 'test-token',- headers: { 'Content-Type': 'application/json', 'Oidc-Auth': 'test-token' },+ mockGetAgentStreamAuthInfo.mockResolvedValue({+ headers: { 'Oidc-Auth': 'test-token' },serverUrl: 'https://example.com',});mockStreamAgentEvents.mockResolvedValue(undefined);+ mockResolveLocalDeviceId.mockReset();for (const method of Object.values(mockTrpcClient.agent)) {for (const fn of Object.values(method)) {(fn as ReturnType<typeof vi.fn>).mockReset();@@ -74,6 +82,11 @@ describe('agent command', () => {(fn as ReturnType<typeof vi.fn>).mockReset();}}+ for (const method of Object.values(mockTrpcClient.device)) {+ for (const fn of Object.values(method)) {+ (fn as ReturnType<typeof vi.fn>).mockReset();+ }+ }});afterEach(() => {@@ -297,7 +310,6 @@ describe('agent command', () => {expect.objectContaining({ json: undefined, verbose: undefined }),);});-it('should support --slug option', async () => {mockTrpcClient.aiAgent.execAgent.mutate.mockResolvedValue({operationId: 'op-456',@@ -384,6 +396,186 @@ describe('agent command', () => {);});+ it('should pass --device local as deviceId', async () => {+ mockResolveLocalDeviceId.mockReturnValue('local-device-1');+ mockTrpcClient.device.listDevices.query.mockResolvedValue([+ { deviceId: 'local-device-1', online: true },+ ]);+ mockTrpcClient.aiAgent.execAgent.mutate.mockResolvedValue({+ operationId: 'op-device',+ success: true,+ });++ const program = createProgram();+ await program.parseAsync([+ 'node',+ 'test',+ 'agent',+ 'run',+ '--agent-id',+ 'a1',+ '--prompt',+ 'Hi',+ '--device',+ 'local',+ ]);++ expect(mockTrpcClient.aiAgent.execAgent.mutate).toHaveBeenCalledWith(+ expect.objectContaining({ agentId: 'a1', deviceId: 'local-device-1', prompt: 'Hi' }),+ );+ });++ it('should pass --topic-id and --device local together', async () => {+ mockResolveLocalDeviceId.mockReturnValue('local-device-1');+ mockTrpcClient.device.listDevices.query.mockResolvedValue([+ { deviceId: 'local-device-1', online: true },+ ]);+ mockTrpcClient.aiAgent.execAgent.mutate.mockResolvedValue({+ operationId: 'op-topic-device',+ success: true,+ });++ const program = createProgram();+ await program.parseAsync([+ 'node',+ 'test',+ 'agent',+ 'run',+ '--agent-id',+ 'a1',+ '--prompt',+ 'Hi',+ '--topic-id',+ 't1',+ '--device',+ 'local',+ ]);++ expect(mockTrpcClient.aiAgent.execAgent.mutate).toHaveBeenCalledWith(+ expect.objectContaining({ appContext: { topicId: 't1' }, deviceId: 'local-device-1' }),+ );+ });++ it('should pass explicit --device id as deviceId', async () => {+ mockTrpcClient.device.listDevices.query.mockResolvedValue([+ { deviceId: 'device-remote-1', online: true },+ ]);+ mockTrpcClient.aiAgent.execAgent.mutate.mockResolvedValue({+ operationId: 'op-explicit-device',+ success: true,+ });++ const program = createProgram();+ await program.parseAsync([+ 'node',+ 'test',+ 'agent',+ 'run',+ '--agent-id',+ 'a1',+ '--prompt',+ 'Hi',+ '--device',+ 'device-remote-1',+ ]);++ expect(mockResolveLocalDeviceId).not.toHaveBeenCalled();+ expect(mockTrpcClient.aiAgent.execAgent.mutate).toHaveBeenCalledWith(+ expect.objectContaining({ agentId: 'a1', deviceId: 'device-remote-1', prompt: 'Hi' }),+ );+ });++ it('should exit when explicit device is not found', async () => {+ mockTrpcClient.device.listDevices.query.mockResolvedValue([+ { deviceId: 'other-device', online: true },+ ]);++ const program = createProgram();+ await program.parseAsync([+ 'node',+ 'test',+ 'agent',+ 'run',+ '--agent-id',+ 'a1',+ '--prompt',+ 'Hi',+ '--device',+ 'device-remote-1',+ ]);++ expect(log.error).toHaveBeenCalledWith(expect.stringContaining('was not found'));+ expect(exitSpy).toHaveBeenCalledWith(1);+ });++ it('should exit when local device cannot be resolved', async () => {+ mockResolveLocalDeviceId.mockReturnValue(undefined);++ const program = createProgram();+ await program.parseAsync([+ 'node',+ 'test',+ 'agent',+ 'run',+ '--agent-id',+ 'a1',+ '--prompt',+ 'Hi',+ '--device',+ 'local',+ ]);++ expect(log.error).toHaveBeenCalledWith(expect.stringContaining("Run 'lh connect' first"));+ expect(exitSpy).toHaveBeenCalledWith(1);+ });++ it('should exit when local device is offline', async () => {+ mockResolveLocalDeviceId.mockReturnValue('local-device-1');+ mockTrpcClient.device.listDevices.query.mockResolvedValue([+ { deviceId: 'local-device-1', online: false },+ ]);++ const program = createProgram();+ await program.parseAsync([+ 'node',+ 'test',+ 'agent',+ 'run',+ '--agent-id',+ 'a1',+ '--prompt',+ 'Hi',+ '--device',+ 'local',+ ]);++ expect(log.error).toHaveBeenCalledWith(expect.stringContaining('is not online'));+ expect(exitSpy).toHaveBeenCalledWith(1);+ });++ it('should exit when explicit device is offline', async () => {+ mockTrpcClient.device.listDevices.query.mockResolvedValue([+ { deviceId: 'device-remote-1', online: false },+ ]);++ const program = createProgram();+ await program.parseAsync([+ 'node',+ 'test',+ 'agent',+ 'run',+ '--agent-id',+ 'a1',+ '--prompt',+ 'Hi',+ '--device',+ 'device-remote-1',+ ]);++ expect(log.error).toHaveBeenCalledWith(expect.stringContaining('Bring it online'));+ expect(exitSpy).toHaveBeenCalledWith(1);+ });+it('should pass --json to stream options', async () => {mockTrpcClient.aiAgent.execAgent.mutate.mockResolvedValue({operationId: 'op-j',diff --git a/apps/cli/src/commands/agent.ts b/apps/cli/src/commands/agent.tsindex fcd58f9b60b..a3811e87c24 100644--- a/apps/cli/src/commands/agent.ts+++ b/apps/cli/src/commands/agent.ts@@ -4,8 +4,9 @@ import type { Command } from 'commander';import pc from 'picocolors';import { getTrpcClient } from '../api/client';-import { getAuthInfo } from '../api/http';+import { getAgentStreamAuthInfo } from '../api/http';import { replayAgentEvents, streamAgentEvents } from '../utils/agentStream';+import { resolveLocalDeviceId } from '../utils/device';import { confirm, outputJson, printTable, truncate } from '../utils/format';import { log, setVerbose } from '../utils/logger';@@ -248,6 +249,10 @@ export function registerAgentCommand(program: Command) {.option('-p, --prompt <text>', 'User prompt').option('-t, --topic-id <id>', 'Reuse an existing topic').option('--no-auto-start', 'Do not auto-start the agent')+ .option(+ '--device <target>',+ 'Target device ID, or use "local" for the current connected device',+ ).option('--json', 'Output full JSON event stream').option('-v, --verbose', 'Show detailed tool call info').option('--replay <file>', 'Replay events from a saved JSON file (offline)')@@ -255,6 +260,7 @@ export function registerAgentCommand(program: Command) {async (options: {agentId?: string;autoStart?: boolean;+ device?: string;json?: boolean;prompt?: string;replay?: string;@@ -285,9 +291,45 @@ export function registerAgentCommand(program: Command) {const client = await getTrpcClient();+ let deviceId: string | undefined;+ if (options.device !== undefined) {+ if (options.device === 'local') {+ deviceId = resolveLocalDeviceId();+ if (!deviceId) {+ log.error(+ "No local device found. Run 'lh connect' first, then retry with --device local.",+ );+ process.exit(1);+ return;+ }+ } else {+ deviceId = options.device;+ }++ const devices = await client.device.listDevices.query();+ const matchedDevice = devices.find(+ (device: { deviceId?: string; online?: boolean }) => device.deviceId === deviceId,+ );+ if (!matchedDevice) {+ log.error(`Device "${deviceId}" was not found. Check 'lh device list' and try again.`);+ process.exit(1);+ return;+ }+ if (!matchedDevice.online) {+ log.error(+ options.device === 'local'+ ? `Local device "${deviceId}" is not online. Reconnect with 'lh connect' and try again.`+ : `Device "${deviceId}" is not online. Bring it online and try again.`,+ );+ process.exit(1);+ return;+ }+ }+// 1. Exec agent to get operationIdconst input: Record<string, any> = { prompt: options.prompt };if (options.agentId) input.agentId = options.agentId;+ if (deviceId) input.deviceId = deviceId;if (options.slug) input.slug = options.slug;if (options.topicId) input.appContext = { topicId: options.topicId };if (options.autoStart === false) input.autoStart = false;@@ -306,7 +348,7 @@ export function registerAgentCommand(program: Command) {}// 2. Connect to SSE stream- const { serverUrl, headers } = await getAuthInfo();+ const { serverUrl, headers } = await getAgentStreamAuthInfo();const streamUrl = `${serverUrl}/api/agent/stream?operationId=${encodeURIComponent(operationId)}`;await streamAgentEvents(streamUrl, headers, {diff --git a/apps/cli/src/commands/connect.test.ts b/apps/cli/src/commands/connect.test.tsindex e2171c39523..9d47ee4ded5 100644--- a/apps/cli/src/commands/connect.test.ts+++ b/apps/cli/src/commands/connect.test.ts@@ -96,7 +96,7 @@ vi.mock('@lobechat/device-gateway-client', () => ({// eslint-disable-next-line import-x/firstimport { resolveToken } from '../auth/resolveToken';// eslint-disable-next-line import-x/first-import { spawnDaemon, stopDaemon } from '../daemon/manager';+import { removeStatus, spawnDaemon, stopDaemon, writeStatus } from '../daemon/manager';// eslint-disable-next-line import-x/firstimport { loadSettings, saveSettings } from '../settings';// eslint-disable-next-line import-x/first@@ -130,6 +130,36 @@ describe('connect command', () => {return program;}+ it('should persist deviceId in status for foreground connections', async () => {+ const program = createProgram();+ await program.parseAsync(['node', 'test', 'connect']);++ expect(writeStatus).toHaveBeenCalledWith(+ expect.objectContaining({ connectionStatus: 'connecting', deviceId: 'mock-device-id' }),+ );++ clientEventHandlers.connected?.();++ expect(writeStatus).toHaveBeenLastCalledWith(+ expect.objectContaining({ connectionStatus: 'connected', deviceId: 'mock-device-id' }),+ );+ });++ it('should persist deviceId in status for daemon child connections', async () => {+ const program = createProgram();+ await program.parseAsync(['node', 'test', 'connect', '--daemon-child']);++ expect(writeStatus).toHaveBeenCalledWith(+ expect.objectContaining({ connectionStatus: 'connecting', deviceId: 'mock-device-id' }),+ );++ clientEventHandlers.connected?.();++ expect(writeStatus).toHaveBeenLastCalledWith(+ expect.objectContaining({ connectionStatus: 'connected', deviceId: 'mock-device-id' }),+ );+ });+it('should connect to gateway', async () => {const program = createProgram();await program.parseAsync(['node', 'test', 'connect']);@@ -288,6 +318,7 @@ describe('connect command', () => {}expect(cleanupAllProcesses).toHaveBeenCalled();+ expect(removeStatus).toHaveBeenCalled();});it('should handle auth_expired when refresh fails', async () => {diff --git a/apps/cli/src/commands/connect.ts b/apps/cli/src/commands/connect.tsindex 2598e5ce8cb..cb38f361249 100644--- a/apps/cli/src/commands/connect.ts+++ b/apps/cli/src/commands/connect.ts@@ -221,16 +221,15 @@ async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {info(` Mode : ${isDaemonChild ? 'daemon' : 'foreground'}`);info('βββββββββββββββββββ');- // Update status file for daemon mode+ // Update local connection status so other CLI commands can resolve the current deviceconst updateStatus = (connectionStatus: string) => {- if (isDaemonChild) {- writeStatus({- connectionStatus,- gatewayUrl: resolvedGatewayUrl,- pid: process.pid,- startedAt: startedAt.toISOString(),- });- }+ writeStatus({+ connectionStatus,+ deviceId: client.currentDeviceId,+ gatewayUrl: resolvedGatewayUrl,+ pid: process.pid,+ startedAt: startedAt.toISOString(),+ });};const startedAt = new Date();@@ -333,8 +332,8 @@ async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {info('Shutting down...');cleanupAllProcesses();client.disconnect();+ removeStatus();if (isDaemonChild) {- removeStatus();removePid();}};diff --git a/apps/cli/src/daemon/manager.ts b/apps/cli/src/daemon/manager.tsindex 3f201a2c7d5..d4b1fcef05c 100644--- a/apps/cli/src/daemon/manager.ts+++ b/apps/cli/src/daemon/manager.ts@@ -23,6 +23,7 @@ function getLogFilePath() {export interface DaemonStatus {connectionStatus: string;+ deviceId?: string;gatewayUrl: string;pid: number;startedAt: string;diff --git a/apps/cli/src/utils/device.ts b/apps/cli/src/utils/device.tsnew file mode 100644index 00000000000..a30186f47b9--- /dev/null+++ b/apps/cli/src/utils/device.ts@@ -0,0 +1,5 @@+import { readStatus } from '../daemon/manager';++export function resolveLocalDeviceId(): string | undefined {+ return readStatus()?.deviceId;+}diff --git a/packages/openapi/src/types/topic.type.ts b/packages/openapi/src/types/topic.type.tsindex cea65bd13e9..fed3a31e479 100644--- a/packages/openapi/src/types/topic.type.ts+++ b/packages/openapi/src/types/topic.type.ts@@ -59,6 +59,7 @@ export const TopicUpdateRequestSchema = z.object({.object({model: z.string().optional(),provider: z.string().optional(),+ boundDeviceId: z.string().optional(),workingDirectory: z.string().optional(),}).optional(),diff --git a/packages/types/src/agentExecution/index.ts b/packages/types/src/agentExecution/index.tsindex d5361fe818a..42e4f19492e 100644--- a/packages/types/src/agentExecution/index.ts+++ b/packages/types/src/agentExecution/index.ts@@ -28,6 +28,8 @@ export interface ExecAgentParams {appContext?: ExecAgentAppContext;/** Whether to auto-start execution after creating operation (default: true) */autoStart?: boolean;+ /** Explicit device ID to bind to the topic and activate for this run */+ deviceId?: string;/** Optional existing message IDs to include in context */existingMessageIds?: string[];/** Additional system instructions appended after the agent's own system role */diff --git a/packages/types/src/topic/topic.ts b/packages/types/src/topic/topic.tsindex add457b4e01..0403f019198 100644--- a/packages/types/src/topic/topic.ts+++ b/packages/types/src/topic/topic.ts@@ -42,6 +42,7 @@ export interface ChatTopicBotContext {export interface ChatTopicMetadata {bot?: ChatTopicBotContext;+ boundDeviceId?: string;/*** Cron job ID that triggered this topic creation (if created by scheduled task)*/diff --git a/src/routes/(main)/community/(detail)/skill/features/Details/index.tsx b/src/routes/(main)/community/(detail)/skill/features/Details/index.tsxindex ae33314c44d..8ce24785cb5 100644--- a/src/routes/(main)/community/(detail)/skill/features/Details/index.tsx+++ b/src/routes/(main)/community/(detail)/skill/features/Details/index.tsx@@ -64,4 +64,4 @@ const Details = memo<{ mobile?: boolean }>(({ mobile: isMobile }) => {);});-export default Details;\ No newline at end of file+export default Details;diff --git a/src/server/routers/lambda/__tests__/aiAgent.test.ts b/src/server/routers/lambda/__tests__/aiAgent.test.tsindex f3c398e5002..a92e36aa0d0 100644--- a/src/server/routers/lambda/__tests__/aiAgent.test.ts+++ b/src/server/routers/lambda/__tests__/aiAgent.test.ts@@ -165,6 +165,62 @@ describe('AI Agent Router Integration Tests', () => {expect(createdTopics[0].title!.length).toBeLessThanOrEqual(53); // 50 + '...'});+ it('should persist boundDeviceId when creating a topic with deviceId', async () => {+ const caller = aiAgentRouter.createCaller(createTestContext());++ const result = await caller.execAgent({+ agentId: testAgentId,+ deviceId: 'device-local-1',+ prompt: 'Hello, device!',+ });++ expect(result.success).toBe(true);++ const createdTopics = await serverDB+ .select()+ .from(topics)+ .where(eq(topics.agentId, testAgentId));++ expect(createdTopics).toHaveLength(1);+ expect(createdTopics[0].metadata).toEqual(+ expect.objectContaining({ boundDeviceId: 'device-local-1' }),+ );+ });++ it('should keep existing topic boundDeviceId when reusing a topic with deviceId', async () => {+ const caller = aiAgentRouter.createCaller(createTestContext());++ const [existingTopic] = await serverDB+ .insert(topics)+ .values({+ title: 'Existing Topic',+ agentId: testAgentId,+ metadata: { boundDeviceId: 'device-old' },+ sessionId: testSessionId,+ userId,+ })+ .returning();++ const result = await caller.execAgent({+ agentId: testAgentId,+ deviceId: 'device-new',+ prompt: 'Follow up question',+ appContext: {+ topicId: existingTopic.id,+ },+ });++ expect(result.success).toBe(true);++ const updatedTopic = await serverDB.query.topics.findFirst({+ where: eq(topics.id, existingTopic.id),+ });++ expect(updatedTopic?.metadata).toEqual(+ expect.objectContaining({ boundDeviceId: 'device-old' }),+ );+ });+it('should reuse existing topic when topicId is provided', async () => {const caller = aiAgentRouter.createCaller(createTestContext());diff --git a/src/server/routers/lambda/__tests__/integration/aiAgent/execAgents.integration.test.ts b/src/server/routers/lambda/__tests__/integration/aiAgent/execAgents.integration.test.tsindex 8d76f7a26d4..f946deacda7 100644--- a/src/server/routers/lambda/__tests__/integration/aiAgent/execAgents.integration.test.ts+++ b/src/server/routers/lambda/__tests__/integration/aiAgent/execAgents.integration.test.ts@@ -209,6 +209,42 @@ describe('Batch Execution (execAgents)', () => {expect(createdTopics.map((t) => t.title).sort()).toEqual(['Topic 1 prompt', 'Topic 2 prompt']);});+ it('should preserve deviceId bindings for batch tasks', async () => {+ mockResponsesCreate.mockResolvedValue(+ createMockResponsesAPIStream('Response for device-bound topics') as any,+ );++ const caller = aiAgentRouter.createCaller(createTestContext());++ await caller.execAgents({+ tasks: [+ {+ agentId: testAgentId,+ autoStart: false,+ deviceId: 'device-batch-1',+ prompt: 'Device-bound task 1',+ },+ {+ agentId: testAgentId,+ autoStart: false,+ deviceId: 'device-batch-2',+ prompt: 'Device-bound task 2',+ },+ ],+ });++ const createdTopics = await serverDB+ .select()+ .from(topics)+ .where(eq(topics.agentId, testAgentId));++ expect(createdTopics).toHaveLength(2);+ expect(createdTopics.map((topic) => topic.metadata?.boundDeviceId).sort()).toEqual([+ 'device-batch-1',+ 'device-batch-2',+ ]);+ });+it('should support autoStart for batch tasks', async () => {mockResponsesCreate.mockResolvedValue(createMockResponsesAPIStream('Auto start test') as any);diff --git a/src/server/routers/lambda/aiAgent.ts b/src/server/routers/lambda/aiAgent.tsindex 6e430d0b97b..552ed30136a 100644--- a/src/server/routers/lambda/aiAgent.ts+++ b/src/server/routers/lambda/aiAgent.ts@@ -91,6 +91,8 @@ const ExecAgentSchema = z.optional(),/** Whether to auto-start execution after creating operation */autoStart: z.boolean().optional().default(true),+ /** Explicit device ID to bind to the topic and activate for this run */+ deviceId: z.string().optional(),/** Optional existing message IDs to include in context */existingMessageIds: z.array(z.string()).optional().default([]),/** The user input/prompt */@@ -518,7 +520,15 @@ export const aiAgentRouter = router({}),execAgent: aiAgentProcedure.input(ExecAgentSchema).mutation(async ({ input, ctx }) => {- const { agentId, slug, prompt, appContext, autoStart = true, existingMessageIds = [] } = input;+ const {+ agentId,+ slug,+ prompt,+ appContext,+ autoStart = true,+ deviceId,+ existingMessageIds = [],+ } = input;log('execAgent: identifier=%s, prompt=%s', agentId || slug, prompt.slice(0, 50));@@ -527,6 +537,7 @@ export const aiAgentRouter = router({agentId,appContext,autoStart,+ deviceId,existingMessageIds,prompt,slug,@@ -567,13 +578,22 @@ export const aiAgentRouter = router({task: (typeof tasks)[number],taskIndex: number,): Promise<TaskResult> => {- const { agentId, slug, prompt, appContext, autoStart = true, existingMessageIds = [] } = task;+ const {+ agentId,+ slug,+ prompt,+ appContext,+ autoStart = true,+ deviceId,+ existingMessageIds = [],+ } = task;try {const result = await ctx.aiAgentService.execAgent({agentId,appContext,autoStart,+ deviceId,existingMessageIds,prompt,slug,diff --git a/src/server/routers/lambda/topic.ts b/src/server/routers/lambda/topic.tsindex fc3058ccf22..e4d9208d9a0 100644--- a/src/server/routers/lambda/topic.ts+++ b/src/server/routers/lambda/topic.ts@@ -558,6 +558,7 @@ export const topicRouter = router({metadata: z.object({model: z.string().optional(),provider: z.string().optional(),+ boundDeviceId: z.string().optional(),workingDirectory: z.string().optional(),}),}),diff --git a/src/server/services/aiAgent/__tests__/execAgent.device.test.ts b/src/server/services/aiAgent/__tests__/execAgent.device.test.tsindex 22ce935aca6..9fa26d774a1 100644--- a/src/server/services/aiAgent/__tests__/execAgent.device.test.ts+++ b/src/server/services/aiAgent/__tests__/execAgent.device.test.ts@@ -71,10 +71,13 @@ vi.mock('@/database/models/plugin', () => ({})),}));+const topicMock = {+ create: vi.fn().mockResolvedValue({ id: 'topic-1', metadata: undefined }),+ findById: vi.fn().mockResolvedValue(undefined),+ updateMetadata: vi.fn().mockResolvedValue(undefined),+};vi.mock('@/database/models/topic', () => ({- TopicModel: vi.fn().mockImplementation(() => ({- create: vi.fn().mockResolvedValue({ id: 'topic-1' }),- })),+ TopicModel: vi.fn().mockImplementation(() => topicMock),}));vi.mock('@/database/models/thread', () => ({@@ -139,6 +142,9 @@ describe('AiAgentService.execAgent - device auto-activation', () => {beforeEach(() => {vi.clearAllMocks();+ topicMock.create.mockResolvedValue({ id: 'topic-1', metadata: undefined });+ topicMock.findById.mockResolvedValue(undefined);+ topicMock.updateMetadata.mockResolvedValue(undefined);mockMessageCreate.mockResolvedValue({ id: 'msg-1' });mockCreateOperation.mockResolvedValue({autoStarted: true,@@ -324,6 +330,99 @@ describe('AiAgentService.execAgent - device auto-activation', () => {});});+ describe('topic and explicit device binding', () => {+ it('should prefer explicit deviceId over topic and agent bindings when online', async () => {+ mockDeviceProxy.isConfigured = true;+ mockDeviceProxy.queryDeviceList.mockResolvedValue([onlineDevice, onlineDevice2]);+ topicMock.findById.mockResolvedValue({ metadata: { boundDeviceId: 'device-002' } });++ const { AgentService } = await import('@/server/services/agent');+ vi.mocked(AgentService).mockImplementation(+ () =>+ ({+ getAgentConfig: vi.fn().mockResolvedValue({+ agencyConfig: { boundDeviceId: 'device-002' },+ chatConfig: {},+ files: [],+ id: 'agent-1',+ knowledgeBases: [],+ model: 'gpt-4',+ plugins: [],+ provider: 'openai',+ systemRole: 'You are a helpful assistant',+ }),+ }) as any,+ );++ service = new AiAgentService(mockDb, userId);++ await service.execAgent({+ agentId: 'agent-1',+ appContext: { topicId: 'topic-existing' },+ deviceId: 'device-001',+ prompt: 'Run a command',+ });++ const createOpArgs = mockCreateOperation.mock.calls[0][0];+ expect(createOpArgs.activeDeviceId).toBe('device-001');+ expect(topicMock.updateMetadata).not.toHaveBeenCalled();+ });++ it('should not reuse topic boundDeviceId when no explicit deviceId is provided', async () => {+ mockDeviceProxy.isConfigured = true;+ mockDeviceProxy.queryDeviceList.mockResolvedValue([onlineDevice, onlineDevice2]);+ topicMock.findById.mockResolvedValue({ metadata: { boundDeviceId: 'device-002' } });+ const { AgentService } = await import('@/server/services/agent');+ vi.mocked(AgentService).mockImplementation(+ () =>+ ({+ getAgentConfig: vi.fn().mockResolvedValue({+ chatConfig: {},+ files: [],+ id: 'agent-1',+ knowledgeBases: [],+ model: 'gpt-4',+ plugins: [],+ provider: 'openai',+ systemRole: 'You are a helpful assistant',+ }),+ }) as any,+ );++ service = new AiAgentService(mockDb, userId);++ await service.execAgent({+ agentId: 'agent-1',+ appContext: { topicId: 'topic-existing' },+ prompt: 'Run a command',+ });++ const createOpArgs = mockCreateOperation.mock.calls[0][0];+ expect(createOpArgs.activeDeviceId).toBeUndefined();+ });++ it('should keep explicit topic binding when the bound device is offline', async () => {+ mockDeviceProxy.isConfigured = true;+ mockDeviceProxy.queryDeviceList.mockResolvedValue([onlineDevice2]);++ service = new AiAgentService(mockDb, userId);++ await service.execAgent({+ agentId: 'agent-1',+ deviceId: 'device-001',+ prompt: 'Run a command',+ });++ const createOpArgs = mockCreateOperation.mock.calls[0][0];+ expect(createOpArgs.activeDeviceId).toBeUndefined();+ expect(topicMock.create).toHaveBeenCalledWith(+ expect.objectContaining({+ metadata: expect.objectContaining({ boundDeviceId: 'device-001' }),+ }),+ );+ });+ });+describe('gateway not configured', () => {it('should never set activeDeviceId when gateway is not configured', async () => {mockDeviceProxy.isConfigured = false;@@ -341,11 +440,86 @@ describe('AiAgentService.execAgent - device auto-activation', () => {});});+ describe('topic metadata binding', () => {+ it('should include requested deviceId when creating a new topic', async () => {+ mockDeviceProxy.isConfigured = true;+ mockDeviceProxy.queryDeviceList.mockResolvedValue([onlineDevice]);++ await service.execAgent({+ agentId: 'agent-1',+ deviceId: 'device-001',+ prompt: 'Run with device',+ });++ expect(topicMock.create).toHaveBeenCalled();+ const createArgs = topicMock.create.mock.calls[0][0];+ expect(createArgs.metadata?.boundDeviceId).toBe('device-001');+ const createOpArgs = mockCreateOperation.mock.calls[0][0];+ expect(createOpArgs.activeDeviceId).toBe('device-001');+ });++ it('should not reuse topic metadata bound device when no deviceId is supplied', async () => {+ mockDeviceProxy.isConfigured = true;+ mockDeviceProxy.queryDeviceList.mockResolvedValue([onlineDevice]);+ topicMock.findById.mockResolvedValue({+ id: 'topic-1',+ metadata: { boundDeviceId: 'device-001' },+ });++ await service.execAgent({+ agentId: 'agent-1',+ prompt: 'Use topic device',+ appContext: { topicId: 'topic-1' },+ });++ const createOpArgs = mockCreateOperation.mock.calls[0][0];+ expect(createOpArgs.activeDeviceId).toBeUndefined();+ });++ it('should not update topic metadata when a new deviceId is provided for existing topic', async () => {+ mockDeviceProxy.isConfigured = true;+ mockDeviceProxy.queryDeviceList.mockResolvedValue([onlineDevice2]);+ topicMock.findById.mockResolvedValue({+ id: 'topic-1',+ metadata: { boundDeviceId: 'device-old' },+ });++ await service.execAgent({+ agentId: 'agent-1',+ prompt: 'Switch device',+ appContext: { topicId: 'topic-1' },+ deviceId: 'device-002',+ });++ expect(topicMock.updateMetadata).not.toHaveBeenCalled();+ const createOpArgs = mockCreateOperation.mock.calls[0][0];+ expect(createOpArgs.activeDeviceId).toBe('device-002');+ });+ });+describe('Remote Device tool injection when device is auto-activated', () => {it('should mark autoActivated when single device is auto-activated (IM/Bot)', async () => {mockDeviceProxy.isConfigured = true;mockDeviceProxy.queryDeviceList.mockResolvedValue([onlineDevice]);+ const { AgentService } = await import('@/server/services/agent');+ vi.mocked(AgentService).mockImplementation(+ () =>+ ({+ getAgentConfig: vi.fn().mockResolvedValue({+ chatConfig: {},+ files: [],+ id: 'agent-1',+ knowledgeBases: [],+ model: 'gpt-4',+ plugins: [],+ provider: 'openai',+ systemRole: 'You are a helpful assistant',+ }),+ }) as any,+ );+ service = new AiAgentService(mockDb, userId);+await service.execAgent({agentId: 'agent-1',botContext: { platform: 'discord' } as any,@@ -353,6 +527,8 @@ describe('AiAgentService.execAgent - device auto-activation', () => {});const toolsEngineArgs = mockCreateServerAgentToolsEngine.mock.calls[0][1];+ const createOpArgs = mockCreateOperation.mock.calls[0][0];+ expect(createOpArgs.activeDeviceId).toBe('device-001');// Device auto-activated β Remote Device tool should be suppressedexpect(toolsEngineArgs.deviceContext.autoActivated).toBe(true);});diff --git a/src/server/services/aiAgent/__tests__/execAgent.threadId.test.ts b/src/server/services/aiAgent/__tests__/execAgent.threadId.test.tsindex 4d540cf35f5..3891c487124 100644--- a/src/server/services/aiAgent/__tests__/execAgent.threadId.test.ts+++ b/src/server/services/aiAgent/__tests__/execAgent.threadId.test.ts@@ -66,6 +66,8 @@ vi.mock('@/database/models/plugin', () => ({vi.mock('@/database/models/topic', () => ({TopicModel: vi.fn().mockImplementation(() => ({create: vi.fn().mockResolvedValue({ id: 'topic-1' }),+ findById: vi.fn().mockResolvedValue(undefined),+ updateMetadata: vi.fn().mockResolvedValue(undefined),})),}));diff --git a/src/server/services/aiAgent/__tests__/execAgent.topicHistory.test.ts b/src/server/services/aiAgent/__tests__/execAgent.topicHistory.test.tsindex 31d56e4342c..5b75ae4fee1 100644--- a/src/server/services/aiAgent/__tests__/execAgent.topicHistory.test.ts+++ b/src/server/services/aiAgent/__tests__/execAgent.topicHistory.test.ts@@ -64,6 +64,8 @@ vi.mock('@/database/models/plugin', () => ({vi.mock('@/database/models/topic', () => ({TopicModel: vi.fn().mockImplementation(() => ({create: vi.fn().mockResolvedValue({ id: 'topic-new' }),+ findById: vi.fn().mockResolvedValue(undefined),+ updateMetadata: vi.fn().mockResolvedValue(undefined),})),}));diff --git a/src/server/services/aiAgent/index.ts b/src/server/services/aiAgent/index.tsindex 3682a03e693..f40182176a5 100644--- a/src/server/services/aiAgent/index.ts+++ b/src/server/services/aiAgent/index.ts@@ -237,6 +237,7 @@ export class AiAgentService {appContext,autoStart = true,botContext,+ deviceId: requestedDeviceId,botPlatformContext,discordContext,existingMessageIds = [],@@ -402,15 +403,21 @@ export class AiAgentService {// 3. Handle topic creation: if no topicId provided, create a new topic; otherwise reuse existinglet topicId = appContext?.topicId;+ const topicBoundDeviceId = requestedDeviceId;if (!topicId) {if (resume) {throw new Error('Resume mode requires the parent message to belong to a topic');}- // Prepare metadata with cronJobId, taskId, and botContext if provided+ // Prepare metadata with cronJobId, taskId, botContext, and bound device if providedconst metadata =- cronJobId || taskId || botContext- ? { bot: botContext, cronJobId: cronJobId || undefined, taskId: taskId || undefined }+ cronJobId || taskId || botContext || requestedDeviceId+ ? {+ bot: botContext,+ boundDeviceId: requestedDeviceId,+ cronJobId: cronJobId || undefined,+ taskId: taskId || undefined,+ }: undefined;const newTopic = await this.topicModel.create({@@ -530,7 +537,8 @@ export class AiAgentService {// Build device context for ToolsEngine enableCheckerconst gatewayConfigured = deviceProxy.isConfigured;- const boundDeviceId = agentConfig.agencyConfig?.boundDeviceId;+ const agentBoundDeviceId = agentConfig.agencyConfig?.boundDeviceId;+ const boundDeviceId = topicBoundDeviceId || agentBoundDeviceId;if (gatewayConfigured) {try {onlineDevices = await deviceProxy.queryDeviceList(this.userId);@@ -554,9 +562,13 @@ export class AiAgentService {...(isBotConversation ? [MessageToolIdentifier] : []),];- // Derive activeDeviceId from device context+ // Derive activeDeviceId from device context:+ // 1. If this run explicitly requested a device and that device is online, use it+ // 2. Otherwise, if the current topic has a bound device and it is online, use that+ // 3. Otherwise, fall back to the agent-level bound device when it is online+ // 4. Otherwise, in IM/Bot scenarios, auto-activate only when exactly one device is onlineactiveDeviceId = boundDeviceId- ? deviceOnline+ ? onlineDevices.some((device) => device.deviceId === boundDeviceId)? boundDeviceId: undefined: (discordContext || botContext) && onlineDevices.length === 1diff --git a/src/services/aiAgent.ts b/src/services/aiAgent.tsindex 5fef4e8c80a..7f838ac57b2 100644--- a/src/services/aiAgent.ts+++ b/src/services/aiAgent.ts@@ -10,6 +10,7 @@ export interface ExecAgentTaskParams {topicId?: string | null;};autoStart?: boolean;+ deviceId?: string;existingMessageIds?: string[];prompt: string;slug?: string;diff --git a/src/services/topic/index.ts b/src/services/topic/index.tsindex 616e5fccb5f..ed5d9d91114 100644--- a/src/services/topic/index.ts+++ b/src/services/topic/index.ts@@ -80,7 +80,12 @@ export class TopicService {updateTopicMetadata = (id: string,- metadata: { model?: string; provider?: string; workingDirectory?: string },+ metadata: {+ model?: string;+ provider?: string;+ workingDirectory?: string;+ boundDeviceId?: string;+ },) => {return lambdaClient.topic.updateTopicMetadata.mutate({ id, metadata });};