Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

🐛 fix(database): preserve agencyConfig when duplicating an agent (#17905)

Northword6c356bcb0cdb
diff --git a/packages/database/src/models/__tests__/agent.test.ts b/packages/database/src/models/__tests__/agent.test.ts
index 4e338de184d..325eb9cc3d9 100644
--- a/packages/database/src/models/__tests__/agent.test.ts
+++ b/packages/database/src/models/__tests__/agent.test.ts
@@ -2019,6 +2019,28 @@ describe('AgentModel', () => {
expect(duplicatedAgent?.slug).not.toBe(sourceAgent.slug);
});
+ it('should preserve agencyConfig when duplicating', async () => {
+ const agencyConfig = {
+ heterogeneousProvider: {
+ type: 'claude-code',
+ command: 'claude',
+ } as const,
+ executionTarget: 'local',
+ };
+ const [sourceAgent] = await serverDB
+ .insert(agents)
+ .values({ userId, title: 'Hetero Agent', agencyConfig } as NewAgent)
+ .returning();
+
+ const result = await agentModel.duplicate(sourceAgent.id);
+
+ const duplicatedAgent = await serverDB.query.agents.findFirst({
+ where: eq(agents.id, result!.agentId),
+ });
+
+ expect(duplicatedAgent?.agencyConfig).toEqual(agencyConfig);
+ });
+
it('should use provided title when duplicating', async () => {
const [sourceAgent] = await serverDB
.insert(agents)
diff --git a/packages/database/src/models/__tests__/agentDeviceBinding.test.ts b/packages/database/src/models/__tests__/agentDeviceBinding.test.ts
index 92e755faffa..09db613bdac 100644
--- a/packages/database/src/models/__tests__/agentDeviceBinding.test.ts
+++ b/packages/database/src/models/__tests__/agentDeviceBinding.test.ts
@@ -3,7 +3,7 @@ import { eq } from 'drizzle-orm';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { getTestDB } from '../../core/getTestDB';
-import { agents, devices, users, workspaces } from '../../schemas';
+import { agents, devices, type NewAgent, users, workspaces } from '../../schemas';
import type { LobeChatDatabase } from '../../type';
import { AgentModel } from '../agent';
@@ -278,6 +278,116 @@ describe('AgentModel workspace device binding', () => {
});
});
+ describe('duplicate', () => {
+ it('drops stale personal-device bindings when duplicating a workspace agent', async () => {
+ // Legacy row predating the workspace-device guard: a public workspace
+ // agent whose config still references a personal device (updateConfig
+ // grandfathers it on the source, but the copy is a fresh caller-owned
+ // row with nothing to grandfather).
+ const [sourceAgent] = await serverDB
+ .insert(agents)
+ .values({
+ userId,
+ workspaceId: wsId,
+ title: 'Legacy WS agent',
+ visibility: 'public',
+ agencyConfig: {
+ boundDeviceId: personalDeviceId,
+ executionTargetSelectionPolicy: 'fixed',
+ executionTarget: 'device',
+ workingDirByDevice: {
+ [personalDeviceId]: '/tmp/legacy',
+ [workspaceDeviceId]: '/tmp/ws',
+ },
+ },
+ } as NewAgent)
+ .returning();
+
+ const wsModel = new AgentModel(serverDB, userId, wsId);
+ const result = await wsModel.duplicate(sourceAgent.id);
+
+ const copy = await serverDB.query.agents.findFirst({
+ where: eq(agents.id, result!.agentId),
+ });
+ expect(copy?.agencyConfig?.boundDeviceId).toBeUndefined();
+ expect(copy?.agencyConfig?.workingDirByDevice).toEqual({
+ [workspaceDeviceId]: '/tmp/ws',
+ });
+ // The fixed device contract can't be preserved without a valid device:
+ // relaxed to the workspace default so the copy resolves the caller's
+ // device instead of a stale foreign one.
+ expect(copy?.agencyConfig?.executionTargetSelectionPolicy).toBe('member');
+ });
+
+ it('preserves a valid fixed workspace-device contract when duplicating', async () => {
+ const [sourceAgent] = await serverDB
+ .insert(agents)
+ .values({
+ userId,
+ workspaceId: wsId,
+ title: 'Fixed WS agent',
+ visibility: 'public',
+ agencyConfig: {
+ boundDeviceId: workspaceDeviceId,
+ executionTargetSelectionPolicy: 'fixed',
+ executionTarget: 'device',
+ workingDirByDevice: { [workspaceDeviceId]: '/tmp/ws' },
+ },
+ } as NewAgent)
+ .returning();
+
+ const wsModel = new AgentModel(serverDB, userId, wsId);
+ const result = await wsModel.duplicate(sourceAgent.id);
+
+ const copy = await serverDB.query.agents.findFirst({
+ where: eq(agents.id, result!.agentId),
+ });
+ expect(copy?.agencyConfig).toEqual({
+ boundDeviceId: workspaceDeviceId,
+ executionTargetSelectionPolicy: 'fixed',
+ executionTarget: 'device',
+ workingDirByDevice: { [workspaceDeviceId]: '/tmp/ws' },
+ });
+ });
+
+ it('relaxes a fixed contract bound to a private workspace device when duplicating', async () => {
+ const privateDeviceId = 'workspace-private-device';
+ await serverDB.insert(devices).values({
+ userId,
+ workspaceId: wsId,
+ deviceId: privateDeviceId,
+ identitySource: 'machine-id',
+ visibility: 'private',
+ });
+
+ const [sourceAgent] = await serverDB
+ .insert(agents)
+ .values({
+ userId,
+ workspaceId: wsId,
+ title: 'Legacy private-device agent',
+ visibility: 'public',
+ agencyConfig: {
+ boundDeviceId: privateDeviceId,
+ executionTargetSelectionPolicy: 'fixed',
+ executionTarget: 'device',
+ },
+ } as NewAgent)
+ .returning();
+
+ const wsModel = new AgentModel(serverDB, userId, wsId);
+ const result = await wsModel.duplicate(sourceAgent.id);
+
+ const copy = await serverDB.query.agents.findFirst({
+ where: eq(agents.id, result!.agentId),
+ });
+ // Enrolled device stays, but the fixed contract can't be shared with a
+ // private device: relaxed to the workspace member default.
+ expect(copy?.agencyConfig?.executionTargetSelectionPolicy).toBe('member');
+ expect(copy?.agencyConfig?.boundDeviceId).toBe(privateDeviceId);
+ });
+ });
+
describe('transferAgent', () => {
it('strips a personal-device binding when moving an agent into a workspace', async () => {
const personalModel = new AgentModel(serverDB, userId);
diff --git a/packages/database/src/models/agent.ts b/packages/database/src/models/agent.ts
index b6d315eeb0b..277b8d01769 100644
--- a/packages/database/src/models/agent.ts
+++ b/packages/database/src/models/agent.ts
@@ -52,7 +52,7 @@ import {
threads,
topics,
} from '../schemas';
-import type { LobeChatDatabase } from '../type';
+import type { LobeChatDatabase, Transaction } from '../type';
import { genEndDateWhere, genRangeWhere, genStartDateWhere, genWhere } from '../utils/genWhere';
import { normalizeInboxAgentMeta } from '../utils/inboxAgent';
import { buildWorkspacePayload, buildWorkspaceWhere } from '../utils/workspace';
@@ -248,6 +248,90 @@ export class AgentModel {
return ids;
};
+ /**
+ * Strip device bindings that are not enrolled in `targetWorkspaceId`, and
+ * downgrade `fixed` device execution targets that can no longer be resolved.
+ * Any `boundDeviceId` / `workingDirByDevice` entry pointing outside the
+ * target workspace is dropped, and a `fixed` device target without a valid
+ * public device is downgraded to `member` (defaulting to the caller's own
+ * device). Shared by `transferAgents` (moving a row into a workspace) and
+ * `duplicate` (copying a row into the caller's workspace): both re-home the
+ * row to a new owner, so a leftover reference to a device only the previous
+ * owner can reach would otherwise point the re-homed agent at a target
+ * nobody else can resolve.
+ */
+ private sanitizeAgencyConfigForWorkspace = async (
+ db: LobeChatDatabase | Transaction,
+ targetWorkspaceId: string,
+ agencyConfigs: Array<LobeAgentAgencyConfig | null | undefined>,
+ ): Promise<Array<LobeAgentAgencyConfig | null>> => {
+ const allCandidateIds = [
+ ...new Set(agencyConfigs.flatMap((config) => this.collectBoundDeviceIds(config))),
+ ];
+ const deviceRows =
+ allCandidateIds.length > 0
+ ? await db
+ .select({ deviceId: devices.deviceId, visibility: devices.visibility })
+ .from(devices)
+ .where(
+ and(
+ eq(devices.workspaceId, targetWorkspaceId),
+ inArray(devices.deviceId, allCandidateIds),
+ ),
+ )
+ : [];
+ const allowed = new Set(deviceRows.map((r) => r.deviceId));
+ const publicDeviceIds = new Set(
+ deviceRows.filter((r) => r.visibility === 'public').map((r) => r.deviceId),
+ );
+
+ return agencyConfigs.map((config) => {
+ let next: LobeAgentAgencyConfig | null = config ?? null;
+ if (!next) return next;
+
+ const candidateIds = this.collectBoundDeviceIds(next);
+ if (candidateIds.length > 0) {
+ const cleaned: LobeAgentAgencyConfig = { ...next };
+ if (cleaned.boundDeviceId && !allowed.has(cleaned.boundDeviceId)) {
+ delete cleaned.boundDeviceId;
+ }
+ if (cleaned.workingDirByDevice) {
+ const filtered: Record<string, string> = {};
+ for (const [deviceId, cwd] of Object.entries(cleaned.workingDirByDevice)) {
+ if (allowed.has(deviceId) && typeof cwd === 'string') filtered[deviceId] = cwd;
+ }
+ cleaned.workingDirByDevice = Object.keys(filtered).length > 0 ? filtered : undefined;
+ }
+ if (
+ cleaned.executionTargetSelectionPolicy === 'fixed' &&
+ cleaned.executionTarget === 'device' &&
+ (!cleaned.boundDeviceId || !allowed.has(cleaned.boundDeviceId))
+ ) {
+ cleaned.executionTargetSelectionPolicy = 'member';
+ }
+ next = cleaned;
+ }
+
+ if (
+ next.executionTargetSelectionPolicy === 'fixed' &&
+ (!next.executionTarget ||
+ !['auto', 'device', 'none', 'sandbox'].includes(next.executionTarget))
+ ) {
+ next.executionTargetSelectionPolicy = 'member';
+ }
+
+ if (
+ next.executionTargetSelectionPolicy === 'fixed' &&
+ next.executionTarget === 'device' &&
+ (!next.boundDeviceId || !publicDeviceIds.has(next.boundDeviceId))
+ ) {
+ next.executionTargetSelectionPolicy = 'member';
+ }
+
+ return next;
+ });
+ };
+
/**
* Enforce: a workspace-scoped agent may only bind devices enrolled in the
* same workspace. Personal devices (workspace_id IS NULL) are reachable only
@@ -1409,6 +1493,22 @@ export class AgentModel {
if (!sourceAgent) return null;
+ // The copy is owned by the caller, so device references must be resolvable
+ // by the caller too. A public workspace agent may still carry a legacy
+ // personal-device `boundDeviceId` / `workingDirByDevice` that `updateConfig`
+ // grandfathers; duplicating it verbatim would point the new agent at a
+ // device outside the workspace instead of defaulting to the caller's own
+ // device. Sanitize exactly like `transferAgents` does when moving into a
+ // workspace. Personal-scope copies keep existing bindings (any device is
+ // reachable there).
+ const agencyConfig = this.workspaceId
+ ? (
+ await this.sanitizeAgencyConfigForWorkspace(this.db, this.workspaceId, [
+ sourceAgent.agencyConfig,
+ ])
+ )[0]
+ : (sourceAgent.agencyConfig ?? null);
+
// Create new agent with explicit include fields
const [newAgent] = await this.db
.insert(agents)
@@ -1416,6 +1516,11 @@ export class AgentModel {
buildWorkspacePayload(
{ userId: this.userId, workspaceId: this.workspaceId },
{
+ // Agency config (heterogeneous provider, execution target, device
+ // binding, sub-agent defaults, verify rubric...). Duplicating must
+ // preserve it, otherwise a heterogeneous agent is copied as a plain
+ // one and its external runtime config is silently lost.
+ agencyConfig,
avatar: sourceAgent.avatar,
backgroundColor: sourceAgent.backgroundColor,
chatConfig: sourceAgent.chatConfig,
@@ -1800,77 +1905,14 @@ export class AgentModel {
// Device rows for the whole batch are fetched with one query.
const resolvedAgencyConfigs = new Map<string, LobeAgentAgencyConfig | null>();
if (targetWorkspaceId) {
- const allCandidateIds = [
- ...new Set(
- foundAgents.flatMap((agent) => this.collectBoundDeviceIds(agent.agencyConfig)),
- ),
- ];
- const deviceRows =
- allCandidateIds.length > 0
- ? await trx
- .select({ deviceId: devices.deviceId, visibility: devices.visibility })
- .from(devices)
- .where(
- and(
- eq(devices.workspaceId, targetWorkspaceId),
- inArray(devices.deviceId, allCandidateIds),
- ),
- )
- : [];
- const allowed = new Set(deviceRows.map((r) => r.deviceId));
- const publicDeviceIds = new Set(
- deviceRows.filter((r) => r.visibility === 'public').map((r) => r.deviceId),
+ const cleanedConfigs = await this.sanitizeAgencyConfigForWorkspace(
+ trx,
+ targetWorkspaceId,
+ foundAgents.map((agent) => agent.agencyConfig),
+ );
+ foundAgents.forEach((agent, index) =>
+ resolvedAgencyConfigs.set(agent.id, cleanedConfigs[index]),
);
-
- for (const agent of foundAgents) {
- let nextAgencyConfig: LobeAgentAgencyConfig | null = agent.agencyConfig ?? null;
- if (!nextAgencyConfig) {
- resolvedAgencyConfigs.set(agent.id, nextAgencyConfig);
- continue;
- }
-
- const candidateIds = this.collectBoundDeviceIds(nextAgencyConfig);
- if (candidateIds.length > 0) {
- const cleaned: LobeAgentAgencyConfig = { ...nextAgencyConfig };
- if (cleaned.boundDeviceId && !allowed.has(cleaned.boundDeviceId)) {
- delete cleaned.boundDeviceId;
- }
- if (cleaned.workingDirByDevice) {
- const filtered: Record<string, string> = {};
- for (const [deviceId, cwd] of Object.entries(cleaned.workingDirByDevice)) {
- if (allowed.has(deviceId) && typeof cwd === 'string') filtered[deviceId] = cwd;
- }
- cleaned.workingDirByDevice = Object.keys(filtered).length > 0 ? filtered : undefined;
- }
- if (
- cleaned.executionTargetSelectionPolicy === 'fixed' &&
- cleaned.executionTarget === 'device' &&
- (!cleaned.boundDeviceId || !allowed.has(cleaned.boundDeviceId))
- ) {
- cleaned.executionTargetSelectionPolicy = 'member';
- }
- nextAgencyConfig = cleaned;
- }
-
- if (
- nextAgencyConfig.executionTargetSelectionPolicy === 'fixed' &&
- (!nextAgencyConfig.executionTarget ||
- !['auto', 'device', 'none', 'sandbox'].includes(nextAgencyConfig.executionTarget))
- ) {
- nextAgencyConfig.executionTargetSelectionPolicy = 'member';
- }
-
- if (
- nextAgencyConfig.executionTargetSelectionPolicy === 'fixed' &&
- nextAgencyConfig.executionTarget === 'device' &&
- (!nextAgencyConfig.boundDeviceId ||
- !publicDeviceIds.has(nextAgencyConfig.boundDeviceId))
- ) {
- nextAgencyConfig.executionTargetSelectionPolicy = 'member';
- }
-
- resolvedAgencyConfigs.set(agent.id, nextAgencyConfig);
- }
}
// 4. Update the agent records. slug / agencyConfig differ per agent, so