🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(group): member permissions, and personal model choice on shared builtins (#18122)
Rdmclin268a318992b6c
diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.tsindex 592c31d9bf7..ad93ef9b030 100644--- a/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts@@ -206,6 +206,7 @@ export class ServerToolTransport implements ToolTransport {: undefined,documentId: context.state.metadata?.documentId,editingAgentId: context.state.metadata?.editingAgentId,+ editingGroupId: context.state.metadata?.editingGroupId,execSubAgent: this.ctx.execSubAgent,executionTimeoutMs: timeoutMs,groupId: context.state.metadata?.groupId,diff --git a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.tsindex ee014092250..96acddd1c83 100644--- a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.ts+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.ts@@ -14,6 +14,8 @@ import type {AgentBuilderContext,AgentContextDocument,AgentGroupConfig,+ GroupAgentBuilderContext,+ GroupOfficialToolItem,OfficialToolItem,OnboardingContext,PlanTodoConfig,@@ -30,6 +32,7 @@ import { getActivePluginIds, getDisabledPluginIds } from '@lobechat/types';import { composioEnv } from '@/config/composio';import { AgentModel } from '@/database/models/agent';+import { ChatGroupModel } from '@/database/models/chatGroup';import { FileModel } from '@/database/models/file';import { MessageModel as MessageModelClass } from '@/database/models/message';import { TopicModel } from '@/database/models/topic';@@ -481,6 +484,104 @@ export const buildServerCallLlmContext = async ({}}+ // Group Agent Builder — mirrors the block above for the group Profile panel.+ // Without this the model has no idea which group it is editing, so it cannot+ // address members by id (updateAgentPrompt) and falls back to telling the user+ // to wire the group up by hand (LOBE-12941).+ let groupAgentBuilderContext: GroupAgentBuilderContext | undefined;+ const editingGroupId = state.metadata?.editingGroupId;+ if (editingGroupId && ctx.serverDB && ctx.userId) {+ try {+ const chatGroupModel = new ChatGroupModel(ctx.serverDB, ctx.userId, ctx.workspaceId);+ const [group, roster] = await Promise.all([+ chatGroupModel.findById(editingGroupId),+ chatGroupModel.getGroupAgentsWithMeta(editingGroupId),+ ]);++ if (group) {+ const supervisorAgentId = roster.find((member) => member.role === 'supervisor')?.agentId;++ let supervisorConfig: GroupAgentBuilderContext['supervisorConfig'];+ let enabledPlugins: string[] = [];+ if (supervisorAgentId) {+ const supervisorModel = new AgentModel(ctx.serverDB, ctx.userId, ctx.workspaceId);+ const supervisor = await supervisorModel.getAgentConfigById(supervisorAgentId);+ if (supervisor) {+ // Pinned identifiers only — `supervisorConfig.plugins` is a prompt+ // formatting DTO and a disabled plugin isn't "enabled".+ enabledPlugins = getActivePluginIds(+ Array.isArray(supervisor.plugins) ? supervisor.plugins : undefined,+ );+ supervisorConfig = {+ model: supervisor.model ?? undefined,+ plugins: enabledPlugins,+ provider: supervisor.provider ?? undefined,+ };+ }+ }++ const composioIdentifiers = new Set(COMPOSIO_APP_TYPES.map((tool) => tool.identifier));+ const groupOfficialTools: GroupOfficialToolItem[] = [];++ for (const tool of builtinTools) {+ if (tool.hidden) continue;+ if (composioIdentifiers.has(tool.identifier)) continue;+ groupOfficialTools.push({+ description: tool.manifest?.meta?.description,+ enabled: enabledPlugins.includes(tool.identifier),+ identifier: tool.identifier,+ installed: true,+ name: tool.manifest?.meta?.title || tool.identifier,+ type: 'builtin',+ });+ }++ if (composioEnv.COMPOSIO_API_KEY) {+ try {+ const connectedComposioIds = await loadConnectedComposioIds(+ ctx.serverDB,+ ctx.userId,+ ctx.workspaceId,+ supervisorAgentId,+ );+ for (const tool of COMPOSIO_APP_TYPES) {+ groupOfficialTools.push({+ description: `LobeHub Mcp Server: ${tool.label}`,+ enabled: enabledPlugins.includes(tool.identifier),+ identifier: tool.identifier,+ installed: connectedComposioIds.has(tool.identifier),+ name: tool.label,+ type: 'composio',+ });+ }+ } catch (composioError) {+ log('Failed to load Composio status for groupAgentBuilderContext: %O', composioError);+ }+ }++ groupAgentBuilderContext = {+ config: {+ openingMessage: group.config?.openingMessage || undefined,+ openingQuestions: group.config?.openingQuestions ?? undefined,+ systemPrompt: group.content || undefined,+ },+ groupId: editingGroupId,+ groupTitle: group.title || undefined,+ members: roster.map((member) => ({+ description: member.description ?? undefined,+ id: member.agentId,+ isSupervisor: member.role === 'supervisor',+ title: member.title || 'Untitled Agent',+ })),+ officialTools: groupOfficialTools,+ supervisorConfig,+ };+ }+ } catch (error) {+ log('Failed to build groupAgentBuilderContext for group %s: %O', editingGroupId, error);+ }+ }+const contextEngineInput = {additionalContexts: llmPayload.additionalContexts,agentDocuments,@@ -513,6 +614,7 @@ export const buildServerCallLlmContext = async ({enableHistoryCount: agentConfig.chatConfig?.enableHistoryCount ?? undefined,evalContext: ctx.evalContext,forceFinish: state.forceFinish,+ ...(groupAgentBuilderContext && { groupAgentBuilderContext }),historyCount: resolveRuntimeHistoryCount(agentConfig.chatConfig?.historyCount),initialContext: (state as any).initialContext?.initialContext,knowledge: {diff --git a/apps/server/src/modules/Mecha/ContextEngineering/index.ts b/apps/server/src/modules/Mecha/ContextEngineering/index.tsindex ffade6efe39..effe951e2bf 100644--- a/apps/server/src/modules/Mecha/ContextEngineering/index.ts+++ b/apps/server/src/modules/Mecha/ContextEngineering/index.ts@@ -143,6 +143,7 @@ export const serverMessagesEngine = async ({discordContext,evalContext,agentManagementContext,+ groupAgentBuilderContext,onboardingContext,pageContentContext,planTodo,@@ -243,6 +244,7 @@ export const serverMessagesEngine = async ({...(evalContext && { evalContext }),...(onboardingContext && { onboardingContext }),...(agentManagementContext && { agentManagementContext }),+ ...(groupAgentBuilderContext && { groupAgentBuilderContext }),...(pageContentContext && { pageContentContext }),});diff --git a/apps/server/src/modules/Mecha/ContextEngineering/types.ts b/apps/server/src/modules/Mecha/ContextEngineering/types.tsindex 9bd33128a1a..464c342e6bd 100644--- a/apps/server/src/modules/Mecha/ContextEngineering/types.ts+++ b/apps/server/src/modules/Mecha/ContextEngineering/types.ts@@ -8,6 +8,7 @@ import type {DiscordContext,EvalContext,FileContent,+ GroupAgentBuilderContext,KnowledgeBaseInfo,LobeToolManifest,OnboardingContext,@@ -92,6 +93,8 @@ export interface ServerMessagesEngineParams {agentGroup?: AgentGroupConfig;/** Agent Management context (optional, available models and plugins) */agentManagementContext?: AgentManagementContext;+ /** Group Agent Builder context (optional, for editing the current group) */+ groupAgentBuilderContext?: GroupAgentBuilderContext;// ========== Capability injection ==========/** Model capability checkers */capabilities?: ServerModelCapabilities;diff --git a/apps/server/src/routers/lambda/__tests__/agent.test.ts b/apps/server/src/routers/lambda/__tests__/agent.test.tsindex 220795485db..11aaf450fb9 100644--- a/apps/server/src/routers/lambda/__tests__/agent.test.ts+++ b/apps/server/src/routers/lambda/__tests__/agent.test.ts@@ -13,6 +13,7 @@ import { SessionModel } from '@/database/models/session';import { TaskModel } from '@/database/models/task';import { UserModel } from '@/database/models/user';import { WorkspaceUserSettingsModel } from '@/database/models/workspaceUserSettings';+import { DEFAULT_RESOURCE_ACCESS_LEVELS } from '@/database/schemas';import { AgentService } from '@/server/services/agent';import { EditLockService } from '@/server/services/editLock';import { publishResourceEvent } from '@/server/services/resourceEvents';@@ -496,7 +497,7 @@ describe('agentRouter', () => {expect(resourcePermissionModelMock.setAccessLevel).toHaveBeenCalledWith('agent','copied-agent',- 'use',+ DEFAULT_RESOURCE_ACCESS_LEVELS.agent,userId,);// Folder placement is shared state, carried by AgentModel.duplicate's@@ -555,7 +556,7 @@ describe('agentRouter', () => {expect(resourcePermissionModelMock.setAccessLevel).toHaveBeenCalledWith('agent','agent-1',- 'use',+ DEFAULT_RESOURCE_ACCESS_LEVELS.agent,userId,);});@@ -701,7 +702,7 @@ describe('agentRouter', () => {expect(resourcePermissionModelMock.setAccessLevel).toHaveBeenCalledWith('agent','agent-1',- 'use',+ DEFAULT_RESOURCE_ACCESS_LEVELS.agent,userId,);});diff --git a/apps/server/src/routers/lambda/__tests__/agentGroup.test.ts b/apps/server/src/routers/lambda/__tests__/agentGroup.test.tsindex 63c6dd02ac1..92afac6ef92 100644--- a/apps/server/src/routers/lambda/__tests__/agentGroup.test.ts+++ b/apps/server/src/routers/lambda/__tests__/agentGroup.test.ts@@ -4,19 +4,33 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import { DEFAULT_CHAT_GROUP_CHAT_CONFIG } from '@/const/settings';import * as AgentModelModule from '@/database/models/agent';import * as ChatGroupModelModule from '@/database/models/chatGroup';+import * as ResourcePermissionModelModule from '@/database/models/resourcePermission';import * as UserModelModule from '@/database/models/user';import * as AgentGroupRepoModule from '@/database/repositories/agentGroup';import * as ChatGroupServiceModule from '@/server/services/agentGroup';import { EditLockService } from '@/server/services/editLock';import { publishResourceEvent } from '@/server/services/resourceEvents';import { canPerformResourceAction } from '@/server/services/resourcePermission';--import { getWorkspaceAgentParentGroupIds } from '../_helpers/workspaceAgentGuard';+import {+ hasWorkspaceScopedPermission,+ isWorkspacePrimaryOwner,+} from '@/server/services/workspacePermission';++import {+ getWorkspaceAgentParentGroupIds,+ getWorkspaceGroupVirtualAgentIds,+} from '../_helpers/workspaceAgentGuard';import { agentGroupRouter } from '../agentGroup';vi.mock('@/server/services/resourceEvents', () => ({ publishResourceEvent: vi.fn() }));+// Both read the DB directly; `mockCtx.serverDB` is a bare object.+vi.mock('@/server/services/workspacePermission', () => ({+ hasWorkspaceScopedPermission: vi.fn().mockResolvedValue(true),+ isWorkspacePrimaryOwner: vi.fn().mockResolvedValue(true),+}));vi.mock('../_helpers/workspaceAgentGuard', () => ({getWorkspaceAgentParentGroupIds: vi.fn().mockResolvedValue([]),+ getWorkspaceGroupVirtualAgentIds: vi.fn().mockResolvedValue([]),}));vi.mock('@/server/services/resourcePermission', () => ({@@ -43,10 +57,14 @@ describe('agentGroupRouter', () => {let agentGroupRepoMock: any;let userModelMock: any;let chatGroupServiceMock: any;+ let resourcePermissionModelMock: any;beforeEach(() => {vi.restoreAllMocks();vi.mocked(getWorkspaceAgentParentGroupIds).mockResolvedValue([]);+ vi.mocked(getWorkspaceGroupVirtualAgentIds).mockResolvedValue([]);+ vi.mocked(hasWorkspaceScopedPermission).mockResolvedValue(true);+ vi.mocked(isWorkspacePrimaryOwner).mockResolvedValue(true);agentModelMock = {batchCreate: vi.fn(),@@ -69,6 +87,8 @@ describe('agentGroupRouter', () => {createGroupWithSupervisor: vi.fn(),findByIdWithAgents: vi.fn(),removeAgentsFromGroup: vi.fn(),+ transferHasForeignRows: vi.fn().mockResolvedValue(false),+ transferToWorkspace: vi.fn(),};userModelMock = {@@ -85,8 +105,17 @@ describe('agentGroupRouter', () => {),};+ resourcePermissionModelMock = {+ getAccessLevel: vi.fn().mockResolvedValue(null),+ removeAll: vi.fn(),+ setAccessLevel: vi.fn(),+ };+// Use vi.spyOn to mock the class constructors to return our mock instancesvi.spyOn(AgentModelModule, 'AgentModel').mockImplementation(() => agentModelMock as any);+ vi.spyOn(ResourcePermissionModelModule, 'ResourcePermissionModel').mockImplementation(+ () => resourcePermissionModelMock as any,+ );vi.spyOn(ChatGroupModelModule, 'ChatGroupModel').mockImplementation(() => chatGroupModelMock as any,);@@ -586,6 +615,149 @@ describe('agentGroupRouter', () => {});});+ // The Permission page lets a creator pick an access level while the group is+ // still private ("Members get this level once the group is published"). Both+ // routes into the publish transition must read that row back — stamping the+ // default over it silently upgrades everyone to `edit`.+ describe('publish keeps the level chosen while private', () => {+ beforeEach(() => {+ mockCtx.workspaceId = 'ws_1';+ chatGroupModelMock.countPrivateGroupAgents = vi.fn().mockResolvedValue(0);+ chatGroupModelMock.publishToWorkspace = vi.fn().mockResolvedValue({ success: true });+ chatGroupModelMock.setVisibility = vi.fn().mockResolvedValue(true);+ chatGroupModelMock.findById.mockResolvedValue({+ id: 'cg_1',+ userId,+ visibility: 'private',+ workspaceId: 'ws_1',+ });+ });++ it('publishGroupToWorkspace reads the stored level', async () => {+ resourcePermissionModelMock.getAccessLevel.mockResolvedValue('use');++ await agentGroupRouter.createCaller(mockCtx).publishGroupToWorkspace({ id: 'cg_1' });++ expect(resourcePermissionModelMock.setAccessLevel).toHaveBeenCalledWith(+ 'agentGroup',+ 'cg_1',+ 'use',+ userId,+ );+ });++ it('publishGroupToWorkspace falls back to the default when nothing was stored', async () => {+ await agentGroupRouter.createCaller(mockCtx).publishGroupToWorkspace({ id: 'cg_1' });++ expect(resourcePermissionModelMock.setAccessLevel).toHaveBeenCalledWith(+ 'agentGroup',+ 'cg_1',+ 'edit',+ userId,+ );+ });++ it('publishGroupToWorkspace lets an explicit request win', async () => {+ resourcePermissionModelMock.getAccessLevel.mockResolvedValue('use');++ await agentGroupRouter+ .createCaller(mockCtx)+ .publishGroupToWorkspace({ accessLevel: 'view', id: 'cg_1' });++ expect(resourcePermissionModelMock.setAccessLevel).toHaveBeenCalledWith(+ 'agentGroup',+ 'cg_1',+ 'view',+ userId,+ );+ });++ it('setGroupVisibility reads the stored level when promoting', async () => {+ resourcePermissionModelMock.getAccessLevel.mockResolvedValue('use');++ await agentGroupRouter+ .createCaller(mockCtx)+ .setGroupVisibility({ id: 'cg_1', visibility: 'public' });++ expect(resourcePermissionModelMock.setAccessLevel).toHaveBeenCalledWith(+ 'agentGroup',+ 'cg_1',+ 'use',+ userId,+ );+ });++ // `assertCanEditResource` authorizes an agent by its own ACL alone, so a+ // virtual agent left without a row falls back to the agent default (`edit`)+ // and stays editable by everyone despite a use-only group.+ describe('cascades the level to group-owned virtual agents', () => {+ beforeEach(() => {+ vi.mocked(getWorkspaceGroupVirtualAgentIds).mockResolvedValue(['agt_sup', 'agt_member']);+ resourcePermissionModelMock.getAccessLevel.mockResolvedValue('use');+ });++ it('on publishGroupToWorkspace', async () => {+ await agentGroupRouter.createCaller(mockCtx).publishGroupToWorkspace({ id: 'cg_1' });++ expect(resourcePermissionModelMock.setAccessLevel).toHaveBeenCalledWith(+ 'agent',+ 'agt_sup',+ 'use',+ userId,+ );+ expect(resourcePermissionModelMock.setAccessLevel).toHaveBeenCalledWith(+ 'agent',+ 'agt_member',+ 'use',+ userId,+ );+ });++ it('on transferGroup into the target workspace', async () => {+ agentGroupRepoMock.transferToWorkspace = vi.fn().mockResolvedValue({ success: true });++ await agentGroupRouter.createCaller(mockCtx).transferGroup({+ groupId: 'cg_1',+ targetAccessLevel: 'use',+ targetVisibility: 'public',+ targetWorkspaceId: 'ws_2',+ });++ expect(resourcePermissionModelMock.setAccessLevel).toHaveBeenCalledWith(+ 'agent',+ 'agt_sup',+ 'use',+ userId,+ );+ expect(resourcePermissionModelMock.setAccessLevel).toHaveBeenCalledWith(+ 'agent',+ 'agt_member',+ 'use',+ userId,+ );+ });++ it('on setGroupVisibility promotion', async () => {+ await agentGroupRouter+ .createCaller(mockCtx)+ .setGroupVisibility({ id: 'cg_1', visibility: 'public' });++ expect(resourcePermissionModelMock.setAccessLevel).toHaveBeenCalledWith(+ 'agent',+ 'agt_sup',+ 'use',+ userId,+ );+ expect(resourcePermissionModelMock.setAccessLevel).toHaveBeenCalledWith(+ 'agent',+ 'agt_member',+ 'use',+ userId,+ );+ });+ });+ });+describe('edit lock', () => {const wsCtx = () => ({ serverDB: {}, userId, workspaceId: 'ws-1' });diff --git a/apps/server/src/routers/lambda/__tests__/resourcePermission.test.ts b/apps/server/src/routers/lambda/__tests__/resourcePermission.test.tsindex 6067d423353..39bab9fe2f5 100644--- a/apps/server/src/routers/lambda/__tests__/resourcePermission.test.ts+++ b/apps/server/src/routers/lambda/__tests__/resourcePermission.test.ts@@ -80,6 +80,37 @@ describe('resourcePermissionRouter.setGeneralAccess', () => {expect(result.visibility).toBe('private');});+ // Regression: `viewer` used to be resolved through the resource default, which+ // was `use` at the time. Once the Agent / Group default became `edit`, that+ // path would have handed edit access to a released client that explicitly+ // asked for the non-editor option.+ it.each([+ ['agent', 'use'],+ ['agentGroup', 'use'],+ ['document', 'view'],+ ] as const)('maps a legacy %s viewer role to %s, not to the default', async (type, expected) => {+ getResourceMetaMock.mockResolvedValue({+ userId: 'user_creator',+ visibility: 'public',+ workspaceId: 'ws_1',+ } as any);+ canManageMock.mockResolvedValue(true);++ const result = await caller().setGeneralAccess({+ resourceId: 'resource-1',+ resourceType: type,+ role: 'viewer',+ });++ expect(permissionModelMock.setAccessLevel).toHaveBeenCalledWith(+ type,+ 'resource-1',+ expected,+ 'user_creator',+ );+ expect(result.accessLevel).toBe(expected);+ });+it('reports public resources as public', async () => {getResourceMetaMock.mockResolvedValue({userId: 'user_creator',diff --git a/apps/server/src/routers/lambda/agent.ts b/apps/server/src/routers/lambda/agent.tsindex 443cc87ff09..fc2fb475e20 100644--- a/apps/server/src/routers/lambda/agent.ts+++ b/apps/server/src/routers/lambda/agent.ts@@ -27,7 +27,11 @@ import { TopicModel } from '@/database/models/topic';import { TOPIC_COMMENT_TRANSFER_HAS_FOREIGN_AUTHORS } from '@/database/models/topicComment';import { UserModel } from '@/database/models/user';import type { ResourceAccessLevel } from '@/database/schemas';-import { DEFAULT_RESOURCE_ACCESS_LEVELS, RESOURCE_ACCESS_LEVELS_BY_TYPE } from '@/database/schemas';+import {+ DEFAULT_RESOURCE_ACCESS_LEVELS,+ LEGACY_VIEWER_ACCESS_LEVELS,+ RESOURCE_ACCESS_LEVELS_BY_TYPE,+} from '@/database/schemas';import { router } from '@/libs/trpc/lambda';import { serverDatabase } from '@/libs/trpc/lambda/middleware';import { AgentService } from '@/server/services/agent';@@ -993,9 +997,17 @@ export const agentRouter = router({);}if (input.targetWorkspaceId && input.targetVisibility === 'public') {+ // A released client's two-valued `viewer` is an explicit "less than+ // editor" choice, so it resolves through the legacy map rather than the+ // default (which is `edit`); saying nothing at all still means "what a+ // newly created agent would get".const targetAccessLevel =input.targetAccessLevel ??- (input.targetGeneralAccess === 'editor' ? 'edit' : DEFAULT_RESOURCE_ACCESS_LEVELS.agent);+ (input.targetGeneralAccess+ ? input.targetGeneralAccess === 'editor'+ ? 'edit'+ : LEGACY_VIEWER_ACCESS_LEVELS.agent+ : DEFAULT_RESOURCE_ACCESS_LEVELS.agent);await new ResourcePermissionModel(ctx.serverDB, input.targetWorkspaceId).setAccessLevel('agent',input.agentId,diff --git a/apps/server/src/routers/lambda/agentGroup.ts b/apps/server/src/routers/lambda/agentGroup.tsindex 6cd36076ae9..4225503e3d2 100644--- a/apps/server/src/routers/lambda/agentGroup.ts+++ b/apps/server/src/routers/lambda/agentGroup.ts@@ -16,7 +16,13 @@ import { ResourcePermissionModel } from '@/database/models/resourcePermission';import { TOPIC_COMMENT_TRANSFER_HAS_FOREIGN_AUTHORS } from '@/database/models/topicComment';import { UserModel } from '@/database/models/user';import { AgentGroupRepository } from '@/database/repositories/agentGroup';-import { DEFAULT_RESOURCE_ACCESS_LEVELS, RESOURCE_ACCESS_LEVELS_BY_TYPE } from '@/database/schemas';+import type { ResourceAccessLevel } from '@/database/schemas';+import {+ DEFAULT_RESOURCE_ACCESS_LEVELS,+ LEGACY_VIEWER_ACCESS_LEVELS,+ RESOURCE_ACCESS_LEVELS_BY_TYPE,+} from '@/database/schemas';+import type { LobeChatDatabase } from '@/database/type';import { type ChatGroupConfig } from '@/database/types/chatGroup';import { router } from '@/libs/trpc/lambda';import { serverDatabase } from '@/libs/trpc/lambda/middleware';@@ -41,6 +47,7 @@ import {redactGroupConfig,type ResourceConfigAccess,} from './_helpers/resourceConfigGuard';+import { getWorkspaceGroupVirtualAgentIds } from './_helpers/workspaceAgentGuard';const resourceConfigGuardCtx = (ctx: {serverDB: Parameters<typeof getResourceConfigAccess>[0]['db'];@@ -157,6 +164,45 @@ const agentGroupProcedure = wsCompatProcedure.use(serverDatabase).use(async (opt// delete + member adds/removes). Reads keep the bare proc.const agentGroupProcedureWrite = agentGroupProcedure.use(withScopedPermission('agent:update'));+/**+ * Write a group's access level onto the group AND the group-owned virtual+ * agents (supervisor + generated members).+ *+ * The cascade is not decorative: `assertCanEditResource` authorizes an agent by+ * that agent's OWN ACL, with no parent-group term. A virtual agent left without+ * a row falls back to the agent default (`edit`), so publishing a group as+ * `use`/`view` while skipping the cascade leaves its supervisor editable by+ * every member who can resolve its id — the group restriction would apply to+ * the group resource only. Mirrors `resourcePermission.setGeneralAccess`;+ * standalone agents linked into the group keep their own ACL.+ */+const applyGroupAccessLevel = async ({+ accessLevel,+ ctx,+ groupId,+ permissionModel,+ workspaceId,+}: {+ accessLevel: ResourceAccessLevel;+ ctx: { serverDB: LobeChatDatabase; userId: string };+ groupId: string;+ permissionModel: ResourcePermissionModel;+ workspaceId: string;+}): Promise<void> => {+ const virtualAgentIds = await getWorkspaceGroupVirtualAgentIds({+ db: ctx.serverDB,+ groupId,+ workspaceId,+ });++ await Promise.all([+ permissionModel.setAccessLevel('agentGroup', groupId, accessLevel, ctx.userId),+ ...virtualAgentIds.map((agentId) =>+ permissionModel.setAccessLevel('agent', agentId, accessLevel, ctx.userId),+ ),+ ]);+};+export const agentGroupRouter = router({addAgentsToGroup: agentGroupProcedureWrite.input(@@ -807,17 +853,29 @@ export const agentGroupRouter = router({);}if (input.targetWorkspaceId && input.targetVisibility === 'public') {+ // A released client's two-valued `viewer` is an explicit "less than+ // editor" choice, so it resolves through the legacy map rather than the+ // default (which is `edit`); saying nothing at all still means "what a+ // newly created group would get".const targetAccessLevel =input.targetAccessLevel ??- (input.targetGeneralAccess === 'editor'- ? 'edit'+ (input.targetGeneralAccess+ ? input.targetGeneralAccess === 'editor'+ ? 'edit'+ : LEGACY_VIEWER_ACCESS_LEVELS.agentGroup: DEFAULT_RESOURCE_ACCESS_LEVELS.agentGroup);- await new ResourcePermissionModel(ctx.serverDB, input.targetWorkspaceId).setAccessLevel(- 'agentGroup',- input.groupId,- targetAccessLevel,- ctx.userId,- );+ // `transferToWorkspace` makes the moved supervisor / generated members+ // public in the target too, so they need the same cascade as the+ // publish paths — otherwise their own ACL falls back to the agent+ // default (`edit`) and target members can edit the owned agents of a+ // use/view-only group.+ await applyGroupAccessLevel({+ accessLevel: targetAccessLevel,+ ctx,+ groupId: input.groupId,+ permissionModel: new ResourcePermissionModel(ctx.serverDB, input.targetWorkspaceId),+ workspaceId: input.targetWorkspaceId,+ });}return result;@@ -855,7 +913,12 @@ export const agentGroupRouter = router({* back to `private`. Restricted to the creator's own still-private group.*/publishGroupToWorkspace: agentGroupProcedureWrite- .input(z.object({ id: z.string() }))+ .input(+ z.object({+ accessLevel: z.enum(RESOURCE_ACCESS_LEVELS_BY_TYPE.agentGroup).optional(),+ id: z.string(),+ }),+ ).mutation(async ({ input, ctx }) => {// Same rule `setGroupVisibility` enforces, on the other route to the same// transition: a private group may hold the creator's private member@@ -875,12 +938,22 @@ export const agentGroupRouter = router({const result = await ctx.chatGroupModel.publishToWorkspace(input.id);if (ctx.workspaceId) {- await new ResourcePermissionModel(ctx.serverDB, ctx.workspaceId).setAccessLevel(- 'agentGroup',- input.id,- DEFAULT_RESOURCE_ACCESS_LEVELS.agentGroup,- ctx.userId,- );+ const permissionModel = new ResourcePermissionModel(ctx.serverDB, ctx.workspaceId);+ // Same rule as `publishAgentToWorkspace`: an explicit request wins;+ // otherwise keep whatever the creator already chose on the Permission+ // page while the group was still private — rewriting the default here+ // would silently discard that decision.+ const accessLevel =+ input.accessLevel ??+ (await permissionModel.getAccessLevel('agentGroup', input.id)) ??+ DEFAULT_RESOURCE_ACCESS_LEVELS.agentGroup;+ await applyGroupAccessLevel({+ accessLevel,+ ctx,+ groupId: input.id,+ permissionModel,+ workspaceId: ctx.workspaceId,+ });}return result;}),@@ -971,19 +1044,24 @@ export const agentGroupRouter = router({const updated = await ctx.chatGroupModel.setVisibility(input.id, input.visibility);if (!updated) throw new TRPCError({ code: 'NOT_FOUND', message: 'Group not found' });- const accessLevel =- input.visibility === 'private'- ? 'edit'- : (input.accessLevel ?? DEFAULT_RESOURCE_ACCESS_LEVELS.agentGroup);+ let accessLevel: ResourceAccessLevel;if (input.visibility === 'private') {+ accessLevel = 'edit';await permissionModel.removeAll('agentGroup', input.id);} else {- await permissionModel.setAccessLevel(- 'agentGroup',- input.id,- input.accessLevel ?? DEFAULT_RESOURCE_ACCESS_LEVELS.agentGroup,- ctx.userId,- );+ // Same rule as `publishGroupToWorkspace`: promotion keeps a level the+ // creator already set while private instead of resetting to the default.+ accessLevel =+ input.accessLevel ??+ (await permissionModel.getAccessLevel('agentGroup', input.id)) ??+ DEFAULT_RESOURCE_ACCESS_LEVELS.agentGroup;+ await applyGroupAccessLevel({+ accessLevel,+ ctx,+ groupId: input.id,+ permissionModel,+ workspaceId: ctx.workspaceId,+ });}return buildResourcePermissionState({diff --git a/apps/server/src/routers/lambda/aiAgent.ts b/apps/server/src/routers/lambda/aiAgent.tsindex 6d053b6cb95..0a176712f8c 100644--- a/apps/server/src/routers/lambda/aiAgent.ts+++ b/apps/server/src/routers/lambda/aiAgent.ts@@ -207,6 +207,8 @@ const ExecAgentSchema = zdocumentId: z.string().nullish(),/** The agent being edited when scope is 'agent_builder' (not the builder builtin itself). */editingAgentId: z.string().optional(),+ /** The group being edited when scope is 'group_agent_builder' (not a group chat turn). */+ editingGroupId: z.string().optional(),groupId: z.string().nullish(),initialTopicMetadata: z.object({diff --git a/apps/server/src/routers/lambda/resourcePermission.ts b/apps/server/src/routers/lambda/resourcePermission.tsindex 998b8a6d05e..7be0b6e77d6 100644--- a/apps/server/src/routers/lambda/resourcePermission.ts+++ b/apps/server/src/routers/lambda/resourcePermission.ts@@ -5,6 +5,7 @@ import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAimport { ResourcePermissionModel } from '@/database/models/resourcePermission';import {getDefaultResourceAccessLevel,+ getLegacyViewerAccessLevel,PERMISSION_RESOURCE_TYPES,RESOURCE_ACCESS_LEVELS,} from '@/database/schemas';@@ -82,8 +83,8 @@ export const resourcePermissionRouter = router({// A collaborative builtin with no explicit row is editable by every capable// member (`canPerformResourceAction`), so report that as its access level- // rather than the `use` default — the client's config gate reads this field,- // and `canManage` deliberately stays author/admin-only for these rows.+ // rather than the resource default — the client's config gate reads this+ // field, and `canManage` deliberately stays author/admin-only for these rows.const accessLevel =explicitAccessLevel ??(isCollaborativeBuiltinAgent(input.resourceType, meta)@@ -147,9 +148,12 @@ export const resourcePermissionRouter = router({// demoting to private clears the row again (`removeAll`). The// creator-only guard above already keeps other members out.+ // A released client sends only `role`, and its `viewer` is an explicit+ // "less than editor" choice — resolve it through the legacy map, never+ // through the default (which is `edit` for agents and groups).const accessLevel =input.accessLevel ??- (input.role === 'editor' ? 'edit' : getDefaultResourceAccessLevel(input.resourceType));+ (input.role === 'editor' ? 'edit' : getLegacyViewerAccessLevel(input.resourceType));if (!isAccessLevelAllowed(input.resourceType, accessLevel)) {throw new TRPCError({code: 'BAD_REQUEST',diff --git a/apps/server/src/routers/lambda/topic.ts b/apps/server/src/routers/lambda/topic.tsindex 1093cf6d007..158d6d75175 100644--- a/apps/server/src/routers/lambda/topic.ts+++ b/apps/server/src/routers/lambda/topic.ts@@ -486,6 +486,13 @@ export const topicRouter = router({z.object({agentId: z.string().nullish(),current: z.number().optional(),+ /**+ * Scope an `agentId` query to the builder conversations that configured+ * one target. Builder panels show their full history on purpose; these+ * are for callers that want a single agent's / group's builds.+ */+ editingAgentId: z.string().nullish(),+ editingGroupId: z.string().nullish(),excludeStatuses: z.array(z.string()).optional(),excludeTriggers: z.array(z.string()).optional(),groupId: z.string().nullish(),diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.modelOverride.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.modelOverride.test.tsindex 8778b02d55e..ea46564cb82 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.modelOverride.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.modelOverride.test.ts@@ -64,6 +64,23 @@ vi.mock('@/database/models/plugin', () => ({})),}));+// 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(() => ({+ queryByIdentifiers: vi.fn().mockResolvedValue([]),+ resolveByIdentifiers: vi.fn().mockResolvedValue([]),+ })),+}));++vi.mock('@/database/models/connectorTool', () => ({+ ConnectorToolModel: vi.fn().mockImplementation(() => ({+ queryAllByConnectorIds: vi.fn().mockResolvedValue([]),+ queryByConnector: vi.fn().mockResolvedValue([]),+ queryByConnectorIds: vi.fn().mockResolvedValue([]),+ })),+}));+vi.mock('@/database/models/topic', () => ({TopicModel: vi.fn().mockImplementation(() => ({releaseTaskCallbackReservation: vi.fn().mockResolvedValue(undefined),@@ -350,6 +367,37 @@ describe('AiAgentService.execAgent - model/provider override', () => {);});+ it('uses the caller model preference on a collaborative builtin the caller created', async () => {+ // The Agent Builder row is provisioned by whichever member opened the panel+ // first; being that member (or an admin) must not pin everyone to their+ // model, so the run reads this caller's own override. Chat/Agent mode keeps+ // the ordinary author rule and stays shared.+ mockIsResourceAuthorOrAdmin.mockResolvedValue(true);+ mockGetAgentConfig.mockResolvedValue({+ ...defaultAgentConfig,+ chatConfig: { enableAgentMode: true },+ slug: 'group-agent-builder',+ userId,+ virtual: true,+ visibility: 'public',+ workspaceId: 'workspace-1',+ });+ mockGetPreference.mockResolvedValue({+ agentModelOverrides: {+ 'agent-1': { model: 'claude-sonnet-4-6', provider: 'anthropic' },+ },+ agentModeOverrides: { 'agent-1': false },+ });+ service = new AiAgentService(mockDb, userId, { workspaceId: 'workspace-1' });++ await service.execAgent({ agentId: 'agent-1', prompt: 'Hello' });++ const callArgs = mockCreateOperation.mock.calls[0][0];+ expect(callArgs.agentConfig.model).toBe('claude-sonnet-4-6');+ expect(callArgs.agentConfig.provider).toBe('anthropic');+ expect(callArgs.agentConfig.chatConfig.enableAgentMode).toBe(true);+ });+it('ignores the caller model preference when the workspace Agent is private', async () => {mockGetAgentConfig.mockResolvedValue({...defaultAgentConfig,diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.tsindex 7bd688e70e8..d6316ca637b 100644--- a/apps/server/src/services/aiAgent/index.ts+++ b/apps/server/src/services/aiAgent/index.ts@@ -9,7 +9,11 @@ import {GeneralChatAgent,GraphAgent,} from '@lobechat/agent-runtime';-import { BUILTIN_AGENT_SLUGS, getAgentRuntimeConfig } from '@lobechat/builtin-agents';+import {+ BUILTIN_AGENT_SLUGS,+ getAgentRuntimeConfig,+ isCollaborativeBuiltinAgentRow,+} from '@lobechat/builtin-agents';import { builtinSkills } from '@lobechat/builtin-skills';import { CloudSandboxManifest } from '@lobechat/builtin-tool-cloud-sandbox';import { GoalIdentifier, isGoalPrompt } from '@lobechat/builtin-tool-goal';@@ -1471,7 +1475,19 @@ export class AiAgentService {// The callSubAgent spawn site resolves the sub-agent default and passes it// explicitly, so this path never has to special-case sub-agents.const effectiveModel = resolveAgentModelConfig(- { ...agentConfig, canManage: canManageAgent, workspaceId: agentWorkspaceId },+ {+ ...agentConfig,+ canManage: canManageAgent,+ // A collaborative builtin is Workspace infrastructure with no author and+ // no config page, so its model is personal for every caller — being its+ // creator or an admin must not pin the whole Workspace to one model.+ // Device / mode overrides keep the ordinary author rule above.+ personalModelSelection: isCollaborativeBuiltinAgentRow({+ ...agentConfig,+ workspaceId: agentWorkspaceId,+ }),+ workspaceId: agentWorkspaceId,+ },memberModelOverride,{...(modelOverride ? { model: modelOverride } : {}),@@ -1899,12 +1915,27 @@ export class AiAgentService {// Prepare metadata with cronJobId, taskId, botContext, bound device, and any// client-supplied initial metadata (e.g. repos selected before first message).const initialTopicMeta = appContext?.initialTopicMetadata;+ // Builder conversations are owned by a builtin builder agent and get no+ // `groupId` / `sessionId` (those columns mark the target's own chat), so+ // without this the row keeps no trace of what it was configuring. The+ // 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 metadata =- cronJobId || operationTaskId || botContext || topicBoundDeviceId || initialTopicMeta+ cronJobId ||+ operationTaskId ||+ botContext ||+ topicBoundDeviceId ||+ initialTopicMeta ||+ editingGroupId ||+ editingAgentId? {bot: botContext,boundDeviceId: topicBoundDeviceId,cronJobId: cronJobId || undefined,+ ...(editingAgentId && { editingAgentId }),+ ...(editingGroupId && { editingGroupId }),taskId: operationTaskId,...(initialTopicMeta?.repos && { repos: initialTopicMeta.repos }),...(initialTopicMeta?.workingDirectory && {@@ -4474,6 +4505,13 @@ export class AiAgentService {...(appContext?.scope === 'agent_builder' && appContext?.editingAgentId? { editingAgentId: appContext.editingAgentId }: {}),+ // Mirror of the above for the Group Agent Builder panel: the run is+ // 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 }+ : {}),// Run-scoped Agent Signal marker for background self-iteration / memory// runs — lands in state.metadata.agentSignal so the completion path can// project receipts/briefs. Undefined for ordinary chat runs.diff --git a/apps/server/src/services/resourcePermission/index.test.ts b/apps/server/src/services/resourcePermission/index.test.tsindex 5e460e07477..b9469e8b9e9 100644--- a/apps/server/src/services/resourcePermission/index.test.ts+++ b/apps/server/src/services/resourcePermission/index.test.ts@@ -402,7 +402,7 @@ describe('canPerformResourceAction', () => {).resolves.toBe(false);});- it('still lets every member use an internal builtin (resource default is use)', async () => {+ it('still lets every member use an internal builtin at use-level access', async () => {permissionMatchesMock.mockResolvedValue({ hasAllScope: false, hasOwnerScope: true });effectiveAccessMock.mockResolvedValue('use');@@ -610,7 +610,7 @@ describe('canPerformResourceAction', () => {).resolves.toBe(true);});- // The bypass covers the *implicit* `use` default only. An owner who explicitly+ // The bypass covers the *implicit* resource default only. An owner who explicitly// narrows General access means it — otherwise that control would persist a value// it never enforces.it('enforces an explicitly configured access level on a collaborative builtin', async () => {diff --git a/apps/server/src/services/resourcePermission/index.ts b/apps/server/src/services/resourcePermission/index.tsindex 01ac612c701..7fcee66a4bf 100644--- a/apps/server/src/services/resourcePermission/index.ts+++ b/apps/server/src/services/resourcePermission/index.ts@@ -1,4 +1,4 @@-import { BUILTIN_AGENT_SLUGS } from '@lobechat/builtin-agents';+import { isCollaborativeBuiltinAgentRow } from '@lobechat/builtin-agents';import type { PERMISSION_ACTIONS } from '@lobechat/const/rbac';import { TRPCError } from '@trpc/server';import { eq } from 'drizzle-orm';@@ -133,27 +133,6 @@ const resolveAgentBuiltinMarkers = async (return { slug: row?.slug ?? null, virtual: row?.virtual ?? null };};-/**- * The builtin agents a workspace *collaborates on* — the ones members open and- * configure from the UI (Lobe AI, the Agent / Group Agent builders, the page- * agent's Copilot panel).- *- * Deliberately NOT the whole of `BUILTIN_AGENT_SLUGS`: the internal automation- * agents (`nightly-review`, `self-reflection`, `self-feedback-intent`,- * `skill-management`, `verify-agent`, `task-agent`, the onboarding agents, the- * group supervisor) have no configuration surface, and letting any member- * repoint their persisted model / chatConfig would silently change background- * automation for the entire workspace. They keep the ordinary creator + General- * access rules, which still allow every member to *use* them (the resource- * default is `use`).- */-const COLLABORATIVE_BUILTIN_AGENT_SLUGS: ReadonlySet<string> = new Set<string>([- BUILTIN_AGENT_SLUGS.agentBuilder,- BUILTIN_AGENT_SLUGS.groupAgentBuilder,- BUILTIN_AGENT_SLUGS.inbox,- BUILTIN_AGENT_SLUGS.pageAgent,-]);-/*** Whether the resource is a workspace-level builtin agent that members are meant* to configure together.@@ -162,7 +141,7 @@ const COLLABORATIVE_BUILTIN_AGENT_SLUGS: ReadonlySet<string> = new Set<string>([* created lazily by whichever member happens to trigger them first, so* `agents.user_id` records an accident of timing rather than authorship, and no* `resource_permissions` row is ever written for them (their effective General- * access falls back to the `use` default). Treating them as creator-owned locks+ * access falls back to the resource default). Treating them as creator-owned locks* every other member out of the Agent Builder, of Lobe AI's config page, and of* the Page Copilot's own settings, so they are governed by workspace* capability instead: anyone holding `agent:update:{owner,all}` may@@ -186,15 +165,7 @@ const COLLABORATIVE_BUILTIN_AGENT_SLUGS: ReadonlySet<string> = new Set<string>([export const isCollaborativeBuiltinAgent = (resourceType: PermissionResourceType,meta: ResourceMeta,-): boolean =>- resourceType === 'agent' &&- !!meta.workspaceId &&- // `virtual` is what provisioning writes; a legacy row that merely holds a- // reserved slug (the passthrough config endpoint used to allow that) stays an- // ordinary agent, so no migration is needed to keep it out of the bypass.- meta.virtual === true &&- !!meta.slug &&- COLLABORATIVE_BUILTIN_AGENT_SLUGS.has(meta.slug);+): boolean => resourceType === 'agent' && isCollaborativeBuiltinAgentRow(meta);const getRbacAction = (resourceType: PermissionResourceType,@@ -282,7 +253,9 @@ export const canPerformResourceAction = async (params: {const isSharedWorkspaceAgent =!isPrivate && isCollaborativeBuiltinAgent(resourceType, resolvedMeta);// The bypass exists because these rows have no `resource_permissions` row and- // would silently fall back to the `use` default. An owner who *explicitly* sets+ // would silently inherit whatever the resource default happens to be — today+ // that default is `edit` and the bypass is a no-op, but it must not become a+ // lockout again if the default is ever lowered. An owner who *explicitly* sets// a level still means it — otherwise the General-access control would persist a// value it never enforces — so only the implicit default is overridden.const hasExplicitAccessLevel = isSharedWorkspaceAgent@@ -305,7 +278,7 @@ export const canPerformResourceAction = async (params: {if (isCreator) return true;// Collaboratively-configured workspace infrastructure is not creator-owned- // content, so the *implicit* `use` default must not lock members out. An+ // content, so an *implicit* default below `edit` must not lock members out. An// explicitly configured level falls through to the comparison below.if (bypassesImplicitDefault) return true;if (isPrivate) return false;diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/groupAgentBuilder.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/groupAgentBuilder.test.tsnew file mode 100644index 00000000000..da91faf82ce--- /dev/null+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/groupAgentBuilder.test.ts@@ -0,0 +1,290 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { hasServerRuntime } from '..';+import { groupAgentBuilderRuntime } from '../groupAgentBuilder';++const {+ mockAddAgentsToGroup,+ mockBatchCreate,+ mockBuilderUpdateConfig,+ mockFindById,+ mockGetAccessLevel,+ mockGetAgentConfigById,+ mockGetGroupAgentsWithMeta,+ mockRemoveAgentsFromGroup,+ mockSetAccessLevel,+ mockUpdateAgent,+ mockUpdateGroup,+} = vi.hoisted(() => ({+ mockAddAgentsToGroup: vi.fn(),+ mockBatchCreate: vi.fn(),+ mockBuilderUpdateConfig: vi.fn(),+ mockFindById: vi.fn(),+ mockGetAccessLevel: vi.fn(),+ mockGetAgentConfigById: vi.fn(),+ mockGetGroupAgentsWithMeta: vi.fn(),+ mockRemoveAgentsFromGroup: vi.fn(),+ mockSetAccessLevel: vi.fn(),+ mockUpdateAgent: vi.fn(),+ mockUpdateGroup: vi.fn(),+}));++vi.mock('@/database/models/agent', () => ({+ AgentModel: vi.fn(() => ({+ batchCreate: mockBatchCreate,+ getAgentConfigById: mockGetAgentConfigById,+ queryAgents: vi.fn(async () => []),+ update: mockUpdateAgent,+ updateConfig: vi.fn(),+ })),+}));++vi.mock('@/database/models/chatGroup', () => ({+ ChatGroupModel: vi.fn(() => ({+ addAgentsToGroup: mockAddAgentsToGroup,+ findById: mockFindById,+ getGroupAgentsWithMeta: mockGetGroupAgentsWithMeta,+ removeAgentsFromGroup: mockRemoveAgentsFromGroup,+ update: mockUpdateGroup,+ })),+}));++vi.mock('@/database/models/resourcePermission', () => ({+ ResourcePermissionModel: vi.fn(() => ({+ getAccessLevel: mockGetAccessLevel,+ setAccessLevel: mockSetAccessLevel,+ })),+}));++vi.mock('@/database/repositories/agentGroup', () => ({+ AgentGroupRepository: vi.fn(() => ({ createGroupWithSupervisor: vi.fn() })),+}));++vi.mock('@/server/services/agentGroup', () => ({+ AgentGroupService: vi.fn(() => ({ normalizeGroupConfig: (config: unknown) => config })),+}));++vi.mock('@/server/services/resourcePermission', () => ({+ assertCanPerformResourceAction: vi.fn(async () => undefined),+}));++vi.mock('../agentBuilder', () => ({+ agentBuilderRuntime: {+ factory: () => ({ updateConfig: mockBuilderUpdateConfig }),+ identifier: 'lobe-agent-builder',+ },+}));++const createRuntime = (workspaceId?: string) =>+ groupAgentBuilderRuntime.factory({+ serverDB: {} as never,+ toolManifestMap: {},+ userId: 'user-1',+ workspaceId,+ });++const groupCtx = { editingGroupId: 'cg_1' } as never;++describe('groupAgentBuilderRuntime', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mockFindById.mockResolvedValue({ id: 'cg_1', title: 'Launch Team', visibility: 'public' });+ mockGetGroupAgentsWithMeta.mockResolvedValue([+ { agentId: 'agt_sup', description: null, role: 'supervisor', title: 'Supervisor' },+ ]);+ });++ // The bug: gateway mode executes every builtin tool server-side, and a missing+ // registry entry makes `executeBuiltinTool` throw "is not implemented", so no+ // member ever reaches the group.+ it('is registered in the server runtime registry', () => {+ expect(hasServerRuntime('lobe-group-agent-builder')).toBe(true);+ });++ describe('createAgent', () => {+ it('creates a virtual agent and adds it to the edited group', async () => {+ mockBatchCreate.mockResolvedValue([{ id: 'agt_new', visibility: 'public' }]);++ const result = await createRuntime().createAgent(+ {+ systemRole: 'You drive launches.',+ title: 'Product Manager',+ tools: ['lobe-web-browsing'],+ },+ groupCtx,+ );++ expect(mockBatchCreate).toHaveBeenCalledWith([+ expect.objectContaining({+ plugins: ['lobe-web-browsing'],+ title: 'Product Manager',+ virtual: true,+ visibility: 'public',+ }),+ ]);+ expect(mockAddAgentsToGroup).toHaveBeenCalledWith('cg_1', ['agt_new']);+ expect(result).toMatchObject({+ state: { agentId: 'agt_new', success: true, title: 'Product Manager' },+ success: true,+ });+ });++ it('inherits the group access level for workspace members', async () => {+ mockBatchCreate.mockResolvedValue([{ id: 'agt_new', visibility: 'public' }]);+ mockGetAccessLevel.mockResolvedValue('edit');++ await createRuntime('ws_1').createAgent({ systemRole: 'x', title: 'PM' }, groupCtx);++ expect(mockSetAccessLevel).toHaveBeenCalledWith('agent', 'agt_new', 'edit', 'user-1');+ });++ it('returns a structured error instead of throwing when no group is in context', async () => {+ const result = await createRuntime().createAgent(+ { systemRole: 'x', title: 'PM' },+ {} as never,+ );++ expect(result).toMatchObject({ error: { type: 'NoGroupContext' }, success: false });+ expect(mockBatchCreate).not.toHaveBeenCalled();+ });+ });++ describe('batchCreateAgents', () => {+ it('creates every agent and adds them all to the group in one roster write', async () => {+ mockBatchCreate.mockResolvedValue([+ { id: 'agt_a', visibility: 'public' },+ { id: 'agt_b', visibility: 'public' },+ ]);++ const result = await createRuntime().batchCreateAgents(+ {+ agents: [+ { systemRole: 'a', title: 'Marketing Lead' },+ { systemRole: 'b', title: 'Engineering Lead' },+ ],+ },+ groupCtx,+ );++ expect(mockAddAgentsToGroup).toHaveBeenCalledWith('cg_1', ['agt_a', 'agt_b']);+ expect(result).toMatchObject({+ state: { failedCount: 0, successCount: 2 },+ success: true,+ });+ });+ });++ describe('removeAgent', () => {+ it('refuses to remove the supervisor', async () => {+ const result = await createRuntime().removeAgent({ agentId: 'agt_sup' }, groupCtx);++ expect(result.success).toBe(false);+ expect(mockRemoveAgentsFromGroup).not.toHaveBeenCalled();+ });++ it('removes a participant', async () => {+ mockGetGroupAgentsWithMeta.mockResolvedValue([+ { agentId: 'agt_sup', role: 'supervisor', title: 'Supervisor' },+ { agentId: 'agt_a', role: 'participant', title: 'Marketing Lead' },+ ]);++ const result = await createRuntime().removeAgent({ agentId: 'agt_a' }, groupCtx);++ expect(mockRemoveAgentsFromGroup).toHaveBeenCalledWith('cg_1', ['agt_a']);+ expect(result).toMatchObject({ state: { agentId: 'agt_a', success: true }, success: true });+ });+ });++ describe('updateAgentPrompt', () => {+ it('rejects an agent that is not a member of the group', async () => {+ const result = await createRuntime().updateAgentPrompt(+ { agentId: 'agt_outsider', prompt: 'hi' },+ groupCtx,+ );++ expect(result).toMatchObject({ error: { type: 'AgentNotFound' }, success: false });+ expect(mockUpdateAgent).not.toHaveBeenCalled();+ });++ it('clears editorData so the profile editor does not revert the write', async () => {+ mockGetAgentConfigById.mockResolvedValue({ systemRole: 'old' });++ const result = await createRuntime().updateAgentPrompt(+ { agentId: 'agt_sup', prompt: 'new prompt' },+ groupCtx,+ );++ expect(mockUpdateAgent).toHaveBeenCalledWith('agt_sup', {+ editorData: null,+ systemRole: 'new prompt',+ });+ expect(result).toMatchObject({+ state: { newPrompt: 'new prompt', previousPrompt: 'old', success: true },+ success: true,+ });+ });+ });++ describe('updateConfig', () => {+ // The delegated `AgentBuilder.updateConfig` write is scoped by visibility+ // alone, so an unchecked caller-supplied id would let a group edit+ // reconfigure any workspace agent the caller can merely see.+ it('rejects a caller-supplied agent that is not on the roster', async () => {+ const result = await createRuntime('ws_1').updateConfig(+ { agentId: 'agt_outsider', model: 'gpt-5' },+ groupCtx,+ );++ expect(result).toMatchObject({ error: { type: 'AgentNotFound' }, success: false });+ expect(mockBuilderUpdateConfig).not.toHaveBeenCalled();+ });++ it('refuses a caller-supplied agent when there is no group in context', async () => {+ const result = await createRuntime('ws_1').updateConfig(+ { agentId: 'agt_sup', model: 'gpt-5' },+ {} as never,+ );++ expect(result).toMatchObject({ success: false });+ expect(mockBuilderUpdateConfig).not.toHaveBeenCalled();+ });++ it('delegates for a roster member, stamping it as the edited agent', async () => {+ await createRuntime('ws_1').updateConfig({ agentId: 'agt_sup', model: 'gpt-5' }, groupCtx);++ expect(mockBuilderUpdateConfig).toHaveBeenCalledWith(+ { model: 'gpt-5' },+ expect.objectContaining({ editingAgentId: 'agt_sup' }),+ );+ });++ it('falls back to the supervisor when no agentId is given', async () => {+ await createRuntime('ws_1').updateConfig({ model: 'gpt-5' }, groupCtx);++ expect(mockBuilderUpdateConfig).toHaveBeenCalledWith(+ { model: 'gpt-5' },+ expect.objectContaining({ editingAgentId: 'agt_sup' }),+ );+ });+ });++ describe('updateGroupPrompt', () => {+ it('writes the shared prompt onto the edited group', async () => {+ mockFindById.mockResolvedValue({ content: 'old', id: 'cg_1', visibility: 'public' });++ const result = await createRuntime().updateGroupPrompt(+ { prompt: 'shared context' },+ groupCtx,+ );++ expect(mockUpdateGroup).toHaveBeenCalledWith('cg_1', {+ content: 'shared context',+ editorData: null,+ });+ expect(result).toMatchObject({+ state: { newPrompt: 'shared context', previousPrompt: 'old', success: true },+ success: true,+ });+ });+ });+});diff --git a/apps/server/src/services/toolExecution/serverRuntimes/groupAgentBuilder.ts b/apps/server/src/services/toolExecution/serverRuntimes/groupAgentBuilder.tsnew file mode 100644index 00000000000..d3bc53fffaf--- /dev/null+++ b/apps/server/src/services/toolExecution/serverRuntimes/groupAgentBuilder.ts@@ -0,0 +1,752 @@+/**+ * Group Agent Builder Server Runtime — server-side group configuration.+ *+ * The client counterpart (`packages/builtin-tool-group-agent-builder/src/ExecutionRuntime`)+ * drives zustand stores and only runs under the legacy client runtime. Cloud runs+ * gateway mode, where every builtin tool executes here, so without this runtime+ * `toolExecution/builtin.ts` throws `Builtin tool "lobe-group-agent-builder" is+ * not implemented` and *every* member/config mutation fails — the model then+ * falls back to generic agent creation, which spawns standalone agents outside+ * the group (LOBE-12941).+ *+ * 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.+ *+ * Member creation mirrors `routers/lambda/agentGroup.ts` exactly — virtual+ * agents, roster insert, and workspace access-level inheritance — so an agent+ * created by the assistant is indistinguishable from one created through the UI.+ */+import type {+ GetAvailableModelsParams,+ InstallPluginParams,+ SearchMarketToolsParams,+} from '@lobechat/builtin-tool-agent-builder';+import type {+ BatchCreateAgentsParams,+ BatchCreateAgentsState,+ CreateAgentParams,+ CreateAgentState,+ CreateGroupParams,+ CreateGroupState,+ GetAgentInfoParams,+ InviteAgentParams,+ InviteAgentState,+ RemoveAgentParams,+ RemoveAgentState,+ SearchAgentParams,+ SearchAgentState,+ UpdateAgentConfigWithIdParams,+ UpdateAgentPromptParams,+ UpdateAgentPromptState,+ UpdateGroupParams,+ UpdateGroupPromptParams,+ UpdateGroupPromptState,+ UpdateGroupState,+} from '@lobechat/builtin-tool-group-agent-builder';+import { GroupAgentBuilderIdentifier } from '@lobechat/builtin-tool-group-agent-builder';+import { formatAgentProfile } from '@lobechat/prompts';++import { AgentModel } from '@/database/models/agent';+import { ChatGroupModel } from '@/database/models/chatGroup';+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 { AgentGroupService } from '@/server/services/agentGroup';+import { assertCanPerformResourceAction } from '@/server/services/resourcePermission';++import { type ToolExecutionContext, type ToolExecutionResult } from '../types';+import { agentBuilderRuntime } from './agentBuilder';+import { type ServerRuntimeRegistration } from './types';++const handleError = (error: unknown, message: string): ToolExecutionResult => {+ const err = error as Error;+ return { content: `${message}: ${err.message}`, success: false };+};++const noGroupContext = (): ToolExecutionResult => ({+ content: 'No active group found',+ error: { message: 'No active group found', type: 'NoGroupContext' },+ success: false,+});++const groupNotFound = (groupId: string): ToolExecutionResult => ({+ content: `Group "${groupId}" not found`,+ error: { message: `Group "${groupId}" not found`, type: 'GroupNotFound' },+ success: false,+});++export const groupAgentBuilderRuntime: ServerRuntimeRegistration = {+ factory: (context: ToolExecutionContext) => {+ if (!context.userId || !context.serverDB) {+ throw new Error('userId and serverDB are required for Group Agent Builder execution');+ }+ const { serverDB, userId } = context;+ const workspaceId = context.workspaceId ?? undefined;++ const agentModel = new AgentModel(serverDB, userId, workspaceId);+ const chatGroupModel = new ChatGroupModel(serverDB, userId, workspaceId);+ 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;++ /**+ * Mutating a group's roster or config is a group edit — same ACL as the+ * `agentGroup` router. Runs before any write so a denied call never leaves+ * a half-created agent behind.+ */+ const assertGroupEditable = async (groupId: string) => {+ if (!workspaceId) return;+ await assertCanPerformResourceAction({+ action: 'edit',+ db: serverDB,+ resourceId: groupId,+ resourceType: 'agentGroup',+ userId,+ workspaceId,+ });+ };++ /**+ * Group-owned members inherit the group's current General Access so a group+ * already opened to `edit` doesn't spawn `use`-locked members. Mirrors+ * `agentGroup.batchCreateAgentsInGroup`.+ */+ const inheritGroupAccessLevel = async (+ groupId: string,+ createdAgents: Array<{ id: string; visibility?: string | null }>,+ ) => {+ if (!workspaceId) return;+ const permissionModel = new ResourcePermissionModel(serverDB, workspaceId);+ const groupLevel = await permissionModel.getAccessLevel('agentGroup', groupId);+ await Promise.all(+ createdAgents+ .filter((agent) => agent.visibility !== 'private')+ .map((agent) =>+ permissionModel.setAccessLevel(+ 'agent',+ agent.id,+ groupLevel ?? DEFAULT_RESOURCE_ACCESS_LEVELS.agent,+ userId,+ ),+ ),+ );+ };++ const findSupervisorAgentId = async (groupId: string) => {+ const roster = await chatGroupModel.getGroupAgentsWithMeta(groupId);+ return roster.find((member) => member.role === 'supervisor')?.agentId;+ };++ /** Delegate to the AgentBuilder runtime with the target agent pinned. */+ const withEditingAgent = (+ ctx: ToolExecutionContext,+ agentId: string,+ ): ToolExecutionContext => ({+ ...ctx,+ editingAgentId: agentId,+ });++ const builder = agentBuilderRuntime.factory(context);++ return {+ // ==================== Agent Info ====================++ getAgentInfo: async (+ params: GetAgentInfoParams,+ ctx: ToolExecutionContext,+ ): Promise<ToolExecutionResult> => {+ const groupId = resolveGroupId(ctx);+ if (!groupId) return noGroupContext();++ try {+ const roster = await chatGroupModel.getGroupAgentsWithMeta(groupId);+ const member = roster.find((item) => item.agentId === params.agentId);++ if (!member) {+ return {+ content: `Agent "${params.agentId}" not found in this group`,+ error: { message: `Agent "${params.agentId}" not found`, type: 'AgentNotFound' },+ success: false,+ };+ }++ const config = await agentModel.getAgentConfigById(params.agentId);+ const agent = {+ description: member.description ?? undefined,+ id: params.agentId,+ model: config?.model ?? undefined,+ systemRole: config?.systemRole ?? undefined,+ title: member.title ?? undefined,+ };++ return { content: formatAgentProfile(agent), state: agent, success: true };+ } catch (error) {+ return handleError(error, 'Failed to get agent info');+ }+ },++ // ==================== Group Member Management ====================++ searchAgent: async (params: SearchAgentParams): Promise<ToolExecutionResult> => {+ const { query, limit = 10 } = params;++ try {+ const results = await agentModel.queryAgents({ keyword: query, limit });+ const agents = results.map((agent) => ({+ avatar: agent.avatar ?? undefined,+ description: agent.description ?? undefined,+ id: agent.id,+ title: agent.title ?? '',+ }));++ if (agents.length === 0) {+ return {+ content: query+ ? `No agents found matching "${query}".`+ : 'No agents found. You can create a new agent or search with different keywords.',+ state: { agents: [], query, total: 0 } satisfies SearchAgentState,+ success: true,+ };+ }++ const agentList = agents+ .map(+ (a, i) =>+ `${i + 1}. ${a.title || 'Untitled'} (ID: ${a.id})${a.description ? ` - ${a.description}` : ''}`,+ )+ .join('\n');++ return {+ content: query+ ? `Found ${agents.length} agent${agents.length > 1 ? 's' : ''} matching "${query}":\n${agentList}`+ : `Found ${agents.length} agent${agents.length > 1 ? 's' : ''}:\n${agentList}`,+ state: { agents, query, total: agents.length } satisfies SearchAgentState,+ success: true,+ };+ } catch (error) {+ return handleError(error, 'Failed to search agents');+ }+ },++ createGroup: async (params: CreateGroupParams): Promise<ToolExecutionResult> => {+ try {+ const groupConfig: ChatGroupConfig = {+ ...(params.openingMessage !== undefined && { openingMessage: params.openingMessage }),+ ...(params.openingQuestions !== undefined && {+ openingQuestions: params.openingQuestions,+ }),+ } as ChatGroupConfig;++ const { group, supervisorAgentId } = await agentGroupRepo.createGroupWithSupervisor(+ {+ avatar: params.avatar,+ backgroundColor: params.backgroundColor,+ config: agentGroupService.normalizeGroupConfig(+ Object.keys(groupConfig).length > 0 ? groupConfig : null,+ ),+ content: params.prompt,+ description: params.description,+ title: params.title,+ },+ [],+ params.supervisor+ ? {+ avatar: params.supervisor.avatar,+ backgroundColor: params.supervisor.backgroundColor,+ description: params.supervisor.description,+ model: params.supervisor.model,+ params: params.supervisor.params,+ provider: params.supervisor.provider,+ systemRole: params.supervisor.systemRole,+ tags: params.supervisor.tags,+ title: params.supervisor.title,+ }+ : undefined,+ );++ if (workspaceId && group.visibility !== 'private') {+ const permissionModel = new ResourcePermissionModel(serverDB, workspaceId);+ await Promise.all([+ permissionModel.setAccessLevel(+ 'agentGroup',+ group.id,+ DEFAULT_RESOURCE_ACCESS_LEVELS.agentGroup,+ userId,+ ),+ permissionModel.setAccessLevel(+ 'agent',+ supervisorAgentId,+ DEFAULT_RESOURCE_ACCESS_LEVELS.agent,+ userId,+ ),+ ]);+ }++ return {+ content: `Successfully created group "${params.title}" with ID: ${group.id}`,+ state: {+ groupId: group.id,+ success: true,+ supervisorAgentId,+ title: params.title,+ } satisfies CreateGroupState,+ success: true,+ };+ } catch (error) {+ return handleError(error, 'Failed to create group');+ }+ },++ createAgent: async (+ params: CreateAgentParams,+ ctx: ToolExecutionContext,+ ): Promise<ToolExecutionResult> => {+ const groupId = resolveGroupId(ctx);+ if (!groupId) return noGroupContext();++ try {+ const group = await chatGroupModel.findById(groupId);+ if (!group) return groupNotFound(groupId);++ await assertGroupEditable(groupId);++ const [agent] = await agentModel.batchCreate([+ {+ avatar: params.avatar,+ description: params.description,+ // Domain tool plugins support structured entries, while the DB+ // model's JSONB column still carries its legacy string[] type.+ plugins: params.tools as unknown as string[] | undefined,+ systemRole: params.systemRole,+ title: params.title,+ virtual: true,+ ...(group.visibility ? { visibility: group.visibility } : {}),+ },+ ]);++ await chatGroupModel.addAgentsToGroup(groupId, [agent.id]);+ await inheritGroupAccessLevel(groupId, [agent]);++ return {+ content: `Successfully created agent "${params.title}" and added it to the group.`,+ state: {+ agentId: agent.id,+ success: true,+ title: params.title,+ } satisfies CreateAgentState,+ success: true,+ };+ } catch (error) {+ return handleError(error, 'Failed to create agent');+ }+ },++ batchCreateAgents: async (+ params: BatchCreateAgentsParams,+ ctx: ToolExecutionContext,+ ): Promise<ToolExecutionResult> => {+ const groupId = resolveGroupId(ctx);+ if (!groupId) return noGroupContext();++ try {+ const group = await chatGroupModel.findById(groupId);+ if (!group) return groupNotFound(groupId);++ await assertGroupEditable(groupId);++ const createdAgents = await agentModel.batchCreate(+ params.agents.map((agent) => ({+ avatar: agent.avatar,+ description: agent.description,+ plugins: agent.tools as unknown as string[] | undefined,+ systemRole: agent.systemRole,+ title: agent.title,+ virtual: true,+ ...(group.visibility ? { visibility: group.visibility } : {}),+ })),+ );++ await chatGroupModel.addAgentsToGroup(+ groupId,+ createdAgents.map((agent) => agent.id),+ );+ await inheritGroupAccessLevel(groupId, createdAgents);++ const results = createdAgents.map((agent, index) => ({+ agentId: agent.id,+ success: true,+ title: params.agents[index].title,+ }));+ const createdList = results.map((r) => `- ${r.title} (ID: ${r.agentId})`).join('\n');++ return {+ content: `Successfully created ${results.length} agent${results.length > 1 ? 's' : ''}:\n${createdList}`,+ state: {+ agents: results,+ failedCount: 0,+ successCount: results.length,+ } satisfies BatchCreateAgentsState,+ success: true,+ };+ } catch (error) {+ return handleError(error, 'Failed to create agents');+ }+ },++ inviteAgent: async (+ params: InviteAgentParams,+ ctx: ToolExecutionContext,+ ): Promise<ToolExecutionResult> => {+ const groupId = resolveGroupId(ctx);+ if (!groupId) return noGroupContext();++ try {+ const group = await chatGroupModel.findById(groupId);+ if (!group) return groupNotFound(groupId);++ await assertGroupEditable(groupId);++ const roster = await chatGroupModel.getGroupAgentsWithMeta(groupId);+ const existing = roster.find((member) => member.agentId === params.agentId);++ if (existing) {+ return {+ content: `Agent ${existing.title || params.agentId} is already in the group`,+ state: {+ agentId: params.agentId,+ agentName: existing.title ?? undefined,+ success: false,+ } satisfies InviteAgentState,+ success: false,+ };+ }++ const result = await chatGroupModel.addAgentsToGroup(groupId, [params.agentId]);+ const wasAdded = result.added.length > 0;++ const agentMeta = await agentModel.getAgentConfigById(params.agentId);+ const agentName = agentMeta?.title ?? undefined;+ const agentDisplay = agentName ? `${agentName} (ID: ${params.agentId})` : params.agentId;++ return {+ content: wasAdded+ ? `Successfully invited agent ${agentDisplay} to the group`+ : `Agent ${agentDisplay} was already in the group`,+ state: {+ agentAvatar: agentMeta?.avatar ?? undefined,+ agentId: params.agentId,+ agentName,+ success: wasAdded,+ } satisfies InviteAgentState,+ success: wasAdded,+ };+ } catch (error) {+ return handleError(error, 'Failed to invite agent');+ }+ },++ removeAgent: async (+ params: RemoveAgentParams,+ ctx: ToolExecutionContext,+ ): Promise<ToolExecutionResult> => {+ const groupId = resolveGroupId(ctx);+ if (!groupId) return noGroupContext();++ try {+ const group = await chatGroupModel.findById(groupId);+ if (!group) return groupNotFound(groupId);++ await assertGroupEditable(groupId);++ const roster = await chatGroupModel.getGroupAgentsWithMeta(groupId);+ const member = roster.find((item) => item.agentId === params.agentId);++ if (!member) {+ return {+ content: `Agent ${params.agentId} is not in the group`,+ state: { agentId: params.agentId, success: false } satisfies RemoveAgentState,+ success: false,+ };+ }++ const agentName = member.title ?? undefined;+ const agentDisplay = agentName ? `${agentName} (ID: ${params.agentId})` : params.agentId;++ // The supervisor is the group's orchestrator — removing it would leave+ // the group unable to dispatch. Same guard as the client runtime.+ if (member.role === 'supervisor') {+ return {+ content: `Cannot remove supervisor agent ${agentDisplay} from the group`,+ state: {+ agentId: params.agentId,+ agentName,+ success: false,+ } satisfies RemoveAgentState,+ success: false,+ };+ }++ await chatGroupModel.removeAgentsFromGroup(groupId, [params.agentId]);++ return {+ content: `Successfully removed agent ${agentDisplay} from the group`,+ state: {+ agentId: params.agentId,+ agentName,+ success: true,+ } satisfies RemoveAgentState,+ success: true,+ };+ } catch (error) {+ return handleError(error, 'Failed to remove agent');+ }+ },++ // ==================== Group Configuration ====================++ updateAgentPrompt: async (+ params: UpdateAgentPromptParams,+ ctx: ToolExecutionContext,+ ): Promise<ToolExecutionResult> => {+ const groupId = resolveGroupId(ctx);+ if (!groupId) return noGroupContext();++ try {+ await assertGroupEditable(groupId);++ const roster = await chatGroupModel.getGroupAgentsWithMeta(groupId);+ if (!roster.some((member) => member.agentId === params.agentId)) {+ return {+ content: `Agent "${params.agentId}" is not a member of this group`,+ error: { message: `Agent "${params.agentId}" not found`, type: 'AgentNotFound' },+ success: false,+ };+ }++ const previous = await agentModel.getAgentConfigById(params.agentId);++ // Clear `editorData` alongside `systemRole`: the profile editor treats+ // the JSON doc as authoritative, so leaving it stale would revert the+ // markdown on the next autosave (same rule as AgentBuilder.updatePrompt).+ await agentModel.update(params.agentId, {+ editorData: null,+ systemRole: params.prompt,+ } as Record<string, unknown>);++ return {+ content: params.prompt+ ? `Successfully updated agent ${params.agentId} system prompt (${params.prompt.length} characters)`+ : `Successfully cleared agent ${params.agentId} system prompt`,+ state: {+ agentId: params.agentId,+ newPrompt: params.prompt,+ previousPrompt: previous?.systemRole ?? undefined,+ success: true,+ } satisfies UpdateAgentPromptState,+ success: true,+ };+ } catch (error) {+ return handleError(error, 'Failed to update agent prompt');+ }+ },++ updateGroup: async (+ params: UpdateGroupParams,+ ctx: ToolExecutionContext,+ ): Promise<ToolExecutionResult> => {+ const groupId = resolveGroupId(ctx, params.groupId);+ if (!groupId) return noGroupContext();++ const { config, meta } = params;+ if (!config && !meta) {+ return {+ content: 'No configuration or metadata provided',+ error: { message: 'No configuration or metadata provided', type: 'NoDataProvided' },+ success: false,+ };+ }++ try {+ const group = await chatGroupModel.findById(groupId);+ if (!group) return groupNotFound(groupId);++ await assertGroupEditable(groupId);++ const updatedFields: string[] = [];+ const state: UpdateGroupState = { success: true };+ const patch: Record<string, unknown> = {};++ if (config) {+ const configUpdate: { openingMessage?: string; openingQuestions?: string[] } = {};++ if (config.openingMessage !== undefined) {+ configUpdate.openingMessage = config.openingMessage;+ updatedFields.push(+ config.openingMessage+ ? `openingMessage (${config.openingMessage.length} chars)`+ : 'openingMessage (cleared)',+ );+ }+ if (config.openingQuestions !== undefined) {+ configUpdate.openingQuestions = config.openingQuestions;+ updatedFields.push(+ config.openingQuestions.length > 0+ ? `openingQuestions (${config.openingQuestions.length} questions)`+ : 'openingQuestions (cleared)',+ );+ }++ if (Object.keys(configUpdate).length > 0) {+ patch.config = { ...group.config, ...configUpdate };+ state.updatedConfig = configUpdate;+ }+ }++ if (meta && Object.keys(meta).length > 0) {+ Object.assign(patch, meta);+ state.updatedMeta = meta;++ if (meta.avatar !== undefined)+ updatedFields.push(`avatar (${meta.avatar || 'cleared'})`);+ if (meta.title !== undefined) updatedFields.push(`title (${meta.title || 'cleared'})`);+ if (meta.description !== undefined) {+ updatedFields.push(+ meta.description+ ? `description (${meta.description.length} chars)`+ : 'description (cleared)',+ );+ }+ if (meta.backgroundColor !== undefined) {+ updatedFields.push(`backgroundColor (${meta.backgroundColor || 'cleared'})`);+ }+ }++ if (Object.keys(patch).length > 0) await chatGroupModel.update(groupId, patch);++ return {+ content: `Successfully updated group: ${updatedFields.join(', ')}`,+ state,+ success: true,+ };+ } catch (error) {+ return handleError(error, 'Failed to update group');+ }+ },++ updateGroupPrompt: async (+ params: UpdateGroupPromptParams,+ ctx: ToolExecutionContext,+ ): Promise<ToolExecutionResult> => {+ const groupId = resolveGroupId(ctx, params.groupId);+ if (!groupId) return noGroupContext();++ try {+ const group = await chatGroupModel.findById(groupId);+ if (!group) return groupNotFound(groupId);++ await assertGroupEditable(groupId);++ // `editorData` mirrors `content` for the profile editor; clear it so a+ // stale JSON doc doesn't overwrite the new markdown on next autosave.+ await chatGroupModel.update(groupId, { content: params.prompt, editorData: null });++ return {+ content: params.prompt+ ? `Successfully updated group shared prompt (${params.prompt.length} characters)`+ : 'Successfully cleared group shared prompt',+ state: {+ newPrompt: params.prompt,+ previousPrompt: group.content ?? undefined,+ success: true,+ } satisfies UpdateGroupPromptState,+ success: true,+ };+ } catch (error) {+ return {+ ...handleError(error, 'Failed to update group prompt'),+ state: { newPrompt: params.prompt, success: false } satisfies UpdateGroupPromptState,+ };+ }+ },++ // ============ Inherited from AgentBuilder (supervisor / member agent) ============++ getAvailableModels: (params: GetAvailableModelsParams): Promise<ToolExecutionResult> =>+ builder.getAvailableModels(params),++ searchMarketTools: (params: SearchMarketToolsParams): Promise<ToolExecutionResult> =>+ builder.searchMarketTools(params),++ updateConfig: async (+ params: UpdateAgentConfigWithIdParams,+ ctx: ToolExecutionContext,+ ): Promise<ToolExecutionResult> => {+ const groupId = resolveGroupId(ctx);+ const { agentId: paramAgentId, ...rest } = params;++ // A caller-supplied id has to be confirmed against this group's roster+ // first. The delegated `AgentBuilder.updateConfig` write is scoped by+ // visibility alone, so without this check a tool call naming any agent+ // the caller can merely *see* would reconfigure it from inside a group+ // edit. The supervisor fallback below needs no check — it is read off+ // the roster itself. (The tool contract documents `agentId` as optional+ // and "defaults to the supervisor agent".)+ if (paramAgentId) {+ if (!groupId) return noGroupContext();++ const roster = await chatGroupModel.getGroupAgentsWithMeta(groupId);+ if (!roster.some((member) => member.agentId === paramAgentId)) {+ return {+ content: `Agent "${paramAgentId}" is not a member of this group`,+ error: { message: `Agent "${paramAgentId}" not found`, type: 'AgentNotFound' },+ success: false,+ };+ }+ }++ const agentId =+ paramAgentId ?? (groupId ? await findSupervisorAgentId(groupId) : undefined);++ if (!agentId) {+ return {+ content:+ 'No agent found. Please provide an agentId or ensure supervisor context is available.',+ error: { message: 'No agent found', type: 'NoAgentContext' },+ success: false,+ };+ }++ if (groupId) await assertGroupEditable(groupId);++ return builder.updateConfig(rest, withEditingAgent(ctx, agentId));+ },++ installPlugin: async (+ params: InstallPluginParams,+ ctx: ToolExecutionContext,+ ): Promise<ToolExecutionResult> => {+ const groupId = resolveGroupId(ctx);+ const agentId = groupId ? await findSupervisorAgentId(groupId) : undefined;++ if (!agentId) {+ return {+ content: 'No supervisor agent found',+ error: { message: 'No supervisor agent found', type: 'NoAgentContext' },+ success: false,+ };+ }++ if (groupId) await assertGroupEditable(groupId);++ return builder.installPlugin(params, withEditingAgent(ctx, agentId));+ },+ };+ },+ identifier: GroupAgentBuilderIdentifier,+};diff --git a/apps/server/src/services/toolExecution/serverRuntimes/index.ts b/apps/server/src/services/toolExecution/serverRuntimes/index.tsindex b22fdd7477c..68b7814dc07 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/index.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/index.ts@@ -22,6 +22,7 @@ import { browserRuntime } from './browser';import { calculatorRuntime } from './calculator';import { cloudSandboxRuntime } from './cloudSandbox';import { credsRuntime } from './creds';+import { groupAgentBuilderRuntime } from './groupAgentBuilder';import { groupManagementRuntime } from './groupManagement';import { imageGenerationRuntime } from './imageGeneration';import { knowledgeBaseRuntime } from './knowledgeBase';@@ -90,6 +91,7 @@ registerRuntimes([topicReferenceRuntime,userInteractionRuntime,credsRuntime,+ groupAgentBuilderRuntime,groupManagementRuntime,goalRuntime,imageGenerationRuntime,diff --git a/apps/server/src/services/toolExecution/types.ts b/apps/server/src/services/toolExecution/types.tsindex 5f1a0d396f1..f2ce99f8255 100644--- a/apps/server/src/services/toolExecution/types.ts+++ b/apps/server/src/services/toolExecution/types.ts@@ -201,6 +201,12 @@ export interface ToolExecutionContext {* bound to the builder builtin; only AgentBuilder tool methods read this.*/editingAgentId?: string;+ /**+ * When scope is 'group_agent_builder', the ID of the group being edited. Kept+ * separate from `groupId` so the builder's own conversation is not treated as+ * a group chat turn; only GroupAgentBuilder tool methods read this.+ */+ editingGroupId?: string;/*** Legacy agent invocation callback forwarded from RuntimeExecutorContext.* Kept for tool runtimes that still dispatch through exec_sub_agent stylediff --git a/locales/ar/setting.json b/locales/ar/setting.jsonindex e2a94c2c99d..b5cc7ce609c 100644--- a/locales/ar/setting.json+++ b/locales/ar/setting.json@@ -623,6 +623,18 @@"permission.page.editableWhenShared": "يمكن التعديل عند المشاركة","permission.page.entry": "أذونات الأعضاء","permission.page.generalAccessDesc": "ما يمكن لكل عضو في مساحة العمل القيام به باستخدام هذا الوكيل. يحتفظ المنشئ ومالكو مساحة العمل دائمًا بالوصول الكامل.",+ "permission.page.groupAccessLevelPrivateHint": "يحصل الأعضاء على هذا المستوى بمجرد نشر المجموعة في مساحة العمل. يمكن تغييره بعد النشر.",+ "permission.page.groupDevicePolicyDesc": "ما إذا كان يمكن للأعضاء تبديل بيئة التنفيذ لتشغيلاتهم الخاصة في هذه المجموعة.",+ "permission.page.groupDevicePolicyFixedDesc": "يمكن للأعضاء استخدام البيئة التي تحددها فقط لهذه المجموعة.",+ "permission.page.groupDevicePolicyMemberDesc": "يمكن للأعضاء تحديد بيئة التنفيذ الخاصة بهم.",+ "permission.page.groupDevicePolicyUnset": "اختر بيئة تنفيذ للمنسق أولاً، ثم يمكنك تثبيتها هنا.",+ "permission.page.groupGeneralAccessDesc": "ما يمكن لكل عضو في مساحة العمل القيام به مع هذه المجموعة. يتم تطبيق نفس المستوى على وكلاء الأعضاء الذين تمتلكهم المجموعة. يحتفظ المنشئ ومالكو مساحة العمل دائمًا بالوصول الكامل.",+ "permission.page.groupModelPolicyDesc": "ما إذا كان يمكن للأعضاء تبديل النموذج لمحادثاتهم الخاصة في هذه المجموعة.",+ "permission.page.groupModelPolicyFixedDesc": "يمكن للأعضاء استخدام النموذج الذي تحدده فقط لهذه المجموعة.",+ "permission.page.groupModelPolicyMemberDesc": "يمكن للأعضاء استخدام نموذج يحددونه بأنفسهم.",+ "permission.page.groupPersonalDesc": "هذه المجموعة تخصك فقط، لذا لا يوجد شيء لمشاركته حتى الآن. انشرها في مساحة العمل لتحديد أذونات الأعضاء.",+ "permission.page.groupPersonalTitle": "تنطبق الأذونات على مجموعات مساحة العمل",+ "permission.page.groupPrivateNotice": "هذه المجموعة لا تزال خاصة. كل شيء هنا يصبح ساريًا بمجرد نشرها في مساحة العمل.","permission.page.memberGroup": "الوصول","permission.page.modelPolicyDesc": "ما إذا كان يمكن للأعضاء تبديل النموذج لمحادثاتهم الخاصة.","permission.page.modelPolicyFixedDesc": "يمكن للأعضاء استخدام النموذج الذي تحدده فقط",diff --git a/locales/bg-BG/setting.json b/locales/bg-BG/setting.jsonindex ef132fe71da..3efc5513d80 100644--- a/locales/bg-BG/setting.json+++ b/locales/bg-BG/setting.json@@ -623,6 +623,18 @@"permission.page.editableWhenShared": "Може да се редактира, когато е споделено","permission.page.entry": "Права на членовете","permission.page.generalAccessDesc": "Какво може всеки член на работното пространство да прави с този агент. Създателят и собствениците на работното пространство винаги запазват пълен достъп.",+ "permission.page.groupAccessLevelPrivateHint": "Членовете получават това ниво, след като групата бъде публикувана в работното пространство. То може да бъде променено след публикуването.",+ "permission.page.groupDevicePolicyDesc": "Дали членовете могат да сменят средата за изпълнение за своите собствени изпълнения в тази група.",+ "permission.page.groupDevicePolicyFixedDesc": "Членовете могат да използват само средата, която сте задали за тази група.",+ "permission.page.groupDevicePolicyMemberDesc": "Членовете могат да задават своя собствена среда за изпълнение.",+ "permission.page.groupDevicePolicyUnset": "Изберете среда за изпълнение за оркестратора първо, след това можете да я фиксирате тук.",+ "permission.page.groupGeneralAccessDesc": "Какво може да прави всеки член на работното пространство с тази група. Същото ниво се прилага и за агентите-членове, които групата притежава. Създателят и собствениците на работното пространство винаги запазват пълен достъп.",+ "permission.page.groupModelPolicyDesc": "Дали членовете могат да сменят модела за своите собствени разговори в тази група.",+ "permission.page.groupModelPolicyFixedDesc": "Членовете могат да използват само модела, който сте задали за тази група.",+ "permission.page.groupModelPolicyMemberDesc": "Членовете могат да използват модел, който сами са задали.",+ "permission.page.groupPersonalDesc": "Тази група принадлежи само на вас, така че все още няма какво да се споделя. Публикувайте я в работно пространство, за да зададете права за членовете.",+ "permission.page.groupPersonalTitle": "Правата се прилагат за групи в работното пространство",+ "permission.page.groupPrivateNotice": "Тази група все още е частна. Всичко тук ще влезе в сила, след като я публикувате в работното пространство.","permission.page.memberGroup": "Достъп","permission.page.modelPolicyDesc": "Дали членовете могат да сменят модела за своите собствени разговори.","permission.page.modelPolicyFixedDesc": "Членовете могат да използват само модела, който сте задали",diff --git a/locales/de-DE/setting.json b/locales/de-DE/setting.jsonindex 3b257eefec5..d6cb66fcd86 100644--- a/locales/de-DE/setting.json+++ b/locales/de-DE/setting.json@@ -623,6 +623,18 @@"permission.page.editableWhenShared": "Kann bearbeitet werden, wenn geteilt","permission.page.entry": "Mitgliederberechtigungen","permission.page.generalAccessDesc": "Was jeder Arbeitsbereichsmitglied mit diesem Agenten tun kann. Der Ersteller und die Arbeitsbereichsbesitzer behalten immer vollen Zugriff.",+ "permission.page.groupAccessLevelPrivateHint": "Mitglieder erhalten diese Stufe, sobald die Gruppe im Arbeitsbereich veröffentlicht wird. Sie kann nach der Veröffentlichung geändert werden.",+ "permission.page.groupDevicePolicyDesc": "Ob Mitglieder die Ausführungsumgebung für ihre eigenen Abläufe in dieser Gruppe wechseln können.",+ "permission.page.groupDevicePolicyFixedDesc": "Mitglieder können nur die von Ihnen für diese Gruppe festgelegte Umgebung verwenden.",+ "permission.page.groupDevicePolicyMemberDesc": "Mitglieder können ihre eigene Ausführungsumgebung festlegen.",+ "permission.page.groupDevicePolicyUnset": "Wählen Sie zuerst eine Ausführungsumgebung für den Orchestrator aus, dann können Sie sie hier festlegen.",+ "permission.page.groupGeneralAccessDesc": "Was jedes Mitglied des Arbeitsbereichs mit dieser Gruppe tun kann. Die gleiche Stufe gilt für die Mitgliederagenten, die die Gruppe besitzt. Der Ersteller und die Eigentümer des Arbeitsbereichs behalten immer vollen Zugriff.",+ "permission.page.groupModelPolicyDesc": "Ob Mitglieder das Modell für ihre eigenen Gespräche in dieser Gruppe wechseln können.",+ "permission.page.groupModelPolicyFixedDesc": "Mitglieder können nur das von Ihnen für diese Gruppe festgelegte Modell verwenden.",+ "permission.page.groupModelPolicyMemberDesc": "Mitglieder können ein Modell verwenden, das sie selbst festgelegt haben.",+ "permission.page.groupPersonalDesc": "Diese Gruppe gehört nur Ihnen, daher gibt es noch nichts zu teilen. Veröffentlichen Sie sie in einem Arbeitsbereich, um Mitgliederberechtigungen festzulegen.",+ "permission.page.groupPersonalTitle": "Berechtigungen gelten für Arbeitsbereichsgruppen",+ "permission.page.groupPrivateNotice": "Diese Gruppe ist noch privat. Alles hier tritt in Kraft, sobald Sie sie im Arbeitsbereich veröffentlichen.","permission.page.memberGroup": "Zugriff","permission.page.modelPolicyDesc": "Ob Mitglieder das Modell für ihre eigenen Gespräche wechseln können.","permission.page.modelPolicyFixedDesc": "Mitglieder können nur das von Ihnen festgelegte Modell verwenden",diff --git a/locales/en-US/setting.json b/locales/en-US/setting.jsonindex 04ffea597d1..e8807e06fbc 100644--- a/locales/en-US/setting.json+++ b/locales/en-US/setting.json@@ -623,6 +623,18 @@"permission.page.editableWhenShared": "Can edit when shared","permission.page.entry": "Member Permissions","permission.page.generalAccessDesc": "What every workspace member can do with this agent. The creator and workspace owners always keep full access.",+ "permission.page.groupAccessLevelPrivateHint": "Members get this level once the group is published to the workspace. It can be changed after publishing.",+ "permission.page.groupDevicePolicyDesc": "Whether members can switch the execution environment for their own runs in this group.",+ "permission.page.groupDevicePolicyFixedDesc": "Members can only use the environment you set for this group",+ "permission.page.groupDevicePolicyMemberDesc": "Members can set their own execution environment",+ "permission.page.groupDevicePolicyUnset": "Pick an execution environment for the orchestrator first, then you can fix it here.",+ "permission.page.groupGeneralAccessDesc": "What every workspace member can do with this group. The same level is applied to the member agents the group owns. The creator and workspace owners always keep full access.",+ "permission.page.groupModelPolicyDesc": "Whether members can switch the model for their own conversations in this group.",+ "permission.page.groupModelPolicyFixedDesc": "Members can only use the model you set for this group",+ "permission.page.groupModelPolicyMemberDesc": "Members can use a model they set themselves",+ "permission.page.groupPersonalDesc": "This group only belongs to you, so there is nothing to share yet. Publish it to a workspace to set member permissions.",+ "permission.page.groupPersonalTitle": "Permissions apply to workspace groups",+ "permission.page.groupPrivateNotice": "This group is still private. Everything here takes effect once you publish it to the workspace.","permission.page.memberGroup": "Access","permission.page.modelPolicyDesc": "Whether members can switch the model for their own conversations.","permission.page.modelPolicyFixedDesc": "Members can only use the model you set",diff --git a/locales/es-ES/setting.json b/locales/es-ES/setting.jsonindex 220b9663f46..c73bde0e1ba 100644--- a/locales/es-ES/setting.json+++ b/locales/es-ES/setting.json@@ -623,6 +623,18 @@"permission.page.editableWhenShared": "Puede editarse cuando se comparte","permission.page.entry": "Permisos de miembros","permission.page.generalAccessDesc": "Lo que cada miembro del espacio de trabajo puede hacer con este agente. El creador y los propietarios del espacio de trabajo siempre mantienen acceso completo.",+ "permission.page.groupAccessLevelPrivateHint": "Los miembros obtienen este nivel una vez que el grupo se publica en el espacio de trabajo. Puede cambiarse después de la publicación.",+ "permission.page.groupDevicePolicyDesc": "Si los miembros pueden cambiar el entorno de ejecución para sus propias ejecuciones en este grupo.",+ "permission.page.groupDevicePolicyFixedDesc": "Los miembros solo pueden usar el entorno que configures para este grupo.",+ "permission.page.groupDevicePolicyMemberDesc": "Los miembros pueden configurar su propio entorno de ejecución.",+ "permission.page.groupDevicePolicyUnset": "Primero selecciona un entorno de ejecución para el orquestador, luego podrás fijarlo aquí.",+ "permission.page.groupGeneralAccessDesc": "Lo que cada miembro del espacio de trabajo puede hacer con este grupo. El mismo nivel se aplica a los agentes miembros que posee el grupo. El creador y los propietarios del espacio de trabajo siempre mantienen acceso completo.",+ "permission.page.groupModelPolicyDesc": "Si los miembros pueden cambiar el modelo para sus propias conversaciones en este grupo.",+ "permission.page.groupModelPolicyFixedDesc": "Los miembros solo pueden usar el modelo que configures para este grupo.",+ "permission.page.groupModelPolicyMemberDesc": "Los miembros pueden usar un modelo que configuren ellos mismos.",+ "permission.page.groupPersonalDesc": "Este grupo solo te pertenece a ti, por lo que aún no hay nada que compartir. Publícalo en un espacio de trabajo para establecer permisos de miembros.",+ "permission.page.groupPersonalTitle": "Los permisos se aplican a los grupos del espacio de trabajo.",+ "permission.page.groupPrivateNotice": "Este grupo aún es privado. Todo aquí entrará en vigor una vez que lo publiques en el espacio de trabajo.","permission.page.memberGroup": "Acceso","permission.page.modelPolicyDesc": "Si los miembros pueden cambiar el modelo para sus propias conversaciones.","permission.page.modelPolicyFixedDesc": "Los miembros solo pueden usar el modelo que configures",diff --git a/locales/fa-IR/setting.json b/locales/fa-IR/setting.jsonindex ee5a376f5fc..08e005d7739 100644--- a/locales/fa-IR/setting.json+++ b/locales/fa-IR/setting.json@@ -623,6 +623,18 @@"permission.page.editableWhenShared": "قابل ویرایش هنگام اشتراکگذاری","permission.page.entry": "مجوزهای اعضا","permission.page.generalAccessDesc": "آنچه هر عضو فضای کاری میتواند با این عامل انجام دهد. سازنده و صاحبان فضای کاری همیشه دسترسی کامل دارند.",+ "permission.page.groupAccessLevelPrivateHint": "اعضا این سطح را زمانی دریافت میکنند که گروه به فضای کاری منتشر شود. این سطح میتواند پس از انتشار تغییر کند.",+ "permission.page.groupDevicePolicyDesc": "آیا اعضا میتوانند محیط اجرای خود را برای اجرای خود در این گروه تغییر دهند یا خیر.",+ "permission.page.groupDevicePolicyFixedDesc": "اعضا فقط میتوانند از محیطی که شما برای این گروه تنظیم کردهاید استفاده کنند.",+ "permission.page.groupDevicePolicyMemberDesc": "اعضا میتوانند محیط اجرای خود را تنظیم کنند.",+ "permission.page.groupDevicePolicyUnset": "ابتدا یک محیط اجرا برای ارکستراتور انتخاب کنید، سپس میتوانید آن را اینجا ثابت کنید.",+ "permission.page.groupGeneralAccessDesc": "آنچه هر عضو فضای کاری میتواند با این گروه انجام دهد. همان سطح به عوامل عضوی که گروه مالک آنها است اعمال میشود. سازنده و صاحبان فضای کاری همیشه دسترسی کامل دارند.",+ "permission.page.groupModelPolicyDesc": "آیا اعضا میتوانند مدل را برای مکالمات خود در این گروه تغییر دهند یا خیر.",+ "permission.page.groupModelPolicyFixedDesc": "اعضا فقط میتوانند از مدلی که شما برای این گروه تنظیم کردهاید استفاده کنند.",+ "permission.page.groupModelPolicyMemberDesc": "اعضا میتوانند از مدلی که خودشان تنظیم کردهاند استفاده کنند.",+ "permission.page.groupPersonalDesc": "این گروه فقط متعلق به شماست، بنابراین هنوز چیزی برای اشتراکگذاری وجود ندارد. آن را به یک فضای کاری منتشر کنید تا مجوزهای اعضا تنظیم شود.",+ "permission.page.groupPersonalTitle": "مجوزها برای گروههای فضای کاری اعمال میشوند.",+ "permission.page.groupPrivateNotice": "این گروه هنوز خصوصی است. همه چیز اینجا زمانی اعمال میشود که آن را به فضای کاری منتشر کنید.","permission.page.memberGroup": "دسترسی","permission.page.modelPolicyDesc": "آیا اعضا میتوانند مدل را برای مکالمات خود تغییر دهند؟","permission.page.modelPolicyFixedDesc": "اعضا فقط میتوانند از مدلی که شما تنظیم کردهاید استفاده کنند",diff --git a/locales/fr-FR/setting.json b/locales/fr-FR/setting.jsonindex 59b2878f6d6..28d744d3ae6 100644--- a/locales/fr-FR/setting.json+++ b/locales/fr-FR/setting.json@@ -623,6 +623,18 @@"permission.page.editableWhenShared": "Peut être modifié lorsqu'il est partagé","permission.page.entry": "Autorisations des membres","permission.page.generalAccessDesc": "Ce que chaque membre de l'espace de travail peut faire avec cet agent. Le créateur et les propriétaires de l'espace de travail conservent toujours un accès complet.",+ "permission.page.groupAccessLevelPrivateHint": "Les membres obtiennent ce niveau une fois que le groupe est publié dans l'espace de travail. Il peut être modifié après la publication.",+ "permission.page.groupDevicePolicyDesc": "Détermine si les membres peuvent changer l'environnement d'exécution pour leurs propres exécutions dans ce groupe.",+ "permission.page.groupDevicePolicyFixedDesc": "Les membres ne peuvent utiliser que l'environnement que vous avez défini pour ce groupe.",+ "permission.page.groupDevicePolicyMemberDesc": "Les membres peuvent définir leur propre environnement d'exécution.",+ "permission.page.groupDevicePolicyUnset": "Choisissez d'abord un environnement d'exécution pour l'orchestrateur, puis vous pourrez le fixer ici.",+ "permission.page.groupGeneralAccessDesc": "Ce que chaque membre de l'espace de travail peut faire avec ce groupe. Le même niveau est appliqué aux agents membres que possède le groupe. Le créateur et les propriétaires de l'espace de travail conservent toujours un accès complet.",+ "permission.page.groupModelPolicyDesc": "Détermine si les membres peuvent changer le modèle pour leurs propres conversations dans ce groupe.",+ "permission.page.groupModelPolicyFixedDesc": "Les membres ne peuvent utiliser que le modèle que vous avez défini pour ce groupe.",+ "permission.page.groupModelPolicyMemberDesc": "Les membres peuvent utiliser un modèle qu'ils ont eux-mêmes défini.",+ "permission.page.groupPersonalDesc": "Ce groupe vous appartient uniquement, il n'y a donc rien à partager pour l'instant. Publiez-le dans un espace de travail pour définir les autorisations des membres.",+ "permission.page.groupPersonalTitle": "Les autorisations s'appliquent aux groupes de l'espace de travail.",+ "permission.page.groupPrivateNotice": "Ce groupe est encore privé. Tout ce qui est ici prendra effet une fois que vous l'aurez publié dans l'espace de travail.","permission.page.memberGroup": "Accès","permission.page.modelPolicyDesc": "Détermine si les membres peuvent changer le modèle pour leurs propres conversations.","permission.page.modelPolicyFixedDesc": "Les membres ne peuvent utiliser que le modèle que vous avez défini",diff --git a/locales/it-IT/setting.json b/locales/it-IT/setting.jsonindex 2327d48bab0..681b27fd67e 100644--- a/locales/it-IT/setting.json+++ b/locales/it-IT/setting.json@@ -623,6 +623,18 @@"permission.page.editableWhenShared": "Modificabile quando condiviso","permission.page.entry": "Permessi dei membri","permission.page.generalAccessDesc": "Cosa ogni membro dello spazio di lavoro può fare con questo agente. Il creatore e i proprietari dello spazio di lavoro mantengono sempre pieno accesso.",+ "permission.page.groupAccessLevelPrivateHint": "I membri ottengono questo livello una volta che il gruppo è pubblicato nello spazio di lavoro. Può essere modificato dopo la pubblicazione.",+ "permission.page.groupDevicePolicyDesc": "Se i membri possono cambiare l'ambiente di esecuzione per le proprie esecuzioni in questo gruppo.",+ "permission.page.groupDevicePolicyFixedDesc": "I membri possono utilizzare solo l'ambiente che hai impostato per questo gruppo.",+ "permission.page.groupDevicePolicyMemberDesc": "I membri possono impostare il proprio ambiente di esecuzione.",+ "permission.page.groupDevicePolicyUnset": "Scegli prima un ambiente di esecuzione per l'orchestratore, poi puoi fissarlo qui.",+ "permission.page.groupGeneralAccessDesc": "Cosa ogni membro dello spazio di lavoro può fare con questo gruppo. Lo stesso livello viene applicato agli agenti membri che il gruppo possiede. Il creatore e i proprietari dello spazio di lavoro mantengono sempre pieno accesso.",+ "permission.page.groupModelPolicyDesc": "Se i membri possono cambiare il modello per le proprie conversazioni in questo gruppo.",+ "permission.page.groupModelPolicyFixedDesc": "I membri possono utilizzare solo il modello che hai impostato per questo gruppo.",+ "permission.page.groupModelPolicyMemberDesc": "I membri possono utilizzare un modello che hanno impostato loro stessi.",+ "permission.page.groupPersonalDesc": "Questo gruppo appartiene solo a te, quindi non c'è ancora nulla da condividere. Pubblicalo in uno spazio di lavoro per impostare i permessi dei membri.",+ "permission.page.groupPersonalTitle": "I permessi si applicano ai gruppi dello spazio di lavoro.",+ "permission.page.groupPrivateNotice": "Questo gruppo è ancora privato. Tutto ciò che è qui avrà effetto una volta che lo pubblichi nello spazio di lavoro.","permission.page.memberGroup": "Accesso","permission.page.modelPolicyDesc": "Se i membri possono cambiare il modello per le proprie conversazioni.","permission.page.modelPolicyFixedDesc": "I membri possono utilizzare solo il modello che hai impostato",diff --git a/locales/ja-JP/setting.json b/locales/ja-JP/setting.jsonindex d05f986c942..7da459498a7 100644--- a/locales/ja-JP/setting.json+++ b/locales/ja-JP/setting.json@@ -623,6 +623,18 @@"permission.page.editableWhenShared": "共有時に編集可能","permission.page.entry": "メンバー権限","permission.page.generalAccessDesc": "ワークスペースのメンバー全員がこのエージェントでできること。作成者とワークスペースの所有者は常に完全なアクセス権を保持します。",+ "permission.page.groupAccessLevelPrivateHint": "グループがワークスペースに公開されると、メンバーはこのレベルを取得します。公開後に変更することができます。",+ "permission.page.groupDevicePolicyDesc": "メンバーがこのグループ内で自分の実行環境を切り替えることができるかどうか。",+ "permission.page.groupDevicePolicyFixedDesc": "メンバーは、このグループに設定された環境のみを使用できます。",+ "permission.page.groupDevicePolicyMemberDesc": "メンバーは自分で実行環境を設定できます。",+ "permission.page.groupDevicePolicyUnset": "まずオーケストレーターの実行環境を選択し、それからここで固定できます。",+ "permission.page.groupGeneralAccessDesc": "ワークスペースのメンバー全員がこのグループでできること。同じレベルがグループが所有するメンバーエージェントにも適用されます。作成者とワークスペースの所有者は常に完全なアクセス権を保持します。",+ "permission.page.groupModelPolicyDesc": "メンバーがこのグループ内で自分の会話に使用するモデルを切り替えることができるかどうか。",+ "permission.page.groupModelPolicyFixedDesc": "メンバーは、このグループに設定されたモデルのみを使用できます。",+ "permission.page.groupModelPolicyMemberDesc": "メンバーは自分で設定したモデルを使用できます。",+ "permission.page.groupPersonalDesc": "このグループはあなた専用のものなので、まだ共有するものはありません。メンバーの権限を設定するには、ワークスペースに公開してください。",+ "permission.page.groupPersonalTitle": "権限はワークスペースグループに適用されます",+ "permission.page.groupPrivateNotice": "このグループはまだ非公開です。ここでの設定は、ワークスペースに公開されると有効になります。","permission.page.memberGroup": "アクセス","permission.page.modelPolicyDesc": "メンバーが自分の会話用にモデルを切り替えられるかどうか。","permission.page.modelPolicyFixedDesc": "メンバーはあなたが設定したモデルのみを使用できます",diff --git a/locales/ko-KR/setting.json b/locales/ko-KR/setting.jsonindex 0504f5cc47c..7a149cd2b7a 100644--- a/locales/ko-KR/setting.json+++ b/locales/ko-KR/setting.json@@ -623,6 +623,18 @@"permission.page.editableWhenShared": "공유 시 편집 가능","permission.page.entry": "멤버 권한","permission.page.generalAccessDesc": "워크스페이스 멤버가 이 에이전트로 할 수 있는 작업입니다. 생성자와 워크스페이스 소유자는 항상 전체 접근 권한을 유지합니다.",+ "permission.page.groupAccessLevelPrivateHint": "그룹이 워크스페이스에 게시되면 멤버는 이 수준을 받게 됩니다. 게시 후 변경할 수 있습니다.",+ "permission.page.groupDevicePolicyDesc": "멤버가 이 그룹에서 자신의 실행 환경을 변경할 수 있는지 여부를 설정합니다.",+ "permission.page.groupDevicePolicyFixedDesc": "멤버는 이 그룹에 대해 설정한 환경만 사용할 수 있습니다.",+ "permission.page.groupDevicePolicyMemberDesc": "멤버는 자신의 실행 환경을 설정할 수 있습니다.",+ "permission.page.groupDevicePolicyUnset": "오케스트레이터의 실행 환경을 먼저 선택한 후, 여기에서 고정할 수 있습니다.",+ "permission.page.groupGeneralAccessDesc": "모든 워크스페이스 멤버가 이 그룹에서 수행할 수 있는 작업입니다. 동일한 수준이 그룹이 소유한 멤버 에이전트에도 적용됩니다. 생성자와 워크스페이스 소유자는 항상 전체 액세스 권한을 유지합니다.",+ "permission.page.groupModelPolicyDesc": "멤버가 이 그룹에서 자신의 대화에 사용할 모델을 변경할 수 있는지 여부를 설정합니다.",+ "permission.page.groupModelPolicyFixedDesc": "멤버는 이 그룹에 대해 설정한 모델만 사용할 수 있습니다.",+ "permission.page.groupModelPolicyMemberDesc": "멤버는 자신이 설정한 모델을 사용할 수 있습니다.",+ "permission.page.groupPersonalDesc": "이 그룹은 오직 당신만의 것이므로 아직 공유할 것이 없습니다. 워크스페이스에 게시하여 멤버 권한을 설정하세요.",+ "permission.page.groupPersonalTitle": "권한은 워크스페이스 그룹에 적용됩니다.",+ "permission.page.groupPrivateNotice": "이 그룹은 아직 비공개 상태입니다. 여기에서 설정한 모든 것이 워크스페이스에 게시되면 적용됩니다.","permission.page.memberGroup": "접근","permission.page.modelPolicyDesc": "멤버가 자신의 대화에 사용할 모델을 전환할 수 있는지 여부를 설정합니다.","permission.page.modelPolicyFixedDesc": "멤버는 설정한 모델만 사용할 수 있습니다.",diff --git a/locales/nl-NL/setting.json b/locales/nl-NL/setting.jsonindex 4decae3c663..aab3df03acc 100644--- a/locales/nl-NL/setting.json+++ b/locales/nl-NL/setting.json@@ -623,6 +623,18 @@"permission.page.editableWhenShared": "Kan bewerkt worden wanneer gedeeld","permission.page.entry": "Ledenrechten","permission.page.generalAccessDesc": "Wat elk lid van de werkruimte met deze agent kan doen. De maker en eigenaren van de werkruimte behouden altijd volledige toegang.",+ "permission.page.groupAccessLevelPrivateHint": "Leden krijgen dit niveau zodra de groep is gepubliceerd naar de werkruimte. Dit kan na publicatie worden gewijzigd.",+ "permission.page.groupDevicePolicyDesc": "Of leden de uitvoeringsomgeving voor hun eigen runs in deze groep kunnen wijzigen.",+ "permission.page.groupDevicePolicyFixedDesc": "Leden kunnen alleen de omgeving gebruiken die u voor deze groep hebt ingesteld.",+ "permission.page.groupDevicePolicyMemberDesc": "Leden kunnen hun eigen uitvoeringsomgeving instellen.",+ "permission.page.groupDevicePolicyUnset": "Kies eerst een uitvoeringsomgeving voor de orkestrator, daarna kunt u deze hier vastleggen.",+ "permission.page.groupGeneralAccessDesc": "Wat elk lid van de werkruimte met deze groep kan doen. Hetzelfde niveau wordt toegepast op de ledenagents die de groep bezit. De maker en werkruimte-eigenaren behouden altijd volledige toegang.",+ "permission.page.groupModelPolicyDesc": "Of leden het model voor hun eigen gesprekken in deze groep kunnen wijzigen.",+ "permission.page.groupModelPolicyFixedDesc": "Leden kunnen alleen het model gebruiken dat u voor deze groep hebt ingesteld.",+ "permission.page.groupModelPolicyMemberDesc": "Leden kunnen een model gebruiken dat ze zelf hebben ingesteld.",+ "permission.page.groupPersonalDesc": "Deze groep behoort alleen aan u toe, dus er is nog niets om te delen. Publiceer het naar een werkruimte om ledenrechten in te stellen.",+ "permission.page.groupPersonalTitle": "Rechten zijn van toepassing op werkruimtegroepen",+ "permission.page.groupPrivateNotice": "Deze groep is nog steeds privé. Alles hier wordt van kracht zodra u het publiceert naar de werkruimte.","permission.page.memberGroup": "Toegang","permission.page.modelPolicyDesc": "Of leden het model voor hun eigen gesprekken kunnen wijzigen.","permission.page.modelPolicyFixedDesc": "Leden kunnen alleen het model gebruiken dat u instelt",diff --git a/locales/pl-PL/setting.json b/locales/pl-PL/setting.jsonindex 03bf1e37629..869a220fee4 100644--- a/locales/pl-PL/setting.json+++ b/locales/pl-PL/setting.json@@ -623,6 +623,18 @@"permission.page.editableWhenShared": "Można edytować po udostępnieniu","permission.page.entry": "Uprawnienia członków","permission.page.generalAccessDesc": "Co każdy członek przestrzeni roboczej może zrobić z tym agentem. Twórca i właściciele przestrzeni roboczej zawsze mają pełny dostęp.",+ "permission.page.groupAccessLevelPrivateHint": "Członkowie otrzymują ten poziom dostępu, gdy grupa zostanie opublikowana w przestrzeni roboczej. Można go zmienić po publikacji.",+ "permission.page.groupDevicePolicyDesc": "Czy członkowie mogą zmieniać środowisko wykonawcze dla swoich własnych uruchomień w tej grupie.",+ "permission.page.groupDevicePolicyFixedDesc": "Członkowie mogą korzystać tylko ze środowiska, które ustawisz dla tej grupy.",+ "permission.page.groupDevicePolicyMemberDesc": "Członkowie mogą ustawić własne środowisko wykonawcze.",+ "permission.page.groupDevicePolicyUnset": "Najpierw wybierz środowisko wykonawcze dla orkiestratora, a następnie możesz je tutaj ustalić.",+ "permission.page.groupGeneralAccessDesc": "Co każdy członek przestrzeni roboczej może zrobić z tą grupą. Ten sam poziom dostępu jest stosowany do agentów członkowskich, których grupa jest właścicielem. Twórca i właściciele przestrzeni roboczej zawsze mają pełny dostęp.",+ "permission.page.groupModelPolicyDesc": "Czy członkowie mogą zmieniać model dla swoich własnych rozmów w tej grupie.",+ "permission.page.groupModelPolicyFixedDesc": "Członkowie mogą korzystać tylko z modelu, który ustawisz dla tej grupy.",+ "permission.page.groupModelPolicyMemberDesc": "Członkowie mogą korzystać z modelu, który sami ustawili.",+ "permission.page.groupPersonalDesc": "Ta grupa należy tylko do Ciebie, więc nie ma jeszcze nic do udostępnienia. Opublikuj ją w przestrzeni roboczej, aby ustawić uprawnienia członków.",+ "permission.page.groupPersonalTitle": "Uprawnienia dotyczą grup w przestrzeni roboczej",+ "permission.page.groupPrivateNotice": "Ta grupa jest nadal prywatna. Wszystko tutaj zacznie obowiązywać po jej opublikowaniu w przestrzeni roboczej.","permission.page.memberGroup": "Dostęp","permission.page.modelPolicyDesc": "Czy członkowie mogą zmieniać model dla swoich własnych rozmów.","permission.page.modelPolicyFixedDesc": "Członkowie mogą korzystać tylko z modelu, który ustawisz",diff --git a/locales/pt-BR/setting.json b/locales/pt-BR/setting.jsonindex 021a526eb8a..fad59f473c9 100644--- a/locales/pt-BR/setting.json+++ b/locales/pt-BR/setting.json@@ -623,6 +623,18 @@"permission.page.editableWhenShared": "Pode editar quando compartilhado","permission.page.entry": "Permissões de Membro","permission.page.generalAccessDesc": "O que cada membro do espaço de trabalho pode fazer com este agente. O criador e os proprietários do espaço de trabalho sempre mantêm acesso total.",+ "permission.page.groupAccessLevelPrivateHint": "Os membros recebem este nível assim que o grupo é publicado no espaço de trabalho. Isso pode ser alterado após a publicação.",+ "permission.page.groupDevicePolicyDesc": "Se os membros podem alternar o ambiente de execução para suas próprias execuções neste grupo.",+ "permission.page.groupDevicePolicyFixedDesc": "Os membros só podem usar o ambiente que você definiu para este grupo.",+ "permission.page.groupDevicePolicyMemberDesc": "Os membros podem definir seu próprio ambiente de execução.",+ "permission.page.groupDevicePolicyUnset": "Escolha primeiro um ambiente de execução para o orquestrador, depois você pode fixá-lo aqui.",+ "permission.page.groupGeneralAccessDesc": "O que cada membro do espaço de trabalho pode fazer com este grupo. O mesmo nível é aplicado aos agentes membros que o grupo possui. O criador e os proprietários do espaço de trabalho sempre mantêm acesso total.",+ "permission.page.groupModelPolicyDesc": "Se os membros podem alternar o modelo para suas próprias conversas neste grupo.",+ "permission.page.groupModelPolicyFixedDesc": "Os membros só podem usar o modelo que você definiu para este grupo.",+ "permission.page.groupModelPolicyMemberDesc": "Os membros podem usar um modelo que eles mesmos definiram.",+ "permission.page.groupPersonalDesc": "Este grupo pertence apenas a você, então ainda não há nada para compartilhar. Publique-o em um espaço de trabalho para definir as permissões dos membros.",+ "permission.page.groupPersonalTitle": "As permissões se aplicam aos grupos do espaço de trabalho.",+ "permission.page.groupPrivateNotice": "Este grupo ainda é privado. Tudo aqui entra em vigor assim que você o publica no espaço de trabalho.","permission.page.memberGroup": "Acesso","permission.page.modelPolicyDesc": "Se os membros podem alterar o modelo para suas próprias conversas.","permission.page.modelPolicyFixedDesc": "Os membros só podem usar o modelo que você definiu",diff --git a/locales/ru-RU/setting.json b/locales/ru-RU/setting.jsonindex 523a16cf8b3..dbf6aa14d61 100644--- a/locales/ru-RU/setting.json+++ b/locales/ru-RU/setting.json@@ -623,6 +623,18 @@"permission.page.editableWhenShared": "Можно редактировать при совместном использовании","permission.page.entry": "Разрешения участников","permission.page.generalAccessDesc": "Что каждый участник рабочего пространства может делать с этим агентом. Создатель и владельцы рабочего пространства всегда сохраняют полный доступ.",+ "permission.page.groupAccessLevelPrivateHint": "Участники получают этот уровень, как только группа публикуется в рабочую область. Это можно изменить после публикации.",+ "permission.page.groupDevicePolicyDesc": "Могут ли участники переключать среду выполнения для своих собственных запусков в этой группе.",+ "permission.page.groupDevicePolicyFixedDesc": "Участники могут использовать только ту среду, которую вы установили для этой группы.",+ "permission.page.groupDevicePolicyMemberDesc": "Участники могут устанавливать свою собственную среду выполнения.",+ "permission.page.groupDevicePolicyUnset": "Сначала выберите среду выполнения для оркестратора, затем вы сможете зафиксировать её здесь.",+ "permission.page.groupGeneralAccessDesc": "Что каждый участник рабочей области может делать с этой группой. Тот же уровень применяется к агентам-участникам, которыми владеет группа. Создатель и владельцы рабочей области всегда сохраняют полный доступ.",+ "permission.page.groupModelPolicyDesc": "Могут ли участники переключать модель для своих собственных разговоров в этой группе.",+ "permission.page.groupModelPolicyFixedDesc": "Участники могут использовать только ту модель, которую вы установили для этой группы.",+ "permission.page.groupModelPolicyMemberDesc": "Участники могут использовать модель, которую они установили сами.",+ "permission.page.groupPersonalDesc": "Эта группа принадлежит только вам, поэтому пока нечего делить. Опубликуйте её в рабочей области, чтобы установить разрешения для участников.",+ "permission.page.groupPersonalTitle": "Разрешения применяются к группам рабочей области",+ "permission.page.groupPrivateNotice": "Эта группа всё ещё является частной. Всё здесь вступит в силу, как только вы опубликуете её в рабочей области.","permission.page.memberGroup": "Доступ","permission.page.modelPolicyDesc": "Могут ли участники переключать модель для своих собственных разговоров.","permission.page.modelPolicyFixedDesc": "Участники могут использовать только ту модель, которую вы установили",diff --git a/locales/tr-TR/setting.json b/locales/tr-TR/setting.jsonindex 3755f2cc043..508b9fd5c44 100644--- a/locales/tr-TR/setting.json+++ b/locales/tr-TR/setting.json@@ -623,6 +623,18 @@"permission.page.editableWhenShared": "Paylaşıldığında düzenlenebilir","permission.page.entry": "Üye İzinleri","permission.page.generalAccessDesc": "Her çalışma alanı üyesinin bu ajanla ne yapabileceği. Oluşturucu ve çalışma alanı sahipleri her zaman tam erişime sahiptir.",+ "permission.page.groupAccessLevelPrivateHint": "Grup, çalışma alanına yayınlandığında üyeler bu seviyeyi alır. Yayınlandıktan sonra değiştirilebilir.",+ "permission.page.groupDevicePolicyDesc": "Üyelerin bu gruptaki kendi çalıştırma ortamlarını değiştirip değiştiremeyeceği.",+ "permission.page.groupDevicePolicyFixedDesc": "Üyeler yalnızca bu grup için belirlediğiniz ortamı kullanabilir.",+ "permission.page.groupDevicePolicyMemberDesc": "Üyeler kendi çalıştırma ortamlarını ayarlayabilir.",+ "permission.page.groupDevicePolicyUnset": "Önce düzenleyici için bir çalıştırma ortamı seçin, ardından burada sabitleyebilirsiniz.",+ "permission.page.groupGeneralAccessDesc": "Her çalışma alanı üyesinin bu grupla ne yapabileceği. Grup sahip olduğu üye ajanlara aynı seviye uygulanır. Oluşturucu ve çalışma alanı sahipleri her zaman tam erişime sahiptir.",+ "permission.page.groupModelPolicyDesc": "Üyelerin bu gruptaki kendi konuşmaları için modeli değiştirip değiştiremeyeceği.",+ "permission.page.groupModelPolicyFixedDesc": "Üyeler yalnızca bu grup için belirlediğiniz modeli kullanabilir.",+ "permission.page.groupModelPolicyMemberDesc": "Üyeler kendi belirledikleri bir modeli kullanabilir.",+ "permission.page.groupPersonalDesc": "Bu grup yalnızca size aittir, bu yüzden henüz paylaşacak bir şey yok. Üye izinlerini ayarlamak için bunu bir çalışma alanına yayınlayın.",+ "permission.page.groupPersonalTitle": "İzinler çalışma alanı gruplarına uygulanır.",+ "permission.page.groupPrivateNotice": "Bu grup hâlâ özel. Buradaki her şey, çalışma alanına yayınladığınızda etkili olur.","permission.page.memberGroup": "Erişim","permission.page.modelPolicyDesc": "Üyelerin kendi konuşmaları için modeli değiştirip değiştiremeyeceği.","permission.page.modelPolicyFixedDesc": "Üyeler yalnızca sizin belirlediğiniz modeli kullanabilir",diff --git a/locales/vi-VN/setting.json b/locales/vi-VN/setting.jsonindex 4d0911dd42a..b981a97fdb2 100644--- a/locales/vi-VN/setting.json+++ b/locales/vi-VN/setting.json@@ -623,6 +623,18 @@"permission.page.editableWhenShared": "Có thể chỉnh sửa khi được chia sẻ","permission.page.entry": "Quyền của Thành viên","permission.page.generalAccessDesc": "Những gì mọi thành viên trong không gian làm việc có thể làm với tác nhân này. Người tạo và chủ sở hữu không gian làm việc luôn giữ quyền truy cập đầy đủ.",+ "permission.page.groupAccessLevelPrivateHint": "Thành viên sẽ nhận được cấp độ này khi nhóm được xuất bản lên không gian làm việc. Cấp độ này có thể được thay đổi sau khi xuất bản.",+ "permission.page.groupDevicePolicyDesc": "Quy định liệu thành viên có thể thay đổi môi trường thực thi cho các lần chạy của họ trong nhóm này hay không.",+ "permission.page.groupDevicePolicyFixedDesc": "Thành viên chỉ có thể sử dụng môi trường mà bạn đã thiết lập cho nhóm này.",+ "permission.page.groupDevicePolicyMemberDesc": "Thành viên có thể tự thiết lập môi trường thực thi của họ.",+ "permission.page.groupDevicePolicyUnset": "Hãy chọn môi trường thực thi cho bộ điều phối trước, sau đó bạn có thể cố định nó tại đây.",+ "permission.page.groupGeneralAccessDesc": "Những gì mỗi thành viên không gian làm việc có thể làm với nhóm này. Cùng một cấp độ sẽ được áp dụng cho các tác nhân thành viên mà nhóm sở hữu. Người tạo và chủ sở hữu không gian làm việc luôn giữ quyền truy cập đầy đủ.",+ "permission.page.groupModelPolicyDesc": "Quy định liệu thành viên có thể thay đổi mô hình cho các cuộc trò chuyện của họ trong nhóm này hay không.",+ "permission.page.groupModelPolicyFixedDesc": "Thành viên chỉ có thể sử dụng mô hình mà bạn đã thiết lập cho nhóm này.",+ "permission.page.groupModelPolicyMemberDesc": "Thành viên có thể sử dụng mô hình mà họ tự thiết lập.",+ "permission.page.groupPersonalDesc": "Nhóm này chỉ thuộc về bạn, vì vậy hiện tại chưa có gì để chia sẻ. Xuất bản nó lên không gian làm việc để thiết lập quyền của thành viên.",+ "permission.page.groupPersonalTitle": "Quyền áp dụng cho các nhóm trong không gian làm việc",+ "permission.page.groupPrivateNotice": "Nhóm này vẫn đang ở chế độ riêng tư. Mọi thứ ở đây sẽ có hiệu lực khi bạn xuất bản nó lên không gian làm việc.","permission.page.memberGroup": "Quyền truy cập","permission.page.modelPolicyDesc": "Liệu thành viên có thể chuyển đổi mô hình cho các cuộc hội thoại của họ hay không.","permission.page.modelPolicyFixedDesc": "Thành viên chỉ có thể sử dụng mô hình mà bạn đã thiết lập",diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.jsonindex 81b32762366..a7b3871fa78 100644--- a/locales/zh-CN/setting.json+++ b/locales/zh-CN/setting.json@@ -623,6 +623,18 @@"permission.page.editableWhenShared": "公开后可编辑","permission.page.entry": "成员权限","permission.page.generalAccessDesc": "工作区成员可以对这个助手做什么。创建者和工作区所有者始终拥有完整权限。",+ "permission.page.groupAccessLevelPrivateHint": "发布到工作区后成员会拿到这个级别,发布后可以再调整。",+ "permission.page.groupDevicePolicyDesc": "成员在这个群组的运行中是否可以切换执行环境。",+ "permission.page.groupDevicePolicyFixedDesc": "成员只能使用你为这个群组设定的执行环境",+ "permission.page.groupDevicePolicyMemberDesc": "成员可以自己设定执行环境",+ "permission.page.groupDevicePolicyUnset": "请先为群组主管选择执行环境,之后才能在这里固定它。",+ "permission.page.groupGeneralAccessDesc": "工作区成员可以对这个群组做什么。同样的级别会应用到群组自有的成员助手上。创建者和工作区所有者始终拥有完整权限。",+ "permission.page.groupModelPolicyDesc": "成员在这个群组的会话中是否可以切换模型。",+ "permission.page.groupModelPolicyFixedDesc": "成员只能使用你为这个群组设定的模型",+ "permission.page.groupModelPolicyMemberDesc": "成员可以使用自己设定的模型",+ "permission.page.groupPersonalDesc": "这个群组只属于你,暂时没有需要分享的对象。发布到工作区后即可设置成员权限。",+ "permission.page.groupPersonalTitle": "权限配置仅对工作区群组生效",+ "permission.page.groupPrivateNotice": "这个群组当前是私人的,以下配置会在发布到工作区后生效。","permission.page.memberGroup": "访问权限","permission.page.modelPolicyDesc": "成员在自己的会话中是否可以切换模型。","permission.page.modelPolicyFixedDesc": "成员只能使用你设定的模型",diff --git a/locales/zh-TW/setting.json b/locales/zh-TW/setting.jsonindex 32c3aed1133..3b891687c0c 100644--- a/locales/zh-TW/setting.json+++ b/locales/zh-TW/setting.json@@ -623,6 +623,18 @@"permission.page.editableWhenShared": "共享時可編輯","permission.page.entry": "成員權限","permission.page.generalAccessDesc": "每個工作區成員對此代理程式的操作權限。創建者和工作區擁有者始終擁有完整存取權限。",+ "permission.page.groupAccessLevelPrivateHint": "成員在群組發佈到工作區後會獲得此級別。發佈後可以進行更改。",+ "permission.page.groupDevicePolicyDesc": "是否允許成員切換執行環境以進行群組內的運行。",+ "permission.page.groupDevicePolicyFixedDesc": "成員只能使用您為此群組設定的環境。",+ "permission.page.groupDevicePolicyMemberDesc": "成員可以設定自己的執行環境。",+ "permission.page.groupDevicePolicyUnset": "請先為協調器選擇執行環境,然後才能在此固定設定。",+ "permission.page.groupGeneralAccessDesc": "工作區成員對此群組的操作權限。相同的級別也適用於群組擁有的成員代理。創建者和工作區擁有者始終擁有完全訪問權限。",+ "permission.page.groupModelPolicyDesc": "是否允許成員切換模型以進行群組內的對話。",+ "permission.page.groupModelPolicyFixedDesc": "成員只能使用您為此群組設定的模型。",+ "permission.page.groupModelPolicyMemberDesc": "成員可以使用自己設定的模型。",+ "permission.page.groupPersonalDesc": "此群組僅屬於您,因此目前無需分享。發佈到工作區後即可設定成員權限。",+ "permission.page.groupPersonalTitle": "權限適用於工作區群組",+ "permission.page.groupPrivateNotice": "此群組仍為私人狀態。所有設定在發佈到工作區後生效。","permission.page.memberGroup": "存取權限","permission.page.modelPolicyDesc": "成員是否可以為自己的對話切換模型。","permission.page.modelPolicyFixedDesc": "成員只能使用您設定的模型",diff --git a/packages/builtin-agents/src/collaborative.test.ts b/packages/builtin-agents/src/collaborative.test.tsnew file mode 100644index 00000000000..3ab0242f89c--- /dev/null+++ b/packages/builtin-agents/src/collaborative.test.ts@@ -0,0 +1,34 @@+import { describe, expect, it } from 'vitest';++import { isCollaborativeBuiltinAgentRow } from './collaborative';+import { BUILTIN_AGENT_SLUGS } from './types';++const builder = {+ slug: BUILTIN_AGENT_SLUGS.groupAgentBuilder,+ virtual: true,+ workspaceId: 'workspace-1',+};++describe('isCollaborativeBuiltinAgentRow', () => {+ it('matches a provisioned workspace builtin', () => {+ expect(isCollaborativeBuiltinAgentRow(builder)).toBe(true);+ });++ it('rejects the personal copy of the same builtin', () => {+ expect(isCollaborativeBuiltinAgentRow({ ...builder, workspaceId: null })).toBe(false);+ });++ it('rejects a legacy row that merely holds a reserved slug', () => {+ expect(isCollaborativeBuiltinAgentRow({ ...builder, virtual: false })).toBe(false);+ });++ it('rejects a builtin members are not meant to configure together', () => {+ expect(+ isCollaborativeBuiltinAgentRow({ ...builder, slug: BUILTIN_AGENT_SLUGS.taskAgent }),+ ).toBe(false);+ });++ it('rejects an ordinary agent', () => {+ expect(isCollaborativeBuiltinAgentRow({ slug: null, workspaceId: 'workspace-1' })).toBe(false);+ });+});diff --git a/packages/builtin-agents/src/collaborative.ts b/packages/builtin-agents/src/collaborative.tsnew file mode 100644index 00000000000..b17bddbd4c0--- /dev/null+++ b/packages/builtin-agents/src/collaborative.ts@@ -0,0 +1,49 @@+import { BUILTIN_AGENT_SLUGS } from './types';++/**+ * Builtin agents that a Workspace provisions once and every member then works+ * in together, rather than one member owning them.+ *+ * The row is created lazily by whichever member reaches the feature first, so+ * `agents.user_id` records an accident of timing rather than authorship, and no+ * `resource_permissions` row is ever written for it. Two rules follow, and both+ * read this set:+ *+ * - authorization treats the row as workspace infrastructure instead of the+ * creator's private content (see `isCollaborativeBuiltinAgent` in the server's+ * resourcePermission service);+ * - the model choice stays personal for every member, admins included (see+ * `AgentModelConfig.personalModelSelection`).+ *+ * Deliberately NOT the whole of `BUILTIN_AGENT_SLUGS`: the internal automation+ * agents (`nightly-review`, `self-reflection`, `self-feedback-intent`,+ * `skill-management`, `verify-agent`, `task-agent`, the onboarding agents, the+ * group supervisor) have no configuration surface, and letting any member+ * repoint their persisted model / chatConfig would silently change background+ * automation for the entire workspace. They keep the ordinary creator + General+ * access rules, which still allow every member to reach them through whatever+ * level the workspace grants.+ */+export const COLLABORATIVE_BUILTIN_AGENT_SLUGS: ReadonlySet<string> = new Set<string>([+ BUILTIN_AGENT_SLUGS.agentBuilder,+ BUILTIN_AGENT_SLUGS.groupAgentBuilder,+ BUILTIN_AGENT_SLUGS.inbox,+ BUILTIN_AGENT_SLUGS.pageAgent,+]);++/**+ * Whether an agent row is one of the shared Workspace builtins above.+ *+ * `virtual` is what provisioning writes; a legacy row that merely holds a+ * reserved slug (the passthrough config endpoint used to allow that) stays an+ * ordinary agent, so no migration is needed to keep it out.+ */+export const isCollaborativeBuiltinAgentRow = (row: {+ slug?: string | null;+ virtual?: boolean | null;+ workspaceId?: string | null;+}): boolean =>+ !!row.workspaceId &&+ row.virtual === true &&+ !!row.slug &&+ COLLABORATIVE_BUILTIN_AGENT_SLUGS.has(row.slug);diff --git a/packages/builtin-agents/src/index.ts b/packages/builtin-agents/src/index.tsindex b440d738c82..42a697d70e4 100644--- a/packages/builtin-agents/src/index.ts+++ b/packages/builtin-agents/src/index.ts@@ -15,6 +15,7 @@ import { WEB_ONBOARDING } from './agents/web-onboarding';import type { BuiltinAgentDefinition, BuiltinAgentSlug, RuntimeContext } from './types';import { BUILTIN_AGENT_SLUGS } from './types';+export * from './collaborative';export * from './types';// Agent exportsdiff --git a/packages/builtin-tool-group-agent-builder/src/executor.test.ts b/packages/builtin-tool-group-agent-builder/src/executor.test.tsnew file mode 100644index 00000000000..7e9ca51b1ec--- /dev/null+++ b/packages/builtin-tool-group-agent-builder/src/executor.test.ts@@ -0,0 +1,129 @@+import type { BuiltinToolContext } from '@lobechat/types';+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(),+ }));++let activeGroupId: string | undefined = 'cg_1';++vi.mock('@/store/agentGroup', () => ({+ getChatGroupStoreState: () => ({+ activeGroupId,+ refreshGroupDetail: mockRefreshGroupDetail,+ refreshGroups: mockRefreshGroups,+ }),+}));++vi.mock('@/store/groupProfile', () => ({+ useGroupProfileStore: {+ getState: () => ({ setAgentBuilderContent: mockSetAgentBuilderContent }),+ },+}));++vi.mock('@/services/agent', () => ({ agentService: {} }));+vi.mock('@/services/discover', () => ({ discoverService: {} }));++vi.mock('@lobechat/agent-manager-runtime', () => ({ AgentManagerRuntime: vi.fn(() => ({})) }));++vi.mock('./ExecutionRuntime', () => ({+ GroupAgentBuilderExecutionRuntime: vi.fn(() => ({ createAgent: mockCreateAgent })),+}));++const afterCall = (apiName: string, params: unknown, success: boolean) =>+ groupAgentBuilderExecutor.onAfterCall({+ apiName,+ identifier: GroupAgentBuilderIdentifier,+ params,+ result: { content: '', success },+ });++describe('GroupAgentBuilderExecutor', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ activeGroupId = 'cg_1';+ });++ describe('group context resolution', () => {+ // The builder conversation is keyed by the builtin builder agent, so its+ // ConversationContext carries no groupId — falling back to the active group+ // is what keeps member creation working instead of erroring out.+ it('falls back to the active group when the tool context has no groupId', async () => {+ mockCreateAgent.mockResolvedValue({ content: 'ok', success: true });++ await groupAgentBuilderExecutor.createAgent(+ { systemRole: 'x', title: 'PM' },+ {} as BuiltinToolContext,+ );++ expect(mockCreateAgent).toHaveBeenCalledWith(+ 'cg_1',+ expect.objectContaining({ title: 'PM' }),+ );+ });++ it('reports a structured error when there is no group at all', async () => {+ activeGroupId = undefined;++ const result = await groupAgentBuilderExecutor.createAgent(+ { systemRole: 'x', title: 'PM' },+ {} as BuiltinToolContext,+ );++ expect(result).toMatchObject({ error: { type: 'NoGroupContext' }, success: false });+ expect(mockCreateAgent).not.toHaveBeenCalled();+ });+ });++ describe('onAfterCall', () => {+ // Under gateway mode the write commits server-side, so this hook is the only+ // thing that re-syncs the group Profile sidebar's member list.+ it('refreshes the group detail after a successful member write', async () => {+ await afterCall(GroupAgentBuilderApiName.batchCreateAgents, { agents: [] }, true);++ expect(mockRefreshGroupDetail).toHaveBeenCalledWith('cg_1');+ });++ it('does not refresh when the tool call failed', async () => {+ await afterCall(GroupAgentBuilderApiName.createAgent, { title: 'PM' }, false);++ expect(mockRefreshGroupDetail).not.toHaveBeenCalled();+ });++ it('does not refresh for read-only APIs', async () => {+ await afterCall(GroupAgentBuilderApiName.searchAgent, { query: 'pm' }, true);++ expect(mockRefreshGroupDetail).not.toHaveBeenCalled();+ });++ it('refreshes the group list after createGroup instead of a detail', async () => {+ await afterCall(GroupAgentBuilderApiName.createGroup, { title: 'Launch' }, true);++ expect(mockRefreshGroups).toHaveBeenCalled();+ expect(mockRefreshGroupDetail).not.toHaveBeenCalled();+ });++ it('syncs the open editor after a prompt write so autosave cannot revert it', async () => {+ await afterCall(+ GroupAgentBuilderApiName.updateAgentPrompt,+ { agentId: 'agt_1', prompt: 'new prompt' },+ true,+ );++ expect(mockSetAgentBuilderContent).toHaveBeenCalledWith('agt_1', 'new prompt');+ });++ it('syncs the group editor after a group prompt write', async () => {+ await afterCall(GroupAgentBuilderApiName.updateGroupPrompt, { prompt: 'shared' }, true);++ expect(mockSetAgentBuilderContent).toHaveBeenCalledWith('cg_1', 'shared');+ });+ });+});diff --git a/packages/builtin-tool-group-agent-builder/src/executor.ts b/packages/builtin-tool-group-agent-builder/src/executor.tsindex bb8c28f40dd..a01c4977395 100644--- a/packages/builtin-tool-group-agent-builder/src/executor.ts+++ b/packages/builtin-tool-group-agent-builder/src/executor.ts@@ -10,11 +10,13 @@ import type {InstallPluginParams,SearchMarketToolsParams,} from '@lobechat/builtin-tool-agent-builder';-import type { BuiltinToolContext, BuiltinToolResult } from '@lobechat/types';+import type { BuiltinToolContext, BuiltinToolResult, ToolAfterCallContext } from '@lobechat/types';import { BaseExecutor } from '@lobechat/types';import { agentService } from '@/services/agent';import { discoverService } from '@/services/discover';+import { getChatGroupStoreState } from '@/store/agentGroup';+import { useGroupProfileStore } from '@/store/groupProfile';import { GroupAgentBuilderExecutionRuntime } from './ExecutionRuntime';import type {@@ -38,6 +40,34 @@ const agentManagerRuntime = new AgentManagerRuntime({});const groupAgentBuilderRuntime = new GroupAgentBuilderExecutionRuntime();+// APIs that mutate group / member state. Under gateway mode these commit inside+// the server runtime, so the client stores only learn about them through+// `onAfterCall` (fired on `tool_end` regardless of where the tool ran).+const GROUP_WRITE_APIS = new Set<string>([+ GroupAgentBuilderApiName.batchCreateAgents,+ GroupAgentBuilderApiName.createAgent,+ GroupAgentBuilderApiName.inviteAgent,+ GroupAgentBuilderApiName.removeAgent,+ GroupAgentBuilderApiName.updateAgentPrompt,+ GroupAgentBuilderApiName.updateGroup,+ GroupAgentBuilderApiName.updateGroupPrompt,+]);++/**+ * 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 NO_GROUP_CONTEXT: BuiltinToolResult = {+ content: 'No active group found',+ error: { message: 'No active group found', type: 'NoGroupContext' },+ success: false,+};+class GroupAgentBuilderExecutor extends BaseExecutor<typeof GroupAgentBuilderApiName> {readonly identifier = GroupAgentBuilderIdentifier;protected readonly apiEnum = GroupAgentBuilderApiName;@@ -65,15 +95,9 @@ class GroupAgentBuilderExecutor extends BaseExecutor<typeof GroupAgentBuilderApiparams: CreateAgentParams,ctx: BuiltinToolContext,): Promise<BuiltinToolResult> => {- const groupId = ctx.groupId;+ const groupId = resolveActiveGroupId(ctx);- if (!groupId) {- return {- content: 'No active group found',- error: { message: 'No active group found', type: 'NoGroupContext' },- success: false,- };- }+ if (!groupId) return NO_GROUP_CONTEXT;return groupAgentBuilderRuntime.createAgent(groupId, params);};@@ -82,15 +106,9 @@ class GroupAgentBuilderExecutor extends BaseExecutor<typeof GroupAgentBuilderApiparams: BatchCreateAgentsParams,ctx: BuiltinToolContext,): Promise<BuiltinToolResult> => {- const groupId = ctx.groupId;+ const groupId = resolveActiveGroupId(ctx);- if (!groupId) {- return {- content: 'No active group found',- error: { message: 'No active group found', type: 'NoGroupContext' },- success: false,- };- }+ if (!groupId) return NO_GROUP_CONTEXT;return groupAgentBuilderRuntime.batchCreateAgents(groupId, params);};@@ -99,15 +117,9 @@ class GroupAgentBuilderExecutor extends BaseExecutor<typeof GroupAgentBuilderApiparams: InviteAgentParams,ctx: BuiltinToolContext,): Promise<BuiltinToolResult> => {- const groupId = ctx.groupId;+ const groupId = resolveActiveGroupId(ctx);- if (!groupId) {- return {- content: 'No active group found',- error: { message: 'No active group found', type: 'NoGroupContext' },- success: false,- };- }+ if (!groupId) return NO_GROUP_CONTEXT;return groupAgentBuilderRuntime.inviteAgent(groupId, params);};@@ -116,15 +128,9 @@ class GroupAgentBuilderExecutor extends BaseExecutor<typeof GroupAgentBuilderApiparams: RemoveAgentParams,ctx: BuiltinToolContext,): Promise<BuiltinToolResult> => {- const groupId = ctx.groupId;+ const groupId = resolveActiveGroupId(ctx);- if (!groupId) {- return {- content: 'No active group found',- error: { message: 'No active group found', type: 'NoGroupContext' },- success: false,- };- }+ if (!groupId) return NO_GROUP_CONTEXT;return groupAgentBuilderRuntime.removeAgent(groupId, params);};@@ -135,15 +141,9 @@ class GroupAgentBuilderExecutor extends BaseExecutor<typeof GroupAgentBuilderApiparams: UpdateAgentPromptParams,ctx: BuiltinToolContext,): Promise<BuiltinToolResult> => {- const groupId = ctx.groupId;+ const groupId = resolveActiveGroupId(ctx);- if (!groupId) {- return {- content: 'No active group found',- error: { message: 'No active group found', type: 'NoGroupContext' },- success: false,- };- }+ if (!groupId) return NO_GROUP_CONTEXT;return groupAgentBuilderRuntime.updateAgentPrompt(groupId, params);};@@ -205,6 +205,43 @@ class GroupAgentBuilderExecutor extends BaseExecutor<typeof GroupAgentBuilderApireturn agentManagerRuntime.installPlugin(agentId, params);};++ // ==================== Hooks ====================++ /**+ * Under gateway mode these tools run in the server runtime, so the client-side+ * `refreshGroupDetail` inside `GroupAgentBuilderExecutionRuntime` never fires+ * and the group Profile sidebar keeps showing the pre-change roster. This hook+ * 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> => {+ const groupStore = getChatGroupStoreState();++ // A brand-new group isn't in the list yet — refresh the list, not a detail.+ if (apiName === GroupAgentBuilderApiName.createGroup) {+ if (result.success) await groupStore.refreshGroups();+ return;+ }++ 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;+ if (!groupId) return;++ await groupStore.refreshGroupDetail(groupId);++ // Prompt writes must also land in the open editor: it treats its own JSON+ // doc as authoritative and would otherwise autosave the stale text back over+ // the change the agent just made.+ if (apiName === GroupAgentBuilderApiName.updateAgentPrompt && args.agentId) {+ useGroupProfileStore.getState().setAgentBuilderContent(args.agentId, args.prompt ?? '');+ }+ if (apiName === GroupAgentBuilderApiName.updateGroupPrompt) {+ useGroupProfileStore.getState().setAgentBuilderContent(groupId, args.prompt ?? '');+ }+ };}export const groupAgentBuilderExecutor = new GroupAgentBuilderExecutor();diff --git a/packages/builtin-tool-group-agent-builder/src/systemRole.ts b/packages/builtin-tool-group-agent-builder/src/systemRole.tsindex cc794fef62a..2603a9c085a 100644--- a/packages/builtin-tool-group-agent-builder/src/systemRole.ts+++ b/packages/builtin-tool-group-agent-builder/src/systemRole.ts@@ -44,6 +44,18 @@ You have access to tools that can modify group configurations:- **installPlugin**: Install and enable a plugin for the supervisor agent</capabilities>+<hard_constraints>+**These are absolute. Violating them produces agents that are stranded outside the group.**++1. **You are already inside a group.** Unless the user has no group yet, \`<current_group_context>\` tells you exactly which group you are configuring. Never ask the user to "create a group in your workspace" or to "invite the agents manually" — creating and wiring members IS your job, and you have the tools for it.++2. **Create members ONLY via \`createAgent\` / \`batchCreateAgents\`.** These create the agent AND add it to the current group in one step. NEVER use a general-purpose agent-creation tool from any other toolset (e.g. Agent Management) to build group members: those create standalone agents that land in the user's agent list and never join the group — exactly the outcome the user does not want.++3. **Never fabricate a manual workaround when a tool fails.** If a tool call returns an error, say plainly what failed and retry or ask the user how to proceed. Do not "helpfully" fall back to instructions for doing it by hand, and do not describe an agent as created/added unless the tool call actually succeeded.++4. **Report the real result.** After creating or inviting members, state which agents are now in the group, based on the tool results — not on what you intended to do.+</hard_constraints>+<prompt_architecture>**IMPORTANT: There are TWO types of prompts in a group:**@@ -199,6 +211,7 @@ When creating agents (via \`createAgent\` or \`batchCreateAgents\`), you MUST an10. **Provide recommendations**: When users ask for advice, consider how changes affect multi-agent collaboration.11. **Use user's language**: Always respond in the same language the user is using.12. **Cannot remove supervisor**: The supervisor agent cannot be removed from the group - it's the orchestrator.+13. **CRITICAL - Never delegate the work back to the user**: Do not suggest creating a group manually, inviting agents manually, or using another surface to do what your tools already do. See \`<hard_constraints>\`.</guidelines><configuration_knowledge>diff --git a/packages/builtin-tool-group-agent-builder/vitest.config.mts b/packages/builtin-tool-group-agent-builder/vitest.config.mtsnew file mode 100644index 00000000000..1d6d3125033--- /dev/null+++ b/packages/builtin-tool-group-agent-builder/vitest.config.mts@@ -0,0 +1,16 @@+import path from 'node:path';++import { defineConfig } from 'vitest/config';++export default defineConfig({+ test: {+ alias: {+ '@': path.resolve(__dirname, '../../src'),+ },+ coverage: {+ provider: 'v8',+ reporter: ['text', 'json', 'lcov', 'text-summary'],+ },+ environment: 'node',+ },+});diff --git a/packages/database/src/models/__tests__/resourcePermission.test.ts b/packages/database/src/models/__tests__/resourcePermission.test.tsindex aa628db3e86..f1b7116c078 100644--- a/packages/database/src/models/__tests__/resourcePermission.test.ts+++ b/packages/database/src/models/__tests__/resourcePermission.test.ts@@ -38,8 +38,8 @@ afterEach(async () => {describe('ResourcePermissionModel', () => {it.each([- ['agent', 'use'],- ['agentGroup', 'use'],+ ['agent', 'edit'],+ ['agentGroup', 'edit'],['document', 'view'],] as const)('falls back to %s-specific default %s without a row',diff --git a/packages/database/src/models/__tests__/topics/topic.query.test.ts b/packages/database/src/models/__tests__/topics/topic.query.test.tsindex 0dfbdb844e5..03b4b63c1d7 100644--- a/packages/database/src/models/__tests__/topics/topic.query.test.ts+++ b/packages/database/src/models/__tests__/topics/topic.query.test.ts@@ -213,7 +213,7 @@ describe('TopicModel - Query', () => {// The client sorts the sidebar by `sortUpdatedAt`, so it must carry the same// activity time the server ORDER BY uses (topicActivityAt) — otherwise the two// sorts disagree and the list jumps. `updatedAt` stays the raw row value so- // rename/favorite edits still show a real edit time.+ // rename/favorite edits still show a real edit time.await serverDB.insert(topics).values([{ id: 'has-msg', sessionId, updatedAt: new Date('2023-01-01'), userId },{ id: 'no-msg', sessionId, updatedAt: new Date('2023-03-01'), userId },@@ -928,6 +928,114 @@ describe('TopicModel - Query', () => {});});+ describe('query with editing-target filters', () => {+ // Builder panels run on one shared builtin agent for every target, so their+ // topics all carry the same `agentId` and no `groupId` (a groupId would pull+ // them into the target's own chat read path). What each conversation was+ // configuring lives only in `metadata.editingGroupId` / `editingAgentId`.+ // The panels list the full history on purpose — these filters exist for+ // callers that want one target's builds.+ const seedBuilderTopics = async () => {+ await serverDB.transaction(async (trx) => {+ await trx+ .insert(agents)+ .values([{ id: 'builder-agent', userId, title: 'Group Agent Builder' }]);+ await trx.insert(chatGroups).values([+ { id: 'grp-a', userId, title: 'Group A' },+ { id: 'grp-b', userId, title: 'Group B' },+ ]);+ await trx.insert(topics).values([+ {+ id: 'builder-topic-a',+ userId,+ agentId: 'builder-agent',+ metadata: { editingGroupId: 'grp-a' },+ updatedAt: new Date('2023-01-01'),+ },+ {+ id: 'builder-topic-b',+ userId,+ agentId: 'builder-agent',+ metadata: { editingGroupId: 'grp-b' },+ updatedAt: new Date('2023-01-02'),+ },+ {+ id: 'builder-topic-legacy',+ userId,+ agentId: 'builder-agent',+ updatedAt: new Date('2023-01-03'),+ },+ ]);+ });+ };++ it('should only return builder topics belonging to the edited group', async () => {+ await seedBuilderTopics();++ const result = await topicModel.query({+ agentId: 'builder-agent',+ editingGroupId: 'grp-a',+ });++ expect(result.items.map((item) => item.id)).toEqual(['builder-topic-a']);+ expect(result.total).toBe(1);+ });++ it('should exclude legacy builder topics that carry no editingGroupId', async () => {+ await seedBuilderTopics();++ const result = await topicModel.query({+ agentId: 'builder-agent',+ editingGroupId: 'grp-b',+ });++ expect(result.items.map((item) => item.id)).toEqual(['builder-topic-b']);+ });++ // The builder panel relies on this: its history list is deliberately+ // unfiltered, so the default query must keep returning every build.+ it('should return every builder topic when no editing target is given', async () => {+ await seedBuilderTopics();++ const result = await topicModel.query({ agentId: 'builder-agent' });++ expect(result.items).toHaveLength(3);+ });++ it('should filter agent-builder topics by the agent they configured', async () => {+ await serverDB.transaction(async (trx) => {+ await trx.insert(agents).values([+ { id: 'agent-builder-agent', userId, title: 'Agent Builder' },+ { id: 'edited-agent-a', userId, title: 'Edited A' },+ { id: 'edited-agent-b', userId, title: 'Edited B' },+ ]);+ await trx.insert(topics).values([+ {+ id: 'agent-build-a',+ userId,+ agentId: 'agent-builder-agent',+ metadata: { editingAgentId: 'edited-agent-a' },+ updatedAt: new Date('2023-01-01'),+ },+ {+ id: 'agent-build-b',+ userId,+ agentId: 'agent-builder-agent',+ metadata: { editingAgentId: 'edited-agent-b' },+ updatedAt: new Date('2023-01-02'),+ },+ ]);+ });++ const result = await topicModel.query({+ agentId: 'agent-builder-agent',+ editingAgentId: 'edited-agent-a',+ });++ expect(result.items.map((item) => item.id)).toEqual(['agent-build-a']);+ });+ });+describe('query with withDetails option', () => {const seedTopicWithMessages = async (topicId: string,diff --git a/packages/database/src/models/topic.ts b/packages/database/src/models/topic.tsindex a4c3ef80041..ac73fdeca5f 100644--- a/packages/database/src/models/topic.ts+++ b/packages/database/src/models/topic.ts@@ -105,6 +105,19 @@ interface QueryTopicParams {*/containerId?: string | null;current?: number;+ /**+ * Restrict an `agentId` query to the builder conversations that configured+ * one specific target (`metadata.editingAgentId` / `metadata.editingGroupId`).+ *+ * Builder panels run on a single builtin agent shared by every target, whose+ * topics deliberately carry no `groupId` / `sessionId` — those columns mark a+ * topic as part of the target's own chat read path. The builder panel itself+ * shows the unfiltered history on purpose; these exist so a caller that wants+ * one target's builds can ask for them. Only meaningful alongside `agentId`;+ * ignored by the group / container branches.+ */+ editingAgentId?: string | null;+ editingGroupId?: string | null;/*** Exclude topics by status (e.g. ['completed'])*/@@ -277,6 +290,8 @@ export class TopicModel {agentId,containerId,current = 0,+ editingAgentId,+ editingGroupId,excludeStatuses,excludeTriggers,includeTriggers,@@ -365,6 +380,14 @@ export class TopicModel {not(inArray(topics.status, excludeStatuses as ChatTopicStatus[])),): undefined;+ // Topics created before the marker existed carry neither key and therefore+ // match no target — they cannot: what they configured was never recorded+ // anywhere in the row. `topics_agent_id_idx` still drives the scan, so the+ // unindexed JSONB comparison only runs over one agent's rows.+ const editingTargetCondition = and(+ editingAgentId ? sql`${topics.metadata}->>'editingAgentId' = ${editingAgentId}` : undefined,+ editingGroupId ? sql`${topics.metadata}->>'editingGroupId' = ${editingGroupId}` : undefined,+ );// If groupId is provided, query topics by groupId directlyif (groupId) {@@ -450,6 +473,7 @@ export class TopicModel {const agentWhere = and(this.ownership(),agentCondition,+ editingTargetCondition,includeTriggerCondition,excludeTriggerCondition,triggerCondition,diff --git a/packages/database/src/schemas/resourcePermission.ts b/packages/database/src/schemas/resourcePermission.tsindex beb312d4ce2..712490b6b19 100644--- a/packages/database/src/schemas/resourcePermission.ts+++ b/packages/database/src/schemas/resourcePermission.ts@@ -32,9 +32,21 @@ export const RESOURCE_ACCESS_LEVELS_BY_TYPE = {document: ['view', 'edit'],} as const satisfies Record<PermissionResourceType, readonly ResourceAccessLevel[]>;+/**+ * What a public resource grants the workspace when nobody has said otherwise.+ *+ * Agents and Agent Groups default to `edit`: a workspace is a collaborative+ * space, and the same default has to hold for both — a group whose members+ * could only *use* it while the agents inside it were editable (or vice versa)+ * reads as a bug, not as a policy. Documents stay `view`, which is the Notion-+ * style expectation for a written page.+ *+ * Lowering a resource is one control away (the Permission page), and the+ * creator / workspace owners are unaffected either way.+ */export const DEFAULT_RESOURCE_ACCESS_LEVELS = {- agent: 'use',- agentGroup: 'use',+ agent: 'edit',+ agentGroup: 'edit',document: 'view',} as const satisfies Record<PermissionResourceType, ResourceAccessLevel>;@@ -42,6 +54,25 @@ export const getDefaultResourceAccessLevel = (resourceType: PermissionResourceType,): ResourceAccessLevel => DEFAULT_RESOURCE_ACCESS_LEVELS[resourceType];+/**+ * What the released clients' two-valued `viewer` / `editor` role maps onto.+ *+ * Deliberately not `DEFAULT_RESOURCE_ACCESS_LEVELS`: those two happened to be+ * the same value once, but they answer different questions — "nobody chose"+ * versus "the caller chose the non-editor option". Now that the Agent / Group+ * default is `edit`, resolving `viewer` through the default would hand edit+ * access to a client that explicitly asked for less.+ */+export const LEGACY_VIEWER_ACCESS_LEVELS = {+ agent: 'use',+ agentGroup: 'use',+ document: 'view',+} as const satisfies Record<PermissionResourceType, ResourceAccessLevel>;++export const getLegacyViewerAccessLevel = (+ resourceType: PermissionResourceType,+): ResourceAccessLevel => LEGACY_VIEWER_ACCESS_LEVELS[resourceType];+export const isResourceAccessLevelAllowed = (resourceType: PermissionResourceType,accessLevel: ResourceAccessLevel,@@ -55,9 +86,9 @@ export const isResourceAccessLevelAllowed = (** The current phase intentionally has exactly one possible subject: the* resource's workspace. New or newly-published resources store an explicit- * row. Public resources without a row resolve to the resource-specific safe- * default (`use` for Agent/Group, `view` for Document), avoiding a production- * backfill while keeping the rollout non-editable by default.+ * row. Public resources without a row resolve to the resource-specific default+ * (`edit` for Agent/Group, `view` for Document), so no production backfill is+ * needed to keep legacy rows consistent with newly created ones.** Visibility itself stays on the resources' own `visibility` column; this* table only grades what visible workspace members may do. Private resourcesdiff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.tsindex be12401b7af..73dbfd46dcc 100644--- a/packages/locales/src/default/setting.ts+++ b/packages/locales/src/default/setting.ts@@ -260,6 +260,27 @@ export default {'permission.page.entry': 'Member Permissions','permission.page.generalAccessDesc':'What every workspace member can do with this agent. The creator and workspace owners always keep full access.',+ 'permission.page.groupAccessLevelPrivateHint':+ 'Members get this level once the group is published to the workspace. It can be changed after publishing.',+ 'permission.page.groupDevicePolicyDesc':+ 'Whether members can switch the execution environment for their own runs in this group.',+ 'permission.page.groupDevicePolicyFixedDesc':+ 'Members can only use the environment you set for this group',+ 'permission.page.groupDevicePolicyMemberDesc': 'Members can set their own execution environment',+ 'permission.page.groupDevicePolicyUnset':+ 'Pick an execution environment for the orchestrator first, then you can fix it here.',+ 'permission.page.groupGeneralAccessDesc':+ 'What every workspace member can do with this group. The same level is applied to the member agents the group owns. The creator and workspace owners always keep full access.',+ 'permission.page.groupPersonalDesc':+ 'This group only belongs to you, so there is nothing to share yet. Publish it to a workspace to set member permissions.',+ 'permission.page.groupPersonalTitle': 'Permissions apply to workspace groups',+ 'permission.page.groupPrivateNotice':+ 'This group is still private. Everything here takes effect once you publish it to the workspace.',+ 'permission.page.groupModelPolicyDesc':+ 'Whether members can switch the model for their own conversations in this group.',+ 'permission.page.groupModelPolicyFixedDesc':+ 'Members can only use the model you set for this group',+ 'permission.page.groupModelPolicyMemberDesc': 'Members can use a model they set themselves','permission.page.memberGroup': 'Access','permission.page.modelPolicyFixedDesc': 'Members can only use the model you set','permission.page.modelPolicyMemberDesc': 'Members can use a model they set themselves',diff --git a/packages/types/src/agent/modelSelection.test.ts b/packages/types/src/agent/modelSelection.test.tsindex 7c048d3b824..f0b9a3eba45 100644--- a/packages/types/src/agent/modelSelection.test.ts+++ b/packages/types/src/agent/modelSelection.test.ts@@ -32,6 +32,16 @@ describe('resolveAgentModelSelectionPolicy', () => {}),).toBe('fixed');});++ it('forces member selection on a personal-selection Agent', () => {+ expect(+ resolveAgentModelSelectionPolicy({+ ...workspaceShared,+ agencyConfig: { modelSelectionPolicy: 'fixed' },+ personalModelSelection: true,+ }),+ ).toBe('member');+ });});describe('resolveAgentModelConfig', () => {@@ -75,6 +85,19 @@ describe('resolveAgentModelConfig', () => {).toEqual({ model: 'shared-model', provider: 'shared-provider' });});+ it('applies the member override on a personal-selection Agent even for an admin', () => {+ expect(+ resolveAgentModelConfig(+ {+ ...workspaceShared,+ canManage: true,+ personalModelSelection: true,+ },+ { model: 'member-model', provider: 'member-provider' },+ ),+ ).toEqual({ model: 'member-model', provider: 'member-provider' });+ });+it('ignores the member override while the workspace Agent is private', () => {expect(resolveAgentModelConfig(diff --git a/packages/types/src/agent/modelSelection.ts b/packages/types/src/agent/modelSelection.tsindex 82524efcd87..4311143309a 100644--- a/packages/types/src/agent/modelSelection.ts+++ b/packages/types/src/agent/modelSelection.ts@@ -11,6 +11,19 @@ export interface AgentModelConfig {/** Author/admin callers use the shared model and ignore member overrides. */canManage?: boolean;model: string;+ /**+ * The Agent's model is a personal choice for *every* member, including the+ * row's creator and Workspace admins — `canManage` does not promote anyone to+ * editing a shared default, and an author-set `fixed` policy cannot lock it.+ *+ * Set for collaborative builtin Agents (Agent Builder, Group Agent Builder,+ * inbox, Page Copilot). Those rows are shared Workspace infrastructure+ * provisioned lazily by whichever member opened the feature first, so+ * `agents.user_id` records an accident of timing rather than authorship —+ * letting it decide a shared model means one member's pick silently becomes+ * everyone else's, with no settings page to change it back.+ */+ personalModelSelection?: boolean;provider?: string;visibility?: 'private' | 'public';workspaceId?: string | null;@@ -24,12 +37,17 @@ export interface AgentModelConfig {* the shared model and an explicit `fixed` policy always remains authoritative.*/export const resolveAgentModelSelectionPolicy = (- shared: Pick<AgentModelConfig, 'agencyConfig' | 'visibility' | 'workspaceId'>,+ shared: Pick<+ AgentModelConfig,+ 'agencyConfig' | 'personalModelSelection' | 'visibility' | 'workspaceId'+ >,): AgentModelSelectionPolicy => {const isPublicWorkspaceAgent = !!shared.workspaceId && shared.visibility !== 'private';if (!isPublicWorkspaceAgent) return 'fixed';+ if (shared.personalModelSelection) return 'member';+return shared.agencyConfig?.modelSelectionPolicy ?? 'member';};@@ -49,8 +67,12 @@ export const resolveAgentModelConfig = (memberOverride?: AgentModelOverride | null,explicitOverride?: Partial<AgentModelOverride> | null,): Pick<AgentModelConfig, 'model' | 'provider'> => {+ // `personalModelSelection` outranks `canManage`: on those rows there is no+ // "shared default" to manage, so an admin reads their own choice like anyone+ // else (see the field doc).+ const readsMemberOverride = shared.personalModelSelection === true || shared.canManage !== true;const effectiveMemberOverride =- shared.canManage !== true && resolveAgentModelSelectionPolicy(shared) === 'member'+ readsMemberOverride && resolveAgentModelSelectionPolicy(shared) === 'member'? memberOverride: undefined;diff --git a/packages/types/src/agentExecution/index.ts b/packages/types/src/agentExecution/index.tsindex ff7fc7fd71c..97fe0cc7cb8 100644--- a/packages/types/src/agentExecution/index.ts+++ b/packages/types/src/agentExecution/index.ts@@ -85,6 +85,18 @@ export interface ExecAgentAppContext {* itself.*/editingAgentId?: string;+ /**+ * When scope is 'group_agent_builder', the ID of the group being edited (the+ * group whose Profile page the user opened the builder panel on).+ *+ * Deliberately NOT `groupId`: that field marks the run as a *group chat* turn+ * and gets stamped onto the created topic and messages, which would pull the+ * builder's private side-conversation into the group's message read path+ * (`MessageModel.query` filters group chats by `messages.groupId`). The+ * builder conversation stays owned by the builtin builder agent; only the+ * group-agent-builder tool runtime and its context injector read this field.+ */+ editingGroupId?: string;/** Group ID for group chat */groupId?: string | null;/**diff --git a/packages/types/src/conversation.ts b/packages/types/src/conversation.tsindex 8c8c6b25fe6..b4a45735aab 100644--- a/packages/types/src/conversation.ts+++ b/packages/types/src/conversation.ts@@ -139,6 +139,17 @@ export interface ConversationContext {* other agent resources tied to the same topic.*/documentId?: string;+ /**+ * Group being configured by the Group Agent Builder panel (`group_agent_builder`+ * scope).+ *+ * Deliberately separate from {@link groupId}: that field marks the run as a+ * group *chat* turn and gets stamped onto the created topic and messages,+ * which would drag the builder's side-conversation into the group's own+ * message read path. This one only scopes the builder's own buckets and topic+ * list, and travels to the server as `ExecAgentAppContext.editingGroupId`.+ */+ editingGroupId?: string;/*** Group ID for group conversations* Used when scope is 'group' or 'group_agent'diff --git a/packages/types/src/topic/topic.ts b/packages/types/src/topic/topic.tsindex 8529e66b563..2587ba392ea 100644--- a/packages/types/src/topic/topic.ts+++ b/packages/types/src/topic/topic.ts@@ -121,6 +121,28 @@ export interface ChatTopicMetadata {bot?: ChatTopicBotContext;boundDeviceId?: string;cronJobId?: string;+ /**+ * The agent whose Profile page this Agent Builder conversation was started+ * from (mirrors `ExecAgentAppContext.editingAgentId`).+ *+ * Recorded for the same reason as {@link editingGroupId} — see there.+ */+ editingAgentId?: string;+ /**+ * The group whose Profile page this Group Agent Builder conversation was+ * started from (mirrors `ExecAgentAppContext.editingGroupId`).+ *+ * Builder panels run on one builtin agent shared by every target, and their+ * topics carry no `groupId` / `sessionId` on purpose — those columns would+ * pull the builder's side-conversation into the target's own chat read path.+ * So nothing else in the row records what the conversation was configuring.+ *+ * Showing the builder's full build history in one list is intentional, so+ * nothing filters on this today. It is captured because it can only be+ * captured now: the association exists solely at run time, and a topic+ * written without it can never be attributed afterwards.+ */+ editingGroupId?: string;/*** Scoped pointer to the currently active assistant message for a running* heterogeneous agent operation. Includes `operationId` so cold-start@@ -599,6 +621,12 @@ export interface CreateTopicParams {export interface QueryTopicParams {agentId?: string | null;current?: number;+ /**+ * Scope an `agentId` query to the builder conversations that configured one+ * target — see `ChatTopicMetadata.editingGroupId`. Ignored without `agentId`.+ */+ editingAgentId?: string | null;+ editingGroupId?: string | null;/*** Exclude topics by status (e.g. ['completed'])*/diff --git a/src/business/client/hooks/useRenderBusinessChatErrorMessageExtra.tsx b/src/business/client/hooks/useRenderBusinessChatErrorMessageExtra.tsxindex 650202fe0e5..ba15d865730 100644--- a/src/business/client/hooks/useRenderBusinessChatErrorMessageExtra.tsx+++ b/src/business/client/hooks/useRenderBusinessChatErrorMessageExtra.tsx@@ -1,8 +1,19 @@import { type ChatMessageError } from '@lobechat/types';+interface BusinessChatErrorMessageExtraOptions {+ /**+ * Retry for the failed turn, resolved by the render surface. Business cards+ * must use it instead of deriving a retry from `messageId`: on the group+ * surface (a multi-step run) `messageId` is a nested content block, which the+ * message-level store actions cannot resolve.+ */+ onRetry?: () => void;+}+export default function useRenderBusinessChatErrorMessageExtra(_error: ChatMessageError | null | undefined,_messageId: string,+ _options?: BusinessChatErrorMessageExtraOptions,) {return null;}diff --git a/src/features/AgentBuilder/TopicSelector.tsx b/src/features/AgentBuilder/TopicSelector.tsxindex 9c87c3f6643..4a994951d76 100644--- a/src/features/AgentBuilder/TopicSelector.tsx+++ b/src/features/AgentBuilder/TopicSelector.tsx@@ -86,8 +86,13 @@ const TopicSelector = memo<TopicSelectorProps>(({ agentId, disabled }) => {return (<NavHeadershowTogglePanelButton={false}+ styles={{ right: { flex: 'none' } }}left={- activeTopic?.title ? <span className={styles.title}>{activeTopic.title}</span> : undefined+ activeTopic?.title ? (+ <span className={styles.title} title={activeTopic.title}>+ {activeTopic.title}+ </span>+ ) : undefined}right={<>@@ -108,7 +113,11 @@ const TopicSelector = memo<TopicSelectorProps>(({ agentId, disabled }) => {popupProps={{ style: { maxHeight: 400, minWidth: 280, overflowY: 'auto' } }}triggerProps={{ disabled: disabled || isEmpty }}>- <ActionIcon disabled={disabled || isEmpty} icon={Clock3Icon} />+ <ActionIcon+ disabled={disabled || isEmpty}+ icon={Clock3Icon}+ size={DESKTOP_HEADER_ICON_SMALL_SIZE}+ /></DropdownMenu></>}diff --git a/src/features/AgentPermission/PermissionForm.tsx b/src/features/AgentPermission/PermissionForm.tsxindex 7468a6b98fe..28167152ccf 100644--- a/src/features/AgentPermission/PermissionForm.tsx+++ b/src/features/AgentPermission/PermissionForm.tsx@@ -4,25 +4,16 @@ import type { AgentModelSelectionPolicy } from '@lobechat/types';import type { FormGroupItemType } from '@lobehub/ui';import { Alert, Empty, Form, Icon } from '@lobehub/ui';import { createStaticStyles } from 'antd-style';-import {- Bot,- EyeIcon,- InfoIcon,- LockIcon,- MonitorSmartphone,- PencilIcon,- PlayIcon,- UsersIcon,-} from 'lucide-react';+import { Bot, InfoIcon, LockIcon, MonitorSmartphone, UsersIcon } from 'lucide-react';import { memo, useMemo } from 'react';import { useTranslation } from 'react-i18next';import AsyncError from '@/components/AsyncError';import { FORM_STYLE } from '@/const/layoutTokens';-import type { ResourceAccessLevel } from '@/services/resourcePermission';+import PolicySelect, { type PolicyOption } from '@/features/ResourcePermission/PolicySelect';+import { getSelectionPolicyLabelKeys } from '@/features/ResourcePermission/selectionPolicyLabels';+import { useAccessLevelOptions } from '@/features/ResourcePermission/useAccessLevelOptions';-import PolicySelect, { type PolicyOption } from './PolicySelect';-import { getSelectionPolicyLabelKeys } from './selectionPolicyLabels';import { useAgentPermission } from './useAgentPermission';const styles = createStaticStyles(({ css }) => ({@@ -82,42 +73,7 @@ const PermissionForm = memo<PermissionFormProps>(({ agentId }) => {[labelKeys, t],);- const accessOptions = useMemo((): PolicyOption<ResourceAccessLevel>[] => {- // A private agent has no members yet, so the level names carry the same- // "once shared" tense the switch policies already use; the descriptions- // explain what the level itself means and stay as they are.- const options: PolicyOption<ResourceAccessLevel>[] = [- {- desc: t('permission.generalAccess.editableDesc'),- icon: PencilIcon,- label: t(- isPrivate ? 'permission.page.editableWhenShared' : 'permission.generalAccess.editable',- ),- value: 'edit',- },- {- desc: t('permission.generalAccess.usableDesc'),- icon: PlayIcon,- label: t(- isPrivate ? 'permission.page.usableWhenShared' : 'permission.generalAccess.usable',- ),- value: 'use',- },- ];-- // `view` is a document-only level, but a legacy row can still carry it —- // list it so the control shows the real current value instead of blank.- if (accessLevel === 'view') {- options.push({- desc: t('permission.generalAccess.viewableDesc'),- icon: EyeIcon,- label: t('permission.generalAccess.viewable'),- value: 'view',- });- }-- return options;- }, [accessLevel, isPrivate, t]);+ const accessOptions = useAccessLevelOptions({ accessLevel, isPrivate });const executionPolicyOptions = useMemo((): PolicyOption<AgentModelSelectionPolicy>[] => [diff --git a/src/features/AgentPermission/useAgentPermission.ts b/src/features/AgentPermission/useAgentPermission.tsindex 27edf76f792..3e0cbe3bdca 100644--- a/src/features/AgentPermission/useAgentPermission.ts+++ b/src/features/AgentPermission/useAgentPermission.ts@@ -1,15 +1,9 @@'use client';-import type { AgentModelSelectionPolicy, LobeAgentAgencyConfig } from '@lobechat/types';-import { useCallback, useMemo } from 'react';+import type { AgentModelSelectionPolicy } from '@lobechat/types';-import { useDeviceList } from '@/features/DeviceManager/useDeviceList';-import {- groupExecutionTargetDevices,- resolveExecutionTargetSelection,-} from '@/features/ExecutionTargetPicker';+import { useAgentSelectionPolicies } from '@/features/ResourcePermission/useAgentSelectionPolicies';import { useResourcePermission } from '@/features/ResourcePermission/useResourcePermission';-import { isHeterogeneousSandboxExecutionAvailable } from '@/helpers/executionTarget';import { usePermission } from '@/hooks/usePermission';import type { ResourceAccessLevel } from '@/services/resourcePermission';import { useAgentStore } from '@/store/agent';@@ -36,20 +30,16 @@ export interface AgentPermissionState {}/**- * View model of the Agent Permission page.+ * View model of the Agent Permission page: the member access level plus the+ * agent's own Editable settings (shared with the Agent Group page through+ * {@link useAgentSelectionPolicies}).*- * The stored policy is read directly rather than through- * `resolveAgentModelSelectionPolicy`: that resolver answers "what happens at- * run time", which collapses to `fixed` for a private agent — so a control- * driven by it would look stuck on an agent whose author is configuring the- * rules ahead of sharing. Here the author's *intent* is what's edited — which- * is also why a private agent still shows every control: all of them are the- * same promise about what happens once it reaches the workspace.+ * A private agent still shows every control: all of them are the same promise+ * about what happens once it reaches the workspace.*/export const useAgentPermission = (agentId: string): AgentPermissionState => {const { allowed: canEditContent } = usePermission('edit_own_content');const agent = useAgentStore(agentByIdSelectors.getAgentById(agentId));- const updateAgentConfigById = useAgentStore((s) => s.updateAgentConfigById);const isWorkspaceAgent = !!agent?.workspaceId;const isPrivate = agent?.visibility === 'private';@@ -59,74 +49,24 @@ export const useAgentPermission = (agentId: string): AgentPermissionState => {error: accessError,isLoading: accessLoading,mutate: retryAccess,- setAccessLevel,// Settable while private too: the server stores the level and the publish// paths read it back, so it is the same configure-ahead-of-sharing promise// the policies below make.+ setAccessLevel,} = useResourcePermission('agent', isWorkspaceAgent ? agentId : undefined);- const { data: devices } = useDeviceList();- const publicWorkspaceDevices = useMemo(- () => groupExecutionTargetDevices(devices).publicWorkspace,- [devices],- );-- const agencyConfig = agent?.agencyConfig;- const heterogeneousType = agencyConfig?.heterogeneousProvider?.type;- const executionSelection = resolveExecutionTargetSelection({- boundDeviceId: agencyConfig?.boundDeviceId,- configuredTarget: agencyConfig?.executionTarget,- devices: publicWorkspaceDevices,- isHeterogeneous: !!heterogeneousType,- });-- const saveAgencyConfig = useCallback(- (patch: Partial<LobeAgentAgencyConfig>) =>- updateAgentConfigById(agentId, { agencyConfig: patch }),- [agentId, updateAgentConfigById],- );-- const setExecutionTargetPolicy = useCallback(- (policy: AgentModelSelectionPolicy) => {- if (policy === 'member') {- void saveAgencyConfig({ executionTargetSelectionPolicy: 'member' });- return;- }- // Fixing pins whatever is selected right now, so a run can't fall back to- // a target the author never chose.- if (!executionSelection) return;-- void saveAgencyConfig({- ...(executionSelection.deviceId ? { boundDeviceId: executionSelection.deviceId } : {}),- executionTarget: executionSelection.target,- executionTargetSelectionPolicy: 'fixed',- });- },- [executionSelection, saveAgencyConfig],- );-- const setModelPolicy = useCallback(- (policy: AgentModelSelectionPolicy) => void saveAgencyConfig({ modelSelectionPolicy: policy }),- [saveAgencyConfig],- );+ const policies = useAgentSelectionPolicies(agentId);return {+ ...policies,accessError,accessLevel: access?.accessLevel,accessLoading,canEditConfig: canEditContent,- canFixExecutionTarget:- !!executionSelection &&- (executionSelection.target !== 'sandbox' ||- isHeterogeneousSandboxExecutionAvailable(heterogeneousType)),canManageAccess: access?.canManage === true,- executionTargetPolicy: agencyConfig?.executionTargetSelectionPolicy ?? 'member',isPrivate,isWorkspaceAgent,- modelPolicy: agencyConfig?.modelSelectionPolicy ?? 'member',retryAccess: () => void retryAccess(),setAccessLevel: (level) => void setAccessLevel(level),- setExecutionTargetPolicy,- setModelPolicy,};};diff --git a/src/features/ChatInput/hooks/useAgentModelSelection.test.ts b/src/features/ChatInput/hooks/useAgentModelSelection.test.tsindex 9782ea0cceb..b96d5fc49d2 100644--- a/src/features/ChatInput/hooks/useAgentModelSelection.test.ts+++ b/src/features/ChatInput/hooks/useAgentModelSelection.test.ts@@ -19,7 +19,12 @@ const testState = vi.hoisted(() => ({agent: {agencyConfig: undefined as { modelSelectionPolicy?: 'fixed' | 'member' } | undefined,agentMap: {- 'agent-1': {} as { visibility?: 'private' | 'public'; workspaceId?: string },+ 'agent-1': {} as {+ slug?: string;+ virtual?: boolean;+ visibility?: 'private' | 'public';+ workspaceId?: string;+ },},model: 'shared-model',provider: 'shared-provider',@@ -147,6 +152,42 @@ describe('useAgentModelSelection', () => {expect(testState.agent.updateAgentConfigById).not.toHaveBeenCalled();});+ it('keeps the model personal on a collaborative builtin Agent even for an admin', async () => {+ // Admin of the workspace: canManage is true, yet the Agent Builder row is+ // shared infrastructure, so the pick must stay this member's own.+ testState.access.canManageAgent = true;+ testState.resource.canConfigureResource = true;+ testState.agent.agentMap['agent-1'] = {+ slug: 'group-agent-builder',+ virtual: true,+ visibility: 'public',+ workspaceId: 'workspace-1',+ };+ testState.user.workspaceUserPreference = {+ agentModelOverrides: {+ 'agent-1': { model: 'member-model', provider: 'member-provider' },+ },+ };+ const { result } = renderHook(() => useAgentModelSelection('agent-1'));++ await result.current.selectModel({ model: 'next-model', provider: 'next-provider' });++ expect(result.current).toMatchObject({+ canDisplayModel: true,+ canSelectModel: true,+ model: 'member-model',+ provider: 'member-provider',+ selectionPolicy: 'member',+ usesWorkspaceMemberSelection: true,+ });+ expect(testState.user.updateWorkspaceUserPreference).toHaveBeenCalledWith({+ agentModelOverrides: {+ 'agent-1': { model: 'next-model', provider: 'next-provider' },+ },+ });+ expect(testState.agent.updateAgentConfigById).not.toHaveBeenCalled();+ });+it('keeps an explicit fixed policy locked for a public Workspace Agent', async () => {testState.access.canManageAgent = false;testState.resource.canConfigureResource = false;diff --git a/src/features/ChatInput/hooks/useAgentModelSelection.ts b/src/features/ChatInput/hooks/useAgentModelSelection.tsindex 544724ddeca..29b53ff1a08 100644--- a/src/features/ChatInput/hooks/useAgentModelSelection.ts+++ b/src/features/ChatInput/hooks/useAgentModelSelection.ts@@ -1,5 +1,6 @@'use client';+import { isCollaborativeBuiltinAgentRow } from '@lobechat/builtin-agents';import type { AgentModelSelectionPolicy } from '@lobechat/types';import { resolveAgentModelConfig, resolveAgentModelSelectionPolicy } from '@lobechat/types';import { useCallback } from 'react';@@ -61,8 +62,15 @@ export const useAgentModelSelection = (agentId: string): UseAgentModelSelectionRconst sharedProvider = useAgentStore(agentByIdSelectors.getAgentModelProviderById(agentId));const updateAgentConfigById = useAgentStore((s) => s.updateAgentConfigById);const { canManageAgent, isAccessLoading } = useAgentManagementAccess(agentId);+ // Collaborative builtins (the builders, Lobe AI, the Page Copilot) are one+ // shared row per Workspace with no config page of their own, so managing the+ // row must not mean picking the model for everyone else — see+ // `AgentModelConfig.personalModelSelection`.+ const personalModelSelection = isCollaborativeBuiltinAgentRow(agent ?? {});const usesWorkspaceMemberSelection =- !!agent?.workspaceId && agent.visibility !== 'private' && !canManageAgent;+ !!agent?.workspaceId &&+ agent.visibility !== 'private' &&+ (personalModelSelection || !canManageAgent);const updateWorkspaceUserPreference = useUserStore((s) => s.updateWorkspaceUserPreference);const storePreference = useUserStore((s) => s.workspaceUserPreference);@@ -76,6 +84,7 @@ export const useAgentModelSelection = (agentId: string): UseAgentModelSelectionRconst sharedModelConfig = {agencyConfig: sharedAgencyConfig,model: sharedModel,+ personalModelSelection,provider: sharedProvider,visibility: agent?.visibility,workspaceId: agent?.workspaceId,diff --git a/src/features/Conversation/Error/QuotaLimitError.tsx b/src/features/Conversation/Error/QuotaLimitError.tsxindex e3cd8f64efa..a0ed64ad338 100644--- a/src/features/Conversation/Error/QuotaLimitError.tsx+++ b/src/features/Conversation/Error/QuotaLimitError.tsx@@ -10,9 +10,15 @@ import { useRetryParentMessage } from './useRetryParentMessage';interface QuotaLimitErrorProps {id: string;+ /**+ * Retry resolved by the render surface. Preferred over the parent-message+ * fallback because on the group surface `id` is a nested content block, whose+ * parent is another block rather than the user message.+ */+ onRetry?: () => void;}-const QuotaLimitError = memo<QuotaLimitErrorProps>(({ id }) => {+const QuotaLimitError = memo<QuotaLimitErrorProps>(({ id, onRetry }) => {const { t } = useTranslation('error');const { disabled, loading, retryParentMessage } = useRetryParentMessage(id);@@ -22,12 +28,12 @@ const QuotaLimitError = memo<QuotaLimitErrorProps>(({ id }) => {title={t('response.QuotaLimitReachedCloud')}action={<Button- disabled={disabled}+ disabled={onRetry ? false : disabled}icon={<Icon icon={RotateCw} />}loading={loading}size={'small'}type={'primary'}- onClick={() => retryParentMessage()}+ onClick={() => (onRetry ? onRetry() : retryParentMessage())}>{t('unknownError.retry')}</Button>diff --git a/src/features/Conversation/Error/index.test.tsx b/src/features/Conversation/Error/index.test.tsxindex be6f0fde89b..2199b964bd3 100644--- a/src/features/Conversation/Error/index.test.tsx+++ b/src/features/Conversation/Error/index.test.tsx@@ -21,6 +21,8 @@ const delAndRegenerateMessageMock = vi.hoisted(() => vi.fn());// displayMessage hanging off a user turn — the condition that decides whether a// self-contained retry can actually do anything.const displayMessageMock = vi.hoisted(() => new Map<string, { parentId?: string }>());+// Stands in for whatever card a downstream build installs into the business slot.+const businessSlot = vi.hoisted(() => ({ render: false }));const missingTranslationKeys = vi.hoisted(() => new Set<string>());const businessErrorContentMock = vi.hoisted(() =>vi.fn(() => ({@@ -96,7 +98,10 @@ vi.mock('@/business/client/hooks/useBusinessErrorContent', () => ({}));vi.mock('@/business/client/hooks/useRenderBusinessChatErrorMessageExtra', () => ({- default: () => undefined,+ default: (_error: unknown, _messageId: string, options?: { onRetry?: () => void }) =>+ businessSlot.render ? (+ <button onClick={() => options?.onRetry?.()}>business-retry</button>+ ) : undefined,}));vi.mock('@/features/Conversation/ChatItem/components/ErrorContent', () => ({@@ -185,6 +190,7 @@ describe('ErrorMessageExtra', () => {beforeEach(() => {dynamicComponentPropsMock.mockClear();missingTranslationKeys.clear();+ businessSlot.render = false;serverConfigMock.enableBusinessFeatures = false;businessErrorContentMock.mockReturnValue({errorType: undefined,@@ -344,6 +350,32 @@ describe('ErrorMessageExtra', () => {expect(onRegenerate).toHaveBeenCalledTimes(1);});+ it('hands the group retry to the business card so a multi-step run can resume', () => {+ serverConfigMock.enableBusinessFeatures = true;+ businessSlot.render = true;+ const onRegenerate = vi.fn();++ render(+ <ErrorMessageExtra+ error={{ message: 'response.InsufficientBudgetForModel' }}+ retryScopeId="group-parent"+ data={{+ error: {+ type: ChatErrorType.InsufficientBudgetForModel,+ } as any,+ // A nested content block of an assistantGroup — not a top-level+ // display message, so the card cannot resolve a retry from it.+ id: 'group-child-step-14',+ }}+ onRegenerate={onRegenerate}+ />,+ );++ fireEvent.click(screen.getByRole('button', { name: 'business-retry' }));++ expect(onRegenerate).toHaveBeenCalledTimes(1);+ });+it('shows the trace-id report UI for fallback provider errors', () => {serverConfigMock.enableBusinessFeatures = true;diff --git a/src/features/Conversation/Error/index.tsx b/src/features/Conversation/Error/index.tsxindex 8d77391abca..8076ab8f7c5 100644--- a/src/features/Conversation/Error/index.tsx+++ b/src/features/Conversation/Error/index.tsx@@ -274,7 +274,6 @@ const ErrorMessageExtra = memo<ErrorExtraProps>(({ error: alertError, data, onRegenerate, retryScopeId }) => {const error = data.error;const navigate = useWorkspaceAwareNavigate();- const businessChatErrorMessageExtra = useRenderBusinessChatErrorMessageExtra(error, data.id);const enableBusinessFeatures = useServerConfigStore(serverConfigSelectors.enableBusinessFeatures,);@@ -333,6 +332,13 @@ const ErrorMessageExtra = memo<ErrorExtraProps>(handleRetryAgentMessage();}, [handleRetryAgentMessage, resetHeteroOverloadRetry, resolvedScopeId]);+ // Business cards get the surface-resolved retry rather than deriving one+ // from `data.id`: on the group surface that id is a nested content block,+ // so message-level store actions can't resolve it and silently no-op.+ const businessChatErrorMessageExtra = useRenderBusinessChatErrorMessageExtra(error, data.id, {+ onRetry: canRetry ? handleManualRetry : undefined,+ });+const autoRetry = useHeterogeneousAutoRetry({// Must be an actual heterogeneous-agent (CC / Codex) overloaded error —// not just any ChatMessageError whose body happens to carry@@ -441,7 +447,10 @@ const ErrorMessageExtra = memo<ErrorExtraProps>(case AgentRuntimeErrorType.QuotaLimitReached:case AgentRuntimeErrorType.RateLimitExceeded: {- if (enableBusinessFeatures) return <QuotaLimitError id={data.id} />;+ if (enableBusinessFeatures)+ return (+ <QuotaLimitError id={data.id} onRetry={canRetry ? handleManualRetry : undefined} />+ );break;}diff --git a/src/features/Conversation/store/utils/effectiveModel.test.ts b/src/features/Conversation/store/utils/effectiveModel.test.tsindex 247738b0667..b95d3744b98 100644--- a/src/features/Conversation/store/utils/effectiveModel.test.ts+++ b/src/features/Conversation/store/utils/effectiveModel.test.ts@@ -78,6 +78,32 @@ describe('getEffectiveConversationModel', () => {expect(getEffectiveConversationModel({ agentId: AGENT_ID })).toBe('claude-opus-5');});+ it('applies the member override on a collaborative builtin the caller created', () => {+ // The workspace Agent Builder row is provisioned by whichever member opened+ // it first; being that member must not turn their pick into everyone's.+ useAgentStore.setState({+ agentMap: {+ [AGENT_ID]: {+ chatConfig: {},+ model: 'glm-5.2',+ slug: 'group-agent-builder',+ userId: 'user_self',+ virtual: true,+ visibility: 'public',+ workspaceId: 'ws_1',+ },+ },+ } as any);+ useUserStore.setState({+ user: { id: 'user_self' },+ workspaceUserPreference: {+ agentModelOverrides: { [AGENT_ID]: { model: 'claude-opus-5', provider: 'anthropic' } },+ },+ } as any);++ expect(getEffectiveConversationModel({ agentId: AGENT_ID })).toBe('claude-opus-5');+ });+it('falls back to the agent default without a topic', () => {useAgentStore.setState({agentMap: { [AGENT_ID]: { chatConfig: {}, model: 'gpt-5.2' } },diff --git a/src/features/Conversation/store/utils/effectiveModel.ts b/src/features/Conversation/store/utils/effectiveModel.tsindex 46f10ee45e9..d56adceb837 100644--- a/src/features/Conversation/store/utils/effectiveModel.ts+++ b/src/features/Conversation/store/utils/effectiveModel.ts@@ -1,3 +1,4 @@+import { isCollaborativeBuiltinAgentRow } from '@lobechat/builtin-agents';import { resolveAgentModelConfig } from '@lobechat/types';import { getAgentStoreState } from '@/store/agent';@@ -44,8 +45,12 @@ export const getEffectiveConversationModel = (context: {const userState = useUserStore.getState();const currentUserId = userProfileSelectors.userId(userState);const isAuthor = !!currentUserId && agent?.userId === currentUserId;+ // Collaborative builtins have no author to speak of — the row belongs to+ // whoever opened the feature first — so their model stays personal for every+ // member (see `AgentModelConfig.personalModelSelection`).+ const personalModelSelection = isCollaborativeBuiltinAgentRow(agent ?? {});const usesWorkspaceMemberSelection =- !!agent?.workspaceId && agent.visibility !== 'private' && !isAuthor;+ !!agent?.workspaceId && agent.visibility !== 'private' && (personalModelSelection || !isAuthor);const memberOverride = usesWorkspaceMemberSelection? userState.workspaceUserPreference?.agentModelOverrides?.[context.agentId]: undefined;@@ -54,6 +59,7 @@ export const getEffectiveConversationModel = (context: {{...sharedConfig,canManage: isAuthor,+ personalModelSelection,visibility: agent?.visibility,workspaceId: agent?.workspaceId,},diff --git a/src/features/GroupPermission/GroupBreadcrumb.tsx b/src/features/GroupPermission/GroupBreadcrumb.tsxnew file mode 100644index 00000000000..e7c949789c4--- /dev/null+++ b/src/features/GroupPermission/GroupBreadcrumb.tsx@@ -0,0 +1,87 @@+'use client';++import { Icon, Text } from '@lobehub/ui';+import { Breadcrumb as AntBreadcrumb } from 'antd';+import { createStaticStyles } from 'antd-style';+import { ChevronRight } from 'lucide-react';+import { memo, type ReactNode, useMemo } from 'react';+import { useTranslation } from 'react-i18next';+import { Link } from 'react-router';+import urlJoin from 'url-join';++import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';+import { buildWorkspaceAwarePath } from '@/features/Workspace/workspaceAwarePath';+import { useAgentGroupStore } from '@/store/agentGroup';+import { agentGroupSelectors } from '@/store/agentGroup/selectors';++const styles = createStaticStyles(({ css }) => ({+ breadcrumb: css`+ ol {+ align-items: center;+ }++ li,+ .ant-breadcrumb-link,+ .ant-breadcrumb-link > a {+ display: flex;+ align-items: center;+ }+ `,+}));++interface GroupBreadcrumbProps {+ groupId: string;+ /** The current section under the group, e.g. 成员权限. */+ title?: ReactNode;+}++/**+ * Breadcrumb for pages that live under an agent group: `<GroupName> › <Section>`,+ * the group-side counterpart of `AgentBreadcrumb`. The group name links back to+ * the group chat.+ */+const GroupBreadcrumb = memo<GroupBreadcrumbProps>(({ groupId, title }) => {+ const { t } = useTranslation('chat');+ const activeWorkspaceSlug = useActiveWorkspaceSlug();+ const groupTitle = useAgentGroupStore(+ (s) => agentGroupSelectors.getGroupById(groupId)(s)?.title || '',+ );+ const displayTitle = groupTitle || t('group.title');+ const groupHomePath = useMemo(+ () => buildWorkspaceAwarePath(urlJoin('/group', groupId), activeWorkspaceSlug),+ [activeWorkspaceSlug, groupId],+ );++ return (+ <AntBreadcrumb+ className={styles.breadcrumb}+ separator={<Icon icon={ChevronRight} size={14} />}+ items={[+ {+ title: (+ <Link to={groupHomePath}>+ <Text ellipsis as={'span'} color={'inherit'} style={{ maxWidth: 200 }} weight={500}>+ {displayTitle}+ </Text>+ </Link>+ ),+ },+ ...(title === undefined || title === null+ ? []+ : [+ {+ title: (+ <Text as={'span'} color={'inherit'} weight={500}>+ {title}+ </Text>+ ),+ },+ ]),+ ]}+ />+ );+});++GroupBreadcrumb.displayName = 'GroupBreadcrumb';++export default GroupBreadcrumb;diff --git a/src/features/GroupPermission/PermissionForm.tsx b/src/features/GroupPermission/PermissionForm.tsxnew file mode 100644index 00000000000..f6e97bed3f4--- /dev/null+++ b/src/features/GroupPermission/PermissionForm.tsx@@ -0,0 +1,229 @@+'use client';++import type { AgentModelSelectionPolicy } from '@lobechat/types';+import type { FormGroupItemType } from '@lobehub/ui';+import { Alert, Empty, Form, Icon } from '@lobehub/ui';+import { createStaticStyles } from 'antd-style';+import { Bot, InfoIcon, LockIcon, MonitorSmartphone, UsersIcon } from 'lucide-react';+import { memo, useMemo } from 'react';+import { useTranslation } from 'react-i18next';++import AsyncError from '@/components/AsyncError';+import { FORM_STYLE } from '@/const/layoutTokens';+import PolicySelect, { type PolicyOption } from '@/features/ResourcePermission/PolicySelect';+import { getSelectionPolicyLabelKeys } from '@/features/ResourcePermission/selectionPolicyLabels';+import { useAccessLevelOptions } from '@/features/ResourcePermission/useAccessLevelOptions';++import { resolveGroupPermissionSections } from './permissionSections';+import { useGroupPermission } from './useGroupPermission';++const styles = createStaticStyles(({ css }) => ({+ // Same one-line-icon alignment the Agent Permission form uses: FormTitle+ // centres the avatar against title+description, which drops a single-line+ // icon below the label it belongs to.+ rowIcon: css`+ display: flex;+ align-items: center;+ align-self: flex-start;+ height: 1em;+ `,+}));++interface PermissionFormProps {+ groupId: string;+}++const PermissionForm = memo<PermissionFormProps>(({ groupId }) => {+ const { t } = useTranslation('setting');+ const {+ accessError,+ accessLevel,+ accessLoading,+ canEditConfig,+ canFixExecutionTarget,+ canManageAccess,+ executionTargetPolicy,+ hasSupervisor,+ isPrivate,+ isWorkspaceGroup,+ modelPolicy,+ retryAccess,+ setAccessLevel,+ setExecutionTargetPolicy,+ setModelPolicy,+ } = useGroupPermission(groupId);++ const accessOptions = useAccessLevelOptions({ accessLevel, isPrivate });+ const labelKeys = getSelectionPolicyLabelKeys(isPrivate);+ const sections = resolveGroupPermissionSections({+ accessError,+ canManageAccess,+ hasSupervisor,+ isPrivate,+ isWorkspaceGroup,+ });++ const modelPolicyOptions = useMemo(+ (): PolicyOption<AgentModelSelectionPolicy>[] => [+ {+ desc: t('permission.page.groupModelPolicyMemberDesc'),+ icon: UsersIcon,+ label: t(labelKeys.member),+ value: 'member',+ },+ {+ desc: t('permission.page.groupModelPolicyFixedDesc'),+ icon: LockIcon,+ label: t(labelKeys.fixed),+ value: 'fixed',+ },+ ],+ [labelKeys, t],+ );++ const executionPolicyOptions = useMemo(+ (): PolicyOption<AgentModelSelectionPolicy>[] => [+ {+ desc: t('permission.page.groupDevicePolicyMemberDesc'),+ icon: UsersIcon,+ label: t(labelKeys.member),+ value: 'member',+ },+ // Nothing to pin to yet — say so where the choice is made rather than+ // letting the click fail silently.+ canFixExecutionTarget+ ? {+ desc: t('permission.page.groupDevicePolicyFixedDesc'),+ icon: LockIcon,+ label: t(labelKeys.fixed),+ value: 'fixed',+ }+ : {+ desc: t('permission.page.groupDevicePolicyUnset'),+ disabled: true,+ icon: LockIcon,+ label: t(labelKeys.fixed),+ value: 'fixed',+ },+ ],+ [canFixExecutionTarget, labelKeys, t],+ );++ if (sections.showPersonalEmpty) {+ return (+ <Empty+ description={t('permission.page.groupPersonalDesc')}+ icon={LockIcon}+ title={t('permission.page.groupPersonalTitle')}+ type={'page'}+ />+ );+ }++ const memberGroup: FormGroupItemType | undefined = sections.showAccessCard+ ? {+ children: [+ {+ avatar: (+ <span className={styles.rowIcon}>+ <Icon icon={UsersIcon} size={16} />+ </span>+ ),+ children: (+ <PolicySelect+ // Not disabled while the write is in flight: the level updates+ // optimistically and a failure rolls back with a toast, so+ // greying the control out only adds a visible dead beat — the+ // policies next to it behave the same way.+ disabled={!canManageAccess}+ loading={accessLoading}+ options={accessOptions}+ value={accessLevel}+ onChange={setAccessLevel}+ />+ ),+ desc: t(sections.accessDescKey),+ label: t('permission.page.accessLevelLabel'),+ },+ ],+ title: t('permission.page.memberGroup'),+ }+ : undefined;++ // Both rows write to the supervisor agent. Until group detail resolves one+ // there is no row to write to, so the whole card waits rather than offering+ // controls whose save would silently target nothing.+ const configGroup: FormGroupItemType | undefined = sections.showConfigCard+ ? {+ children: [+ {+ avatar: (+ <span className={styles.rowIcon}>+ <Icon icon={Bot} size={16} />+ </span>+ ),+ children: (+ <PolicySelect+ disabled={!canEditConfig}+ options={modelPolicyOptions}+ value={modelPolicy}+ onChange={setModelPolicy}+ />+ ),+ desc: t('permission.page.groupModelPolicyDesc'),+ label: t('settingAgent.modelPolicy.title'),+ },+ {+ avatar: (+ <span className={styles.rowIcon}>+ <Icon icon={MonitorSmartphone} size={16} />+ </span>+ ),+ children: (+ <PolicySelect+ disabled={!canEditConfig}+ options={executionPolicyOptions}+ value={executionTargetPolicy}+ onChange={setExecutionTargetPolicy}+ />+ ),+ desc: t('permission.page.groupDevicePolicyDesc'),+ label: t('settingAgent.devicePolicy.title'),+ },+ ],+ title: t('permission.page.configGroup'),+ }+ : undefined;++ return (+ <>+ {/* A failed permission fetch must not read as "this group has no member+ permissions" — name the failure and keep a way back to the data. */}+ {accessError ? (+ <AsyncError error={accessError} variant={'inline'} onRetry={retryAccess} />+ ) : null}+ {/* Everything below describes what happens once the group is shared, so+ say that once, up front, instead of qualifying each control. */}+ {sections.showPrivateNotice ? (+ <Alert+ icon={<Icon icon={InfoIcon} />}+ style={{ width: '100%' }}+ title={t('permission.page.groupPrivateNotice')}+ type={'info'}+ variant={'outlined'}+ />+ ) : null}+ <Form+ collapsible={false}+ items={[...(memberGroup ? [memberGroup] : []), ...(configGroup ? [configGroup] : [])]}+ itemsType={'group'}+ variant={'filled'}+ {...FORM_STYLE}+ />+ </>+ );+});++PermissionForm.displayName = 'GroupPermissionForm';++export default PermissionForm;diff --git a/src/features/GroupPermission/index.tsx b/src/features/GroupPermission/index.tsxnew file mode 100644index 00000000000..b59f330e57a--- /dev/null+++ b/src/features/GroupPermission/index.tsx@@ -0,0 +1,63 @@+'use client';++import { Flexbox } from '@lobehub/ui';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import AsyncBoundary from '@/components/AsyncBoundary';+import Loading from '@/components/Loading/BrandTextLoading';+import NavHeader from '@/features/NavHeader';+import WideScreenContainer from '@/features/WideScreenContainer';+import { useAgentGroupStore } from '@/store/agentGroup';+import { agentGroupSelectors } from '@/store/agentGroup/selectors';+import { StyleSheet } from '@/utils/styles';++import GroupBreadcrumb from './GroupBreadcrumb';+import PermissionForm from './PermissionForm';++const styles = StyleSheet.create({+ body: {+ display: 'flex',+ overflowY: 'auto',+ position: 'relative',+ },+});++const GroupPermission = memo(() => {+ const { t } = useTranslation('setting');+ const activeGroupId = useAgentGroupStore(agentGroupSelectors.activeGroupId);+ // The group row itself is what the form reads (visibility / workspace); until+ // it lands the page would otherwise render the personal-group empty state,+ // which is a different fact.+ const isGroupLoading = useAgentGroupStore(agentGroupSelectors.isGroupsInit);++ return (+ <Flexbox height={'100%'} width={'100%'}>+ <NavHeader+ styles={{ left: { paddingInlineStart: 24 } }}+ left={+ activeGroupId ? (+ <GroupBreadcrumb groupId={activeGroupId} title={t('permission.page.title')} />+ ) : null+ }+ />+ <Flexbox flex={1} style={styles.body} width={'100%'}>+ <WideScreenContainer>+ <Flexbox gap={16} paddingBlock={16}>+ <AsyncBoundary+ data={isGroupLoading ? undefined : true}+ isLoading={isGroupLoading}+ loading={<Loading debugId="GroupPermission" />}+ >+ <PermissionForm groupId={activeGroupId ?? ''} />+ </AsyncBoundary>+ </Flexbox>+ </WideScreenContainer>+ </Flexbox>+ </Flexbox>+ );+});++GroupPermission.displayName = 'GroupPermission';++export default GroupPermission;diff --git a/src/features/GroupPermission/permissionSections.test.ts b/src/features/GroupPermission/permissionSections.test.tsnew file mode 100644index 00000000000..8224f2b042c--- /dev/null+++ b/src/features/GroupPermission/permissionSections.test.ts@@ -0,0 +1,78 @@+import { describe, expect, it } from 'vitest';++import { resolveGroupPermissionSections } from './permissionSections';++const state = (overrides: Partial<Parameters<typeof resolveGroupPermissionSections>[0]>) => ({+ accessError: undefined,+ canManageAccess: true,+ hasSupervisor: true,+ isPrivate: false,+ isWorkspaceGroup: true,+ ...overrides,+});++describe('resolveGroupPermissionSections', () => {+ it('shows both cards for a shared workspace group', () => {+ const sections = resolveGroupPermissionSections(state({}));++ expect(sections.showAccessCard).toBe(true);+ expect(sections.showConfigCard).toBe(true);+ expect(sections.showPrivateNotice).toBe(false);+ expect(sections.accessDescKey).toBe('permission.page.groupGeneralAccessDesc');+ });++ describe('private group', () => {+ // Mirrors the Agent page: a private group configures every control ahead of+ // publishing, so it keeps the whole page plus the notice — it must not+ // degrade to a stripped-down view.+ it('keeps both cards and adds the publish notice', () => {+ const sections = resolveGroupPermissionSections(state({ isPrivate: true }));++ expect(sections.showPrivateNotice).toBe(true);+ expect(sections.showAccessCard).toBe(true);+ expect(sections.showConfigCard).toBe(true);+ expect(sections.showPersonalEmpty).toBe(false);+ });++ it('describes the access level as taking effect after publishing', () => {+ const sections = resolveGroupPermissionSections(state({ isPrivate: true }));++ expect(sections.accessDescKey).toBe('permission.page.groupAccessLevelPrivateHint');+ });++ it('still defers to the no-manage copy for a member who cannot re-level it', () => {+ const sections = resolveGroupPermissionSections(+ state({ canManageAccess: false, isPrivate: true }),+ );++ expect(sections.accessDescKey).toBe('permission.noManagePermission');+ });+ });++ it('shows only the personal empty state outside a workspace', () => {+ const sections = resolveGroupPermissionSections(state({ isWorkspaceGroup: false }));++ expect(sections.showPersonalEmpty).toBe(true);+ expect(sections.showAccessCard).toBe(false);+ expect(sections.showConfigCard).toBe(false);+ expect(sections.showPrivateNotice).toBe(false);+ });++ it('hides the Editable settings until the supervisor resolves', () => {+ // Both rows write to the supervisor agent; with no row to write to, an+ // enabled control would save to nothing.+ const sections = resolveGroupPermissionSections(state({ hasSupervisor: false }));++ expect(sections.showConfigCard).toBe(false);+ expect(sections.showAccessCard).toBe(true);+ });++ it('drops only the access card when its level fails to load', () => {+ // The two halves have independent sources — the group's permission row vs+ // the supervisor agent — so one failing must not blank the other.+ const sections = resolveGroupPermissionSections(state({ accessError: new Error('boom') }));++ expect(sections.showAccessCard).toBe(false);+ expect(sections.showConfigCard).toBe(true);+ });+});diff --git a/src/features/GroupPermission/permissionSections.ts b/src/features/GroupPermission/permissionSections.tsnew file mode 100644index 00000000000..a70470a884b--- /dev/null+++ b/src/features/GroupPermission/permissionSections.ts@@ -0,0 +1,55 @@+import type { GroupPermissionState } from './useGroupPermission';++/** The three copies the access-level row can carry, as a `t()`-assignable union. */+export type GroupAccessDescKey =+ | 'permission.noManagePermission'+ | 'permission.page.groupAccessLevelPrivateHint'+ | 'permission.page.groupGeneralAccessDesc';++export interface GroupPermissionSections {+ /** Copy under the access-level row: private groups get the publish hint. */+ accessDescKey: GroupAccessDescKey;+ /** Hidden when the level failed to load; the error block replaces it. */+ showAccessCard: boolean;+ /** Both rows write to the supervisor agent — no supervisor, no card. */+ showConfigCard: boolean;+ /** Personal (non-workspace) group — nothing to share, so nothing to grade. */+ showPersonalEmpty: boolean;+ /** "Everything here takes effect once you publish it." */+ showPrivateNotice: boolean;+}++/**+ * Which parts of the Group Permission page are shown, and which copy the access+ * row carries.+ *+ * Extracted from the form so the page's shape is asserted directly — in+ * particular that a **private** group keeps the full page (notice + both cards,+ * with the "when shared" tense) exactly like a private Agent, rather than+ * degrading to a stripped-down view. The two halves have independent failure+ * modes: the access level comes from the group's permission row, while the+ * Editable settings come from the supervisor agent, so one can be missing+ * without taking the other down.+ */+export const resolveGroupPermissionSections = (+ state: Pick<+ GroupPermissionState,+ 'accessError' | 'canManageAccess' | 'hasSupervisor' | 'isPrivate' | 'isWorkspaceGroup'+ >,+): GroupPermissionSections => {+ const { accessError, canManageAccess, hasSupervisor, isPrivate, isWorkspaceGroup } = state;++ const accessDescKey: GroupAccessDescKey = canManageAccess+ ? isPrivate+ ? 'permission.page.groupAccessLevelPrivateHint'+ : 'permission.page.groupGeneralAccessDesc'+ : 'permission.noManagePermission';++ return {+ accessDescKey,+ showAccessCard: isWorkspaceGroup && !accessError,+ showConfigCard: isWorkspaceGroup && hasSupervisor,+ showPersonalEmpty: !isWorkspaceGroup,+ showPrivateNotice: isWorkspaceGroup && isPrivate,+ };+};diff --git a/src/features/GroupPermission/useGroupPermission.test.ts b/src/features/GroupPermission/useGroupPermission.test.tsnew file mode 100644index 00000000000..9463fecb5d2--- /dev/null+++ b/src/features/GroupPermission/useGroupPermission.test.ts@@ -0,0 +1,170 @@+import { renderHook } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { useGroupPermission } from './useGroupPermission';++const mocks = vi.hoisted(() => ({+ access: undefined as { accessLevel: string; canManage: boolean } | undefined,+ accessError: undefined as unknown,+ canEditContent: true,+ groupMap: {} as Record<string, object>,+ permissionResourceId: undefined as string | undefined,+ policiesAgentId: undefined as string | undefined,+ setAccessLevel: vi.fn(),+ setModelPolicy: vi.fn(),+}));++vi.mock('@/hooks/usePermission', () => ({+ usePermission: () => ({ allowed: mocks.canEditContent }),+}));++// The Editable-settings half is the shared agent hook; assert which agent the+// group page points it at rather than re-testing its internals.+vi.mock('@/features/ResourcePermission/useAgentSelectionPolicies', () => ({+ useAgentSelectionPolicies: (agentId: string) => {+ mocks.policiesAgentId = agentId;++ return {+ canFixExecutionTarget: true,+ executionTargetPolicy: 'member',+ modelPolicy: 'member',+ setExecutionTargetPolicy: vi.fn(),+ setModelPolicy: mocks.setModelPolicy,+ };+ },+}));++vi.mock('@/features/ResourcePermission/useResourcePermission', () => ({+ useResourcePermission: (_type: string, resourceId: string | undefined) => {+ mocks.permissionResourceId = resourceId;++ return {+ data: mocks.access,+ error: mocks.accessError,+ isLoading: false,+ mutate: vi.fn(),+ setAccessLevel: mocks.setAccessLevel,+ updating: false,+ };+ },+}));++vi.mock('@/store/agentGroup', () => ({+ useAgentGroupStore: (selector: (state: unknown) => unknown) =>+ selector({ groupMap: mocks.groupMap }),+}));++const workspaceGroup = (overrides: Record<string, unknown> = {}) => ({+ id: 'group-1',+ supervisorAgentId: 'agt-supervisor',+ visibility: 'public',+ workspaceId: 'workspace-1',+ ...overrides,+});++const setup = (groupId = 'group-1') => renderHook(() => useGroupPermission(groupId));++describe('useGroupPermission', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.access = { accessLevel: 'edit', canManage: true };+ mocks.accessError = undefined;+ mocks.canEditContent = true;+ mocks.permissionResourceId = undefined;+ mocks.policiesAgentId = undefined;+ mocks.groupMap = { 'group-1': workspaceGroup() };+ });++ it('exposes member access for a shared workspace group', () => {+ const { result } = setup();++ expect(result.current.isWorkspaceGroup).toBe(true);+ expect(mocks.permissionResourceId).toBe('group-1');+ expect(result.current.accessLevel).toBe('edit');+ expect(result.current.canManageAccess).toBe(true);+ });++ it('keeps the member level readable and settable on a private group', () => {+ // The server stores it and `publishGroupToWorkspace` reads it back, so the+ // creator can decide ahead of sharing.+ mocks.groupMap = { 'group-1': workspaceGroup({ visibility: 'private' }) };++ const { result } = setup();++ expect(result.current.isPrivate).toBe(true);+ expect(mocks.permissionResourceId).toBe('group-1');+ expect(result.current.canManageAccess).toBe(true);+ });++ it('reports a personal group as out of scope for permissions', () => {+ mocks.groupMap = { 'group-1': { id: 'group-1', visibility: 'private' } };++ const { result } = setup();++ expect(result.current.isWorkspaceGroup).toBe(false);+ // No workspace means no permission row to fetch at all.+ expect(mocks.permissionResourceId).toBeUndefined();+ });++ it('reports a member who cannot re-level the group', () => {+ mocks.access = { accessLevel: 'use', canManage: false };++ const { result } = setup();++ expect(result.current.canManageAccess).toBe(false);+ expect(result.current.accessLevel).toBe('use');+ });++ it('forwards a level change to the permission service', () => {+ const { result } = setup();++ result.current.setAccessLevel('use');++ expect(mocks.setAccessLevel).toHaveBeenCalledWith('use');+ });++ it('surfaces a failed permission fetch instead of an empty level', () => {+ mocks.access = undefined;+ mocks.accessError = new Error('boom');++ const { result } = setup();++ expect(result.current.accessError).toBeInstanceOf(Error);+ expect(result.current.accessLevel).toBeUndefined();+ expect(result.current.canManageAccess).toBe(false);+ });++ describe('editable settings', () => {+ it('reads and writes the policies on the supervisor agent', () => {+ // A group conversation IS a conversation with the supervisor+ // (`useGroupContext` resolves the chat agentId to supervisorAgentId), so+ // the group chat's model switcher reads exactly that row.+ const { result } = setup();++ expect(mocks.policiesAgentId).toBe('agt-supervisor');+ expect(result.current.modelPolicy).toBe('member');+ expect(result.current.executionTargetPolicy).toBe('member');++ result.current.setModelPolicy('fixed');+ expect(mocks.setModelPolicy).toHaveBeenCalledWith('fixed');+ });++ it('reports a group whose supervisor has not resolved yet', () => {+ mocks.groupMap = { 'group-1': workspaceGroup({ supervisorAgentId: undefined }) };++ const { result } = setup();++ expect(result.current.hasSupervisor).toBe(false);+ // No row to write to — the form hides the card rather than saving to ''.+ expect(mocks.policiesAgentId).toBe('');+ });++ it('gates the policies on the role-level content permission', () => {+ mocks.canEditContent = false;++ const { result } = setup();++ expect(result.current.canEditConfig).toBe(false);+ });+ });+});diff --git a/src/features/GroupPermission/useGroupPermission.ts b/src/features/GroupPermission/useGroupPermission.tsnew file mode 100644index 00000000000..6806421f508--- /dev/null+++ b/src/features/GroupPermission/useGroupPermission.ts@@ -0,0 +1,86 @@+'use client';++import type { AgentModelSelectionPolicy } from '@lobechat/types';++import { useAgentSelectionPolicies } from '@/features/ResourcePermission/useAgentSelectionPolicies';+import { useResourcePermission } from '@/features/ResourcePermission/useResourcePermission';+import { usePermission } from '@/hooks/usePermission';+import type { ResourceAccessLevel } from '@/services/resourcePermission';+import { useAgentGroupStore } from '@/store/agentGroup';+import { agentGroupSelectors } from '@/store/agentGroup/selectors';++export interface GroupPermissionState {+ accessError: unknown;+ accessLevel?: ResourceAccessLevel;+ accessLoading: boolean;+ /** Role-level gate for the model / execution-environment policies. */+ canEditConfig: boolean;+ /** Fixing needs an execution environment resolvable on the supervisor. */+ canFixExecutionTarget: boolean;+ /** Only the creator or a workspace owner may re-level members. */+ canManageAccess: boolean;+ executionTargetPolicy: AgentModelSelectionPolicy;+ /** No supervisor row yet — the Editable settings have nothing to write to. */+ hasSupervisor: boolean;+ isPrivate: boolean;+ isWorkspaceGroup: boolean;+ modelPolicy: AgentModelSelectionPolicy;+ retryAccess: () => void;+ setAccessLevel: (level: ResourceAccessLevel) => void;+ setExecutionTargetPolicy: (policy: AgentModelSelectionPolicy) => void;+ setModelPolicy: (policy: AgentModelSelectionPolicy) => void;+}++/**+ * View model of the Agent Group Permission page.+ *+ * The two halves have different subjects, which is the whole reason this page+ * can exist at all:+ *+ * - **Access level** is about the *group* resource — who may open and edit it.+ * The server cascades it to the agents the group owns.+ * - **Editable settings** are about the *supervisor agent*, because a group+ * conversation is a conversation with the supervisor: `useGroupContext`+ * resolves the chat context's `agentId` to `supervisorAgentId`, so the group+ * chat's model / execution-environment switcher reads exactly that row's+ * policies. Deliberately NOT fanned out to the member agents — a workspace+ * member has no per-member switcher to gate, and writing a `fixed` policy+ * onto an agent with no execution target is rejected by `AgentModel`.+ *+ * The group store hydrates the supervisor into `agentMap` whenever group detail+ * loads (`agentGroup/action.ts`), so the shared agent hook has its row here.+ */+export const useGroupPermission = (groupId: string): GroupPermissionState => {+ const { allowed: canEditContent } = usePermission('edit_own_content');+ const group = useAgentGroupStore(agentGroupSelectors.getGroupById(groupId));++ const isWorkspaceGroup = !!group?.workspaceId;+ const isPrivate = group?.visibility === 'private';+ const supervisorAgentId = group?.supervisorAgentId;++ const {+ data: access,+ error: accessError,+ isLoading: accessLoading,+ mutate: retryAccess,+ // Settable while private too: the server stores the level and the publish+ // path reads it back, so the creator can decide ahead of sharing.+ setAccessLevel,+ } = useResourcePermission('agentGroup', isWorkspaceGroup ? groupId : undefined);++ const policies = useAgentSelectionPolicies(supervisorAgentId ?? '');++ return {+ ...policies,+ accessError,+ accessLevel: access?.accessLevel,+ accessLoading,+ canEditConfig: canEditContent,+ canManageAccess: access?.canManage === true,+ hasSupervisor: !!supervisorAgentId,+ isPrivate,+ isWorkspaceGroup,+ retryAccess: () => void retryAccess(),+ setAccessLevel: (level) => void setAccessLevel(level),+ };+};diff --git a/src/features/AgentPermission/PolicySelect.tsx b/src/features/ResourcePermission/PolicySelect.tsxsimilarity index 92%rename from src/features/AgentPermission/PolicySelect.tsxrename to src/features/ResourcePermission/PolicySelect.tsxindex 76158f5209b..89c1a935a68 100644--- a/src/features/AgentPermission/PolicySelect.tsx+++ b/src/features/ResourcePermission/PolicySelect.tsx@@ -74,10 +74,10 @@ interface PolicySelectProps<Value extends string> {}/**- * The one control shape shared by every row of the Agent Permission page:- * a two-line option in the popup (what it means), a single compact line once- * chosen. Keeping all three rows on one component is what makes "who can do- * what" read as a single decision rather than three unrelated widgets.+ * The one control shape shared by every row of the Agent / Agent Group+ * Permission pages: a two-line option in the popup (what it means), a single+ * compact line once chosen. Keeping every row on one component is what makes+ * "who can do what" read as a single decision rather than unrelated widgets.*/const PolicySelectInner = <Value extends string>({disabled,diff --git a/src/features/AgentPermission/selectionPolicyLabels.ts b/src/features/ResourcePermission/selectionPolicyLabels.tssimilarity index 100%rename from src/features/AgentPermission/selectionPolicyLabels.tsrename to src/features/ResourcePermission/selectionPolicyLabels.tsdiff --git a/src/features/ResourcePermission/useAccessLevelOptions.ts b/src/features/ResourcePermission/useAccessLevelOptions.tsnew file mode 100644index 00000000000..0bf1bc8d4d9--- /dev/null+++ b/src/features/ResourcePermission/useAccessLevelOptions.ts@@ -0,0 +1,63 @@+'use client';++import { EyeIcon, PencilIcon, PlayIcon } from 'lucide-react';+import { useMemo } from 'react';+import { useTranslation } from 'react-i18next';++import type { ResourceAccessLevel } from '@/services/resourcePermission';++import type { PolicyOption } from './PolicySelect';++/**+ * The workspace General-access options offered on a Permission page, shared by+ * Agent and Agent Group so the two surfaces can never drift into naming the+ * same level differently.+ *+ * `isPrivate` only changes the *label tense*: a still-private resource has no+ * members yet, so "Can edit" would describe a state that does not exist —+ * "Can edit when shared" says the same decision is being configured ahead of+ * publishing. The descriptions explain what the level itself means and stay as+ * they are either way.+ */+export const useAccessLevelOptions = (params: {+ /** Current level — a legacy `view` row is listed so the control shows it. */+ accessLevel?: ResourceAccessLevel;+ isPrivate: boolean;+}): PolicyOption<ResourceAccessLevel>[] => {+ const { accessLevel, isPrivate } = params;+ const { t } = useTranslation('setting');++ return useMemo(() => {+ const options: PolicyOption<ResourceAccessLevel>[] = [+ {+ desc: t('permission.generalAccess.editableDesc'),+ icon: PencilIcon,+ label: t(+ isPrivate ? 'permission.page.editableWhenShared' : 'permission.generalAccess.editable',+ ),+ value: 'edit',+ },+ {+ desc: t('permission.generalAccess.usableDesc'),+ icon: PlayIcon,+ label: t(+ isPrivate ? 'permission.page.usableWhenShared' : 'permission.generalAccess.usable',+ ),+ value: 'use',+ },+ ];++ // `view` is a document-only level, but a legacy row can still carry it —+ // list it so the control shows the real current value instead of blank.+ if (accessLevel === 'view') {+ options.push({+ desc: t('permission.generalAccess.viewableDesc'),+ icon: EyeIcon,+ label: t('permission.generalAccess.viewable'),+ value: 'view',+ });+ }++ return options;+ }, [accessLevel, isPrivate, t]);+};diff --git a/src/features/ResourcePermission/useAgentSelectionPolicies.ts b/src/features/ResourcePermission/useAgentSelectionPolicies.tsnew file mode 100644index 00000000000..dba38559814--- /dev/null+++ b/src/features/ResourcePermission/useAgentSelectionPolicies.ts@@ -0,0 +1,99 @@+'use client';++import type { AgentModelSelectionPolicy, LobeAgentAgencyConfig } from '@lobechat/types';+import { useCallback, useMemo } from 'react';++import { useDeviceList } from '@/features/DeviceManager/useDeviceList';+import {+ groupExecutionTargetDevices,+ resolveExecutionTargetSelection,+} from '@/features/ExecutionTargetPicker';+import { isHeterogeneousSandboxExecutionAvailable } from '@/helpers/executionTarget';+import { useAgentStore } from '@/store/agent';+import { agentByIdSelectors } from '@/store/agent/selectors';++export interface AgentSelectionPoliciesState {+ /** Members can be assigned a target only if one is actually resolvable. */+ canFixExecutionTarget: boolean;+ executionTargetPolicy: AgentModelSelectionPolicy;+ modelPolicy: AgentModelSelectionPolicy;+ setExecutionTargetPolicy: (policy: AgentModelSelectionPolicy) => void;+ setModelPolicy: (policy: AgentModelSelectionPolicy) => void;+}++/**+ * The "Editable settings" half of a Permission page: what a workspace member+ * may switch for their own conversations / runs with ONE agent.+ *+ * Shared by the Agent page and the Agent Group page, because a group's+ * conversation *is* a conversation with its supervisor agent — the group chat+ * input resolves its `agentId` to `supervisorAgentId`+ * (`useGroupContext`), so these policies are read off that one row in both+ * cases. Nothing here is group-aware; the caller decides which agent it means.+ *+ * The stored policy is read directly rather than through+ * `resolveAgentModelSelectionPolicy`: that resolver answers "what happens at+ * run time", which collapses to `fixed` for a private agent — so a control+ * driven by it would look stuck while its author configures the rules ahead of+ * sharing. What is edited here is the author's *intent*.+ */+export const useAgentSelectionPolicies = (agentId: string): AgentSelectionPoliciesState => {+ const agent = useAgentStore(agentByIdSelectors.getAgentById(agentId));+ const updateAgentConfigById = useAgentStore((s) => s.updateAgentConfigById);++ const { data: devices } = useDeviceList();+ const publicWorkspaceDevices = useMemo(+ () => groupExecutionTargetDevices(devices).publicWorkspace,+ [devices],+ );++ const agencyConfig = agent?.agencyConfig;+ const heterogeneousType = agencyConfig?.heterogeneousProvider?.type;+ const executionSelection = resolveExecutionTargetSelection({+ boundDeviceId: agencyConfig?.boundDeviceId,+ configuredTarget: agencyConfig?.executionTarget,+ devices: publicWorkspaceDevices,+ isHeterogeneous: !!heterogeneousType,+ });++ const saveAgencyConfig = useCallback(+ (patch: Partial<LobeAgentAgencyConfig>) =>+ updateAgentConfigById(agentId, { agencyConfig: patch }),+ [agentId, updateAgentConfigById],+ );++ const setExecutionTargetPolicy = useCallback(+ (policy: AgentModelSelectionPolicy) => {+ if (policy === 'member') {+ void saveAgencyConfig({ executionTargetSelectionPolicy: 'member' });+ return;+ }+ // Fixing pins whatever is selected right now, so a run can't fall back to+ // a target the author never chose.+ if (!executionSelection) return;++ void saveAgencyConfig({+ ...(executionSelection.deviceId ? { boundDeviceId: executionSelection.deviceId } : {}),+ executionTarget: executionSelection.target,+ executionTargetSelectionPolicy: 'fixed',+ });+ },+ [executionSelection, saveAgencyConfig],+ );++ const setModelPolicy = useCallback(+ (policy: AgentModelSelectionPolicy) => void saveAgencyConfig({ modelSelectionPolicy: policy }),+ [saveAgencyConfig],+ );++ return {+ canFixExecutionTarget:+ !!executionSelection &&+ (executionSelection.target !== 'sandbox' ||+ isHeterogeneousSandboxExecutionAvailable(heterogeneousType)),+ executionTargetPolicy: agencyConfig?.executionTargetSelectionPolicy ?? 'member',+ modelPolicy: agencyConfig?.modelSelectionPolicy ?? 'member',+ setExecutionTargetPolicy,+ setModelPolicy,+ };+};diff --git a/src/features/RouteMeta/GroupDynamicMeta.tsx b/src/features/RouteMeta/GroupDynamicMeta.tsxindex 36032fcf14b..28b7e97aa95 100644--- a/src/features/RouteMeta/GroupDynamicMeta.tsx+++ b/src/features/RouteMeta/GroupDynamicMeta.tsx@@ -64,4 +64,22 @@ export const GroupProfileDynamicMeta = ({ onResolve, params }: DynamicRouteMetaPreturn null;};+export const GroupPermissionDynamicMeta = ({ onResolve, params }: DynamicRouteMetaProps) => {+ const { t } = useTranslation('electron');+ const routeWorkspaceId = useRouteWorkspaceId(params);+ const group = useSessionStore((state) => {+ const item = sessionGroupSelectors.getGroupById(params.gid ?? '')(state);+ return matchesRouteWorkspace(getWorkspaceId(item), routeWorkspaceId) ? item : undefined;+ });++ usePublishDynamicRouteMeta(+ {+ title: [t('navigation.permission'), group?.name].filter(Boolean).join(' · ') || undefined,+ },+ onResolve,+ );++ return null;+};+export default GroupDynamicMeta;diff --git a/src/routes/(main)/group/features/routeMeta.ts b/src/routes/(main)/group/features/routeMeta.tsindex 9881ce21de5..3a836ba0f61 100644--- a/src/routes/(main)/group/features/routeMeta.ts+++ b/src/routes/(main)/group/features/routeMeta.ts@@ -1,4 +1,4 @@-import { FileUserIcon, Users } from 'lucide-react';+import { FileUserIcon, Users, UsersIcon } from 'lucide-react';import { lazy } from 'react';import { routeMeta } from '@/spa/router/routeMeta';@@ -9,6 +9,11 @@ const GroupProfileDynamicMeta = lazy(() =>default: module.GroupProfileDynamicMeta,})),);+const GroupPermissionDynamicMeta = lazy(() =>+ import('@/features/RouteMeta/GroupDynamicMeta').then((module) => ({+ default: module.GroupPermissionDynamicMeta,+ })),+);export const groupRouteMeta = routeMeta({DynamicMeta: GroupDynamicMeta,@@ -21,3 +26,9 @@ export const groupProfileRouteMeta = routeMeta({icon: FileUserIcon,titleKey: 'navigation.groupProfile',});++export const groupPermissionRouteMeta = routeMeta({+ DynamicMeta: GroupPermissionDynamicMeta,+ icon: UsersIcon,+ titleKey: 'navigation.permission',+});diff --git a/src/routes/(main)/group/permission/index.tsx b/src/routes/(main)/group/permission/index.tsxnew file mode 100644index 00000000000..d431f663d9c--- /dev/null+++ b/src/routes/(main)/group/permission/index.tsx@@ -0,0 +1,28 @@+'use client';++import { memo, Suspense } from 'react';+import { useParams } from 'react-router';++import Loading from '@/components/Loading/BrandTextLoading';+import GroupPermission from '@/features/GroupPermission';+import ResourceConfigAccessGate from '@/features/ResourcePermission/ResourceConfigAccessGate';++const GroupPermissionPage = memo(() => {+ const { gid } = useParams<{ gid: string }>();++ return (+ <Suspense fallback={<Loading debugId="GroupPermissionPage" />}>+ {/* Managing who can do what is a configuration action: a chat-only member+ gets the same redirect + reason toast as on Group Profile. */}+ <ResourceConfigAccessGate+ redirectPath={`/group/${gid ?? ''}`}+ resourceId={gid}+ resourceType="agentGroup"+ >+ <GroupPermission />+ </ResourceConfigAccessGate>+ </Suspense>+ );+});++export default GroupPermissionPage;diff --git a/src/routes/(main)/group/profile/features/AgentBuilder/AgentBuilderProvider.tsx b/src/routes/(main)/group/profile/features/AgentBuilder/AgentBuilderProvider.tsxindex 0669319a342..ace61bdf4c5 100644--- a/src/routes/(main)/group/profile/features/AgentBuilder/AgentBuilderProvider.tsx+++ b/src/routes/(main)/group/profile/features/AgentBuilder/AgentBuilderProvider.tsx@@ -1,5 +1,6 @@import { type ReactNode } from 'react';import { memo, useMemo } from 'react';+import { useParams } from 'react-router';import { ConversationProvider } from '@/features/Conversation';import { useOperationState } from '@/hooks/useOperationState';@@ -21,15 +22,25 @@ const AgentBuilderProvider = memo<AgentBuilderProviderProps>(({ agentId, childre// Use activeTopicId from chatStore (synced with URL query 'bt' via ProfileHydration)const activeTopicId = useChatStore((s) => s.activeTopicId);+ // The group being configured comes from the ROUTE, not the global store: the+ // send path samples its fallback (`activeGroupId`) after async preflight work,+ // so switching groups while a send is starting would hand the server the newly+ // active group and let the tool runtime stamp the wrong one.+ const { gid } = useParams<{ gid: string }>();+// Build conversation context for group agent builder// Using group_agent_builder scope with groupId for per-group message isolation- const context = useMemo<MessageMapKeyInput>(+ const context = useMemo<MessageMapKeyInput & { editingGroupId?: string }>(() => ({agentId,+ // NOT `groupId`: that would key the builder's messages into the group's+ // own chat bucket. `editingGroupId` is ignored by `messageMapKey` and only+ // travels to the server as `ExecAgentAppContext.editingGroupId`.+ editingGroupId: gid,scope: 'group_agent_builder',topicId: activeTopicId,}),- [agentId, activeTopicId],+ [agentId, activeTopicId, gid],);// Get messages from ChatStore based on contextdiff --git a/src/routes/(main)/group/profile/features/AgentBuilder/TopicSelector.tsx b/src/routes/(main)/group/profile/features/AgentBuilder/TopicSelector.tsxindex 36ee3fb0ba9..eb65c0ac7db 100644--- a/src/routes/(main)/group/profile/features/AgentBuilder/TopicSelector.tsx+++ b/src/routes/(main)/group/profile/features/AgentBuilder/TopicSelector.tsx@@ -1,5 +1,6 @@import { type DropdownMenuCheckboxItem } from '@lobehub/ui';import { ActionIcon, DropdownMenu, Tag } from '@lobehub/ui';+import { createStaticStyles } from 'antd-style';import { Clock3Icon, PlusIcon } from 'lucide-react';import { memo, useCallback, useMemo } from 'react';import { useTranslation } from 'react-i18next';@@ -10,6 +11,20 @@ import { useQueryState } from '@/hooks/useQueryParam';import { useChatStore } from '@/store/chat';import { topicSelectors } from '@/store/chat/slices/topic/selectors';+const styles = createStaticStyles(({ css }) => ({+ // The tag is a flex item of the header's left slot: without these it keeps its+ // full text width and overlaps the action icons on the right.+ tag: css`+ overflow: hidden;+ min-width: 0;+ `,+ title: css`+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ `,+}));+interface TopicSelectorProps {agentId: string;disabled?: boolean;@@ -62,8 +77,17 @@ const TopicSelector = memo<TopicSelectorProps>(({ agentId, disabled }) => {return (<NavHeader- left={activeTopic?.title ? <Tag>{activeTopic.title}</Tag> : undefined}showTogglePanelButton={false}+ styles={{ right: { flex: 'none' } }}+ left={+ activeTopic?.title ? (+ <Tag className={styles.tag}>+ <span className={styles.title} title={activeTopic.title}>+ {activeTopic.title}+ </span>+ </Tag>+ ) : undefined+ }right={<><ActionIcon@@ -83,7 +107,11 @@ const TopicSelector = memo<TopicSelectorProps>(({ agentId, disabled }) => {popupProps={{ style: { maxHeight: 600, minWidth: 200, overflowY: 'auto' } }}triggerProps={{ disabled: disabled || isEmpty }}>- <ActionIcon disabled={disabled || isEmpty} icon={Clock3Icon} />+ <ActionIcon+ disabled={disabled || isEmpty}+ icon={Clock3Icon}+ size={DESKTOP_HEADER_ICON_SMALL_SIZE}+ /></DropdownMenu></>}diff --git a/src/routes/(main)/group/profile/features/GroupProfile/index.tsx b/src/routes/(main)/group/profile/features/GroupProfile/index.tsxindex 41034053848..84f7f5bda55 100644--- a/src/routes/(main)/group/profile/features/GroupProfile/index.tsx+++ b/src/routes/(main)/group/profile/features/GroupProfile/index.tsx@@ -1,10 +1,10 @@'use client';-import { ActionIcon, DropdownMenu, Flexbox } from '@lobehub/ui';+import { ActionIcon, DropdownMenu, Flexbox, Icon } from '@lobehub/ui';import { Button, type ModalInstance } from '@lobehub/ui/base-ui';import { Divider } from 'antd';import { useTheme } from 'antd-style';-import { MoreHorizontalIcon, PlayIcon, Settings2Icon } from 'lucide-react';+import { MoreHorizontalIcon, PlayIcon, Settings2Icon, UsersIcon } from 'lucide-react';import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';import { useParams } from 'react-router';@@ -16,7 +16,7 @@ import { EditingIndicator, type EditLockClient, useEditLock } from '@/features/Eimport { EditorCanvas } from '@/features/EditorCanvas';import AccessLevelTag from '@/features/ResourcePermission/AccessLevelTag';import { useResourceAccess } from '@/features/ResourcePermission/useResourceAccess';-import { useResourcePermissionMenuItem } from '@/features/ResourcePermission/useResourcePermissionMenuItem';+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';import { usePermission } from '@/hooks/usePermission';import { useQueryRoute } from '@/hooks/useQueryRoute';import { lambdaClient } from '@/libs/trpc/client';@@ -50,6 +50,9 @@ const GroupProfile = memo(() => {const currentGroup = useAgentGroupStore((s) => agentGroupSelectors.getGroupById(gid ?? '')(s));const updateGroup = useAgentGroupStore((s) => s.updateGroup);const router = useQueryRoute();+ // The profile page keeps its active tab in `?tab=`; the permission page has no+ // tabs, so navigate without carrying the query over (unlike `router.push`).+ const navigate = useWorkspaceAwareNavigate();const transferMenuItems = useAgentGroupTransferMenuItem(groupId ?? undefined);// A workspace member whose General access on this group is view/use level// can't edit it (defaults permissive while loading — server enforces).@@ -59,25 +62,34 @@ const GroupProfile = memo(() => {);const canEdit = hasEditPermission && canEditResource;- // Member-permission entry lives inside the "..." menu, matching the agent- // profile header (only meaningful for public workspace groups).- const memberPermissionMenuItem = useResourcePermissionMenuItem(- 'agentGroup',- hasActiveWorkspace && currentGroup?.visibility !== 'private'- ? (groupId ?? undefined)- : undefined,- );- const moreMenuItems = useMemo(- () =>- [- memberPermissionMenuItem,- memberPermissionMenuItem && transferMenuItems?.length- ? ({ type: 'divider' } as const)- : null,- ...(transferMenuItems ?? []),- ].filter(Boolean),- [memberPermissionMenuItem, transferMenuItems],- );+ // Member-permission entry lives inside the "..." menu and opens the dedicated+ // page, matching the agent profile header. Shown for private groups too: the+ // creator sets there what members get the moment the group is published.+ const showPermissionPageEntry = hasActiveWorkspace && !!groupId;+ const moreMenuItems = useMemo(() => {+ const permissionMenuItem = showPermissionPageEntry+ ? {+ // Same gate the page itself applies (ResourceConfigAccessGate):+ // without edit-level access it redirects straight back with a toast,+ // so an enabled entry here is a click into a dead end. Disabled, not+ // hidden — the member can still see the action exists.+ disabled: !canEdit,+ icon: <Icon icon={UsersIcon} />,+ key: 'permission',+ label: t('permission.page.entry', { ns: 'setting' }),+ onClick: () => {+ if (!canEdit || !groupId) return;+ navigate(urlJoin('/group', groupId, 'permission'));+ },+ }+ : null;++ return [+ permissionMenuItem,+ permissionMenuItem && transferMenuItems?.length ? ({ type: 'divider' } as const) : null,+ ...(transferMenuItems ?? []),+ ].filter(Boolean);+ }, [canEdit, groupId, navigate, showPermissionPageEntry, t, transferMenuItems]);const settingsModalRef = useRef<ModalInstance | null>(null);useEffect(diff --git a/src/services/chat/mecha/agentConfigResolver.test.ts b/src/services/chat/mecha/agentConfigResolver.test.tsindex 998824c1ac0..562284431da 100644--- a/src/services/chat/mecha/agentConfigResolver.test.ts+++ b/src/services/chat/mecha/agentConfigResolver.test.ts@@ -197,6 +197,35 @@ describe('resolveAgentConfig', () => {expect(result.agentConfig.provider).toBe('member-provider');});+ it('uses the member model override on a collaborative builtin the caller created', () => {+ vi.spyOn(agentSelectors.agentByIdSelectors, 'getAgentById').mockReturnValue(+ () =>+ ({+ slug: 'group-agent-builder',+ userId: 'member-1',+ virtual: true,+ visibility: 'public',+ workspaceId: 'workspace-1',+ }) as any,+ );+ vi.spyOn(agentSelectors.agentSelectors, 'getAgentConfigById').mockReturnValue(+ () => ({ ...mockAgentConfig, provider: 'openai' }) as any,+ );+ useUserStore.setState({+ user: { id: 'member-1' } as any,+ workspaceUserPreference: {+ agentModelOverrides: {+ 'test-agent': { model: 'member-model', provider: 'member-provider' },+ },+ },+ });++ const result = resolveAgentConfig({ agentId: 'test-agent' });++ expect(result.agentConfig.model).toBe('member-model');+ expect(result.agentConfig.provider).toBe('member-provider');+ });+it('ignores a retained member model override when the workspace policy is fixed', () => {vi.spyOn(agentSelectors.agentByIdSelectors, 'getAgentById').mockReturnValue(() => ({ visibility: 'public', workspaceId: 'workspace-1' }) as any,diff --git a/src/services/chat/mecha/agentConfigResolver.ts b/src/services/chat/mecha/agentConfigResolver.tsindex fae78807383..5f484cd1048 100644--- a/src/services/chat/mecha/agentConfigResolver.ts+++ b/src/services/chat/mecha/agentConfigResolver.ts@@ -1,5 +1,9 @@import { type BuiltinAgentSlug } from '@lobechat/builtin-agents';-import { BUILTIN_AGENT_SLUGS, getAgentRuntimeConfig } from '@lobechat/builtin-agents';+import {+ BUILTIN_AGENT_SLUGS,+ getAgentRuntimeConfig,+ isCollaborativeBuiltinAgentRow,+} from '@lobechat/builtin-agents';import { PageAgentIdentifier } from '@lobechat/builtin-tool-page-agent';import { TaskIdentifier } from '@lobechat/builtin-tool-task';import { type LobeToolManifest } from '@lobechat/context-engine';@@ -199,11 +203,17 @@ export const resolveAgentConfig = (ctx: AgentConfigResolverContext): ResolvedAgeconst agent = agentByIdSelectors.getAgentById(agentId)(agentStoreState);const currentUserId = userProfileSelectors.userId(useUserStore.getState());const isAuthor = !!currentUserId && agent?.userId === currentUserId;- const usesWorkspaceMemberSelection =- !!agent?.workspaceId && agent.visibility !== 'private' && !isAuthor;- const memberModelOverride = usesWorkspaceMemberSelection- ? useUserStore.getState().workspaceUserPreference.agentModelOverrides?.[agentId]- : undefined;+ const isPublicWorkspaceAgent = !!agent?.workspaceId && agent.visibility !== 'private';+ // A collaborative builtin has no real author (the row is provisioned by+ // whoever opened the feature first), so its *model* stays personal even for+ // that member — see `AgentModelConfig.personalModelSelection`. Chat/Agent mode+ // keeps the ordinary author rule.+ const personalModelSelection = isCollaborativeBuiltinAgentRow(agent ?? {});+ const usesWorkspaceMemberSelection = isPublicWorkspaceAgent && !isAuthor;+ const memberModelOverride =+ isPublicWorkspaceAgent && (personalModelSelection || !isAuthor)+ ? useUserStore.getState().workspaceUserPreference.agentModelOverrides?.[agentId]+ : undefined;const memberModeOverride = usesWorkspaceMemberSelection? useUserStore.getState().workspaceUserPreference.agentModeOverrides?.[agentId]: undefined;@@ -213,6 +223,7 @@ export const resolveAgentConfig = (ctx: AgentConfigResolverContext): ResolvedAge{...sharedAgentConfig,canManage: isAuthor,+ personalModelSelection,visibility: agent?.visibility,workspaceId: agent?.workspaceId,},diff --git a/src/services/topic/index.ts b/src/services/topic/index.tsindex 964c0f03779..936eb31c288 100644--- a/src/services/topic/index.ts+++ b/src/services/topic/index.ts@@ -84,6 +84,8 @@ export class TopicService {return lambdaClient.topic.getTopics.query({agentId: params.agentId,current: params.current,+ editingAgentId: params.editingAgentId,+ editingGroupId: params.editingGroupId,excludeStatuses: params.excludeStatuses,excludeTriggers: params.excludeTriggers,groupId: params.groupId,diff --git a/src/spa/router/desktopRouter.shared.tsx b/src/spa/router/desktopRouter.shared.tsxindex 814f6c03add..1d09ad00c21 100644--- a/src/spa/router/desktopRouter.shared.tsx+++ b/src/spa/router/desktopRouter.shared.tsx@@ -34,7 +34,11 @@ import {agentStatisticsRouteMeta,topicsRouteMeta,} from '@/routes/(main)/agent/features/routeMeta';-import { groupProfileRouteMeta, groupRouteMeta } from '@/routes/(main)/group/features/routeMeta';+import {+ groupPermissionRouteMeta,+ groupProfileRouteMeta,+ groupRouteMeta,+} from '@/routes/(main)/group/features/routeMeta';import AppShellSkeleton, { APP_SHELL_FALLBACK_ID } from '@/spa/BootShell/AppShellSkeleton';import { loadRouteWithBuiltinToolSurfaces } from '@/spa/initialize/toolSurfaces';import { routeMeta } from '@/spa/router/routeMeta';@@ -241,6 +245,14 @@ export const sharedMainAreaChildren: RouteObject[] = [handle: { meta: groupProfileRouteMeta },path: 'profile',},+ {+ element: dynamicElement(+ () => import('@/routes/(main)/group/permission'),+ 'Desktop > Agent Group > Permission',+ ),+ handle: { meta: groupPermissionRouteMeta },+ path: 'permission',+ },{element: groupChatElement,handle: { meta: groupRouteMeta },diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.tsindex d2b36578c13..f1d6a9603f1 100644--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts@@ -584,6 +584,20 @@ export class GatewayActionImpl {...(executionContext.scope === 'agent_builder' && {editingAgentId: this.#get().activeAgentId ?? undefined,}),+ // Same shape as `editingAgentId`, for the Group Agent Builder panel on+ // the group Profile page. The builder conversation is keyed by the+ // builtin builder agent (no groupId in its ConversationContext, so the+ // message map key and the group's own chat stay separate), which left+ // the server runtime with no idea which group it was editing.+ // The context value wins, and every surface that opens this scope sets+ // it from its own route/group: it is fixed for the run, so a mid-run+ // navigation cannot make the server stamp a different group than the+ // panel is reading from. The `activeGroupId` fallback is a last resort+ // for a caller that forgot — it is sampled here, AFTER the async+ // preflight above, so it can already be stale by this point.+ ...(executionContext.scope === 'group_agent_builder' && {+ editingGroupId: executionContext.editingGroupId ?? this.#get().activeGroupId,+ }),groupId: executionContext.groupId,...(initialTopicMetadata && { initialTopicMetadata }),// Forward the group orchestration role so the server can stamp it ontodiff --git a/src/store/chat/slices/topic/action.test.ts b/src/store/chat/slices/topic/action.test.tsindex 9d5b1ee85c8..cf39603ad39 100644--- a/src/store/chat/slices/topic/action.test.ts+++ b/src/store/chat/slices/topic/action.test.ts@@ -310,6 +310,74 @@ describe('topic action', () => {// Additional tests for refreshTopic can be added here...});+ describe('updateTopicModel', () => {+ // The Agent Builder panels render a whole conversation for a builtin agent+ // while the page's activeAgentId still points at the agent being edited, so+ // the topic being switched lives in another `topicDataMap` bucket.+ const BUILDER_KEY = topicMapKey({ agentId: 'builder-agent' });++ const seedBuilderTopic = () => {+ act(() => {+ useChatStore.setState({+ activeAgentId: 'edited-agent',+ activeTopicId: 'builder-topic',+ topicDataMap: {+ [BUILDER_KEY]: {+ currentPage: 0,+ hasMore: false,+ items: [+ {+ id: 'builder-topic',+ model: 'glm-5.2',+ provider: 'lobehub',+ title: 'Builder chat',+ } as ChatTopic,+ ],+ pageSize: 20,+ total: 1,+ },+ },+ });+ });+ };++ it('applies the switch to the bucket that owns the topic', async () => {+ const { result } = renderHook(() => useChatStore());+ vi.spyOn(topicService, 'updateTopic').mockResolvedValue(undefined as any);+ seedBuilderTopic();++ await act(async () => {+ await result.current.updateTopicModel('builder-topic', {+ model: 'deepseek-v4-flash',+ provider: 'lobehub',+ });+ });++ expect(useChatStore.getState().topicDataMap[BUILDER_KEY].items[0]).toMatchObject({+ model: 'deepseek-v4-flash',+ provider: 'lobehub',+ });+ });++ it('revalidates the owning bucket instead of the active agent bucket', async () => {+ const { result } = renderHook(() => useChatStore());+ vi.spyOn(topicService, 'updateTopic').mockResolvedValue(undefined as any);+ (mutate as Mock).mockClear();+ seedBuilderTopic();++ await act(async () => {+ await result.current.updateTopicModel('builder-topic', {+ model: 'deepseek-v4-flash',+ provider: 'lobehub',+ });+ });++ const matcherFn = (mutate as Mock).mock.calls[0][0];+ expect(matcherFn(['topic:list', BUILDER_KEY, { pageSize: 20 }])).toBe(true);+ expect(matcherFn(['topic:list', topicMapKey({ agentId: 'edited-agent' }), {}])).toBe(false);+ });+ });+describe('favoriteTopic', () => {it('should update the favorite state of a topic and refresh topics', async () => {const { result } = renderHook(() => useChatStore());diff --git a/src/store/chat/slices/topic/action.ts b/src/store/chat/slices/topic/action.tsindex 115d90d69b4..b327e0497e8 100644--- a/src/store/chat/slices/topic/action.ts+++ b/src/store/chat/slices/topic/action.ts@@ -1400,12 +1400,20 @@ export class ChatTopicActionImpl {);};- refreshTopic = async (): Promise<void> => {+ /**+ * @param ownerContainerKey - Revalidate this `topicDataMap` bucket instead of+ * the active agent/group one. Pass it whenever the affected row may live+ * elsewhere (Agent Builder panels render another agent's conversation);+ * omitting it refreshes whatever the page is showing.+ */+ refreshTopic = async (ownerContainerKey?: string): Promise<void> => {const { activeAgentId, activeGroupId } = this.#get();// Use topicMapKey to generate the same key used in useFetchTopics// Key format: topicKeys.list(containerKey, { isInbox, pageSize })- const containerKey = topicMapKey({ agentId: activeAgentId, groupId: activeGroupId });- const agentViewKey = activeAgentId ? topicMapKey({ agentId: activeAgentId }) : null;+ const containerKey =+ ownerContainerKey ?? topicMapKey({ agentId: activeAgentId, groupId: activeGroupId });+ const agentViewKey =+ ownerContainerKey ?? (activeAgentId ? topicMapKey({ agentId: activeAgentId }) : null);await mutate((key) =>Array.isArray(key) &&@@ -1454,10 +1462,15 @@ export class ChatTopicActionImpl {};internal_updateTopic = async (id: string, data: Partial<ChatTopic>): Promise<void> => {- this.#get().internal_dispatchTopic({ type: 'updateTopic', id, value: data });+ // The row is not necessarily in the active agent/group bucket — resolve the+ // one that holds it, so the optimistic write and the revalidation both land+ // where the topic is actually rendered (see `getTopicContainerKeyById`).+ const containerKey = topicSelectors.getTopicContainerKeyById(id)(this.#get());++ this.#get().internal_dispatchTopic({ type: 'updateTopic', id, value: data, containerKey });await topicService.updateTopic(id, data);- await this.#get().refreshTopic();+ await this.#get().refreshTopic(containerKey);};internal_updateTopicLinkedPullRequest = async (@@ -1574,11 +1587,13 @@ export class ChatTopicActionImpl {const { activeAgentId, activeGroupId } = this.#get();const scopedAgentId = payload.scope ? payload.agentId : (payload.agentId ?? activeAgentId);const scopedGroupId = payload.scope ? payload.groupId : (payload.groupId ?? activeGroupId);- const key = topicMapKey({- agentId: scopedAgentId,- groupId: scopedGroupId,- scope: payload.scope,- });+ const key =+ payload.containerKey ??+ topicMapKey({+ agentId: scopedAgentId,+ groupId: scopedGroupId,+ scope: payload.scope,+ });const currentData = this.#get().topicDataMap[key];const nextItems = topicReducer(currentData?.items, payload);diff --git a/src/store/chat/slices/topic/reducer.ts b/src/store/chat/slices/topic/reducer.tsindex 32dbea69e63..34dbf2466c4 100644--- a/src/store/chat/slices/topic/reducer.ts+++ b/src/store/chat/slices/topic/reducer.ts@@ -13,6 +13,12 @@ import { type ChatTopic, type CreateTopicParams } from '@/types/topic';*/interface ChatTopicScope {agentId?: string;+ /**+ * Pre-resolved `topicDataMap` key, taking precedence over the fields above.+ * For callers that hold a topic id but not its container coordinates — see+ * `topicSelectors.getTopicContainerKeyById`.+ */+ containerKey?: string;groupId?: string;scope?: TopicMapScope;}diff --git a/src/store/chat/slices/topic/selectors.ts b/src/store/chat/slices/topic/selectors.tsindex 49828e382f8..e8d30d764fb 100644--- a/src/store/chat/slices/topic/selectors.ts+++ b/src/store/chat/slices/topic/selectors.ts@@ -70,6 +70,25 @@ const getTopicById =}};+/**+ * The `topicDataMap` bucket that actually holds this topic, or undefined when+ * no loaded bucket does.+ *+ * Writes must target it rather than the active agent/group bucket: the Agent+ * Builder panels render a whole conversation for a builtin agent while+ * `activeAgentId` still points at the agent being edited, so a write keyed on+ * the active pair silently lands in a bucket without the row — the optimistic+ * update no-ops and the revalidation refreshes the wrong list, leaving the+ * panel showing a stale value forever (the server row having changed).+ */+const getTopicContainerKeyById =+ (id: string) =>+ (s: ChatStoreState): string | undefined => {+ for (const [key, data] of Object.entries(s.topicDataMap)) {+ if (data.items.some((item) => item.id === id)) return key;+ }+ };+/*** Get topics by specific agentId (for AgentBuilder scenarios where agentId differs from activeAgentId)*/@@ -344,6 +363,7 @@ export const topicSelectors = {displayTopics,displayTopicsForSidebar,getTopicById,+ getTopicContainerKeyById,getTopicModelById,getTopicWorkingDirectory,getTopicsByAgentId,diff --git a/src/store/home/slices/homeInput/action.test.ts b/src/store/home/slices/homeInput/action.test.tsindex 5b23433b59c..fac92e5b5f6 100644--- a/src/store/home/slices/homeInput/action.test.ts+++ b/src/store/home/slices/homeInput/action.test.ts@@ -320,7 +320,14 @@ describe('HomeInputActionImpl', () => {expect(navigateMock).toHaveBeenCalledWith('/group/group-new/profile');expect(sendMessageMock).toHaveBeenCalledWith(expect.objectContaining({- context: { agentId: 'groupAgentBuilder', scope: 'group_agent_builder' },+ context: {+ agentId: 'groupAgentBuilder',+ // Names the freshly created group so the builder topic is stamped+ // with it, instead of relying on the not-yet-mounted group route to+ // have set `chatStore.activeGroupId`.+ editingGroupId: 'group-new',+ scope: 'group_agent_builder',+ },message: 'build a research group',}),);@@ -335,6 +342,7 @@ describe('HomeInputActionImpl', () => {expect.objectContaining({context: {agentId: 'groupAgentBuilder',+ editingGroupId: 'group-new',scope: 'group_agent_builder',workspaceSlug: 'team',},diff --git a/src/store/home/slices/homeInput/action.ts b/src/store/home/slices/homeInput/action.tsindex 3215ac77ee2..172524b3659 100644--- a/src/store/home/slices/homeInput/action.ts+++ b/src/store/home/slices/homeInput/action.ts@@ -279,6 +279,12 @@ export class HomeInputActionImpl {await sendMessage({context: {agentId: groupAgentBuilderId,+ // Name the group explicitly rather than letting the transport read+ // `chatStore.activeGroupId`: the navigation above may not have+ // mounted the group layout yet, and an unset id here would create+ // the builder topic without its `editingGroupId` marker — invisible+ // in every group's topic list afterwards.+ editingGroupId: group.id,scope: 'group_agent_builder',...(workspaceSlug ? { workspaceSlug } : {}),},