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(group-builder): keep member tools on the right group after createGroup (#19971)

Arvin Xu224ca0c5569f
diff --git a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.ts
index f9e038b105c..f27a123647d 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.ts
@@ -4,6 +4,7 @@ import {
selectEnableExpertise,
selectExpertise,
} from '@lobechat/agent-runtime';
+import { GroupAgentBuilderIdentifier } from '@lobechat/builtin-tool-group-agent-builder';
import { gatherContextFacts } from '@lobechat/mecha';
import type { ChatStreamPayload } from '@lobechat/model-runtime';
import { SpanStatusCode } from '@lobechat/observability-otel/api';
@@ -18,6 +19,7 @@ import {
createServerContextFactProviders,
resolveServerConnectorFeatures,
} from '@/server/modules/Mecha/ContextEngineering/providers';
+import { resolveBuilderGroupId } from '@/server/services/toolExecution/serverRuntimes/groupAgentBuilderTarget';
import type { RuntimeExecutorContext } from '../context';
import {
@@ -84,6 +86,19 @@ export const buildServerCallLlmContext = async ({
const agentId = state.origin?.agentId;
const topicId = ctx.topicId ?? state.origin?.topicId;
+ // `<current_group_context>` must describe the group the builder tools will
+ // write to β€” after a `createGroup` that is the new group, not the pinned one.
+ const editingGroupId =
+ ctx.serverDB && ctx.userId && resolved.enabledToolIds.includes(GroupAgentBuilderIdentifier)
+ ? await resolveBuilderGroupId({
+ db: ctx.serverDB,
+ editingGroupId: state.origin?.editingGroupId,
+ threadId: state.origin?.threadId,
+ topicId,
+ userId: ctx.userId,
+ workspaceId: state.origin?.workspaceId ?? ctx.workspaceId,
+ })
+ : state.origin?.editingGroupId;
// Which facts this turn needs is decided by the shared rules; the server
// only answers the lookups they ask for.
const facts = await gatherContextFacts(
@@ -98,7 +113,7 @@ export const buildServerCallLlmContext = async ({
agentId,
disabledPluginIds: state.world?.disabledPluginIds,
editingAgentId: state.origin?.editingAgentId,
- editingGroupId: state.origin?.editingGroupId,
+ editingGroupId,
enabledToolIds: resolved.enabledToolIds,
executionTarget,
features: resolveServerConnectorFeatures(),
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.builderEditingGroup.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.builderEditingGroup.test.ts
new file mode 100644
index 00000000000..477c9111c4e
--- /dev/null
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.builderEditingGroup.test.ts
@@ -0,0 +1,282 @@
+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 Group Agent Builder topic records the group it edits on
+ * `topics.metadata.editingGroupId`, but only a request sent from the group's
+ * builder panel (scope `group_agent_builder`) names that group. Continuing the
+ * same topic from any other surface arrives with scope `main`, and the run lost
+ * its target: every member tool answered "No active group found" (op origin
+ * `{ scope: 'main' }` with no group).
+ */
+describe('AiAgentService.execAgent - group builder editing target', () => {
+ let service: AiAgentService;
+ const mockDb = {} as any;
+ const userId = 'test-user-id';
+
+ const builderAgentConfig = {
+ chatConfig: {},
+ id: 'agt_group_builder',
+ model: 'gpt-4',
+ plugins: [],
+ provider: 'openai',
+ slug: 'group-agent-builder',
+ systemRole: 'You configure groups.',
+ };
+
+ 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({ ...builderAgentConfig });
+ service = new AiAgentService(mockDb, userId);
+ });
+
+ const createdAppContext = () => mockCreateOperation.mock.calls[0][0].appContext;
+
+ it('falls back to the group the topic was opened on when the request names none', async () => {
+ mockTopicFindById.mockResolvedValue({
+ agentId: 'agt_group_builder',
+ id: 'tpc_builder',
+ metadata: { editingGroupId: 'cg_edited' },
+ });
+
+ await service.execAgent({
+ agentId: 'agt_group_builder',
+ appContext: { scope: 'main', topicId: 'tpc_builder' },
+ prompt: 'Add a reviewer to the team',
+ });
+
+ expect(createdAppContext()).toMatchObject({ editingGroupId: 'cg_edited', scope: 'main' });
+ });
+
+ it('keeps the group the builder panel names over the topic record', async () => {
+ mockTopicFindById.mockResolvedValue({
+ agentId: 'agt_group_builder',
+ id: 'tpc_builder',
+ metadata: { editingGroupId: 'cg_old' },
+ });
+
+ await service.execAgent({
+ agentId: 'agt_group_builder',
+ appContext: {
+ editingGroupId: 'cg_panel',
+ scope: 'group_agent_builder',
+ topicId: 'tpc_builder',
+ },
+ prompt: 'Rename the group',
+ });
+
+ expect(createdAppContext()).toMatchObject({ editingGroupId: 'cg_panel' });
+ });
+
+ it('leaves ordinary topics without an editing group', async () => {
+ mockTopicFindById.mockResolvedValue({ agentId: 'agt_group_builder', id: 'tpc_plain' });
+
+ await service.execAgent({
+ agentId: 'agt_group_builder',
+ appContext: { scope: 'main', topicId: 'tpc_plain' },
+ prompt: 'Hello',
+ });
+
+ expect(createdAppContext().editingGroupId).toBeUndefined();
+ });
+});
diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.ts
index de94fa39e2b..57693308885 100644
--- a/apps/server/src/services/aiAgent/index.ts
+++ b/apps/server/src/services/aiAgent/index.ts
@@ -1080,6 +1080,7 @@ export class AiAgentService {
resolvedAgentId,
runFacts,
shareGate,
+ topicEditingGroupId: turn.topicEditingGroupId,
topicId,
trigger,
userMessageId: turn.userMessageId,
diff --git a/apps/server/src/services/aiAgent/pipeline/startOperation.ts b/apps/server/src/services/aiAgent/pipeline/startOperation.ts
index 98ce1170faf..af5b878f32d 100644
--- a/apps/server/src/services/aiAgent/pipeline/startOperation.ts
+++ b/apps/server/src/services/aiAgent/pipeline/startOperation.ts
@@ -86,6 +86,7 @@ export const startOperation = async (
provider,
resolvedAgentId,
shareGate,
+ topicEditingGroupId,
topicId,
trigger,
userMessageId,
@@ -124,6 +125,12 @@ export const startOperation = async (
userTimezone,
} = input;
const { audio, video, vision } = discovery.modelMediaCapabilities;
+ // A builder topic continued from another surface (scope `main`, an approval
+ // resume) arrives without the group it edits; the group the topic was opened
+ // on stands in, so the run still knows its target.
+ const editingGroupId =
+ (appContext?.scope === 'group_agent_builder' ? appContext.editingGroupId : undefined) ||
+ topicEditingGroupId;
log(
'execAgent: creating operation %s β€” agentDocuments=%d, knowledgeBases=%s, tools=%d, skills=%d',
@@ -214,9 +221,7 @@ export const startOperation = async (
// owned by the builtin builder agent, so the edited group only rides
// here. Read by the group-agent-builder server runtime and by the
// `<current_group_context>` injector.
- ...(appContext?.scope === 'group_agent_builder' && appContext?.editingGroupId
- ? { editingGroupId: appContext.editingGroupId }
- : {}),
+ ...(editingGroupId ? { editingGroupId } : {}),
// Run-scoped Agent Signal marker for background self-iteration / memory
// runs β€” lands in state.origin.signal so the completion path can
// project receipts/briefs. Undefined for ordinary chat runs.
diff --git a/apps/server/src/services/aiAgent/pipeline/turnSetup.ts b/apps/server/src/services/aiAgent/pipeline/turnSetup.ts
index 2c66d91c23c..8441459164c 100644
--- a/apps/server/src/services/aiAgent/pipeline/turnSetup.ts
+++ b/apps/server/src/services/aiAgent/pipeline/turnSetup.ts
@@ -382,6 +382,11 @@ export interface TurnSetupResult {
/** Rows THIS turn persisted β€” the history loader must exclude them. */
selfMessageIds: Set<string>;
topicBoundDeviceId?: string | null;
+ /**
+ * The group a reused Group Agent Builder topic was opened on
+ * (`metadata.editingGroupId`), for runs whose request does not name it.
+ */
+ topicEditingGroupId?: string;
topicId: string;
userMessageId?: string;
}
@@ -460,6 +465,7 @@ export const setupTurn = async (
let provider = agentConfig.provider!;
const heterogeneousProvider = agentConfig.agencyConfig?.heterogeneousProvider;
let pinnedHeterogeneousTopicModel: HeterogeneousTopicPin | undefined;
+ let topicEditingGroupId: string | undefined;
// Share-visitor fail-closed gate β€” reject a heterogeneous (Claude Code /
// Codex / …) agent BEFORE any topic/message row is written. Heterogeneous
@@ -582,6 +588,7 @@ export const setupTurn = async (
// The pinned model lives in the top-level `topics.model`/`provider` columns
// (config source of truth), NOT in metadata.
const existingTopic = await deps.topicModel.findById(topicId);
+ topicEditingGroupId = existingTopic?.metadata?.editingGroupId ?? undefined;
// Fail-closed guard: a non-share run must never operate on a share-visitor
// topic. `findById` is ownership-scoped but deliberately does NOT exclude
@@ -927,6 +934,7 @@ export const setupTurn = async (
runAttachments,
selfMessageIds,
topicBoundDeviceId,
+ topicEditingGroupId,
topicId,
userMessageId: userMessageRecord?.id,
};
diff --git a/apps/server/src/services/aiAgent/types.ts b/apps/server/src/services/aiAgent/types.ts
index d35b8dadc17..76e68dcb0c9 100644
--- a/apps/server/src/services/aiAgent/types.ts
+++ b/apps/server/src/services/aiAgent/types.ts
@@ -59,6 +59,8 @@ export interface ExecRunContext {
* ordinary (non-share) run.
*/
shareGate?: AgentShareGate;
+ /** The group a reused Group Agent Builder topic was opened on β€” see `TurnSetupResult`. */
+ topicEditingGroupId?: string;
/** Topic id β€” guaranteed to exist by the time pipeline stages run. */
topicId: string;
trigger?: string;
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/groupAgentBuilder.createGroupTarget.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/groupAgentBuilder.createGroupTarget.test.ts
new file mode 100644
index 00000000000..e2f63114ea4
--- /dev/null
+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/groupAgentBuilder.createGroupTarget.test.ts
@@ -0,0 +1,341 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { groupAgentBuilderRuntime } from '../groupAgentBuilder';
+
+const {
+ mockAddAgentsToGroup,
+ mockBatchCreate,
+ mockCreateGroupWithSupervisor,
+ mockFindById,
+ mockFindLatestPluginStateInTopic,
+ mockGetGroupAgentsWithMeta,
+ mockUpdateGroup,
+} = vi.hoisted(() => ({
+ mockAddAgentsToGroup: vi.fn(),
+ mockBatchCreate: vi.fn(),
+ mockCreateGroupWithSupervisor: vi.fn(),
+ mockFindById: vi.fn(),
+ mockFindLatestPluginStateInTopic: vi.fn(),
+ mockGetGroupAgentsWithMeta: vi.fn(),
+ mockUpdateGroup: vi.fn(),
+}));
+
+vi.mock('@/database/models/agent', () => ({
+ AgentModel: vi.fn(function () {
+ return {
+ batchCreate: mockBatchCreate,
+ getAgentConfigById: vi.fn(async () => null),
+ queryAgents: vi.fn(async () => []),
+ update: vi.fn(),
+ updateConfig: vi.fn(),
+ };
+ }),
+}));
+
+vi.mock('@/database/models/chatGroup', () => ({
+ ChatGroupModel: vi.fn(function () {
+ return {
+ addAgentsToGroup: mockAddAgentsToGroup,
+ findById: mockFindById,
+ getGroupAgentsWithMeta: mockGetGroupAgentsWithMeta,
+ removeAgentsFromGroup: vi.fn(),
+ update: mockUpdateGroup,
+ };
+ }),
+}));
+
+/** Messages / tool results the fake message model serves, keyed by id / tool call id. */
+let assistantMessages: Record<string, { tools?: unknown[] }> = {};
+let toolStates: Record<string, Record<string, unknown> | undefined> = {};
+
+vi.mock('@/database/models/message', () => ({
+ MessageModel: vi.fn(function () {
+ return {
+ findById: vi.fn(async (id: string) => assistantMessages[id]),
+ findLatestPluginStateInTopic: mockFindLatestPluginStateInTopic,
+ findMessagePlugin: vi.fn(async (id: string) =>
+ id in toolStates ? { id, state: toolStates[id] } : undefined,
+ ),
+ findToolMessageIdByToolCallId: vi.fn(async (toolCallId: string) =>
+ toolCallId in toolStates ? toolCallId : null,
+ ),
+ };
+ }),
+}));
+
+vi.mock('@/database/models/resourcePermission', () => ({
+ ResourcePermissionModel: vi.fn(function () {
+ return { getAccessLevel: vi.fn(), setAccessLevel: vi.fn() };
+ }),
+}));
+
+vi.mock('@/database/repositories/agentGroup', () => ({
+ AgentGroupRepository: vi.fn(function () {
+ return { createGroupWithSupervisor: mockCreateGroupWithSupervisor };
+ }),
+}));
+
+vi.mock('@/server/services/agentGroup', () => ({
+ AgentGroupService: vi.fn(function () {
+ return { normalizeGroupConfig: (config: unknown) => config };
+ }),
+}));
+
+vi.mock('@/server/services/resourcePermission', () => ({
+ assertCanPerformResourceAction: vi.fn(async () => undefined),
+}));
+
+vi.mock('../agentBuilder', () => ({
+ agentBuilderRuntime: {
+ factory: () => ({ updateConfig: vi.fn() }),
+ identifier: 'lobe-agent-builder',
+ },
+}));
+
+// Each tool call builds its own runtime, like `getServerRuntime` does per call,
+// so nothing can be carried over in memory between calls.
+const createRuntime = () =>
+ groupAgentBuilderRuntime.factory({
+ serverDB: {} as never,
+ toolManifestMap: {},
+ userId: 'user-1',
+ });
+
+/**
+ * Stand-in for the tool transport: it persists each tool result's `state` on the
+ * tool message, which is what a later call in the same topic reads back.
+ */
+const persistToolState = (topicState: Record<string, unknown> | undefined) =>
+ mockFindLatestPluginStateInTopic.mockResolvedValue(topicState);
+
+/**
+ * "createGroup succeeds, then every member tool says No active group found".
+ * Mirrors the production call sequence recorded in tpc_t7cFeao1KEWW /
+ * tpc_Ik31uOJ3BmWG: createGroup β†’ updateGroupPrompt β†’ createAgent /
+ * batchCreateAgents / inviteAgent.
+ */
+describe('group agent builder β€” members after createGroup', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockCreateGroupWithSupervisor.mockResolvedValue({
+ group: { id: 'cg_new' },
+ supervisorAgentId: 'agt_sup_new',
+ });
+ mockFindById.mockImplementation(async (id: string) => ({ id, title: id }));
+ mockGetGroupAgentsWithMeta.mockResolvedValue([]);
+ mockBatchCreate.mockResolvedValue([{ id: 'agt_m1', visibility: 'public' }]);
+ mockAddAgentsToGroup.mockResolvedValue({ added: ['agt_x'] });
+ mockUpdateGroup.mockResolvedValue({});
+ persistToolState(undefined);
+ });
+
+ // Run context as it looked on prod for all 12 vents: the run carried no
+ // editing group, so only an explicit groupId could name the new group β€” and
+ // the member tools had no such parameter.
+ it('without an editing group, member tools reach the group createGroup returned', async () => {
+ const ctx = { topicId: 'tpc_builder' } as never;
+
+ const created = await createRuntime().createGroup(
+ { title: 'Tim Brainstorming Bisnis' } as never,
+ ctx,
+ );
+ expect(created.success).toBe(true);
+ expect(created.content).toContain('cg_new');
+ persistToolState(created.state as Record<string, unknown>);
+
+ const promptNoId = await createRuntime().updateGroupPrompt({ prompt: 'x' } as never, ctx);
+ const create = await createRuntime().createAgent(
+ { systemRole: 'r', title: 'Strategist' } as never,
+ ctx,
+ );
+ const batch = await createRuntime().batchCreateAgents(
+ { agents: [{ title: 'A' }] } as never,
+ ctx,
+ );
+ const invite = await createRuntime().inviteAgent({ agentId: 'agt_x' } as never, ctx);
+
+ for (const result of [promptNoId, create, batch, invite]) {
+ expect(result.content).not.toBe('No active group found');
+ expect(result.success).toBe(true);
+ }
+ expect(mockAddAgentsToGroup.mock.calls.map(([groupId]) => groupId)).toEqual([
+ 'cg_new',
+ 'cg_new',
+ 'cg_new',
+ ]);
+ });
+
+ // Still present after the editing target was restored on the run origin: the
+ // run is pinned to the group the Home "create group" flow pre-created
+ // (editingGroupId), createGroup does not re-target the run, and member tools
+ // take no groupId β€” members silently land in the empty shell group.
+ it('members go to the group createGroup just made, not the pinned one', async () => {
+ const ctx = { editingGroupId: 'cg_shell', topicId: 'tpc_builder' } as never;
+
+ const created = await createRuntime().createGroup({ title: 'Dev Team' } as never, ctx);
+ expect(created.state).toMatchObject({ groupId: 'cg_new' });
+ persistToolState(created.state as Record<string, unknown>);
+
+ await createRuntime().createAgent({ systemRole: 'r', title: 'Tech Lead' } as never, ctx);
+
+ expect(mockAddAgentsToGroup).toHaveBeenCalledWith('cg_new', ['agt_m1']);
+ });
+
+ it('an explicit groupId wins over both the pinned and the created group', async () => {
+ const ctx = { editingGroupId: 'cg_shell', topicId: 'tpc_builder' } as never;
+ persistToolState({ groupId: 'cg_new' });
+
+ await createRuntime().createAgent(
+ { groupId: 'cg_named', systemRole: 'r', title: 'Tech Lead' } as never,
+ ctx,
+ );
+
+ expect(mockAddAgentsToGroup).toHaveBeenCalledWith('cg_named', ['agt_m1']);
+ expect(mockFindLatestPluginStateInTopic).not.toHaveBeenCalled();
+ });
+
+ it('keeps the pinned group while the conversation has created none', async () => {
+ const ctx = { editingGroupId: 'cg_shell', topicId: 'tpc_builder' } as never;
+
+ await createRuntime().createAgent({ systemRole: 'r', title: 'Tech Lead' } as never, ctx);
+
+ expect(mockFindLatestPluginStateInTopic).toHaveBeenCalledWith({
+ apiName: 'createGroup',
+ identifier: 'lobe-group-agent-builder',
+ threadId: null,
+ topicId: 'tpc_builder',
+ });
+ expect(mockAddAgentsToGroup).toHaveBeenCalledWith('cg_shell', ['agt_m1']);
+ });
+
+ // A builder topic can branch into threads. The created group is read back
+ // from the branch the tool call runs in, so a `createGroup` in one thread
+ // must not retarget its siblings or the main conversation.
+ it('reads the created group back from the current thread only', async () => {
+ const threadCtx = {
+ editingGroupId: 'cg_shell',
+ threadId: 'thd_branch',
+ topicId: 'tpc_builder',
+ } as never;
+ const mainCtx = { editingGroupId: 'cg_shell', topicId: 'tpc_builder' } as never;
+
+ await createRuntime().createAgent({ systemRole: 'r', title: 'Tech Lead' } as never, threadCtx);
+ await createRuntime().createAgent({ systemRole: 'r', title: 'Tech Lead' } as never, mainCtx);
+
+ expect(mockFindLatestPluginStateInTopic.mock.calls.map(([params]) => params)).toEqual([
+ {
+ apiName: 'createGroup',
+ identifier: 'lobe-group-agent-builder',
+ threadId: 'thd_branch',
+ topicId: 'tpc_builder',
+ },
+ {
+ apiName: 'createGroup',
+ identifier: 'lobe-group-agent-builder',
+ threadId: null,
+ topicId: 'tpc_builder',
+ },
+ ]);
+ });
+});
+
+/**
+ * One assistant message issues createGroup + updateGroup + updateGroupPrompt +
+ * createAgent. createGroup needs approval, so GeneralChatAgent runs the other
+ * three first; the created-group lookup finds nothing yet and would fall back to
+ * the pinned shell group β€” silently editing the wrong group.
+ */
+describe('group agent builder β€” siblings of a createGroup awaiting approval', () => {
+ const ctxFor = (toolCallId: string) =>
+ ({
+ assistantMessageId: 'msg_assistant',
+ editingGroupId: 'cg_shell',
+ toolCallId,
+ topicId: 'tpc_builder',
+ }) as never;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockFindById.mockImplementation(async (id: string) => ({ id, title: id }));
+ mockGetGroupAgentsWithMeta.mockResolvedValue([]);
+ mockBatchCreate.mockResolvedValue([{ id: 'agt_m1', visibility: 'public' }]);
+ mockAddAgentsToGroup.mockResolvedValue({ added: ['agt_m1'] });
+ mockUpdateGroup.mockResolvedValue({});
+ // createGroup has not run, so no created group is on record yet.
+ persistToolState(undefined);
+ assistantMessages = {
+ msg_assistant: {
+ tools: [
+ { apiName: 'createGroup', id: 'call_group', identifier: 'lobe-group-agent-builder' },
+ { apiName: 'updateGroup', id: 'call_update', identifier: 'lobe-group-agent-builder' },
+ {
+ apiName: 'updateGroupPrompt',
+ id: 'call_prompt',
+ identifier: 'lobe-group-agent-builder',
+ },
+ { apiName: 'createAgent', id: 'call_agent', identifier: 'lobe-group-agent-builder' },
+ ],
+ },
+ };
+ toolStates = {};
+ });
+
+ it('refuses dependent writes instead of editing the pinned group', async () => {
+ const update = await createRuntime().updateGroup(
+ { meta: { title: 'Dev Team' } } as never,
+ ctxFor('call_update'),
+ );
+ const prompt = await createRuntime().updateGroupPrompt(
+ { prompt: 'shared' } as never,
+ ctxFor('call_prompt'),
+ );
+ const agent = await createRuntime().createAgent(
+ { systemRole: 'r', title: 'Tech Lead' } as never,
+ ctxFor('call_agent'),
+ );
+
+ for (const result of [update, prompt, agent]) {
+ expect(result).toMatchObject({ error: { type: 'AwaitingCreateGroup' }, success: false });
+ }
+ expect(mockUpdateGroup).not.toHaveBeenCalled();
+ expect(mockAddAgentsToGroup).not.toHaveBeenCalled();
+ });
+
+ it('runs them on the created group once createGroup has returned', async () => {
+ toolStates = { call_group: { groupId: 'cg_new', success: true } };
+ persistToolState({ groupId: 'cg_new', success: true });
+
+ await createRuntime().createAgent(
+ { systemRole: 'r', title: 'Tech Lead' } as never,
+ ctxFor('call_agent'),
+ );
+
+ expect(mockAddAgentsToGroup).toHaveBeenCalledWith('cg_new', ['agt_m1']);
+ });
+
+ it('does not hold back a call that names its group', async () => {
+ await createRuntime().createAgent(
+ { groupId: 'cg_named', systemRole: 'r', title: 'Tech Lead' } as never,
+ ctxFor('call_agent'),
+ );
+
+ expect(mockAddAgentsToGroup).toHaveBeenCalledWith('cg_named', ['agt_m1']);
+ });
+
+ it('keeps the pinned group when the step has no createGroup', async () => {
+ assistantMessages = {
+ msg_assistant: {
+ tools: [
+ { apiName: 'createAgent', id: 'call_agent', identifier: 'lobe-group-agent-builder' },
+ ],
+ },
+ };
+
+ await createRuntime().createAgent(
+ { systemRole: 'r', title: 'Tech Lead' } as never,
+ ctxFor('call_agent'),
+ );
+
+ expect(mockAddAgentsToGroup).toHaveBeenCalledWith('cg_shell', ['agt_m1']);
+ });
+});
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/groupAgentBuilder.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/groupAgentBuilder.test.ts
index ecf252380a6..2f5c8e0e6ed 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/groupAgentBuilder.test.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/groupAgentBuilder.test.ts
@@ -11,6 +11,7 @@ const {
mockGetAccessLevel,
mockGetAgentConfigById,
mockGetGroupAgentsWithMeta,
+ mockGetResourceConfigAccess,
mockRemoveAgentsFromGroup,
mockSetAccessLevel,
mockUpdateAgent,
@@ -23,6 +24,7 @@ const {
mockGetAccessLevel: vi.fn(),
mockGetAgentConfigById: vi.fn(),
mockGetGroupAgentsWithMeta: vi.fn(),
+ mockGetResourceConfigAccess: vi.fn(),
mockRemoveAgentsFromGroup: vi.fn(),
mockSetAccessLevel: vi.fn(),
mockUpdateAgent: vi.fn(),
@@ -78,6 +80,10 @@ vi.mock('@/server/services/resourcePermission', () => ({
assertCanPerformResourceAction: vi.fn(async () => undefined),
}));
+vi.mock('@/server/routers/lambda/_helpers/resourceConfigGuard', () => ({
+ getResourceConfigAccess: mockGetResourceConfigAccess,
+}));
+
vi.mock('../agentBuilder', () => ({
agentBuilderRuntime: {
factory: () => ({ updateConfig: mockBuilderUpdateConfig }),
@@ -102,6 +108,7 @@ describe('groupAgentBuilderRuntime', () => {
mockGetGroupAgentsWithMeta.mockResolvedValue([
{ agentId: 'agt_sup', description: null, role: 'supervisor', title: 'Supervisor' },
]);
+ mockGetResourceConfigAccess.mockResolvedValue('full');
});
// The bug: gateway mode executes every builtin tool server-side, and a missing
@@ -297,4 +304,64 @@ describe('groupAgentBuilderRuntime', () => {
});
});
});
+ // An explicit `groupId` comes straight from the tool arguments, and the model
+ // predicates admit any public workspace row. Prompts are edit-level config
+ // (`resourceConfigGuard`), so a view/use member must not read them here.
+ describe('config access on an explicitly targeted group', () => {
+ const explicit = { agentId: 'agt_sup', groupId: 'cg_other' };
+
+ beforeEach(() => {
+ mockGetAgentConfigById.mockResolvedValue({ model: 'gpt-x', systemRole: 'secret prompt' });
+ });
+
+ it('returns the system prompt only with full config access', async () => {
+ const result = await createRuntime('ws_1').getAgentInfo(explicit, groupCtx);
+
+ expect(mockGetResourceConfigAccess).toHaveBeenCalledWith(
+ expect.objectContaining({ userId: 'user-1', workspaceId: 'ws_1' }),
+ 'agent',
+ 'agt_sup',
+ );
+ expect(result.state).toMatchObject({ systemRole: 'secret prompt' });
+ });
+
+ it('omits the system prompt for view/use access', async () => {
+ mockGetResourceConfigAccess.mockImplementation(async (_ctx, type) =>
+ type === 'agent' ? 'profile' : 'full',
+ );
+
+ const result = await createRuntime('ws_1').getAgentInfo(explicit, groupCtx);
+
+ expect(result.success).toBe(true);
+ expect(result.content).not.toContain('secret prompt');
+ expect(result.state).toMatchObject({ model: 'gpt-x', title: 'Supervisor' });
+ expect((result.state as { systemRole?: string }).systemRole).toBeUndefined();
+ });
+
+ it('hides a group the caller has no access to', async () => {
+ mockGetResourceConfigAccess.mockResolvedValue('none');
+
+ const result = await createRuntime('ws_1').getAgentInfo(explicit, groupCtx);
+
+ expect(result).toMatchObject({ error: { type: 'GroupNotFound' }, success: false });
+ expect(mockGetGroupAgentsWithMeta).not.toHaveBeenCalled();
+ expect(mockGetAgentConfigById).not.toHaveBeenCalled();
+ });
+
+ it('refuses to read or rewrite a member prompt without full config access', async () => {
+ mockGetResourceConfigAccess.mockImplementation(async (_ctx, type) =>
+ type === 'agent' ? 'profile' : 'full',
+ );
+
+ const result = await createRuntime('ws_1').updateAgentPrompt(
+ { ...explicit, prompt: 'overwrite' },
+ groupCtx,
+ );
+
+ expect(result).toMatchObject({ error: { type: 'Forbidden' }, success: false });
+ expect(result.content).not.toContain('secret prompt');
+ expect(mockGetAgentConfigById).not.toHaveBeenCalled();
+ expect(mockUpdateAgent).not.toHaveBeenCalled();
+ });
+ });
});
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/groupAgentBuilder.ts b/apps/server/src/services/toolExecution/serverRuntimes/groupAgentBuilder.ts
index 5dfb0b22a56..662c2dafa15 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/groupAgentBuilder.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/groupAgentBuilder.ts
@@ -11,7 +11,8 @@
*
* The edited group rides on `ctx.editingGroupId` (see `ExecAgentAppContext`),
* NOT `ctx.groupId`: the builder conversation is owned by the builtin builder
- * agent and must not be stamped as a group-chat turn.
+ * agent and must not be stamped as a group-chat turn. A group created in the
+ * conversation with `createGroup` takes over from it (`resolveBuilderGroupId`).
*
* Member creation mirrors `routers/lambda/agentGroup.ts` exactly β€” virtual
* agents, roster insert, and workspace access-level inheritance β€” so an agent
@@ -44,7 +45,10 @@ import type {
UpdateGroupPromptState,
UpdateGroupState,
} from '@lobechat/builtin-tool-group-agent-builder';
-import { GroupAgentBuilderIdentifier } from '@lobechat/builtin-tool-group-agent-builder';
+import {
+ AWAITING_CREATE_GROUP_RESULT,
+ GroupAgentBuilderIdentifier,
+} from '@lobechat/builtin-tool-group-agent-builder';
import { formatAgentProfile } from '@lobechat/prompts';
import { AgentModel } from '@/database/models/agent';
@@ -53,11 +57,13 @@ import { ResourcePermissionModel } from '@/database/models/resourcePermission';
import { AgentGroupRepository } from '@/database/repositories/agentGroup';
import { DEFAULT_RESOURCE_ACCESS_LEVELS } from '@/database/schemas';
import type { ChatGroupConfig } from '@/database/types/chatGroup';
+import { getResourceConfigAccess } from '@/server/routers/lambda/_helpers/resourceConfigGuard';
import { AgentGroupService } from '@/server/services/agentGroup';
import { assertCanPerformResourceAction } from '@/server/services/resourcePermission';
import { type ToolExecutionContext, type ToolExecutionResult } from '../types';
import { agentBuilderRuntime } from './agentBuilder';
+import { isAwaitingSiblingCreateGroup, resolveBuilderGroupId } from './groupAgentBuilderTarget';
import { type ServerRuntimeRegistration } from './types';
const handleError = (error: unknown, message: string): ToolExecutionResult => {
@@ -90,10 +96,42 @@ export const groupAgentBuilderRuntime: ServerRuntimeRegistration = {
const agentGroupRepo = new AgentGroupRepository(serverDB, userId, workspaceId);
const agentGroupService = new AgentGroupService(serverDB, userId, workspaceId);
- // The edited group is carried by `editingGroupId`; `groupId` is kept as a
- // fallback for callers that legitimately run inside a group chat turn.
- const resolveGroupId = (ctx: ToolExecutionContext, override?: string) =>
- override ?? ctx.editingGroupId ?? ctx.groupId ?? undefined;
+ // An explicit `groupId` argument wins. Otherwise the group this conversation
+ // is working on β€” a group made here with `createGroup`, else the pinned
+ // `editingGroupId`; `groupId` is kept as a fallback for callers that
+ // legitimately run inside a group chat turn.
+ const resolveGroupId = async (ctx: ToolExecutionContext, override?: string) =>
+ override ??
+ (await resolveBuilderGroupId({
+ db: serverDB,
+ editingGroupId: ctx.editingGroupId,
+ threadId: ctx.threadId,
+ topicId: ctx.topicId,
+ userId,
+ workspaceId,
+ })) ??
+ ctx.groupId ??
+ undefined;
+
+ /**
+ * A call that leaves its target to the conversation must not run ahead of a
+ * `createGroup` issued in the same step β€” see `isAwaitingSiblingCreateGroup`.
+ * An explicit `groupId` names its target, so it is never held back.
+ */
+ const awaitingCreateGroup = async (
+ ctx: ToolExecutionContext,
+ override?: string,
+ ): Promise<ToolExecutionResult | undefined> => {
+ if (override) return undefined;
+ const awaiting = await isAwaitingSiblingCreateGroup({
+ assistantMessageId: ctx.assistantMessageId,
+ db: serverDB,
+ toolCallId: ctx.toolCallId,
+ userId,
+ workspaceId,
+ });
+ return awaiting ? { ...AWAITING_CREATE_GROUP_RESULT } : undefined;
+ };
/**
* Mutating a group's roster or config is a group edit β€” same ACL as the
@@ -138,6 +176,25 @@ export const groupAgentBuilderRuntime: ServerRuntimeRegistration = {
);
};
+ /**
+ * Prompts and tools are edit-level config (`resourceConfigGuard`). The model
+ * predicates admit any public workspace row, and the target group/agent id
+ * can come straight from the tool arguments, so every config read or member
+ * config write goes through the same guard as the `agent` / `agentGroup`
+ * routers. Outside a workspace the guard returns `full`.
+ */
+ const getConfigAccess = (resourceType: 'agent' | 'agentGroup', resourceId: string) =>
+ getResourceConfigAccess({ db: serverDB, userId, workspaceId }, resourceType, resourceId);
+
+ const configAccessDenied = (agentId: string): ToolExecutionResult => ({
+ content: `No permission to access the configuration of agent "${agentId}"`,
+ error: {
+ message: `No permission to access the configuration of agent "${agentId}"`,
+ type: 'Forbidden',
+ },
+ success: false,
+ });
+
const findSupervisorAgentId = async (groupId: string) => {
const roster = await chatGroupModel.getGroupAgentsWithMeta(groupId);
return roster.find((member) => member.role === 'supervisor')?.agentId;
@@ -161,14 +218,24 @@ export const groupAgentBuilderRuntime: ServerRuntimeRegistration = {
params: GetAgentInfoParams,
ctx: ToolExecutionContext,
): Promise<ToolExecutionResult> => {
- const groupId = resolveGroupId(ctx);
+ const blocked = await awaitingCreateGroup(ctx, params.groupId);
+ if (blocked) return blocked;
+
+ const groupId = await resolveGroupId(ctx, params.groupId);
if (!groupId) return noGroupContext();
try {
+ // A group the caller cannot even view is reported as missing, the same
+ // way the `agentGroup` router hides it.
+ if ((await getConfigAccess('agentGroup', groupId)) === 'none') {
+ return groupNotFound(groupId);
+ }
+
const roster = await chatGroupModel.getGroupAgentsWithMeta(groupId);
const member = roster.find((item) => item.agentId === params.agentId);
+ const memberAccess = member ? await getConfigAccess('agent', params.agentId) : 'none';
- if (!member) {
+ if (!member || memberAccess === 'none') {
return {
content: `Agent "${params.agentId}" not found in this group`,
error: { message: `Agent "${params.agentId}" not found`, type: 'AgentNotFound' },
@@ -177,11 +244,13 @@ export const groupAgentBuilderRuntime: ServerRuntimeRegistration = {
}
const config = await agentModel.getAgentConfigById(params.agentId);
+ // View/use access gets the public profile only β€” the system prompt is
+ // edit-level config (`redactAgentConfig` keeps `model` but not `systemRole`).
const agent = {
description: member.description ?? undefined,
id: params.agentId,
model: config?.model ?? undefined,
- systemRole: config?.systemRole ?? undefined,
+ systemRole: memberAccess === 'full' ? (config?.systemRole ?? undefined) : undefined,
title: member.title ?? undefined,
};
@@ -289,7 +358,7 @@ export const groupAgentBuilderRuntime: ServerRuntimeRegistration = {
}
return {
- content: `Successfully created group "${params.title}" with ID: ${group.id}`,
+ content: `Successfully created group "${params.title}" with ID: ${group.id}. Later group and member tool calls in this conversation target it; pass groupId "${group.id}" to be explicit.`,
state: {
groupId: group.id,
success: true,
@@ -307,7 +376,10 @@ export const groupAgentBuilderRuntime: ServerRuntimeRegistration = {
params: CreateAgentParams,
ctx: ToolExecutionContext,
): Promise<ToolExecutionResult> => {
- const groupId = resolveGroupId(ctx);
+ const blocked = await awaitingCreateGroup(ctx, params.groupId);
+ if (blocked) return blocked;
+
+ const groupId = await resolveGroupId(ctx, params.groupId);
if (!groupId) return noGroupContext();
try {
@@ -351,7 +423,10 @@ export const groupAgentBuilderRuntime: ServerRuntimeRegistration = {
params: BatchCreateAgentsParams,
ctx: ToolExecutionContext,
): Promise<ToolExecutionResult> => {
- const groupId = resolveGroupId(ctx);
+ const blocked = await awaitingCreateGroup(ctx, params.groupId);
+ if (blocked) return blocked;
+
+ const groupId = await resolveGroupId(ctx, params.groupId);
if (!groupId) return noGroupContext();
try {
@@ -403,7 +478,10 @@ export const groupAgentBuilderRuntime: ServerRuntimeRegistration = {
params: InviteAgentParams,
ctx: ToolExecutionContext,
): Promise<ToolExecutionResult> => {
- const groupId = resolveGroupId(ctx);
+ const blocked = await awaitingCreateGroup(ctx, params.groupId);
+ if (blocked) return blocked;
+
+ const groupId = await resolveGroupId(ctx, params.groupId);
if (!groupId) return noGroupContext();
try {
@@ -455,7 +533,10 @@ export const groupAgentBuilderRuntime: ServerRuntimeRegistration = {
params: RemoveAgentParams,
ctx: ToolExecutionContext,
): Promise<ToolExecutionResult> => {
- const groupId = resolveGroupId(ctx);
+ const blocked = await awaitingCreateGroup(ctx, params.groupId);
+ if (blocked) return blocked;
+
+ const groupId = await resolveGroupId(ctx, params.groupId);
if (!groupId) return noGroupContext();
try {
@@ -514,7 +595,10 @@ export const groupAgentBuilderRuntime: ServerRuntimeRegistration = {
params: UpdateAgentPromptParams,
ctx: ToolExecutionContext,
): Promise<ToolExecutionResult> => {
- const groupId = resolveGroupId(ctx);
+ const blocked = await awaitingCreateGroup(ctx, params.groupId);
+ if (blocked) return blocked;
+
+ const groupId = await resolveGroupId(ctx, params.groupId);
if (!groupId) return noGroupContext();
try {
@@ -529,6 +613,12 @@ export const groupAgentBuilderRuntime: ServerRuntimeRegistration = {
};
}
+ // Group edit alone is not enough: a linked standalone member keeps its
+ // own ACL, and its prompt is edit-level config.
+ if ((await getConfigAccess('agent', params.agentId)) !== 'full') {
+ return configAccessDenied(params.agentId);
+ }
+
const previous = await agentModel.getAgentConfigById(params.agentId);
// Clear `editorData` alongside `systemRole`: the profile editor treats
@@ -560,7 +650,10 @@ export const groupAgentBuilderRuntime: ServerRuntimeRegistration = {
params: UpdateGroupParams,
ctx: ToolExecutionContext,
): Promise<ToolExecutionResult> => {
- const groupId = resolveGroupId(ctx, params.groupId);
+ const blocked = await awaitingCreateGroup(ctx, params.groupId);
+ if (blocked) return blocked;
+
+ const groupId = await resolveGroupId(ctx, params.groupId);
if (!groupId) return noGroupContext();
const { config, meta } = params;
@@ -643,7 +736,10 @@ export const groupAgentBuilderRuntime: ServerRuntimeRegistration = {
params: UpdateGroupPromptParams,
ctx: ToolExecutionContext,
): Promise<ToolExecutionResult> => {
- const groupId = resolveGroupId(ctx, params.groupId);
+ const blocked = await awaitingCreateGroup(ctx, params.groupId);
+ if (blocked) return blocked;
+
+ const groupId = await resolveGroupId(ctx, params.groupId);
if (!groupId) return noGroupContext();
try {
@@ -687,7 +783,10 @@ export const groupAgentBuilderRuntime: ServerRuntimeRegistration = {
params: UpdateAgentConfigWithIdParams,
ctx: ToolExecutionContext,
): Promise<ToolExecutionResult> => {
- const groupId = resolveGroupId(ctx);
+ const blocked = await awaitingCreateGroup(ctx);
+ if (blocked) return blocked;
+
+ const groupId = await resolveGroupId(ctx);
const { agentId: paramAgentId, ...rest } = params;
// A caller-supplied id has to be confirmed against this group's roster
@@ -731,7 +830,10 @@ export const groupAgentBuilderRuntime: ServerRuntimeRegistration = {
params: InstallPluginParams,
ctx: ToolExecutionContext,
): Promise<ToolExecutionResult> => {
- const groupId = resolveGroupId(ctx);
+ const blocked = await awaitingCreateGroup(ctx);
+ if (blocked) return blocked;
+
+ const groupId = await resolveGroupId(ctx);
const agentId = groupId ? await findSupervisorAgentId(groupId) : undefined;
if (!agentId) {
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/groupAgentBuilderTarget.ts b/apps/server/src/services/toolExecution/serverRuntimes/groupAgentBuilderTarget.ts
new file mode 100644
index 00000000000..123f4973483
--- /dev/null
+++ b/apps/server/src/services/toolExecution/serverRuntimes/groupAgentBuilderTarget.ts
@@ -0,0 +1,103 @@
+import {
+ findSiblingCreateGroupCallIds,
+ GroupAgentBuilderApiName,
+ GroupAgentBuilderIdentifier,
+} from '@lobechat/builtin-tool-group-agent-builder';
+import type { LobeChatDatabase } from '@lobechat/database';
+
+import { MessageModel } from '@/database/models/message';
+
+interface ResolveBuilderGroupIdParams {
+ db: LobeChatDatabase;
+ /** The group the run was opened on (`state.origin.editingGroupId`). */
+ editingGroupId?: string;
+ /** The branch the run is on; `null`/absent means the main conversation. */
+ threadId?: string | null;
+ topicId?: string;
+ userId: string;
+ workspaceId?: string;
+}
+
+/**
+ * The group a Group Agent Builder conversation is working on.
+ *
+ * A run is pinned to the group it was opened on, but `createGroup` can make a
+ * new one mid-conversation β€” from then on "the group" means the new one, both
+ * for the rest of this run and for later runs in the same topic. The run's
+ * origin is frozen, so the switch is read back from the conversation itself:
+ * the newest `createGroup` result on the run's branch wins over the pinned
+ * group. Only that branch counts β€” a group created in a sibling thread must
+ * not retarget this one.
+ */
+export const resolveBuilderGroupId = async ({
+ db,
+ editingGroupId,
+ threadId,
+ topicId,
+ userId,
+ workspaceId,
+}: ResolveBuilderGroupIdParams): Promise<string | undefined> => {
+ if (topicId) {
+ const created = await new MessageModel(db, userId, workspaceId).findLatestPluginStateInTopic({
+ apiName: GroupAgentBuilderApiName.createGroup,
+ identifier: GroupAgentBuilderIdentifier,
+ threadId: threadId ?? null,
+ topicId,
+ });
+ if (typeof created?.groupId === 'string' && created.groupId) return created.groupId;
+ }
+
+ return editingGroupId;
+};
+
+interface AwaitingSiblingCreateGroupParams {
+ /** The assistant message that issued this tool call (and its siblings). */
+ assistantMessageId?: string;
+ db: LobeChatDatabase;
+ toolCallId?: string;
+ userId: string;
+ workspaceId?: string;
+}
+
+/**
+ * Whether a `createGroup` issued in the same step as this call has not returned
+ * a group yet.
+ *
+ * `createGroup` needs approval, so the runtime runs its siblings first β€” before
+ * any group exists. Resolving "the group" then falls back to the pinned one and
+ * a write meant for the new group lands on the old. Such a call has to be
+ * refused rather than guessed at; once `createGroup` has produced its group the
+ * normal resolution applies.
+ */
+export const isAwaitingSiblingCreateGroup = async ({
+ assistantMessageId,
+ db,
+ toolCallId,
+ userId,
+ workspaceId,
+}: AwaitingSiblingCreateGroupParams): Promise<boolean> => {
+ if (!assistantMessageId) return false;
+
+ const messageModel = new MessageModel(db, userId, workspaceId);
+ const assistant = await messageModel.findById(assistantMessageId);
+ const siblingIds = findSiblingCreateGroupCallIds(
+ assistant?.tools as Parameters<typeof findSiblingCreateGroupCallIds>[0],
+ toolCallId,
+ );
+ if (siblingIds.length === 0) return false;
+
+ const createdGroupIds = await Promise.all(
+ siblingIds.map(async (siblingId) => {
+ const toolMessageId = await messageModel.findToolMessageIdByToolCallId(
+ siblingId,
+ assistantMessageId,
+ );
+ const plugin = toolMessageId
+ ? await messageModel.findMessagePlugin(toolMessageId)
+ : undefined;
+ return plugin?.state?.groupId;
+ }),
+ );
+
+ return createdGroupIds.some((groupId) => typeof groupId !== 'string' || !groupId);
+};
diff --git a/packages/builtin-tool-group-agent-builder/src/createGroupOrdering.ts b/packages/builtin-tool-group-agent-builder/src/createGroupOrdering.ts
new file mode 100644
index 00000000000..41fbbaeb341
--- /dev/null
+++ b/packages/builtin-tool-group-agent-builder/src/createGroupOrdering.ts
@@ -0,0 +1,41 @@
+import { GroupAgentBuilderApiName, GroupAgentBuilderIdentifier } from './types';
+
+interface ToolCallRef {
+ apiName?: string;
+ id?: string;
+ identifier?: string;
+}
+
+/**
+ * The `createGroup` calls the model issued in the same assistant message as
+ * `toolCallId`.
+ *
+ * Calls from one message are not run in the order the model wrote them:
+ * `createGroup` needs approval, so the agent runtime executes the siblings that
+ * don't *before* parking for it. A sibling that relies on "the group this
+ * conversation created" would then run while no group has been created yet and
+ * silently fall back to the pinned group. Callers use this to spot that window.
+ */
+export const findSiblingCreateGroupCallIds = (
+ tools: ToolCallRef[] | null | undefined,
+ toolCallId: string | undefined,
+): string[] =>
+ (tools ?? [])
+ .filter(
+ (tool) =>
+ tool.identifier === GroupAgentBuilderIdentifier &&
+ tool.apiName === GroupAgentBuilderApiName.createGroup &&
+ !!tool.id &&
+ tool.id !== toolCallId,
+ )
+ .map((tool) => tool.id!);
+
+const AWAITING_CREATE_GROUP_MESSAGE =
+ 'Not run: createGroup was called in the same step and has not returned yet (it may still be waiting for approval), so this call cannot tell which group to change. Call it again after createGroup returns, passing the groupId it returned.';
+
+/** Result for a call that would otherwise run ahead of its sibling `createGroup`. */
+export const AWAITING_CREATE_GROUP_RESULT = {
+ content: AWAITING_CREATE_GROUP_MESSAGE,
+ error: { message: AWAITING_CREATE_GROUP_MESSAGE, type: 'AwaitingCreateGroup' },
+ success: false,
+};
diff --git a/packages/builtin-tool-group-agent-builder/src/executor.test.ts b/packages/builtin-tool-group-agent-builder/src/executor.test.ts
index dc642c78c87..3ae2da3b21c 100644
--- a/packages/builtin-tool-group-agent-builder/src/executor.test.ts
+++ b/packages/builtin-tool-group-agent-builder/src/executor.test.ts
@@ -4,13 +4,21 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import { groupAgentBuilderExecutor } from './executor';
import { GroupAgentBuilderApiName, GroupAgentBuilderIdentifier } from './types';
-const { mockCreateAgent, mockRefreshGroupDetail, mockRefreshGroups, mockSetAgentBuilderContent } =
- vi.hoisted(() => ({
- mockCreateAgent: vi.fn(),
- mockRefreshGroupDetail: vi.fn(),
- mockRefreshGroups: vi.fn(),
- mockSetAgentBuilderContent: vi.fn(),
- }));
+const {
+ mockCreateAgent,
+ mockRefreshGroupDetail,
+ mockRefreshGroups,
+ mockSetAgentBuilderContent,
+ mockUpdateGroup,
+ mockUpdateGroupPrompt,
+} = vi.hoisted(() => ({
+ mockCreateAgent: vi.fn(),
+ mockRefreshGroupDetail: vi.fn(),
+ mockRefreshGroups: vi.fn(),
+ mockSetAgentBuilderContent: vi.fn(),
+ mockUpdateGroup: vi.fn(),
+ mockUpdateGroupPrompt: vi.fn(),
+}));
let activeGroupId: string | undefined = 'cg_1';
@@ -22,6 +30,27 @@ vi.mock('@/store/agentGroup', () => ({
}),
}));
+let dbMessagesMap: Record<string, unknown[]> = {};
+
+vi.mock('@/store/chat', () => ({
+ useChatStore: { getState: () => ({ dbMessagesMap }) },
+}));
+
+/** A builder conversation whose earlier `createGroup` produced `cg_new`. */
+const conversationWithCreatedGroup = () => ({
+ 'builder-topic': [
+ { id: 'msg_user', role: 'user' },
+ {
+ id: 'msg_create_group',
+ plugin: { apiName: 'createGroup', identifier: GroupAgentBuilderIdentifier },
+ pluginState: { groupId: 'cg_new', success: true },
+ role: 'tool',
+ tool_call_id: 'call_create_group',
+ },
+ { id: 'msg_create_agent', role: 'tool', tool_call_id: 'call_create_agent' },
+ ],
+});
+
vi.mock('@/store/groupProfile', () => ({
useGroupProfileStore: {
getState: () => ({ setAgentBuilderContent: mockSetAgentBuilderContent }),
@@ -39,7 +68,11 @@ vi.mock('@lobechat/agent-manager-runtime', () => ({
vi.mock('./ExecutionRuntime', () => ({
GroupAgentBuilderExecutionRuntime: vi.fn(function () {
- return { createAgent: mockCreateAgent };
+ return {
+ createAgent: mockCreateAgent,
+ updateGroup: mockUpdateGroup,
+ updateGroupPrompt: mockUpdateGroupPrompt,
+ };
}),
}));
@@ -55,6 +88,7 @@ describe('GroupAgentBuilderExecutor', () => {
beforeEach(() => {
vi.clearAllMocks();
activeGroupId = 'cg_1';
+ dbMessagesMap = {};
});
describe('group context resolution', () => {
@@ -75,6 +109,174 @@ describe('GroupAgentBuilderExecutor', () => {
);
});
+ // Client-runtime counterpart of the server fix: createGroup does not make
+ // the new group active, so without reading it back from the conversation a
+ // member tool without groupId lands in the old (shell) group.
+ it('follows the group createGroup made earlier in this conversation', async () => {
+ dbMessagesMap = conversationWithCreatedGroup();
+ mockCreateAgent.mockResolvedValue({ content: 'ok', success: true });
+
+ await groupAgentBuilderExecutor.createAgent({ systemRole: 'x', title: 'PM' }, {
+ messageId: 'msg_create_agent',
+ } as BuiltinToolContext);
+
+ expect(mockCreateAgent).toHaveBeenCalledWith(
+ 'cg_new',
+ expect.objectContaining({ title: 'PM' }),
+ );
+ });
+
+ it('an explicit groupId wins over the created group', async () => {
+ dbMessagesMap = conversationWithCreatedGroup();
+ mockCreateAgent.mockResolvedValue({ content: 'ok', success: true });
+
+ await groupAgentBuilderExecutor.createAgent(
+ { groupId: 'cg_named', systemRole: 'x', title: 'PM' },
+ {
+ messageId: 'msg_create_agent',
+ } as BuiltinToolContext,
+ );
+
+ expect(mockCreateAgent).toHaveBeenCalledWith('cg_named', expect.anything());
+ });
+
+ // Group-level writes resolve their target inside the execution runtime,
+ // which only knows the profile page's active group β€” the created group has
+ // to be handed to it, or `createGroup` β†’ `updateGroupPrompt` edits the shell.
+ it('group-level writes follow the group createGroup made in this conversation', async () => {
+ dbMessagesMap = conversationWithCreatedGroup();
+ const ctx = { messageId: 'msg_create_agent' } as BuiltinToolContext;
+
+ await groupAgentBuilderExecutor.updateGroupPrompt({ prompt: 'shared' }, ctx);
+ await groupAgentBuilderExecutor.updateGroup({ meta: { title: 'Dev Team' } }, ctx);
+
+ expect(mockUpdateGroupPrompt).toHaveBeenCalledWith(
+ expect.objectContaining({ groupId: 'cg_new', prompt: 'shared' }),
+ );
+ expect(mockUpdateGroup).toHaveBeenCalledWith(
+ expect.objectContaining({ groupId: 'cg_new', meta: { title: 'Dev Team' } }),
+ );
+ });
+
+ it('group-level writes keep an explicit groupId and otherwise defer to the runtime', async () => {
+ dbMessagesMap = conversationWithCreatedGroup();
+
+ await groupAgentBuilderExecutor.updateGroupPrompt({ groupId: 'cg_named', prompt: 'p' }, {
+ messageId: 'msg_create_agent',
+ } as BuiltinToolContext);
+ // No group created in this conversation: leave the target to the runtime's
+ // own active-group resolution.
+ await groupAgentBuilderExecutor.updateGroup(
+ { meta: { title: 'T' } },
+ {} as BuiltinToolContext,
+ );
+
+ expect(mockUpdateGroupPrompt).toHaveBeenCalledWith(
+ expect.objectContaining({ groupId: 'cg_named' }),
+ );
+ expect(mockUpdateGroup.mock.calls[0][0].groupId).toBeUndefined();
+ });
+
+ // One assistant message issues createGroup + updateGroupPrompt + createAgent.
+ // createGroup needs approval, so the runtime runs the other two first β€” at
+ // that point no group has been created yet and they would silently edit the
+ // pinned/active group. They must not run until createGroup has returned.
+ describe('mixed batch with createGroup still awaiting approval', () => {
+ const mixedBatch = (createGroupState?: Record<string, unknown>) => ({
+ 'builder-topic': [
+ { id: 'msg_user', role: 'user' },
+ {
+ id: 'msg_assistant',
+ role: 'assistant',
+ tools: [
+ {
+ apiName: 'createGroup',
+ id: 'call_create_group',
+ identifier: GroupAgentBuilderIdentifier,
+ },
+ {
+ apiName: 'updateGroupPrompt',
+ id: 'call_prompt',
+ identifier: GroupAgentBuilderIdentifier,
+ },
+ { apiName: 'createAgent', id: 'call_agent', identifier: GroupAgentBuilderIdentifier },
+ ],
+ },
+ {
+ id: 'msg_create_group',
+ parentId: 'msg_assistant',
+ plugin: { apiName: 'createGroup', identifier: GroupAgentBuilderIdentifier },
+ pluginState: createGroupState,
+ role: 'tool',
+ tool_call_id: 'call_create_group',
+ },
+ {
+ id: 'msg_prompt',
+ parentId: 'msg_assistant',
+ role: 'tool',
+ tool_call_id: 'call_prompt',
+ },
+ { id: 'msg_agent', parentId: 'msg_assistant', role: 'tool', tool_call_id: 'call_agent' },
+ ],
+ });
+
+ it('refuses sibling writes instead of editing the active group', async () => {
+ dbMessagesMap = mixedBatch();
+
+ const prompt = await groupAgentBuilderExecutor.updateGroupPrompt({ prompt: 'shared' }, {
+ anchorMessageId: 'msg_assistant',
+ messageId: 'msg_prompt',
+ toolCallId: 'call_prompt',
+ } as BuiltinToolContext);
+ const agent = await groupAgentBuilderExecutor.createAgent(
+ { systemRole: 'x', title: 'PM' },
+ {
+ anchorMessageId: 'msg_assistant',
+ messageId: 'msg_agent',
+ toolCallId: 'call_agent',
+ } as BuiltinToolContext,
+ );
+
+ for (const result of [prompt, agent]) {
+ expect(result).toMatchObject({
+ error: { type: 'AwaitingCreateGroup' },
+ success: false,
+ });
+ }
+ expect(mockUpdateGroupPrompt).not.toHaveBeenCalled();
+ expect(mockCreateAgent).not.toHaveBeenCalled();
+ });
+
+ it('lets the siblings through once createGroup has returned its group', async () => {
+ dbMessagesMap = mixedBatch({ groupId: 'cg_new', success: true });
+ mockCreateAgent.mockResolvedValue({ content: 'ok', success: true });
+
+ await groupAgentBuilderExecutor.createAgent({ systemRole: 'x', title: 'PM' }, {
+ anchorMessageId: 'msg_assistant',
+ messageId: 'msg_agent',
+ toolCallId: 'call_agent',
+ } as BuiltinToolContext);
+
+ expect(mockCreateAgent).toHaveBeenCalledWith('cg_new', expect.anything());
+ });
+
+ it('an explicit groupId is not held back', async () => {
+ dbMessagesMap = mixedBatch();
+ mockCreateAgent.mockResolvedValue({ content: 'ok', success: true });
+
+ await groupAgentBuilderExecutor.createAgent(
+ { groupId: 'cg_named', systemRole: 'x', title: 'PM' },
+ {
+ anchorMessageId: 'msg_assistant',
+ messageId: 'msg_agent',
+ toolCallId: 'call_agent',
+ } as BuiltinToolContext,
+ );
+
+ expect(mockCreateAgent).toHaveBeenCalledWith('cg_named', expect.anything());
+ });
+ });
+
it('reports a structured error when there is no group at all', async () => {
activeGroupId = undefined;
@@ -97,6 +299,20 @@ describe('GroupAgentBuilderExecutor', () => {
expect(mockRefreshGroupDetail).toHaveBeenCalledWith('cg_1');
});
+ it('refreshes the group createGroup made in this conversation', async () => {
+ dbMessagesMap = conversationWithCreatedGroup();
+
+ await groupAgentBuilderExecutor.onAfterCall({
+ apiName: GroupAgentBuilderApiName.createAgent,
+ identifier: GroupAgentBuilderIdentifier,
+ params: { title: 'PM' },
+ result: { content: '', success: true },
+ toolCallId: 'call_create_agent',
+ });
+
+ expect(mockRefreshGroupDetail).toHaveBeenCalledWith('cg_new');
+ });
+
it('does not refresh when the tool call failed', async () => {
await afterCall(GroupAgentBuilderApiName.createAgent, { title: 'PM' }, false);
diff --git a/packages/builtin-tool-group-agent-builder/src/executor.ts b/packages/builtin-tool-group-agent-builder/src/executor.ts
index a01c4977395..b89064692b4 100644
--- a/packages/builtin-tool-group-agent-builder/src/executor.ts
+++ b/packages/builtin-tool-group-agent-builder/src/executor.ts
@@ -16,8 +16,10 @@ import { BaseExecutor } from '@lobechat/types';
import { agentService } from '@/services/agent';
import { discoverService } from '@/services/discover';
import { getChatGroupStoreState } from '@/store/agentGroup';
+import { useChatStore } from '@/store/chat';
import { useGroupProfileStore } from '@/store/groupProfile';
+import { AWAITING_CREATE_GROUP_RESULT, findSiblingCreateGroupCallIds } from './createGroupOrdering';
import { GroupAgentBuilderExecutionRuntime } from './ExecutionRuntime';
import type {
BatchCreateAgentsParams,
@@ -53,14 +55,80 @@ const GROUP_WRITE_APIS = new Set<string>([
GroupAgentBuilderApiName.updateGroupPrompt,
]);
+/**
+ * Client mirror of the server's `resolveBuilderGroupId`: once `createGroup` has
+ * run in this conversation, "the group" means the new one, not the group the
+ * profile page has active. The conversation holding this tool call is already
+ * in the chat store, so the newest `createGroup` result is read back from it.
+ */
+const findGroupCreatedInConversation = ({
+ messageId,
+ toolCallId,
+}: {
+ messageId?: string;
+ toolCallId?: string;
+}): string | undefined => {
+ if (!messageId && !toolCallId) return undefined;
+
+ const conversation = Object.values(useChatStore.getState().dbMessagesMap).find((messages) =>
+ messages.some(
+ (m) => (messageId && m.id === messageId) || (toolCallId && m.tool_call_id === toolCallId),
+ ),
+ );
+ if (!conversation) return undefined;
+
+ for (let i = conversation.length - 1; i >= 0; i--) {
+ const { plugin, pluginState } = conversation[i];
+ if (
+ plugin?.identifier === GroupAgentBuilderIdentifier &&
+ plugin.apiName === GroupAgentBuilderApiName.createGroup &&
+ typeof pluginState?.groupId === 'string'
+ )
+ return pluginState.groupId;
+ }
+
+ return undefined;
+};
+
+/**
+ * Client mirror of the server's `isAwaitingSiblingCreateGroup`: `createGroup`
+ * needs approval, so the runtime runs the calls issued alongside it first. A
+ * call that leaves its target to the conversation would then act on the active
+ * group instead of the one about to be created, so it is refused until that
+ * `createGroup` has returned its group. An explicit `groupId` is never held back.
+ */
+const awaitingCreateGroup = (
+ ctx: BuiltinToolContext,
+ override?: string,
+): BuiltinToolResult | undefined => {
+ if (override || !ctx.anchorMessageId) return undefined;
+
+ const conversation = Object.values(useChatStore.getState().dbMessagesMap).find((messages) =>
+ messages.some((m) => m.id === ctx.anchorMessageId),
+ );
+ const assistant = conversation?.find((m) => m.id === ctx.anchorMessageId);
+ const siblingIds = findSiblingCreateGroupCallIds(assistant?.tools, ctx.toolCallId);
+
+ const awaiting = siblingIds.some((siblingId) => {
+ const groupId = conversation?.find((m) => m.tool_call_id === siblingId)?.pluginState?.groupId;
+ return typeof groupId !== 'string' || !groupId;
+ });
+
+ return awaiting ? { ...AWAITING_CREATE_GROUP_RESULT } : undefined;
+};
+
/**
* The Group Agent Builder conversation is keyed by the builtin builder agent, so
* its ConversationContext deliberately carries no groupId. The edited group is
* whatever the profile page has active β€” the same source `resolveGroupTarget`
* already uses for the group-level APIs.
*/
-const resolveActiveGroupId = (ctx: BuiltinToolContext): string | undefined =>
- ctx.groupId ?? getChatGroupStoreState().activeGroupId ?? undefined;
+const resolveActiveGroupId = (ctx: BuiltinToolContext, override?: string): string | undefined =>
+ override ??
+ findGroupCreatedInConversation({ messageId: ctx.messageId }) ??
+ ctx.groupId ??
+ getChatGroupStoreState().activeGroupId ??
+ undefined;
const NO_GROUP_CONTEXT: BuiltinToolResult = {
content: 'No active group found',
@@ -78,7 +146,10 @@ class GroupAgentBuilderExecutor extends BaseExecutor<typeof GroupAgentBuilderApi
params: GetAgentInfoParams,
ctx: BuiltinToolContext,
): Promise<BuiltinToolResult> => {
- return groupAgentBuilderRuntime.getAgentInfo(ctx.groupId, params);
+ const blocked = awaitingCreateGroup(ctx, params.groupId);
+ if (blocked) return blocked;
+
+ return groupAgentBuilderRuntime.getAgentInfo(resolveActiveGroupId(ctx, params.groupId), params);
};
// ==================== Group Member Management ====================
@@ -95,7 +166,10 @@ class GroupAgentBuilderExecutor extends BaseExecutor<typeof GroupAgentBuilderApi
params: CreateAgentParams,
ctx: BuiltinToolContext,
): Promise<BuiltinToolResult> => {
- const groupId = resolveActiveGroupId(ctx);
+ const blocked = awaitingCreateGroup(ctx, params.groupId);
+ if (blocked) return blocked;
+
+ const groupId = resolveActiveGroupId(ctx, params.groupId);
if (!groupId) return NO_GROUP_CONTEXT;
@@ -106,7 +180,10 @@ class GroupAgentBuilderExecutor extends BaseExecutor<typeof GroupAgentBuilderApi
params: BatchCreateAgentsParams,
ctx: BuiltinToolContext,
): Promise<BuiltinToolResult> => {
- const groupId = resolveActiveGroupId(ctx);
+ const blocked = awaitingCreateGroup(ctx, params.groupId);
+ if (blocked) return blocked;
+
+ const groupId = resolveActiveGroupId(ctx, params.groupId);
if (!groupId) return NO_GROUP_CONTEXT;
@@ -117,7 +194,10 @@ class GroupAgentBuilderExecutor extends BaseExecutor<typeof GroupAgentBuilderApi
params: InviteAgentParams,
ctx: BuiltinToolContext,
): Promise<BuiltinToolResult> => {
- const groupId = resolveActiveGroupId(ctx);
+ const blocked = awaitingCreateGroup(ctx, params.groupId);
+ if (blocked) return blocked;
+
+ const groupId = resolveActiveGroupId(ctx, params.groupId);
if (!groupId) return NO_GROUP_CONTEXT;
@@ -128,7 +208,10 @@ class GroupAgentBuilderExecutor extends BaseExecutor<typeof GroupAgentBuilderApi
params: RemoveAgentParams,
ctx: BuiltinToolContext,
): Promise<BuiltinToolResult> => {
- const groupId = resolveActiveGroupId(ctx);
+ const blocked = awaitingCreateGroup(ctx, params.groupId);
+ if (blocked) return blocked;
+
+ const groupId = resolveActiveGroupId(ctx, params.groupId);
if (!groupId) return NO_GROUP_CONTEXT;
@@ -141,21 +224,42 @@ class GroupAgentBuilderExecutor extends BaseExecutor<typeof GroupAgentBuilderApi
params: UpdateAgentPromptParams,
ctx: BuiltinToolContext,
): Promise<BuiltinToolResult> => {
- const groupId = resolveActiveGroupId(ctx);
+ const blocked = awaitingCreateGroup(ctx, params.groupId);
+ if (blocked) return blocked;
+
+ const groupId = resolveActiveGroupId(ctx, params.groupId);
if (!groupId) return NO_GROUP_CONTEXT;
return groupAgentBuilderRuntime.updateAgentPrompt(groupId, params);
};
- updateGroup = async (params: UpdateGroupParams): Promise<BuiltinToolResult> => {
- return groupAgentBuilderRuntime.updateGroup(params);
+ // The runtime resolves a missing `groupId` to the profile page's active
+ // group, so a group created in this conversation has to be handed in here.
+ updateGroup = async (
+ params: UpdateGroupParams,
+ ctx: BuiltinToolContext,
+ ): Promise<BuiltinToolResult> => {
+ const blocked = awaitingCreateGroup(ctx, params.groupId);
+ if (blocked) return blocked;
+
+ return groupAgentBuilderRuntime.updateGroup({
+ ...params,
+ groupId: params.groupId ?? findGroupCreatedInConversation({ messageId: ctx.messageId }),
+ });
};
- updateGroupPrompt = async (params: UpdateGroupPromptParams): Promise<BuiltinToolResult> => {
+ updateGroupPrompt = async (
+ params: UpdateGroupPromptParams,
+ ctx: BuiltinToolContext,
+ ): Promise<BuiltinToolResult> => {
+ const blocked = awaitingCreateGroup(ctx, params.groupId);
+ if (blocked) return blocked;
+
return groupAgentBuilderRuntime.updateGroupPrompt({
streaming: true,
...params,
+ groupId: params.groupId ?? findGroupCreatedInConversation({ messageId: ctx.messageId }),
});
};
@@ -215,7 +319,12 @@ class GroupAgentBuilderExecutor extends BaseExecutor<typeof GroupAgentBuilderApi
* runs on `tool_end` for both transports, so it is the one place that reliably
* re-syncs the stores after a write.
*/
- onAfterCall = async ({ apiName, params, result }: ToolAfterCallContext): Promise<void> => {
+ onAfterCall = async ({
+ apiName,
+ params,
+ result,
+ toolCallId,
+ }: ToolAfterCallContext): Promise<void> => {
const groupStore = getChatGroupStoreState();
// A brand-new group isn't in the list yet β€” refresh the list, not a detail.
@@ -227,7 +336,8 @@ class GroupAgentBuilderExecutor extends BaseExecutor<typeof GroupAgentBuilderApi
if (!result.success || !GROUP_WRITE_APIS.has(apiName)) return;
const args = (params ?? {}) as { agentId?: string; groupId?: string; prompt?: string };
- const groupId = args.groupId ?? groupStore.activeGroupId;
+ const groupId =
+ args.groupId ?? findGroupCreatedInConversation({ toolCallId }) ?? groupStore.activeGroupId;
if (!groupId) return;
await groupStore.refreshGroupDetail(groupId);
diff --git a/packages/builtin-tool-group-agent-builder/src/index.ts b/packages/builtin-tool-group-agent-builder/src/index.ts
index 31124147ca2..4886dbe0ad0 100644
--- a/packages/builtin-tool-group-agent-builder/src/index.ts
+++ b/packages/builtin-tool-group-agent-builder/src/index.ts
@@ -1,3 +1,4 @@
+export { AWAITING_CREATE_GROUP_RESULT, findSiblingCreateGroupCallIds } from './createGroupOrdering';
export { GroupAgentBuilderManifest } from './manifest';
export { systemPrompt } from './systemRole';
export * from './types';
diff --git a/packages/builtin-tool-group-agent-builder/src/manifest.ts b/packages/builtin-tool-group-agent-builder/src/manifest.ts
index 5349517c964..0d5cffc69d5 100644
--- a/packages/builtin-tool-group-agent-builder/src/manifest.ts
+++ b/packages/builtin-tool-group-agent-builder/src/manifest.ts
@@ -3,6 +3,16 @@ import type { BuiltinToolManifest } from '@lobechat/types';
import { systemPrompt } from './systemRole';
import { GroupAgentBuilderApiName, GroupAgentBuilderIdentifier } from './types';
+/**
+ * Member tools act on the group being edited by default. A group created mid-run
+ * with `createGroup` is not that group, so every member tool can name it.
+ */
+const targetGroupIdProperty = {
+ description:
+ 'The group to act on. Omit to use the group being edited; after createGroup, pass the groupId it returned.',
+ type: 'string',
+};
+
export const GroupAgentBuilderManifest: BuiltinToolManifest = {
api: [
// ==================== Agent Info ====================
@@ -16,6 +26,7 @@ export const GroupAgentBuilderManifest: BuiltinToolManifest = {
description: 'The ID of the agent to get information about.',
type: 'string',
},
+ groupId: targetGroupIdProperty,
},
required: ['agentId'],
type: 'object',
@@ -61,6 +72,7 @@ export const GroupAgentBuilderManifest: BuiltinToolManifest = {
description: 'A brief description of what this agent does and its expertise.',
type: 'string',
},
+ groupId: targetGroupIdProperty,
systemRole: {
description:
"The system prompt that defines the agent's behavior, personality, and capabilities.",
@@ -208,6 +220,7 @@ export const GroupAgentBuilderManifest: BuiltinToolManifest = {
},
type: 'array',
},
+ groupId: targetGroupIdProperty,
},
required: ['agents'],
type: 'object',
@@ -223,6 +236,7 @@ export const GroupAgentBuilderManifest: BuiltinToolManifest = {
description: 'The agent identifier to invite to the group',
type: 'string',
},
+ groupId: targetGroupIdProperty,
},
required: ['agentId'],
type: 'object',
@@ -237,6 +251,7 @@ export const GroupAgentBuilderManifest: BuiltinToolManifest = {
description: 'The agent identifier to remove from the group',
type: 'string',
},
+ groupId: targetGroupIdProperty,
},
required: ['agentId'],
type: 'object',
@@ -378,6 +393,7 @@ export const GroupAgentBuilderManifest: BuiltinToolManifest = {
description: 'The agent ID to update.',
type: 'string',
},
+ groupId: targetGroupIdProperty,
prompt: {
description: 'The new system prompt content. Supports markdown formatting.',
type: 'string',
diff --git a/packages/builtin-tool-group-agent-builder/src/systemRole.ts b/packages/builtin-tool-group-agent-builder/src/systemRole.ts
index 2603a9c085a..bc2d1e82b3b 100644
--- a/packages/builtin-tool-group-agent-builder/src/systemRole.ts
+++ b/packages/builtin-tool-group-agent-builder/src/systemRole.ts
@@ -169,8 +169,9 @@ When creating agents (via \`createAgent\` or \`batchCreateAgents\`), you MUST an
**Execution Order (MUST follow this sequence):**
3. **Step 1 - Create or Update Group Identity FIRST**:
- - If the user does not yet have a target group, create it first using \`createGroup\`
- - If the group already exists, update the group's title, description, and avatar using \`updateGroup\`
+ - If \`<current_group_context>\` is present, the group already exists (even when it is still empty): update its title, description, and avatar using \`updateGroup\`. Do NOT call \`createGroup\` for it
+ - Only when there is no \`<current_group_context>\` (or the user explicitly asks for another group) create one with \`createGroup\`, then pass the \`groupId\` it returns to every later group or member tool call
+ - Call \`createGroup\` on its own and wait for its result: it needs the user's approval, so group or member tools issued alongside it are refused until it returns
This establishes the group's identity and purpose.
4. **Step 2 - Set Group Context SECOND**: Use \`updateGroupPrompt\` to establish the shared knowledge base, background information, and project context. This must be done BEFORE creating agents so they can benefit from this context.
@@ -250,7 +251,7 @@ When creating agents (via \`createAgent\` or \`batchCreateAgents\`), you MUST an
<example title="Complete Team Setup (Shows Required Order)">
User: "Help me build a development team"
Action (MUST follow this order):
- 1. **First** - createGroup: { title: "Development Team", avatar: "πŸ‘¨β€πŸ’»" }
+ 1. **First** - updateGroup: { meta: { title: "Development Team", avatar: "πŸ‘¨β€πŸ’»" } } (or createGroup when there is no \`<current_group_context>\`)
2. **Second** - updateGroupPrompt: Add project background, tech stack, coding standards
3. **Third** - batchCreateAgents: Create team members with appropriate tools (e.g., Developer with ["lobe-cloud-sandbox"], Researcher with ["web-crawler"])
4. **Fourth** - updateAgentPrompt: Update supervisor with delegation rules
diff --git a/packages/builtin-tool-group-agent-builder/src/types.ts b/packages/builtin-tool-group-agent-builder/src/types.ts
index 72347d571d8..cc4f7cb639e 100644
--- a/packages/builtin-tool-group-agent-builder/src/types.ts
+++ b/packages/builtin-tool-group-agent-builder/src/types.ts
@@ -49,6 +49,11 @@ export interface GetAgentInfoParams {
* The ID of the agent to get information about
*/
agentId: string;
+ /**
+ * The group to act on. Defaults to the group this conversation is editing β€”
+ * pass the id `createGroup` returned to target a group created in this run.
+ */
+ groupId?: string;
}
export interface SearchAgentParams {
@@ -71,6 +76,11 @@ export interface CreateAgentParams {
* A brief description of what this agent does
*/
description?: string;
+ /**
+ * The group to act on. Defaults to the group this conversation is editing β€”
+ * pass the id `createGroup` returned to target a group created in this run.
+ */
+ groupId?: string;
/**
* The system prompt that defines the agent's behavior
*/
@@ -182,6 +192,11 @@ export interface InviteAgentParams {
* Agent identifier to invite to the group
*/
agentId: string;
+ /**
+ * The group to act on. Defaults to the group this conversation is editing β€”
+ * pass the id `createGroup` returned to target a group created in this run.
+ */
+ groupId?: string;
}
export interface RemoveAgentParams {
@@ -189,6 +204,11 @@ export interface RemoveAgentParams {
* Agent identifier to remove from the group
*/
agentId: string;
+ /**
+ * The group to act on. Defaults to the group this conversation is editing β€”
+ * pass the id `createGroup` returned to target a group created in this run.
+ */
+ groupId?: string;
}
export interface UpdateAgentPromptParams {
@@ -196,6 +216,11 @@ export interface UpdateAgentPromptParams {
* The agent ID to update
*/
agentId: string;
+ /**
+ * The group to act on. Defaults to the group this conversation is editing β€”
+ * pass the id `createGroup` returned to target a group created in this run.
+ */
+ groupId?: string;
/**
* The new system prompt content (markdown format)
*/
@@ -313,6 +338,11 @@ export interface BatchCreateAgentsParams {
* Array of agents to create
*/
agents: CreateAgentParams[];
+ /**
+ * The group to act on. Defaults to the group this conversation is editing β€”
+ * pass the id `createGroup` returned to target a group created in this run.
+ */
+ groupId?: string;
}
export interface BatchCreateAgentsState {
diff --git a/packages/database/src/models/__tests__/messages/message.latestPluginState.test.ts b/packages/database/src/models/__tests__/messages/message.latestPluginState.test.ts
new file mode 100644
index 00000000000..bd69de70532
--- /dev/null
+++ b/packages/database/src/models/__tests__/messages/message.latestPluginState.test.ts
@@ -0,0 +1,192 @@
+// @vitest-environment node
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../../core/getTestDB';
+import { messagePlugins, messages, threads, topics, users } from '../../../schemas';
+import type { LobeChatDatabase } from '../../../type';
+import { MessageModel } from '../../message';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const userId = 'latest-plugin-state-user';
+const otherUserId = 'latest-plugin-state-other';
+const messageModel = new MessageModel(serverDB, userId);
+
+const identifier = 'lobe-group-agent-builder';
+
+const seedToolCall = async (opts: {
+ apiName?: string;
+ createdAt: Date;
+ id: string;
+ ownerId?: string;
+ state?: Record<string, unknown> | null;
+ threadId?: string;
+ topicId: string;
+}) => {
+ const owner = opts.ownerId ?? userId;
+ await serverDB.insert(messages).values({
+ content: '',
+ createdAt: opts.createdAt,
+ id: opts.id,
+ role: 'tool',
+ threadId: opts.threadId,
+ topicId: opts.topicId,
+ userId: owner,
+ });
+ await serverDB.insert(messagePlugins).values({
+ apiName: opts.apiName ?? 'createGroup',
+ id: opts.id,
+ identifier,
+ state: opts.state ?? null,
+ toolCallId: `tc-${opts.id}`,
+ userId: owner,
+ });
+};
+
+beforeEach(async () => {
+ await serverDB.delete(users).where(eq(users.id, userId));
+ await serverDB.delete(users).where(eq(users.id, otherUserId));
+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);
+ await serverDB.insert(topics).values([
+ { id: 'lps-topic1', userId },
+ { id: 'lps-topic2', userId },
+ { id: 'lps-other-topic', userId: otherUserId },
+ ]);
+});
+
+afterEach(async () => {
+ await serverDB.delete(users).where(eq(users.id, userId));
+ await serverDB.delete(users).where(eq(users.id, otherUserId));
+});
+
+describe('MessageModel.findLatestPluginStateInTopic', () => {
+ const query = (topicId: string) =>
+ messageModel.findLatestPluginStateInTopic({ apiName: 'createGroup', identifier, topicId });
+
+ it('returns the state of the newest call in the topic', async () => {
+ await seedToolCall({
+ createdAt: new Date('2026-09-25T06:16:24Z'),
+ id: 'lps-a',
+ state: { groupId: 'cg_first' },
+ topicId: 'lps-topic1',
+ });
+ await seedToolCall({
+ createdAt: new Date('2026-09-25T06:20:00Z'),
+ id: 'lps-b',
+ state: { groupId: 'cg_second' },
+ topicId: 'lps-topic1',
+ });
+
+ expect(await query('lps-topic1')).toEqual({ groupId: 'cg_second' });
+ });
+
+ it('skips calls that produced no state (failed or aborted)', async () => {
+ await seedToolCall({
+ createdAt: new Date('2026-09-25T06:16:24Z'),
+ id: 'lps-ok',
+ state: { groupId: 'cg_ok' },
+ topicId: 'lps-topic1',
+ });
+ await seedToolCall({
+ createdAt: new Date('2026-09-25T06:17:00Z'),
+ id: 'lps-aborted',
+ state: null,
+ topicId: 'lps-topic1',
+ });
+
+ expect(await query('lps-topic1')).toEqual({ groupId: 'cg_ok' });
+ });
+
+ it('only looks at the given topic, api and the caller’s own rows', async () => {
+ await seedToolCall({
+ apiName: 'updateGroup',
+ createdAt: new Date('2026-09-25T06:16:24Z'),
+ id: 'lps-other-api',
+ state: { success: true },
+ topicId: 'lps-topic1',
+ });
+ await seedToolCall({
+ createdAt: new Date('2026-09-25T06:16:24Z'),
+ id: 'lps-other-topic-call',
+ state: { groupId: 'cg_elsewhere' },
+ topicId: 'lps-topic2',
+ });
+ await seedToolCall({
+ createdAt: new Date('2026-09-25T06:16:24Z'),
+ id: 'lps-foreign',
+ ownerId: otherUserId,
+ state: { groupId: 'cg_foreign' },
+ topicId: 'lps-other-topic',
+ });
+
+ expect(await query('lps-topic1')).toBeUndefined();
+ expect(await query('lps-other-topic')).toBeUndefined();
+ });
+});
+
+describe('MessageModel.findLatestPluginStateInTopic thread scoping', () => {
+ const query = (threadId?: string | null) =>
+ messageModel.findLatestPluginStateInTopic({
+ apiName: 'createGroup',
+ identifier,
+ threadId,
+ topicId: 'lps-topic1',
+ });
+
+ // Main conversation made cg_main; a later branch thread made cg_branch.
+ beforeEach(async () => {
+ await seedToolCall({
+ createdAt: new Date('2026-09-25T06:00:00Z'),
+ id: 'lps-main',
+ state: { groupId: 'cg_main' },
+ topicId: 'lps-topic1',
+ });
+ await serverDB.insert(threads).values([
+ {
+ id: 'lps-thread-branch',
+ sourceMessageId: 'lps-main',
+ topicId: 'lps-topic1',
+ type: 'continuation',
+ userId,
+ },
+ {
+ id: 'lps-thread-sibling',
+ sourceMessageId: 'lps-main',
+ topicId: 'lps-topic1',
+ type: 'continuation',
+ userId,
+ },
+ {
+ id: 'lps-thread-isolated',
+ sourceMessageId: 'lps-main',
+ topicId: 'lps-topic1',
+ type: 'isolation',
+ userId,
+ },
+ ]);
+ await seedToolCall({
+ createdAt: new Date('2026-09-25T06:10:00Z'),
+ id: 'lps-branch',
+ state: { groupId: 'cg_branch' },
+ threadId: 'lps-thread-branch',
+ topicId: 'lps-topic1',
+ });
+ });
+
+ it('keeps a group created in a thread out of the main conversation', async () => {
+ expect(await query()).toEqual({ groupId: 'cg_main' });
+ expect(await query(null)).toEqual({ groupId: 'cg_main' });
+ });
+
+ it('keeps a group created in a thread out of its sibling threads', async () => {
+ // A continuation sibling still inherits the main conversation up to its source.
+ expect(await query('lps-thread-sibling')).toEqual({ groupId: 'cg_main' });
+ // An isolated thread inherits nothing.
+ expect(await query('lps-thread-isolated')).toBeUndefined();
+ });
+
+ it('sees the thread’s own call first, then its inherited ancestors', async () => {
+ expect(await query('lps-thread-branch')).toEqual({ groupId: 'cg_branch' });
+ });
+});
diff --git a/packages/database/src/models/message.ts b/packages/database/src/models/message.ts
index eaa3575c205..6dabb5c54b0 100644
--- a/packages/database/src/models/message.ts
+++ b/packages/database/src/models/message.ts
@@ -3935,6 +3935,47 @@ export class MessageModel {
}));
};
+ /**
+ * The `state` of the most recent call to one tool API in a topic that
+ * produced any β€” a failed or aborted call leaves no state. Lets a tool read
+ * back what an earlier call in the same conversation produced, e.g. the group
+ * a builder conversation last created with `createGroup`.
+ *
+ * Scoped like a message query for the same branch: without `threadId` only
+ * the main conversation counts; with it, the thread plus the parent messages
+ * its type inherits β€” never a sibling thread.
+ */
+ findLatestPluginStateInTopic = async (params: {
+ apiName: string;
+ identifier: string;
+ threadId?: string | null;
+ topicId: string;
+ }): Promise<Record<string, any> | undefined> => {
+ const threadCondition = params.threadId
+ ? await this.buildThreadQueryCondition(params.threadId)
+ : isNull(messages.threadId);
+
+ const [row] = await this.db
+ .select({ state: messagePlugins.state })
+ .from(messagePlugins)
+ .innerJoin(messages, eq(messagePlugins.id, messages.id))
+ .where(
+ and(
+ eq(messages.topicId, params.topicId),
+ threadCondition,
+ eq(messagePlugins.identifier, params.identifier),
+ eq(messagePlugins.apiName, params.apiName),
+ isNotNull(messagePlugins.state),
+ this.ownership(),
+ this.pluginsOwnership(),
+ ),
+ )
+ .orderBy(desc(messages.createdAt), desc(messages.id))
+ .limit(1);
+
+ return row?.state ?? undefined;
+ };
+
/**
* List the tool/plugin rows produced by ONE agent operation, for the
* per-operation file-edit scan.