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.

✨ feat(cli): dispatch to a new conversation with `lh topic send --new` / `lh message send` (#21965)

Arvin Xu93ea1ee63c03
diff --git a/apps/cli/src/commands/message.ts b/apps/cli/src/commands/message.ts
index 9ff8c415d96..019e8630349 100644
--- a/apps/cli/src/commands/message.ts
+++ b/apps/cli/src/commands/message.ts
@@ -15,6 +15,7 @@ import { log } from '../utils/logger';
import type { TimeWindow } from '../utils/timeWindow';
import { parseTimeWindow, TIME_POINT_HELP } from '../utils/timeWindow';
import { registerMessageReplyCommand } from './message/reply';
+import { registerMessageSendCommand } from './message/send';
import { resolveUrlBuilder, resourcePath, withUrls } from './resourceUrl';
interface MessageSearchOptions {
@@ -406,7 +407,7 @@ export function registerMessageCommand(program: Command) {
message
.command('create')
.description(
- "Write a message row without running anything: no agent sees or answers it. To have another conversation's agent act on a message, use 'lh topic send'",
+ "Write a message row without running anything: no agent sees or answers it. To have an agent act on a message, use 'lh message send' or 'lh topic send'",
)
.requiredOption('-r, --role <role>', 'Message role (user, assistant, system)')
.requiredOption('-c, --content <content>', 'Message content')
@@ -624,4 +625,5 @@ export function registerMessageCommand(program: Command) {
});
registerMessageReplyCommand(message);
+ registerMessageSendCommand(message);
}
diff --git a/apps/cli/src/commands/message/send.ts b/apps/cli/src/commands/message/send.ts
new file mode 100644
index 00000000000..ec4da3db669
--- /dev/null
+++ b/apps/cli/src/commands/message/send.ts
@@ -0,0 +1,65 @@
+import type { Command } from 'commander';
+
+import { getTrpcClient } from '../../api/client';
+import { resolveWorkspaceRef } from '../../api/workspaceRef';
+import {
+ NEW_CONVERSATION_OPTIONS_HELP,
+ type NewConversationOptions,
+ reportConversationSend,
+ sendToConversation,
+ sendToNewConversation,
+} from '../topic/send';
+
+/**
+ * `lh message send`: the message-first spelling of `lh topic send`. With
+ * `--topic-id` the message goes to that conversation; without it, a new
+ * conversation is opened for it.
+ */
+export function registerMessageSendCommand(message: Command) {
+ message
+ .command('send')
+ .description(
+ "Send a message and have an agent act on it: to an existing conversation with --topic-id (queued if it is busy), otherwise to a new one. Unlike 'lh message create', this wakes the agent",
+ )
+ .requiredOption('-c, --content <content>', 'Message content')
+ .option('--topic-id <id>', 'Conversation to send to; omit to open a new conversation')
+ .option('--agent-id <id>', `New conversation only: ${NEW_CONVERSATION_OPTIONS_HELP.agentId}`)
+ .option('--device <target>', `New conversation only: ${NEW_CONVERSATION_OPTIONS_HELP.device}`)
+ .option('--title <title>', `New conversation only: ${NEW_CONVERSATION_OPTIONS_HELP.title}`)
+ .option(
+ '--workspace <id|slug>',
+ "The workspace to send in (overrides LOBEHUB_WORKSPACE_ID and 'workspace use')",
+ )
+ .option('--json', 'Output JSON')
+ .addHelpText(
+ 'after',
+ `
+Examples:
+ lh message send --topic-id tpc_xxx -c "Iterate the verifier with these notes"
+ lh message send -c "Draft the release notes" --device local --title "Release notes"
+
+Same delivery as 'lh topic send': run by an agent, the message is shown as
+written by that agent, and the receiver answers with 'lh message reply'.`,
+ )
+ .action(
+ async (
+ options: NewConversationOptions & {
+ content: string;
+ json?: boolean;
+ topicId?: string;
+ workspace?: string;
+ },
+ ) => {
+ const client = await getTrpcClient(await resolveWorkspaceRef(options.workspace));
+ await reportConversationSend(() => {
+ if (!options.topicId) return sendToNewConversation(client, { ...options });
+ if (options.agentId || options.device || options.title) {
+ throw new Error(
+ '--agent-id, --device and --title only apply to a new conversation; drop --topic-id to open one.',
+ );
+ }
+ return sendToConversation(client, { content: options.content, topicId: options.topicId });
+ }, options);
+ },
+ );
+}
diff --git a/apps/cli/src/commands/topic/send.newConversation.test.ts b/apps/cli/src/commands/topic/send.newConversation.test.ts
new file mode 100644
index 00000000000..390a5af06f8
--- /dev/null
+++ b/apps/cli/src/commands/topic/send.newConversation.test.ts
@@ -0,0 +1,212 @@
+import { Command } from 'commander';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { log } from '../../utils/logger';
+import { registerMessageSendCommand } from '../message/send';
+import { registerTopicSendCommand } from './send';
+
+const { client, mockGetTrpcClient, mockResolveLocalDeviceId } = vi.hoisted(() => ({
+ client: {
+ agentSteerQueue: { append: { mutate: vi.fn() } },
+ aiAgent: { execAgent: { mutate: vi.fn() } },
+ device: { listDevices: { query: vi.fn() } },
+ topic: { getTopicDetail: { query: vi.fn() } },
+ },
+ mockGetTrpcClient: vi.fn(),
+ mockResolveLocalDeviceId: vi.fn(),
+}));
+
+vi.mock('../../api/client', () => ({ getTrpcClient: mockGetTrpcClient }));
+vi.mock('../../api/workspaceRef', () => ({ resolveWorkspaceRef: vi.fn(async () => undefined) }));
+vi.mock('../../utils/device', () => ({ resolveLocalDeviceId: mockResolveLocalDeviceId }));
+
+const run = async (...args: string[]) => {
+ const program = new Command();
+ program.exitOverride();
+ registerTopicSendCommand(program.command('topic'));
+ registerMessageSendCommand(program.command('message'));
+ await program.parseAsync(['node', 'lh', ...args]);
+};
+
+const errorLogged = () =>
+ vi
+ .mocked(log.error)
+ .mock.calls.map(([message]) => message)
+ .join('\n');
+
+describe('sending into a new conversation', () => {
+ let exit: ReturnType<typeof vi.spyOn>;
+ let logged: string[];
+
+ beforeEach(() => {
+ vi.stubEnv('LOBEHUB_AGENT_ID', 'agt-self');
+ vi.stubEnv('LOBEHUB_OPERATION_ID', 'op-sender');
+ vi.stubEnv('LOBEHUB_TOPIC_ID', 'tpc-here');
+ mockGetTrpcClient.mockResolvedValue(client);
+ client.aiAgent.execAgent.mutate.mockResolvedValue({
+ operationId: 'op-new',
+ success: true,
+ topicId: 'tpc-new',
+ });
+ client.device.listDevices.query.mockResolvedValue([
+ { deviceId: 'dev-mac', online: true },
+ { deviceId: 'dev-off', online: false },
+ ]);
+ mockResolveLocalDeviceId.mockReturnValue('dev-mac');
+ logged = [];
+ vi.spyOn(console, 'log').mockImplementation((...parts) => {
+ logged.push(parts.join(' '));
+ });
+ exit = vi.spyOn(process, 'exit').mockImplementation((() => undefined) as never);
+ });
+
+ afterEach(() => {
+ vi.mocked(log.error).mockClear();
+ vi.unstubAllEnvs();
+ vi.restoreAllMocks();
+ Object.values(client).forEach((router) =>
+ Object.values(router).forEach((procedure) =>
+ Object.values(procedure).forEach((fn) => (fn as any).mockReset()),
+ ),
+ );
+ });
+
+ it('opens a new conversation of the calling agent, authored by the sending run', async () => {
+ await run('topic', 'send', '--new', '-c', 'Draft the release notes', '--json');
+
+ expect(client.aiAgent.execAgent.mutate).toHaveBeenCalledWith({
+ agentId: 'agt-self',
+ prompt: 'Draft the release notes',
+ sourceOperationId: 'op-sender',
+ trigger: 'cli',
+ userInterventionConfig: { approvalMode: 'headless' },
+ });
+ // No topic is named, so nothing is queued and no existing topic is read.
+ expect(client.agentSteerQueue.append.mutate).not.toHaveBeenCalled();
+ expect(client.topic.getTopicDetail.query).not.toHaveBeenCalled();
+ expect(JSON.parse(logged[0])).toEqual({
+ agentId: 'agt-self',
+ delivery: 'created',
+ operationId: 'op-new',
+ topicId: 'tpc-new',
+ });
+ });
+
+ it('runs the new conversation on the named device, with the given agent and title', async () => {
+ await run(
+ 'topic',
+ 'send',
+ '--new',
+ '-c',
+ 'Check the build',
+ '--agent-id',
+ 'agt-builder',
+ '--device',
+ 'local',
+ '--title',
+ 'Build check',
+ );
+
+ expect(client.aiAgent.execAgent.mutate).toHaveBeenCalledWith(
+ expect.objectContaining({
+ agentId: 'agt-builder',
+ deviceId: 'dev-mac',
+ title: 'Build check',
+ }),
+ );
+ });
+
+ it('refuses an offline or unknown device instead of running elsewhere', async () => {
+ await run('topic', 'send', '--new', '-c', 'x', '--device', 'dev-off');
+ await run('topic', 'send', '--new', '-c', 'x', '--device', 'dev-gone');
+
+ expect(client.aiAgent.execAgent.mutate).not.toHaveBeenCalled();
+ expect(exit).toHaveBeenCalledTimes(2);
+ expect(errorLogged()).toContain('"dev-off" is not online');
+ expect(errorLogged()).toContain('"dev-gone" was not found');
+ });
+
+ // ROOT CAUSE:
+ //
+ // A workspace agent with a fixed execution target always runs on that target;
+ // the server dropped a requested device for it, and the CLI still reported a
+ // send to that machine. Whether the policy applies depends on the caller's
+ // effective config (owners and private agents are exempt), which only the
+ // server knows.
+ //
+ // Before: --device was a preference the fixed target silently overrode.
+ // After: the CLI requires the device and the server refuses instead.
+ it('requires the device, and surfaces the server refusing one the agent would ignore', async () => {
+ client.aiAgent.execAgent.mutate.mockRejectedValueOnce(
+ Object.assign(
+ new Error(
+ 'This agent always runs on its configured execution target, so device dev-mac would be ignored.',
+ ),
+ { data: { code: 'PRECONDITION_FAILED' } },
+ ),
+ );
+
+ await run('message', 'send', '-c', 'x', '--device', 'local');
+
+ expect(client.aiAgent.execAgent.mutate).toHaveBeenCalledWith(
+ expect.objectContaining({ deviceId: 'dev-mac', requireDevice: true }),
+ );
+ expect(exit).toHaveBeenCalledWith(1);
+ expect(errorLogged()).toContain('would be ignored');
+ });
+
+ it('does not require a device it was not given', async () => {
+ await run('topic', 'send', '--new', '-c', 'x');
+
+ expect(client.aiAgent.execAgent.mutate.mock.calls[0][0]).not.toHaveProperty('requireDevice');
+ });
+
+ it('needs exactly one of a topic id and --new, and keeps new-only options off existing topics', async () => {
+ await run('topic', 'send', 'tpc-target', '--new', '-c', 'x');
+ await run('topic', 'send', '-c', 'x');
+ await run('topic', 'send', 'tpc-target', '-c', 'x', '--device', 'local');
+
+ expect(client.aiAgent.execAgent.mutate).not.toHaveBeenCalled();
+ expect(exit).toHaveBeenCalledTimes(3);
+ });
+
+ it('asks for an agent when none is running this command', async () => {
+ vi.stubEnv('LOBEHUB_AGENT_ID', '');
+
+ await run('topic', 'send', '--new', '-c', 'x');
+
+ expect(client.aiAgent.execAgent.mutate).not.toHaveBeenCalled();
+ expect(errorLogged()).toContain('--agent-id');
+ });
+
+ describe('lh message send', () => {
+ it('opens a new conversation without --topic-id', async () => {
+ await run('message', 'send', '-c', 'Draft the release notes', '--title', 'Notes');
+
+ expect(client.aiAgent.execAgent.mutate).toHaveBeenCalledWith(
+ expect.objectContaining({ agentId: 'agt-self', title: 'Notes' }),
+ );
+ expect(client.agentSteerQueue.append.mutate).not.toHaveBeenCalled();
+ });
+
+ it('sends to the conversation named with --topic-id, like topic send', async () => {
+ client.topic.getTopicDetail.query.mockResolvedValue({ agentId: 'agt-target' });
+ client.agentSteerQueue.append.mutate.mockResolvedValue({ id: 'q-1', queued: true });
+
+ await run('message', 'send', '--topic-id', 'tpc-target', '-c', 'hello', '--json');
+
+ expect(client.agentSteerQueue.append.mutate).toHaveBeenCalledWith({
+ id: expect.any(String),
+ request: expect.objectContaining({ agentId: 'agt-target', prompt: 'hello' }),
+ });
+ expect(JSON.parse(logged[0])).toMatchObject({ delivery: 'queued', topicId: 'tpc-target' });
+ });
+
+ it('keeps new-conversation options off an existing conversation', async () => {
+ await run('message', 'send', '--topic-id', 'tpc-target', '-c', 'x', '--title', 'T');
+
+ expect(client.topic.getTopicDetail.query).not.toHaveBeenCalled();
+ expect(exit).toHaveBeenCalledWith(1);
+ });
+ });
+});
diff --git a/apps/cli/src/commands/topic/send.ts b/apps/cli/src/commands/topic/send.ts
index 293f2c705db..ecaec2e3dde 100644
--- a/apps/cli/src/commands/topic/send.ts
+++ b/apps/cli/src/commands/topic/send.ts
@@ -6,6 +6,7 @@ import pc from 'picocolors';
import type { TrpcClient } from '../../api/client';
import { getTrpcClient } from '../../api/client';
import { resolveWorkspaceRef } from '../../api/workspaceRef';
+import { resolveLocalDeviceId } from '../../utils/device';
import { outputJson } from '../../utils/format';
import { log } from '../../utils/logger';
@@ -14,8 +15,12 @@ const MAX_DELIVERY_ATTEMPTS = 3;
export interface ConversationSendResult {
agentId: string;
- /** Started a run of the conversation's agent (`started`), or queued behind its running turn. */
- delivery: 'queued' | 'started';
+ /**
+ * Opened a new conversation and started its agent (`created`), started a run
+ * of an existing conversation's agent (`started`), or queued behind its
+ * running turn (`queued`).
+ */
+ delivery: 'created' | 'queued' | 'started';
operationId?: string;
threadId?: string;
topicId: string;
@@ -112,6 +117,116 @@ export const sendToConversation = async (
};
};
+/**
+ * The device a new conversation runs on: an id from `lh device list`, or
+ * `local` for the device this CLI is connected as. It has to be online β€” a run
+ * is never moved to another machine behind the caller's back.
+ *
+ * @throws with a message fit for the user when the device cannot be used
+ */
+const resolveTargetDevice = async (client: TrpcClient, device: string): Promise<string> => {
+ const deviceId = device === 'local' ? resolveLocalDeviceId() : device;
+ if (!deviceId) {
+ throw new Error(
+ "No local device found. Run 'lh connect' first, then retry with --device local.",
+ );
+ }
+
+ const devices = (await client.device.listDevices.query()) as {
+ deviceId?: string;
+ online?: boolean;
+ }[];
+ const matched = devices.find((candidate) => candidate.deviceId === deviceId);
+ if (!matched) {
+ throw new Error(`Device "${deviceId}" was not found. Check 'lh device list' and try again.`);
+ }
+ if (!matched.online) {
+ throw new Error(
+ 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.`,
+ );
+ }
+ return deviceId;
+};
+
+/**
+ * Dispatch a message into a NEW conversation of an agent β€” the calling agent
+ * itself by default β€” and start that agent on it: handing work to a fresh
+ * conversation the way `sendToConversation` hands it to an existing one, with
+ * the same authorship, reply route and relay bound. With a device the
+ * conversation is bound to it, so its later turns run there too.
+ *
+ * @throws with a message fit for the user when the send is refused
+ */
+export const sendToNewConversation = async (
+ client: TrpcClient,
+ params: {
+ agentId?: string;
+ content: string;
+ device?: string;
+ title?: string;
+ },
+): Promise<ConversationSendResult> => {
+ const agentId = params.agentId ?? process.env.LOBEHUB_AGENT_ID;
+ if (!agentId) {
+ throw new Error(
+ 'No agent to start the new conversation with: pass --agent-id (LOBEHUB_AGENT_ID is not set).',
+ );
+ }
+
+ const request: Record<string, any> = {
+ agentId,
+ prompt: params.content,
+ trigger: 'cli',
+ // Nobody is at the new conversation's composer to approve tool calls.
+ userInterventionConfig: { approvalMode: 'headless' },
+ };
+ if (params.device) {
+ request.deviceId = await resolveTargetDevice(client, params.device);
+ // The server refuses (nothing written) when the agent's effective execution
+ // target would drop the device, instead of running the work elsewhere.
+ request.requireDevice = true;
+ }
+ if (params.title) request.title = params.title;
+ const sourceOperationId = process.env.LOBEHUB_OPERATION_ID;
+ if (sourceOperationId) request.sourceOperationId = sourceOperationId;
+
+ const started = (await client.aiAgent.execAgent.mutate(request as any)) as {
+ error?: string;
+ operationId?: string;
+ success?: boolean;
+ topicId?: string;
+ };
+ if (!started.success || !started.topicId) {
+ throw new Error(
+ `Failed to start a new conversation of ${agentId}: ${started.error || 'unknown error'}`,
+ );
+ }
+
+ return {
+ agentId,
+ delivery: 'created',
+ operationId: started.operationId,
+ topicId: started.topicId,
+ };
+};
+
+/** Options shared by the commands that send into a new conversation. */
+export interface NewConversationOptions {
+ agentId?: string;
+ device?: string;
+ title?: string;
+}
+
+export const NEW_CONVERSATION_OPTIONS_HELP = {
+ agentId:
+ 'Agent of the new conversation (default: the agent running this command, LOBEHUB_AGENT_ID)',
+ device:
+ 'Device the new conversation runs on β€” an id from `lh device list`, or "local" for this machine; later turns stay on it',
+ title: 'Title of the new conversation (default: taken from the message)',
+};
+
/** Print a send's outcome, or the reason it was refused, and set the exit code. */
export const reportConversationSend = async (
send: () => Promise<ConversationSendResult>,
@@ -132,9 +247,11 @@ export const reportConversationSend = async (
}
console.log(
- result.delivery === 'started'
- ? `${pc.green('βœ“')} Sent to ${pc.bold(result.topicId)}; its agent is working on it (operation ${pc.dim(result.operationId ?? 'n/a')}).`
- : `${pc.green('βœ“')} Sent to ${pc.bold(result.topicId)}; it is busy, so its agent takes the message right after the current turn.`,
+ result.delivery === 'created'
+ ? `${pc.green('βœ“')} Opened ${pc.bold(result.topicId)}; its agent is working on it (operation ${pc.dim(result.operationId ?? 'n/a')}).`
+ : result.delivery === 'started'
+ ? `${pc.green('βœ“')} Sent to ${pc.bold(result.topicId)}; its agent is working on it (operation ${pc.dim(result.operationId ?? 'n/a')}).`
+ : `${pc.green('βœ“')} Sent to ${pc.bold(result.topicId)}; it is busy, so its agent takes the message right after the current turn.`,
);
console.log(
pc.dim(
@@ -145,11 +262,15 @@ export const reportConversationSend = async (
export function registerTopicSendCommand(topic: Command) {
topic
- .command('send <topicId>')
+ .command('send [topicId]')
.description(
- "Send a message to another conversation and have its agent act on it (queued if it is busy). Unlike 'lh message create', this wakes the agent",
+ "Send a message to another conversation and have its agent act on it (queued if it is busy), or with --new hand it to a new conversation. Unlike 'lh message create', this wakes the agent",
)
.requiredOption('-c, --content <content>', 'Message content')
+ .option('--new', 'Open a new conversation for the message instead of sending to <topicId>')
+ .option('--agent-id <id>', `With --new: ${NEW_CONVERSATION_OPTIONS_HELP.agentId}`)
+ .option('--device <target>', `With --new: ${NEW_CONVERSATION_OPTIONS_HELP.device}`)
+ .option('--title <title>', `With --new: ${NEW_CONVERSATION_OPTIONS_HELP.title}`)
.option(
'--workspace <id|slug>',
"The workspace the topic lives in (overrides LOBEHUB_WORKSPACE_ID and 'workspace use')",
@@ -158,18 +279,41 @@ export function registerTopicSendCommand(topic: Command) {
.addHelpText(
'after',
`
+Examples:
+ lh topic send tpc_xxx -c "Iterate the verifier with these notes"
+ lh topic send --new -c "Draft the release notes" --device local --title "Release notes"
+
Run by an agent, the message is shown as written by that agent, and the
receiving agent can answer it with 'lh message reply <messageId>', which wakes
the sending conversation. Agents that keep sending to each other are stopped
after a few rounds, so a person can step in.`,
)
.action(
- async (topicId: string, options: { content: string; json?: boolean; workspace?: string }) => {
+ async (
+ topicId: string | undefined,
+ options: NewConversationOptions & {
+ content: string;
+ json?: boolean;
+ new?: boolean;
+ workspace?: string;
+ },
+ ) => {
const client = await getTrpcClient(await resolveWorkspaceRef(options.workspace));
- await reportConversationSend(
- () => sendToConversation(client, { content: options.content, topicId }),
- options,
- );
+ await reportConversationSend(() => {
+ if (options.new) {
+ if (topicId) throw new Error('Pass either <topicId> or --new, not both.');
+ return sendToNewConversation(client, { ...options });
+ }
+ if (!topicId) {
+ throw new Error('Pass the <topicId> to send to, or --new to open a new conversation.');
+ }
+ if (options.agentId || options.device || options.title) {
+ throw new Error(
+ '--agent-id, --device and --title only apply with --new; an existing conversation keeps its own.',
+ );
+ }
+ return sendToConversation(client, { content: options.content, topicId });
+ }, options);
},
);
}
diff --git a/apps/server/src/routers/lambda/__tests__/aiAgent.topicTitle.test.ts b/apps/server/src/routers/lambda/__tests__/aiAgent.topicTitle.test.ts
new file mode 100644
index 00000000000..a93d9ed0974
--- /dev/null
+++ b/apps/server/src/routers/lambda/__tests__/aiAgent.topicTitle.test.ts
@@ -0,0 +1,204 @@
+// @vitest-environment node
+import { type LobeChatDatabase } from '@lobechat/database';
+import { agents, topics } from '@lobechat/database/schemas';
+import { getTestDB } from '@lobechat/database/test-utils';
+import { eq } from 'drizzle-orm';
+import type * as ModelBankModule from 'model-bank';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type * as InternalJwtModule from '@/libs/trpc/utils/internalJwt';
+import { AiAgentService } from '@/server/services/aiAgent';
+
+import { aiAgentRouter } from '../aiAgent';
+import { cleanupTestUser, createTestUser } from './integration/setup';
+
+// Mock getServerDB to return our test database instance
+let testDB: LobeChatDatabase;
+vi.mock('@/database/core/db-adaptor', () => ({
+ getServerDB: vi.fn(function () {
+ return testDB;
+ }),
+}));
+
+// Mock AgentRuntimeService since we only want to test the router's business logic
+vi.mock('@/server/services/agentRuntime', () => ({
+ AgentRuntimeService: vi.fn().mockImplementation(function () {
+ return {
+ createOperation: vi.fn(async (params: any) => {
+ // The real runtime invokes this before the run's first step, with the
+ // operation it is about to start; mirror it so the router's Task-run
+ // reopen path runs when a test seeds a Task run. It is a no-op for the
+ // ordinary conversation, which attaches no hooks.
+ await params?.onOperationCreated?.(params?.operationId);
+ return {
+ success: true,
+ operationId: params?.operationId ?? 'mock-operation-id',
+ autoStarted: true,
+ messageId: 'mock-message-id',
+ };
+ }),
+ };
+ }),
+}));
+
+// Mock serverMessagesEngine
+vi.mock('@/server/modules/Mecha', () => ({
+ createServerAgentToolsEngine: vi.fn(function () {
+ return {
+ generateToolsDetailed: vi.fn(function () {
+ return { tools: [] };
+ }),
+ getEnabledPluginManifests: vi.fn(function () {
+ return new Map();
+ }),
+ };
+ }),
+ serverMessagesEngine: vi.fn().mockResolvedValue({
+ messages: [
+ { role: 'system', content: 'You are a helpful assistant.' },
+ { role: 'user', content: 'Hello' },
+ ],
+ metadata: {},
+ }),
+}));
+
+// Mock AiChatService to avoid S3 dependency
+vi.mock('@/server/services/aiChat', () => ({
+ AiChatService: vi.fn().mockImplementation(function () {
+ return {
+ getMessagesAndTopics: vi.fn().mockResolvedValue({ messages: [], topics: [] }),
+ };
+ }),
+}));
+
+// Mock FileService to avoid S3 dependency
+vi.mock('@/server/services/file', () => ({
+ FileService: vi.fn().mockImplementation(function () {
+ return {
+ getFullFileUrl: vi.fn(function (path: string | null) {
+ return path;
+ }),
+ };
+ }),
+}));
+
+// Mock the resource-permission guard so workspace-mode tests can assert the
+// router resolves slug β†’ agent id and runs the `use` guard (the guard's own
+// RBAC evaluation is covered by its service tests).
+vi.mock('@/server/services/resourcePermission', () => ({
+ assertCanPerformResourceAction: vi.fn(),
+ getResourceMeta: vi.fn(),
+}));
+
+// The user-hub token is a real RS256 signature in production; the integration
+// DB has no JWKS_KEY, so pin the signer and assert the subject it is asked for.
+const mockSignUserJWT = vi.fn();
+vi.mock('@/libs/trpc/utils/internalJwt', async (importOriginal) => ({
+ ...(await importOriginal<typeof InternalJwtModule>()),
+ signUserJWT: (...args: any[]) => mockSignUserJWT(...args),
+}));
+
+// Mock model-bank with dynamic import to preserve other exports
+vi.mock('model-bank', async (importOriginal) => {
+ const actual = await importOriginal<typeof ModelBankModule>();
+ return {
+ ...actual,
+ LOBE_DEFAULT_MODEL_LIST: [
+ {
+ id: 'gpt-4o-mini',
+ providerId: 'openai',
+ abilities: { functionCall: true, vision: true, video: false },
+ },
+ ],
+ };
+});
+
+describe('aiAgent router - topic title', () => {
+ let serverDB: LobeChatDatabase;
+ let userId: string;
+ let agentId: string;
+
+ beforeEach(async () => {
+ serverDB = await getTestDB();
+ testDB = serverDB;
+ userId = await createTestUser(serverDB);
+ const [agent] = await serverDB
+ .insert(agents)
+ .values({
+ model: 'gpt-4o-mini',
+ provider: 'openai',
+ systemRole: 'You are a helpful assistant.',
+ title: 'Writer',
+ userId,
+ })
+ .returning();
+ agentId = agent.id;
+ });
+
+ afterEach(async () => {
+ await cleanupTestUser(serverDB, userId);
+ vi.restoreAllMocks();
+ });
+
+ const caller = () => aiAgentRouter.createCaller({ jwtPayload: { userId }, userId });
+ const titleOf = async (topicId: string) =>
+ (await serverDB.select({ title: topics.title }).from(topics).where(eq(topics.id, topicId)))[0]
+ ?.title;
+
+ it('names the topic a send creates', async () => {
+ const result = await caller().execAgent({
+ agentId,
+ prompt: 'Draft the release notes for this week, section by section',
+ title: 'Release notes',
+ });
+
+ expect(await titleOf(result.topicId!)).toBe('Release notes');
+ });
+
+ it('keeps naming a new topic after the prompt without a title', async () => {
+ const result = await caller().execAgent({ agentId, prompt: 'Draft the release notes' });
+
+ expect(await titleOf(result.topicId!)).toBe('Draft the release notes');
+ });
+
+ it('leaves an existing topic its own title', async () => {
+ const [topic] = await serverDB
+ .insert(topics)
+ .values({ agentId, title: 'Original', userId })
+ .returning();
+
+ await caller().execAgent({
+ agentId,
+ appContext: { topicId: topic.id },
+ prompt: 'Continue',
+ title: 'Renamed',
+ });
+
+ expect(await titleOf(topic.id)).toBe('Original');
+ });
+
+ // The title and a required device travel router β†’ composerRun β†’ service; a
+ // field dropped (or misplaced) in between would leave the service-level
+ // tests green while the route never honours it.
+ it('forwards the title and a required device to the run', async () => {
+ // Only the hand-off is under test: the device is not online here, and the
+ // service would (rightly) refuse to run without it.
+ const spy = vi
+ .spyOn(AiAgentService.prototype, 'execAgent')
+ .mockResolvedValue({ operationId: 'op-1', success: true, topicId: 'tpc-1' } as any);
+
+ await caller().execAgent({
+ agentId,
+ deviceId: 'device-001',
+ prompt: 'Run it there',
+ requireDevice: true,
+ title: 'On the Mac',
+ });
+
+ expect(spy.mock.calls[0][0]).toMatchObject({
+ deviceId: 'device-001',
+ requireDevice: true,
+ title: 'On the Mac',
+ });
+ });
+});
diff --git a/apps/server/src/routers/lambda/agentSteerQueue.ts b/apps/server/src/routers/lambda/agentSteerQueue.ts
index 2bbc94d7678..b52ba6c6f5b 100644
--- a/apps/server/src/routers/lambda/agentSteerQueue.ts
+++ b/apps/server/src/routers/lambda/agentSteerQueue.ts
@@ -45,8 +45,10 @@ const QueuedRequestSchema = ExecAgentFieldsSchema.omit({
resumeApproval: true,
resumeApprovals: true,
resumeToolResult: true,
+ requireDevice: true,
steer: true,
supersedeLiveRun: true,
+ title: true,
}).refine((data) => data.agentId || data.slug, {
message: 'Either agentId or slug must be provided',
});
diff --git a/apps/server/src/routers/lambda/aiAgent/exec.ts b/apps/server/src/routers/lambda/aiAgent/exec.ts
index 507f1d6b2d7..02674fd784c 100644
--- a/apps/server/src/routers/lambda/aiAgent/exec.ts
+++ b/apps/server/src/routers/lambda/aiAgent/exec.ts
@@ -18,6 +18,7 @@ import { unwrapPgError } from '@/server/modules/AgentRuntime/pgError';
import { toClientExecAgentResult } from '@/server/routers/lambda/_helpers/groupMemberContinuationResult';
import { assertCanUseWorkspaceAgent } from '@/server/routers/lambda/_helpers/workspaceAgentGuard';
import { startComposerRun } from '@/server/services/aiAgent/composerRun';
+import { RequestedDeviceIgnoredError } from '@/server/services/aiAgent/pipeline/turnSetup';
import { AgentRelayHopLimitError } from '@/server/services/aiAgent/sourceAttribution';
import { TopicStartReservationError } from '@/server/services/aiAgent/topicStartReservation';
@@ -304,6 +305,12 @@ export const execRouter = router({
});
}
+ // A device the caller required would be dropped by the agent's fixed
+ // execution target; nothing was written.
+ if (error instanceof RequestedDeviceIgnoredError) {
+ throw new TRPCError({ cause: error, code: 'PRECONDITION_FAILED', message: error.message });
+ }
+
// An agent β†’ agent send past the relay bound: the sending agent has to
// hand back to a person, so the reason travels to it verbatim.
if (error instanceof AgentRelayHopLimitError) {
diff --git a/apps/server/src/routers/lambda/aiAgent/execSchemas.ts b/apps/server/src/routers/lambda/aiAgent/execSchemas.ts
index e04280ba1ba..61039ed9db5 100644
--- a/apps/server/src/routers/lambda/aiAgent/execSchemas.ts
+++ b/apps/server/src/routers/lambda/aiAgent/execSchemas.ts
@@ -200,6 +200,12 @@ export const ExecAgentFieldsSchema = z.object({
clientIds: execAgentClientIdsSchema,
/** Explicit device ID to bind to the topic and activate for this run */
deviceId: z.string().optional(),
+ /**
+ * The run must take place on `deviceId`: refuse it (`PRECONDITION_FAILED`,
+ * nothing written) when the agent's effective execution target would drop
+ * that device. Sent by `lh topic send --new --device`.
+ */
+ requireDevice: z.boolean().optional(),
/** Current desktop device hint, honored only for an effective local target */
localDeviceId: z.string().optional(),
/** Optional existing message IDs to include in context */
@@ -312,6 +318,12 @@ export const ExecAgentFieldsSchema = z.object({
* the message behind that run instead.
*/
supersedeLiveRun: z.boolean().optional(),
+ /**
+ * Title of the topic this send creates (`lh topic send --new --title`).
+ * Ignored when the send continues an existing topic; without it the topic is
+ * named after the prompt.
+ */
+ title: z.string().max(255).optional(),
trigger: z
.string()
.refine((value) => value !== RequestTrigger.Bot, {
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.device.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.device.test.ts
index 037ddc99f77..8eb38466dec 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.device.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.device.test.ts
@@ -691,6 +691,52 @@ describe('AiAgentService.execAgent - device auto-activation', () => {
expect(createOpArgs.activeDeviceId).toBe('device-001');
});
+ // An explicit device on the request is a promise to the caller, so the new
+ // topic records that the binding was pinned rather than auto-picked β€” a
+ // later turn on an `auto` agent then stays on it instead of choosing
+ // whichever machine happens to be online.
+ it('should pin an explicitly requested device on the new topic metadata', async () => {
+ mockDeviceProxy.isConfigured = true;
+ mockDeviceProxy.queryDeviceList.mockResolvedValue([onlineDevice]);
+ await useAgencyConfig({ executionTarget: 'auto' });
+
+ await service.execAgent({
+ agentId: 'agent-1',
+ deviceId: 'device-001',
+ prompt: 'Run a command',
+ });
+
+ expect(topicMock.create).toHaveBeenCalledWith(
+ expect.objectContaining({
+ metadata: expect.objectContaining({
+ boundDeviceId: 'device-001',
+ deviceBindingPinned: true,
+ }),
+ }),
+ undefined,
+ );
+ });
+
+ // Same setup as the "not silently reused" spec above, except the topic
+ // records that the device was chosen explicitly. An `auto` agent must now
+ // honour it even though both machines are online.
+ it('should keep a pinned topic device on later turns for an auto agent', async () => {
+ mockDeviceProxy.isConfigured = true;
+ mockDeviceProxy.queryDeviceList.mockResolvedValue([onlineDevice, onlineDevice2]);
+ topicMock.findById.mockResolvedValue({
+ metadata: { boundDeviceId: 'device-002', deviceBindingPinned: true },
+ });
+ await useAgencyConfig({ executionTarget: 'auto' });
+
+ await service.execAgent({
+ agentId: 'agent-1',
+ appContext: { topicId: 'topic-existing' },
+ prompt: 'Run a command',
+ });
+
+ expect(mockCreateOperation.mock.calls[0][0].activeDeviceId).toBe('device-002');
+ });
+
it('should keep explicit topic binding when the bound device is offline', async () => {
mockDeviceProxy.isConfigured = true;
mockDeviceProxy.queryDeviceList.mockResolvedValue([onlineDevice2]);
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.requiredDevice.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.requiredDevice.test.ts
new file mode 100644
index 00000000000..5e511fcdcf2
--- /dev/null
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.requiredDevice.test.ts
@@ -0,0 +1,368 @@
+import type * as ModelBankModule from 'model-bank';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { AiAgentService } from '../index';
+import { RequestedDeviceIgnoredError } from '../pipeline/turnSetup';
+
+const {
+ mockCreateOperation,
+ mockCreateServerAgentToolsEngine,
+ mockMessageCreate,
+ mockMessageUpdate,
+} = vi.hoisted(() => ({
+ mockCreateOperation: vi.fn(),
+ mockCreateServerAgentToolsEngine: vi.fn().mockReturnValue({
+ generateToolsDetailed: vi.fn().mockReturnValue({ enabledToolIds: [], tools: [] }),
+ getEnabledPluginManifests: vi.fn().mockReturnValue(new Map()),
+ }),
+ mockMessageCreate: vi.fn(),
+ mockMessageUpdate: vi.fn(),
+}));
+
+const { mockDeviceProxy } = vi.hoisted(() => ({
+ mockDeviceProxy: {
+ isConfigured: false,
+ queryDeviceList: vi.fn().mockResolvedValue([]),
+ queryDeviceSystemInfo: vi.fn().mockResolvedValue(undefined),
+ // Present so a send-path regression that probes the device shows up as a
+ // failed assertion rather than a "not a function" crash.
+ statPath: vi.fn().mockResolvedValue({ exists: true, isDirectory: true }),
+ },
+}));
+
+vi.mock('@/libs/trusted-client', () => ({
+ generateTrustedClientToken: vi.fn().mockReturnValue(undefined),
+ getTrustedClientTokenForSession: vi.fn().mockResolvedValue(undefined),
+ isTrustedClientEnabled: vi.fn().mockReturnValue(false),
+}));
+
+vi.mock('@/database/models/message', () => ({
+ MessageModel: vi.fn().mockImplementation(function () {
+ return {
+ create: mockMessageCreate,
+ getLatestNonToolMessageId: vi.fn().mockResolvedValue(undefined),
+ getLatestSpineMessageId: vi.fn().mockResolvedValue(undefined),
+ query: vi.fn().mockResolvedValue([]),
+ update: mockMessageUpdate,
+ };
+ }),
+}));
+
+vi.mock('@/database/models/agent', () => ({
+ AgentModel: vi.fn().mockImplementation(function () {
+ return {
+ getAgentConfig: vi.fn().mockResolvedValue({
+ chatConfig: {},
+ files: [],
+ id: 'agent-1',
+ knowledgeBases: [],
+ model: 'gpt-4',
+ plugins: [],
+ provider: 'openai',
+ systemRole: 'You are a helpful assistant',
+ }),
+ queryAgents: vi.fn().mockResolvedValue([]),
+ };
+ }),
+}));
+
+vi.mock('@/server/services/agent', () => ({
+ AgentService: vi.fn().mockImplementation(function () {
+ return {
+ getAgentConfig: vi.fn().mockResolvedValue({
+ chatConfig: {},
+ files: [],
+ id: 'agent-1',
+ knowledgeBases: [],
+ model: 'gpt-4',
+ plugins: [],
+ provider: 'openai',
+ systemRole: 'You are a helpful assistant',
+ }),
+ };
+ }),
+}));
+
+vi.mock('@/database/models/plugin', () => ({
+ PluginModel: vi.fn().mockImplementation(function () {
+ return {
+ query: vi.fn().mockResolvedValue([]),
+ };
+ }),
+}));
+
+const topicMock = {
+ create: vi.fn().mockResolvedValue({ id: 'topic-1', metadata: undefined }),
+ findById: vi.fn().mockResolvedValue(undefined),
+ releaseTaskCallbackReservation: vi.fn().mockResolvedValue(undefined),
+ tryReserveTaskCallback: vi.fn().mockResolvedValue(true),
+ updateMetadata: vi.fn().mockResolvedValue(undefined),
+};
+vi.mock('@/database/models/topic', () => ({
+ TopicModel: vi.fn().mockImplementation(function () {
+ return topicMock;
+ }),
+}));
+
+const { mockResolveProjectDirectory, mockResolveProjectDirectoryForTopic } = vi.hoisted(() => ({
+ mockResolveProjectDirectory: vi.fn(),
+ mockResolveProjectDirectoryForTopic: vi.fn().mockResolvedValue(undefined),
+}));
+vi.mock('@/database/models/projectWorkingDirectory', () => ({
+ ProjectWorkingDirectoryModel: vi.fn().mockImplementation(function () {
+ return {
+ resolve: mockResolveProjectDirectory,
+ resolveForTopic: mockResolveProjectDirectoryForTopic,
+ };
+ }),
+}));
+
+vi.mock('@/database/models/thread', () => ({
+ ThreadModel: vi.fn().mockImplementation(function () {
+ return {
+ create: vi.fn(),
+ findById: vi.fn(),
+ update: vi.fn(),
+ };
+ }),
+}));
+
+vi.mock('@/server/services/agentRuntime', () => ({
+ AgentRuntimeService: vi.fn().mockImplementation(function () {
+ return {
+ createOperation: mockCreateOperation,
+ };
+ }),
+}));
+
+vi.mock('@/server/services/market', () => ({
+ MarketService: vi.fn().mockImplementation(function () {
+ return {
+ getLobehubSkillManifests: vi.fn().mockResolvedValue([]),
+ };
+ }),
+}));
+
+vi.mock('@/server/services/composio', () => ({
+ ComposioService: vi.fn().mockImplementation(function () {
+ return {
+ getComposioManifests: vi.fn().mockResolvedValue([]),
+ };
+ }),
+}));
+
+vi.mock('@/server/services/file', () => ({
+ FileService: vi.fn().mockImplementation(function () {
+ return {
+ uploadFromUrl: vi.fn(),
+ };
+ }),
+}));
+
+vi.mock('@/server/modules/Mecha', () => ({
+ createServerAgentToolsEngine: mockCreateServerAgentToolsEngine,
+ serverMessagesEngine: vi.fn().mockResolvedValue([{ content: 'test', role: 'user' }]),
+}));
+
+vi.mock('@/server/services/deviceGateway', () => ({
+ deviceGateway: mockDeviceProxy,
+}));
+
+vi.mock('model-bank', async (importOriginal) => {
+ const actual = await importOriginal<typeof ModelBankModule>();
+ return {
+ ...actual,
+ LOBE_DEFAULT_MODEL_LIST: [
+ {
+ abilities: { functionCall: true, video: false, vision: true },
+ id: 'gpt-4',
+ providerId: 'openai',
+ },
+ ],
+ };
+});
+
+describe('AiAgentService.execAgent - required device', () => {
+ let service: AiAgentService;
+ const mockDb = {} as any;
+ const userId = 'test-user-id';
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ topicMock.create.mockResolvedValue({ id: 'topic-1', metadata: undefined });
+ topicMock.findById.mockResolvedValue(undefined);
+ topicMock.updateMetadata.mockResolvedValue(undefined);
+ mockMessageCreate.mockResolvedValue({ id: 'msg-1' });
+ mockMessageUpdate.mockResolvedValue({});
+ mockCreateOperation.mockResolvedValue({
+ autoStarted: true,
+ messageId: 'queue-msg-1',
+ operationId: 'op-123',
+ success: true,
+ });
+ // Reset device proxy state
+ mockDeviceProxy.isConfigured = false;
+ mockDeviceProxy.queryDeviceList.mockResolvedValue([]);
+
+ service = new AiAgentService(mockDb, userId);
+ });
+
+ afterEach(() => {
+ vi.clearAllMocks();
+ });
+
+ const onlineDevice = {
+ deviceId: 'device-001',
+ hostname: 'my-laptop',
+ lastSeen: '2026-03-06T12:00:00.000Z',
+ online: true,
+ platform: 'linux' as const,
+ };
+
+ const onlineDevice2 = {
+ deviceId: 'device-002',
+ hostname: 'my-desktop',
+ lastSeen: '2026-03-06T12:00:00.000Z',
+ online: true,
+ platform: 'darwin' as const,
+ };
+
+ // Override the agent's agencyConfig and rebuild the service. Auto-activation
+ // is now exclusive to `executionTarget: 'auto'` β€” the default (`local`) never
+ // grabs a device β€” so the auto-activation specs opt in explicitly.
+ const useAgencyConfig = async (agencyConfig: Record<string, unknown>) => {
+ const { AgentService } = await import('@/server/services/agent');
+ vi.mocked(AgentService).mockImplementation(function () {
+ return {
+ getAgentConfig: vi.fn().mockResolvedValue({
+ agencyConfig,
+ 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);
+ };
+
+ // ROOT CAUSE:
+ //
+ // `lh topic send --new --device` reported a send to the requested machine
+ // while a fixed execution target dropped that device and ran the work
+ // elsewhere. Only the server knows the caller's effective policy (owners and
+ // private agents have the fixed policy lifted), so the refusal lives here.
+ //
+ // Before: a required device was silently overridden by a fixed target.
+ // After: `requireDevice` refuses before anything is created.
+ describe('a required device', () => {
+ const requireDevice = (deviceId: string) =>
+ service.execAgent({
+ agentId: 'agent-1',
+ deviceId,
+ prompt: 'Run a command',
+ requireDevice: true,
+ });
+
+ it('is refused when a fixed device target would drop it, creating nothing', async () => {
+ mockDeviceProxy.isConfigured = true;
+ mockDeviceProxy.queryDeviceList.mockResolvedValue([onlineDevice, onlineDevice2]);
+ await useAgencyConfig({
+ boundDeviceId: 'device-001',
+ executionTarget: 'device',
+ executionTargetSelectionPolicy: 'fixed',
+ });
+ service = new AiAgentService(mockDb, userId, { workspaceId: 'workspace-1' });
+
+ await expect(requireDevice('device-002')).rejects.toBeInstanceOf(RequestedDeviceIgnoredError);
+ expect(mockCreateOperation).not.toHaveBeenCalled();
+ expect(topicMock.create).not.toHaveBeenCalled();
+ });
+
+ it('is refused by a fixed sandbox target', async () => {
+ mockDeviceProxy.isConfigured = true;
+ mockDeviceProxy.queryDeviceList.mockResolvedValue([onlineDevice]);
+ await useAgencyConfig({
+ executionTarget: 'sandbox',
+ executionTargetSelectionPolicy: 'fixed',
+ });
+ service = new AiAgentService(mockDb, userId, { workspaceId: 'workspace-1' });
+
+ await expect(requireDevice('device-001')).rejects.toBeInstanceOf(RequestedDeviceIgnoredError);
+ expect(mockCreateOperation).not.toHaveBeenCalled();
+ });
+
+ it('runs when the fixed target is that same device', async () => {
+ mockDeviceProxy.isConfigured = true;
+ mockDeviceProxy.queryDeviceList.mockResolvedValue([onlineDevice]);
+ await useAgencyConfig({
+ boundDeviceId: 'device-001',
+ executionTarget: 'device',
+ executionTargetSelectionPolicy: 'fixed',
+ });
+ service = new AiAgentService(mockDb, userId, { workspaceId: 'workspace-1' });
+
+ await requireDevice('device-001');
+
+ expect(mockCreateOperation.mock.calls[0][0].activeDeviceId).toBe('device-001');
+ });
+
+ // ROOT CAUSE:
+ //
+ // The CLI checks the device is online, but it can drop before the server
+ // routes the run; a non-fixed agent then degraded to the cloud sandbox and
+ // ran the work there.
+ //
+ // Before: an unrouted required device silently fell back to the sandbox.
+ // After: the run fails before any operation starts.
+ it('fails before operation creation when the required device went offline', async () => {
+ mockDeviceProxy.isConfigured = true;
+ mockDeviceProxy.queryDeviceList.mockResolvedValue([onlineDevice2]);
+ await useAgencyConfig({ executionTarget: 'auto' });
+
+ await expect(requireDevice('device-001')).rejects.toMatchObject({
+ cause: { data: { code: 'DEVICE_NOT_FOUND', deviceId: 'device-001' } },
+ code: 'PRECONDITION_FAILED',
+ });
+
+ expect(mockCreateOperation).not.toHaveBeenCalled();
+ expect(mockMessageUpdate).toHaveBeenCalledWith(
+ 'msg-1',
+ expect.objectContaining({
+ error: expect.objectContaining({ message: 'Required device unavailable' }),
+ }),
+ );
+ });
+
+ it('still lets a device that is only preferred fall back when it is offline', async () => {
+ mockDeviceProxy.isConfigured = true;
+ mockDeviceProxy.queryDeviceList.mockResolvedValue([onlineDevice2]);
+ await useAgencyConfig({ executionTarget: 'auto' });
+
+ await service.execAgent({
+ agentId: 'agent-1',
+ deviceId: 'device-001',
+ prompt: 'Run a command',
+ });
+
+ expect(mockCreateOperation).toHaveBeenCalled();
+ });
+
+ it('runs on the requested device when the effective policy is not fixed (e.g. lifted for a manager)', async () => {
+ mockDeviceProxy.isConfigured = true;
+ mockDeviceProxy.queryDeviceList.mockResolvedValue([onlineDevice, onlineDevice2]);
+ // What `resolveAgentAgencyConfig` leaves for a managing caller: the
+ // stored device target without the fixed selection policy.
+ await useAgencyConfig({ boundDeviceId: 'device-001', executionTarget: 'device' });
+ service = new AiAgentService(mockDb, userId, { workspaceId: 'workspace-1' });
+
+ await requireDevice('device-002');
+
+ expect(mockCreateOperation.mock.calls[0][0].activeDeviceId).toBe('device-002');
+ });
+ });
+});
diff --git a/apps/server/src/services/aiAgent/composerRun.ts b/apps/server/src/services/aiAgent/composerRun.ts
index df26ff0fdb8..a798e1189f8 100644
--- a/apps/server/src/services/aiAgent/composerRun.ts
+++ b/apps/server/src/services/aiAgent/composerRun.ts
@@ -34,6 +34,7 @@ export type ComposerRunRequest = Pick<
| 'prompt'
| 'queuedSuccessor'
| 'replacesOperationId'
+ | 'requireDevice'
| 'resumeApproval'
| 'resumeApprovals'
| 'resumeToolResult'
@@ -42,6 +43,7 @@ export type ComposerRunRequest = Pick<
| 'slug'
| 'sourceOperationId'
| 'steer'
+ | 'title'
| 'trigger'
| 'userInterventionConfig'
| 'userMessage'
@@ -116,6 +118,7 @@ export const startComposerRun = async (ctx: ComposerRunContext, input: ComposerR
// intentionally not part of the client-passable input schema.
clientIp: ctx.clientIp,
deviceId: input.deviceId,
+ requireDevice: input.requireDevice,
localDeviceId: input.localDeviceId,
existingMessageIds: input.existingMessageIds,
...(topicRun && {
@@ -159,6 +162,7 @@ export const startComposerRun = async (ctx: ComposerRunContext, input: ComposerR
agentSender: input.agentSender,
sourceOperationId: input.sourceOperationId,
steer: input.steer,
+ title: input.title,
trigger: input.trigger ?? RequestTrigger.Chat,
userAgent: ctx.userAgent,
userInterventionConfig: input.userInterventionConfig,
diff --git a/apps/server/src/services/aiAgent/pipeline/execTurn.ts b/apps/server/src/services/aiAgent/pipeline/execTurn.ts
index 7a3d24ccd4d..ee13b5b2261 100644
--- a/apps/server/src/services/aiAgent/pipeline/execTurn.ts
+++ b/apps/server/src/services/aiAgent/pipeline/execTurn.ts
@@ -103,6 +103,7 @@ export const execAgentTurn = async (
clientIp,
userAgent,
deviceId: requestedDeviceId,
+ requireDevice,
localDeviceId,
botPlatformContext,
discordContext,
@@ -429,6 +430,7 @@ export const execAgentTurn = async (
prompt,
providerOverride,
requestedDeviceId,
+ requireDevice,
resolvedAgentId,
resume,
runFromHistory,
@@ -612,6 +614,7 @@ export const execAgentTurn = async (
hasMentionedAgents,
isFixedDeviceTarget: turn.isFixedDeviceTarget,
localDeviceId,
+ requireDevice,
mentionedAgents,
parentMessageId,
prompt,
diff --git a/apps/server/src/services/aiAgent/pipeline/newTopicMetadata.ts b/apps/server/src/services/aiAgent/pipeline/newTopicMetadata.ts
index 006b3f0c42b..dc5c44140ba 100644
--- a/apps/server/src/services/aiAgent/pipeline/newTopicMetadata.ts
+++ b/apps/server/src/services/aiAgent/pipeline/newTopicMetadata.ts
@@ -5,6 +5,8 @@ export interface NewTopicMetadataInput {
appContext?: InternalExecAgentParams['appContext'];
botContext?: InternalExecAgentParams['botContext'];
cronJobId?: string;
+ /** The bound device was chosen explicitly for this conversation, not auto-picked. */
+ deviceBindingPinned?: boolean;
editingAgentId?: string;
/** Working directory the topic is born in; overrides the client-supplied one. */
projectDirectory?: { path: string };
@@ -24,6 +26,7 @@ export const buildNewTopicMetadata = ({
appContext,
botContext,
cronJobId,
+ deviceBindingPinned,
editingAgentId,
projectDirectory,
taskId,
@@ -58,6 +61,7 @@ export const buildNewTopicMetadata = ({
bot: botContext,
boundDeviceId: topicBoundDeviceId,
cronJobId: cronJobId || undefined,
+ ...(deviceBindingPinned && { deviceBindingPinned }),
...(editingAgentId && { editingAgentId }),
...(editingGroupId && { editingGroupId }),
taskId,
diff --git a/apps/server/src/services/aiAgent/pipeline/operationInit.ts b/apps/server/src/services/aiAgent/pipeline/operationInit.ts
index 7570fc9e43c..5038f086a1d 100644
--- a/apps/server/src/services/aiAgent/pipeline/operationInit.ts
+++ b/apps/server/src/services/aiAgent/pipeline/operationInit.ts
@@ -185,6 +185,7 @@ export const runOperationInit = async (
globalMemoryEnabled: request.globalMemoryEnabled,
hasMentionedAgents: request.hasMentionedAgents,
isFixedDeviceTarget: request.isFixedDeviceTarget,
+ requireDevice: request.requireDevice,
loadHistoryMessages: deps.loadHistoryMessages,
localDeviceId: request.localDeviceId,
requestTrigger: request.requestTrigger as RequestTrigger | undefined,
diff --git a/apps/server/src/services/aiAgent/pipeline/toolDiscovery/devicePlan.ts b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/devicePlan.ts
index 2dd602df1ee..0d551f092a3 100644
--- a/apps/server/src/services/aiAgent/pipeline/toolDiscovery/devicePlan.ts
+++ b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/devicePlan.ts
@@ -58,6 +58,7 @@ export const resolveDevicePlan = async (
| 'localDeviceId'
| 'requestedDeviceId'
| 'requestTrigger'
+ | 'requireDevice'
>,
devices: {
boundDeviceId?: string | null;
@@ -72,6 +73,7 @@ export const resolveDevicePlan = async (
localDeviceId,
requestTrigger,
requestedDeviceId,
+ requireDevice,
} = input;
const { boundDeviceId, gatewayConfigured, onlineDevices } = devices;
@@ -86,31 +88,21 @@ export const resolveDevicePlan = async (
sandboxFallback: shareGate ? shareGateGrantsCloudSandbox(shareGate) : false,
trigger: requestTrigger,
});
- // A fixed device target must never degrade to the cloud sandbox or a
- // different device. Persist a visible assistant error and fail the RPC
- // before tool/runtime preparation so no operation can start elsewhere.
- if (
- isFixedDeviceTarget &&
- boundDeviceId &&
- resolveToolMode(agentConfig.chatConfig ?? undefined) !== 'chat' &&
- executionPlan.kind !== 'device'
- ) {
+ // Persist a visible assistant error and fail the RPC before tool/runtime
+ // preparation, so no operation can start somewhere it must not run.
+ const failUnroutedDevice = async (deviceId: string, message: string, detail: string) => {
const errorData: DeviceUnavailableErrorData = {
code: 'DEVICE_NOT_FOUND',
- deviceId: boundDeviceId,
+ deviceId,
retryable: true,
scope: deps.workspaceId ? 'workspace' : 'personal',
...(deps.workspaceId ? { workspaceId: deps.workspaceId } : {}),
};
- const detail =
- executionPlan.kind === 'device-unrouted' && executionPlan.reason === 'bound-device-offline'
- ? 'The device fixed by this agent is offline. Ask an editor to bring it online or change the agent device policy.'
- : 'The device fixed by this agent is unavailable for this run. Ask an editor to check the agent device policy.';
await deps.messageModel.update(assistantMessageId, {
content: '',
error: {
body: { detail, ...errorData },
- message: 'Fixed agent device unavailable',
+ message,
type: 'ServerAgentRuntimeError',
},
});
@@ -119,6 +111,38 @@ export const resolveDevicePlan = async (
code: 'PRECONDITION_FAILED',
message: detail,
});
+ };
+ const isChatMode = resolveToolMode(agentConfig.chatConfig ?? undefined) === 'chat';
+ const deviceOffline =
+ executionPlan.kind === 'device-unrouted' && executionPlan.reason === 'bound-device-offline';
+
+ // A fixed device target must never degrade to the cloud sandbox or a
+ // different device.
+ if (isFixedDeviceTarget && boundDeviceId && !isChatMode && executionPlan.kind !== 'device') {
+ await failUnroutedDevice(
+ boundDeviceId,
+ 'Fixed agent device unavailable',
+ deviceOffline
+ ? 'The device fixed by this agent is offline. Ask an editor to bring it online or change the agent device policy.'
+ : 'The device fixed by this agent is unavailable for this run. Ask an editor to check the agent device policy.',
+ );
+ }
+ // Nor may a device the request required (`lh topic send --new --device`):
+ // it can go offline between the caller's check and this routing, and the
+ // run would otherwise degrade to the cloud sandbox or another machine.
+ if (
+ requireDevice &&
+ requestedDeviceId &&
+ !isChatMode &&
+ !(executionPlan.kind === 'device' && executionPlan.deviceId === requestedDeviceId)
+ ) {
+ await failUnroutedDevice(
+ requestedDeviceId,
+ 'Required device unavailable',
+ deviceOffline
+ ? `Device ${requestedDeviceId} went offline before the run could start there. Bring it online and send again.`
+ : `This run cannot be routed to device ${requestedDeviceId}, so it was not started elsewhere.`,
+ );
}
// Device tools (local-system / remote-device proxy) only exist in a
// device-capable session β€” `none` and `sandbox` sessions must never see
diff --git a/apps/server/src/services/aiAgent/pipeline/toolDiscovery/types.ts b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/types.ts
index 973cf14aded..9f12c5f5a5f 100644
--- a/apps/server/src/services/aiAgent/pipeline/toolDiscovery/types.ts
+++ b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/types.ts
@@ -69,6 +69,8 @@ export interface ToolDiscoveryInput {
localDeviceId?: string;
requestedDeviceId?: string;
requestTrigger?: RequestTrigger;
+ /** See `AgentRunInitRequest.requireDevice`. */
+ requireDevice?: boolean;
selectedToolIds?: string[];
throwIfExecutionAborted: (stage: string) => Promise<void>;
topicBoundDeviceId?: string | null;
diff --git a/apps/server/src/services/aiAgent/pipeline/turnSetup.ts b/apps/server/src/services/aiAgent/pipeline/turnSetup.ts
index bef358409f0..573c19b7c9f 100644
--- a/apps/server/src/services/aiAgent/pipeline/turnSetup.ts
+++ b/apps/server/src/services/aiAgent/pipeline/turnSetup.ts
@@ -361,6 +361,8 @@ export interface TurnSetupInput {
prompt: string;
providerOverride?: string;
requestedDeviceId?: string;
+ /** See `InternalExecAgentParams.requireDevice`. */
+ requireDevice?: boolean;
resolvedAgentId: string;
/** Raw resume flag β€” a resume run must land on an existing topic. */
resume?: boolean;
@@ -421,6 +423,16 @@ export interface TurnSetupResult {
userMessageId?: string;
}
+/** The agent's fixed execution target would drop a device the caller required. */
+export class RequestedDeviceIgnoredError extends Error {
+ constructor(readonly deviceId: string) {
+ super(
+ `This agent always runs on its configured execution target, so device ${deviceId} would be ignored. Drop the device, or have a workspace admin change the agent's execution target.`,
+ );
+ this.name = 'RequestedDeviceIgnoredError';
+ }
+}
+
/**
* Stage 3 + the shared turn setup of {@link AiAgentService.execAgent}: topic
* creation/reuse (with the topic-pinned model), device-access policy, hetero
@@ -459,6 +471,7 @@ export const setupTurn = async (
prompt,
providerOverride,
requestedDeviceId,
+ requireDevice,
resolvedAgentId,
resume,
runFromHistory,
@@ -479,6 +492,19 @@ export const setupTurn = async (
!!deps.workspaceId && agentConfig.agencyConfig?.executionTargetSelectionPolicy === 'fixed';
const isFixedDeviceTarget =
isFixedExecutionTargetSelection && agentConfig.agencyConfig?.executionTarget === 'device';
+ // A caller that needs the run on its device (`lh topic send --new --device`)
+ // must not be told it was sent there when the fixed target drops the device.
+ // `agentConfig` already carries the caller's EFFECTIVE policy (a managing
+ // caller's or a private agent's fixed policy is lifted upstream, in
+ // `resolveRunAgentConfig`), and nothing is written yet.
+ if (
+ requireDevice &&
+ requestedDeviceId &&
+ isFixedExecutionTargetSelection &&
+ !(isFixedDeviceTarget && agentConfig.agencyConfig?.boundDeviceId === requestedDeviceId)
+ ) {
+ throw new RequestedDeviceIgnoredError(requestedDeviceId);
+ }
// `let`: a reused topic that already ran on a machine supplies the device
// when the request names none (see the reuse branch below).
let resolvedRequestedDeviceId = requestedDeviceId;
@@ -595,6 +621,7 @@ export const setupTurn = async (
appContext,
botContext,
cronJobId,
+ deviceBindingPinned: Boolean(effectiveRequestedDeviceId),
editingAgentId,
projectDirectory,
taskId: operationTaskId,
@@ -750,18 +777,25 @@ export const setupTurn = async (
// session live there, so the agent-level target (the default for NEW
// topics) must not move a later turn elsewhere. An explicit request device
// (the picker's in-process preset, a task/sub-agent override) and a fixed
- // workspace target still win. `auto` opted into picking a fresh online
- // device every run, so an earlier pick never pins it.
+ // workspace target still win. `auto` picked a fresh online device every
+ // run, so its own earlier pick never pins the conversation β€” but a device
+ // the caller chose explicitly did (see `deviceBindingPinned` below).
const topicPinnedDeviceId = canUseTopicPin
? existingTopic?.metadata?.boundDeviceId
: undefined;
+ // A binding the caller chose for this conversation (`--device`, the
+ // composer preset, a project directory) is a promise, not an auto pick:
+ // later turns stay there even for an `auto` agent, which would otherwise
+ // grab whichever machine is online now.
+ const topicDeviceBindingPinned =
+ canUseTopicPin && existingTopic?.metadata?.deviceBindingPinned === true;
// A project-directory topic already routed to its directory's device above.
if (
!requestedDeviceId &&
!existingTopic?.projectWorkingDirectoryId &&
topicPinnedDeviceId &&
!isFixedExecutionTargetSelection &&
- agentConfig.agencyConfig?.executionTarget !== 'auto'
+ (agentConfig.agencyConfig?.executionTarget !== 'auto' || topicDeviceBindingPinned)
) {
resolvedRequestedDeviceId = topicPinnedDeviceId;
effectiveRequestedDeviceId = topicPinnedDeviceId;
diff --git a/apps/server/src/services/aiAgent/steerQueue/index.ts b/apps/server/src/services/aiAgent/steerQueue/index.ts
index e3b59dcb964..b107531bb39 100644
--- a/apps/server/src/services/aiAgent/steerQueue/index.ts
+++ b/apps/server/src/services/aiAgent/steerQueue/index.ts
@@ -31,11 +31,13 @@ export type QueuedFollowUpRequest = Omit<
| 'parentMessageId'
| 'queuedSuccessor'
| 'replacesOperationId'
+ | 'requireDevice'
| 'resumeApproval'
| 'resumeApprovals'
| 'resumeToolResult'
| 'sourceOperationId'
| 'steer'
+ | 'title'
>;
export interface QueuedFollowUp extends SteerQueueEntry {
diff --git a/apps/server/src/services/aiAgent/types.ts b/apps/server/src/services/aiAgent/types.ts
index 0643810815a..99d7f2ccb6c 100644
--- a/apps/server/src/services/aiAgent/types.ts
+++ b/apps/server/src/services/aiAgent/types.ts
@@ -246,6 +246,13 @@ export interface InternalExecAgentParams extends ExecAgentParams {
queuedSuccessor?: boolean;
queueRetries?: number;
queueRetryDelay?: string;
+ /**
+ * The run must take place on the requested `deviceId`: refuse it, before
+ * anything is written, when the agent's effective execution target would drop
+ * that device (a workspace agent fixed to another target). Without it the
+ * device is a preference the target policy may override.
+ */
+ requireDevice?: boolean;
/** An idle operation reserved by the dispatcher for this exact Agent, topic and requester. */
reservedOperationId?: string;
/** Whether to continue execution from an existing persisted message */
diff --git a/packages/heterogeneous-agents/src/protocol/lobeHubCliGuide.ts b/packages/heterogeneous-agents/src/protocol/lobeHubCliGuide.ts
index d5a253611a1..9f572889cbd 100644
--- a/packages/heterogeneous-agents/src/protocol/lobeHubCliGuide.ts
+++ b/packages/heterogeneous-agents/src/protocol/lobeHubCliGuide.ts
@@ -78,7 +78,7 @@ const lobeHubCliGuideBody = [
'- **When to use it:** only when the user asks for something that lives in LobeHub rather than in this working directory β€” saving a document, recalling an earlier conversation, generating an image, or changing your own agent configuration. A request about local files, code or another tool does not need `lh`. Say what you did and where it landed.',
"- **You already know where you are.** `LOBEHUB_TOPIC_ID` (this conversation) and `LOBEHUB_OPERATION_ID` (this run) are in your environment, and `LOBEHUB_AGENT_ID` (you) and `LOBEHUB_WORKSPACE_ID` (the workspace this conversation belongs to, which scopes every `lh` call) are too whenever the run carries them. They are ordinary environment variables, so every sub-shell, script or tool you spawn inherits them. Pass them straight to commands rather than listing agents or topics to find yourself; if the one you need is empty, say so instead of guessing an id. LobeHub topic ids start with `tpc_` β€” an id in the user's message without that prefix belongs to something else.",
'- **Earlier conversations:** read one with `lh topic view <id>`. This run can always read its own conversation and the ones the user names in it (a `tpc_…` id or a `<refer_topic>` tag); for any other, ask the user to name it here.',
- '- **Talking to another conversation:** `lh topic send <tpc_id> -c "…"` delivers a message to that conversation and has its agent act on it (queued behind its current turn if it is busy). `lh message create` only writes a row β€” nobody sees or answers it. A message another agent sent you starts with an `<agent_sender>` header; answer it with `lh message reply <message_id> -c "…"`, which wakes the sender\'s conversation. Your ordinary response is not delivered to that agent.',
+ '- **Talking to another conversation:** `lh topic send <tpc_id> -c "…"` delivers a message to that conversation and has its agent act on it (queued behind its current turn if it is busy). To hand work to a fresh conversation instead, `lh topic send --new -c "…"` opens one for you (or `--agent-id` another agent), optionally on a given machine with `--device <id|local>` and named with `--title`; `lh message send -c "…"` is the same thing spelled message-first: without `--topic-id` it opens a new conversation, with `--topic-id <tpc_id>` it sends to that one. Prefer these over `lh agent run` for handing off work. `lh message create` only writes a row β€” nobody sees or answers it. A message another agent sent you starts with an `<agent_sender>` header; answer it with `lh message reply <message_id> -c "…"`, which wakes the sender\'s conversation. Your ordinary response is not delivered to that agent.',
'- **If `lh` is older than this app**, the shell may have found a stale global install first: `lh man` lacks a command you expect, or `lh` reports an unknown command. When `LOBEHUB_CLI` is set it is the path of the CLI this app ships β€” run that path instead of `lh` for the rest of the session.',
'- **Look commands up, do not guess them.** `lh man` lists every command, and `lh man <command>` (e.g. `lh man doc create`) prints the manual for the CLI actually installed here, including exactly which flags that command takes. Many commands offer `--json` for structured output, but not all of them β€” the manual is what says so, and an invented flag just fails the call.',
'- **What it reaches:** `lh kb` knowledge bases Β· `lh doc` documents Β· `lh file` files Β· `lh artifact` artifacts Β· `lh topic` / `lh message` past conversations Β· `lh agent` agents Β· `lh task` / `lh project` work Β· `lh widget` / `lh dashboard` monitoring widgets and dashboards Β· `lh search` local resources and the web Β· `lh recall` past messages, topics, goals and pages in a time window Β· `lh gen` text/image/video/TTS/ASR generation Β· `lh memory` user memory Β· `lh notify` notifications to the user Β· `lh model` / `lh provider` / `lh plugin` / `lh skill` platform configuration Β· `lh bot` chat-platform bots.',
diff --git a/packages/types/src/agentExecution/initRequest.ts b/packages/types/src/agentExecution/initRequest.ts
index 46e5f0b73db..27a185d8ff0 100644
--- a/packages/types/src/agentExecution/initRequest.ts
+++ b/packages/types/src/agentExecution/initRequest.ts
@@ -83,6 +83,12 @@ export interface AgentRunInitRequest {
*/
requestedTopicId?: string;
requestTrigger?: string;
+ /**
+ * The request required its `requestedDeviceId` (`lh topic send --new --device`):
+ * a plan that does not route to that device fails instead of degrading to
+ * the cloud sandbox or another machine.
+ */
+ requireDevice?: boolean;
/**
* The caller re-answers an existing turn (regenerate / continue). Unlike
* `resumeFromHistory`, a run that only suppresses its user row does not set it.
diff --git a/packages/types/src/topic/topic.ts b/packages/types/src/topic/topic.ts
index 4fc2e439254..fd833c903cb 100644
--- a/packages/types/src/topic/topic.ts
+++ b/packages/types/src/topic/topic.ts
@@ -134,6 +134,14 @@ export interface ChatTopicMetadata {
botCreator?: BotSenderMetadata | null;
boundDeviceId?: string;
cronJobId?: string;
+ /**
+ * The conversation's device was chosen explicitly for it (the composer's
+ * picker preset, a project directory, or `lh topic send --new --device`), not
+ * picked automatically by an `auto` agent. Later turns honour that choice
+ * instead of picking a fresh online device, because the caller was told the
+ * work stays on that machine.
+ */
+ deviceBindingPinned?: boolean;
/**
* Set on a topic created by editing and resending a user message of a
* runtime whose native history cannot be rewound (Codex). The topic holds a