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(agent-builder): stop builder writes landing on the wrong agent or vanishing (#19994)

Arvin Xu0058df6246f7
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
index 08a1b58f424..6393f30ca7b 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
@@ -979,6 +979,7 @@ export class AgentRuntimeService {
appContext: {
defaultTaskAssigneeAgentId: appContext?.defaultTaskAssigneeAgentId,
documentId: appContext?.documentId,
+ editingAgentId: appContext?.editingAgentId,
groupId: appContext?.groupId,
scope: appContext?.scope,
sessionId: appContext?.sessionId,
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.builderEditingTarget.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.builderEditingTarget.test.ts
new file mode 100644
index 00000000000..45c390427b5
--- /dev/null
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.builderEditingTarget.test.ts
@@ -0,0 +1,268 @@
+import type * as ModelBankModule from 'model-bank';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { AiAgentService } from '../index';
+
+const {
+ mockIsResourceAuthorOrAdmin,
+ mockCreateOperation,
+ mockGetAgentConfig,
+ mockGetPreference,
+ mockMessageCreate,
+ mockTopicCreate,
+ mockTopicFindById,
+} = vi.hoisted(() => ({
+ mockIsResourceAuthorOrAdmin: vi.fn(),
+ mockCreateOperation: vi.fn(),
+ mockGetAgentConfig: vi.fn(),
+ mockGetPreference: vi.fn(),
+ mockMessageCreate: vi.fn(),
+ mockTopicCreate: vi.fn().mockResolvedValue({ id: 'topic-1' }),
+ mockTopicFindById: vi.fn(),
+}));
+
+vi.mock('@/server/services/resourcePermission', () => ({
+ isResourceAuthorOrAdmin: mockIsResourceAuthorOrAdmin,
+}));
+
+vi.mock('@/libs/trusted-client', () => ({
+ generateTrustedClientToken: vi.fn().mockReturnValue(undefined),
+ getTrustedClientTokenForSession: vi.fn().mockResolvedValue(undefined),
+ isTrustedClientEnabled: vi.fn().mockReturnValue(false),
+}));
+
+vi.mock('@/database/models/chatGroup', () => ({
+ ChatGroupModel: class {
+ findById = vi.fn().mockResolvedValue(undefined);
+ getGroupAgentsWithMeta = vi.fn().mockResolvedValue([]);
+ },
+}));
+
+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: vi.fn().mockResolvedValue({}),
+ };
+ }),
+}));
+
+vi.mock('@/database/models/workspaceUserSettings', () => ({
+ WorkspaceUserSettingsModel: vi.fn().mockImplementation(function () {
+ return {
+ getPreference: mockGetPreference,
+ };
+ }),
+}));
+
+vi.mock('@/database/models/agent', () => ({
+ AgentModel: vi.fn().mockImplementation(function () {
+ return {
+ getAgentConfig: vi.fn(),
+ queryAgents: vi.fn().mockResolvedValue([]),
+ };
+ }),
+}));
+
+vi.mock('@/server/services/agent', () => ({
+ AgentService: vi.fn().mockImplementation(function () {
+ return {
+ getAgentConfig: mockGetAgentConfig,
+ };
+ }),
+}));
+
+vi.mock('@/database/models/plugin', () => ({
+ PluginModel: vi.fn().mockImplementation(function () {
+ return {
+ query: vi.fn().mockResolvedValue([]),
+ };
+ }),
+}));
+
+// Builtin agents inject their own tools, so a run under a builtin slug reaches
+// connector resolution that the plain-agent cases never do.
+vi.mock('@/database/models/connector', () => ({
+ ConnectorModel: vi.fn().mockImplementation(function () {
+ return {
+ queryByIdentifiers: vi.fn().mockResolvedValue([]),
+ resolveByIdentifiers: vi.fn().mockResolvedValue([]),
+ };
+ }),
+}));
+
+vi.mock('@/database/models/connectorTool', () => ({
+ ConnectorToolModel: vi.fn().mockImplementation(function () {
+ return {
+ queryAllByConnectorIds: vi.fn().mockResolvedValue([]),
+ queryByConnector: vi.fn().mockResolvedValue([]),
+ queryByConnectorIds: vi.fn().mockResolvedValue([]),
+ };
+ }),
+}));
+
+vi.mock('@/database/models/topic', () => ({
+ TopicModel: vi.fn().mockImplementation(function () {
+ return {
+ releaseTaskCallbackReservation: vi.fn().mockResolvedValue(undefined),
+ tryReserveTaskCallback: vi.fn().mockResolvedValue(true),
+ create: mockTopicCreate,
+ armScheduledRun: vi.fn().mockResolvedValue(undefined),
+ findById: mockTopicFindById,
+ };
+ }),
+}));
+
+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: vi.fn().mockReturnValue({
+ generateToolsDetailed: vi.fn().mockReturnValue({ enabledToolIds: [], tools: [] }),
+ getEnabledPluginManifests: vi.fn().mockReturnValue(new Map()),
+ }),
+ serverMessagesEngine: vi.fn().mockResolvedValue([{ content: 'test', role: 'user' }]),
+}));
+
+vi.mock('@/server/services/deviceGateway', () => ({
+ deviceGateway: {
+ isConfigured: false,
+ queryDeviceList: vi.fn().mockResolvedValue([]),
+ },
+}));
+
+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',
+ },
+ {
+ abilities: { functionCall: true, video: false, vision: true },
+ id: 'claude-sonnet-4-6',
+ providerId: 'anthropic',
+ },
+ ],
+ };
+});
+
+// A builder run is owned by the builtin builder agent; the agent it edits only rides on
+// `appContext.editingAgentId`. Continuations rebuilt from the durable operation (approval /
+// askUserQuestion resumes) arrive without it, which left the builder tools with no target.
+describe('AiAgentService.execAgent - agent builder editing target', () => {
+ let service: AiAgentService;
+
+ const builderConfig = {
+ chatConfig: {},
+ id: 'agt_builder',
+ model: 'gpt-4',
+ plugins: [],
+ provider: 'openai',
+ slug: 'agent-builder',
+ systemRole: '',
+ };
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockMessageCreate.mockResolvedValue({ id: 'msg-1' });
+ mockCreateOperation.mockResolvedValue({
+ autoStarted: true,
+ messageId: 'queue-msg-1',
+ operationId: 'op-123',
+ success: true,
+ });
+ mockGetPreference.mockResolvedValue({});
+ mockIsResourceAuthorOrAdmin.mockResolvedValue(false);
+ mockGetAgentConfig.mockResolvedValue({ ...builderConfig });
+ mockTopicFindById.mockResolvedValue({
+ agentId: 'agt_builder',
+ id: 'tpc_builder',
+ metadata: { editingAgentId: 'agt_target' },
+ });
+ service = new AiAgentService({} as any, 'test-user-id');
+ });
+
+ it('recovers the editing target from the builder topic when the run omits it', async () => {
+ await service.execAgent({
+ agentId: 'agt_builder',
+ appContext: { scope: 'agent_builder', topicId: 'tpc_builder' },
+ prompt: 'set temperature to 0.8',
+ });
+
+ expect(mockCreateOperation).toHaveBeenCalledTimes(1);
+ expect(mockCreateOperation.mock.calls[0][0].appContext).toMatchObject({
+ agentId: 'agt_builder',
+ editingAgentId: 'agt_target',
+ });
+ });
+
+ it('keeps an explicit editing target over the topic record', async () => {
+ await service.execAgent({
+ agentId: 'agt_builder',
+ appContext: {
+ editingAgentId: 'agt_explicit',
+ scope: 'agent_builder',
+ topicId: 'tpc_builder',
+ },
+ prompt: 'hi',
+ });
+
+ expect(mockCreateOperation.mock.calls[0][0].appContext.editingAgentId).toBe('agt_explicit');
+ });
+
+ it('does not attach an editing target outside the agent builder scope', async () => {
+ await service.execAgent({
+ agentId: 'agt_builder',
+ appContext: { scope: 'main', topicId: 'tpc_builder' },
+ prompt: 'hi',
+ });
+
+ expect(mockCreateOperation.mock.calls[0][0].appContext.editingAgentId).toBeUndefined();
+ });
+});
diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.ts
index 6be40841faa..40b0eed0dfa 100644
--- a/apps/server/src/services/aiAgent/index.ts
+++ b/apps/server/src/services/aiAgent/index.ts
@@ -1037,7 +1037,10 @@ export class AiAgentService {
const runContext: ExecRunContext = {
agentConfig,
- appContext,
+ appContext:
+ turn.editingAgentId && turn.editingAgentId !== appContext?.editingAgentId
+ ? { ...appContext, editingAgentId: turn.editingAgentId }
+ : appContext,
assistantMessageId: turn.assistantMessageId,
canUseDevice,
deviceAccessReason,
diff --git a/apps/server/src/services/aiAgent/pipeline/turnSetup.ts b/apps/server/src/services/aiAgent/pipeline/turnSetup.ts
index f35f2167750..8b8e7334b8d 100644
--- a/apps/server/src/services/aiAgent/pipeline/turnSetup.ts
+++ b/apps/server/src/services/aiAgent/pipeline/turnSetup.ts
@@ -356,6 +356,8 @@ export interface TurnSetupResult {
assistantMessageId: string;
canUseDevice: boolean;
deviceAccessReason: DeviceAccessReason;
+ /** The agent a builder run edits — from the request, else recovered from the builder topic. */
+ editingAgentId?: string;
effectiveRequestedDeviceId?: string;
heterogeneousProvider?: NonNullable<AgentConfigWithId['agencyConfig']>['heterogeneousProvider'];
heteroType: HeterogeneousAgentType;
@@ -427,6 +429,7 @@ export const setupTurn = async (
} = input;
let topicId = appContext?.topicId;
+ let editingAgentId = appContext?.editingAgentId;
const isFixedExecutionTargetSelection =
!!deps.workspaceId && agentConfig.agencyConfig?.executionTargetSelectionPolicy === 'fixed';
@@ -479,7 +482,7 @@ export const setupTurn = async (
// association exists only at run time: a topic written without it can
// never be attributed afterwards, which is why it is stamped even though
// nothing filters on it yet.
- const { editingAgentId, editingGroupId } = appContext ?? {};
+ const { editingGroupId } = appContext ?? {};
const metadata =
cronJobId ||
operationTaskId ||
@@ -619,6 +622,16 @@ export const setupTurn = async (
message: ChatErrorType.ShareHeterogeneousAgentUnsupported,
});
}
+
+ // A builder conversation edits exactly one agent, stamped on the topic when
+ // it was created. Continuations rebuilt from the durable operation (approval
+ // or askUserQuestion resumes) arrive without `editingAgentId`; recover it
+ // here so the run origin still carries the target instead of leaving the
+ // builder tools with nothing to write to.
+ if (appContext?.scope === 'agent_builder' && !editingAgentId) {
+ editingAgentId = existingTopic?.metadata?.editingAgentId ?? undefined;
+ log('execAgent: recovered editingAgentId=%s from topic %s', editingAgentId, topicId);
+ }
}
await throwIfExecutionAborted('topic setup');
@@ -875,6 +888,7 @@ export const setupTurn = async (
assistantMessageId: assistantMessageRecord.id,
canUseDevice,
deviceAccessReason,
+ editingAgentId,
effectiveRequestedDeviceId,
heteroType,
heterogeneousProvider,
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/agentBuilder.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/agentBuilder.test.ts
index 1cf378c8576..2464b20bb8b 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/agentBuilder.test.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/agentBuilder.test.ts
@@ -351,3 +351,51 @@ describe('agentBuilderRuntime', () => {
});
});
});
+
+// A builder run whose tool context lost `editingAgentId` used to fall back to
+// `ctx.agentId` — the builder builtin itself — and report success while the
+// agent the user was editing stayed untouched.
+describe('agentBuilderRuntime without an editing target', () => {
+ const builderRunCtx = {
+ agentId: 'agt_builder_virtual',
+ serverDB: {} as never,
+ toolManifestMap: {},
+ userId: 'user-1',
+ };
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockGetAgentConfigById.mockResolvedValue({ plugins: [] });
+ });
+
+ it('updatePrompt refuses instead of writing to the builder itself', async () => {
+ const runtime = agentBuilderRuntime.factory(builderRunCtx);
+ const result = await runtime.updatePrompt({ prompt: 'NEW PROMPT' }, builderRunCtx);
+
+ expect(mockUpdateAgent).not.toHaveBeenCalled();
+ expect(result).toMatchObject({ error: { type: 'NoEditingTarget' }, success: false });
+ });
+
+ it('updateConfig refuses instead of writing to the builder itself', async () => {
+ const runtime = agentBuilderRuntime.factory(builderRunCtx);
+ const result = await runtime.updateConfig(
+ { config: { params: { temperature: 0.8 } } } as any,
+ builderRunCtx,
+ );
+
+ expect(mockServiceUpdateConfig).not.toHaveBeenCalled();
+ expect(mockUpdateAgent).not.toHaveBeenCalled();
+ expect(result).toMatchObject({ error: { type: 'NoEditingTarget' }, success: false });
+ });
+
+ it('installPlugin refuses instead of writing to the builder itself', async () => {
+ const runtime = agentBuilderRuntime.factory(builderRunCtx);
+ const result = await runtime.installPlugin(
+ { identifier: 'lobe-web-browsing', source: 'official' },
+ builderRunCtx,
+ );
+
+ expect(mockUpdateConfig).not.toHaveBeenCalled();
+ expect(result).toMatchObject({ error: { type: 'NoEditingTarget' }, success: false });
+ });
+});
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/agentBuilder.ts b/apps/server/src/services/toolExecution/serverRuntimes/agentBuilder.ts
index bb1b59f4a61..fefef9ef0c5 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/agentBuilder.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/agentBuilder.ts
@@ -30,6 +30,19 @@ const handleError = (error: unknown, message: string): ToolExecutionResult => {
return { content: `${message}: ${err.message}`, success: false };
};
+/**
+ * The builder run is owned by the builtin builder agent, so `ctx.agentId` is the
+ * builder itself — never the agent the user is editing. Without an explicit
+ * editing target the write must fail loudly: falling back to `ctx.agentId`
+ * silently rewrote the builder's own row while reporting success.
+ */
+const noEditingTargetResult: ToolExecutionResult = {
+ content:
+ 'No agent is being edited in this conversation, so nothing was changed. Ask the user to open the target agent and use the Agent Builder panel there.',
+ error: { message: 'Missing editing target agent', type: 'NoEditingTarget' },
+ success: false,
+};
+
export const agentBuilderRuntime: ServerRuntimeRegistration = {
factory: (context: ToolExecutionContext) => {
if (!context.userId || !context.serverDB) {
@@ -182,15 +195,8 @@ export const agentBuilderRuntime: ServerRuntimeRegistration = {
params: UpdateAgentConfigParams,
ctx: ToolExecutionContext,
): Promise<ToolExecutionResult> => {
- const agentId = ctx.editingAgentId ?? ctx.agentId;
-
- if (!agentId) {
- return {
- content: 'No active agent found',
- error: { message: 'No active agent found', type: 'NoAgentContext' },
- success: false,
- };
- }
+ const agentId = ctx.editingAgentId;
+ if (!agentId) return noEditingTargetResult;
try {
const agent = await agentModel.getAgentConfigById(agentId);
@@ -260,15 +266,8 @@ export const agentBuilderRuntime: ServerRuntimeRegistration = {
params: UpdatePromptParams,
ctx: ToolExecutionContext,
): Promise<ToolExecutionResult> => {
- const agentId = ctx.editingAgentId ?? ctx.agentId;
-
- if (!agentId) {
- return {
- content: 'No active agent found',
- error: { message: 'No active agent found', type: 'NoAgentContext' },
- success: false,
- };
- }
+ const agentId = ctx.editingAgentId;
+ if (!agentId) return noEditingTargetResult;
try {
await agentModel.update(agentId, {
@@ -292,15 +291,8 @@ export const agentBuilderRuntime: ServerRuntimeRegistration = {
params: InstallPluginParams,
ctx: ToolExecutionContext,
): Promise<ToolExecutionResult> => {
- const agentId = ctx.editingAgentId ?? ctx.agentId;
-
- if (!agentId) {
- return {
- content: 'No active agent found',
- error: { message: 'No active agent found', type: 'NoAgentContext' },
- success: false,
- };
- }
+ const agentId = ctx.editingAgentId;
+ if (!agentId) return noEditingTargetResult;
const { identifier, source } = params;
diff --git a/packages/business-server/src/agent-run/agentInterventionReview.ts b/packages/business-server/src/agent-run/agentInterventionReview.ts
index a1d8bff61c8..7d26e0ece49 100644
--- a/packages/business-server/src/agent-run/agentInterventionReview.ts
+++ b/packages/business-server/src/agent-run/agentInterventionReview.ts
@@ -298,6 +298,11 @@ export interface ResolveAgentInterventionBySourceParams {
*/
export interface AgentInterventionRuntimeAppContext {
documentId?: string | null;
+ /**
+ * The agent a builder run edits. Without it an `agent_builder` continuation
+ * resumes with no target (the run is owned by the builder itself).
+ */
+ editingAgentId?: string;
groupId?: string | null;
scope?: MessageMapScope;
sessionId?: string;
diff --git a/packages/database/src/models/__tests__/agent.test.ts b/packages/database/src/models/__tests__/agent.test.ts
index 40b604da2b8..adc030a98ff 100644
--- a/packages/database/src/models/__tests__/agent.test.ts
+++ b/packages/database/src/models/__tests__/agent.test.ts
@@ -1,7 +1,7 @@
// @vitest-environment node
import { DEFAULT_INBOX_AVATAR, DEFAULT_INBOX_TITLE, INBOX_SESSION_ID } from '@lobechat/const';
import { eq } from 'drizzle-orm';
-import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { getTestDB } from '../../core/getTestDB';
import type { NewAgent } from '../../schemas';
@@ -839,23 +839,25 @@ describe('AgentModel', () => {
expect(result?.title).toBe('Original Title');
});
- it("should strip identity fields when updating the Agent Builder's own row", async () => {
+ it("should reject identity fields when updating the Agent Builder's own row", async () => {
const agent = await serverDB
.insert(agents)
.values({ slug: 'agent-builder', userId })
.returning()
.then((res) => res[0]);
- await agentModel.update(agent.id, {
- avatar: 'hacked-avatar',
- backgroundColor: 'hacked-color',
- description: 'hacked description',
- marketIdentifier: 'hacked-market-id',
- model: 'gpt-4', // non-protected field should still be applied
- name: 'Hacked Builder Name',
- tags: ['hacked'],
- title: 'Hacked Builder Title',
- });
+ await expect(
+ agentModel.update(agent.id, {
+ avatar: 'hacked-avatar',
+ backgroundColor: 'hacked-color',
+ description: 'hacked description',
+ marketIdentifier: 'hacked-market-id',
+ model: 'gpt-4', // rejected together with the protected fields: no half-write
+ name: 'Hacked Builder Name',
+ tags: ['hacked'],
+ title: 'Hacked Builder Title',
+ }),
+ ).rejects.toThrow("The Agent Builder's own title, name, description");
const result = await serverDB.query.agents.findFirst({
where: eq(agents.id, agent.id),
@@ -868,22 +870,25 @@ describe('AgentModel', () => {
expect(result?.backgroundColor).toBeNull();
expect(result?.marketIdentifier).toBeNull();
expect(result?.tags).toEqual([]);
- expect(result?.model).toBe('gpt-4');
+ expect(result?.model).toBeNull();
});
- it('should strip systemRole when the gateway updatePrompt path writes it via update()', async () => {
- // Mirrors apps/server/.../serverRuntimes/agentBuilder.ts's updatePrompt, which calls
- // agentModel.update(agentId, { editorData: null, systemRole }) directly.
+ it('should reject systemRole when an updatePrompt tool writes it via update()', async () => {
+ // Mirrors lobe-agent-management.updatePrompt({ agentId: <the builder> }), which calls
+ // agentModel.update(agentId, { editorData: null, systemRole }) and then reports
+ // "Successfully updated system prompt" — the write must fail instead of being dropped.
const agent = await serverDB
.insert(agents)
.values({ slug: 'agent-builder', userId })
.returning()
.then((res) => res[0]);
- await agentModel.update(agent.id, {
- editorData: null,
- systemRole: 'You are now a pirate.',
- });
+ await expect(
+ agentModel.update(agent.id, {
+ editorData: null,
+ systemRole: 'You are now a pirate.',
+ }),
+ ).rejects.toThrow("The Agent Builder's own systemRole cannot be changed");
const result = await serverDB.query.agents.findFirst({
where: eq(agents.id, agent.id),
@@ -1413,27 +1418,45 @@ describe('AgentModel', () => {
expect(result?.title).toBe('Original Title');
});
- it("should strip systemRole when updating the Agent Builder's own row", async () => {
+ it("should reject systemRole when updating the Agent Builder's own row", async () => {
const agent = await serverDB
.insert(agents)
.values({ slug: 'agent-builder', userId })
.returning()
.then((res) => res[0]);
- await agentModel.updateConfig(agent.id, {
- model: 'gpt-4', // non-protected field should still be applied
- systemRole: 'You are now a pirate.',
- });
+ await expect(
+ agentModel.updateConfig(agent.id, {
+ model: 'gpt-4', // rejected together with the protected field: no half-write
+ systemRole: 'You are now a pirate.',
+ }),
+ ).rejects.toThrow("The Agent Builder's own systemRole cannot be changed");
const result = await serverDB.query.agents.findFirst({
where: eq(agents.id, agent.id),
});
expect(result?.systemRole).toBeNull();
- expect(result?.model).toBe('gpt-4');
+ expect(result?.model).toBeNull();
});
- it("should strip identity fields when the browser client's meta editor writes them via updateConfig()", async () => {
+ it("should still apply non-protected fields to the Agent Builder's own row", async () => {
+ const agent = await serverDB
+ .insert(agents)
+ .values({ slug: 'agent-builder', userId })
+ .returning()
+ .then((res) => res[0]);
+
+ await agentModel.updateConfig(agent.id, { model: 'gpt-4', provider: 'openai' });
+
+ const result = await serverDB.query.agents.findFirst({
+ where: eq(agents.id, agent.id),
+ });
+
+ expect(result).toMatchObject({ model: 'gpt-4', provider: 'openai' });
+ });
+
+ it("should reject identity fields when the browser client's meta editor writes them via updateConfig()", async () => {
// Mirrors the browser client path: agentService.updateAgentMeta() sends
// title/avatar/etc. through the updateAgentConfig mutation, which calls
// agentModel.updateConfig() rather than update().
@@ -1443,16 +1466,18 @@ describe('AgentModel', () => {
.returning()
.then((res) => res[0]);
- await agentModel.updateConfig(agent.id, {
- avatar: 'hacked-avatar',
- backgroundColor: 'hacked-color',
- description: 'hacked description',
- marketIdentifier: 'hacked-market-id',
- model: 'gpt-4', // non-protected field should still be applied
- name: 'Hacked Builder Name',
- tags: ['hacked'],
- title: 'Hacked Builder Title',
- });
+ await expect(
+ agentModel.updateConfig(agent.id, {
+ avatar: 'hacked-avatar',
+ backgroundColor: 'hacked-color',
+ description: 'hacked description',
+ marketIdentifier: 'hacked-market-id',
+ model: 'gpt-4', // rejected together with the protected fields: no half-write
+ name: 'Hacked Builder Name',
+ tags: ['hacked'],
+ title: 'Hacked Builder Title',
+ }),
+ ).rejects.toThrow("The Agent Builder's own title, name, description");
const result = await serverDB.query.agents.findFirst({
where: eq(agents.id, agent.id),
@@ -1465,7 +1490,7 @@ describe('AgentModel', () => {
expect(result?.backgroundColor).toBeNull();
expect(result?.marketIdentifier).toBeNull();
expect(result?.tags).toEqual([]);
- expect(result?.model).toBe('gpt-4');
+ expect(result?.model).toBeNull();
});
it('should strip heterogeneousProvider when updating the inbox agent', async () => {
@@ -2971,6 +2996,34 @@ describe('AgentModel', () => {
});
describe('updateConfig edge cases', () => {
+ it('should keep a systemRole committed by a parallel update() while the config write is in flight', async () => {
+ // Same shape as a batch where the model calls updateAgent(config: openingMessage…) and
+ // updatePrompt in parallel: each tool runs on its own pooled connection, so the prompt
+ // write can commit between updateConfig's read and its write. Pin that interleaving.
+ const [agent] = await serverDB
+ .insert(agents)
+ .values({ systemRole: 'OLD PROMPT', userId })
+ .returning();
+
+ const original = (agentModel as any).assertWorkspaceDeviceBinding.bind(agentModel);
+ const spy = vi
+ .spyOn(agentModel as any, 'assertWorkspaceDeviceBinding')
+ .mockImplementationOnce(async (...args: unknown[]) => {
+ await agentModel.update(agent.id, { editorData: null, systemRole: 'NEW PROMPT' });
+ return original(...args);
+ });
+
+ await agentModel.updateConfig(agent.id, { openingMessage: 'hi', openingQuestions: ['q'] });
+ spy.mockRestore();
+
+ const dbAgent = await serverDB.query.agents.findFirst({ where: eq(agents.id, agent.id) });
+ expect(dbAgent).toMatchObject({
+ openingMessage: 'hi',
+ openingQuestions: ['q'],
+ systemRole: 'NEW PROMPT',
+ });
+ });
+
it('should return early for null data', async () => {
const [agent] = await serverDB
.insert(agents)
diff --git a/packages/database/src/models/agent.ts b/packages/database/src/models/agent.ts
index 678eb3bcce0..c372bfa421c 100644
--- a/packages/database/src/models/agent.ts
+++ b/packages/database/src/models/agent.ts
@@ -118,6 +118,10 @@ import {
* not just the fields each historically happened to receive. Clients on builds older than
* PR #16420 can still hit this path, so enforce it here (the single write chokepoint)
* regardless of caller.
+ *
+ * Such a write is rejected, not silently trimmed: the writer is almost always aiming at a
+ * different agent (the one the builder is editing), and a trimmed write still reports
+ * success — the caller would believe the prompt/name landed when nothing changed.
*/
const AGENT_BUILDER_PROTECTED_FIELDS = [
'title',
@@ -130,6 +134,18 @@ const AGENT_BUILDER_PROTECTED_FIELDS = [
'systemRole',
] as const;
+const assertNoAgentBuilderProtectedFields = (data: Record<string, unknown>) => {
+ const fields = AGENT_BUILDER_PROTECTED_FIELDS.filter((field) => data[field] !== undefined);
+ if (fields.length === 0) return;
+
+ throw new TRPCError({
+ code: 'FORBIDDEN',
+ message:
+ `The Agent Builder's own ${fields.join(', ')} cannot be changed, so nothing was updated. ` +
+ 'Target the agent being edited instead.',
+ });
+};
+
/**
* Fields that define a row's identity, scope and provisioning status. Every one of
* them feeds authorization — `slug` + `virtual` classify collaborative builtins,
@@ -1133,10 +1149,8 @@ export class AgentModel {
const apiSafeData = Object.hasOwn(data, 'agencyConfig')
? { ...data, agencyConfig: sanitizeAgentApiConfig(data.agencyConfig) }
: data;
- const sanitizedData = await this.stripAgentBuilderProtectedFields(
- agentId,
- this.stripImmutableFields(apiSafeData),
- );
+ const sanitizedData = this.stripImmutableFields(apiSafeData);
+ await this.assertNotAgentBuilderProtectedWrite(agentId, sanitizedData);
return this.db
.update(agents)
@@ -1145,27 +1159,22 @@ export class AgentModel {
};
/**
- * Strip fields the Agent Builder's own row must never carry (see
+ * Reject a write of fields the Agent Builder's own row must never carry (see
* {@link AGENT_BUILDER_PROTECTED_FIELDS}). Only looks up the target row's `slug` when the
* incoming patch actually touches a protected field, so normal updates pay no extra query.
*/
- private stripAgentBuilderProtectedFields = async <T extends Record<string, any>>(
+ private assertNotAgentBuilderProtectedWrite = async (
agentId: string,
- data: T,
- protectedFields: readonly string[] = AGENT_BUILDER_PROTECTED_FIELDS,
- ): Promise<T> => {
- if (!protectedFields.some((field) => field in data)) return data;
+ data: Record<string, unknown>,
+ ) => {
+ if (!AGENT_BUILDER_PROTECTED_FIELDS.some((field) => data[field] !== undefined)) return;
const agent = await this.db.query.agents.findFirst({
columns: { slug: true },
where: and(eq(agents.id, agentId), this.ownership()),
});
- if (agent?.slug !== BUILTIN_AGENT_SLUGS.agentBuilder) return data;
-
- const sanitized = { ...data };
- for (const field of protectedFields) delete sanitized[field];
- return sanitized;
+ if (agent?.slug === BUILTIN_AGENT_SLUGS.agentBuilder) assertNoAgentBuilderProtectedFields(data);
};
/**
@@ -1422,9 +1431,16 @@ export class AgentModel {
// See AGENT_BUILDER_PROTECTED_FIELDS: some callers (e.g. the browser client's meta
// editor) route title/avatar/etc. through updateConfig() rather than update().
if (agent.slug === BUILTIN_AGENT_SLUGS.agentBuilder) {
- for (const field of AGENT_BUILDER_PROTECTED_FIELDS) delete restData[field];
+ assertNoAgentBuilderProtectedFields(restData as Record<string, unknown>);
}
+ // Only the columns this patch touches are written back. The row was read
+ // before the awaits above, so writing the whole merged row would restore
+ // any column another writer committed in between — e.g. a parallel
+ // `updatePrompt` losing its new systemRole to a concurrent config write.
+ const touchedColumns = new Set<string>(Object.keys(restData));
+ if (data.params) touchedColumns.add('params');
+
const mergedValue = merge(agent, restData);
// API bindings follow updateConfig's partial deep-merge contract. A user-provider patch must
@@ -1453,9 +1469,11 @@ export class AgentModel {
if (agent.slug === INBOX_SESSION_ID) {
if (mergedValue.agencyConfig?.heterogeneousProvider) {
delete mergedValue.agencyConfig.heterogeneousProvider;
+ touchedColumns.add('agencyConfig');
}
if (isHeterogeneousAgentModelId(mergedValue.model)) {
mergedValue.model = null;
+ touchedColumns.add('model');
}
}
@@ -1481,6 +1499,7 @@ export class AgentModel {
// ownership of the graph: drop the legacy chatConfig fields so the
// runtime's `??` fallback cannot resurrect an old snapshot.
if (mergedValue.chatConfig) {
+ touchedColumns.add('chatConfig');
const {
graph: _legacyGraph,
enableGraphMode: _legacyEnableGraphMode,
@@ -1489,6 +1508,7 @@ export class AgentModel {
mergedValue.chatConfig = restChatConfig as AgentItem['chatConfig'];
}
} else if (data.chatConfig && Object.hasOwn(data.chatConfig, 'graph')) {
+ touchedColumns.add('agencyConfig');
const legacyChatConfig = data.chatConfig as Record<string, unknown>;
mergedValue.agencyConfig = {
...mergedValue.agencyConfig,
@@ -1527,9 +1547,15 @@ export class AgentModel {
}
}
- // Remove timestamp fields to let Drizzle's $onUpdate handle them automatically
+ // Timestamp fields are left to Drizzle's $onUpdate.
+ touchedColumns.delete('updatedAt');
+ touchedColumns.delete('accessedAt');
+ touchedColumns.delete('createdAt');
- const { updatedAt: _, accessedAt: __, createdAt: ___, ...updateData } = mergedValue;
+ const updateData = Object.fromEntries(
+ Object.entries(mergedValue).filter(([column]) => touchedColumns.has(column)),
+ ) as Partial<typeof mergedValue>;
+ if (!Object.values(updateData).some((value) => value !== undefined)) return;
return this.db
.update(agents)
diff --git a/packages/database/src/schemas/agentOperations.ts b/packages/database/src/schemas/agentOperations.ts
index fa2f6555a46..dc42eb00f06 100644
--- a/packages/database/src/schemas/agentOperations.ts
+++ b/packages/database/src/schemas/agentOperations.ts
@@ -29,6 +29,8 @@ export interface AgentOperationError {
export interface AgentOperationAppContext {
defaultTaskAssigneeAgentId?: string;
documentId?: string | null;
+ /** The agent a builder run edits (scope `agent_builder`); the run itself is owned by the builder. */
+ editingAgentId?: string;
groupId?: string | null;
scope?: string | null;
sessionId?: string;