Skip to content

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

✨ feat: workspace resource collaborators & permissions (#17192)

Rdmclin2b5f07d1379f7
diff --git a/apps/server/src/routers/lambda/__tests__/agent.test.ts b/apps/server/src/routers/lambda/__tests__/agent.test.ts
index 3116989901c..ab033fff29e 100644
--- a/apps/server/src/routers/lambda/__tests__/agent.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/agent.test.ts
@@ -1,4 +1,5 @@
// @vitest-environment node
+import { TRPCError } from '@trpc/server';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { INBOX_SESSION_ID } from '@/const/session';
@@ -7,18 +8,28 @@ import { AgentModel } from '@/database/models/agent';
import { ChatGroupModel } from '@/database/models/chatGroup';
import { FileModel } from '@/database/models/file';
import { KnowledgeBaseModel } from '@/database/models/knowledgeBase';
+import { ResourcePermissionModel } from '@/database/models/resourcePermission';
import { SessionModel } from '@/database/models/session';
import { TaskModel } from '@/database/models/task';
import { UserModel } from '@/database/models/user';
import { AgentService } from '@/server/services/agent';
import { EditLockService } from '@/server/services/editLock';
import { publishResourceEvent } from '@/server/services/resourceEvents';
+import {
+ assertCanEditResource,
+ assertCanPerformResourceAction,
+ canPerformResourceAction,
+ getResourceMeta,
+} from '@/server/services/resourcePermission';
import { hasWorkspaceScopedPermission } from '@/server/services/workspacePermission';
import { KnowledgeType } from '@/types/knowledgeBase';
import { agentRouter } from '../agent';
vi.mock('@/server/services/resourceEvents', () => ({ publishResourceEvent: vi.fn() }));
+vi.mock('../_helpers/workspaceAgentGuard', () => ({
+ getWorkspaceAgentParentGroupIds: vi.fn().mockResolvedValue([]),
+}));
const publishResourceEventMock = vi.mocked(publishResourceEvent);
@@ -52,6 +63,10 @@ vi.mock('@/database/models/knowledgeBase', () => ({
KnowledgeBaseModel: vi.fn(),
}));
+vi.mock('@/database/models/resourcePermission', () => ({
+ ResourcePermissionModel: vi.fn(),
+}));
+
vi.mock('@/server/services/agent', () => ({
AgentService: vi.fn(),
}));
@@ -60,6 +75,17 @@ vi.mock('@/server/services/workspacePermission', () => ({
hasWorkspaceScopedPermission: vi.fn(),
}));
+vi.mock('@/server/services/resourcePermission', () => ({
+ assertCanEditResource: vi.fn(),
+ assertCanPerformResourceAction: vi.fn(),
+ buildResourcePermissionState: vi.fn((params: any) => ({
+ ...params,
+ generalAccess: params.accessLevel === 'edit' ? 'editor' : 'viewer',
+ })),
+ canPerformResourceAction: vi.fn(),
+ getResourceMeta: vi.fn(),
+}));
+
describe('agentRouter', () => {
const userId = 'testUserId';
let mockCtx: any;
@@ -70,9 +96,22 @@ describe('agentRouter', () => {
let fileModelMock: any;
let knowledgeBaseModelMock: any;
let agentServiceMock: any;
+ let resourcePermissionModelMock: any;
beforeEach(() => {
vi.clearAllMocks();
+ vi.mocked(assertCanPerformResourceAction).mockResolvedValue();
+ vi.mocked(getResourceMeta).mockResolvedValue({
+ userId: 'creator-1',
+ visibility: 'public',
+ workspaceId: 'ws-1',
+ });
+ resourcePermissionModelMock = {
+ getEffectiveAccessLevel: vi.fn().mockResolvedValue('use'),
+ removeAll: vi.fn(),
+ setAccessLevel: vi.fn(),
+ };
+ vi.mocked(ResourcePermissionModel).mockImplementation(() => resourcePermissionModelMock);
agentModelMock = {
createAgentFiles: vi.fn(),
@@ -82,6 +121,7 @@ describe('agentRouter', () => {
findBySessionId: vi.fn(),
getAgentAssignedKnowledge: vi.fn(),
getAgentVisibility: vi.fn().mockResolvedValue(null),
+ publishToWorkspace: vi.fn(),
toggleFile: vi.fn(),
toggleKnowledgeBase: vi.fn(),
update: vi.fn(),
@@ -169,6 +209,59 @@ describe('agentRouter', () => {
});
});
+ describe('configuration read guard', () => {
+ const fullConfig = {
+ avatar: 'avatar.png',
+ id: 'agent-1',
+ model: 'private-model',
+ openingMessage: 'Hello',
+ plugins: ['private-tool'],
+ systemRole: 'private prompt',
+ title: 'Public title',
+ userId: 'creator-1',
+ visibility: 'public',
+ workspaceId: 'ws-1',
+ };
+
+ it('redacts getAgentConfigById for a member who can view but not edit', async () => {
+ agentServiceMock.getAgentConfigById = vi.fn().mockResolvedValue(fullConfig);
+ vi.mocked(canPerformResourceAction).mockResolvedValueOnce(false).mockResolvedValueOnce(true);
+
+ const caller = agentRouter.createCaller({
+ ...mockCtx,
+ serverDB: {},
+ workspaceId: 'ws-1',
+ });
+ const result = await caller.getAgentConfigById({ agentId: 'agent-1' });
+
+ expect(result).toEqual({
+ avatar: 'avatar.png',
+ id: 'agent-1',
+ openingMessage: 'Hello',
+ title: 'Public title',
+ userId: 'creator-1',
+ visibility: 'public',
+ workspaceId: 'ws-1',
+ });
+ expect(result).not.toHaveProperty('systemRole');
+ expect(result).not.toHaveProperty('plugins');
+ expect(result).not.toHaveProperty('model');
+ });
+
+ it('returns the full config to a member who can edit', async () => {
+ agentServiceMock.getAgentConfigById = vi.fn().mockResolvedValue(fullConfig);
+ vi.mocked(canPerformResourceAction).mockResolvedValueOnce(true);
+
+ const caller = agentRouter.createCaller({
+ ...mockCtx,
+ serverDB: {},
+ workspaceId: 'ws-1',
+ });
+
+ await expect(caller.getAgentConfigById({ agentId: 'agent-1' })).resolves.toEqual(fullConfig);
+ });
+ });
+
describe('getKnowledgeBasesAndFiles', () => {
it('should return combined knowledge bases and files', async () => {
const mockFiles = [
@@ -372,6 +465,40 @@ describe('agentRouter', () => {
});
});
+ describe('publishAgentToWorkspace', () => {
+ const wsCtx = () => ({ ...mockCtx, workspaceId: 'ws-1' });
+
+ it('writes general access only after the private agent is actually published', async () => {
+ agentModelMock.publishToWorkspace.mockResolvedValue({
+ id: 'agent-1',
+ visibility: 'public',
+ });
+
+ const caller = agentRouter.createCaller(wsCtx());
+ await caller.publishAgentToWorkspace({ accessLevel: 'view', id: 'agent-1' });
+
+ expect(resourcePermissionModelMock.setAccessLevel).toHaveBeenCalledWith(
+ 'agent',
+ 'agent-1',
+ 'view',
+ userId,
+ );
+ });
+
+ it('does not write general access when the guarded publish updates no row', async () => {
+ agentModelMock.publishToWorkspace.mockRejectedValue(
+ new Error('Agent not found, already published, or access denied'),
+ );
+
+ const caller = agentRouter.createCaller(wsCtx());
+
+ await expect(caller.publishAgentToWorkspace({ id: 'agent-1' })).rejects.toThrow(
+ 'Agent not found, already published, or access denied',
+ );
+ expect(resourcePermissionModelMock.setAccessLevel).not.toHaveBeenCalled();
+ });
+ });
+
describe('setAgentVisibility', () => {
const wsCtx = () => ({ ...mockCtx, workspaceId: 'ws-1' });
@@ -403,7 +530,13 @@ describe('agentRouter', () => {
const caller = agentRouter.createCaller(wsCtx());
const result = await caller.setAgentVisibility({ id: 'agent-1', visibility: 'private' });
- expect(result).toEqual({ success: true });
+ expect(result).toEqual({
+ accessLevel: 'edit',
+ canManage: true,
+ creatorId: userId,
+ generalAccess: 'editor',
+ visibility: 'private',
+ });
expect(agentModelMock.setVisibility).toHaveBeenCalledWith('agent-1', 'private');
});
@@ -429,6 +562,9 @@ describe('agentRouter', () => {
userId: 'other-member',
visibility: 'public',
});
+ vi.mocked(assertCanPerformResourceAction).mockRejectedValueOnce(
+ new TRPCError({ code: 'FORBIDDEN' }),
+ );
const caller = agentRouter.createCaller(wsCtx());
@@ -440,19 +576,21 @@ describe('agentRouter', () => {
expect(agentModelMock.setVisibility).not.toHaveBeenCalled();
});
- it('still allows a workspace owner to promote another member agent', async () => {
+ it('rejects promotion of another member agent even for a workspace owner', async () => {
agentModelMock.getAgentVisibilityMeta.mockResolvedValue({
slug: null,
userId: 'other-member',
visibility: 'private',
});
- vi.mocked(hasWorkspaceScopedPermission).mockResolvedValue(true);
+ vi.mocked(assertCanPerformResourceAction).mockRejectedValueOnce(
+ new TRPCError({ code: 'FORBIDDEN' }),
+ );
const caller = agentRouter.createCaller(wsCtx());
- const result = await caller.setAgentVisibility({ id: 'agent-1', visibility: 'public' });
-
- expect(result).toEqual({ success: true });
- expect(agentModelMock.setVisibility).toHaveBeenCalledWith('agent-1', 'public');
+ await expect(
+ caller.setAgentVisibility({ id: 'agent-1', visibility: 'public' }),
+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });
+ expect(agentModelMock.setVisibility).not.toHaveBeenCalled();
});
it('rejects promotion of another member agent for a plain member', async () => {
@@ -461,7 +599,9 @@ describe('agentRouter', () => {
userId: 'other-member',
visibility: 'private',
});
- vi.mocked(hasWorkspaceScopedPermission).mockResolvedValue(false);
+ vi.mocked(assertCanPerformResourceAction).mockRejectedValueOnce(
+ new TRPCError({ code: 'FORBIDDEN' }),
+ );
const caller = agentRouter.createCaller(wsCtx());
@@ -483,6 +623,35 @@ describe('agentRouter', () => {
expect(taskModelMock.countTasksBlockingAgentDemotion).not.toHaveBeenCalled();
expect(agentModelMock.setVisibility).toHaveBeenCalledWith('agent-1', 'public');
+ expect(resourcePermissionModelMock.setAccessLevel).toHaveBeenCalledWith(
+ 'agent',
+ 'agent-1',
+ 'use',
+ userId,
+ );
+ });
+
+ it('stores explicit view access when publishing an agent', async () => {
+ agentModelMock.getAgentVisibilityMeta.mockResolvedValue({
+ slug: null,
+ userId,
+ visibility: 'private',
+ });
+
+ const caller = agentRouter.createCaller(wsCtx());
+ await caller.setAgentVisibility({
+ accessLevel: 'view',
+ id: 'agent-1',
+ visibility: 'public',
+ });
+
+ expect(agentModelMock.setVisibility).toHaveBeenCalledWith('agent-1', 'public');
+ expect(resourcePermissionModelMock.setAccessLevel).toHaveBeenCalledWith(
+ 'agent',
+ 'agent-1',
+ 'view',
+ userId,
+ );
});
});
@@ -490,6 +659,31 @@ describe('agentRouter', () => {
const wsCtx = () => ({ ...mockCtx, workspaceId: 'ws-1' });
describe('updateAgentConfig write guard', () => {
+ it('rejects the update when general access is use-only for the caller', async () => {
+ agentServiceMock.updateAgentConfig = vi.fn().mockResolvedValue({ id: 'agent-1' });
+ const { TRPCError } = await import('@trpc/server');
+ vi.mocked(assertCanEditResource).mockRejectedValueOnce(
+ new TRPCError({
+ code: 'FORBIDDEN',
+ message: 'This resource is use-only for workspace members',
+ }),
+ );
+
+ const caller = agentRouter.createCaller(wsCtx());
+
+ await expect(
+ caller.updateAgentConfig({ agentId: 'agent-1', value: { systemRole: 'x' } }),
+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });
+ expect(assertCanEditResource).toHaveBeenCalledWith(
+ expect.objectContaining({
+ resourceId: 'agent-1',
+ resourceType: 'agent',
+ workspaceId: 'ws-1',
+ }),
+ );
+ expect(agentServiceMock.updateAgentConfig).not.toHaveBeenCalled();
+ });
+
it('rejects the update when another member holds the lock', async () => {
agentServiceMock.updateAgentConfig = vi.fn().mockResolvedValue({ id: 'agent-1' });
vi.spyOn(EditLockService.prototype, 'getBlockingHolder').mockResolvedValue('other-user');
diff --git a/apps/server/src/routers/lambda/__tests__/agentGroup.test.ts b/apps/server/src/routers/lambda/__tests__/agentGroup.test.ts
index d0923766bc5..ab3e9b2b4ac 100644
--- a/apps/server/src/routers/lambda/__tests__/agentGroup.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/agentGroup.test.ts
@@ -9,10 +9,26 @@ 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 { agentGroupRouter } from '../agentGroup';
vi.mock('@/server/services/resourceEvents', () => ({ publishResourceEvent: vi.fn() }));
+vi.mock('../_helpers/workspaceAgentGuard', () => ({
+ getWorkspaceAgentParentGroupIds: vi.fn().mockResolvedValue([]),
+}));
+
+vi.mock('@/server/services/resourcePermission', () => ({
+ assertCanEditResource: vi.fn(),
+ assertCanPerformResourceAction: vi.fn(),
+ buildResourcePermissionState: vi.fn((params: any) => ({
+ ...params,
+ generalAccess: params.accessLevel === 'edit' ? 'editor' : 'viewer',
+ })),
+ canPerformResourceAction: vi.fn(),
+ getResourceMeta: vi.fn(),
+}));
const publishResourceEventMock = vi.mocked(publishResourceEvent);
@@ -27,6 +43,7 @@ describe('agentGroupRouter', () => {
beforeEach(() => {
vi.restoreAllMocks();
+ vi.mocked(getWorkspaceAgentParentGroupIds).mockResolvedValue([]);
agentModelMock = {
batchCreate: vi.fn(),
@@ -258,6 +275,91 @@ describe('agentGroupRouter', () => {
expect(result).toBeNull();
});
+
+ it('redacts group and member configuration for a member without edit access', async () => {
+ const fullGroupDetail = {
+ agents: [
+ {
+ id: 'agent-1',
+ isSupervisor: true,
+ model: 'private-model',
+ plugins: ['private-tool'],
+ systemRole: 'private member prompt',
+ title: 'Agent 1',
+ },
+ ],
+ config: { openingMessage: 'Welcome', systemPrompt: 'private group prompt' },
+ content: 'private editor content',
+ id: 'group-1',
+ supervisorAgentId: 'agent-1',
+ title: 'Test Group',
+ userId: 'creator-1',
+ visibility: 'public',
+ workspaceId: 'ws-1',
+ };
+ chatGroupServiceMock.getGroupDetail.mockResolvedValue(fullGroupDetail);
+ vi.mocked(canPerformResourceAction).mockResolvedValueOnce(false).mockResolvedValueOnce(true);
+
+ const caller = agentGroupRouter.createCaller({ ...mockCtx, workspaceId: 'ws-1' });
+ const result = await caller.getGroupDetail({ id: 'group-1' });
+
+ expect(result).toEqual({
+ agents: [{ id: 'agent-1', isSupervisor: true, title: 'Agent 1' }],
+ config: { openingMessage: 'Welcome' },
+ id: 'group-1',
+ supervisorAgentId: 'agent-1',
+ title: 'Test Group',
+ userId: 'creator-1',
+ visibility: 'public',
+ workspaceId: 'ws-1',
+ });
+ expect(userModelMock.getUserSettingsDefaultAgentConfig).not.toHaveBeenCalled();
+ });
+
+ it('keeps editable group config but redacts separately restricted member agents', async () => {
+ const fullGroupDetail = {
+ agents: [
+ {
+ id: 'agent-1',
+ model: 'private-model',
+ systemRole: 'private member prompt',
+ title: 'Agent 1',
+ userId: 'creator-1',
+ visibility: 'public',
+ workspaceId: 'ws-1',
+ },
+ ],
+ config: { systemPrompt: 'editable group prompt' },
+ id: 'group-1',
+ title: 'Test Group',
+ userId: 'creator-1',
+ visibility: 'public',
+ workspaceId: 'ws-1',
+ };
+ chatGroupServiceMock.getGroupDetail.mockResolvedValue(fullGroupDetail);
+ vi.mocked(canPerformResourceAction)
+ .mockResolvedValueOnce(true)
+ .mockResolvedValueOnce(false)
+ .mockResolvedValueOnce(true);
+
+ const caller = agentGroupRouter.createCaller({ ...mockCtx, workspaceId: 'ws-1' });
+ const result = await caller.getGroupDetail({ id: 'group-1' });
+
+ expect(result).toEqual({
+ ...fullGroupDetail,
+ agents: [
+ {
+ id: 'agent-1',
+ title: 'Agent 1',
+ userId: 'creator-1',
+ visibility: 'public',
+ workspaceId: 'ws-1',
+ },
+ ],
+ });
+ expect(result?.config).toEqual({ systemPrompt: 'editable group prompt' });
+ expect(result?.agents[0]).not.toHaveProperty('systemRole');
+ });
});
describe('getGroupAgents', () => {
@@ -292,6 +394,38 @@ describe('agentGroupRouter', () => {
expect(chatGroupServiceMock.getGroups).toHaveBeenCalled();
expect(result).toEqual(mockGroups);
});
+
+ it('redacts config-bearing list results for use/view-only members', async () => {
+ const groups = [
+ {
+ agents: [{ id: 'agent-1', systemRole: 'private prompt', title: 'Agent 1' }],
+ config: { systemPrompt: 'private group prompt' },
+ id: 'group-1',
+ title: 'Group 1',
+ userId: 'creator-1',
+ visibility: 'public',
+ workspaceId: 'ws-1',
+ },
+ ];
+ chatGroupServiceMock.getGroups.mockResolvedValue(groups);
+ vi.mocked(canPerformResourceAction).mockResolvedValueOnce(false).mockResolvedValueOnce(true);
+
+ const caller = agentGroupRouter.createCaller({ ...mockCtx, workspaceId: 'ws-1' });
+ const result = await caller.getGroups();
+
+ expect(result).toEqual([
+ {
+ agents: [{ id: 'agent-1', title: 'Agent 1' }],
+ config: {},
+ id: 'group-1',
+ title: 'Group 1',
+ userId: 'creator-1',
+ visibility: 'public',
+ workspaceId: 'ws-1',
+ },
+ ]);
+ expect(userModelMock.getUserSettingsDefaultAgentConfig).not.toHaveBeenCalled();
+ });
});
describe('addAgentsToGroup', () => {
diff --git a/apps/server/src/routers/lambda/__tests__/aiAgent.test.ts b/apps/server/src/routers/lambda/__tests__/aiAgent.test.ts
index cfac3810b99..9725786afe4 100644
--- a/apps/server/src/routers/lambda/__tests__/aiAgent.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/aiAgent.test.ts
@@ -7,12 +7,19 @@ import {
sessions,
threads,
topics,
+ workspaces,
} from '@lobechat/database/schemas';
import { getTestDB } from '@lobechat/database/test-utils';
+import { TRPCError } from '@trpc/server';
import { eq } from 'drizzle-orm';
import type * as ModelBankModule from 'model-bank';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import {
+ assertCanPerformResourceAction,
+ getResourceMeta,
+} from '@/server/services/resourcePermission';
+
import { aiAgentRouter } from '../aiAgent';
import { cleanupTestUser, createTestUser } from './integration/setup';
@@ -60,6 +67,14 @@ vi.mock('@/server/services/file', () => ({
})),
}));
+// Mock the resource-permission guard so workspace-mode tests can assert the
+// router resolves slug → agent id and runs the `use` guard (the guard's own
+// RBAC evaluation is covered by its service tests).
+vi.mock('@/server/services/resourcePermission', () => ({
+ assertCanPerformResourceAction: vi.fn(),
+ getResourceMeta: vi.fn(),
+}));
+
// Mock model-bank with dynamic import to preserve other exports
vi.mock('model-bank', async (importOriginal) => {
const actual = await importOriginal<typeof ModelBankModule>();
@@ -434,6 +449,114 @@ describe('AI Agent Router Integration Tests', () => {
});
});
+ describe('execAgent workspace use guard', () => {
+ let workspaceId: string;
+ let wsAgentId: string;
+
+ beforeEach(async () => {
+ const [workspace] = await serverDB
+ .insert(workspaces)
+ .values({ name: 'Test Workspace', primaryOwnerId: userId, slug: `ws-${userId}` })
+ .returning();
+ workspaceId = workspace.id;
+
+ const [wsAgent] = await serverDB
+ .insert(agents)
+ .values({
+ model: 'gpt-4o-mini',
+ provider: 'openai',
+ slug: 'ws-helper',
+ title: 'Workspace Agent',
+ userId,
+ visibility: 'public',
+ workspaceId,
+ })
+ .returning();
+ wsAgentId = wsAgent.id;
+ vi.mocked(getResourceMeta).mockResolvedValue({
+ userId,
+ visibility: 'public',
+ workspaceId,
+ });
+ });
+
+ const wsCtx = () => ({ ...createTestContext(), workspaceId });
+
+ it('runs the use guard on the agent resolved from a slug-only call', async () => {
+ vi.mocked(assertCanPerformResourceAction).mockRejectedValueOnce(
+ new TRPCError({ code: 'FORBIDDEN', message: 'denied' }),
+ );
+
+ const caller = aiAgentRouter.createCaller(wsCtx());
+
+ await expect(caller.execAgent({ prompt: 'hi', slug: 'ws-helper' })).rejects.toMatchObject({
+ code: 'FORBIDDEN',
+ });
+
+ expect(assertCanPerformResourceAction).toHaveBeenCalledWith(
+ expect.objectContaining({
+ action: 'use',
+ resourceId: wsAgentId,
+ resourceType: 'agent',
+ userId,
+ workspaceId,
+ }),
+ );
+ });
+
+ it('rejects an agent run that appends to a view-only topic', async () => {
+ const [topic] = await serverDB
+ .insert(topics)
+ .values({
+ agentId: wsAgentId,
+ title: 'View-only topic',
+ userId,
+ workspaceId,
+ })
+ .returning();
+ vi.mocked(assertCanPerformResourceAction)
+ .mockResolvedValueOnce(undefined)
+ .mockRejectedValueOnce(new TRPCError({ code: 'FORBIDDEN', message: 'denied' }));
+
+ const caller = aiAgentRouter.createCaller(wsCtx());
+
+ await expect(
+ caller.execAgent({
+ agentId: wsAgentId,
+ appContext: { topicId: topic.id },
+ prompt: 'hi',
+ }),
+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });
+
+ expect(assertCanPerformResourceAction).toHaveBeenNthCalledWith(
+ 2,
+ expect.objectContaining({
+ action: 'use',
+ resourceId: wsAgentId,
+ resourceType: 'agent',
+ userId,
+ workspaceId,
+ }),
+ );
+ });
+
+ it('lets an unresolvable slug fall through without running the guard', async () => {
+ const caller = aiAgentRouter.createCaller(wsCtx());
+
+ await expect(caller.execAgent({ prompt: 'hi', slug: 'missing-slug' })).rejects.toThrow();
+
+ expect(assertCanPerformResourceAction).not.toHaveBeenCalled();
+ });
+
+ it('does not run the guard in personal mode', async () => {
+ const caller = aiAgentRouter.createCaller(createTestContext());
+
+ await caller.execAgent({ agentId: testAgentId, prompt: 'hi' });
+
+ expect(assertCanPerformResourceAction).not.toHaveBeenCalled();
+ });
+ });
+
describe('heteroIngest/heteroFinish ownership guard', () => {
// Build a context that drives heteroOperationAuth to the desired kind:
// - omit `purpose` → a normal user OIDC token → kind 'user' (ownership-gated)
diff --git a/apps/server/src/routers/lambda/__tests__/document.test.ts b/apps/server/src/routers/lambda/__tests__/document.test.ts
new file mode 100644
index 00000000000..b488cfdf084
--- /dev/null
+++ b/apps/server/src/routers/lambda/__tests__/document.test.ts
@@ -0,0 +1,167 @@
+// @vitest-environment node
+import { TRPCError } from '@trpc/server';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { TransferErrorCode } from '@/types/transferError';
+
+const mocks = vi.hoisted(() => ({
+ assertCanEditResource: vi.fn(),
+ assertCanPerformResourceAction: vi.fn(),
+ businessFileTransferStorageCheck: vi.fn(),
+ countFileUsageInSubtree: vi.fn(),
+ findById: vi.fn(),
+ getResourceMeta: vi.fn(),
+ subtreeHasForeignRows: vi.fn(),
+ transferTo: vi.fn(),
+ updateDocument: vi.fn(),
+}));
+
+vi.mock('@/business/server/lambda-routers/file', () => ({
+ businessFileTransferStorageCheck: mocks.businessFileTransferStorageCheck,
+}));
+vi.mock('@/database/models/chunk', () => ({ ChunkModel: vi.fn(() => ({})) }));
+vi.mock('@/database/models/document', () => ({
+ DocumentModel: vi.fn(() => ({
+ countFileUsageInSubtree: mocks.countFileUsageInSubtree,
+ findById: mocks.findById,
+ subtreeHasForeignRows: mocks.subtreeHasForeignRows,
+ transferTo: mocks.transferTo,
+ })),
+}));
+vi.mock('@/database/models/file', () => ({ FileModel: vi.fn(() => ({})) }));
+vi.mock('@/database/models/message', () => ({ MessageModel: vi.fn(() => ({})) }));
+vi.mock('@/database/models/resourcePermission', () => ({
+ ResourcePermissionModel: vi.fn(() => ({ removeAll: vi.fn(), setAccessLevel: vi.fn() })),
+}));
+vi.mock('@/server/services/document', () => ({
+ DocumentService: vi.fn(() => ({ updateDocument: mocks.updateDocument })),
+}));
+vi.mock('@/server/services/resourcePermission', () => ({
+ assertCanEditResource: mocks.assertCanEditResource,
+ assertCanPerformResourceAction: mocks.assertCanPerformResourceAction,
+ buildResourcePermissionState: vi.fn(),
+ getResourceMeta: mocks.getResourceMeta,
+}));
+vi.mock('@/server/services/workspacePermission', () => ({
+ hasWorkspaceScopedPermission: vi.fn(),
+}));
+
+const { documentRouter } = await import('../document');
+
+describe('documentRouter transferDocument', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.assertCanPerformResourceAction.mockResolvedValue(undefined);
+ mocks.assertCanEditResource.mockResolvedValue(undefined);
+ mocks.findById.mockResolvedValue({
+ id: 'doc-1',
+ parentId: 'old-parent',
+ userId: 'member-1',
+ visibility: 'public',
+ workspaceId: 'ws-1',
+ });
+ mocks.getResourceMeta.mockResolvedValue({
+ userId: 'creator-1',
+ visibility: 'public',
+ workspaceId: 'ws-1',
+ });
+ mocks.subtreeHasForeignRows.mockResolvedValue(false);
+ });
+
+ it('blocks a non-owner from transferring a tree containing foreign rows', async () => {
+ mocks.subtreeHasForeignRows.mockResolvedValueOnce(true);
+ const caller = documentRouter.createCaller({
+ serverDB: {},
+ userId: 'member-1',
+ workspaceId: 'ws-1',
+ workspaceRole: 'member',
+ } as any);
+
+ await expect(
+ caller.transferDocument({ documentId: 'doc-1', targetWorkspaceId: null }),
+ ).rejects.toMatchObject({
+ cause: { data: { code: TransferErrorCode.OwnerOnly } },
+ code: 'FORBIDDEN',
+ });
+
+ expect(mocks.subtreeHasForeignRows).toHaveBeenCalledWith('doc-1');
+ expect(mocks.countFileUsageInSubtree).not.toHaveBeenCalled();
+ expect(mocks.transferTo).not.toHaveBeenCalled();
+ });
+
+ it('checks edit access on both the source and destination parents before moving a document', async () => {
+ mocks.assertCanEditResource
+ .mockResolvedValueOnce(undefined) // the document itself
+ .mockResolvedValueOnce(undefined) // the current (source) parent
+ .mockRejectedValueOnce(new TRPCError({ code: 'FORBIDDEN' })); // the destination parent
+ const caller = documentRouter.createCaller({
+ serverDB: {},
+ userId: 'member-1',
+ workspaceId: 'ws-1',
+ workspaceRole: 'member',
+ } as any);
+
+ await expect(
+ caller.updateDocument({ id: 'doc-1', parentId: 'view-only-folder' }),
+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });
+
+ expect(mocks.findById).toHaveBeenCalledWith('doc-1');
+ expect(mocks.assertCanEditResource).toHaveBeenNthCalledWith(
+ 2,
+ expect.objectContaining({
+ resourceId: 'old-parent',
+ resourceType: 'document',
+ workspaceId: 'ws-1',
+ }),
+ );
+ expect(mocks.assertCanEditResource).toHaveBeenNthCalledWith(
+ 3,
+ expect.objectContaining({
+ resourceId: 'view-only-folder',
+ resourceType: 'document',
+ workspaceId: 'ws-1',
+ }),
+ );
+ expect(mocks.updateDocument).not.toHaveBeenCalled();
+ });
+
+ it('checks edit access on the source parent when detaching a document (parentId: null)', async () => {
+ mocks.assertCanEditResource
+ .mockResolvedValueOnce(undefined) // the document itself
+ .mockRejectedValueOnce(new TRPCError({ code: 'FORBIDDEN' })); // the current parent
+ const caller = documentRouter.createCaller({
+ serverDB: {},
+ userId: 'member-1',
+ workspaceId: 'ws-1',
+ workspaceRole: 'member',
+ } as any);
+
+ await expect(caller.updateDocument({ id: 'doc-1', parentId: null })).rejects.toMatchObject({
+ code: 'FORBIDDEN',
+ });
+
+ expect(mocks.assertCanEditResource).toHaveBeenNthCalledWith(
+ 2,
+ expect.objectContaining({ resourceId: 'old-parent', resourceType: 'document' }),
+ );
+ expect(mocks.updateDocument).not.toHaveBeenCalled();
+ });
+
+ it('does not re-check the parent when an ordinary update includes the current parent', async () => {
+ const caller = documentRouter.createCaller({
+ serverDB: {},
+ userId: 'member-1',
+ workspaceId: 'ws-1',
+ workspaceRole: 'member',
+ } as any);
+
+ await caller.updateDocument({ id: 'doc-1', parentId: 'old-parent', title: 'Renamed' });
+
+ expect(mocks.assertCanEditResource).toHaveBeenCalledTimes(1);
+ expect(mocks.updateDocument).toHaveBeenCalledWith('doc-1', {
+ editorData: undefined,
+ parentId: 'old-parent',
+ title: 'Renamed',
+ });
+ });
+});
diff --git a/apps/server/src/routers/lambda/__tests__/file.test.ts b/apps/server/src/routers/lambda/__tests__/file.test.ts
index 4c1c50f0621..841d809fabc 100644
--- a/apps/server/src/routers/lambda/__tests__/file.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/file.test.ts
@@ -221,6 +221,12 @@ vi.mock('@/server/services/document', () => ({
})),
}));
+const mockAssertCanPerformResourceAction = vi.hoisted(() => vi.fn());
+
+vi.mock('@/server/services/resourcePermission', () => ({
+ assertCanPerformResourceAction: mockAssertCanPerformResourceAction,
+}));
+
describe('fileRouter', () => {
let ctx: any;
let caller: any;
@@ -920,6 +926,15 @@ describe('fileRouter', () => {
});
expect(mockDocumentModelFindById).toHaveBeenCalledWith('doc-1');
+ expect(mockAssertCanPerformResourceAction).toHaveBeenCalledWith(
+ expect.objectContaining({
+ action: 'transfer',
+ resourceId: 'doc-1',
+ resourceType: 'document',
+ userId: 'test-user',
+ workspaceId: 'workspace-active',
+ }),
+ );
expect(mockDocumentModelCountFileUsageInSubtree).toHaveBeenCalledWith('doc-1');
expect(routerMocks.businessFileTransferStorageCheck).toHaveBeenCalledWith({
additionalSize: 4096,
diff --git a/apps/server/src/routers/lambda/__tests__/session.test.ts b/apps/server/src/routers/lambda/__tests__/session.test.ts
new file mode 100644
index 00000000000..19511f173e8
--- /dev/null
+++ b/apps/server/src/routers/lambda/__tests__/session.test.ts
@@ -0,0 +1,124 @@
+// @vitest-environment node
+import { TRPCError } from '@trpc/server';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { SessionModel } from '@/database/models/session';
+import { SessionGroupModel } from '@/database/models/sessionGroup';
+import { assertCanEditResource } from '@/server/services/resourcePermission';
+
+import { sessionRouter } from '../session';
+
+vi.mock('@/database/core/db-adaptor', () => ({
+ getServerDB: vi.fn(async () => ({})),
+}));
+
+vi.mock('@/database/models/session', () => ({
+ SessionModel: vi.fn(),
+}));
+
+vi.mock('@/database/models/sessionGroup', () => ({
+ SessionGroupModel: vi.fn(),
+}));
+
+vi.mock('@/server/services/resourcePermission', () => ({
+ assertCanEditResource: vi.fn(),
+}));
+
+describe('sessionRouter', () => {
+ const userId = 'testUserId';
+ let sessionModelMock: any;
+ let mockCtx: any;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ vi.mocked(assertCanEditResource).mockResolvedValue();
+
+ sessionModelMock = {
+ findByIdOrSlug: vi.fn(),
+ updateConfig: vi.fn().mockResolvedValue(undefined),
+ };
+ vi.mocked(SessionModel).mockImplementation(() => sessionModelMock);
+ vi.mocked(SessionGroupModel).mockImplementation(() => ({}) as any);
+
+ mockCtx = {
+ jwtPayload: { userId },
+ userId,
+ };
+ });
+
+ describe('updateSessionConfig workspace edit guard', () => {
+ it('requires edit on the linked agent in workspace mode', async () => {
+ sessionModelMock.findByIdOrSlug.mockResolvedValue({
+ agent: { id: 'agent-1' },
+ id: 'session-1',
+ });
+
+ const caller = sessionRouter.createCaller({ ...mockCtx, workspaceId: 'ws-1' });
+ await caller.updateSessionConfig({ id: 'session-1', value: { model: 'gpt-4o-mini' } });
+
+ expect(assertCanEditResource).toHaveBeenCalledWith(
+ expect.objectContaining({
+ resourceId: 'agent-1',
+ resourceType: 'agent',
+ userId,
+ workspaceId: 'ws-1',
+ }),
+ );
+ expect(sessionModelMock.updateConfig).toHaveBeenCalledWith('session-1', {
+ model: 'gpt-4o-mini',
+ });
+ });
+
+ it('blocks the write when the guard denies edit', async () => {
+ sessionModelMock.findByIdOrSlug.mockResolvedValue({
+ agent: { id: 'agent-1' },
+ id: 'session-1',
+ });
+ vi.mocked(assertCanEditResource).mockRejectedValue(
+ new TRPCError({ code: 'FORBIDDEN', message: 'denied' }),
+ );
+
+ const caller = sessionRouter.createCaller({ ...mockCtx, workspaceId: 'ws-1' });
+
+ await expect(
+ caller.updateSessionConfig({ id: 'session-1', value: { model: 'gpt-4o-mini' } }),
+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });
+
+ expect(sessionModelMock.updateConfig).not.toHaveBeenCalled();
+ });
+
+ it('skips the guard in personal mode', async () => {
+ const caller = sessionRouter.createCaller(mockCtx);
+ await caller.updateSessionConfig({ id: 'session-1', value: { model: 'gpt-4o-mini' } });
+
+ expect(sessionModelMock.findByIdOrSlug).not.toHaveBeenCalled();
+ expect(assertCanEditResource).not.toHaveBeenCalled();
+ expect(sessionModelMock.updateConfig).toHaveBeenCalled();
+ });
+ });
+
+ describe('updateSessionChatConfig workspace edit guard', () => {
+ it('requires edit on the linked agent in workspace mode', async () => {
+ sessionModelMock.findByIdOrSlug.mockResolvedValue({
+ agent: { id: 'agent-1' },
+ id: 'session-1',
+ });
+
+ const caller = sessionRouter.createCaller({ ...mockCtx, workspaceId: 'ws-1' });
+ await caller.updateSessionChatConfig({ id: 'session-1', value: { historyCount: 4 } });
+
+ expect(assertCanEditResource).toHaveBeenCalledWith(
+ expect.objectContaining({
+ resourceId: 'agent-1',
+ resourceType: 'agent',
+ userId,
+ workspaceId: 'ws-1',
+ }),
+ );
+ // The input schema fills other chatConfig defaults; only assert ours.
+ expect(sessionModelMock.updateConfig).toHaveBeenCalledWith('session-1', {
+ chatConfig: expect.objectContaining({ historyCount: 4 }),
+ });
+ });
+ });
+});
diff --git a/apps/server/src/routers/lambda/_helpers/conversationResourceGuard.test.ts b/apps/server/src/routers/lambda/_helpers/conversationResourceGuard.test.ts
new file mode 100644
index 00000000000..1f35eda24cb
--- /dev/null
+++ b/apps/server/src/routers/lambda/_helpers/conversationResourceGuard.test.ts
@@ -0,0 +1,221 @@
+// @vitest-environment node
+import { TRPCError } from '@trpc/server';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ assertCanPerformResourceAction,
+ getResourceMeta,
+} from '@/server/services/resourcePermission';
+
+import {
+ assertCanUseConversationTargets,
+ assertCanUseCreateMessageTargets,
+ assertCanUseMessageTargets,
+ assertCanUseSessionTargets,
+ assertCanUseTopicTargets,
+} from './conversationResourceGuard';
+import { getWorkspaceAgentParentGroupIds } from './workspaceAgentGuard';
+
+vi.mock('@/server/services/resourcePermission', () => ({
+ assertCanPerformResourceAction: vi.fn(),
+ getResourceMeta: vi.fn(),
+}));
+vi.mock('./workspaceAgentGuard', () => ({
+ getWorkspaceAgentParentGroupIds: vi.fn(),
+}));
+
+const getResourceMetaMock = vi.mocked(getResourceMeta);
+const assertActionMock = vi.mocked(assertCanPerformResourceAction);
+const getParentGroupIdsMock = vi.mocked(getWorkspaceAgentParentGroupIds);
+
+/** Minimal drizzle stub: every select().from().where() resolves `rows`. */
+const createDb = (rowsPerCall: any[][]) => {
+ let call = 0;
+ return {
+ select: () => ({
+ from: () => ({
+ where: async () => rowsPerCall[call++] ?? [],
+ }),
+ }),
+ } as any;
+};
+
+const baseCtx = (db: any, workspaceId: string | null = 'ws-1') => ({
+ db,
+ userId: 'user-1',
+ workspaceId,
+});
+
+const wsMeta = { userId: 'creator', visibility: 'public', workspaceId: 'ws-1' };
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ getResourceMetaMock.mockResolvedValue(wsMeta as any);
+ getParentGroupIdsMock.mockResolvedValue([]);
+});
+
+describe('assertCanUseConversationTargets', () => {
+ it('no-ops in personal mode', async () => {
+ await assertCanUseConversationTargets(baseCtx(createDb([]), null), [{ agentId: 'agent-1' }]);
+
+ expect(getResourceMetaMock).not.toHaveBeenCalled();
+ expect(assertActionMock).not.toHaveBeenCalled();
+ });
+
+ it('asserts `use` on the agent of each deduped target', async () => {
+ await assertCanUseConversationTargets(baseCtx(createDb([])), [
+ { agentId: 'agent-1' },
+ { agentId: 'agent-1' },
+ ]);
+
+ expect(assertActionMock).toHaveBeenCalledTimes(1);
+ expect(assertActionMock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ action: 'use',
+ resourceId: 'agent-1',
+ resourceType: 'agent',
+ userId: 'user-1',
+ workspaceId: 'ws-1',
+ }),
+ );
+ });
+
+ it('checks both the group and agent when both contexts are supplied', async () => {
+ await assertCanUseConversationTargets(baseCtx(createDb([])), [
+ { agentId: 'supervisor-1', groupId: 'group-1' },
+ ]);
+
+ expect(assertActionMock).toHaveBeenCalledTimes(2);
+ expect(assertActionMock).toHaveBeenCalledWith(
+ expect.objectContaining({ resourceId: 'group-1', resourceType: 'agentGroup' }),
+ );
+ expect(assertActionMock).toHaveBeenCalledWith(
+ expect.objectContaining({ resourceId: 'supervisor-1', resourceType: 'agent' }),
+ );
+ });
+
+ it('also checks parent groups for an agent-only virtual member target', async () => {
+ getParentGroupIdsMock.mockResolvedValueOnce(['group-1']);
+
+ await assertCanUseConversationTargets(baseCtx(createDb([])), [{ agentId: 'agent-1' }]);
+
+ expect(assertActionMock).toHaveBeenCalledTimes(2);
+ expect(assertActionMock).toHaveBeenCalledWith(
+ expect.objectContaining({ resourceId: 'agent-1', resourceType: 'agent' }),
+ );
+ expect(assertActionMock).toHaveBeenCalledWith(
+ expect.objectContaining({ resourceId: 'group-1', resourceType: 'agentGroup' }),
+ );
+ });
+
+ it('skips resources that do not belong to the current workspace', async () => {
+ getResourceMetaMock.mockResolvedValueOnce({ ...wsMeta, workspaceId: 'other-ws' } as any);
+
+ await assertCanUseConversationTargets(baseCtx(createDb([])), [{ agentId: 'agent-1' }]);
+
+ expect(assertActionMock).not.toHaveBeenCalled();
+ });
+
+ it('propagates FORBIDDEN from the permission assert', async () => {
+ assertActionMock.mockRejectedValueOnce(new TRPCError({ code: 'FORBIDDEN' }));
+
+ await expect(
+ assertCanUseConversationTargets(baseCtx(createDb([])), [{ agentId: 'agent-1' }]),
+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });
+ });
+});
+
+describe('assertCanUseMessageTargets', () => {
+ it('resolves the owning agent from the message rows', async () => {
+ const db = createDb([[{ agentId: 'agent-1', groupId: null, topicId: 't-1' }]]);
+
+ await assertCanUseMessageTargets(baseCtx(db), ['msg-1']);
+
+ expect(assertActionMock).toHaveBeenCalledWith(
+ expect.objectContaining({ resourceId: 'agent-1', resourceType: 'agent' }),
+ );
+ });
+
+ it('falls back to the topic linkage when the row has no agent/group', async () => {
+ const db = createDb([
+ [{ agentId: null, groupId: null, topicId: 't-1' }],
+ [{ agentId: 'agent-2', groupId: null }],
+ ]);
+
+ await assertCanUseMessageTargets(baseCtx(db), ['msg-1']);
+
+ expect(assertActionMock).toHaveBeenCalledWith(
+ expect.objectContaining({ resourceId: 'agent-2', resourceType: 'agent' }),
+ );
+ });
+
+ it('no-ops without ids or workspace', async () => {
+ await assertCanUseMessageTargets(baseCtx(createDb([]), null), ['msg-1']);
+ await assertCanUseMessageTargets(baseCtx(createDb([])), []);
+
+ expect(assertActionMock).not.toHaveBeenCalled();
+ });
+});
+
+describe('assertCanUseTopicTargets', () => {
+ it('resolves the owning group from the topic rows', async () => {
+ const db = createDb([[{ agentId: null, groupId: 'group-1' }]]);
+
+ await assertCanUseTopicTargets(baseCtx(db), ['t-1']);
+
+ expect(assertActionMock).toHaveBeenCalledWith(
+ expect.objectContaining({ resourceId: 'group-1', resourceType: 'agentGroup' }),
+ );
+ });
+});
+
+describe('assertCanUseSessionTargets', () => {
+ it('resolves the linked agent from agentsToSessions and asserts use', async () => {
+ const db = createDb([[{ agentId: 'agent-1' }]]);
+
+ await assertCanUseSessionTargets(baseCtx(db), ['session-1']);
+
+ expect(assertActionMock).toHaveBeenCalledWith(
+ expect.objectContaining({ action: 'use', resourceId: 'agent-1', resourceType: 'agent' }),
+ );
+ });
+
+ it('no-ops without ids or workspace', async () => {
+ await assertCanUseSessionTargets(baseCtx(createDb([]), null), ['session-1']);
+ await assertCanUseSessionTargets(baseCtx(createDb([])), []);
+
+ expect(assertActionMock).not.toHaveBeenCalled();
+ });
+});
+
+describe('assertCanUseCreateMessageTargets', () => {
+ it('guards topic and existing parent rows even when explicit context is omitted', async () => {
+ const db = createDb([
+ [{ agentId: null, groupId: 'group-1', sessionId: null }],
+ [{ agentId: 'agent-2', groupId: null, topicId: 'topic-1' }],
+ ]);
+
+ await assertCanUseCreateMessageTargets(baseCtx(db), [
+ { parentId: 'parent-1', topicId: 'topic-1' },
+ ]);
+
+ expect(assertActionMock).toHaveBeenCalledWith(
+ expect.objectContaining({ resourceId: 'group-1', resourceType: 'agentGroup' }),
+ );
+ expect(assertActionMock).toHaveBeenCalledWith(
+ expect.objectContaining({ resourceId: 'agent-2', resourceType: 'agent' }),
+ );
+ });
+
+ it('also guards the explicit target so forged context cannot replace row authority', async () => {
+ const db = createDb([[], []]);
+
+ await assertCanUseCreateMessageTargets(baseCtx(db), [
+ { agentId: 'agent-1', parentId: 'parent-1', topicId: 'topic-1' },
+ ]);
+
+ expect(assertActionMock).toHaveBeenCalledWith(
+ expect.objectContaining({ resourceId: 'agent-1', resourceType: 'agent' }),
+ );
+ });
+});
diff --git a/apps/server/src/routers/lambda/_helpers/conversationResourceGuard.ts b/apps/server/src/routers/lambda/_helpers/conversationResourceGuard.ts
new file mode 100644
index 00000000000..47bd87b9a6a
--- /dev/null
+++ b/apps/server/src/routers/lambda/_helpers/conversationResourceGuard.ts
@@ -0,0 +1,201 @@
+import { inArray } from 'drizzle-orm';
+
+import { agentsToSessions, messages, topics } from '@/database/schemas';
+import type { LobeChatDatabase } from '@/database/type';
+import {
+ assertCanPerformResourceAction,
+ getResourceMeta,
+} from '@/server/services/resourcePermission';
+
+import { getWorkspaceAgentParentGroupIds } from './workspaceAgentGuard';
+
+interface ConversationGuardCtx {
+ db: LobeChatDatabase;
+ userId: string;
+ workspaceId?: string | null;
+}
+
+export interface ConversationTarget {
+ agentId?: string | null;
+ groupId?: string | null;
+}
+
+export interface CreateMessageTarget extends ConversationTarget {
+ parentId?: string | null;
+ topicId?: string | null;
+}
+
+/**
+ * Workspace General-access guard for conversation writes.
+ *
+ * Workspace topics/messages are visible workspace-wide (`buildWorkspaceWhere`
+ * matches every member's rows), and shared conversations are intentionally
+ * co-editable by members — but only for members who can at least USE the
+ * agent/group the conversation belongs to. `view`-level General access means
+ * read-only: no sends, no message edits/deletes, no topic co-edits.
+ *
+ * Personal mode (no workspaceId) is a no-op. Targets that don't resolve to a
+ * workspace-shared agent/group of the CURRENT workspace (inbox, legacy rows,
+ * cross-workspace ids) fall through — the models' workspace ownership WHERE
+ * already keeps those writes scoped.
+ */
+export const assertCanUseConversationTargets = async (
+ ctx: ConversationGuardCtx,
+ targets: ConversationTarget[],
+): Promise<void> => {
+ const workspaceId = ctx.workspaceId ?? undefined;
+ if (!workspaceId || targets.length === 0) return;
+
+ // A conversation belongs to its group when it has one, otherwise its agent.
+ const refs = new Map<string, { resourceId: string; resourceType: 'agent' | 'agentGroup' }>();
+ for (const target of targets) {
+ if (target.groupId) {
+ refs.set(`agentGroup:${target.groupId}`, {
+ resourceId: target.groupId,
+ resourceType: 'agentGroup',
+ });
+ }
+ if (target.agentId) {
+ refs.set(`agent:${target.agentId}`, { resourceId: target.agentId, resourceType: 'agent' });
+ }
+ }
+
+ // Agent-only context is client-supplied and may point directly at a virtual
+ // group member. Its conversation capability cannot exceed any parent group,
+ // matching the execution and configuration guards.
+ const agentRefs = [...refs.values()].filter((ref) => ref.resourceType === 'agent');
+ const parentGroupIds = await Promise.all(
+ agentRefs.map((ref) =>
+ getWorkspaceAgentParentGroupIds({ agentId: ref.resourceId, db: ctx.db, workspaceId }),
+ ),
+ );
+ for (const groupId of parentGroupIds.flat()) {
+ refs.set(`agentGroup:${groupId}`, { resourceId: groupId, resourceType: 'agentGroup' });
+ }
+
+ for (const { resourceId, resourceType } of refs.values()) {
+ const meta = await getResourceMeta(ctx.db, resourceType, resourceId);
+ // Not a resource of the current workspace — nothing to guard at this
+ // layer; the ownership WHERE keeps foreign ids unreachable anyway.
+ if (!meta || meta.workspaceId !== workspaceId) continue;
+
+ await assertCanPerformResourceAction({
+ action: 'use',
+ db: ctx.db,
+ meta,
+ resourceId,
+ resourceType,
+ userId: ctx.userId,
+ workspaceId,
+ });
+ }
+};
+
+/**
+ * Resolve message ids to their owning agent/group from the DB rows (client
+ * context is untrusted) and assert `use` access. Rows without a direct
+ * agentId/groupId fall back to their topic's linkage.
+ */
+export const assertCanUseMessageTargets = async (
+ ctx: ConversationGuardCtx,
+ messageIds: string[],
+): Promise<void> => {
+ if (!ctx.workspaceId || messageIds.length === 0) return;
+
+ const rows = await ctx.db
+ .select({ agentId: messages.agentId, groupId: messages.groupId, topicId: messages.topicId })
+ .from(messages)
+ .where(inArray(messages.id, messageIds));
+
+ const targets: ConversationTarget[] = [];
+ const fallbackTopicIds = new Set<string>();
+ for (const row of rows) {
+ if (row.agentId || row.groupId) targets.push(row);
+ else if (row.topicId) fallbackTopicIds.add(row.topicId);
+ }
+
+ await assertCanUseConversationTargets(ctx, targets);
+ if (fallbackTopicIds.size > 0) {
+ await assertCanUseTopicTargets(ctx, [...fallbackTopicIds]);
+ }
+};
+
+/**
+ * Resolve topic ids to their owning agent/group from the DB rows and assert
+ * `use` access.
+ */
+export const assertCanUseTopicTargets = async (
+ ctx: ConversationGuardCtx,
+ topicIds: string[],
+): Promise<void> => {
+ if (!ctx.workspaceId || topicIds.length === 0) return;
+
+ const rows = await ctx.db
+ .select({ agentId: topics.agentId, groupId: topics.groupId, sessionId: topics.sessionId })
+ .from(topics)
+ .where(inArray(topics.id, topicIds));
+
+ // Backwards-compatible topics may carry only `sessionId` — resolve those
+ // through `agentsToSessions`, otherwise a session-backed topic would pass an
+ // empty target and skip the guard entirely.
+ const unresolvedSessionIds = [
+ ...new Set(
+ rows
+ .filter((row) => !row.agentId && !row.groupId && row.sessionId)
+ .map((row) => row.sessionId!),
+ ),
+ ];
+ const sessionTargets: ConversationTarget[] =
+ unresolvedSessionIds.length > 0
+ ? await ctx.db
+ .select({ agentId: agentsToSessions.agentId })
+ .from(agentsToSessions)
+ .where(inArray(agentsToSessions.sessionId, unresolvedSessionIds))
+ : [];
+
+ await assertCanUseConversationTargets(ctx, [...rows, ...sessionTargets]);
+};
+
+/**
+ * Resolve session ids to their linked agents via `agentsToSessions` and assert
+ * `use` access — for session-scoped bulk writes that never see a topic id.
+ */
+export const assertCanUseSessionTargets = async (
+ ctx: ConversationGuardCtx,
+ sessionIds: string[],
+): Promise<void> => {
+ if (!ctx.workspaceId || sessionIds.length === 0) return;
+
+ const targets: ConversationTarget[] = await ctx.db
+ .select({ agentId: agentsToSessions.agentId })
+ .from(agentsToSessions)
+ .where(inArray(agentsToSessions.sessionId, sessionIds));
+
+ await assertCanUseConversationTargets(ctx, targets);
+};
+
+/**
+ * Guard every authority-bearing field accepted by message creation. Explicit
+ * agent/group ids are not authoritative: a caller may omit or forge them while
+ * appending through an existing topic or parent message, so all three sources
+ * are checked independently.
+ */
+export const assertCanUseCreateMessageTargets = async (
+ ctx: ConversationGuardCtx,
+ createMessages: CreateMessageTarget[],
+): Promise<void> => {
+ if (!ctx.workspaceId || createMessages.length === 0) return;
+
+ const topicIds = [
+ ...new Set(createMessages.map((message) => message.topicId).filter(Boolean) as string[]),
+ ];
+ const parentIds = [
+ ...new Set(createMessages.map((message) => message.parentId).filter(Boolean) as string[]),
+ ];
+
+ await Promise.all([
+ assertCanUseConversationTargets(ctx, createMessages),
+ assertCanUseTopicTargets(ctx, topicIds),
+ assertCanUseMessageTargets(ctx, parentIds),
+ ]);
+};
diff --git a/apps/server/src/routers/lambda/_helpers/resolveContext.test.ts b/apps/server/src/routers/lambda/_helpers/resolveContext.test.ts
index 9e3ab04c81a..8bf5197eebd 100644
--- a/apps/server/src/routers/lambda/_helpers/resolveContext.test.ts
+++ b/apps/server/src/routers/lambda/_helpers/resolveContext.test.ts
@@ -4,6 +4,7 @@ import {
batchResolveAgentIdFromSessions,
resolveAgentIdFromSession,
resolveContext,
+ resolveContextWithAgentId,
} from './resolveContext';
const { mockBuildWorkspaceWhere } = vi.hoisted(() => ({
@@ -226,6 +227,59 @@ describe('resolveContext', () => {
});
});
+ describe('resolveContextWithAgentId', () => {
+ it('reverse-resolves a session-only context before resolving the canonical session', async () => {
+ const mockDb = createMockDb([{ agentId: 'agent-1', sessionId: 'session-1' }]);
+
+ const result = await resolveContextWithAgentId(
+ { sessionId: 'session-1', topicId: 'topic-1' },
+ mockDb,
+ mockUserId,
+ 'ws-1',
+ );
+
+ expect(result).toEqual({
+ agentId: 'agent-1',
+ groupId: null,
+ sessionId: 'session-1',
+ threadId: null,
+ topicId: 'topic-1',
+ });
+ expect(mockDb.select).toHaveBeenCalledTimes(1);
+ });
+
+ it('keeps an unresolved legacy session without inventing an agent id', async () => {
+ const mockDb = createMockDb([]);
+
+ const result = await resolveContextWithAgentId(
+ { sessionId: 'legacy-session' },
+ mockDb,
+ mockUserId,
+ );
+
+ expect(result.agentId).toBeNull();
+ expect(result.sessionId).toBe('legacy-session');
+ expect(mockDb.select).toHaveBeenCalledTimes(1);
+ });
+
+ it('replaces a stale agent id with the agent linked to the fallback session', async () => {
+ const mockDb = createMockDb();
+ mockDb._mocks.mockLimit
+ .mockResolvedValueOnce([])
+ .mockResolvedValueOnce([{ agentId: 'fallback-agent' }]);
+
+ const result = await resolveContextWithAgentId(
+ { agentId: 'stale-agent', sessionId: 'fallback-session' },
+ mockDb,
+ mockUserId,
+ );
+
+ expect(result.agentId).toBe('fallback-agent');
+ expect(result.sessionId).toBe('fallback-session');
+ expect(mockDb.select).toHaveBeenCalledTimes(2);
+ });
+ });
+
describe('batchResolveAgentIdFromSessions', () => {
// Helper to create a mock database for batch queries (no limit)
const createBatchMockDb = (queryResult: any[] = []) => {
diff --git a/apps/server/src/routers/lambda/_helpers/resolveContext.ts b/apps/server/src/routers/lambda/_helpers/resolveContext.ts
index 9c59c2b5a3b..a9764889c4a 100644
--- a/apps/server/src/routers/lambda/_helpers/resolveContext.ts
+++ b/apps/server/src/routers/lambda/_helpers/resolveContext.ts
@@ -90,6 +90,28 @@ export const resolveAgentIdFromSession = async (
return relation?.agentId;
};
+/**
+ * Resolve a context in both directions so authorization always receives the
+ * canonical agent id even from legacy session-only callers.
+ */
+export const resolveContextWithAgentId = async (
+ input: ConversationContextInput,
+ db: LobeChatDatabase,
+ userId: string,
+ workspaceId?: string,
+): Promise<ResolvedContext> => {
+ const resolved = await resolveContext(input, db, userId, workspaceId);
+ if (!resolved.sessionId) return resolved;
+
+ // Canonicalize the agent from the session that actually won resolution.
+ // This preserves the legacy fallback contract when a stale/non-existent
+ // agentId is sent together with a valid sessionId, instead of carrying the
+ // stale id into a foreign-keyed write.
+ const agentId = await resolveAgentIdFromSession(resolved.sessionId, db, userId, workspaceId);
+
+ return { ...resolved, agentId: agentId ?? resolved.agentId };
+};
+
/**
* Batch reverse resolution: Get agentId mapping from multiple sessionIds
*
diff --git a/apps/server/src/routers/lambda/_helpers/resourceConfigGuard.test.ts b/apps/server/src/routers/lambda/_helpers/resourceConfigGuard.test.ts
new file mode 100644
index 00000000000..fc807751a6d
--- /dev/null
+++ b/apps/server/src/routers/lambda/_helpers/resourceConfigGuard.test.ts
@@ -0,0 +1,148 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { canPerformResourceAction, getResourceMeta } from '@/server/services/resourcePermission';
+
+import {
+ getResourceConfigAccess,
+ redactAgentConfig,
+ redactGroupConfig,
+} from './resourceConfigGuard';
+import { getWorkspaceAgentParentGroupIds } from './workspaceAgentGuard';
+
+vi.mock('@/server/services/resourcePermission', () => ({
+ canPerformResourceAction: vi.fn(),
+ getResourceMeta: vi.fn(),
+}));
+vi.mock('./workspaceAgentGuard', () => ({
+ getWorkspaceAgentParentGroupIds: vi.fn(),
+}));
+
+const canPerformMock = vi.mocked(canPerformResourceAction);
+const getResourceMetaMock = vi.mocked(getResourceMeta);
+const getParentGroupIdsMock = vi.mocked(getWorkspaceAgentParentGroupIds);
+const meta = { userId: 'creator', visibility: 'public', workspaceId: 'ws-1' };
+
+const ctx = (workspaceId: string | null = 'ws-1') => ({
+ db: {} as any,
+ userId: 'member-1',
+ workspaceId,
+});
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ getResourceMetaMock.mockResolvedValue(meta);
+ getParentGroupIdsMock.mockResolvedValue([]);
+});
+
+describe('getResourceConfigAccess', () => {
+ it('returns full access in personal mode', async () => {
+ await expect(getResourceConfigAccess(ctx(null), 'agent', 'agent-1')).resolves.toBe('full');
+
+ expect(getResourceMetaMock).not.toHaveBeenCalled();
+ expect(canPerformMock).not.toHaveBeenCalled();
+ });
+
+ it('returns full access when the caller can edit', async () => {
+ canPerformMock.mockResolvedValueOnce(true);
+
+ await expect(getResourceConfigAccess(ctx(), 'agent', 'agent-1')).resolves.toBe('full');
+
+ expect(canPerformMock).toHaveBeenCalledWith(expect.objectContaining({ action: 'edit' }));
+ expect(canPerformMock).toHaveBeenCalledTimes(1);
+ });
+
+ it('returns profile-only access when the caller can view but not edit', async () => {
+ canPerformMock.mockResolvedValueOnce(false).mockResolvedValueOnce(true);
+
+ await expect(getResourceConfigAccess(ctx(), 'agent', 'agent-1')).resolves.toBe('profile');
+
+ expect(canPerformMock.mock.calls.map(([params]) => params.action)).toEqual(['edit', 'view']);
+ });
+
+ it('returns none when the caller cannot view the resource', async () => {
+ canPerformMock.mockResolvedValue(false);
+
+ await expect(getResourceConfigAccess(ctx(), 'agent', 'agent-1')).resolves.toBe('none');
+ });
+
+ it('limits a virtual agent to the minimum access of its parent groups', async () => {
+ getParentGroupIdsMock.mockResolvedValueOnce(['group-1']);
+ canPerformMock
+ .mockResolvedValueOnce(true)
+ .mockResolvedValueOnce(false)
+ .mockResolvedValueOnce(true);
+
+ await expect(getResourceConfigAccess(ctx(), 'agent', 'agent-1')).resolves.toBe('profile');
+
+ expect(canPerformMock).toHaveBeenLastCalledWith(
+ expect.objectContaining({ action: 'view', resourceId: 'group-1' }),
+ );
+ });
+
+ it('rejects metadata from another workspace without evaluating permissions', async () => {
+ getResourceMetaMock.mockResolvedValueOnce({ ...meta, workspaceId: 'ws-2' });
+
+ await expect(getResourceConfigAccess(ctx(), 'agent', 'agent-1')).resolves.toBe('none');
+
+ expect(canPerformMock).not.toHaveBeenCalled();
+ });
+});
+
+describe('config redaction', () => {
+ it('keeps only agent profile fields', () => {
+ const result = redactAgentConfig({
+ avatar: 'avatar.png',
+ chatConfig: { runtimeEnv: { SECRET: 'value' } },
+ description: 'Public description',
+ files: [{ id: 'file-1' }],
+ id: 'agent-1',
+ model: 'private-model',
+ openingMessage: 'Hello',
+ params: { temperature: 0.8 },
+ plugins: ['private-tool'],
+ systemRole: 'private prompt',
+ title: 'Public title',
+ });
+
+ expect(result).toEqual({
+ avatar: 'avatar.png',
+ description: 'Public description',
+ id: 'agent-1',
+ openingMessage: 'Hello',
+ title: 'Public title',
+ });
+ });
+
+ it('redacts group prompts and every member config', () => {
+ const result = redactGroupConfig({
+ agents: [
+ {
+ id: 'agent-1',
+ isSupervisor: true,
+ plugins: ['private-tool'],
+ systemRole: 'private member prompt',
+ title: 'Agent 1',
+ },
+ ],
+ config: {
+ allowDM: true,
+ openingMessage: 'Welcome',
+ openingQuestions: ['Start'],
+ systemPrompt: 'private group prompt',
+ },
+ content: 'private editor content',
+ id: 'group-1',
+ supervisorAgentId: 'agent-1',
+ title: 'Public group',
+ });
+
+ expect(result).toEqual({
+ agents: [{ id: 'agent-1', isSupervisor: true, title: 'Agent 1' }],
+ config: { openingMessage: 'Welcome', openingQuestions: ['Start'] },
+ id: 'group-1',
+ supervisorAgentId: 'agent-1',
+ title: 'Public group',
+ });
+ });
+});
diff --git a/apps/server/src/routers/lambda/_helpers/resourceConfigGuard.ts b/apps/server/src/routers/lambda/_helpers/resourceConfigGuard.ts
new file mode 100644
index 00000000000..ace8b17fed4
--- /dev/null
+++ b/apps/server/src/routers/lambda/_helpers/resourceConfigGuard.ts
@@ -0,0 +1,162 @@
+import type { PermissionResourceType } from '@/database/schemas';
+import type { LobeChatDatabase } from '@/database/type';
+import {
+ canPerformResourceAction,
+ getResourceMeta,
+ type ResourceMeta,
+} from '@/server/services/resourcePermission';
+
+import { getWorkspaceAgentParentGroupIds } from './workspaceAgentGuard';
+
+interface ResourceConfigGuardCtx {
+ db: LobeChatDatabase;
+ grantedPermissions?: readonly string[];
+ userId: string;
+ workspaceId?: string | null;
+}
+
+export type ResourceConfigAccess = 'full' | 'none' | 'profile';
+
+const ACCESS_RANK: Record<ResourceConfigAccess, number> = {
+ full: 2,
+ none: 0,
+ profile: 1,
+};
+
+const getSingleResourceConfigAccess = async (
+ ctx: ResourceConfigGuardCtx,
+ resourceType: PermissionResourceType,
+ resourceId: string,
+ knownMeta?: ResourceMeta,
+): Promise<ResourceConfigAccess> => {
+ const workspaceId = ctx.workspaceId!;
+ const meta = knownMeta ?? (await getResourceMeta(ctx.db, resourceType, resourceId));
+ if (!meta || meta.workspaceId !== workspaceId) return 'none';
+
+ const permissionParams = {
+ db: ctx.db,
+ grantedPermissions: ctx.grantedPermissions,
+ meta,
+ resourceId,
+ resourceType,
+ userId: ctx.userId,
+ workspaceId,
+ };
+
+ if (await canPerformResourceAction({ ...permissionParams, action: 'edit' })) return 'full';
+ if (await canPerformResourceAction({ ...permissionParams, action: 'view' })) return 'profile';
+ return 'none';
+};
+
+/**
+ * Full configuration is an edit-level capability. Members with only view/use
+ * access still need public profile data to render shared conversations, but
+ * must not receive prompts, tools, model settings, or other editable config.
+ */
+export const getResourceConfigAccess = async (
+ ctx: ResourceConfigGuardCtx,
+ resourceType: PermissionResourceType,
+ resourceId: string,
+ knownMeta?: ResourceMeta,
+): Promise<ResourceConfigAccess> => {
+ const workspaceId = ctx.workspaceId ?? undefined;
+ if (!workspaceId) return 'full';
+
+ const ownAccess = await getSingleResourceConfigAccess(
+ { ...ctx, workspaceId },
+ resourceType,
+ resourceId,
+ knownMeta,
+ );
+ if (resourceType !== 'agent' || ownAccess === 'none') return ownAccess;
+
+ // A virtual member's effective config access cannot exceed any parent
+ // group's access. This closes the direct agent-id path around a restricted
+ // group while still allowing standalone agents to use their own ACL.
+ const parentGroupIds = await getWorkspaceAgentParentGroupIds({
+ agentId: resourceId,
+ db: ctx.db,
+ workspaceId,
+ });
+ if (parentGroupIds.length === 0) return ownAccess;
+
+ const parentAccess = await Promise.all(
+ parentGroupIds.map((groupId) =>
+ getSingleResourceConfigAccess({ ...ctx, workspaceId }, 'agentGroup', groupId),
+ ),
+ );
+
+ return [ownAccess, ...parentAccess].reduce((minimum, access) =>
+ ACCESS_RANK[access] < ACCESS_RANK[minimum] ? access : minimum,
+ );
+};
+
+const pick = <T extends Record<string, any>>(source: T, keys: readonly string[]): T => {
+ const result: Record<string, any> = {};
+ for (const key of keys) {
+ if (key in source) result[key] = source[key];
+ }
+ return result as T;
+};
+
+const AGENT_PROFILE_KEYS = [
+ 'avatar',
+ 'backgroundColor',
+ 'createdAt',
+ 'description',
+ 'id',
+ 'isSupervisor',
+ 'marketIdentifier',
+ 'openingMessage',
+ 'openingQuestions',
+ 'slug',
+ 'title',
+ 'updatedAt',
+ 'userId',
+ 'virtual',
+ 'visibility',
+ 'workspaceId',
+] as const;
+
+/** Return only identity/display fields; deliberately use a whitelist. */
+export const redactAgentConfig = <T extends Record<string, any>>(agent: T): T =>
+ pick(agent, AGENT_PROFILE_KEYS);
+
+const GROUP_PROFILE_KEYS = [
+ 'avatar',
+ 'backgroundColor',
+ 'clientId',
+ 'createdAt',
+ 'description',
+ 'groupId',
+ 'id',
+ 'marketIdentifier',
+ 'pinned',
+ 'supervisorAgentId',
+ 'title',
+ 'updatedAt',
+ 'userId',
+ 'visibility',
+ 'workspaceId',
+] as const;
+
+/**
+ * Preserve group/member display metadata and welcome copy for chat surfaces,
+ * while removing the group system prompt and every member's executable config.
+ */
+export const redactGroupConfig = <T extends Record<string, any>>(group: T): T => {
+ const result = pick(group, GROUP_PROFILE_KEYS) as Record<string, any>;
+ const config = group.config as Record<string, any> | null | undefined;
+
+ if (config) {
+ result.config = pick(config, ['openingMessage', 'openingQuestions']);
+ } else if ('config' in group) {
+ result.config = config;
+ }
+
+ if (Array.isArray(group.agents)) {
+ result.agents = group.agents.map((agent: Record<string, any>) => redactAgentConfig(agent));
+ }
+
+ return result as T;
+};
diff --git a/apps/server/src/routers/lambda/_helpers/workspaceAgentGuard.test.ts b/apps/server/src/routers/lambda/_helpers/workspaceAgentGuard.test.ts
new file mode 100644
index 00000000000..d482bd9b09c
--- /dev/null
+++ b/apps/server/src/routers/lambda/_helpers/workspaceAgentGuard.test.ts
@@ -0,0 +1,125 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { LobeChatDatabase } from '@/database/type';
+import { assertCanPerformResourceAction } from '@/server/services/resourcePermission';
+
+import { assertCanUseWorkspaceAgent } from './workspaceAgentGuard';
+
+vi.mock('@/server/services/resourcePermission', () => ({
+ assertCanPerformResourceAction: vi.fn(),
+}));
+
+const assertActionMock = vi.mocked(assertCanPerformResourceAction);
+
+const createDB = (agent: { id: string } | undefined, linkedGroups: { groupId: string }[] = []) => {
+ const where = vi.fn().mockResolvedValue(linkedGroups);
+ const innerJoin = vi.fn().mockReturnValue({ where });
+ const from = vi.fn().mockReturnValue({ innerJoin });
+ const select = vi.fn().mockReturnValue({ from });
+ const findFirst = vi.fn().mockResolvedValue(agent);
+
+ return {
+ db: { query: { agents: { findFirst } }, select } as unknown as LobeChatDatabase,
+ findFirst,
+ select,
+ };
+};
+
+describe('assertCanUseWorkspaceAgent', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ assertActionMock.mockResolvedValue();
+ });
+
+ it('is a no-op outside a workspace', async () => {
+ const { db, findFirst } = createDB({ id: 'agent-1' });
+
+ await assertCanUseWorkspaceAgent({ agentId: 'agent-1', db, userId: 'user-1' });
+
+ expect(findFirst).not.toHaveBeenCalled();
+ expect(assertActionMock).not.toHaveBeenCalled();
+ });
+
+ it('checks only the agent for a standalone workspace agent', async () => {
+ const { db, findFirst } = createDB({ id: 'agent-1' });
+
+ await assertCanUseWorkspaceAgent({
+ agentId: 'agent-1',
+ db,
+ userId: 'user-1',
+ workspaceId: 'ws-1',
+ });
+
+ expect(findFirst).not.toHaveBeenCalled();
+ expect(assertActionMock).toHaveBeenCalledOnce();
+ expect(assertActionMock).toHaveBeenCalledWith(
+ expect.objectContaining({ resourceId: 'agent-1', resourceType: 'agent' }),
+ );
+ });
+
+ it('also checks every parent group for a group-owned virtual agent', async () => {
+ const { db } = createDB({ id: 'agent-1' }, [{ groupId: 'group-1' }, { groupId: 'group-2' }]);
+
+ await assertCanUseWorkspaceAgent({
+ agentId: 'agent-1',
+ db,
+ userId: 'user-1',
+ workspaceId: 'ws-1',
+ });
+
+ expect(assertActionMock).toHaveBeenCalledTimes(3);
+ expect(assertActionMock).toHaveBeenCalledWith(
+ expect.objectContaining({ resourceId: 'group-1', resourceType: 'agentGroup' }),
+ );
+ expect(assertActionMock).toHaveBeenCalledWith(
+ expect.objectContaining({ resourceId: 'group-2', resourceType: 'agentGroup' }),
+ );
+ });
+
+ it('blocks direct execution when a parent group denies use', async () => {
+ const { db } = createDB({ id: 'agent-1' }, [{ groupId: 'group-1' }]);
+ assertActionMock.mockImplementation(async ({ resourceType }) => {
+ if (resourceType === 'agentGroup') throw new Error('group use denied');
+ });
+
+ await expect(
+ assertCanUseWorkspaceAgent({
+ agentId: 'agent-1',
+ db,
+ userId: 'user-1',
+ workspaceId: 'ws-1',
+ }),
+ ).rejects.toThrow('group use denied');
+ });
+
+ it('checks an explicit group context for a non-virtual member agent', async () => {
+ const { db } = createDB({ id: 'agent-1' });
+
+ await assertCanUseWorkspaceAgent({
+ agentId: 'agent-1',
+ db,
+ groupId: 'group-1',
+ userId: 'user-1',
+ workspaceId: 'ws-1',
+ });
+
+ expect(assertActionMock).toHaveBeenCalledTimes(2);
+ expect(assertActionMock).toHaveBeenCalledWith(
+ expect.objectContaining({ resourceId: 'group-1', resourceType: 'agentGroup' }),
+ );
+ });
+
+ it('preserves downstream not-found behavior when the identifier does not resolve', async () => {
+ const { db } = createDB(undefined);
+
+ await assertCanUseWorkspaceAgent({
+ db,
+ slug: 'missing-agent',
+ userId: 'user-1',
+ workspaceId: 'ws-1',
+ });
+
+ expect(assertActionMock).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/server/src/routers/lambda/_helpers/workspaceAgentGuard.ts b/apps/server/src/routers/lambda/_helpers/workspaceAgentGuard.ts
new file mode 100644
index 00000000000..b586608b30c
--- /dev/null
+++ b/apps/server/src/routers/lambda/_helpers/workspaceAgentGuard.ts
@@ -0,0 +1,124 @@
+import { and, eq } from 'drizzle-orm';
+
+import { agents, chatGroupsAgents } from '@/database/schemas';
+import type { LobeChatDatabase } from '@/database/type';
+import { assertCanPerformResourceAction } from '@/server/services/resourcePermission';
+
+interface WorkspaceAgentGuardParams {
+ agentId?: string;
+ db: LobeChatDatabase;
+ groupId?: string | null;
+ slug?: string;
+ userId: string;
+ workspaceId?: string | null;
+}
+
+export const getWorkspaceAgentParentGroupIds = async ({
+ agentId,
+ db,
+ workspaceId,
+}: {
+ agentId: string;
+ db: LobeChatDatabase;
+ workspaceId: string;
+}): Promise<string[]> => {
+ const linkedGroups = await db
+ .select({ groupId: chatGroupsAgents.chatGroupId })
+ .from(chatGroupsAgents)
+ .innerJoin(agents, eq(chatGroupsAgents.agentId, agents.id))
+ .where(
+ and(
+ eq(chatGroupsAgents.agentId, agentId),
+ eq(chatGroupsAgents.workspaceId, workspaceId),
+ eq(agents.virtual, true),
+ ),
+ );
+
+ return [...new Set(linkedGroups.map((row) => row.groupId))];
+};
+
+/**
+ * Reverse lookup: the virtual (group-owned) agents of a workspace group —
+ * supervisor + generated members. Standalone agents linked into the group are
+ * excluded; they keep their own ACL.
+ */
+export const getWorkspaceGroupVirtualAgentIds = async ({
+ db,
+ groupId,
+ workspaceId,
+}: {
+ db: LobeChatDatabase;
+ groupId: string;
+ workspaceId: string;
+}): Promise<string[]> => {
+ const rows = await db
+ .select({ agentId: chatGroupsAgents.agentId })
+ .from(chatGroupsAgents)
+ .innerJoin(agents, eq(chatGroupsAgents.agentId, agents.id))
+ .where(
+ and(
+ eq(chatGroupsAgents.chatGroupId, groupId),
+ eq(chatGroupsAgents.workspaceId, workspaceId),
+ eq(agents.virtual, true),
+ ),
+ );
+
+ return [...new Set(rows.map((row) => row.agentId))];
+};
+
+/**
+ * Workspace `use` guard for agent execution entrypoints.
+ *
+ * Group-owned virtual agents are standalone rows and can be addressed by id,
+ * but their execution capability must never exceed the parent group. Require
+ * both the agent ACL and every linked group ACL so a direct `execAgent` call
+ * cannot bypass a view-only group. An explicit group context is checked for
+ * non-virtual members too.
+ */
+export const assertCanUseWorkspaceAgent = async ({
+ agentId,
+ db,
+ groupId,
+ slug,
+ userId,
+ workspaceId,
+}: WorkspaceAgentGuardParams): Promise<void> => {
+ if (!workspaceId) return;
+ if (!agentId && !slug) return;
+
+ let resourceId = agentId;
+ if (!resourceId && slug) {
+ const agent = await db.query.agents.findFirst({
+ columns: { id: true },
+ where: and(eq(agents.slug, slug), eq(agents.workspaceId, workspaceId)),
+ });
+ resourceId = agent?.id;
+ }
+ if (!resourceId) return;
+
+ const groupIds = new Set(
+ await getWorkspaceAgentParentGroupIds({ agentId: resourceId, db, workspaceId }),
+ );
+ if (groupId) groupIds.add(groupId);
+
+ await Promise.all([
+ assertCanPerformResourceAction({
+ action: 'use',
+ db,
+ resourceId,
+ resourceType: 'agent',
+ userId,
+ workspaceId,
+ }),
+ ...[...groupIds].map((resourceId) =>
+ assertCanPerformResourceAction({
+ action: 'use',
+ db,
+ resourceId,
+ resourceType: 'agentGroup',
+ userId,
+ workspaceId,
+ }),
+ ),
+ ]);
+};
diff --git a/apps/server/src/routers/lambda/agent.ts b/apps/server/src/routers/lambda/agent.ts
index 34dd6b1d4ea..d60de5fc851 100644
--- a/apps/server/src/routers/lambda/agent.ts
+++ b/apps/server/src/routers/lambda/agent.ts
@@ -11,21 +11,53 @@ import { AgentModel } from '@/database/models/agent';
import { ChatGroupModel } from '@/database/models/chatGroup';
import { FileModel } from '@/database/models/file';
import { KnowledgeBaseModel } from '@/database/models/knowledgeBase';
+import { ResourcePermissionModel } from '@/database/models/resourcePermission';
import { SessionModel } from '@/database/models/session';
import { TaskModel } from '@/database/models/task';
import { UserModel } from '@/database/models/user';
+import { DEFAULT_RESOURCE_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';
import { EditLockService } from '@/server/services/editLock';
import { publishResourceEvent } from '@/server/services/resourceEvents';
+import {
+ assertCanEditResource,
+ assertCanPerformResourceAction,
+ buildResourcePermissionState,
+} from '@/server/services/resourcePermission';
import { hasWorkspaceScopedPermission } from '@/server/services/workspacePermission';
import { TransferErrorCode } from '@/types/transferError';
-import {
- assertWorkspaceRowManageable,
- isWorkspaceNonOwner,
-} from './_helpers/assertWorkspaceRowManageable';
+import { isWorkspaceNonOwner } from './_helpers/assertWorkspaceRowManageable';
+import { getResourceConfigAccess, redactAgentConfig } from './_helpers/resourceConfigGuard';
+
+const protectAgentConfig = async <T extends Record<string, any>>(
+ ctx: {
+ serverDB: Parameters<typeof getResourceConfigAccess>[0]['db'];
+ userId: string;
+ workspaceId?: string | null;
+ workspacePermissionCodes?: string[];
+ },
+ agentId: string,
+ config: T | null | undefined,
+): Promise<T | null> => {
+ if (!config) return null;
+
+ const access = await getResourceConfigAccess(
+ {
+ db: ctx.serverDB,
+ grantedPermissions: ctx.workspacePermissionCodes,
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
+ },
+ 'agent',
+ agentId,
+ );
+
+ if (access === 'none') return null;
+ return access === 'profile' ? redactAgentConfig(config) : config;
+};
const agentProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {
const { ctx } = opts;
@@ -105,6 +137,15 @@ export const agentRouter = router({
...(input.visibility ? { visibility: input.visibility } : {}),
});
+ if (ctx.workspaceId && agent.visibility !== 'private') {
+ await new ResourcePermissionModel(ctx.serverDB, ctx.workspaceId).setAccessLevel(
+ 'agent',
+ agent.id,
+ DEFAULT_RESOURCE_ACCESS_LEVELS.agent,
+ ctx.userId,
+ );
+ }
+
return { agentId: agent.id };
}),
@@ -116,9 +157,23 @@ export const agentRouter = router({
*/
publishAgentToWorkspace: agentProcedure
.use(withScopedPermission('agent:update'))
- .input(z.object({ id: z.string() }))
+ .input(
+ z.object({
+ accessLevel: z.enum(RESOURCE_ACCESS_LEVELS_BY_TYPE.agent).optional(),
+ id: z.string(),
+ }),
+ )
.mutation(async ({ input, ctx }) => {
- return ctx.agentModel.publishToWorkspace(input.id);
+ const result = await ctx.agentModel.publishToWorkspace(input.id);
+ if (ctx.workspaceId) {
+ await new ResourcePermissionModel(ctx.serverDB, ctx.workspaceId).setAccessLevel(
+ 'agent',
+ input.id,
+ input.accessLevel ?? DEFAULT_RESOURCE_ACCESS_LEVELS.agent,
+ ctx.userId,
+ );
+ }
+ return result;
}),
/**
@@ -132,7 +187,13 @@ export const agentRouter = router({
*/
setAgentVisibility: agentProcedure
.use(withScopedPermission('agent:update'))
- .input(z.object({ id: z.string(), visibility: z.enum(['private', 'public']) }))
+ .input(
+ z.object({
+ accessLevel: z.enum(RESOURCE_ACCESS_LEVELS_BY_TYPE.agent).optional(),
+ id: z.string(),
+ visibility: z.enum(['private', 'public']),
+ }),
+ )
.mutation(async ({ input, ctx }) => {
const meta = await ctx.agentModel.getAgentVisibilityMeta(input.id);
if (!meta) throw new TRPCError({ code: 'NOT_FOUND', message: 'Agent not found' });
@@ -144,31 +205,52 @@ export const agentRouter = router({
});
}
- if (meta.visibility === input.visibility) return { success: true };
-
- if (ctx.workspaceId && meta.userId !== ctx.userId) {
- // Demoting to private stays creator-only even for owners: the agent
- // would land in the creator's private list, not the actor's, so an
- // owner-initiated demotion just appropriates another member's data.
- if (input.visibility === 'private') {
- throw new TRPCError({
- code: 'FORBIDDEN',
- message: 'Only the agent creator can make this agent private',
- });
- }
- const canOverride = await hasWorkspaceScopedPermission({
- action: 'AGENT_UPDATE',
+ if (!ctx.workspaceId) {
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message: 'Agent visibility only applies inside a workspace',
+ });
+ }
+ const permissionModel = new ResourcePermissionModel(ctx.serverDB, ctx.workspaceId);
+ const permissionMeta = { ...meta, workspaceId: ctx.workspaceId };
+ const blockingTasksPromise =
+ input.visibility === 'private' && meta.visibility !== input.visibility
+ ? new TaskModel(
+ ctx.serverDB,
+ ctx.userId,
+ ctx.workspaceId,
+ ).countTasksBlockingAgentDemotion(input.id, meta.userId)
+ : Promise.resolve(0);
+ const [, blockingTasks] = await Promise.all([
+ assertCanPerformResourceAction({
+ action: 'changeVisibility',
db: ctx.serverDB,
- scopes: ['ALL'],
+ grantedPermissions: (ctx as { workspacePermissionCodes?: string[] })
+ .workspacePermissionCodes,
+ meta: permissionMeta,
+ resourceId: input.id,
+ resourceType: 'agent',
userId: ctx.userId,
workspaceId: ctx.workspaceId,
- });
- if (!canOverride) {
- throw new TRPCError({
- code: 'FORBIDDEN',
- message: 'Only the agent creator or workspace owner can change visibility',
- });
+ }),
+ blockingTasksPromise,
+ ]);
+
+ if (meta.visibility === input.visibility) {
+ const accessLevel =
+ input.visibility === 'public'
+ ? (input.accessLevel ??
+ (await permissionModel.getEffectiveAccessLevel('agent', input.id)))
+ : 'edit';
+ if (input.visibility === 'public' && input.accessLevel) {
+ await permissionModel.setAccessLevel('agent', input.id, input.accessLevel, ctx.userId);
}
+ return buildResourcePermissionState({
+ accessLevel,
+ canManage: true,
+ creatorId: meta.userId,
+ visibility: input.visibility,
+ });
}
// Demoting an agent must not strand tasks that depend on it: public
@@ -178,24 +260,19 @@ export const agentRouter = router({
// fail future runs/updates because their creators can no longer
// resolve the agent. Reject early — reassign or demote those tasks
// first.
- if (input.visibility === 'private' && ctx.workspaceId) {
- const taskModel = new TaskModel(ctx.serverDB, ctx.userId, ctx.workspaceId);
- const blockingTasks = await taskModel.countTasksBlockingAgentDemotion(
- input.id,
- meta.userId,
- );
- if (blockingTasks > 0) {
- throw new TRPCError({
- code: 'BAD_REQUEST',
- message:
- 'Cannot make this agent private while workspace tasks still depend on it. Reassign those tasks or make them private first.',
- });
- }
+ if (blockingTasks > 0) {
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message:
+ 'Cannot make this agent private while workspace tasks still depend on it. Reassign those tasks or make them private first.',
+ });
+ }
- // Same source-level guard for group chats, but only for the supervisor
- // role: a private supervisor is unresolvable for every other viewer and
- // bricks the whole group. Regular members are not blocked — roster
- // reads drop a non-visible member per viewer instead (LOBE-11772).
+ // Same source-level guard for group chats, but only for the supervisor
+ // role: a private supervisor is unresolvable for every other viewer and
+ // bricks the whole group. Regular members are not blocked — roster
+ // reads drop a non-visible member per viewer instead (LOBE-11772).
+ if (input.visibility === 'private') {
const chatGroupModel = new ChatGroupModel(ctx.serverDB, ctx.userId, ctx.workspaceId);
const blockingGroups = await chatGroupModel.countGroupsBlockingAgentDemotion(
input.id,
@@ -213,7 +290,27 @@ export const agentRouter = router({
const updated = await ctx.agentModel.setVisibility(input.id, input.visibility);
if (!updated) throw new TRPCError({ code: 'NOT_FOUND', message: 'Agent not found' });
- return { success: true };
+ const accessLevel =
+ input.visibility === 'private'
+ ? 'edit'
+ : (input.accessLevel ?? DEFAULT_RESOURCE_ACCESS_LEVELS.agent);
+ if (input.visibility === 'private') {
+ await permissionModel.removeAll('agent', input.id);
+ } else {
+ await permissionModel.setAccessLevel(
+ 'agent',
+ input.id,
+ input.accessLevel ?? DEFAULT_RESOURCE_ACCESS_LEVELS.agent,
+ ctx.userId,
+ );
+ }
+
+ return buildResourcePermissionState({
+ accessLevel,
+ canManage: true,
+ creatorId: meta.userId,
+ visibility: input.visibility,
+ });
}),
createAgentFiles: agentProcedure
@@ -226,6 +323,16 @@ export const agentRouter = router({
}),
)
.mutation(async ({ input, ctx }) => {
+ if (ctx.workspaceId) {
+ await assertCanPerformResourceAction({
+ action: 'edit',
+ db: ctx.serverDB,
+ resourceId: input.agentId,
+ resourceType: 'agent',
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
+ });
+ }
return ctx.agentModel.createAgentFiles(input.agentId, input.fileIds, input.enabled);
}),
@@ -239,6 +346,16 @@ export const agentRouter = router({
}),
)
.mutation(async ({ input, ctx }) => {
+ if (ctx.workspaceId) {
+ await assertCanPerformResourceAction({
+ action: 'edit',
+ db: ctx.serverDB,
+ resourceId: input.agentId,
+ resourceType: 'agent',
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
+ });
+ }
return ctx.agentModel.createAgentKnowledgeBase(
input.agentId,
input.knowledgeBaseId,
@@ -260,12 +377,35 @@ export const agentRouter = router({
}),
)
.mutation(async ({ input, ctx }) => {
+ // Mutating the group's roster is a group edit — same ACL as
+ // `agentGroup.addAgentsToGroup`. Check before creating the agent so a
+ // denied call doesn't leave an orphan agent behind.
+ if (ctx.workspaceId) {
+ await assertCanPerformResourceAction({
+ action: 'edit',
+ db: ctx.serverDB,
+ resourceId: input.groupId,
+ resourceType: 'agentGroup',
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
+ });
+ }
+
// Create the agent entity only (no session)
const agent = await ctx.agentModel.create(input.config ?? {});
// Add the agent to the group
await ctx.chatGroupModel.addAgentToGroup(input.groupId, agent.id);
+ if (ctx.workspaceId && agent.visibility !== 'private') {
+ await new ResourcePermissionModel(ctx.serverDB, ctx.workspaceId).setAccessLevel(
+ 'agent',
+ agent.id,
+ DEFAULT_RESOURCE_ACCESS_LEVELS.agent,
+ ctx.userId,
+ );
+ }
+
return { agentId: agent.id };
}),
@@ -278,6 +418,16 @@ export const agentRouter = router({
}),
)
.mutation(async ({ input, ctx }) => {
+ if (ctx.workspaceId) {
+ await assertCanPerformResourceAction({
+ action: 'edit',
+ db: ctx.serverDB,
+ resourceId: input.agentId,
+ resourceType: 'agent',
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
+ });
+ }
return ctx.agentModel.deleteAgentFile(input.agentId, input.fileId);
}),
@@ -290,6 +440,16 @@ export const agentRouter = router({
}),
)
.mutation(async ({ input, ctx }) => {
+ if (ctx.workspaceId) {
+ await assertCanPerformResourceAction({
+ action: 'edit',
+ db: ctx.serverDB,
+ resourceId: input.agentId,
+ resourceType: 'agent',
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
+ });
+ }
return ctx.agentModel.deleteAgentKnowledgeBase(input.agentId, input.knowledgeBaseId);
}),
@@ -306,7 +466,27 @@ export const agentRouter = router({
}),
)
.mutation(async ({ input, ctx }) => {
- return ctx.agentModel.duplicate(input.agentId, input.newTitle);
+ // Duplicating copies the full config (prompt/plugins/etc.), which a
+ // use-only member must not be able to inspect — same edit gate as
+ // `updateAgentConfig`, mirroring the UI's `canConfigure` guard.
+ await assertCanEditResource({
+ db: ctx.serverDB,
+ resourceId: input.agentId,
+ resourceType: 'agent',
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId ?? undefined,
+ });
+
+ const result = await ctx.agentModel.duplicate(input.agentId, input.newTitle);
+ if (ctx.workspaceId && result) {
+ await new ResourcePermissionModel(ctx.serverDB, ctx.workspaceId).setAccessLevel(
+ 'agent',
+ result.agentId,
+ DEFAULT_RESOURCE_ACCESS_LEVELS.agent,
+ ctx.userId,
+ );
+ }
+ return result;
}),
/**
@@ -362,7 +542,8 @@ export const agentRouter = router({
if (!session) throw new Error(`Session [${input.sessionId}] not found`);
const sessionId = session.id;
- return ctx.agentModel.findBySessionId(sessionId);
+ const config = await ctx.agentModel.findBySessionId(sessionId);
+ return config?.id ? protectAgentConfig(ctx, config.id, config) : config;
}),
getAgentConfigById: agentProcedure
@@ -372,7 +553,8 @@ export const agentRouter = router({
}),
)
.query(async ({ input, ctx }) => {
- return ctx.agentService.getAgentConfigById(input.agentId);
+ const config = await ctx.agentService.getAgentConfigById(input.agentId);
+ return protectAgentConfig(ctx, input.agentId, config);
}),
/**
@@ -386,7 +568,8 @@ export const agentRouter = router({
}),
)
.query(async ({ input, ctx }) => {
- return ctx.agentService.getBuiltinAgent(input.slug);
+ const config = await ctx.agentService.getBuiltinAgent(input.slug);
+ return config?.id ? protectAgentConfig(ctx, config.id, config) : config;
}),
getKnowledgeBasesAndFiles: agentProcedure
@@ -397,6 +580,14 @@ export const agentRouter = router({
}),
)
.query(async ({ ctx, input }): Promise<KnowledgeItem[]> => {
+ await assertCanEditResource({
+ db: ctx.serverDB,
+ resourceId: input.agentId,
+ resourceType: 'agent',
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId ?? undefined,
+ });
+
// Look up the target agent's visibility so we can (a) apply the
// "public agent cannot reach caller's private rows" defensive filter
// in the model layer, and (b) hard-force `visibility='public'` when
@@ -474,25 +665,37 @@ export const agentRouter = router({
.use(withScopedPermission('agent:delete'))
.input(z.object({ agentId: z.string() }))
.mutation(async ({ input, ctx }) => {
- // Deleting cascades sessions/topics/messages, so gate to the creator or
- // a workspace owner before the destructive write.
- const meta = await ctx.agentModel.getAgentVisibilityMeta(input.agentId);
- if (!meta) throw new TRPCError({ code: 'NOT_FOUND', message: 'Agent not found' });
- assertWorkspaceRowManageable(ctx, meta.userId, 'agent');
- // Same rule as transfer: the delete cascade erases every linked
- // session/topic/message, so a non-owner member must not take teammates'
- // conversations down with their own agent.
- if (
- isWorkspaceNonOwner(ctx) &&
- (await ctx.agentModel.transferHasForeignRows(input.agentId))
- ) {
- throw new TRPCError({
- code: 'FORBIDDEN',
- message: "Only workspace owners can delete an agent carrying others' conversations",
+ if (ctx.workspaceId) {
+ await assertCanPerformResourceAction({
+ action: 'delete',
+ db: ctx.serverDB,
+ resourceId: input.agentId,
+ resourceType: 'agent',
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
});
+ // Same rule as transfer: the delete cascade erases every linked
+ // session/topic/message, so a non-owner member must not take teammates'
+ // conversations down with their own agent.
+ if (
+ isWorkspaceNonOwner(ctx) &&
+ (await ctx.agentModel.transferHasForeignRows(input.agentId))
+ ) {
+ throw new TRPCError({
+ cause: { data: { code: TransferErrorCode.OwnerOnly } },
+ code: 'FORBIDDEN',
+ message: "Only workspace owners can delete an agent carrying others' conversations",
+ });
+ }
}
-
- return ctx.agentModel.delete(input.agentId);
+ const result = await ctx.agentModel.delete(input.agentId);
+ if (ctx.workspaceId) {
+ await new ResourcePermissionModel(ctx.serverDB, ctx.workspaceId).removeAll(
+ 'agent',
+ input.agentId,
+ );
+ }
+ return result;
}),
toggleFile: agentProcedure
@@ -505,6 +708,16 @@ export const agentRouter = router({
}),
)
.mutation(async ({ input, ctx }) => {
+ if (ctx.workspaceId) {
+ await assertCanPerformResourceAction({
+ action: 'edit',
+ db: ctx.serverDB,
+ resourceId: input.agentId,
+ resourceType: 'agent',
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
+ });
+ }
return ctx.agentModel.toggleFile(input.agentId, input.fileId, input.enabled);
}),
@@ -518,6 +731,16 @@ export const agentRouter = router({
}),
)
.mutation(async ({ input, ctx }) => {
+ if (ctx.workspaceId) {
+ await assertCanPerformResourceAction({
+ action: 'edit',
+ db: ctx.serverDB,
+ resourceId: input.agentId,
+ resourceType: 'agent',
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
+ });
+ }
return ctx.agentModel.toggleKnowledgeBase(
input.agentId,
input.knowledgeBaseId,
@@ -530,6 +753,9 @@ export const agentRouter = router({
.input(
z.object({
agentId: z.string(),
+ targetAccessLevel: z.enum(RESOURCE_ACCESS_LEVELS_BY_TYPE.agent).optional(),
+ /** @deprecated Compatibility for released clients. */
+ targetGeneralAccess: z.enum(['editor', 'viewer']).optional(),
targetVisibility: z.enum(['private', 'public']).optional(),
targetWorkspaceId: z.string().nullable(),
}),
@@ -545,26 +771,16 @@ export const agentRouter = router({
});
}
- // 2. In workspace mode, members can only transfer private agents they
- // created. Public (workspace-shared) agents carry every member's
- // conversations, so moving them out is owner-only — even for the
- // creator. Owner-level AGENT_UPDATE (scope ALL) overrides both.
- if (ctx.workspaceId && (agent.visibility === 'public' || agent.userId !== ctx.userId)) {
- const canOverride = await hasWorkspaceScopedPermission({
- action: 'AGENT_UPDATE',
+ // 2. Transferring ownership/scope is always creator-only.
+ if (ctx.workspaceId) {
+ await assertCanPerformResourceAction({
+ action: 'transfer',
db: ctx.serverDB,
- scopes: ['ALL'],
+ resourceId: input.agentId,
+ resourceType: 'agent',
userId: ctx.userId,
workspaceId: ctx.workspaceId,
});
-
- if (!canOverride) {
- throw new TRPCError({
- cause: { data: { code: TransferErrorCode.OwnerOnly } },
- code: 'FORBIDDEN',
- message: 'Only workspace owners can transfer shared agents or agents created by others',
- });
- }
}
// 3. Validate target workspace access (user must be member+)
@@ -608,12 +824,32 @@ export const agentRouter = router({
});
}
- return ctx.agentModel.transferAgent(
+ const result = await ctx.agentModel.transferAgent(
input.agentId,
input.targetWorkspaceId,
ctx.userId,
input.targetVisibility,
);
+
+ if (ctx.workspaceId) {
+ await new ResourcePermissionModel(ctx.serverDB, ctx.workspaceId).removeAll(
+ 'agent',
+ input.agentId,
+ );
+ }
+ if (input.targetWorkspaceId && input.targetVisibility === 'public') {
+ const targetAccessLevel =
+ input.targetAccessLevel ??
+ (input.targetGeneralAccess === 'editor' ? 'edit' : DEFAULT_RESOURCE_ACCESS_LEVELS.agent);
+ await new ResourcePermissionModel(ctx.serverDB, input.targetWorkspaceId).setAccessLevel(
+ 'agent',
+ input.agentId,
+ targetAccessLevel,
+ ctx.userId,
+ );
+ }
+
+ return result;
}),
updateAgentConfig: agentProcedure
@@ -625,6 +861,15 @@ export const agentRouter = router({
}),
)
.mutation(async ({ input, ctx }) => {
+ // General-access write guard: only `edit` permits collaborative updates.
+ await assertCanEditResource({
+ db: ctx.serverDB,
+ resourceId: input.agentId,
+ resourceType: 'agent',
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId ?? undefined,
+ });
+
// Collaborative edit lock: reject writes to a workspace agent another
// member is actively editing. Inert until a client acquires the lock.
if (ctx.workspaceId) {
diff --git a/apps/server/src/routers/lambda/agentGroup.ts b/apps/server/src/routers/lambda/agentGroup.ts
index a8d5fd1a81f..7b4b5421bd7 100644
--- a/apps/server/src/routers/lambda/agentGroup.ts
+++ b/apps/server/src/routers/lambda/agentGroup.ts
@@ -6,21 +6,97 @@ import { withScopedPermission } from '@/business/server/trpc-middlewares/rbacPer
import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';
import { AgentModel } from '@/database/models/agent';
import { ChatGroupModel } from '@/database/models/chatGroup';
+import { ResourcePermissionModel } from '@/database/models/resourcePermission';
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 ChatGroupConfig } from '@/database/types/chatGroup';
import { router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
import { AgentGroupService } from '@/server/services/agentGroup';
import { EditLockService } from '@/server/services/editLock';
import { publishResourceEvent } from '@/server/services/resourceEvents';
+import {
+ assertCanEditResource,
+ assertCanPerformResourceAction,
+ buildResourcePermissionState,
+} from '@/server/services/resourcePermission';
import { hasWorkspaceScopedPermission } from '@/server/services/workspacePermission';
import { TransferErrorCode } from '@/types/transferError';
+import { isWorkspaceNonOwner } from './_helpers/assertWorkspaceRowManageable';
import {
- assertWorkspaceRowManageable,
- isWorkspaceNonOwner,
-} from './_helpers/assertWorkspaceRowManageable';
+ getResourceConfigAccess,
+ redactAgentConfig,
+ redactGroupConfig,
+ type ResourceConfigAccess,
+} from './_helpers/resourceConfigGuard';
+
+const resourceConfigGuardCtx = (ctx: {
+ serverDB: Parameters<typeof getResourceConfigAccess>[0]['db'];
+ userId: string;
+ workspaceId?: string | null;
+ workspacePermissionCodes?: string[];
+}) => ({
+ db: ctx.serverDB,
+ grantedPermissions: ctx.workspacePermissionCodes,
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
+});
+
+const getGroupConfigAccess = <T extends Record<string, any>>(
+ ctx: {
+ serverDB: Parameters<typeof getResourceConfigAccess>[0]['db'];
+ userId: string;
+ workspaceId?: string | null;
+ workspacePermissionCodes?: string[];
+ },
+ group: T,
+): Promise<ResourceConfigAccess> =>
+ getResourceConfigAccess(resourceConfigGuardCtx(ctx), 'agentGroup', group.id, {
+ userId: group.userId,
+ visibility: group.visibility ?? null,
+ workspaceId: group.workspaceId ?? null,
+ });
+
+const protectGroupMemberConfigs = async <T extends Record<string, any>>(
+ ctx: Parameters<typeof resourceConfigGuardCtx>[0],
+ group: T,
+): Promise<T> => {
+ if (!Array.isArray(group.agents) || group.agents.length === 0) return group;
+
+ let changed = false;
+ const protectedAgents = await Promise.all(
+ group.agents.map(async (agent: Record<string, any>) => {
+ const knownMeta =
+ agent.userId && agent.workspaceId !== undefined
+ ? {
+ userId: agent.userId,
+ visibility: agent.visibility ?? null,
+ workspaceId: agent.workspaceId ?? null,
+ }
+ : undefined;
+ const access = await getResourceConfigAccess(
+ resourceConfigGuardCtx(ctx),
+ 'agent',
+ agent.id,
+ knownMeta,
+ );
+
+ if (access === 'none') {
+ changed = true;
+ return null;
+ }
+ if (access === 'profile') {
+ changed = true;
+ return redactAgentConfig(agent);
+ }
+ return agent;
+ }),
+ );
+
+ return changed ? ({ ...group, agents: protectedAgents.filter(Boolean) } as T) : group;
+};
/**
* Custom schema for agent member input, replacing drizzle-generated insertAgentSchema
@@ -80,6 +156,16 @@ export const agentGroupRouter = router({
}),
)
.mutation(async ({ input, ctx }) => {
+ if (ctx.workspaceId) {
+ await assertCanPerformResourceAction({
+ action: 'edit',
+ db: ctx.serverDB,
+ resourceId: input.groupId,
+ resourceType: 'agentGroup',
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
+ });
+ }
return ctx.chatGroupModel.addAgentsToGroup(input.groupId, input.agentIds);
}),
@@ -95,6 +181,16 @@ export const agentGroupRouter = router({
}),
)
.mutation(async ({ input, ctx }) => {
+ if (ctx.workspaceId) {
+ await assertCanPerformResourceAction({
+ action: 'edit',
+ db: ctx.serverDB,
+ resourceId: input.groupId,
+ resourceType: 'agentGroup',
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
+ });
+ }
// Batch create virtual agents
const agentConfigs = input.agents.map((agent) => ({
...agent,
@@ -112,6 +208,25 @@ export const agentGroupRouter = router({
// Add all agents to the group
await ctx.chatGroupModel.addAgentsToGroup(input.groupId, agentIds);
+ if (ctx.workspaceId) {
+ const permissionModel = new ResourcePermissionModel(ctx.serverDB, ctx.workspaceId);
+ // Group-owned members inherit the group's current General Access so a
+ // group already opened to `edit` doesn't spawn `use`-locked members.
+ const groupLevel = await permissionModel.getAccessLevel('agentGroup', input.groupId);
+ await Promise.all(
+ createdAgents
+ .filter((agent) => agent.visibility !== 'private')
+ .map((agent) =>
+ permissionModel.setAccessLevel(
+ 'agent',
+ agent.id,
+ groupLevel ?? DEFAULT_RESOURCE_ACCESS_LEVELS.agent,
+ ctx.userId,
+ ),
+ ),
+ );
+ }
+
return { agentIds, agents: createdAgents };
}),
@@ -127,6 +242,14 @@ export const agentGroupRouter = router({
}),
)
.query(async ({ input, ctx }) => {
+ await assertCanEditResource({
+ db: ctx.serverDB,
+ resourceId: input.groupId,
+ resourceType: 'agentGroup',
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId ?? undefined,
+ });
+
return ctx.agentGroupRepo.checkAgentsBeforeRemoval(input.groupId, input.agentIds);
}),
@@ -143,6 +266,24 @@ export const agentGroupRouter = router({
config: ctx.agentGroupService.normalizeGroupConfig(input.config as ChatGroupConfig | null),
});
+ if (ctx.workspaceId && group.visibility !== 'private') {
+ const permissionModel = new ResourcePermissionModel(ctx.serverDB, ctx.workspaceId);
+ await Promise.all([
+ permissionModel.setAccessLevel(
+ 'agentGroup',
+ group.id,
+ DEFAULT_RESOURCE_ACCESS_LEVELS.agentGroup,
+ ctx.userId,
+ ),
+ permissionModel.setAccessLevel(
+ 'agent',
+ supervisorAgentId,
+ DEFAULT_RESOURCE_ACCESS_LEVELS.agent,
+ ctx.userId,
+ ),
+ ]);
+ }
+
return { group, supervisorAgentId };
}),
@@ -210,26 +351,71 @@ export const agentGroupRouter = router({
supervisorConfig as any,
);
+ if (ctx.workspaceId && group.visibility !== 'private') {
+ const permissionModel = new ResourcePermissionModel(ctx.serverDB, ctx.workspaceId);
+ await Promise.all([
+ permissionModel.setAccessLevel(
+ 'agentGroup',
+ group.id,
+ DEFAULT_RESOURCE_ACCESS_LEVELS.agentGroup,
+ ctx.userId,
+ ),
+ permissionModel.setAccessLevel(
+ 'agent',
+ supervisorAgentId,
+ DEFAULT_RESOURCE_ACCESS_LEVELS.agent,
+ ctx.userId,
+ ),
+ ...createdAgents
+ .filter((agent) => agent.visibility !== 'private')
+ .map((agent) =>
+ permissionModel.setAccessLevel(
+ 'agent',
+ agent.id,
+ DEFAULT_RESOURCE_ACCESS_LEVELS.agent,
+ ctx.userId,
+ ),
+ ),
+ ]);
+ }
+
return { agentIds: memberAgentIds, groupId: group.id, supervisorAgentId };
}),
deleteGroup: agentGroupProcedureWrite
.input(z.object({ id: z.string() }))
.mutation(async ({ input, ctx }) => {
- const group = await ctx.chatGroupModel.findById(input.id);
- if (!group) throw new TRPCError({ code: 'NOT_FOUND', message: 'Agent group not found' });
- assertWorkspaceRowManageable(ctx, group.userId, 'group');
- // Same rule as transfer: deleting the group cascades topics/threads/
- // messages via FK, so a non-owner member must not erase teammates'
- // conversations along with their own group.
- if (isWorkspaceNonOwner(ctx) && (await ctx.agentGroupRepo.transferHasForeignRows(input.id))) {
- throw new TRPCError({
- code: 'FORBIDDEN',
- message: "Only workspace owners can delete a group carrying others' conversations",
+ if (ctx.workspaceId) {
+ await assertCanPerformResourceAction({
+ action: 'delete',
+ db: ctx.serverDB,
+ resourceId: input.id,
+ resourceType: 'agentGroup',
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
});
+ // Same rule as transfer: deleting the group cascades topics/threads/
+ // messages via FK, so a non-owner member must not erase teammates'
+ // conversations along with their own group.
+ if (
+ isWorkspaceNonOwner(ctx) &&
+ (await ctx.agentGroupRepo.transferHasForeignRows(input.id))
+ ) {
+ throw new TRPCError({
+ cause: { data: { code: TransferErrorCode.OwnerOnly } },
+ code: 'FORBIDDEN',
+ message: "Only workspace owners can delete a group carrying others' conversations",
+ });
+ }
}
-
- return ctx.agentGroupService.deleteGroup(input.id);
+ const result = await ctx.agentGroupService.deleteGroup(input.id);
+ if (ctx.workspaceId) {
+ await new ResourcePermissionModel(ctx.serverDB, ctx.workspaceId).removeAll(
+ 'agentGroup',
+ input.id,
+ );
+ }
+ return result;
}),
/**
@@ -245,18 +431,59 @@ export const agentGroupRouter = router({
}),
)
.mutation(async ({ input, ctx }) => {
- return ctx.agentGroupRepo.duplicate(input.groupId, input.newTitle);
+ // Duplicating copies the group config + virtual member agent details,
+ // which a use-only member must not be able to inspect — same edit gate
+ // as `updateGroup`, mirroring the UI's `canEditResource` guard.
+ await assertCanEditResource({
+ db: ctx.serverDB,
+ resourceId: input.groupId,
+ resourceType: 'agentGroup',
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId ?? undefined,
+ });
+
+ const result = await ctx.agentGroupRepo.duplicate(input.groupId, input.newTitle);
+ if (ctx.workspaceId && result) {
+ const permissionModel = new ResourcePermissionModel(ctx.serverDB, ctx.workspaceId);
+ await Promise.all([
+ permissionModel.setAccessLevel(
+ 'agentGroup',
+ result.groupId,
+ DEFAULT_RESOURCE_ACCESS_LEVELS.agentGroup,
+ ctx.userId,
+ ),
+ permissionModel.setAccessLevel(
+ 'agent',
+ result.supervisorAgentId,
+ DEFAULT_RESOURCE_ACCESS_LEVELS.agent,
+ ctx.userId,
+ ),
+ ]);
+ }
+ return result;
}),
getGroup: agentGroupProcedure
.input(z.object({ id: z.string() }))
.query(async ({ input, ctx }) => {
- return ctx.chatGroupModel.findById(input.id);
+ const group = await ctx.chatGroupModel.findById(input.id);
+ if (!group) return group;
+ const access = await getGroupConfigAccess(ctx, group);
+ if (access === 'none') return undefined;
+ return access === 'profile' ? redactGroupConfig(group) : group;
}),
getGroupAgents: agentGroupProcedure
.input(z.object({ groupId: z.string() }))
.query(async ({ input, ctx }) => {
+ await assertCanEditResource({
+ db: ctx.serverDB,
+ resourceId: input.groupId,
+ resourceType: 'agentGroup',
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId ?? undefined,
+ });
+
return ctx.chatGroupModel.getGroupAgents(input.groupId);
}),
@@ -277,29 +504,42 @@ export const agentGroupRouter = router({
getGroupDetail: agentGroupProcedure
.input(z.object({ id: z.string() }))
.query(async ({ input, ctx }) => {
- const [defaultAgentConfig, detail] = await Promise.all([
- ctx.userModel.getUserSettingsDefaultAgentConfig(),
- ctx.agentGroupService.getGroupDetail(input.id),
- ]);
-
+ const detail = await ctx.agentGroupService.getGroupDetail(input.id);
if (!detail) return null;
+ const access = await getGroupConfigAccess(ctx, detail);
+ if (access === 'none') return null;
+ if (access === 'profile') return redactGroupConfig(detail);
- return {
+ const defaultAgentConfig = await ctx.userModel.getUserSettingsDefaultAgentConfig();
+ return protectGroupMemberConfigs(ctx, {
...detail,
agents: ctx.agentGroupService.mergeAgentsDefaultConfig(defaultAgentConfig, detail.agents),
- };
+ });
}),
getGroups: agentGroupProcedure.query(async ({ ctx }) => {
- const [defaultAgentConfig, groups] = await Promise.all([
- ctx.userModel.getUserSettingsDefaultAgentConfig(),
- ctx.agentGroupService.getGroups(),
- ]);
-
- return groups.map((group) => ({
- ...group,
- agents: ctx.agentGroupService.mergeAgentsDefaultConfig(defaultAgentConfig, group.agents),
- }));
+ const groups = await ctx.agentGroupService.getGroups();
+ const accessLevels = await Promise.all(groups.map((group) => getGroupConfigAccess(ctx, group)));
+ const hasFullConfig = accessLevels.includes('full');
+ const defaultAgentConfig = hasFullConfig
+ ? await ctx.userModel.getUserSettingsDefaultAgentConfig()
+ : undefined;
+
+ const protectedGroups = await Promise.all(
+ groups.map(async (group, index) => {
+ const access = accessLevels[index];
+ if (access === 'none') return null;
+ if (access === 'profile') return redactGroupConfig(group);
+ if (!defaultAgentConfig) return group;
+
+ return protectGroupMemberConfigs(ctx, {
+ ...group,
+ agents: ctx.agentGroupService.mergeAgentsDefaultConfig(defaultAgentConfig, group.agents),
+ });
+ }),
+ );
+
+ return protectedGroups.filter((group): group is NonNullable<typeof group> => Boolean(group));
}),
/**
@@ -320,11 +560,16 @@ export const agentGroupRouter = router({
}),
)
.mutation(async ({ input, ctx }) => {
- // Strips members and hard-deletes virtual agents — creator/owner only.
- const group = await ctx.chatGroupModel.findById(input.groupId);
- if (!group) throw new TRPCError({ code: 'NOT_FOUND', message: 'Agent group not found' });
- assertWorkspaceRowManageable(ctx, group.userId, 'group');
-
+ if (ctx.workspaceId) {
+ await assertCanPerformResourceAction({
+ action: 'edit',
+ db: ctx.serverDB,
+ resourceId: input.groupId,
+ resourceType: 'agentGroup',
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
+ });
+ }
return ctx.agentGroupRepo.removeAgentsFromGroup(
input.groupId,
input.agentIds,
@@ -336,6 +581,9 @@ export const agentGroupRouter = router({
.input(
z.object({
groupId: z.string(),
+ targetAccessLevel: z.enum(RESOURCE_ACCESS_LEVELS_BY_TYPE.agentGroup).optional(),
+ /** @deprecated Compatibility for released clients. */
+ targetGeneralAccess: z.enum(['editor', 'viewer']).optional(),
targetVisibility: z.enum(['private', 'public']).optional(),
targetWorkspaceId: z.string().nullable(),
}),
@@ -350,22 +598,15 @@ export const agentGroupRouter = router({
});
}
- if (ctx.workspaceId && group.userId !== ctx.userId) {
- const canOverride = await hasWorkspaceScopedPermission({
- action: 'AGENT_UPDATE',
+ if (ctx.workspaceId) {
+ await assertCanPerformResourceAction({
+ action: 'transfer',
db: ctx.serverDB,
- scopes: ['ALL'],
+ resourceId: input.groupId,
+ resourceType: 'agentGroup',
userId: ctx.userId,
workspaceId: ctx.workspaceId,
});
-
- if (!canOverride) {
- throw new TRPCError({
- cause: { data: { code: TransferErrorCode.OwnerOnly } },
- code: 'FORBIDDEN',
- message: 'Only workspace owners can transfer agent groups created by others',
- });
- }
}
if (input.targetWorkspaceId) {
@@ -406,12 +647,34 @@ export const agentGroupRouter = router({
});
}
- return ctx.agentGroupRepo.transferToWorkspace(
+ const result = await ctx.agentGroupRepo.transferToWorkspace(
input.groupId,
input.targetWorkspaceId,
ctx.userId,
input.targetVisibility,
);
+
+ if (ctx.workspaceId) {
+ await new ResourcePermissionModel(ctx.serverDB, ctx.workspaceId).removeAll(
+ 'agentGroup',
+ input.groupId,
+ );
+ }
+ if (input.targetWorkspaceId && input.targetVisibility === 'public') {
+ const targetAccessLevel =
+ input.targetAccessLevel ??
+ (input.targetGeneralAccess === 'editor'
+ ? 'edit'
+ : DEFAULT_RESOURCE_ACCESS_LEVELS.agentGroup);
+ await new ResourcePermissionModel(ctx.serverDB, input.targetWorkspaceId).setAccessLevel(
+ 'agentGroup',
+ input.groupId,
+ targetAccessLevel,
+ ctx.userId,
+ );
+ }
+
+ return result;
}),
updateAgentInGroup: agentGroupProcedureWrite
@@ -427,6 +690,16 @@ export const agentGroupRouter = router({
}),
)
.mutation(async ({ input, ctx }) => {
+ if (ctx.workspaceId) {
+ await assertCanPerformResourceAction({
+ action: 'edit',
+ db: ctx.serverDB,
+ resourceId: input.groupId,
+ resourceType: 'agentGroup',
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
+ });
+ }
return ctx.chatGroupModel.updateAgentInGroup(input.groupId, input.agentId, input.updates);
}),
@@ -438,7 +711,125 @@ export const agentGroupRouter = router({
publishGroupToWorkspace: agentGroupProcedureWrite
.input(z.object({ id: z.string() }))
.mutation(async ({ input, ctx }) => {
- return ctx.chatGroupModel.publishToWorkspace(input.id);
+ 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,
+ );
+ }
+ return result;
+ }),
+
+ /**
+ * Bidirectional visibility switch for the Permission panel, mirroring
+ * `agent.setAgentVisibility`:
+ * - demoting to private stays creator-only (an owner-initiated demotion
+ * would appropriate the creator's group);
+ * - publishing may also be done by a workspace owner (`AGENT_UPDATE:all`)
+ * or a granted `manager` collaborator.
+ */
+ setGroupVisibility: agentGroupProcedureWrite
+ .input(
+ z.object({
+ accessLevel: z.enum(RESOURCE_ACCESS_LEVELS_BY_TYPE.agentGroup).optional(),
+ id: z.string(),
+ visibility: z.enum(['private', 'public']),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ if (!ctx.workspaceId) {
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message: 'Group visibility only applies inside a workspace',
+ });
+ }
+
+ const group = await ctx.chatGroupModel.findById(input.id);
+ if (!group) throw new TRPCError({ code: 'NOT_FOUND', message: 'Group not found' });
+
+ const permissionModel = new ResourcePermissionModel(ctx.serverDB, ctx.workspaceId);
+ const privateMembersPromise =
+ input.visibility === 'public' && group.visibility !== input.visibility
+ ? ctx.chatGroupModel.countPrivateGroupAgents(input.id)
+ : Promise.resolve(0);
+ const [, privateMembers] = await Promise.all([
+ assertCanPerformResourceAction({
+ action: 'changeVisibility',
+ db: ctx.serverDB,
+ grantedPermissions: (ctx as { workspacePermissionCodes?: string[] })
+ .workspacePermissionCodes,
+ meta: {
+ userId: group.userId,
+ visibility: group.visibility,
+ workspaceId: group.workspaceId,
+ },
+ resourceId: input.id,
+ resourceType: 'agentGroup',
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
+ }),
+ privateMembersPromise,
+ ]);
+ if (group.visibility === input.visibility) {
+ const accessLevel =
+ input.visibility === 'public'
+ ? (input.accessLevel ??
+ (await permissionModel.getEffectiveAccessLevel('agentGroup', input.id)))
+ : 'edit';
+ if (input.visibility === 'public' && input.accessLevel) {
+ await permissionModel.setAccessLevel(
+ 'agentGroup',
+ input.id,
+ input.accessLevel,
+ ctx.userId,
+ );
+ }
+ return buildResourcePermissionState({
+ accessLevel,
+ canManage: true,
+ creatorId: group.userId,
+ visibility: input.visibility,
+ });
+ }
+
+ // A private group may hold the creator's private member agents; those
+ // would leak to every member on publish. Reject until the members are
+ // published or removed (mirrors the composite rule in addAgentsToGroup).
+ if (input.visibility === 'public' && privateMembers > 0) {
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message:
+ 'Cannot publish a group that still contains private agents. Publish or remove those agents first.',
+ });
+ }
+
+ 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);
+ if (input.visibility === 'private') {
+ await permissionModel.removeAll('agentGroup', input.id);
+ } else {
+ await permissionModel.setAccessLevel(
+ 'agentGroup',
+ input.id,
+ input.accessLevel ?? DEFAULT_RESOURCE_ACCESS_LEVELS.agentGroup,
+ ctx.userId,
+ );
+ }
+
+ return buildResourcePermissionState({
+ accessLevel,
+ canManage: true,
+ creatorId: group.userId,
+ visibility: input.visibility,
+ });
}),
updateGroup: agentGroupProcedureWrite
@@ -449,6 +840,15 @@ export const agentGroupRouter = router({
}),
)
.mutation(async ({ input, ctx }) => {
+ // General-access write guard: only `edit` permits collaborative updates.
+ await assertCanEditResource({
+ db: ctx.serverDB,
+ resourceId: input.id,
+ resourceType: 'agentGroup',
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId ?? undefined,
+ });
+
// Collaborative edit lock: reject writes to a workspace group another
// member is actively editing. Inert until a client acquires the lock.
if (ctx.workspaceId) {
diff --git a/apps/server/src/routers/lambda/agentNotify.ts b/apps/server/src/routers/lambda/agentNotify.ts
index 987709527a3..caad3b956dc 100644
--- a/apps/server/src/routers/lambda/agentNotify.ts
+++ b/apps/server/src/routers/lambda/agentNotify.ts
@@ -11,6 +11,7 @@ import { TopicModel } from '@/database/models/topic';
import { router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
import { createStreamEventManager } from '@/server/modules/AgentRuntime/factory';
+import { assertCanUseWorkspaceAgent } from '@/server/routers/lambda/_helpers/workspaceAgentGuard';
import { CompletionLifecycle } from '@/server/services/agentRuntime/CompletionLifecycle';
import type { SerializedHook } from '@/server/services/agentRuntime/hooks/types';
import { AiAgentService } from '@/server/services/aiAgent';
@@ -144,6 +145,16 @@ export const agentNotifyRouter = router({
});
}
+ // Workspace guard: notify executes the resolved agent (directly in user
+ // mode, via `continue` in assistant mode) — require `use` before any write.
+ await assertCanUseWorkspaceAgent({
+ agentId,
+ db: ctx.serverDB,
+ groupId: topic.groupId,
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
+ });
+
/**
* Publish a stream event for remote hetero agents (openclaw / hermes).
* Fire-and-forget — stream publish failures must not break the notify response.
diff --git a/apps/server/src/routers/lambda/aiAgent.ts b/apps/server/src/routers/lambda/aiAgent.ts
index 704455cdf4d..33c9ae933e9 100644
--- a/apps/server/src/routers/lambda/aiAgent.ts
+++ b/apps/server/src/routers/lambda/aiAgent.ts
@@ -20,10 +20,16 @@ import { MessageModel } from '@/database/models/message';
import { ThreadModel } from '@/database/models/thread';
import { TopicModel } from '@/database/models/topic';
import { agentOperations, topics } from '@/database/schemas';
+import type { LobeChatDatabase } from '@/database/type';
import { heteroAuthedProcedure, router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
import { signUserJWT } from '@/libs/trpc/utils/internalJwt';
import { createStreamEventManager } from '@/server/modules/AgentRuntime/factory';
+import {
+ assertCanUseMessageTargets,
+ assertCanUseTopicTargets,
+} from '@/server/routers/lambda/_helpers/conversationResourceGuard';
+import { assertCanUseWorkspaceAgent } from '@/server/routers/lambda/_helpers/workspaceAgentGuard';
import { AgentRuntimeService } from '@/server/services/agentRuntime';
import { AiAgentService } from '@/server/services/aiAgent';
import { AiChatService } from '@/server/services/aiChat';
@@ -32,6 +38,59 @@ import { HeterogeneousAgentService } from '@/server/services/heterogeneousAgent'
const log = debug('lobe-server:ai-agent-router');
+/**
+ * Workspace `use` guard for operation-keyed endpoints: resolve the operation
+ * row to its agent and run the same `use` guard. Operations without an agent
+ * (detached / legacy rows) fall through — there is no resource to guard.
+ * No-op in personal mode (no workspaceId).
+ */
+const assertCanUseOperationAgent = async (params: {
+ db: LobeChatDatabase;
+ operationId: string;
+ userId: string;
+ workspaceId?: string | null;
+}) => {
+ const { db, operationId, userId, workspaceId } = params;
+ if (!workspaceId) return;
+
+ const [row] = await db
+ .select({ agentId: agentOperations.agentId })
+ .from(agentOperations)
+ .where(eq(agentOperations.id, operationId))
+ .limit(1);
+ if (!row?.agentId) return;
+
+ await assertCanUseWorkspaceAgent({
+ agentId: row.agentId,
+ db,
+ userId,
+ workspaceId,
+ });
+};
+
+/**
+ * Resolve client-supplied conversation ids before an agent run writes through
+ * AiAgentService. Checking only the requested agent/group is insufficient: an
+ * existing topic or parent message can belong to a different, view-only
+ * workspace resource.
+ */
+const assertCanUseAgentRunConversation = async (params: {
+ db: LobeChatDatabase;
+ messageIds?: Array<string | null | undefined>;
+ topicId?: string | null;
+ userId: string;
+ workspaceId?: string | null;
+}) => {
+ const { db, messageIds = [], topicId, userId, workspaceId } = params;
+ if (!workspaceId) return;
+
+ const uniqueMessageIds = [...new Set(messageIds.filter(Boolean) as string[])];
+ await Promise.all([
+ assertCanUseTopicTargets({ db, userId, workspaceId }, topicId ? [topicId] : []),
+ assertCanUseMessageTargets({ db, userId, workspaceId }, uniqueMessageIds),
+ ]);
+};
+
const createUiMessageFileUrlResolver = () => {
return async (path: string | null, file: { fileType: string; id?: string | null }) =>
file.id ? getFileProxyUrl(file.id) : (path ?? '');
@@ -572,6 +631,21 @@ export const aiAgentRouter = router({
log('createClientGroupAgentTaskThread: subAgentId=%s, groupId=%s', subAgentId, groupId);
try {
+ await assertCanUseWorkspaceAgent({
+ agentId: subAgentId,
+ db: ctx.serverDB,
+ groupId,
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
+ });
+ await assertCanUseAgentRunConversation({
+ db: ctx.serverDB,
+ messageIds: [parentMessageId],
+ topicId,
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
+ });
+
// 1. Create Thread for isolated task execution
// Use subAgentId as the thread's agentId (the executing agent)
const startedAt = new Date().toISOString();
@@ -667,6 +741,21 @@ export const aiAgentRouter = router({
log('createClientTaskThread: agentId=%s, groupId=%s', agentId, groupId);
try {
+ await assertCanUseWorkspaceAgent({
+ agentId,
+ db: ctx.serverDB,
+ groupId,
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
+ });
+ await assertCanUseAgentRunConversation({
+ db: ctx.serverDB,
+ messageIds: [parentMessageId],
+ topicId,
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
+ });
+
// 1. Create Thread for isolated task execution
const startedAt = new Date().toISOString();
const thread = await ctx.threadModel.create({
@@ -766,6 +855,26 @@ export const aiAgentRouter = router({
log('execAgent: identifier=%s, prompt=%s', agentId || slug, prompt.slice(0, 50));
try {
+ await assertCanUseWorkspaceAgent({
+ agentId,
+ db: ctx.serverDB,
+ groupId: appContext?.groupId,
+ slug,
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
+ });
+ await assertCanUseAgentRunConversation({
+ db: ctx.serverDB,
+ messageIds: [
+ ...existingMessageIds,
+ parentMessageId,
+ resumeApproval?.parentMessageId,
+ resumeToolResult?.parentMessageId,
+ ],
+ topicId: appContext?.topicId,
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
+ });
return await ctx.aiAgentService.execAgent({
agentId,
appContext,
@@ -824,6 +933,13 @@ export const aiAgentRouter = router({
log('scheduleAgentRun: identifier=%s, runAt=%s', input.agentId || input.slug, input.runAt);
try {
+ await assertCanUseWorkspaceAgent({
+ agentId: input.agentId,
+ db: ctx.serverDB,
+ slug: input.slug,
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
+ });
return await ctx.aiAgentService.scheduleAgentRun(input);
} catch (error: any) {
if (error instanceof TRPCError) throw error;
@@ -870,6 +986,26 @@ export const aiAgentRouter = router({
} = task;
try {
+ await assertCanUseWorkspaceAgent({
+ agentId,
+ db: ctx.serverDB,
+ groupId: appContext?.groupId,
+ slug,
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
+ });
+ await assertCanUseAgentRunConversation({
+ db: ctx.serverDB,
+ messageIds: [
+ ...existingMessageIds,
+ parentMessageId,
+ task.resumeApproval?.parentMessageId,
+ task.resumeToolResult?.parentMessageId,
+ ],
+ topicId: appContext?.topicId,
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
+ });
const result = await ctx.aiAgentService.execAgent({
agentId,
appContext,
@@ -940,6 +1076,20 @@ export const aiAgentRouter = router({
log('execGroupAgent: agentId=%s, groupId=%s', agentId, groupId);
try {
+ await assertCanUseWorkspaceAgent({
+ agentId,
+ db: ctx.serverDB,
+ groupId,
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
+ });
+ await assertCanUseAgentRunConversation({
+ db: ctx.serverDB,
+ messageIds: newTopic?.topicMessageIds,
+ topicId,
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
+ });
// Execute group agent
const result = await ctx.aiAgentService.execGroupAgent({
agentId,
@@ -1003,6 +1153,21 @@ export const aiAgentRouter = router({
log('execSubAgentTask: agentId=%s, groupId=%s', agentId, groupId);
try {
+ await assertCanUseWorkspaceAgent({
+ agentId,
+ db: ctx.serverDB,
+ groupId,
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
+ });
+ await assertCanUseAgentRunConversation({
+ db: ctx.serverDB,
+ messageIds: [parentMessageId],
+ topicId,
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
+ });
+
// External procedure name stays `execSubAgentTask`; the service method is `execSubAgent`.
return await ctx.aiAgentService.execSubAgent({
agentId,
@@ -1540,7 +1705,7 @@ export const aiAgentRouter = router({
*/
submitHeteroIntervention: aiAgentWriteProcedure
.input(SubmitHeteroInterventionSchema)
- .mutation(async ({ input }) => {
+ .mutation(async ({ input, ctx }) => {
const { operationId, toolCallId, stepIndex, result, cancelled, cancelReason } = input;
log(
@@ -1550,6 +1715,13 @@ export const aiAgentRouter = router({
cancelled ?? false,
);
+ await assertCanUseOperationAgent({
+ db: ctx.serverDB,
+ operationId,
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
+ });
+
const streamEventManager = createStreamEventManager();
await streamEventManager.publishStreamEvent(operationId, {
data: {
@@ -1572,6 +1744,13 @@ export const aiAgentRouter = router({
log(`Processing ${action} for operation ${operationId}`);
+ await assertCanUseOperationAgent({
+ db: ctx.serverDB,
+ operationId,
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
+ });
+
// Build intervention parameters
const interventionParams: any = {
action,
@@ -1643,6 +1822,13 @@ export const aiAgentRouter = router({
log('Starting execution for operation %s', operationId);
+ await assertCanUseOperationAgent({
+ db: ctx.serverDB,
+ operationId,
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
+ });
+
// Start execution using AgentRuntimeService
const result = await ctx.agentRuntimeService.startExecution({
context,
diff --git a/apps/server/src/routers/lambda/device.ts b/apps/server/src/routers/lambda/device.ts
index be3bc023ded..16e65b56789 100644
--- a/apps/server/src/routers/lambda/device.ts
+++ b/apps/server/src/routers/lambda/device.ts
@@ -55,6 +55,25 @@ const canEditWorkspaceDevice = (
enrollerUserId: string,
): boolean => role === 'owner' || enrollerUserId === actorUserId;
+/**
+ * Fixed workspace agents promise every member the same execution device. Keep
+ * that promise intact until an editor changes the agent back to member choice
+ * (or binds a different public device) before hiding/removing this row.
+ */
+const assertDeviceNotBoundToFixedAgent = async (
+ model: DeviceModel,
+ deviceId: string,
+): Promise<void> => {
+ if (!(await model.hasFixedAgentBinding(deviceId))) return;
+
+ throw new TRPCError({
+ cause: { data: { code: 'DeviceBoundToFixedAgent' } },
+ code: 'PRECONDITION_FAILED',
+ message:
+ 'This device is fixed to one or more workspace agents. Change those agent settings first.',
+ });
+};
+
/**
* Workspace-write gate: membership + at least `member` role (excludes viewer).
* Enrolling a device mutates the shared workspace device pool, so read-only
@@ -1047,6 +1066,9 @@ export const deviceRouter = router({
message: 'Only the enrolling member or a workspace owner can overwrite this device.',
});
}
+ if ((input.visibility ?? 'private') === 'private') {
+ await assertDeviceNotBoundToFixedAgent(model, existing.deviceId);
+ }
}
// Real enrollment — only after the caller is committed (no pending
@@ -1149,6 +1171,9 @@ export const deviceRouter = router({
message: 'Only the enrolling member can change this device visibility.',
});
}
+ if (input.visibility === 'private') {
+ await assertDeviceNotBoundToFixedAgent(model, input.deviceId);
+ }
await model.setWorkspaceDeviceVisibility(input.deviceId, input.visibility);
return { success: true };
}),
@@ -1211,6 +1236,7 @@ export const deviceRouter = router({
message: 'Only the enrolling member or a workspace owner can remove this device.',
});
}
+ await assertDeviceNotBoundToFixedAgent(model, input.deviceId);
// Tell a live device to drop its workspace connection and stop
// auto-reconnecting, so removal doesn't leave an online ghost. For most
// rows this stays best-effort — an offline device simply stops resolving.
diff --git a/apps/server/src/routers/lambda/document.ts b/apps/server/src/routers/lambda/document.ts
index 7a87c0ead09..a4722d21f50 100644
--- a/apps/server/src/routers/lambda/document.ts
+++ b/apps/server/src/routers/lambda/document.ts
@@ -9,16 +9,21 @@ import { ChunkModel } from '@/database/models/chunk';
import { DocumentModel } from '@/database/models/document';
import { FileModel } from '@/database/models/file';
import { MessageModel } from '@/database/models/message';
+import { ResourcePermissionModel } from '@/database/models/resourcePermission';
+import { DEFAULT_RESOURCE_ACCESS_LEVELS } from '@/database/schemas';
import { router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
import { DocumentService } from '@/server/services/document';
+import {
+ assertCanEditResource,
+ assertCanPerformResourceAction,
+ buildResourcePermissionState,
+ getResourceMeta,
+} from '@/server/services/resourcePermission';
import { hasWorkspaceScopedPermission } from '@/server/services/workspacePermission';
import { TransferErrorCode } from '@/types/transferError';
-import {
- assertWorkspaceRowManageable,
- isWorkspaceNonOwner,
-} from './_helpers/assertWorkspaceRowManageable';
+import { isWorkspaceNonOwner } from './_helpers/assertWorkspaceRowManageable';
import {
compareDocumentHistoryItemsInputSchema,
getDocumentHistoryItemInputSchema,
@@ -27,6 +32,32 @@ import {
updateDocumentInputSchema,
} from './_schema/documentHistory';
+/**
+ * Creating a child modifies the parent's tree — viewers of a workspace-shared
+ * parent must not be able to insert under it. Parents outside the current
+ * workspace (personal docs, foreign ids) fall through; the model's ownership
+ * WHERE keeps those unreachable anyway.
+ */
+const assertCanCreateUnderParent = async (
+ ctx: {
+ serverDB: Parameters<typeof getResourceMeta>[0];
+ userId: string;
+ workspaceId?: string | null;
+ },
+ parentId: string | undefined,
+) => {
+ if (!ctx.workspaceId || !parentId) return;
+ const meta = await getResourceMeta(ctx.serverDB, 'document', parentId);
+ if (!meta || meta.workspaceId !== ctx.workspaceId) return;
+ await assertCanEditResource({
+ db: ctx.serverDB,
+ resourceId: parentId,
+ resourceType: 'document',
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
+ });
+};
+
const getFreeDocumentHistorySince = () => {
const now = Date.now();
@@ -62,8 +93,7 @@ export const documentRouter = router({
slug: z.string().optional(),
title: z.string(),
// Workspace-only knob; ignored in personal mode by the model layer.
- // When omitted: top-level docs default to 'private' (sidebar's primary
- // entry point), nested docs inherit the parent's visibility.
+ // When omitted, user-authored workspace docs default to private.
visibility: z.enum(['private', 'public']).optional(),
}),
)
@@ -77,13 +107,24 @@ export const documentRouter = router({
}
}
+ await assertCanCreateUnderParent(ctx, resolvedParentId);
+
// Parse editorData from JSON string to object
const editorData = input.editorData ? JSON.parse(input.editorData) : undefined;
- return ctx.documentService.createDocument({
+ const document = await ctx.documentService.createDocument({
...input,
editorData,
parentId: resolvedParentId,
});
+ if (ctx.workspaceId && document.visibility !== 'private') {
+ await new ResourcePermissionModel(ctx.serverDB, ctx.workspaceId).setAccessLevel(
+ 'document',
+ document.id,
+ DEFAULT_RESOURCE_ACCESS_LEVELS.document,
+ ctx.userId,
+ );
+ }
+ return document;
}),
createDocuments: documentProcedure
@@ -129,36 +170,87 @@ export const documentRouter = router({
}),
);
- return ctx.documentService.createDocuments(processedDocuments);
+ // Same parent-edit guard as `createDocument`, deduped across the batch.
+ const parentIds = [
+ ...new Set(processedDocuments.map((doc) => doc.parentId).filter(Boolean)),
+ ] as string[];
+ for (const parentId of parentIds) {
+ await assertCanCreateUnderParent(ctx, parentId);
+ }
+
+ const createdDocuments = await ctx.documentService.createDocuments(processedDocuments);
+ if (ctx.workspaceId) {
+ const permissionModel = new ResourcePermissionModel(ctx.serverDB, ctx.workspaceId);
+ await Promise.all(
+ createdDocuments
+ .filter((document) => document.visibility !== 'private')
+ .map((document) =>
+ permissionModel.setAccessLevel(
+ 'document',
+ document.id,
+ DEFAULT_RESOURCE_ACCESS_LEVELS.document,
+ ctx.userId,
+ ),
+ ),
+ );
+ }
+ return createdDocuments;
}),
deleteDocument: documentProcedure
.use(withScopedPermission('document:delete'))
.input(z.object({ id: z.string() }))
.mutation(async ({ ctx, input }) => {
- const existing = await ctx.documentModel.findById(input.id);
- if (!existing) return;
- assertWorkspaceRowManageable(ctx, existing.userId, 'document');
-
+ if (ctx.workspaceId) {
+ await assertCanPerformResourceAction({
+ action: 'delete',
+ db: ctx.serverDB,
+ resourceId: input.id,
+ resourceType: 'document',
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
+ });
+ }
// Non-owner members may delete their own folder, but the recursive
// cascade must not take other members' descendants with it.
- return ctx.documentService.deleteDocument(input.id, {
+ const result = await ctx.documentService.deleteDocument(input.id, {
restrictToCreator: isWorkspaceNonOwner(ctx),
});
+ if (ctx.workspaceId) {
+ await new ResourcePermissionModel(ctx.serverDB, ctx.workspaceId).removeAll(
+ 'document',
+ input.id,
+ );
+ }
+ return result;
}),
deleteDocuments: documentProcedure
.use(withScopedPermission('document:delete'))
.input(z.object({ ids: z.array(z.string()) }))
.mutation(async ({ ctx, input }) => {
- const targets = await ctx.documentModel.findByIds(input.ids);
- for (const target of targets) {
- assertWorkspaceRowManageable(ctx, target.userId, 'document');
+ if (ctx.workspaceId) {
+ await Promise.all(
+ input.ids.map((id) =>
+ assertCanPerformResourceAction({
+ action: 'delete',
+ db: ctx.serverDB,
+ resourceId: id,
+ resourceType: 'document',
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId!,
+ }),
+ ),
+ );
}
-
- return ctx.documentService.deleteDocuments(input.ids, {
+ const result = await ctx.documentService.deleteDocuments(input.ids, {
restrictToCreator: isWorkspaceNonOwner(ctx),
});
+ if (ctx.workspaceId) {
+ const permissionModel = new ResourcePermissionModel(ctx.serverDB, ctx.workspaceId);
+ await Promise.all(input.ids.map((id) => permissionModel.removeAll('document', id)));
+ }
+ return result;
}),
getDocumentById: documentProcedure
@@ -201,6 +293,16 @@ export const documentRouter = router({
.use(withScopedPermission('document:update'))
.input(saveDocumentHistoryInputSchema)
.mutation(async ({ ctx, input }) => {
+ // Same write guard as `updateDocument` — history saves rewrite the
+ // document's editorData, so a view-level member must not reach it.
+ await assertCanEditResource({
+ db: ctx.serverDB,
+ resourceId: input.documentId,
+ resourceType: 'document',
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId ?? undefined,
+ });
+
const editorData = JSON.parse(input.editorData);
return ctx.documentService.saveDocumentHistory(
input.documentId,
@@ -281,6 +383,16 @@ export const documentRouter = router({
.use(withScopedPermission('document:update'))
.input(z.object({ id: z.string(), ownerId: z.string().optional() }))
.mutation(async ({ ctx, input }) => {
+ // The lock grants exclusive write access — a view-level member must not
+ // be able to seize it and starve legitimate editors.
+ await assertCanEditResource({
+ db: ctx.serverDB,
+ resourceId: input.id,
+ resourceType: 'document',
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId ?? undefined,
+ });
+
return input.ownerId
? ctx.documentService.acquireDocumentLockWithOwner(input.id, input.ownerId)
: ctx.documentService.acquireDocumentLock(input.id);
@@ -306,6 +418,30 @@ export const documentRouter = router({
.use(withScopedPermission('document:update'))
.input(updateDocumentInputSchema)
.mutation(async ({ ctx, input }) => {
+ // General-access write guard: a public document whose workspace level
+ // is `viewer` is read-only for everyone but the creator / owner.
+ await assertCanEditResource({
+ db: ctx.serverDB,
+ resourceId: input.id,
+ resourceType: 'document',
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId ?? undefined,
+ });
+
+ // A move mutates both the source and destination trees as well as the
+ // document. Only check when the parent really changes: several editor
+ // paths include the current parentId in ordinary metadata/autosave
+ // updates. `null` is an explicit detach and still leaves the source.
+ if (input.parentId !== undefined) {
+ const currentDocument = await ctx.documentModel.findById(input.id);
+ const currentParentId = currentDocument?.parentId ?? null;
+ const nextParentId = input.parentId ?? null;
+ if (currentParentId !== nextParentId) {
+ if (currentParentId) await assertCanCreateUnderParent(ctx, currentParentId);
+ if (nextParentId) await assertCanCreateUnderParent(ctx, nextParentId);
+ }
+ }
+
const { id, editorData: editorDataString, ...params } = input;
// Parse editorData from JSON string to object if present
const editorData = editorDataString ? JSON.parse(editorDataString) : undefined;
@@ -322,6 +458,7 @@ export const documentRouter = router({
.input(
z.object({
documentId: z.string(),
+ targetAccessLevel: z.enum(['view', 'edit']).optional(),
targetVisibility: z.enum(['private', 'public']).optional(),
targetWorkspaceId: z.string().nullable(),
}),
@@ -335,22 +472,15 @@ export const documentRouter = router({
message: 'Document not found',
});
- // Workspace mode: only owners can transfer items created by others
- if (ctx.workspaceId && doc.userId !== ctx.userId) {
- const canOverride = await hasWorkspaceScopedPermission({
- action: 'DOCUMENT_UPDATE',
+ if (ctx.workspaceId) {
+ await assertCanPerformResourceAction({
+ action: 'transfer',
db: ctx.serverDB,
- scopes: ['ALL'],
+ resourceId: input.documentId,
+ resourceType: 'document',
userId: ctx.userId,
workspaceId: ctx.workspaceId,
});
- if (!canOverride) {
- throw new TRPCError({
- cause: { data: { code: TransferErrorCode.OwnerOnly } },
- code: 'FORBIDDEN',
- message: 'Only workspace owners can transfer items created by others',
- });
- }
}
if (input.targetWorkspaceId === (ctx.workspaceId ?? null)) {
@@ -377,6 +507,20 @@ export const documentRouter = router({
}
}
+ // The transfer rehomes every descendant document and anchored file. A
+ // non-owner member may transfer their own root only when the entire
+ // subtree is theirs; workspace owners retain the administrative override.
+ if (
+ isWorkspaceNonOwner(ctx) &&
+ (await ctx.documentModel.subtreeHasForeignRows(input.documentId))
+ ) {
+ throw new TRPCError({
+ cause: { data: { code: TransferErrorCode.OwnerOnly } },
+ code: 'FORBIDDEN',
+ message: "Only workspace owners can transfer a document tree containing others' content",
+ });
+ }
+
const additionalSize = await ctx.documentModel.countFileUsageInSubtree(input.documentId);
await businessFileTransferStorageCheck({
additionalSize,
@@ -384,37 +528,91 @@ export const documentRouter = router({
targetWorkspaceId: input.targetWorkspaceId,
});
- return ctx.documentModel.transferTo(
+ const result = await ctx.documentModel.transferTo(
input.documentId,
input.targetWorkspaceId,
ctx.userId,
input.targetVisibility,
);
+ if (ctx.workspaceId) {
+ const sourcePermissionModel = new ResourcePermissionModel(ctx.serverDB, ctx.workspaceId);
+ await Promise.all(
+ result.documentIds.map((id) => sourcePermissionModel.removeAll('document', id)),
+ );
+ }
+ if (input.targetWorkspaceId && input.targetVisibility === 'public') {
+ const targetPermissionModel = new ResourcePermissionModel(
+ ctx.serverDB,
+ input.targetWorkspaceId,
+ );
+ await Promise.all(
+ result.documentIds.map((id) =>
+ targetPermissionModel.setAccessLevel(
+ 'document',
+ id,
+ input.targetAccessLevel ?? DEFAULT_RESOURCE_ACCESS_LEVELS.document,
+ ctx.userId,
+ ),
+ ),
+ );
+ }
+ return result;
}),
/**
- * Publish a private document subtree into the workspace. Thin wrapper
+ * Publish one private document into the workspace. Thin wrapper
* around `setDocumentVisibility({ id, visibility: 'public' })`; kept for
* backwards compatibility with existing callers.
*/
publishDocumentToWorkspace: documentProcedure
.use(withScopedPermission('document:update'))
- .input(z.object({ id: z.string() }))
+ .input(z.object({ accessLevel: z.enum(['view', 'edit']).optional(), id: z.string() }))
.mutation(async ({ ctx, input }) => {
- return ctx.documentService.publishToWorkspace(input.id);
+ // Same guard as the sibling `setDocumentVisibility` — publishing is a
+ // visibility change and stays creator-only.
+ if (ctx.workspaceId) {
+ const doc = await ctx.documentModel.findById(input.id);
+ if (!doc) throw new TRPCError({ code: 'NOT_FOUND', message: 'Document not found' });
+
+ await assertCanPerformResourceAction({
+ action: 'changeVisibility',
+ db: ctx.serverDB,
+ grantedPermissions: (ctx as { workspacePermissionCodes?: string[] })
+ .workspacePermissionCodes,
+ meta: {
+ userId: doc.userId,
+ visibility: doc.visibility,
+ workspaceId: doc.workspaceId,
+ },
+ resourceId: input.id,
+ resourceType: 'document',
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
+ });
+ }
+
+ const result = await ctx.documentService.publishToWorkspace(input.id);
+ if (ctx.workspaceId) {
+ await new ResourcePermissionModel(ctx.serverDB, ctx.workspaceId).setAccessLevel(
+ 'document',
+ input.id,
+ input.accessLevel ?? DEFAULT_RESOURCE_ACCESS_LEVELS.document,
+ ctx.userId,
+ );
+ }
+ return result;
}),
/**
- * Toggle a document subtree's workspace visibility. Cascades over the whole
- * subtree so a folder Page and every nested child flip together (P1 tree
- * consistency). Creator-only. Personal mode has no workspace visibility
- * concept, so the call is rejected there.
+ * Toggle one document's workspace visibility. Documents do not inherit from
+ * their parent, so children are deliberately left unchanged.
*/
setDocumentVisibility: documentProcedure
.use(withScopedPermission('document:update'))
.input(
z.object({
id: z.string(),
+ accessLevel: z.enum(['view', 'edit']).optional(),
visibility: z.enum(['private', 'public']),
}),
)
@@ -429,14 +627,67 @@ export const documentRouter = router({
const doc = await ctx.documentModel.findById(input.id);
if (!doc) throw new TRPCError({ code: 'NOT_FOUND', message: 'Document not found' });
- if (doc.userId !== ctx.userId) {
- throw new TRPCError({
- code: 'FORBIDDEN',
- message: 'Only the creator can change a document’s visibility',
- });
+ await assertCanPerformResourceAction({
+ action: 'changeVisibility',
+ db: ctx.serverDB,
+ grantedPermissions: (ctx as { workspacePermissionCodes?: string[] })
+ .workspacePermissionCodes,
+ meta: {
+ userId: doc.userId,
+ visibility: doc.visibility,
+ workspaceId: doc.workspaceId,
+ },
+ resourceId: input.id,
+ resourceType: 'document',
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
+ });
+
+ const permissionModel = new ResourcePermissionModel(ctx.serverDB, ctx.workspaceId);
+ if (doc.visibility === input.visibility) {
+ const accessLevel =
+ input.visibility === 'public'
+ ? (input.accessLevel ??
+ (await permissionModel.getEffectiveAccessLevel('document', input.id)))
+ : 'edit';
+ if (input.visibility === 'public' && input.accessLevel) {
+ await permissionModel.setAccessLevel('document', input.id, input.accessLevel, ctx.userId);
+ }
+ return {
+ ...buildResourcePermissionState({
+ accessLevel,
+ canManage: true,
+ creatorId: doc.userId,
+ visibility: input.visibility,
+ }),
+ documentIds: [input.id],
+ };
}
- return ctx.documentService.setVisibility(input.id, input.visibility);
+ const result = await ctx.documentService.setVisibility(input.id, input.visibility);
+ const accessLevel =
+ input.visibility === 'private'
+ ? 'edit'
+ : (input.accessLevel ?? DEFAULT_RESOURCE_ACCESS_LEVELS.document);
+ if (input.visibility === 'private') {
+ await permissionModel.removeAll('document', input.id);
+ } else {
+ await permissionModel.setAccessLevel(
+ 'document',
+ input.id,
+ input.accessLevel ?? DEFAULT_RESOURCE_ACCESS_LEVELS.document,
+ ctx.userId,
+ );
+ }
+ return {
+ ...buildResourcePermissionState({
+ accessLevel,
+ canManage: true,
+ creatorId: doc.userId,
+ visibility: input.visibility,
+ }),
+ ...result,
+ };
}),
copyDocumentToWorkspace: documentProcedure
diff --git a/apps/server/src/routers/lambda/file.ts b/apps/server/src/routers/lambda/file.ts
index 15935fb36f8..ff5af8aa5b3 100644
--- a/apps/server/src/routers/lambda/file.ts
+++ b/apps/server/src/routers/lambda/file.ts
@@ -23,6 +23,7 @@ import { router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
import { DocumentService } from '@/server/services/document';
import { FileService } from '@/server/services/file';
+import { assertCanPerformResourceAction } from '@/server/services/resourcePermission';
import { hasWorkspaceScopedPermission } from '@/server/services/workspacePermission';
import { AsyncTaskStatus, AsyncTaskType, type IAsyncTaskError } from '@/types/asyncTask';
import type { FileListItem, KnowledgeItemStatus } from '@/types/files';
@@ -515,6 +516,22 @@ export const fileRouter = router({
}
if (documentIds.length > 0) {
+ // Per-document delete guard, mirroring `document.deleteDocuments` — a
+ // query-driven sweep must not delete shared docs the member can't delete.
+ if (ctx.workspaceId) {
+ await Promise.all(
+ documentIds.map((id) =>
+ assertCanPerformResourceAction({
+ action: 'delete',
+ db: ctx.serverDB,
+ resourceId: id,
+ resourceType: 'document',
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId!,
+ }),
+ ),
+ );
+ }
await ctx.documentService.deleteDocuments(documentIds, { restrictToCreator });
}
@@ -821,7 +838,17 @@ export const fileRouter = router({
message: input.entityType === 'folder' ? 'Folder not found' : 'Document not found',
});
}
- assertWorkspaceRowManageable(ctx, document.userId, 'document');
+ // Transfer stays creator-only, mirroring `document.transferDocument`.
+ if (ctx.workspaceId) {
+ await assertCanPerformResourceAction({
+ action: 'transfer',
+ db: ctx.serverDB,
+ resourceId: input.id,
+ resourceType: 'document',
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
+ });
+ }
// The transfer rehomes the entire subtree — a non-owner member must
// not move teammates' documents/files along with their own folder.
if (isWorkspaceNonOwner(ctx) && (await ctx.documentModel.subtreeHasForeignRows(input.id))) {
diff --git a/apps/server/src/routers/lambda/index.ts b/apps/server/src/routers/lambda/index.ts
index af61431ebb9..35d8eed9ba0 100644
--- a/apps/server/src/routers/lambda/index.ts
+++ b/apps/server/src/routers/lambda/index.ts
@@ -68,6 +68,7 @@ import { pluginRouter } from './plugin';
import { pushTokenRouter } from './pushToken';
import { ragEvalRouter } from './ragEval';
import { recentRouter } from './recent';
+import { resourcePermissionRouter } from './resourcePermission';
import { searchRouter } from './search';
import { sessionRouter } from './session';
import { sessionGroupRouter } from './sessionGroup';
@@ -140,6 +141,7 @@ export const lambdaRouter = router({
pushToken: pushTokenRouter,
ragEval: ragEvalRouter,
recent: recentRouter,
+ resourcePermission: resourcePermissionRouter,
search: searchRouter,
session: sessionRouter,
sessionGroup: sessionGroupRouter,
diff --git a/apps/server/src/routers/lambda/message.ts b/apps/server/src/routers/lambda/message.ts
index 02f00dfc4c6..2a7834c2e63 100644
--- a/apps/server/src/routers/lambda/message.ts
+++ b/apps/server/src/routers/lambda/message.ts
@@ -22,11 +22,24 @@ import { serverDatabase } from '@/libs/trpc/lambda/middleware';
import { FileService } from '@/server/services/file';
import { type MessageBatchOperation, MessageService } from '@/server/services/message';
+import {
+ assertCanUseConversationTargets,
+ assertCanUseCreateMessageTargets,
+ assertCanUseMessageTargets,
+ assertCanUseTopicTargets,
+} from './_helpers/conversationResourceGuard';
import { resolveAgentIdFromSession, resolveContext } from './_helpers/resolveContext';
import { basicContextSchema } from './_schema/context';
const { logTiming, runTimedStage } = createTimingHelpers('lobe-server:chat:lobehub:timing');
+/** Ctx slice consumed by the conversation General-access guards. */
+const guardCtx = (ctx: {
+ serverDB: Parameters<typeof assertCanUseMessageTargets>[0]['db'];
+ userId: string;
+ workspaceId?: string | null;
+}) => ({ db: ctx.serverDB, userId: ctx.userId, workspaceId: ctx.workspaceId });
+
const messageProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {
const { ctx } = opts;
const wsId = ctx.workspaceId ?? undefined;
@@ -97,6 +110,7 @@ export const messageRouter = router({
)
.mutation(async ({ input, ctx }) => {
const { id, fileIds, agentId, ...options } = input;
+ await assertCanUseMessageTargets(guardCtx(ctx), [id]);
const resolved = await resolveContext(
{ agentId, ...options },
ctx.serverDB,
@@ -143,6 +157,15 @@ export const messageRouter = router({
}),
);
+ await assertCanUseMessageTargets(
+ guardCtx(ctx),
+ operations.flatMap((op) => (op.type === 'createMessage' ? [] : [op.id])),
+ );
+ await assertCanUseCreateMessageTargets(
+ guardCtx(ctx),
+ operations.flatMap((op) => (op.type === 'createMessage' ? [op.message] : [])),
+ );
+
return ctx.messageService.batchMutate(operations);
}),
@@ -163,6 +186,7 @@ export const messageRouter = router({
)
.mutation(async ({ input, ctx }) => {
const { messageGroupId, agentId, groupId, threadId, topicId } = input;
+ await assertCanUseTopicTargets(guardCtx(ctx), [topicId]);
return ctx.messageService.cancelCompression(messageGroupId, {
agentId,
@@ -231,6 +255,7 @@ export const messageRouter = router({
)
.mutation(async ({ input, ctx }) => {
const { topicId, messageIds, agentId, groupId, threadId } = input;
+ await assertCanUseTopicTargets(guardCtx(ctx), [topicId]);
return ctx.messageService.createCompressionGroup(topicId, messageIds, {
agentId,
@@ -255,6 +280,14 @@ export const messageRouter = router({
))!;
}
+ await assertCanUseConversationTargets(guardCtx(ctx), [{ agentId, groupId: input.groupId }]);
+ // The declared agent/group is client-supplied and can be omitted or
+ // forged while still inserting into `topicId` — guard the topic's own
+ // DB-resolved target as well.
+ if (input.topicId) {
+ await assertCanUseTopicTargets(guardCtx(ctx), [input.topicId]);
+ }
+
// Create message with the resolved agentId
return ctx.messageService.createMessage({ ...input, agentId } as any);
}),
@@ -276,6 +309,7 @@ export const messageRouter = router({
)
.mutation(async ({ input, ctx }) => {
const { messageGroupId, content, ...params } = input;
+ await assertCanUseTopicTargets(guardCtx(ctx), [params.topicId]);
return ctx.messageService.finalizeCompression(messageGroupId, content, params);
}),
@@ -398,6 +432,7 @@ export const messageRouter = router({
)
.mutation(async ({ input, ctx }) => {
const { id, agentId, ...options } = input;
+ await assertCanUseMessageTargets(guardCtx(ctx), [id]);
const resolved = await resolveContext(
{ agentId, ...options },
ctx.serverDB,
@@ -412,6 +447,8 @@ export const messageRouter = router({
.use(withScopedPermission('message:delete'))
.input(z.object({ id: z.string() }))
.mutation(async ({ input, ctx }) => {
+ await assertCanUseMessageTargets(guardCtx(ctx), [input.id]);
+
return ctx.messageModel.deleteMessageQuery(input.id);
}),
@@ -426,6 +463,7 @@ export const messageRouter = router({
)
.mutation(async ({ input, ctx }) => {
const { ids, agentId, ...options } = input;
+ await assertCanUseMessageTargets(guardCtx(ctx), ids);
const resolved = await resolveContext(
{ agentId, ...options },
ctx.serverDB,
@@ -447,6 +485,11 @@ export const messageRouter = router({
)
.mutation(async ({ input, ctx }) => {
const { agentId, ...options } = input;
+ // Row-based guard via the topic when available; sweeps without a topic
+ // fall back to the declared agent target.
+ if (options.topicId) await assertCanUseTopicTargets(guardCtx(ctx), [options.topicId]);
+ else
+ await assertCanUseConversationTargets(guardCtx(ctx), [{ agentId, groupId: input.groupId }]);
const resolved = await resolveContext(
{ agentId, ...options },
ctx.serverDB,
@@ -470,6 +513,9 @@ export const messageRouter = router({
}),
)
.mutation(async ({ input, ctx }) => {
+ if (input.topicId) await assertCanUseTopicTargets(guardCtx(ctx), [input.topicId]);
+ else await assertCanUseConversationTargets(guardCtx(ctx), [{ groupId: input.groupId }]);
+
return ctx.messageModel.deleteMessagesBySession(null, input.topicId, input.groupId);
}),
@@ -491,6 +537,7 @@ export const messageRouter = router({
)
.mutation(async ({ input, ctx }) => {
const { id, value, agentId, ...options } = input;
+ await assertCanUseMessageTargets(guardCtx(ctx), [id]);
const timingContext = { requestId: createTimingRequestId(), startedAt: Date.now() };
logTiming(timingContext, 'lambda.message.update:start', {
hasAgentId: !!agentId,
@@ -549,6 +596,7 @@ export const messageRouter = router({
)
.mutation(async ({ input, ctx }) => {
const { messageGroupId, expanded, context } = input;
+ await assertCanUseTopicTargets(guardCtx(ctx), [context.topicId]);
return ctx.messageService.updateMessageGroupMetadata(messageGroupId, { expanded }, context);
}),
@@ -565,6 +613,7 @@ export const messageRouter = router({
)
.mutation(async ({ input, ctx }) => {
const { id, value, agentId, ...options } = input;
+ await assertCanUseMessageTargets(guardCtx(ctx), [id]);
const resolved = await resolveContext(
{ agentId, ...options },
ctx.serverDB,
@@ -580,6 +629,7 @@ export const messageRouter = router({
.input(UpdateMessageRAGParamsSchema.extend(basicContextSchema.shape))
.mutation(async ({ input, ctx }) => {
const { id, value, agentId, ...options } = input;
+ await assertCanUseMessageTargets(guardCtx(ctx), [id]);
const resolved = await resolveContext(
{ agentId, ...options },
ctx.serverDB,
@@ -602,6 +652,7 @@ export const messageRouter = router({
)
.mutation(async ({ input, ctx }) => {
const { id, value, agentId, ...options } = input;
+ await assertCanUseMessageTargets(guardCtx(ctx), [id]);
const resolved = await resolveContext(
{ agentId, ...options },
ctx.serverDB,
@@ -624,6 +675,7 @@ export const messageRouter = router({
)
.mutation(async ({ input, ctx }) => {
const { id, value, agentId, ...options } = input;
+ await assertCanUseMessageTargets(guardCtx(ctx), [id]);
const resolved = await resolveContext(
{ agentId, ...options },
ctx.serverDB,
@@ -646,6 +698,7 @@ export const messageRouter = router({
)
.mutation(async ({ input, ctx }) => {
const { id, value, agentId, ...options } = input;
+ await assertCanUseMessageTargets(guardCtx(ctx), [id]);
const resolved = await resolveContext(
{ agentId, ...options },
ctx.serverDB,
@@ -671,6 +724,7 @@ export const messageRouter = router({
}),
)
.mutation(async ({ input, ctx }) => {
+ await assertCanUseMessageTargets(guardCtx(ctx), [input.id]);
if (input.value === false) {
return ctx.messageModel.deleteMessageTTS(input.id);
}
@@ -690,6 +744,13 @@ export const messageRouter = router({
)
.mutation(async ({ input, ctx }) => {
const { toolCallId, value, agentId, ...options } = input;
+ // No message id in the input — guard by the topic row when present,
+ // falling back to the declared conversation target.
+ if (options.topicId) await assertCanUseTopicTargets(guardCtx(ctx), [options.topicId]);
+ else
+ await assertCanUseConversationTargets(guardCtx(ctx), [
+ { agentId, groupId: options.groupId },
+ ]);
const resolved = await resolveContext(
{ agentId, ...options },
ctx.serverDB,
@@ -722,6 +783,7 @@ export const messageRouter = router({
)
.mutation(async ({ input, ctx }) => {
const { id, value, agentId, ...options } = input;
+ await assertCanUseMessageTargets(guardCtx(ctx), [id]);
const resolved = await resolveContext(
{ agentId, ...options },
ctx.serverDB,
@@ -746,6 +808,7 @@ export const messageRouter = router({
}),
)
.mutation(async ({ input, ctx }) => {
+ await assertCanUseMessageTargets(guardCtx(ctx), [input.id]);
if (input.value === false) {
return ctx.messageModel.deleteMessageTranslate(input.id);
}
diff --git a/apps/server/src/routers/lambda/notebook.ts b/apps/server/src/routers/lambda/notebook.ts
index 0e43392f39c..cec60232f6a 100644
--- a/apps/server/src/routers/lambda/notebook.ts
+++ b/apps/server/src/routers/lambda/notebook.ts
@@ -4,15 +4,17 @@ import { z } from 'zod';
import { withScopedPermission } from '@/business/server/trpc-middlewares/rbacPermission';
import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';
import { DocumentModel } from '@/database/models/document';
+import { ResourcePermissionModel } from '@/database/models/resourcePermission';
import { TopicDocumentModel } from '@/database/models/topicDocument';
import { router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
import { NotebookRuntimeService } from '@/server/services/notebook';
-
import {
- assertWorkspaceRowManageable,
- isWorkspaceNonOwner,
-} from './_helpers/assertWorkspaceRowManageable';
+ assertCanEditResource,
+ assertCanPerformResourceAction,
+} from '@/server/services/resourcePermission';
+
+import { isWorkspaceNonOwner } from './_helpers/assertWorkspaceRowManageable';
const notebookProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {
const { ctx } = opts;
@@ -78,7 +80,18 @@ export const notebookRouter = router({
.mutation(async ({ ctx, input }) => {
const existing = await ctx.documentModel.findById(input.id);
if (!existing) return { success: true };
- assertWorkspaceRowManageable(ctx, existing.userId, 'document');
+ // Same guard as documentRouter.deleteDocument — the two routers delete
+ // from the same `documents` table and must not diverge in semantics.
+ if (ctx.workspaceId) {
+ await assertCanPerformResourceAction({
+ action: 'delete',
+ db: ctx.serverDB,
+ resourceId: input.id,
+ resourceType: 'document',
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
+ });
+ }
// Same cascade rule as documentRouter.deleteDocument: a non-owner's
// folder delete must not take teammates' descendants with it.
@@ -86,6 +99,13 @@ export const notebookRouter = router({
restrictToCreator: isWorkspaceNonOwner(ctx),
});
+ if (ctx.workspaceId) {
+ await new ResourcePermissionModel(ctx.serverDB, ctx.workspaceId).removeAll(
+ 'document',
+ input.id,
+ );
+ }
+
return { success: true };
}),
@@ -138,6 +158,15 @@ export const notebookRouter = router({
}),
)
.mutation(async ({ ctx, input }) => {
+ // General-access write guard, mirroring `document.updateDocument`.
+ await assertCanEditResource({
+ db: ctx.serverDB,
+ resourceId: input.id,
+ resourceType: 'document',
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId ?? undefined,
+ });
+
let contentToUpdate = input.content;
// Handle append mode
diff --git a/apps/server/src/routers/lambda/resourcePermission.ts b/apps/server/src/routers/lambda/resourcePermission.ts
new file mode 100644
index 00000000000..d4d42cd6960
--- /dev/null
+++ b/apps/server/src/routers/lambda/resourcePermission.ts
@@ -0,0 +1,180 @@
+import { TRPCError } from '@trpc/server';
+import { z } from 'zod';
+
+import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';
+import { ResourcePermissionModel } from '@/database/models/resourcePermission';
+import {
+ getDefaultResourceAccessLevel,
+ PERMISSION_RESOURCE_TYPES,
+ RESOURCE_ACCESS_LEVELS,
+} from '@/database/schemas';
+import { router } from '@/libs/trpc/lambda';
+import { serverDatabase } from '@/libs/trpc/lambda/middleware';
+import {
+ buildResourcePermissionState,
+ canManageResourcePermission,
+ getResourceMeta,
+ isAccessLevelAllowed,
+} from '@/server/services/resourcePermission';
+
+import { getWorkspaceGroupVirtualAgentIds } from './_helpers/workspaceAgentGuard';
+
+const resourceInput = z.object({
+ resourceId: z.string(),
+ resourceType: z.enum(PERMISSION_RESOURCE_TYPES),
+});
+
+const accessLevelSchema = z.enum(RESOURCE_ACCESS_LEVELS);
+const legacyGeneralAccessSchema = z.enum(['editor', 'viewer']);
+
+/**
+ * Permission rows only exist inside a team workspace, so unlike the content
+ * routers this one rejects personal-mode calls outright.
+ */
+const permissionProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {
+ const { ctx } = opts;
+ if (!ctx.workspaceId) {
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message: 'Resource permissions only apply inside a workspace',
+ });
+ }
+
+ return opts.next({
+ ctx: {
+ permissionModel: new ResourcePermissionModel(ctx.serverDB, ctx.workspaceId),
+ workspaceId: ctx.workspaceId,
+ },
+ });
+});
+
+export const resourcePermissionRouter = router({
+ /**
+ * The resource's publicity + General-access level plus the caller's own
+ * capability, so the Permission panel renders in one query.
+ */
+ getGeneralAccess: permissionProcedure.input(resourceInput).query(async ({ ctx, input }) => {
+ const meta = await getResourceMeta(ctx.serverDB, input.resourceType, input.resourceId);
+ // Cross-workspace probing gets NOT_FOUND, same as a missing resource.
+ if (!meta || meta.workspaceId !== ctx.workspaceId) {
+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Resource not found' });
+ }
+ // Private rows are creator-only (mirrors `canPerformResourceAction`):
+ // don't leak existence/creator of another member's private resource.
+ if (meta.visibility === 'private' && meta.userId !== ctx.userId) {
+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Resource not found' });
+ }
+
+ const [accessLevel, canManage] = await Promise.all([
+ ctx.permissionModel.getEffectiveAccessLevel(input.resourceType, input.resourceId),
+ canManageResourcePermission({
+ db: ctx.serverDB,
+ grantedPermissions: (ctx as { workspacePermissionCodes?: string[] })
+ .workspacePermissionCodes,
+ meta,
+ resourceId: input.resourceId,
+ resourceType: input.resourceType,
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
+ }),
+ ]);
+
+ return buildResourcePermissionState({
+ accessLevel,
+ canManage,
+ creatorId: meta.userId,
+ visibility: (meta.visibility ?? 'public') as 'private' | 'public',
+ });
+ }),
+
+ /**
+ * Set the explicit Workspace General-access level (creator or workspace owner).
+ */
+ setGeneralAccess: permissionProcedure
+ .input(
+ resourceInput
+ .extend({
+ accessLevel: accessLevelSchema.optional(),
+ /** @deprecated Compatibility for released clients. */
+ role: legacyGeneralAccessSchema.optional(),
+ })
+ .refine(({ accessLevel, role }) => accessLevel !== undefined || role !== undefined, {
+ message: 'accessLevel is required',
+ }),
+ )
+ .mutation(async ({ ctx, input }) => {
+ const meta = await getResourceMeta(ctx.serverDB, input.resourceType, input.resourceId);
+ if (!meta || meta.workspaceId !== ctx.workspaceId) {
+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Resource not found' });
+ }
+ // Same private-row existence guard as `getGeneralAccess`.
+ if (meta.visibility === 'private' && meta.userId !== ctx.userId) {
+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Resource not found' });
+ }
+
+ const canManage = await canManageResourcePermission({
+ db: ctx.serverDB,
+ grantedPermissions: (ctx as { workspacePermissionCodes?: string[] })
+ .workspacePermissionCodes,
+ meta,
+ resourceId: input.resourceId,
+ resourceType: input.resourceType,
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
+ });
+ if (!canManage) {
+ throw new TRPCError({
+ code: 'FORBIDDEN',
+ message: 'Only the creator or a workspace owner can change general access',
+ });
+ }
+
+ if (meta.visibility === 'private') {
+ throw new TRPCError({
+ code: 'PRECONDITION_FAILED',
+ message: 'Private resources do not have Workspace access',
+ });
+ }
+
+ const accessLevel =
+ input.accessLevel ??
+ (input.role === 'editor' ? 'edit' : getDefaultResourceAccessLevel(input.resourceType));
+ if (!isAccessLevelAllowed(input.resourceType, accessLevel)) {
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message: `${accessLevel} access is not supported for ${input.resourceType}`,
+ });
+ }
+
+ await ctx.permissionModel.setAccessLevel(
+ input.resourceType,
+ input.resourceId,
+ accessLevel,
+ ctx.userId,
+ );
+
+ // A group's General Access speaks for the whole group: cascade the level
+ // to its group-owned virtual agents (supervisor + members), whose
+ // effective access is min(own, parent group). Standalone agents linked
+ // into the group keep their own ACL.
+ if (input.resourceType === 'agentGroup') {
+ const virtualAgentIds = await getWorkspaceGroupVirtualAgentIds({
+ db: ctx.serverDB,
+ groupId: input.resourceId,
+ workspaceId: ctx.workspaceId,
+ });
+ await Promise.all(
+ virtualAgentIds.map((agentId) =>
+ ctx.permissionModel.setAccessLevel('agent', agentId, accessLevel, ctx.userId),
+ ),
+ );
+ }
+
+ return buildResourcePermissionState({
+ accessLevel,
+ canManage: true,
+ creatorId: meta.userId,
+ visibility: 'public',
+ });
+ }),
+});
diff --git a/apps/server/src/routers/lambda/session.ts b/apps/server/src/routers/lambda/session.ts
index 0d7b278ba43..87ed388c1d2 100644
--- a/apps/server/src/routers/lambda/session.ts
+++ b/apps/server/src/routers/lambda/session.ts
@@ -1,19 +1,57 @@
+import { TRPCError } from '@trpc/server';
import { z } from 'zod';
import { withScopedPermission } from '@/business/server/trpc-middlewares/rbacPermission';
import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';
+import { AgentModel } from '@/database/models/agent';
import { ChatGroupModel } from '@/database/models/chatGroup';
+import { ResourcePermissionModel } from '@/database/models/resourcePermission';
import { SessionModel } from '@/database/models/session';
import { SessionGroupModel } from '@/database/models/sessionGroup';
import { insertAgentSchema, insertSessionSchema } from '@/database/schemas';
+import type { LobeChatDatabase } from '@/database/type';
import { router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
+import { assertCanEditResource } from '@/server/services/resourcePermission';
import { AgentChatConfigSchema } from '@/types/agent';
import { LobeMetaDataSchema } from '@/types/meta';
import { type BatchTaskResult } from '@/types/service';
import { type ChatSessionList, type LobeGroupSession } from '@/types/session';
+import { TransferErrorCode } from '@/types/transferError';
-import { assertWorkspaceRowManageable } from './_helpers/assertWorkspaceRowManageable';
+import {
+ assertWorkspaceRowManageable,
+ isWorkspaceNonOwner,
+} from './_helpers/assertWorkspaceRowManageable';
+
+/**
+ * Session config updates write through to the linked agent's config, so a
+ * workspace member with view/use access must not use them as an edit
+ * escalation. Resolves the session's linked agent and runs the edit guard.
+ * No-op in personal mode (no workspaceId).
+ */
+const assertCanEditSessionAgent = async (
+ ctx: {
+ serverDB: LobeChatDatabase;
+ sessionModel: SessionModel;
+ userId: string;
+ workspaceId?: string | null;
+ },
+ sessionId: string,
+) => {
+ if (!ctx.workspaceId) return;
+
+ const session = await ctx.sessionModel.findByIdOrSlug(sessionId);
+ if (!session?.agent?.id) return;
+
+ await assertCanEditResource({
+ db: ctx.serverDB,
+ resourceId: session.agent.id,
+ resourceType: 'agent',
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
+ });
+};
const sessionProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {
const { ctx } = opts;
@@ -162,7 +200,37 @@ export const sessionRouter = router({
const session = await ctx.sessionModel.findByIdOrSlug(input.id);
if (session) assertWorkspaceRowManageable(ctx, session.userId, 'session');
- return ctx.sessionModel.delete(input.id);
+ // Deleting the last session of a workspace-shared agent orphan-deletes
+ // the agent itself, and the session cascade erases every member's
+ // topics/messages on it — the same blast radius as `agent.removeAgent`,
+ // so apply the same foreign-rows owner gate here.
+ if (
+ ctx.workspaceId &&
+ session?.agent &&
+ session.agent.visibility === 'public' &&
+ isWorkspaceNonOwner(ctx)
+ ) {
+ const agentModel = new AgentModel(ctx.serverDB, ctx.userId, ctx.workspaceId);
+ if (await agentModel.transferHasForeignRows(session.agent.id)) {
+ throw new TRPCError({
+ cause: { data: { code: TransferErrorCode.OwnerOnly } },
+ code: 'FORBIDDEN',
+ message:
+ "Only workspace owners can delete a session whose shared agent carries others' conversations",
+ });
+ }
+ }
+
+ const { orphanedAgentIds, result } = await ctx.sessionModel.delete(input.id);
+
+ // Mirror `agent.removeAgent`: orphan-deleted shared agents must not
+ // leave dangling resource_permissions rows behind.
+ if (ctx.workspaceId && orphanedAgentIds.length > 0) {
+ const permissionModel = new ResourcePermissionModel(ctx.serverDB, ctx.workspaceId);
+ await Promise.all(orphanedAgentIds.map((id) => permissionModel.removeAll('agent', id)));
+ }
+
+ return result;
}),
searchSessions: sessionProcedure
@@ -194,8 +262,7 @@ export const sessionRouter = router({
}),
)
.mutation(async ({ input, ctx }) => {
- const session = await ctx.sessionModel.findByIdOrSlug(input.id);
- if (session) assertWorkspaceRowManageable(ctx, session.userId, 'session');
+ await assertCanEditSessionAgent(ctx, input.id);
return ctx.sessionModel.updateConfig(input.id, {
chatConfig: input.value,
@@ -210,8 +277,7 @@ export const sessionRouter = router({
}),
)
.mutation(async ({ input, ctx }) => {
- const session = await ctx.sessionModel.findByIdOrSlug(input.id);
- if (session) assertWorkspaceRowManageable(ctx, session.userId, 'session');
+ await assertCanEditSessionAgent(ctx, input.id);
return ctx.sessionModel.updateConfig(input.id, input.value);
}),
diff --git a/apps/server/src/routers/lambda/topic.ts b/apps/server/src/routers/lambda/topic.ts
index 6cf1a585df7..225cc9f16e0 100644
--- a/apps/server/src/routers/lambda/topic.ts
+++ b/apps/server/src/routers/lambda/topic.ts
@@ -40,13 +40,26 @@ import {
assertWorkspaceRowManageable,
shouldRestrictBulkDeleteToCreator,
} from './_helpers/assertWorkspaceRowManageable';
+import {
+ assertCanUseConversationTargets,
+ assertCanUseSessionTargets,
+ assertCanUseTopicTargets,
+} from './_helpers/conversationResourceGuard';
import {
batchResolveAgentIdFromSessions,
resolveAgentIdFromSession,
resolveContext,
+ resolveContextWithAgentId,
} from './_helpers/resolveContext';
import { basicContextSchema } from './_schema/context';
+/** Ctx slice consumed by the conversation General-access guards. */
+const guardCtx = (ctx: {
+ serverDB: LobeChatDatabase;
+ userId: string;
+ workspaceId?: string | null;
+}) => ({ db: ctx.serverDB, userId: ctx.userId, workspaceId: ctx.workspaceId });
+
const topicProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {
const { ctx } = opts;
const wsId = ctx.workspaceId ?? undefined;
@@ -225,20 +238,26 @@ export const topicRouter = router({
),
)
.mutation(async ({ input, ctx }): Promise<BatchTaskResult> => {
- // Resolve sessionId for each topic
+ // Resolve both directions before authorization: legacy callers may send
+ // only sessionId, while the ACL is attached to the owning agent.
const resolvedTopics = await Promise.all(
input.map(async (item) => {
const { agentId, ...rest } = item;
- const resolved = await resolveContext(
- { agentId, sessionId: rest.sessionId },
+ const resolved = await resolveContextWithAgentId(
+ { agentId, groupId: rest.groupId, sessionId: rest.sessionId },
ctx.serverDB,
ctx.userId,
ctx.workspaceId ?? undefined,
);
- return { ...rest, sessionId: resolved.sessionId };
+ return { ...rest, agentId: resolved.agentId, sessionId: resolved.sessionId };
}),
);
+ await assertCanUseConversationTargets(
+ guardCtx(ctx),
+ resolvedTopics.map((item) => ({ agentId: item.agentId, groupId: item.groupId })),
+ );
+
const data = await ctx.topicModel.batchCreate(resolvedTopics as any);
return { added: data.length, ids: [], skips: [], success: true };
@@ -269,6 +288,7 @@ export const topicRouter = router({
.use(withScopedPermission('topic:delete'))
.input(z.object({ groupId: z.string(), scope: topicBulkDeleteScopeSchema }))
.mutation(async ({ input, ctx }) => {
+ await assertCanUseConversationTargets(guardCtx(ctx), [{ groupId: input.groupId }]);
const restrictToCreator = shouldRestrictBulkDeleteToCreator(ctx, input.scope);
return ctx.topicModel.batchDeleteByGroupId(input.groupId, { restrictToCreator });
@@ -291,6 +311,12 @@ export const topicRouter = router({
ctx.workspaceId ?? undefined,
);
+ if (input.agentId) {
+ await assertCanUseConversationTargets(guardCtx(ctx), [{ agentId: input.agentId }]);
+ } else if (resolved.sessionId) {
+ await assertCanUseSessionTargets(guardCtx(ctx), [resolved.sessionId]);
+ }
+
const restrictToCreator = shouldRestrictBulkDeleteToCreator(ctx, input.scope);
return ctx.topicModel.batchDeleteBySessionId(resolved.sessionId, { restrictToCreator });
@@ -309,6 +335,9 @@ export const topicRouter = router({
for (const userId of new Set(rows.map((row) => row.userId))) {
assertWorkspaceRowManageable(ctx, userId, 'topic');
}
+ // Moving needs `use` on both the source conversations and the target agent.
+ await assertCanUseTopicTargets(guardCtx(ctx), input.topicIds);
+ await assertCanUseConversationTargets(guardCtx(ctx), [{ agentId: input.targetAgentId }]);
return ctx.topicModel.batchMoveToAgent(input.topicIds, input.targetAgentId);
}),
@@ -317,6 +346,7 @@ export const topicRouter = router({
.use(withScopedPermission('topic:create'))
.input(z.object({ id: z.string(), newTitle: z.string().optional() }))
.mutation(async ({ input, ctx }) => {
+ await assertCanUseTopicTargets(guardCtx(ctx), [input.id]);
const data = await ctx.topicModel.duplicate(input.id, input.newTitle);
return data.topic.id;
@@ -353,14 +383,21 @@ export const topicRouter = router({
)
.mutation(async ({ input, ctx }) => {
const { agentId, ...rest } = input;
- const resolved = await resolveContext(
- { agentId, sessionId: rest.sessionId },
+ const resolved = await resolveContextWithAgentId(
+ { agentId, groupId: rest.groupId, sessionId: rest.sessionId },
ctx.serverDB,
ctx.userId,
ctx.workspaceId ?? undefined,
);
+ await assertCanUseConversationTargets(guardCtx(ctx), [
+ { agentId: resolved.agentId, groupId: rest.groupId },
+ ]);
- const data = await ctx.topicModel.create({ ...rest, sessionId: resolved.sessionId });
+ const data = await ctx.topicModel.create({
+ ...rest,
+ agentId: resolved.agentId,
+ sessionId: resolved.sessionId,
+ });
return data.id;
}),
@@ -585,6 +622,10 @@ export const topicRouter = router({
}),
)
.mutation(async ({ input, ctx }) => {
+ await assertCanUseConversationTargets(guardCtx(ctx), [
+ { agentId: input.agentId, groupId: input.groupId },
+ ]);
+
return ctx.heteroSessionImporterRepo.importSessions({
agentId: input.agentId,
groupId: input.groupId,
@@ -602,6 +643,10 @@ export const topicRouter = router({
}),
)
.mutation(async ({ input, ctx }) => {
+ await assertCanUseConversationTargets(guardCtx(ctx), [
+ { agentId: input.agentId, groupId: input.groupId },
+ ]);
+
const result = await ctx.topicImporterRepo.importTopic({
agentId: input.agentId,
data: input.data,
@@ -869,7 +914,11 @@ export const topicRouter = router({
.mutation(async ({ input, ctx }) => {
// Intentionally no creator/owner gate: shared topics are co-editable by
// members (title/status/metadata); only delete/transfer is creator-scoped.
+ // Co-editing still requires `use`-level General access on the agent —
+ // view-only members are read-only.
+ await assertCanUseTopicTargets(guardCtx(ctx), [input.id]);
const { agentId, ...restValue } = input.value;
+ if (agentId) await assertCanUseConversationTargets(guardCtx(ctx), [{ agentId }]);
// If agentId is provided, resolve to sessionId
let resolvedSessionId = restValue.sessionId;
@@ -898,6 +947,9 @@ export const topicRouter = router({
// Intentionally no creator/owner gate: metadata follows the same
// co-editable path as updateTopic (chat/tool flows write fields like
// runningOperation on shared topics); only delete/transfer is gated.
+ // Co-editing still requires `use`-level General access on the agent.
+ await assertCanUseTopicTargets(guardCtx(ctx), [input.id]);
+
return ctx.topicModel.updateMetadata(input.id, input.metadata);
}),
});
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.device.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.device.test.ts
index 6dae79c3077..151c1823538 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.device.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.device.test.ts
@@ -3,16 +3,20 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { AiAgentService } from '../index';
-const { mockCreateOperation, mockCreateServerAgentToolsEngine, mockMessageCreate } = vi.hoisted(
- () => ({
- mockCreateOperation: vi.fn(),
- mockCreateServerAgentToolsEngine: vi.fn().mockReturnValue({
- generateToolsDetailed: vi.fn().mockReturnValue({ enabledToolIds: [], tools: [] }),
- getEnabledPluginManifests: vi.fn().mockReturnValue(new Map()),
- }),
- mockMessageCreate: vi.fn(),
+const {
+ mockCreateOperation,
+ mockCreateServerAgentToolsEngine,
+ mockMessageCreate,
+ mockMessageUpdate,
+} = vi.hoisted(() => ({
+ mockCreateOperation: vi.fn(),
+ mockCreateServerAgentToolsEngine: vi.fn().mockReturnValue({
+ generateToolsDetailed: vi.fn().mockReturnValue({ enabledToolIds: [], tools: [] }),
+ getEnabledPluginManifests: vi.fn().mockReturnValue(new Map()),
}),
-);
+ mockMessageCreate: vi.fn(),
+ mockMessageUpdate: vi.fn(),
+}));
const { mockDeviceProxy } = vi.hoisted(() => ({
mockDeviceProxy: {
@@ -33,7 +37,7 @@ vi.mock('@/database/models/message', () => ({
getLatestNonToolMessageId: vi.fn().mockResolvedValue(undefined),
getLatestSpineMessageId: vi.fn().mockResolvedValue(undefined),
query: vi.fn().mockResolvedValue([]),
- update: vi.fn().mockResolvedValue({}),
+ update: mockMessageUpdate,
})),
}));
@@ -149,6 +153,7 @@ describe('AiAgentService.execAgent - device auto-activation', () => {
topicMock.findById.mockResolvedValue(undefined);
topicMock.updateMetadata.mockResolvedValue(undefined);
mockMessageCreate.mockResolvedValue({ id: 'msg-1' });
+ mockMessageUpdate.mockResolvedValue({});
mockCreateOperation.mockResolvedValue({
autoStarted: true,
messageId: 'queue-msg-1',
@@ -507,6 +512,74 @@ describe('AiAgentService.execAgent - device auto-activation', () => {
});
describe('topic and explicit device binding', () => {
+ it('uses the shared fixed device even when the request asks for another device', async () => {
+ mockDeviceProxy.isConfigured = true;
+ mockDeviceProxy.queryDeviceList.mockResolvedValue([onlineDevice, onlineDevice2]);
+ await useAgencyConfig({
+ boundDeviceId: 'device-001',
+ executionTargetSelectionPolicy: 'fixed',
+ executionTarget: 'device',
+ });
+ service = new AiAgentService(mockDb, userId, { workspaceId: 'workspace-1' });
+
+ await service.execAgent({
+ agentId: 'agent-1',
+ deviceId: 'device-002',
+ prompt: 'Run a command',
+ });
+
+ expect(mockCreateOperation.mock.calls[0][0].activeDeviceId).toBe('device-001');
+ expect(topicMock.create).toHaveBeenCalledWith(
+ expect.objectContaining({
+ metadata: expect.objectContaining({ boundDeviceId: 'device-001' }),
+ }),
+ );
+ });
+
+ it('keeps a fixed sandbox target when the request asks for a device', async () => {
+ mockDeviceProxy.isConfigured = true;
+ mockDeviceProxy.queryDeviceList.mockResolvedValue([onlineDevice]);
+ await useAgencyConfig({
+ executionTarget: 'sandbox',
+ executionTargetSelectionPolicy: 'fixed',
+ });
+ service = new AiAgentService(mockDb, userId, { workspaceId: 'workspace-1' });
+
+ await service.execAgent({
+ agentId: 'agent-1',
+ deviceId: 'device-001',
+ prompt: 'Run a command',
+ });
+
+ expect(mockCreateOperation.mock.calls[0][0].activeDeviceId).toBeUndefined();
+ expect(topicMock.create).toHaveBeenCalledWith(
+ expect.objectContaining({ metadata: undefined }),
+ );
+ });
+
+ it('fails before operation creation when the shared fixed device is offline', async () => {
+ mockDeviceProxy.isConfigured = true;
+ mockDeviceProxy.queryDeviceList.mockResolvedValue([onlineDevice2]);
+ await useAgencyConfig({
+ boundDeviceId: 'device-001',
+ executionTargetSelectionPolicy: 'fixed',
+ executionTarget: 'device',
+ });
+ service = new AiAgentService(mockDb, userId, { workspaceId: 'workspace-1' });
+
+ await expect(
+ service.execAgent({ agentId: 'agent-1', prompt: 'Run a command' }),
+ ).rejects.toMatchObject({ code: 'PRECONDITION_FAILED' });
+
+ expect(mockCreateOperation).not.toHaveBeenCalled();
+ expect(mockMessageUpdate).toHaveBeenCalledWith(
+ 'msg-1',
+ expect.objectContaining({
+ error: expect.objectContaining({ message: 'Fixed agent device unavailable' }),
+ }),
+ );
+ });
+
it('should prefer explicit deviceId over topic and agent bindings when online', async () => {
mockDeviceProxy.isConfigured = true;
mockDeviceProxy.queryDeviceList.mockResolvedValue([onlineDevice, onlineDevice2]);
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.modelOverride.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.modelOverride.test.ts
index b3a5aba7b95..c2e64333bba 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.modelOverride.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.modelOverride.test.ts
@@ -3,11 +3,13 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import { AiAgentService } from '../index';
-const { mockCreateOperation, mockGetAgentConfig, mockMessageCreate } = vi.hoisted(() => ({
- mockCreateOperation: vi.fn(),
- mockGetAgentConfig: vi.fn(),
- mockMessageCreate: vi.fn(),
-}));
+const { mockCreateOperation, mockGetAgentConfig, mockGetPreference, mockMessageCreate } =
+ vi.hoisted(() => ({
+ mockCreateOperation: vi.fn(),
+ mockGetAgentConfig: vi.fn(),
+ mockGetPreference: vi.fn(),
+ mockMessageCreate: vi.fn(),
+ }));
vi.mock('@/libs/trusted-client', () => ({
generateTrustedClientToken: vi.fn().mockReturnValue(undefined),
@@ -25,6 +27,12 @@ vi.mock('@/database/models/message', () => ({
})),
}));
+vi.mock('@/database/models/workspaceUserSettings', () => ({
+ WorkspaceUserSettingsModel: vi.fn().mockImplementation(() => ({
+ getPreference: mockGetPreference,
+ })),
+}));
+
vi.mock('@/database/models/agent', () => ({
AgentModel: vi.fn().mockImplementation(() => ({
getAgentConfig: vi.fn(),
@@ -140,6 +148,7 @@ describe('AiAgentService.execAgent - model/provider override', () => {
operationId: 'op-123',
success: true,
});
+ mockGetPreference.mockResolvedValue({});
service = new AiAgentService(mockDb, userId);
});
@@ -202,4 +211,63 @@ describe('AiAgentService.execAgent - model/provider override', () => {
expect(callArgs.agentConfig.model).toBe('claude-sonnet-4-6');
expect(callArgs.agentConfig.provider).toBe('anthropic');
});
+
+ it('uses the caller model preference when the workspace Agent allows member selection', async () => {
+ mockGetAgentConfig.mockResolvedValue({
+ ...defaultAgentConfig,
+ agencyConfig: { modelSelectionPolicy: 'member' },
+ });
+ mockGetPreference.mockResolvedValue({
+ agentModelOverrides: {
+ 'agent-1': { model: 'claude-sonnet-4-6', provider: 'anthropic' },
+ },
+ });
+ 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');
+ });
+
+ it('ignores a retained caller preference when the workspace model policy is missing/fixed', async () => {
+ mockGetAgentConfig.mockResolvedValue({ ...defaultAgentConfig });
+ mockGetPreference.mockResolvedValue({
+ agentModelOverrides: {
+ 'agent-1': { model: 'claude-sonnet-4-6', provider: 'anthropic' },
+ },
+ });
+ 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('gpt-4');
+ expect(callArgs.agentConfig.provider).toBe('openai');
+ });
+
+ it('keeps an explicit per-run model/provider above the caller workspace preference', async () => {
+ mockGetAgentConfig.mockResolvedValue({
+ ...defaultAgentConfig,
+ agencyConfig: { modelSelectionPolicy: 'member' },
+ });
+ mockGetPreference.mockResolvedValue({
+ agentModelOverrides: {
+ 'agent-1': { model: 'gpt-4', provider: 'openai' },
+ },
+ });
+ service = new AiAgentService(mockDb, userId, { workspaceId: 'workspace-1' });
+
+ await service.execAgent({
+ agentId: 'agent-1',
+ model: 'claude-sonnet-4-6',
+ prompt: 'Hello',
+ provider: 'anthropic',
+ });
+
+ const callArgs = mockCreateOperation.mock.calls[0][0];
+ expect(callArgs.agentConfig.model).toBe('claude-sonnet-4-6');
+ expect(callArgs.agentConfig.provider).toBe('anthropic');
+ });
});
diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.ts
index 23d6f1a4a2a..b599f883619 100644
--- a/apps/server/src/services/aiAgent/index.ts
+++ b/apps/server/src/services/aiAgent/index.ts
@@ -39,6 +39,7 @@ import type { LobeChatDatabase } from '@lobechat/database';
import { isRemoteHeterogeneousType } from '@lobechat/heterogeneous-agents';
import { buildTaskManagerDefaultsPrompt, resourcesTreePrompt } from '@lobechat/prompts';
import type {
+ AgentModelOverride,
ChatAudioItem,
ChatFileItem,
ChatTopicBotContext,
@@ -67,6 +68,7 @@ import {
ReasoningGraphSchema,
RequestTrigger,
resolveAgencyConfig,
+ resolveAgentModelConfig,
ThreadStatus,
ThreadType,
} from '@lobechat/types';
@@ -98,6 +100,7 @@ import {
isDeviceCapablePlan,
isDeviceLockedPlan,
resolveExecutionPlan,
+ resolveToolMode,
} from '@/helpers/executionTarget';
import { shouldEnableBuiltinSkill } from '@/helpers/skillFilters';
import { buildConnectorManifests } from '@/libs/mcp/buildConnectorManifests';
@@ -1187,17 +1190,13 @@ export class AiAgentService {
// Use actual agent ID from config for subsequent operations
const resolvedAgentId = agentConfig.id;
+ let memberModelOverride: AgentModelOverride | undefined;
- // Layer this caller's per-user device override (LOBE-11689) over the shared
- // agencyConfig so THIS user's Cloud Sandbox / workspace-device / local pick
- // drives dispatch instead of whichever choice landed on the shared row.
- // Only applied for workspace agents — personal agents already have a single
- // owner whose choice IS the shared config. The override lives in the
- // dedicated `workspace_user_settings` table (per-(workspace, user)) so it
- // stays orthogonal to member-list queries and cascades on either identity
- // delete. `resolveAgencyConfig` is a no-op when no override exists, so a
- // first-open (or a member who hasn't touched the switcher) transparently
- // sees the shared default.
+ // Layer this caller's workspace-scoped execution and model preferences over
+ // the shared Agent row. Device selection keeps its existing fallback rules;
+ // model selection is applied only when the author explicitly allows member
+ // choice (an omitted policy is fixed). Both overrides live in the dedicated
+ // per-(workspace, user) settings row and never mutate shared Agent config.
if (this.workspaceId) {
try {
const workspaceUserSettings = new WorkspaceUserSettingsModel(
@@ -1206,12 +1205,14 @@ export class AiAgentService {
this.workspaceId,
);
const preference = await workspaceUserSettings.getPreference();
- const override = preference.agentDeviceOverrides?.[resolvedAgentId];
- agentConfig.agencyConfig = resolveAgencyConfig(agentConfig.agencyConfig, override);
+ const deviceOverride = preference.agentDeviceOverrides?.[resolvedAgentId];
+ agentConfig.agencyConfig = resolveAgencyConfig(agentConfig.agencyConfig, deviceOverride);
+
+ memberModelOverride = preference.agentModelOverrides?.[resolvedAgentId];
} catch (error) {
- // Losing the override is non-fatal: dispatch falls back to the shared
- // agencyConfig, which is exactly the pre-LOBE-11689 behaviour.
- log('execAgent: failed to load caller workspace_user_settings override: %O', error);
+ // Losing preferences is non-fatal: execution falls back to the shared
+ // Agent row, which is the safe fixed/default behavior.
+ log('execAgent: failed to load caller workspace_user_settings preferences: %O', error);
}
}
@@ -1224,12 +1225,16 @@ export class AiAgentService {
// documents stay keyed on `resolvedAgentId`.
const persistAgentId = appContext?.agentSignal?.agentId ?? resolvedAgentId;
- // Apply per-call model/provider overrides. Sources include task.config and
- // the callSubAgent spawn site, which resolves the sub-agent's default model
- // from the parent agent's `agencyConfig.subagent` and passes it explicitly —
- // so this execution path never has to special-case sub-agents.
- if (modelOverride) agentConfig.model = modelOverride;
- if (providerOverride) agentConfig.provider = providerOverride;
+ // Resolve the final model once, keeping per-call task / sub-agent overrides
+ // above the caller's personal workspace choice and the shared Agent default.
+ // 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, memberModelOverride, {
+ ...(modelOverride ? { model: modelOverride } : {}),
+ ...(providerOverride ? { provider: providerOverride } : {}),
+ });
+ agentConfig.model = effectiveModel.model;
+ agentConfig.provider = effectiveModel.provider;
log(
'execAgent: got agent config for %s (id: %s), model: %s, provider: %s',
@@ -1532,7 +1537,18 @@ export class AiAgentService {
// 3. Handle topic creation: if no topicId provided, create a new topic; otherwise reuse existing
let topicId = appContext?.topicId;
const isNewTopic = !topicId;
- const topicBoundDeviceId = requestedDeviceId;
+ const isFixedExecutionTargetSelection =
+ !!this.workspaceId && agentConfig.agencyConfig?.executionTargetSelectionPolicy === 'fixed';
+ const isFixedDeviceTarget =
+ isFixedExecutionTargetSelection && agentConfig.agencyConfig?.executionTarget === 'device';
+ const effectiveRequestedDeviceId = isFixedExecutionTargetSelection
+ ? undefined
+ : requestedDeviceId;
+ const topicBoundDeviceId = isFixedDeviceTarget
+ ? agentConfig.agencyConfig?.boundDeviceId
+ : isFixedExecutionTargetSelection
+ ? undefined
+ : requestedDeviceId;
if (!topicId) {
if (resume) {
throw new Error('Resume mode requires the parent message to belong to a topic');
@@ -1542,10 +1558,10 @@ export class AiAgentService {
// client-supplied initial metadata (e.g. repos selected before first message).
const initialTopicMeta = appContext?.initialTopicMetadata;
const metadata =
- cronJobId || operationTaskId || botContext || requestedDeviceId || initialTopicMeta
+ cronJobId || operationTaskId || botContext || topicBoundDeviceId || initialTopicMeta
? {
bot: botContext,
- boundDeviceId: requestedDeviceId,
+ boundDeviceId: topicBoundDeviceId,
cronJobId: cronJobId || undefined,
taskId: operationTaskId,
...(initialTopicMeta?.repos && { repos: initialTopicMeta.repos }),
@@ -1930,7 +1946,7 @@ export class AiAgentService {
};
const remoteDeviceId =
- requestedDeviceId || agentConfig.agencyConfig?.boundDeviceId || undefined;
+ effectiveRequestedDeviceId || agentConfig.agencyConfig?.boundDeviceId || undefined;
// Register the run's lifecycle hooks so the hetero terminal path fires
// onComplete/onError through the same `hookDispatcher` the normal LLM
@@ -2840,6 +2856,33 @@ export class AiAgentService {
requestedDeviceId,
trigger: requestTriggerMetadata?.trigger,
});
+ // A fixed device target must never degrade to the cloud sandbox or a
+ // different device. Persist a visible assistant error and fail the RPC
+ // before tool/runtime preparation so no operation can start elsewhere.
+ if (
+ isFixedDeviceTarget &&
+ resolveToolMode(agentConfig.chatConfig ?? undefined) !== 'chat' &&
+ executionPlan.kind !== 'device'
+ ) {
+ const detail =
+ executionPlan.kind === 'device-unrouted' &&
+ executionPlan.reason === 'bound-device-offline'
+ ? 'The device fixed by this agent is offline. Ask an editor to bring it online or change the agent device policy.'
+ : 'The device fixed by this agent is unavailable for this run. Ask an editor to check the agent device policy.';
+ await this.messageModel.update(assistantMessageRecord.id, {
+ content: '',
+ error: {
+ body: { detail },
+ message: 'Fixed agent device unavailable',
+ type: 'ServerAgentRuntimeError',
+ },
+ });
+ throw new TRPCError({
+ cause: { data: { code: 'FixedAgentDeviceUnavailable' } },
+ code: 'PRECONDITION_FAILED',
+ message: detail,
+ });
+ }
// Device tools (local-system / remote-device proxy) only exist in a
// device-capable session — `none` and `sandbox` sessions must never see
// them, not even the proxy that could activate a device mid-run.
diff --git a/apps/server/src/services/document/__tests__/index.test.ts b/apps/server/src/services/document/__tests__/index.test.ts
index 9bfcdf77f63..800eddec4a3 100644
--- a/apps/server/src/services/document/__tests__/index.test.ts
+++ b/apps/server/src/services/document/__tests__/index.test.ts
@@ -356,7 +356,7 @@ describe('DocumentService', () => {
);
});
- it('inherits parent visibility when parentId is set', async () => {
+ it('keeps a nested document private regardless of parent visibility', async () => {
mockDocumentModel.findById.mockResolvedValue({ id: 'parent-1', visibility: 'public' });
await service.createDocument({
@@ -366,13 +366,13 @@ describe('DocumentService', () => {
parentId: 'parent-1',
});
- expect(mockDocumentModel.findById).toHaveBeenCalledWith('parent-1');
+ expect(mockDocumentModel.findById).not.toHaveBeenCalled();
expect(mockFileModel.create).toHaveBeenCalledWith(
- expect.objectContaining({ visibility: 'public' }),
+ expect.objectContaining({ visibility: 'private' }),
false,
);
expect(mockDocumentModel.create).toHaveBeenCalledWith(
- expect.objectContaining({ visibility: 'public' }),
+ expect.objectContaining({ visibility: 'private' }),
);
});
diff --git a/apps/server/src/services/document/index.ts b/apps/server/src/services/document/index.ts
index 0e03dba047a..4304af08683 100644
--- a/apps/server/src/services/document/index.ts
+++ b/apps/server/src/services/document/index.ts
@@ -145,19 +145,13 @@ export class DocumentService {
const totalCharCount = content?.length || 0;
const totalLineCount = content?.split('\n').length || 0;
- // Resolve visibility upfront so the KB mirror file inherits the same
- // visibility as the document. Mirrors DocumentModel.create semantics:
- // explicit → parent inheritance → top-level sourceType:'api' default
- // ('private'). Personal mode (no workspaceId) leaves it undefined —
+ // Resolve visibility upfront so the KB mirror file uses the same policy
+ // as the document. Parent documents are navigation only and do not pass
+ // visibility or ACL to children. Personal mode leaves it undefined —
// the ownership filter ignores the column there.
let resolvedVisibility: 'private' | 'public' | undefined = visibility;
if (!resolvedVisibility && this.workspaceId) {
- if (parentId) {
- const parent = await this.documentModel.findById(parentId);
- resolvedVisibility = parent?.visibility ?? 'private';
- } else {
- resolvedVisibility = 'private';
- }
+ resolvedVisibility = 'private';
}
let fileId: string | null = null;
@@ -210,7 +204,7 @@ export class DocumentService {
}
/**
- * Publish a private document subtree to the workspace. Thin wrapper around
+ * Publish one private document to the workspace. Thin wrapper around
* `DocumentModel.publishToWorkspace`, with a side-effect notification so any
* other workspace member with the page open (referencing chip, etc.) sees
* the new visibility on the next refresh.
@@ -220,7 +214,7 @@ export class DocumentService {
}
/**
- * Flip a document subtree's `visibility`. Thin wrapper around
+ * Flip one document's `visibility`. Thin wrapper around
* `DocumentModel.setVisibility`, plus a side-effect notification so any
* other workspace member with the page open (referencing chip, editor
* placeholder, etc.) sees the new visibility on the next refresh — same
diff --git a/apps/server/src/services/resourcePermission/index.test.ts b/apps/server/src/services/resourcePermission/index.test.ts
new file mode 100644
index 00000000000..97b0454e302
--- /dev/null
+++ b/apps/server/src/services/resourcePermission/index.test.ts
@@ -0,0 +1,64 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { LobeChatDatabase } from '@/database/type';
+import { getWorkspaceScopedPermissionMatches } from '@/server/services/workspacePermission';
+
+import { canPerformResourceAction } from './index';
+
+const effectiveAccessMock = vi.hoisted(() => vi.fn());
+
+vi.mock('@/database/models/resourcePermission', () => ({
+ ResourcePermissionModel: class {
+ getEffectiveAccessLevel = effectiveAccessMock;
+ },
+}));
+
+vi.mock('@/server/services/workspacePermission', () => ({
+ getWorkspaceScopedPermissionMatches: vi.fn(),
+}));
+
+const permissionMatchesMock = vi.mocked(getWorkspaceScopedPermissionMatches);
+const db = {} as LobeChatDatabase;
+const meta = { userId: 'creator', visibility: 'public', workspaceId: 'ws-1' };
+
+describe('canPerformResourceAction', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('lets an action-specific all-scope grant override a view-only resource', async () => {
+ permissionMatchesMock.mockResolvedValue({ hasAllScope: true, hasOwnerScope: false });
+ effectiveAccessMock.mockResolvedValue('view');
+
+ await expect(
+ canPerformResourceAction({
+ action: 'use',
+ db,
+ meta,
+ resourceId: 'agent-1',
+ resourceType: 'agent',
+ userId: 'workspace-owner',
+ workspaceId: 'ws-1',
+ }),
+ ).resolves.toBe(true);
+ expect(effectiveAccessMock).not.toHaveBeenCalled();
+ });
+
+ it('still applies the resource level to an ordinary member', async () => {
+ permissionMatchesMock.mockResolvedValue({ hasAllScope: false, hasOwnerScope: true });
+ effectiveAccessMock.mockResolvedValue('view');
+
+ await expect(
+ canPerformResourceAction({
+ action: 'use',
+ db,
+ meta,
+ resourceId: 'agent-1',
+ resourceType: 'agent',
+ userId: 'member',
+ workspaceId: 'ws-1',
+ }),
+ ).resolves.toBe(false);
+ });
+});
diff --git a/apps/server/src/services/resourcePermission/index.ts b/apps/server/src/services/resourcePermission/index.ts
new file mode 100644
index 00000000000..a8f9b8f652c
--- /dev/null
+++ b/apps/server/src/services/resourcePermission/index.ts
@@ -0,0 +1,189 @@
+import type { PERMISSION_ACTIONS } from '@lobechat/const/rbac';
+import { TRPCError } from '@trpc/server';
+import { eq } from 'drizzle-orm';
+
+import { ResourcePermissionModel } from '@/database/models/resourcePermission';
+import type { PermissionResourceType, ResourceAccessLevel } from '@/database/schemas';
+import { agents, chatGroups, documents, isResourceAccessLevelAllowed } from '@/database/schemas';
+import type { LobeChatDatabase } from '@/database/type';
+import { getWorkspaceScopedPermissionMatches } from '@/server/services/workspacePermission';
+
+export interface ResourceMeta {
+ userId: string;
+ visibility: string | null;
+ workspaceId: string | null;
+}
+
+export interface ResourcePermissionState {
+ accessLevel: ResourceAccessLevel;
+ canManage: boolean;
+ creatorId: string;
+ /** @deprecated Compatibility value returned for released clients. */
+ generalAccess: 'editor' | 'viewer';
+ visibility: 'private' | 'public';
+}
+
+export const buildResourcePermissionState = (params: {
+ accessLevel: ResourceAccessLevel;
+ canManage: boolean;
+ creatorId: string;
+ visibility: 'private' | 'public';
+}): ResourcePermissionState => ({
+ ...params,
+ generalAccess: params.accessLevel === 'edit' ? 'editor' : 'viewer',
+});
+
+export type ResourceAccessAction =
+ 'changeVisibility' | 'delete' | 'edit' | 'manage' | 'transfer' | 'use' | 'view';
+
+const RESOURCE_ACTIONS: Record<
+ PermissionResourceType,
+ {
+ delete: keyof typeof PERMISSION_ACTIONS;
+ edit: keyof typeof PERMISSION_ACTIONS;
+ view: keyof typeof PERMISSION_ACTIONS;
+ }
+> = {
+ agent: { delete: 'AGENT_DELETE', edit: 'AGENT_UPDATE', view: 'AGENT_READ' },
+ agentGroup: { delete: 'AGENT_DELETE', edit: 'AGENT_UPDATE', view: 'AGENT_READ' },
+ document: { delete: 'DOCUMENT_DELETE', edit: 'DOCUMENT_UPDATE', view: 'DOCUMENT_READ' },
+};
+
+const ACCESS_LEVEL_RANK: Record<ResourceAccessLevel, number> = {
+ edit: 2,
+ use: 1,
+ view: 0,
+};
+
+export const isAccessLevelAllowed = (
+ resourceType: PermissionResourceType,
+ accessLevel: ResourceAccessLevel,
+) => isResourceAccessLevelAllowed(resourceType, accessLevel);
+
+/**
+ * Fetch creator/visibility/workspace of a permission-capable resource,
+ * without caller scoping. Authorization is applied by the action evaluator.
+ */
+export const getResourceMeta = async (
+ db: LobeChatDatabase,
+ resourceType: PermissionResourceType,
+ resourceId: string,
+): Promise<ResourceMeta | null> => {
+ const table = { agent: agents, agentGroup: chatGroups, document: documents }[resourceType];
+
+ const [row] = await db
+ .select({ userId: table.userId, visibility: table.visibility, workspaceId: table.workspaceId })
+ .from(table)
+ .where(eq(table.id, resourceId))
+ .limit(1);
+
+ return row ?? null;
+};
+
+const getRbacAction = (
+ resourceType: PermissionResourceType,
+ action: ResourceAccessAction,
+): keyof typeof PERMISSION_ACTIONS => {
+ if (action === 'view') return RESOURCE_ACTIONS[resourceType].view;
+ if (action === 'delete') return RESOURCE_ACTIONS[resourceType].delete;
+ if (action === 'use') return 'AI_MODEL_INVOKE';
+ return RESOURCE_ACTIONS[resourceType].edit;
+};
+
+const getRequiredAccessLevel = (action: ResourceAccessAction): ResourceAccessLevel => {
+ if (action === 'edit') return 'edit';
+ if (action === 'use') return 'use';
+ return 'view';
+};
+
+/**
+ * Merge Workspace RBAC (the capability ceiling) with one public resource's
+ * Workspace access level. Creator and `:all` overrides never bypass the RBAC
+ * ceiling; private resources remain creator-only.
+ */
+export const canPerformResourceAction = async (params: {
+ action: ResourceAccessAction;
+ db: LobeChatDatabase;
+ grantedPermissions?: readonly string[];
+ meta: ResourceMeta;
+ resourceId: string;
+ resourceType: PermissionResourceType;
+ userId: string;
+ workspaceId: string;
+}): Promise<boolean> => {
+ const { action, db, grantedPermissions, meta, resourceId, resourceType, userId, workspaceId } =
+ params;
+ if (meta.workspaceId !== workspaceId) return false;
+
+ const isCreator = meta.userId === userId;
+ const isPrivate = meta.visibility === 'private';
+ if (isPrivate && !isCreator) return false;
+
+ const rbacAction = getRbacAction(resourceType, action);
+ const { hasAllScope, hasOwnerScope } = await getWorkspaceScopedPermissionMatches({
+ action: rbacAction,
+ db,
+ grantedPermissions,
+ userId,
+ workspaceId,
+ });
+ const hasCapability = hasAllScope || hasOwnerScope;
+ if (!hasCapability) return false;
+ if (action === 'changeVisibility' || action === 'transfer') return isCreator;
+ if (action === 'manage') return isCreator || (!isPrivate && hasAllScope);
+ if (action === 'delete') return isCreator || (!isPrivate && hasAllScope);
+
+ if (isCreator || (!isPrivate && hasAllScope)) return true;
+ if (isPrivate) return false;
+
+ const accessLevel = await new ResourcePermissionModel(db, workspaceId).getEffectiveAccessLevel(
+ resourceType,
+ resourceId,
+ );
+ const requiredAccessLevel = getRequiredAccessLevel(action);
+ return ACCESS_LEVEL_RANK[accessLevel] >= ACCESS_LEVEL_RANK[requiredAccessLevel];
+};
+
+export const assertCanPerformResourceAction = async (
+ params: Omit<Parameters<typeof canPerformResourceAction>[0], 'meta'> & { meta?: ResourceMeta },
+): Promise<void> => {
+ const meta =
+ params.meta ?? (await getResourceMeta(params.db, params.resourceType, params.resourceId));
+ if (!meta || meta.workspaceId !== params.workspaceId) {
+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Resource not found' });
+ }
+
+ const allowed = await canPerformResourceAction({ ...params, meta });
+ if (!allowed) {
+ throw new TRPCError({
+ code: 'FORBIDDEN',
+ message: `You do not have permission to ${params.action} this resource`,
+ });
+ }
+};
+
+export const canManageResourcePermission = async (params: {
+ db: LobeChatDatabase;
+ grantedPermissions?: readonly string[];
+ meta: ResourceMeta;
+ resourceId: string;
+ resourceType: PermissionResourceType;
+ userId: string;
+ workspaceId: string;
+}): Promise<boolean> => canPerformResourceAction({ ...params, action: 'manage' });
+
+/** Backward-compatible helper for the first three edit call sites. */
+export const assertCanEditResource = async (params: {
+ db: LobeChatDatabase;
+ resourceId: string;
+ resourceType: PermissionResourceType;
+ userId: string;
+ workspaceId?: string;
+}): Promise<void> => {
+ if (!params.workspaceId) return;
+ await assertCanPerformResourceAction({
+ ...params,
+ action: 'edit',
+ workspaceId: params.workspaceId,
+ });
+};
diff --git a/apps/server/src/services/workspacePermission/index.ts b/apps/server/src/services/workspacePermission/index.ts
index 4c45b3336f8..472fdf337d2 100644
--- a/apps/server/src/services/workspacePermission/index.ts
+++ b/apps/server/src/services/workspacePermission/index.ts
@@ -15,6 +15,61 @@ export interface WorkspaceScopedPermissionOptions {
workspaceId: string;
}
+export interface WorkspaceScopedPermissionMatches {
+ hasAllScope: boolean;
+ hasOwnerScope: boolean;
+}
+
+/**
+ * Resolve both resource scopes with one RBAC read. Membership and permission
+ * lookup are independent, so run them in parallel to keep permission-panel
+ * mutations to one database-latency wave.
+ */
+export const getWorkspaceScopedPermissionMatches = async ({
+ action,
+ db,
+ grantedPermissions,
+ requireMembership = true,
+ userId,
+ workspaceId,
+}: Omit<WorkspaceScopedPermissionOptions, 'scopes'> & {
+ grantedPermissions?: readonly string[];
+}): Promise<WorkspaceScopedPermissionMatches> => {
+ if (grantedPermissions) {
+ const granted = new Set(grantedPermissions);
+ return {
+ hasAllScope: getScopePermissions(action, ['ALL']).some((code) => granted.has(code)),
+ hasOwnerScope: getScopePermissions(action, ['OWNER']).some((code) => granted.has(code)),
+ };
+ }
+
+ const membershipPromise = requireMembership
+ ? db
+ .select({ userId: workspaceMembers.userId })
+ .from(workspaceMembers)
+ .where(
+ and(
+ eq(workspaceMembers.workspaceId, workspaceId),
+ eq(workspaceMembers.userId, userId),
+ isNull(workspaceMembers.deletedAt),
+ ),
+ )
+ .limit(1)
+ : Promise.resolve([{ userId }]);
+
+ const [membership, resolvedPermissions] = await Promise.all([
+ membershipPromise,
+ new RbacModel(db, userId).getUserPermissions({ workspaceId }),
+ ]);
+ if (!membership[0]) return { hasAllScope: false, hasOwnerScope: false };
+
+ const granted = new Set(resolvedPermissions);
+ return {
+ hasAllScope: getScopePermissions(action, ['ALL']).some((code) => granted.has(code)),
+ hasOwnerScope: getScopePermissions(action, ['OWNER']).some((code) => granted.has(code)),
+ };
+};
+
export const hasWorkspaceScopedPermission = async ({
action,
db,
diff --git a/locales/ar/chat.json b/locales/ar/chat.json
index da4bba2b602..149a806dd32 100644
--- a/locales/ar/chat.json
+++ b/locales/ar/chat.json
@@ -3,6 +3,7 @@
"active": "نشط",
"addAgentFromMarket": "إضافة من السوق",
"agent.publishToWorkspace": "نشر إلى مساحة العمل",
+ "agent.publishToWorkspaceErrorFixedPrivateDevice": "انشر الجهاز المثبت إلى مساحة العمل، أو دع الأعضاء يختارون جهازًا، قبل نشر هذا الوكيل.",
"agent.publishToWorkspaceSuccess": "تم النشر إلى مساحة العمل",
"agentBuilder.installPlugin.authRequired": "يتطلب Cloud MCP تسجيل الدخول للمتابعة",
"agentBuilder.installPlugin.cancel": "إلغاء",
@@ -349,9 +350,10 @@
"heteroAgent.executionTarget.downloadDesktop": "احصل على تطبيق سطح المكتب",
"heteroAgent.executionTarget.downloadDesktopDesc": "قم بتشغيل الوكلاء مع الوصول إلى جهاز الكمبيوتر الخاص بك",
"heteroAgent.executionTarget.downloadDesktopTitle": "احصل على تطبيق سطح المكتب",
+ "heteroAgent.executionTarget.fixedTip": "يستخدم هذا الوكيل بيئة تنفيذ مثبتة من قبل محرره. اطلب من المحرر تغييرها.",
"heteroAgent.executionTarget.gateway": "البوابة",
"heteroAgent.executionTarget.gatewayDesc": "التشغيل عبر بوابة الجهاز بحيث يمكن للعملاء الآخرين متابعة التقدم",
- "heteroAgent.executionTarget.infoTooltip": "اختر جهازًا بعيدًا لتشغيل هذا الجهاز من الويب. \"هذا الجهاز\" يشغل الوكيل محليًا وهو متاح فقط داخل تطبيق سطح المكتب.",
+ "heteroAgent.executionTarget.infoTooltip": "اختر مكان تشغيل هذا الوكيل. يمكن للجهاز قراءة وكتابة الملفات أو تشغيل جهاز كمبيوتر؛ يعمل Cloud Sandbox في بيئة مؤقتة معزولة.",
"heteroAgent.executionTarget.loading": "جارٍ تحميل الأجهزة...",
"heteroAgent.executionTarget.local": "هذا الجهاز",
"heteroAgent.executionTarget.localDesc": "تشغيل كعملية محلية على تطبيق سطح المكتب هذا",
@@ -366,7 +368,7 @@
"heteroAgent.executionTarget.sandbox": "بيئة سحابية مؤقتة",
"heteroAgent.executionTarget.sandboxDesc": "تشغيل في بيئة سحابية مؤقتة",
"heteroAgent.executionTarget.sandboxUnsupported": "{{name}} يعمل حاليًا فقط على جهاز محلي أو متصل",
- "heteroAgent.executionTarget.title": "جهاز التنفيذ",
+ "heteroAgent.executionTarget.title": "بيئة التنفيذ",
"heteroAgent.executionTarget.unknownDevice": "جهاز غير معروف",
"heteroAgent.executionTarget.workspaceGroup": "مساحة العمل",
"heteroAgent.fullAccess.label": "وصول كامل",
@@ -470,6 +472,8 @@
"input.sendWithCmdEnter": "اضغط <key/> للإرسال",
"input.sendWithEnter": "اضغط <key/> للإرسال",
"input.stop": "إيقاف",
+ "input.viewOnlyAgent": "لديك وصول للعرض فقط إلى هذا الوكيل، لذا لا يمكن إرسال الرسائل. اطلب من المنشئ أو مالك مساحة العمل الحصول على الوصول.",
+ "input.viewOnlyGroup": "لديك وصول للعرض فقط إلى هذه المجموعة، لذا لا يمكن إرسال الرسائل. اطلب من المنشئ أو مالك مساحة العمل الحصول على الوصول.",
"input.warp": "سطر جديد",
"input.warpWithKey": "اضغط <key/> لإدراج فاصل أسطر",
"inputQueue.delete": "حذف",
@@ -667,6 +671,8 @@
"pageCopilot.title": "وكيل الصفحة",
"pageSelection.lines": "الأسطر {{start}}-{{end}}",
"pageSelection.reference": "النص المحدد",
+ "permission.configAccess.agentChatOnly": "يمكن فقط للمتعاونين الذين لديهم صلاحية التحرير تكوين هذا الوكيل. تمت إعادتك إلى الدردشة.",
+ "permission.configAccess.groupChatOnly": "يمكن فقط للمتعاونين الذين لديهم صلاحية التحرير تكوين مجموعة الوكلاء هذه. تمت إعادتك إلى الدردشة.",
"pin": "تثبيت",
"pinOff": "إلغاء التثبيت",
"platformAgent.create.available": "متاح",
diff --git a/locales/ar/common.json b/locales/ar/common.json
index fcff328e80b..c1c3ee7cb89 100644
--- a/locales/ar/common.json
+++ b/locales/ar/common.json
@@ -212,6 +212,7 @@
"copy": "نسخ",
"copyFail": "فشل النسخ",
"copySuccess": "تم النسخ",
+ "createdAt": "تم الإنشاء في {{time}}",
"dataStatistics.messages": "الرسائل",
"dataStatistics.sessions": "الوكلاء",
"dataStatistics.today": "الجديد اليوم",
@@ -219,6 +220,7 @@
"defaultAgent": "وكيل مخصص",
"defaultSession": "وكيل مخصص",
"delete": "حذف",
+ "deleteSharedOwnerOnly": "يمكن فقط لمالك مساحة العمل حذف هذا — حيث يحتوي على محادثات الأعضاء الآخرين",
"document": "دليل المستخدم",
"download": "تنزيل",
"downloadingUpdate": "جارٍ تنزيل {{percent}}%",
diff --git a/locales/ar/home.json b/locales/ar/home.json
index 5f99d18ccd4..db4843890d7 100644
--- a/locales/ar/home.json
+++ b/locales/ar/home.json
@@ -44,12 +44,16 @@
"homePromoBanner.cta": "جرّب الآن",
"homePromoBanner.dismiss": "تجاهل",
"homePromoBanner.label": "{{model}} متاح الآن",
+ "inbox.author.scheduled": "مجدول",
"inbox.needsYou.title": "يحتاج إليك",
"inbox.news.markAllRead": "تحديد الكل كمقروء",
"inbox.news.subtitle": "لا شيء لتقرره - مجرد نظرة",
"inbox.news.title": "الملخص اليومي",
"inbox.running.title": "{{count}} مهمة قيد التشغيل",
"inbox.running.title_plural": "{{count}} مهام قيد التشغيل",
+ "inbox.scope.mine": "خاصتي",
+ "inbox.scope.onlyMe": "خاص بي فقط",
+ "inbox.scope.team": "الفريق",
"inbox.unread.followUp": "متابعة",
"inbox.unread.followUpPlaceholder": "رد للمتابعة في هذه المحادثة...",
"inbox.unread.title": "غير مقروء",
diff --git a/locales/ar/setting.json b/locales/ar/setting.json
index 0218a63d95c..06671cd2b6c 100644
--- a/locales/ar/setting.json
+++ b/locales/ar/setting.json
@@ -568,6 +568,23 @@
"notification.push.desc": "إرسال إشعارات دفع إلى أجهزتك المحمولة (يتطلب تطبيق LobeHub المحمول)",
"notification.push.title": "إشعارات الدفع للجوال",
"notification.title": "قنوات الإشعارات",
+ "permission.accessTag.useOnlyTip": "إذن العضو هنا هو \"يمكن الاستخدام\" — يمكنك العرض والاستخدام، ولكن لا يمكنك التعديل. اطلب من المنشئ أو مالك مساحة العمل الحصول على إذن التعديل.",
+ "permission.accessTag.viewOnlyTip": "إذن العضو هنا هو \"يمكن العرض\" — يمكنك العرض، ولكن لا يمكنك الاستخدام أو التعديل. اطلب من المنشئ أو مالك مساحة العمل الحصول على المزيد من الوصول.",
+ "permission.generalAccess.editable": "يمكن التعديل",
+ "permission.generalAccess.editableDesc": "يمكن للأعضاء العرض والاستخدام والتعديل",
+ "permission.generalAccess.editableDocumentDesc": "يمكن للأعضاء العرض والتعديل",
+ "permission.generalAccess.label": "أذونات الأعضاء",
+ "permission.generalAccess.trigger": "الأعضاء: {{level}}",
+ "permission.generalAccess.usable": "يمكن الاستخدام",
+ "permission.generalAccess.usableDesc": "يمكن للأعضاء العرض والاستخدام، ولكن لا يمكنهم التعديل",
+ "permission.generalAccess.viewable": "يمكن العرض",
+ "permission.generalAccess.viewableDesc": "يمكن للأعضاء العرض، ولكن لا يمكنهم الاستخدام أو التعديل",
+ "permission.generalAccess.viewableDocumentDesc": "يمكن للأعضاء العرض، ولكن لا يمكنهم التعديل",
+ "permission.loadFailed": "فشل تحميل إعدادات الأذونات",
+ "permission.noManagePermission": "فقط المنشئ أو مالك مساحة العمل يمكنه تغيير الأذونات",
+ "permission.saveNoEditPermission": "لديك إذن عرض فقط لهذه الصفحة، لذا لم يتم حفظ تغييراتك",
+ "permission.updateError": "فشل تحديث الأذونات",
+ "permission.viewOnlySendTip": "لديك إذن عرض فقط ولا يمكنك إرسال الرسائل",
"platformAgentConfig.availability.available": "متاح",
"platformAgentConfig.availability.checking": "جارٍ التحقق...",
"platformAgentConfig.availability.label": "التوفر",
@@ -627,6 +644,9 @@
"settingAgent.description.desc": "مقدمة موجزة عن وكيلك، ليست لإعداد الشخصية",
"settingAgent.description.placeholder": "أدخل وصف الوكيل",
"settingAgent.description.title": "وصف الوكيل",
+ "settingAgent.devicePolicy.noPublicDevice": "لا توجد أجهزة عامة",
+ "settingAgent.devicePolicy.selectTarget": "اختر البيئة",
+ "settingAgent.devicePolicy.title": "بيئة التنفيذ",
"settingAgent.export.dialogTitle": "تصدير ملف تعريف الوكيل",
"settingAgent.export.enabledPlugins": "المهارات المفعلة",
"settingAgent.export.error": "فشل في تصدير ملف تعريف الوكيل",
@@ -637,6 +657,8 @@
"settingAgent.export.tags": "العلامات",
"settingAgent.export.untitled": "وكيل بدون عنوان",
"settingAgent.export.untitledFileName": "ملف تعريف الوكيل",
+ "settingAgent.modelPolicy.fixedTip": "تم تثبيت النموذج في ملف تعريف الوكيل ولا يمكن تغييره أثناء الدردشة.",
+ "settingAgent.modelPolicy.title": "النموذج",
"settingAgent.name.placeholder": "أدخل اسم الوكيل",
"settingAgent.name.title": "الاسم",
"settingAgent.prompt.desc": "يحدد من هو هذا الوكيل، وما هو مسؤوليته، وكيف يعمل ويستجيب. إنه بمثابة تعليمات أساسية في كل محادثة.",
@@ -644,11 +666,14 @@
"settingAgent.prompt.placeholder": "أدخل إعدادات الوكيل، اضغط / لفتح قائمة الأوامر",
"settingAgent.prompt.title": "ملف تعريف الوكيل",
"settingAgent.runtimeConfig.title": "النموذج والأدوات",
+ "settingAgent.selectionPolicy.membersCanSwitch": "يمكن للأعضاء التبديل",
+ "settingAgent.selectionPolicy.membersCannotSwitch": "لا يمكن للأعضاء التبديل",
"settingAgent.submit": "تحديث الوكيل",
"settingAgent.tag.desc": "سيتم عرض علامات الوكيل في مجتمع الوكلاء",
"settingAgent.tag.placeholder": "أدخل علامة",
"settingAgent.tag.title": "العلامة",
"settingAgent.title": "معلومات الوكيل",
+ "settingAgent.toolsConfig.title": "الأدوات",
"settingAppearance.animationMode.agile": "سريع",
"settingAppearance.animationMode.desc": "اختر سرعة الرسوم المتحركة لإجراءات استجابة التطبيق",
"settingAppearance.animationMode.disabled": "إيقاف",
@@ -2274,6 +2299,7 @@
"workspace.member.manageAccess": "إدارة الوصول",
"workspace.member.manageAccessModal.current": "الحالي",
"workspace.member.manageAccessModal.failed": "فشل في تحديث الوصول",
+ "workspace.member.manageAccessModal.memberLimitReached": "لقد وصل هذا مساحة العمل إلى الحد الأقصى {{limit}} من الأعضاء. أضف مقاعد قبل تغيير هذا المستخدم إلى {{role}}.",
"workspace.member.manageAccessModal.save": "حفظ التغييرات",
"workspace.member.manageAccessModal.success": "تم تحديث الوصول",
"workspace.member.manageAccessModal.title": "إدارة الوصول إلى الفريق",
diff --git a/locales/bg-BG/chat.json b/locales/bg-BG/chat.json
index be135fb73f5..65c480e7fa5 100644
--- a/locales/bg-BG/chat.json
+++ b/locales/bg-BG/chat.json
@@ -3,6 +3,7 @@
"active": "Активен",
"addAgentFromMarket": "Добавяне от пазара",
"agent.publishToWorkspace": "Публикувай в работното пространство",
+ "agent.publishToWorkspaceErrorFixedPrivateDevice": "Публикувайте фиксираното устройство в работното пространство или оставете членовете да изберат устройство, преди да публикуват този агент.",
"agent.publishToWorkspaceSuccess": "Публикувано в работното пространство",
"agentBuilder.installPlugin.authRequired": "Cloud MCP изисква влизане, за да продължите",
"agentBuilder.installPlugin.cancel": "Отказ",
@@ -349,9 +350,10 @@
"heteroAgent.executionTarget.downloadDesktop": "Изтеглете десктоп приложението",
"heteroAgent.executionTarget.downloadDesktopDesc": "Стартирайте агенти с достъп до вашия компютър",
"heteroAgent.executionTarget.downloadDesktopTitle": "Изтеглете десктоп приложението",
+ "heteroAgent.executionTarget.fixedTip": "Този агент използва среда за изпълнение, фиксирана от неговия редактор. Помолете редактор да я промени.",
"heteroAgent.executionTarget.gateway": "Шлюз",
"heteroAgent.executionTarget.gatewayDesc": "Изпълнение чрез шлюза на устройството, за да могат други клиенти да следят напредъка",
- "heteroAgent.executionTarget.infoTooltip": "Изберете отдалечено устройство, за да управлявате тази машина от уеба. \"Това устройство\" изпълнява агента локално и е достъпно само в десктоп приложението.",
+ "heteroAgent.executionTarget.infoTooltip": "Изберете къде да работи този агент. Устройство може да чете и записва файлове или да управлява компютър; Cloud Sandbox работи в изолирана временна среда.",
"heteroAgent.executionTarget.loading": "Зареждане на устройства...",
"heteroAgent.executionTarget.local": "Това устройство",
"heteroAgent.executionTarget.localDesc": "Изпълнява се като локален процес в това десктоп приложение",
@@ -366,7 +368,7 @@
"heteroAgent.executionTarget.sandbox": "Облачен пясъчник",
"heteroAgent.executionTarget.sandboxDesc": "Изпълнява се в временен облачен пясъчник",
"heteroAgent.executionTarget.sandboxUnsupported": "{{name}} в момента работи само на локално или свързано устройство",
- "heteroAgent.executionTarget.title": "Устройство за изпълнение",
+ "heteroAgent.executionTarget.title": "Среда за изпълнение",
"heteroAgent.executionTarget.unknownDevice": "Неизвестно устройство",
"heteroAgent.executionTarget.workspaceGroup": "Работно пространство",
"heteroAgent.fullAccess.label": "Пълен достъп",
@@ -470,6 +472,8 @@
"input.sendWithCmdEnter": "Натиснете <key/>, за да изпратите",
"input.sendWithEnter": "Натиснете <key/>, за да изпратите",
"input.stop": "Спри",
+ "input.viewOnlyAgent": "Имате само достъп за преглед до този агент, така че съобщения не могат да бъдат изпращани. Помолете създателя или собственик на работното пространство за достъп.",
+ "input.viewOnlyGroup": "Имате само достъп за преглед до тази група, така че съобщения не могат да бъдат изпращани. Помолете създателя или собственик на работното пространство за достъп.",
"input.warp": "Нов ред",
"input.warpWithKey": "Натиснете <key/>, за да вмъкнете нов ред",
"inputQueue.delete": "Изтрий",
@@ -667,6 +671,8 @@
"pageCopilot.title": "Агент на страницата",
"pageSelection.lines": "Редове {{start}}-{{end}}",
"pageSelection.reference": "Избран текст",
+ "permission.configAccess.agentChatOnly": "Само сътрудници с права за редактиране могат да конфигурират този агент. Бяхте върнати към чата.",
+ "permission.configAccess.groupChatOnly": "Само сътрудници с права за редактиране могат да конфигурират тази група агенти. Бяхте върнати към чата.",
"pin": "Закачи",
"pinOff": "Откачи",
"platformAgent.create.available": "Наличен",
diff --git a/locales/bg-BG/common.json b/locales/bg-BG/common.json
index 36a0af56eea..894c11a397d 100644
--- a/locales/bg-BG/common.json
+++ b/locales/bg-BG/common.json
@@ -212,6 +212,7 @@
"copy": "Копирай",
"copyFail": "Копирането не бе успешно",
"copySuccess": "Копирано",
+ "createdAt": "Създадено на {{time}}",
"dataStatistics.messages": "Съобщения",
"dataStatistics.sessions": "Агенти",
"dataStatistics.today": "Нови днес",
@@ -219,6 +220,7 @@
"defaultAgent": "Потребителски агент",
"defaultSession": "Потребителски агент",
"delete": "Изтрий",
+ "deleteSharedOwnerOnly": "Само собственикът на работното пространство може да изтрие това — то съдържа разговори на други членове",
"document": "Ръководство за потребителя",
"download": "Изтегли",
"downloadingUpdate": "Изтегляне {{percent}}%",
diff --git a/locales/bg-BG/home.json b/locales/bg-BG/home.json
index d500b843b9e..a9843a45e05 100644
--- a/locales/bg-BG/home.json
+++ b/locales/bg-BG/home.json
@@ -44,12 +44,16 @@
"homePromoBanner.cta": "Опитайте сега",
"homePromoBanner.dismiss": "Затвори",
"homePromoBanner.label": "{{model}} вече е наличен",
+ "inbox.author.scheduled": "Планирано",
"inbox.needsYou.title": "Има нужда от вас",
"inbox.news.markAllRead": "Отбележи всички като прочетени",
"inbox.news.subtitle": "Няма какво да решавате — просто погледнете",
"inbox.news.title": "Ежедневен бюлетин",
"inbox.running.title": "{{count}} задача в процес",
"inbox.running.title_plural": "{{count}} задачи в процес",
+ "inbox.scope.mine": "Моите",
+ "inbox.scope.onlyMe": "Само моите",
+ "inbox.scope.team": "Екип",
"inbox.unread.followUp": "Последвайте",
"inbox.unread.followUpPlaceholder": "Отговорете, за да продължите този разговор...",
"inbox.unread.title": "Непрочетено",
diff --git a/locales/bg-BG/setting.json b/locales/bg-BG/setting.json
index 8039769aa29..ba91d7955a5 100644
--- a/locales/bg-BG/setting.json
+++ b/locales/bg-BG/setting.json
@@ -568,6 +568,23 @@
"notification.push.desc": "Изпращайте push известия до вашите мобилни устройства (изисква се мобилното приложение LobeHub)",
"notification.push.title": "Мобилни push известия",
"notification.title": "Канали за известия",
+ "permission.accessTag.useOnlyTip": "Вашето разрешение за членство тук е \"Може да използва\" — можете да го преглеждате и използвате, но не и да го редактирате. Помолете създателя или собственик на работното пространство за достъп за редактиране.",
+ "permission.accessTag.viewOnlyTip": "Вашето разрешение за членство тук е \"Може да преглежда\" — можете да го преглеждате, но не и да го използвате или редактирате. Помолете създателя или собственик на работното пространство за повече достъп.",
+ "permission.generalAccess.editable": "Може да редактира",
+ "permission.generalAccess.editableDesc": "Членовете могат да преглеждат, използват и редактират",
+ "permission.generalAccess.editableDocumentDesc": "Членовете могат да преглеждат и редактират",
+ "permission.generalAccess.label": "Разрешения за членове",
+ "permission.generalAccess.trigger": "Членове: {{level}}",
+ "permission.generalAccess.usable": "Може да използва",
+ "permission.generalAccess.usableDesc": "Членовете могат да преглеждат и използват, но не могат да редактират",
+ "permission.generalAccess.viewable": "Може да преглежда",
+ "permission.generalAccess.viewableDesc": "Членовете могат да преглеждат, но не могат да използват или редактират",
+ "permission.generalAccess.viewableDocumentDesc": "Членовете могат да преглеждат, но не могат да редактират",
+ "permission.loadFailed": "Неуспешно зареждане на настройките за разрешения",
+ "permission.noManagePermission": "Само създателят или собственик на работното пространство може да променя разрешенията",
+ "permission.saveNoEditPermission": "Имате само достъп за преглед на тази страница, затова вашите промени не бяха запазени",
+ "permission.updateError": "Неуспешно актуализиране на разрешението",
+ "permission.viewOnlySendTip": "Имате само достъп за преглед и не можете да изпращате съобщения",
"platformAgentConfig.availability.available": "Наличен",
"platformAgentConfig.availability.checking": "Проверка...",
"platformAgentConfig.availability.label": "Наличност",
@@ -627,6 +644,9 @@
"settingAgent.description.desc": "Кратко представяне на вашия агент, не е за задаване на характер",
"settingAgent.description.placeholder": "Въведете описание на агента",
"settingAgent.description.title": "Описание на агента",
+ "settingAgent.devicePolicy.noPublicDevice": "Няма публични устройства",
+ "settingAgent.devicePolicy.selectTarget": "Изберете среда",
+ "settingAgent.devicePolicy.title": "Среда за изпълнение",
"settingAgent.export.dialogTitle": "Експорт на профил на агент",
"settingAgent.export.enabledPlugins": "Активирани умения",
"settingAgent.export.error": "Неуспешен експорт на профила на агента",
@@ -637,6 +657,8 @@
"settingAgent.export.tags": "Етикети",
"settingAgent.export.untitled": "Безименен агент",
"settingAgent.export.untitledFileName": "профил-на-агент",
+ "settingAgent.modelPolicy.fixedTip": "Моделът е фиксиран в профила на агента и не може да бъде сменян по време на чат.",
+ "settingAgent.modelPolicy.title": "Модел",
"settingAgent.name.placeholder": "Въведете име на агента",
"settingAgent.name.title": "Име",
"settingAgent.prompt.desc": "Определя кой е този агент, за какво е отговорен и как работи и реагира. Той служи като основна инструкция във всяка комуникация.",
@@ -644,11 +666,14 @@
"settingAgent.prompt.placeholder": "Въведете настройки на агента, натиснете / за отваряне на менюто с команди",
"settingAgent.prompt.title": "Профил на агента",
"settingAgent.runtimeConfig.title": "Модел и инструменти",
+ "settingAgent.selectionPolicy.membersCanSwitch": "Членовете могат да сменят",
+ "settingAgent.selectionPolicy.membersCannotSwitch": "Членовете не могат да сменят",
"settingAgent.submit": "Актуализирай агента",
"settingAgent.tag.desc": "Етикетите на агента ще се показват в Общността на агентите",
"settingAgent.tag.placeholder": "Въведете етикет",
"settingAgent.tag.title": "Етикет",
"settingAgent.title": "Информация за агента",
+ "settingAgent.toolsConfig.title": "Инструменти",
"settingAppearance.animationMode.agile": "Бърз",
"settingAppearance.animationMode.desc": "Изберете скоростта на анимация за действията в приложението",
"settingAppearance.animationMode.disabled": "Изключено",
@@ -2274,6 +2299,7 @@
"workspace.member.manageAccess": "Управление на достъпа",
"workspace.member.manageAccessModal.current": "Текущ",
"workspace.member.manageAccessModal.failed": "Неуспешно актуализиране на достъпа",
+ "workspace.member.manageAccessModal.memberLimitReached": "Тази работна област е достигнала лимита от {{limit}} членове. Добавете места, преди да промените този потребител на {{role}}.",
"workspace.member.manageAccessModal.save": "Запазване на промените",
"workspace.member.manageAccessModal.success": "Достъпът е актуализиран",
"workspace.member.manageAccessModal.title": "Управление на достъпа на екипа",
diff --git a/locales/de-DE/chat.json b/locales/de-DE/chat.json
index 4a0d3e733dc..95dd511ba64 100644
--- a/locales/de-DE/chat.json
+++ b/locales/de-DE/chat.json
@@ -3,6 +3,7 @@
"active": "Aktiv",
"addAgentFromMarket": "Aus dem Markt hinzufügen",
"agent.publishToWorkspace": "In den Arbeitsbereich veröffentlichen",
+ "agent.publishToWorkspaceErrorFixedPrivateDevice": "Veröffentlichen Sie das reparierte Gerät im Arbeitsbereich oder lassen Sie Mitglieder ein Gerät auswählen, bevor Sie diesen Agenten veröffentlichen.",
"agent.publishToWorkspaceSuccess": "Im Arbeitsbereich veröffentlicht",
"agentBuilder.installPlugin.authRequired": "Cloud MCP erfordert eine Anmeldung zur Fortsetzung",
"agentBuilder.installPlugin.cancel": "Abbrechen",
@@ -349,9 +350,10 @@
"heteroAgent.executionTarget.downloadDesktop": "Desktop-App herunterladen",
"heteroAgent.executionTarget.downloadDesktopDesc": "Führen Sie Agenten mit Zugriff auf Ihren Computer aus",
"heteroAgent.executionTarget.downloadDesktopTitle": "Desktop-App herunterladen",
+ "heteroAgent.executionTarget.fixedTip": "Dieser Agent verwendet eine Ausführungsumgebung, die von seinem Editor festgelegt wurde. Bitten Sie einen Editor, diese zu ändern.",
"heteroAgent.executionTarget.gateway": "Gateway",
"heteroAgent.executionTarget.gatewayDesc": "Über das Geräte-Gateway ausführen, damit andere Clients den Fortschritt verfolgen können",
- "heteroAgent.executionTarget.infoTooltip": "Wählen Sie ein Remote-Gerät aus, um diese Maschine über das Web zu steuern. \"Dieses Gerät\" führt den Agenten lokal aus und ist nur in der Desktop-App verfügbar.",
+ "heteroAgent.executionTarget.infoTooltip": "Wählen Sie aus, wo dieser Agent ausgeführt wird. Ein Gerät kann Dateien lesen und schreiben oder einen Computer bedienen; Cloud Sandbox läuft in einer isolierten temporären Umgebung.",
"heteroAgent.executionTarget.loading": "Geräte werden geladen…",
"heteroAgent.executionTarget.local": "Dieses Gerät",
"heteroAgent.executionTarget.localDesc": "Als lokaler Prozess in dieser Desktop-App ausführen",
@@ -366,7 +368,7 @@
"heteroAgent.executionTarget.sandbox": "Cloud-Sandbox",
"heteroAgent.executionTarget.sandboxDesc": "In einer temporären Cloud-Sandbox ausführen",
"heteroAgent.executionTarget.sandboxUnsupported": "{{name}} läuft derzeit nur auf einem lokalen oder verbundenen Gerät",
- "heteroAgent.executionTarget.title": "Ausführungsgerät",
+ "heteroAgent.executionTarget.title": "Ausführungsumgebung",
"heteroAgent.executionTarget.unknownDevice": "Unbekanntes Gerät",
"heteroAgent.executionTarget.workspaceGroup": "Arbeitsbereich",
"heteroAgent.fullAccess.label": "Vollzugriff",
@@ -470,6 +472,8 @@
"input.sendWithCmdEnter": "Drücken Sie <key/>, um zu senden",
"input.sendWithEnter": "Drücken Sie <key/>, um zu senden",
"input.stop": "Stopp",
+ "input.viewOnlyAgent": "Sie haben nur Lesezugriff auf diesen Agenten, daher können keine Nachrichten gesendet werden. Bitten Sie den Ersteller oder einen Arbeitsbereichsbesitzer um Zugriff.",
+ "input.viewOnlyGroup": "Sie haben nur Lesezugriff auf diese Gruppe, daher können keine Nachrichten gesendet werden. Bitten Sie den Ersteller oder einen Arbeitsbereichsbesitzer um Zugriff.",
"input.warp": "Neue Zeile",
"input.warpWithKey": "Drücken Sie <key/>, um einen Zeilenumbruch einzufügen",
"inputQueue.delete": "Löschen",
@@ -667,6 +671,8 @@
"pageCopilot.title": "Seitenagent",
"pageSelection.lines": "Zeilen {{start}}–{{end}}",
"pageSelection.reference": "Ausgewählter Text",
+ "permission.configAccess.agentChatOnly": "Nur Mitarbeiter mit der Berechtigung 'Bearbeiten' können diesen Agenten konfigurieren. Sie wurden zurück zum Chat geleitet.",
+ "permission.configAccess.groupChatOnly": "Nur Mitarbeiter mit der Berechtigung 'Bearbeiten' können diese Agentengruppe konfigurieren. Sie wurden zurück zum Chat geleitet.",
"pin": "Anheften",
"pinOff": "Lösen",
"platformAgent.create.available": "Verfügbar",
diff --git a/locales/de-DE/common.json b/locales/de-DE/common.json
index 6949f7abeba..b4ef4bc0e89 100644
--- a/locales/de-DE/common.json
+++ b/locales/de-DE/common.json
@@ -212,6 +212,7 @@
"copy": "Kopieren",
"copyFail": "Kopieren fehlgeschlagen",
"copySuccess": "Kopiert",
+ "createdAt": "Erstellt am {{time}}",
"dataStatistics.messages": "Nachrichten",
"dataStatistics.sessions": "Agenten",
"dataStatistics.today": "Neue heute",
@@ -219,6 +220,7 @@
"defaultAgent": "Benutzerdefinierter Agent",
"defaultSession": "Benutzerdefinierter Agent",
"delete": "Löschen",
+ "deleteSharedOwnerOnly": "Nur ein Arbeitsbereichsbesitzer kann dies löschen — es enthält die Gespräche anderer Mitglieder",
"document": "Benutzerhandbuch",
"download": "Herunterladen",
"downloadingUpdate": "Lade {{percent}}% herunter",
diff --git a/locales/de-DE/home.json b/locales/de-DE/home.json
index e5afc2455d7..a9354ac9685 100644
--- a/locales/de-DE/home.json
+++ b/locales/de-DE/home.json
@@ -44,12 +44,16 @@
"homePromoBanner.cta": "Jetzt ausprobieren",
"homePromoBanner.dismiss": "Schließen",
"homePromoBanner.label": "{{model}} ist jetzt verfügbar",
+ "inbox.author.scheduled": "Geplant",
"inbox.needsYou.title": "Braucht dich",
"inbox.news.markAllRead": "Alle als gelesen markieren",
"inbox.news.subtitle": "Nichts zu entscheiden – nur ein Blick",
"inbox.news.title": "Tägliche Zusammenfassung",
"inbox.running.title": "{{count}} Aufgabe läuft",
"inbox.running.title_plural": "{{count}} Aufgaben laufen",
+ "inbox.scope.mine": "Meins",
+ "inbox.scope.onlyMe": "Nur meins",
+ "inbox.scope.team": "Team",
"inbox.unread.followUp": "Nachverfolgen",
"inbox.unread.followUpPlaceholder": "Antworten, um diesen Vorgang fortzusetzen…",
"inbox.unread.title": "Ungelesen",
diff --git a/locales/de-DE/setting.json b/locales/de-DE/setting.json
index b550ba4f008..eb94728ed01 100644
--- a/locales/de-DE/setting.json
+++ b/locales/de-DE/setting.json
@@ -568,6 +568,23 @@
"notification.push.desc": "Senden Sie Push-Benachrichtigungen an Ihre mobilen Geräte (LobeHub Mobile App erforderlich)",
"notification.push.title": "Mobile Push-Benachrichtigungen",
"notification.title": "Benachrichtigungskanäle",
+ "permission.accessTag.useOnlyTip": "Ihre Mitgliederberechtigung hier ist \"Kann verwenden\" — Sie können sie anzeigen und verwenden, aber nicht bearbeiten. Bitten Sie den Ersteller oder einen Arbeitsbereichsinhaber um Bearbeitungszugriff.",
+ "permission.accessTag.viewOnlyTip": "Ihre Mitgliederberechtigung hier ist \"Kann anzeigen\" — Sie können sie anzeigen, aber nicht verwenden oder bearbeiten. Bitten Sie den Ersteller oder einen Arbeitsbereichsinhaber um mehr Zugriff.",
+ "permission.generalAccess.editable": "Kann bearbeiten",
+ "permission.generalAccess.editableDesc": "Mitglieder können anzeigen, verwenden und bearbeiten",
+ "permission.generalAccess.editableDocumentDesc": "Mitglieder können anzeigen und bearbeiten",
+ "permission.generalAccess.label": "Mitgliederberechtigungen",
+ "permission.generalAccess.trigger": "Mitglieder: {{level}}",
+ "permission.generalAccess.usable": "Kann verwenden",
+ "permission.generalAccess.usableDesc": "Mitglieder können anzeigen und verwenden, aber nicht bearbeiten",
+ "permission.generalAccess.viewable": "Kann anzeigen",
+ "permission.generalAccess.viewableDesc": "Mitglieder können anzeigen, aber nicht verwenden oder bearbeiten",
+ "permission.generalAccess.viewableDocumentDesc": "Mitglieder können anzeigen, aber nicht bearbeiten",
+ "permission.loadFailed": "Fehler beim Laden der Berechtigungseinstellungen",
+ "permission.noManagePermission": "Nur der Ersteller oder ein Arbeitsbereichsinhaber kann Berechtigungen ändern",
+ "permission.saveNoEditPermission": "Sie haben nur Anzeigeberechtigung für diese Seite, daher wurden Ihre Änderungen nicht gespeichert",
+ "permission.updateError": "Fehler beim Aktualisieren der Berechtigung",
+ "permission.viewOnlySendTip": "Sie haben nur Anzeigeberechtigung und können keine Nachrichten senden",
"platformAgentConfig.availability.available": "Verfügbar",
"platformAgentConfig.availability.checking": "Überprüfen...",
"platformAgentConfig.availability.label": "Verfügbarkeit",
@@ -627,6 +644,9 @@
"settingAgent.description.desc": "Eine kurze Einführung in Ihren Agenten, nicht für die Charaktereinstellung",
"settingAgent.description.placeholder": "Agentenbeschreibung eingeben",
"settingAgent.description.title": "Agentenbeschreibung",
+ "settingAgent.devicePolicy.noPublicDevice": "Keine öffentlichen Geräte",
+ "settingAgent.devicePolicy.selectTarget": "Umgebung auswählen",
+ "settingAgent.devicePolicy.title": "Ausführungsumgebung",
"settingAgent.export.dialogTitle": "Agent-Profil exportieren",
"settingAgent.export.enabledPlugins": "Aktivierte Skills",
"settingAgent.export.error": "Agent-Profil konnte nicht exportiert werden",
@@ -637,6 +657,8 @@
"settingAgent.export.tags": "Tags",
"settingAgent.export.untitled": "Unbenannter Agent",
"settingAgent.export.untitledFileName": "agent-profile",
+ "settingAgent.modelPolicy.fixedTip": "Das Modell ist im Agentenprofil festgelegt und kann während des Chats nicht gewechselt werden.",
+ "settingAgent.modelPolicy.title": "Modell",
"settingAgent.name.placeholder": "Agentennamen eingeben",
"settingAgent.name.title": "Name",
"settingAgent.prompt.desc": "Definiert, wer dieser Agent ist, wofür er verantwortlich ist und wie er arbeitet und reagiert. Es dient als zentrale Anweisung in jedem Gespräch.",
@@ -644,11 +666,14 @@
"settingAgent.prompt.placeholder": "Agenteneinstellungen eingeben, / drücken, um das Befehlsmenü zu öffnen",
"settingAgent.prompt.title": "Agentenprofil",
"settingAgent.runtimeConfig.title": "Modell & Werkzeuge",
+ "settingAgent.selectionPolicy.membersCanSwitch": "Mitglieder können wechseln",
+ "settingAgent.selectionPolicy.membersCannotSwitch": "Mitglieder können nicht wechseln",
"settingAgent.submit": "Agent aktualisieren",
"settingAgent.tag.desc": "Agenten-Tags werden in der Agenten-Community angezeigt",
"settingAgent.tag.placeholder": "Tag eingeben",
"settingAgent.tag.title": "Tag",
"settingAgent.title": "Agenteninformationen",
+ "settingAgent.toolsConfig.title": "Werkzeuge",
"settingAppearance.animationMode.agile": "Agil",
"settingAppearance.animationMode.desc": "Wählen Sie die Animationsgeschwindigkeit für Reaktionen in der Anwendung",
"settingAppearance.animationMode.disabled": "Aus",
@@ -2274,6 +2299,7 @@
"workspace.member.manageAccess": "Zugriff verwalten",
"workspace.member.manageAccessModal.current": "Aktuell",
"workspace.member.manageAccessModal.failed": "Zugriff konnte nicht aktualisiert werden",
+ "workspace.member.manageAccessModal.memberLimitReached": "Dieser Arbeitsbereich hat die {{limit}}-Mitglieder-Grenze erreicht. Fügen Sie Plätze hinzu, bevor Sie diesen Benutzer zu {{role}} ändern.",
"workspace.member.manageAccessModal.save": "Änderungen speichern",
"workspace.member.manageAccessModal.success": "Zugriff aktualisiert",
"workspace.member.manageAccessModal.title": "Teamzugriff verwalten",
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index 8384731371c..8434aef2b9e 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -3,6 +3,7 @@
"active": "Active",
"addAgentFromMarket": "Add from Market",
"agent.publishToWorkspace": "Publish to Workspace",
+ "agent.publishToWorkspaceErrorFixedPrivateDevice": "Publish the fixed device to the workspace, or let members choose a device, before publishing this Agent.",
"agent.publishToWorkspaceSuccess": "Published to workspace",
"agentBuilder.installPlugin.authRequired": "Cloud MCP requires sign-in to continue",
"agentBuilder.installPlugin.cancel": "Cancel",
@@ -349,9 +350,10 @@
"heteroAgent.executionTarget.downloadDesktop": "Get Desktop App",
"heteroAgent.executionTarget.downloadDesktopDesc": "Run agents with access to your computer",
"heteroAgent.executionTarget.downloadDesktopTitle": "Get the desktop app",
+ "heteroAgent.executionTarget.fixedTip": "This Agent uses an execution environment fixed by its editor. Ask an editor to change it.",
"heteroAgent.executionTarget.gateway": "Gateway",
"heteroAgent.executionTarget.gatewayDesc": "Run through the device gateway so other clients can follow progress",
- "heteroAgent.executionTarget.infoTooltip": "Pick a device and the agent uses it as its runtime environment — reading and writing files and operating the computer. Cloud sandbox is provided by LobeHub Marketplace.",
+ "heteroAgent.executionTarget.infoTooltip": "Choose where this Agent runs. A device can read and write files or operate a computer; Cloud Sandbox runs in an isolated temporary environment.",
"heteroAgent.executionTarget.loading": "Loading devices…",
"heteroAgent.executionTarget.local": "Local device",
"heteroAgent.executionTarget.localDesc": "Run as a local process on this desktop app",
@@ -366,7 +368,7 @@
"heteroAgent.executionTarget.sandbox": "Cloud Sandbox",
"heteroAgent.executionTarget.sandboxDesc": "Run in an ephemeral cloud sandbox",
"heteroAgent.executionTarget.sandboxUnsupported": "{{name}} currently runs only on a local or connected device",
- "heteroAgent.executionTarget.title": "Execution Device",
+ "heteroAgent.executionTarget.title": "Execution Environment",
"heteroAgent.executionTarget.unknownDevice": "Unknown device",
"heteroAgent.executionTarget.workspaceGroup": "Workspace Devices",
"heteroAgent.fullAccess.label": "Full access",
@@ -470,6 +472,8 @@
"input.sendWithCmdEnter": "Press <key/> to send",
"input.sendWithEnter": "Press <key/> to send",
"input.stop": "Stop",
+ "input.viewOnlyAgent": "You have view-only access to this agent, so messages cannot be sent. Ask the creator or a workspace owner for access.",
+ "input.viewOnlyGroup": "You have view-only access to this group, so messages cannot be sent. Ask the creator or a workspace owner for access.",
"input.warp": "New Line",
"input.warpWithKey": "Press <key/> to insert a line break",
"inputQueue.delete": "Delete",
@@ -667,6 +671,8 @@
"pageCopilot.title": "Page Agent",
"pageSelection.lines": "Lines {{start}}-{{end}}",
"pageSelection.reference": "Selected Text",
+ "permission.configAccess.agentChatOnly": "Only collaborators with Can edit can configure this Agent. You were returned to chat.",
+ "permission.configAccess.groupChatOnly": "Only collaborators with Can edit can configure this Agent Group. You were returned to chat.",
"pin": "Pin",
"pinOff": "Unpin",
"platformAgent.create.available": "Available",
diff --git a/locales/en-US/common.json b/locales/en-US/common.json
index 2c06cc3c181..eac27676340 100644
--- a/locales/en-US/common.json
+++ b/locales/en-US/common.json
@@ -212,6 +212,7 @@
"copy": "Copy",
"copyFail": "Copy failed",
"copySuccess": "Copied",
+ "createdAt": "Created at {{time}}",
"dataStatistics.messages": "Messages",
"dataStatistics.sessions": "Agents",
"dataStatistics.today": "Today's New",
@@ -219,6 +220,7 @@
"defaultAgent": "Custom Agent",
"defaultSession": "Custom Agent",
"delete": "Delete",
+ "deleteSharedOwnerOnly": "Only a workspace owner can delete this — it carries other members' conversations",
"document": "User Manual",
"download": "Download",
"downloadingUpdate": "Downloading {{percent}}%",
diff --git a/locales/en-US/setting.json b/locales/en-US/setting.json
index 8c649185be9..c5bd1910233 100644
--- a/locales/en-US/setting.json
+++ b/locales/en-US/setting.json
@@ -568,6 +568,23 @@
"notification.push.desc": "Send push notifications to your mobile devices (LobeHub mobile app required)",
"notification.push.title": "Mobile Push Notifications",
"notification.title": "Notification Channels",
+ "permission.accessTag.useOnlyTip": "Your member permission here is \"Can use\" — you can view and use it, but not edit. Ask the creator or a workspace owner for edit access.",
+ "permission.accessTag.viewOnlyTip": "Your member permission here is \"Can view\" — you can view it, but not use or edit. Ask the creator or a workspace owner for more access.",
+ "permission.generalAccess.editable": "Can edit",
+ "permission.generalAccess.editableDesc": "Members can view, use, and edit",
+ "permission.generalAccess.editableDocumentDesc": "Members can view and edit",
+ "permission.generalAccess.label": "Member Permissions",
+ "permission.generalAccess.trigger": "Members: {{level}}",
+ "permission.generalAccess.usable": "Can use",
+ "permission.generalAccess.usableDesc": "Members can view and use, but cannot edit",
+ "permission.generalAccess.viewable": "Can view",
+ "permission.generalAccess.viewableDesc": "Members can view, but cannot use or edit",
+ "permission.generalAccess.viewableDocumentDesc": "Members can view, but cannot edit",
+ "permission.loadFailed": "Failed to load permission settings",
+ "permission.noManagePermission": "Only the creator or a workspace owner can change permissions",
+ "permission.saveNoEditPermission": "You have view-only access to this page, so your changes were not saved",
+ "permission.updateError": "Failed to update permission",
+ "permission.viewOnlySendTip": "You have view-only access and cannot send messages",
"platformAgentConfig.availability.available": "Available",
"platformAgentConfig.availability.checking": "Checking...",
"platformAgentConfig.availability.label": "Availability",
@@ -627,6 +644,9 @@
"settingAgent.description.desc": "A brief introduction to your agent, not for character setting",
"settingAgent.description.placeholder": "Enter agent description",
"settingAgent.description.title": "Agent Description",
+ "settingAgent.devicePolicy.noPublicDevice": "No public devices",
+ "settingAgent.devicePolicy.selectTarget": "Select environment",
+ "settingAgent.devicePolicy.title": "Execution environment",
"settingAgent.export.dialogTitle": "Export Agent Profile",
"settingAgent.export.enabledPlugins": "Enabled Skills",
"settingAgent.export.error": "Failed to export the agent profile",
@@ -637,6 +657,8 @@
"settingAgent.export.tags": "Tags",
"settingAgent.export.untitled": "Untitled Agent",
"settingAgent.export.untitledFileName": "agent-profile",
+ "settingAgent.modelPolicy.fixedTip": "The model is fixed in Agent Profile and cannot be switched while chatting.",
+ "settingAgent.modelPolicy.title": "Model",
"settingAgent.name.placeholder": "Enter agent name",
"settingAgent.name.title": "Name",
"settingAgent.prompt.desc": "Defines who this agent is, what it is responsible for, and how it works and responds. It serves as a core instruction in every conversation.",
@@ -644,11 +666,14 @@
"settingAgent.prompt.placeholder": "Enter agent instructions",
"settingAgent.prompt.title": "Core Instructions",
"settingAgent.runtimeConfig.title": "Model & Tools",
+ "settingAgent.selectionPolicy.membersCanSwitch": "Members can switch",
+ "settingAgent.selectionPolicy.membersCannotSwitch": "Members can't switch",
"settingAgent.submit": "Update Agent",
"settingAgent.tag.desc": "Agent tags will be displayed in the Agent Community",
"settingAgent.tag.placeholder": "Enter tag",
"settingAgent.tag.title": "Tag",
"settingAgent.title": "Agent info",
+ "settingAgent.toolsConfig.title": "Tools",
"settingAppearance.animationMode.agile": "Agile",
"settingAppearance.animationMode.desc": "Select the animation speed for application response actions",
"settingAppearance.animationMode.disabled": "Off",
@@ -2274,6 +2299,7 @@
"workspace.member.manageAccess": "Change role...",
"workspace.member.manageAccessModal.current": "Current",
"workspace.member.manageAccessModal.failed": "Failed to update access",
+ "workspace.member.manageAccessModal.memberLimitReached": "This workspace has reached its {{limit}}-member limit. Add seats before changing this user to {{role}}.",
"workspace.member.manageAccessModal.save": "Save Changes",
"workspace.member.manageAccessModal.success": "Access updated",
"workspace.member.manageAccessModal.title": "Change role for {{username}}",
diff --git a/locales/es-ES/chat.json b/locales/es-ES/chat.json
index 9af8a59cca9..b688075833b 100644
--- a/locales/es-ES/chat.json
+++ b/locales/es-ES/chat.json
@@ -3,6 +3,7 @@
"active": "Activo",
"addAgentFromMarket": "Agregar desde el Mercado",
"agent.publishToWorkspace": "Publicar en el espacio de trabajo",
+ "agent.publishToWorkspaceErrorFixedPrivateDevice": "Publica el dispositivo fijo en el espacio de trabajo, o permite que los miembros elijan un dispositivo, antes de publicar este Agente.",
"agent.publishToWorkspaceSuccess": "Publicado en el espacio de trabajo",
"agentBuilder.installPlugin.authRequired": "Cloud MCP requiere iniciar sesión para continuar",
"agentBuilder.installPlugin.cancel": "Cancelar",
@@ -349,9 +350,10 @@
"heteroAgent.executionTarget.downloadDesktop": "Obtener la aplicación de escritorio",
"heteroAgent.executionTarget.downloadDesktopDesc": "Ejecuta agentes con acceso a tu computadora",
"heteroAgent.executionTarget.downloadDesktopTitle": "Obtener la aplicación de escritorio",
+ "heteroAgent.executionTarget.fixedTip": "Este Agente utiliza un entorno de ejecución fijado por su editor. Pide a un editor que lo cambie.",
"heteroAgent.executionTarget.gateway": "Puerta de enlace",
"heteroAgent.executionTarget.gatewayDesc": "Ejecutar a través de la puerta de enlace del dispositivo para que otros clientes puedan seguir el progreso",
- "heteroAgent.executionTarget.infoTooltip": "Elige un dispositivo remoto para controlar esa máquina desde la web. \"Este dispositivo\" ejecuta el agente localmente y solo está disponible dentro de la aplicación de escritorio.",
+ "heteroAgent.executionTarget.infoTooltip": "Elige dónde se ejecuta este Agente. Un dispositivo puede leer y escribir archivos o operar una computadora; Cloud Sandbox se ejecuta en un entorno temporal aislado.",
"heteroAgent.executionTarget.loading": "Cargando dispositivos…",
"heteroAgent.executionTarget.local": "Este dispositivo",
"heteroAgent.executionTarget.localDesc": "Ejecutar como un proceso local en esta aplicación de escritorio",
@@ -366,7 +368,7 @@
"heteroAgent.executionTarget.sandbox": "Sandbox en la nube",
"heteroAgent.executionTarget.sandboxDesc": "Ejecutar en un sandbox efímero en la nube",
"heteroAgent.executionTarget.sandboxUnsupported": "{{name}} actualmente solo se ejecuta en un dispositivo local o conectado",
- "heteroAgent.executionTarget.title": "Dispositivo de Ejecución",
+ "heteroAgent.executionTarget.title": "Entorno de Ejecución",
"heteroAgent.executionTarget.unknownDevice": "Dispositivo desconocido",
"heteroAgent.executionTarget.workspaceGroup": "Espacio de trabajo",
"heteroAgent.fullAccess.label": "Acceso completo",
@@ -470,6 +472,8 @@
"input.sendWithCmdEnter": "Presiona <key/> para enviar",
"input.sendWithEnter": "Presiona <key/> para enviar",
"input.stop": "Detener",
+ "input.viewOnlyAgent": "Tienes acceso de solo lectura a este agente, por lo que no se pueden enviar mensajes. Pide acceso al creador o a un propietario del espacio de trabajo.",
+ "input.viewOnlyGroup": "Tienes acceso de solo lectura a este grupo, por lo que no se pueden enviar mensajes. Pide acceso al creador o a un propietario del espacio de trabajo.",
"input.warp": "Nueva línea",
"input.warpWithKey": "Presiona <key/> para insertar un salto de línea",
"inputQueue.delete": "Eliminar",
@@ -667,6 +671,8 @@
"pageCopilot.title": "Agente de página",
"pageSelection.lines": "Líneas {{start}}-{{end}}",
"pageSelection.reference": "Texto Seleccionado",
+ "permission.configAccess.agentChatOnly": "Solo los colaboradores con permiso de edición pueden configurar este Agente. Has sido devuelto al chat.",
+ "permission.configAccess.groupChatOnly": "Solo los colaboradores con permiso de edición pueden configurar este Grupo de Agentes. Has sido devuelto al chat.",
"pin": "Fijar",
"pinOff": "Desfijar",
"platformAgent.create.available": "Disponible",
diff --git a/locales/es-ES/common.json b/locales/es-ES/common.json
index c5c4b74f1d2..bc40fd3e554 100644
--- a/locales/es-ES/common.json
+++ b/locales/es-ES/common.json
@@ -212,6 +212,7 @@
"copy": "Copiar",
"copyFail": "Error al copiar",
"copySuccess": "Copiado",
+ "createdAt": "Creado el {{time}}",
"dataStatistics.messages": "Mensajes",
"dataStatistics.sessions": "Agentes",
"dataStatistics.today": "Nuevos de hoy",
@@ -219,6 +220,7 @@
"defaultAgent": "Agente personalizado",
"defaultSession": "Agente personalizado",
"delete": "Eliminar",
+ "deleteSharedOwnerOnly": "Solo el propietario del espacio de trabajo puede eliminar esto — contiene conversaciones de otros miembros",
"document": "Manual de usuario",
"download": "Descargar",
"downloadingUpdate": "Descargando {{percent}}%",
diff --git a/locales/es-ES/home.json b/locales/es-ES/home.json
index dd8efefda65..bf18ea7ced6 100644
--- a/locales/es-ES/home.json
+++ b/locales/es-ES/home.json
@@ -44,12 +44,16 @@
"homePromoBanner.cta": "Prueba ahora",
"homePromoBanner.dismiss": "Cerrar",
"homePromoBanner.label": "{{model}} ya está disponible",
+ "inbox.author.scheduled": "Programado",
"inbox.needsYou.title": "Te necesita",
"inbox.news.markAllRead": "Marcar todo como leído",
"inbox.news.subtitle": "Nada que decidir — solo un vistazo",
"inbox.news.title": "Resumen diario",
"inbox.running.title": "{{count}} tarea en ejecución",
"inbox.running.title_plural": "{{count}} tareas en ejecución",
+ "inbox.scope.mine": "Mío",
+ "inbox.scope.onlyMe": "Solo mío",
+ "inbox.scope.team": "Equipo",
"inbox.unread.followUp": "Dar seguimiento",
"inbox.unread.followUpPlaceholder": "Responde para continuar con esta conversación…",
"inbox.unread.title": "Sin leer",
diff --git a/locales/es-ES/setting.json b/locales/es-ES/setting.json
index 5f13681440b..3d28e50b0d3 100644
--- a/locales/es-ES/setting.json
+++ b/locales/es-ES/setting.json
@@ -568,6 +568,23 @@
"notification.push.desc": "Envía notificaciones push a tus dispositivos móviles (se requiere la aplicación móvil LobeHub)",
"notification.push.title": "Notificaciones Push Móviles",
"notification.title": "Canales de Notificación",
+ "permission.accessTag.useOnlyTip": "Tu permiso de miembro aquí es \"Puede usar\" — puedes verlo y usarlo, pero no editarlo. Pide al creador o a un propietario del espacio de trabajo acceso para editar.",
+ "permission.accessTag.viewOnlyTip": "Tu permiso de miembro aquí es \"Puede ver\" — puedes verlo, pero no usarlo ni editarlo. Pide al creador o a un propietario del espacio de trabajo más acceso.",
+ "permission.generalAccess.editable": "Puede editar",
+ "permission.generalAccess.editableDesc": "Los miembros pueden ver, usar y editar",
+ "permission.generalAccess.editableDocumentDesc": "Los miembros pueden ver y editar",
+ "permission.generalAccess.label": "Permisos de miembro",
+ "permission.generalAccess.trigger": "Miembros: {{level}}",
+ "permission.generalAccess.usable": "Puede usar",
+ "permission.generalAccess.usableDesc": "Los miembros pueden ver y usar, pero no pueden editar",
+ "permission.generalAccess.viewable": "Puede ver",
+ "permission.generalAccess.viewableDesc": "Los miembros pueden ver, pero no pueden usar ni editar",
+ "permission.generalAccess.viewableDocumentDesc": "Los miembros pueden ver, pero no pueden editar",
+ "permission.loadFailed": "Error al cargar la configuración de permisos",
+ "permission.noManagePermission": "Solo el creador o un propietario del espacio de trabajo puede cambiar los permisos",
+ "permission.saveNoEditPermission": "Tienes acceso de solo lectura a esta página, por lo que tus cambios no se guardaron",
+ "permission.updateError": "Error al actualizar el permiso",
+ "permission.viewOnlySendTip": "Tienes acceso de solo lectura y no puedes enviar mensajes",
"platformAgentConfig.availability.available": "Disponible",
"platformAgentConfig.availability.checking": "Comprobando...",
"platformAgentConfig.availability.label": "Disponibilidad",
@@ -627,6 +644,9 @@
"settingAgent.description.desc": "Una breve introducción de tu agente, no para configuración de personalidad",
"settingAgent.description.placeholder": "Introduce la descripción del agente",
"settingAgent.description.title": "Descripción del Agente",
+ "settingAgent.devicePolicy.noPublicDevice": "No hay dispositivos públicos",
+ "settingAgent.devicePolicy.selectTarget": "Seleccionar entorno",
+ "settingAgent.devicePolicy.title": "Entorno de ejecución",
"settingAgent.export.dialogTitle": "Exportar perfil del agente",
"settingAgent.export.enabledPlugins": "Habilidades habilitadas",
"settingAgent.export.error": "Error al exportar el perfil del agente",
@@ -637,6 +657,8 @@
"settingAgent.export.tags": "Etiquetas",
"settingAgent.export.untitled": "Agente sin título",
"settingAgent.export.untitledFileName": "perfil-agente",
+ "settingAgent.modelPolicy.fixedTip": "El modelo está fijado en el Perfil del Agente y no se puede cambiar durante el chat.",
+ "settingAgent.modelPolicy.title": "Modelo",
"settingAgent.name.placeholder": "Introduce el nombre del agente",
"settingAgent.name.title": "Nombre",
"settingAgent.prompt.desc": "Define quién es este agente, de qué es responsable y cómo funciona y responde. Sirve como una instrucción central en cada conversación.",
@@ -644,11 +666,14 @@
"settingAgent.prompt.placeholder": "Introduce la configuración del agente, presiona / para abrir el menú de comandos",
"settingAgent.prompt.title": "Perfil del Agente",
"settingAgent.runtimeConfig.title": "Modelo y Herramientas",
+ "settingAgent.selectionPolicy.membersCanSwitch": "Los miembros pueden cambiar",
+ "settingAgent.selectionPolicy.membersCannotSwitch": "Los miembros no pueden cambiar",
"settingAgent.submit": "Actualizar Agente",
"settingAgent.tag.desc": "Las etiquetas del agente se mostrarán en la Comunidad de Agentes",
"settingAgent.tag.placeholder": "Introduce una etiqueta",
"settingAgent.tag.title": "Etiqueta",
"settingAgent.title": "Información del Agente",
+ "settingAgent.toolsConfig.title": "Herramientas",
"settingAppearance.animationMode.agile": "Ágil",
"settingAppearance.animationMode.desc": "Selecciona la velocidad de animación para las acciones de respuesta de la aplicación",
"settingAppearance.animationMode.disabled": "Desactivado",
@@ -2274,6 +2299,7 @@
"workspace.member.manageAccess": "Gestionar acceso",
"workspace.member.manageAccessModal.current": "Actual",
"workspace.member.manageAccessModal.failed": "Error al actualizar acceso",
+ "workspace.member.manageAccessModal.memberLimitReached": "Este espacio de trabajo ha alcanzado su límite de {{limit}} miembros. Agrega asientos antes de cambiar este usuario a {{role}}.",
"workspace.member.manageAccessModal.save": "Guardar cambios",
"workspace.member.manageAccessModal.success": "Acceso actualizado",
"workspace.member.manageAccessModal.title": "Gestionar acceso del equipo",
diff --git a/locales/fa-IR/chat.json b/locales/fa-IR/chat.json
index 50ec90488cb..7a5654c9722 100644
--- a/locales/fa-IR/chat.json
+++ b/locales/fa-IR/chat.json
@@ -3,6 +3,7 @@
"active": "فعال",
"addAgentFromMarket": "افزودن از بازار",
"agent.publishToWorkspace": "انتشار در فضای کاری",
+ "agent.publishToWorkspaceErrorFixedPrivateDevice": "دستگاه ثابت را به فضای کاری منتشر کنید، یا اجازه دهید اعضا یک دستگاه انتخاب کنند، قبل از انتشار این عامل.",
"agent.publishToWorkspaceSuccess": "در فضای کاری منتشر شد",
"agentBuilder.installPlugin.authRequired": "برای ادامه، ورود به Cloud MCP الزامی است",
"agentBuilder.installPlugin.cancel": "لغو",
@@ -349,9 +350,10 @@
"heteroAgent.executionTarget.downloadDesktop": "دریافت اپلیکیشن دسکتاپ",
"heteroAgent.executionTarget.downloadDesktopDesc": "اجرای عوامل با دسترسی به کامپیوتر شما",
"heteroAgent.executionTarget.downloadDesktopTitle": "دریافت اپلیکیشن دسکتاپ",
+ "heteroAgent.executionTarget.fixedTip": "این عامل از محیط اجرایی که توسط ویرایشگر آن ثابت شده است استفاده می‌کند. از یک ویرایشگر بخواهید آن را تغییر دهد.",
"heteroAgent.executionTarget.gateway": "دروازه",
"heteroAgent.executionTarget.gatewayDesc": "از طریق دروازه دستگاه اجرا کنید تا سایر مشتریان بتوانند پیشرفت را دنبال کنند",
- "heteroAgent.executionTarget.infoTooltip": "یک دستگاه از راه دور را انتخاب کنید تا آن ماشین را از طریق وب کنترل کنید. \"این دستگاه\" عامل را به صورت محلی اجرا می‌کند و فقط در داخل برنامه دسکتاپ در دسترس است.",
+ "heteroAgent.executionTarget.infoTooltip": "محل اجرای این عامل را انتخاب کنید. یک دستگاه می‌تواند فایل‌ها را بخواند و بنویسد یا یک کامپیوتر را اجرا کند؛ محیط ابری Sandbox در یک محیط موقت ایزوله اجرا می‌شود.",
"heteroAgent.executionTarget.loading": "در حال بارگذاری دستگاه‌ها...",
"heteroAgent.executionTarget.local": "این دستگاه",
"heteroAgent.executionTarget.localDesc": "به عنوان یک فرآیند محلی در این برنامه دسکتاپ اجرا شود",
@@ -366,7 +368,7 @@
"heteroAgent.executionTarget.sandbox": "محیط آزمایشی ابری",
"heteroAgent.executionTarget.sandboxDesc": "در یک محیط آزمایشی ابری موقت اجرا شود",
"heteroAgent.executionTarget.sandboxUnsupported": "{{name}} در حال حاضر فقط روی یک دستگاه محلی یا متصل اجرا می‌شود",
- "heteroAgent.executionTarget.title": "دستگاه اجرا",
+ "heteroAgent.executionTarget.title": "محیط اجرایی",
"heteroAgent.executionTarget.unknownDevice": "دستگاه ناشناخته",
"heteroAgent.executionTarget.workspaceGroup": "محیط کاری",
"heteroAgent.fullAccess.label": "دسترسی کامل",
@@ -470,6 +472,8 @@
"input.sendWithCmdEnter": "برای ارسال <key/> را فشار دهید",
"input.sendWithEnter": "برای ارسال <key/> را فشار دهید",
"input.stop": "توقف",
+ "input.viewOnlyAgent": "شما فقط دسترسی مشاهده به این عامل دارید، بنابراین نمی‌توانید پیام ارسال کنید. از سازنده یا مالک فضای کاری درخواست دسترسی کنید.",
+ "input.viewOnlyGroup": "شما فقط دسترسی مشاهده به این گروه دارید، بنابراین نمی‌توانید پیام ارسال کنید. از سازنده یا مالک فضای کاری درخواست دسترسی کنید.",
"input.warp": "خط جدید",
"input.warpWithKey": "برای افزودن خط جدید <key/> را فشار دهید",
"inputQueue.delete": "حذف",
@@ -667,6 +671,8 @@
"pageCopilot.title": "نماینده صفحه",
"pageSelection.lines": "خطوط {{start}} تا {{end}}",
"pageSelection.reference": "متن انتخاب‌شده",
+ "permission.configAccess.agentChatOnly": "فقط همکارانی که دسترسی «قابلیت ویرایش» دارند می‌توانند این عامل را پیکربندی کنند. شما به چت بازگردانده شدید.",
+ "permission.configAccess.groupChatOnly": "فقط همکارانی که دسترسی «قابلیت ویرایش» دارند می‌توانند این گروه عامل را پیکربندی کنند. شما به چت بازگردانده شدید.",
"pin": "سنجاق کردن",
"pinOff": "برداشتن سنجاق",
"platformAgent.create.available": "در دسترس",
diff --git a/locales/fa-IR/common.json b/locales/fa-IR/common.json
index ccf4ed2cab5..8e4cb20c62a 100644
--- a/locales/fa-IR/common.json
+++ b/locales/fa-IR/common.json
@@ -212,6 +212,7 @@
"copy": "کپی",
"copyFail": "کپی انجام نشد",
"copySuccess": "کپی شد",
+ "createdAt": "ایجاد شده در {{time}}",
"dataStatistics.messages": "پیام‌ها",
"dataStatistics.sessions": "نمایندگان",
"dataStatistics.today": "جدیدهای امروز",
@@ -219,6 +220,7 @@
"defaultAgent": "نماینده سفارشی",
"defaultSession": "نماینده سفارشی",
"delete": "حذف",
+ "deleteSharedOwnerOnly": "فقط مالک فضای کاری می‌تواند این را حذف کند — این شامل مکالمات سایر اعضا می‌شود",
"document": "راهنمای کاربر",
"download": "دانلود",
"downloadingUpdate": "در حال دانلود {{percent}}%",
diff --git a/locales/fa-IR/home.json b/locales/fa-IR/home.json
index 94086428a33..ce00c5796d9 100644
--- a/locales/fa-IR/home.json
+++ b/locales/fa-IR/home.json
@@ -44,12 +44,16 @@
"homePromoBanner.cta": "همین حالا امتحان کنید",
"homePromoBanner.dismiss": "بستن",
"homePromoBanner.label": "{{model}} اکنون در دسترس است",
+ "inbox.author.scheduled": "برنامه‌ریزی شده",
"inbox.needsYou.title": "به شما نیاز دارد",
"inbox.news.markAllRead": "علامت‌گذاری همه به‌عنوان خوانده‌شده",
"inbox.news.subtitle": "چیزی برای تصمیم‌گیری نیست — فقط یک نگاه",
"inbox.news.title": "خلاصه روزانه",
"inbox.running.title": "{{count}} وظیفه در حال اجرا",
"inbox.running.title_plural": "{{count}} وظیفه در حال اجرا",
+ "inbox.scope.mine": "مال من",
+ "inbox.scope.onlyMe": "فقط مال من",
+ "inbox.scope.team": "تیم",
"inbox.unread.followUp": "پیگیری",
"inbox.unread.followUpPlaceholder": "پاسخ دهید تا این مکالمه ادامه یابد…",
"inbox.unread.title": "خوانده نشده",
diff --git a/locales/fa-IR/setting.json b/locales/fa-IR/setting.json
index bdead06cba5..1b65b13a6d5 100644
--- a/locales/fa-IR/setting.json
+++ b/locales/fa-IR/setting.json
@@ -568,6 +568,23 @@
"notification.push.desc": "ارسال اعلان‌های فشاری به دستگاه‌های موبایل شما (اپلیکیشن موبایل LobeHub مورد نیاز است)",
"notification.push.title": "اعلان‌های فشاری موبایل",
"notification.title": "کانال‌های اعلان",
+ "permission.accessTag.useOnlyTip": "مجوز شما در اینجا \"قابل استفاده\" است — شما می‌توانید آن را مشاهده و استفاده کنید، اما نمی‌توانید آن را ویرایش کنید. برای دسترسی به ویرایش، از سازنده یا مالک فضای کاری درخواست کنید.",
+ "permission.accessTag.viewOnlyTip": "مجوز شما در اینجا \"فقط قابل مشاهده\" است — شما می‌توانید آن را مشاهده کنید، اما نمی‌توانید از آن استفاده یا آن را ویرایش کنید. برای دسترسی بیشتر، از سازنده یا مالک فضای کاری درخواست کنید.",
+ "permission.generalAccess.editable": "قابل ویرایش",
+ "permission.generalAccess.editableDesc": "اعضا می‌توانند مشاهده، استفاده و ویرایش کنند",
+ "permission.generalAccess.editableDocumentDesc": "اعضا می‌توانند مشاهده و ویرایش کنند",
+ "permission.generalAccess.label": "مجوزهای اعضا",
+ "permission.generalAccess.trigger": "اعضا: {{level}}",
+ "permission.generalAccess.usable": "قابل استفاده",
+ "permission.generalAccess.usableDesc": "اعضا می‌توانند مشاهده و استفاده کنند، اما نمی‌توانند ویرایش کنند",
+ "permission.generalAccess.viewable": "قابل مشاهده",
+ "permission.generalAccess.viewableDesc": "اعضا می‌توانند مشاهده کنند، اما نمی‌توانند استفاده یا ویرایش کنند",
+ "permission.generalAccess.viewableDocumentDesc": "اعضا می‌توانند مشاهده کنند، اما نمی‌توانند ویرایش کنند",
+ "permission.loadFailed": "بارگذاری تنظیمات مجوز ناموفق بود",
+ "permission.noManagePermission": "تنها سازنده یا مالک فضای کاری می‌تواند مجوزها را تغییر دهد",
+ "permission.saveNoEditPermission": "شما فقط دسترسی مشاهده به این صفحه دارید، بنابراین تغییرات شما ذخیره نشد",
+ "permission.updateError": "به‌روزرسانی مجوز ناموفق بود",
+ "permission.viewOnlySendTip": "شما فقط دسترسی مشاهده دارید و نمی‌توانید پیام ارسال کنید",
"platformAgentConfig.availability.available": "در دسترس",
"platformAgentConfig.availability.checking": "در حال بررسی...",
"platformAgentConfig.availability.label": "دسترس‌پذیری",
@@ -627,6 +644,9 @@
"settingAgent.description.desc": "معرفی کوتاهی از عامل شما، نه برای تنظیم شخصیت",
"settingAgent.description.placeholder": "توضیحی برای عامل وارد کنید",
"settingAgent.description.title": "توضیحات عامل",
+ "settingAgent.devicePolicy.noPublicDevice": "قبل از ثابت کردن آن به این عامل، یک دستگاه فضای کاری عمومی منتشر کنید.",
+ "settingAgent.devicePolicy.selectTarget": "محیط را انتخاب کنید",
+ "settingAgent.devicePolicy.title": "دستگاه اجرایی",
"settingAgent.export.dialogTitle": "صادر کردن پروفایل عامل",
"settingAgent.export.enabledPlugins": "مهارت‌های فعال",
"settingAgent.export.error": "صادر کردن پروفایل عامل ناموفق بود",
@@ -637,6 +657,8 @@
"settingAgent.export.tags": "برچسب‌ها",
"settingAgent.export.untitled": "عامل بدون عنوان",
"settingAgent.export.untitledFileName": "پروفایل-عامل",
+ "settingAgent.modelPolicy.fixedTip": "مدل در پروفایل عامل ثابت است و نمی‌توان آن را هنگام چت تغییر داد.",
+ "settingAgent.modelPolicy.title": "مدل",
"settingAgent.name.placeholder": "نام عامل را وارد کنید",
"settingAgent.name.title": "نام",
"settingAgent.prompt.desc": "تعریف می‌کند که این عامل کیست، چه مسئولیتی دارد و چگونه کار می‌کند و پاسخ می‌دهد. این به عنوان یک دستورالعمل اصلی در هر مکالمه عمل می‌کند.",
@@ -644,11 +666,14 @@
"settingAgent.prompt.placeholder": "تنظیمات عامل را وارد کنید، برای باز کردن منوی دستورات / را فشار دهید",
"settingAgent.prompt.title": "پروفایل عامل",
"settingAgent.runtimeConfig.title": "مدل و ابزارها",
+ "settingAgent.selectionPolicy.membersCanSwitch": "اعضا می‌توانند تغییر دهند",
+ "settingAgent.selectionPolicy.membersCannotSwitch": "اعضا نمی‌توانند تغییر دهند",
"settingAgent.submit": "به‌روزرسانی عامل",
"settingAgent.tag.desc": "برچسب‌های عامل در جامعه عامل نمایش داده می‌شوند",
"settingAgent.tag.placeholder": "برچسب وارد کنید",
"settingAgent.tag.title": "برچسب",
"settingAgent.title": "اطلاعات عامل",
+ "settingAgent.toolsConfig.title": "ابزارها",
"settingAppearance.animationMode.agile": "سریع",
"settingAppearance.animationMode.desc": "سرعت انیمیشن واکنش‌های برنامه را انتخاب کنید",
"settingAppearance.animationMode.disabled": "خاموش",
@@ -2274,6 +2299,7 @@
"workspace.member.manageAccess": "مدیریت دسترسی",
"workspace.member.manageAccessModal.current": "فعلی",
"workspace.member.manageAccessModal.failed": "به‌روزرسانی دسترسی انجام نشد",
+ "workspace.member.manageAccessModal.memberLimitReached": "این فضای کاری به محدودیت {{limit}} عضو رسیده است. قبل از تغییر این کاربر به {{role}}، صندلی‌های بیشتری اضافه کنید.",
"workspace.member.manageAccessModal.save": "ذخیره تغییرات",
"workspace.member.manageAccessModal.success": "دسترسی به‌روزرسانی شد",
"workspace.member.manageAccessModal.title": "مدیریت دسترسی تیم",
diff --git a/locales/fr-FR/chat.json b/locales/fr-FR/chat.json
index 931aaac5cc2..637e16f3f45 100644
--- a/locales/fr-FR/chat.json
+++ b/locales/fr-FR/chat.json
@@ -3,6 +3,7 @@
"active": "Actif",
"addAgentFromMarket": "Ajouter depuis le Marché",
"agent.publishToWorkspace": "Publier dans l'espace de travail",
+ "agent.publishToWorkspaceErrorFixedPrivateDevice": "Publiez l'appareil corrigé dans l'espace de travail, ou laissez les membres choisir un appareil, avant de publier cet Agent.",
"agent.publishToWorkspaceSuccess": "Publié dans l'espace de travail",
"agentBuilder.installPlugin.authRequired": "Cloud MCP nécessite une connexion pour continuer",
"agentBuilder.installPlugin.cancel": "Annuler",
@@ -349,9 +350,10 @@
"heteroAgent.executionTarget.downloadDesktop": "Obtenir l'application de bureau",
"heteroAgent.executionTarget.downloadDesktopDesc": "Exécutez des agents avec accès à votre ordinateur",
"heteroAgent.executionTarget.downloadDesktopTitle": "Obtenir l'application de bureau",
+ "heteroAgent.executionTarget.fixedTip": "Cet Agent utilise un environnement d'exécution fixé par son éditeur. Demandez à un éditeur de le modifier.",
"heteroAgent.executionTarget.gateway": "Passerelle",
"heteroAgent.executionTarget.gatewayDesc": "Exécuter via la passerelle de l'appareil pour que d'autres clients puissent suivre la progression",
- "heteroAgent.executionTarget.infoTooltip": "Choisissez un appareil distant pour piloter cette machine depuis le web. \"Cet appareil\" exécute l'agent localement et n'est disponible que dans l'application de bureau.",
+ "heteroAgent.executionTarget.infoTooltip": "Choisissez où cet Agent s'exécute. Un appareil peut lire et écrire des fichiers ou faire fonctionner un ordinateur ; le Cloud Sandbox s'exécute dans un environnement temporaire isolé.",
"heteroAgent.executionTarget.loading": "Chargement des appareils…",
"heteroAgent.executionTarget.local": "Cet appareil",
"heteroAgent.executionTarget.localDesc": "Exécuter en tant que processus local sur cette application de bureau",
@@ -366,7 +368,7 @@
"heteroAgent.executionTarget.sandbox": "Bac à sable cloud",
"heteroAgent.executionTarget.sandboxDesc": "Exécuter dans un bac à sable cloud éphémère",
"heteroAgent.executionTarget.sandboxUnsupported": "{{name}} fonctionne actuellement uniquement sur un appareil local ou connecté",
- "heteroAgent.executionTarget.title": "Appareil d'exécution",
+ "heteroAgent.executionTarget.title": "Environnement d'exécution",
"heteroAgent.executionTarget.unknownDevice": "Appareil inconnu",
"heteroAgent.executionTarget.workspaceGroup": "Espace de travail",
"heteroAgent.fullAccess.label": "Accès complet",
@@ -470,6 +472,8 @@
"input.sendWithCmdEnter": "Appuyez sur <key/> pour envoyer",
"input.sendWithEnter": "Appuyez sur <key/> pour envoyer",
"input.stop": "Arrêter",
+ "input.viewOnlyAgent": "Vous avez un accès en lecture seule à cet agent, donc les messages ne peuvent pas être envoyés. Demandez au créateur ou à un propriétaire de l'espace de travail un accès.",
+ "input.viewOnlyGroup": "Vous avez un accès en lecture seule à ce groupe, donc les messages ne peuvent pas être envoyés. Demandez au créateur ou à un propriétaire de l'espace de travail un accès.",
"input.warp": "Nouvelle ligne",
"input.warpWithKey": "Appuyez sur <key/> pour insérer un saut de ligne",
"inputQueue.delete": "Supprimer",
@@ -667,6 +671,8 @@
"pageCopilot.title": "Agent de page",
"pageSelection.lines": "Lignes {{start}}-{{end}}",
"pageSelection.reference": "Texte sélectionné",
+ "permission.configAccess.agentChatOnly": "Seuls les collaborateurs ayant l'autorisation de modifier peuvent configurer cet Agent. Vous avez été renvoyé au chat.",
+ "permission.configAccess.groupChatOnly": "Seuls les collaborateurs ayant l'autorisation de modifier peuvent configurer ce Groupe d'Agents. Vous avez été renvoyé au chat.",
"pin": "Épingler",
"pinOff": "Désépingler",
"platformAgent.create.available": "Disponible",
diff --git a/locales/fr-FR/common.json b/locales/fr-FR/common.json
index 9717cb5fbd3..3944a768f87 100644
--- a/locales/fr-FR/common.json
+++ b/locales/fr-FR/common.json
@@ -212,6 +212,7 @@
"copy": "Copier",
"copyFail": "Échec de la copie",
"copySuccess": "Copié",
+ "createdAt": "Créé à {{time}}",
"dataStatistics.messages": "Messages",
"dataStatistics.sessions": "Agents",
"dataStatistics.today": "Nouveaux aujourd'hui",
@@ -219,6 +220,7 @@
"defaultAgent": "Agent personnalisé",
"defaultSession": "Agent personnalisé",
"delete": "Supprimer",
+ "deleteSharedOwnerOnly": "Seul le propriétaire de l'espace de travail peut supprimer ceci — cela contient les conversations d'autres membres",
"document": "Manuel utilisateur",
"download": "Télécharger",
"downloadingUpdate": "Téléchargement {{percent}}%",
diff --git a/locales/fr-FR/home.json b/locales/fr-FR/home.json
index 54d4a003dfa..75d3ee901e0 100644
--- a/locales/fr-FR/home.json
+++ b/locales/fr-FR/home.json
@@ -44,12 +44,16 @@
"homePromoBanner.cta": "Essayez maintenant",
"homePromoBanner.dismiss": "Fermer",
"homePromoBanner.label": "{{model}} est maintenant disponible",
+ "inbox.author.scheduled": "Planifié",
"inbox.needsYou.title": "A besoin de vous",
"inbox.news.markAllRead": "Marquer tout comme lu",
"inbox.news.subtitle": "Rien à décider — juste un coup d'œil",
"inbox.news.title": "Résumé quotidien",
"inbox.running.title": "{{count}} tâche en cours",
"inbox.running.title_plural": "{{count}} tâches en cours",
+ "inbox.scope.mine": "À moi",
+ "inbox.scope.onlyMe": "Seulement à moi",
+ "inbox.scope.team": "Équipe",
"inbox.unread.followUp": "Faire un suivi",
"inbox.unread.followUpPlaceholder": "Répondez pour continuer cette conversation…",
"inbox.unread.title": "Non lu",
diff --git a/locales/fr-FR/setting.json b/locales/fr-FR/setting.json
index caa25daf0c8..a439e7d0970 100644
--- a/locales/fr-FR/setting.json
+++ b/locales/fr-FR/setting.json
@@ -568,6 +568,23 @@
"notification.push.desc": "Envoyez des notifications push à vos appareils mobiles (application mobile LobeHub requise)",
"notification.push.title": "Notifications Push Mobiles",
"notification.title": "Canaux de notification",
+ "permission.accessTag.useOnlyTip": "Votre autorisation de membre ici est \"Peut utiliser\" — vous pouvez le consulter et l'utiliser, mais pas le modifier. Demandez au créateur ou au propriétaire de l'espace de travail un accès de modification.",
+ "permission.accessTag.viewOnlyTip": "Votre autorisation de membre ici est \"Peut consulter\" — vous pouvez le consulter, mais pas l'utiliser ou le modifier. Demandez au créateur ou au propriétaire de l'espace de travail un accès supplémentaire.",
+ "permission.generalAccess.editable": "Peut modifier",
+ "permission.generalAccess.editableDesc": "Les membres peuvent voir, utiliser et modifier",
+ "permission.generalAccess.editableDocumentDesc": "Les membres peuvent voir et modifier",
+ "permission.generalAccess.label": "Permissions des membres",
+ "permission.generalAccess.trigger": "Membres : {{level}}",
+ "permission.generalAccess.usable": "Peut utiliser",
+ "permission.generalAccess.usableDesc": "Les membres peuvent voir et utiliser, mais ne peuvent pas modifier",
+ "permission.generalAccess.viewable": "Peut voir",
+ "permission.generalAccess.viewableDesc": "Les membres peuvent voir, mais ne peuvent ni utiliser ni modifier",
+ "permission.generalAccess.viewableDocumentDesc": "Les membres peuvent voir, mais ne peuvent pas modifier",
+ "permission.loadFailed": "Échec du chargement des paramètres de permission",
+ "permission.noManagePermission": "Seul le créateur ou un propriétaire de l'espace de travail peut modifier les permissions",
+ "permission.saveNoEditPermission": "Vous avez un accès en lecture seule à cette page, donc vos modifications n'ont pas été enregistrées",
+ "permission.updateError": "Échec de la mise à jour des permissions",
+ "permission.viewOnlySendTip": "Vous avez un accès en lecture seule et ne pouvez pas envoyer de messages",
"platformAgentConfig.availability.available": "Disponible",
"platformAgentConfig.availability.checking": "Vérification...",
"platformAgentConfig.availability.label": "Disponibilité",
@@ -627,6 +644,9 @@
"settingAgent.description.desc": "Une brève présentation de votre agent, sans lien avec sa personnalité",
"settingAgent.description.placeholder": "Saisissez la description de l’agent",
"settingAgent.description.title": "Description de l’agent",
+ "settingAgent.devicePolicy.noPublicDevice": "Publiez un appareil de l'espace de travail avant de le fixer à cet Agent.",
+ "settingAgent.devicePolicy.selectTarget": "Sélectionner l'environnement",
+ "settingAgent.devicePolicy.title": "Appareil d'exécution",
"settingAgent.export.dialogTitle": "Exporter le profil de l'agent",
"settingAgent.export.enabledPlugins": "Compétences activées",
"settingAgent.export.error": "Échec de l'exportation du profil de l'agent",
@@ -637,6 +657,8 @@
"settingAgent.export.tags": "Étiquettes",
"settingAgent.export.untitled": "Agent sans titre",
"settingAgent.export.untitledFileName": "profil-agent",
+ "settingAgent.modelPolicy.fixedTip": "Le modèle est fixé dans le profil de l'agent et ne peut pas être changé pendant la conversation.",
+ "settingAgent.modelPolicy.title": "Modèle",
"settingAgent.name.placeholder": "Saisissez le nom de l’agent",
"settingAgent.name.title": "Nom",
"settingAgent.prompt.desc": "Définit qui est cet agent, ce dont il est responsable, comment il fonctionne et répond. Cela sert d'instruction principale dans chaque conversation.",
@@ -644,11 +666,14 @@
"settingAgent.prompt.placeholder": "Saisissez les paramètres de l’agent, appuyez sur / pour ouvrir le menu de commandes",
"settingAgent.prompt.title": "Profil de l’agent",
"settingAgent.runtimeConfig.title": "Modèle & Outils",
+ "settingAgent.selectionPolicy.membersCanSwitch": "Les membres peuvent changer",
+ "settingAgent.selectionPolicy.membersCannotSwitch": "Les membres ne peuvent pas changer",
"settingAgent.submit": "Mettre à jour l’agent",
"settingAgent.tag.desc": "Les étiquettes de l’agent seront visibles dans la communauté",
"settingAgent.tag.placeholder": "Saisissez une étiquette",
"settingAgent.tag.title": "Étiquette",
"settingAgent.title": "Informations de l’agent",
+ "settingAgent.toolsConfig.title": "Outils",
"settingAppearance.animationMode.agile": "Rapide",
"settingAppearance.animationMode.desc": "Choisissez la vitesse d’animation des actions de réponse de l’application",
"settingAppearance.animationMode.disabled": "Désactivé",
@@ -2274,6 +2299,7 @@
"workspace.member.manageAccess": "Gérer l'accès",
"workspace.member.manageAccessModal.current": "Actuel",
"workspace.member.manageAccessModal.failed": "Échec de la mise à jour de l'accès",
+ "workspace.member.manageAccessModal.memberLimitReached": "Cet espace de travail a atteint sa limite de {{limit}} membres. Ajoutez des places avant de changer cet utilisateur en {{role}}.",
"workspace.member.manageAccessModal.save": "Enregistrer les modifications",
"workspace.member.manageAccessModal.success": "Accès mis à jour",
"workspace.member.manageAccessModal.title": "Gérer l'accès de l'équipe",
diff --git a/locales/it-IT/chat.json b/locales/it-IT/chat.json
index c2ebcbeb9a2..380fe9e8f52 100644
--- a/locales/it-IT/chat.json
+++ b/locales/it-IT/chat.json
@@ -3,6 +3,7 @@
"active": "Attivo",
"addAgentFromMarket": "Aggiungi dal Mercato",
"agent.publishToWorkspace": "Pubblica nello Spazio di Lavoro",
+ "agent.publishToWorkspaceErrorFixedPrivateDevice": "Pubblica il dispositivo fisso nello spazio di lavoro o lascia che i membri scelgano un dispositivo prima di pubblicare questo Agente.",
"agent.publishToWorkspaceSuccess": "Pubblicato nello spazio di lavoro",
"agentBuilder.installPlugin.authRequired": "Cloud MCP richiede l'accesso per continuare",
"agentBuilder.installPlugin.cancel": "Annulla",
@@ -349,9 +350,10 @@
"heteroAgent.executionTarget.downloadDesktop": "Scarica l'App Desktop",
"heteroAgent.executionTarget.downloadDesktopDesc": "Esegui agenti con accesso al tuo computer",
"heteroAgent.executionTarget.downloadDesktopTitle": "Scarica l'app desktop",
+ "heteroAgent.executionTarget.fixedTip": "Questo Agente utilizza un ambiente di esecuzione fissato dal suo editor. Chiedi a un editor di modificarlo.",
"heteroAgent.executionTarget.gateway": "Gateway",
"heteroAgent.executionTarget.gatewayDesc": "Esegui tramite il gateway del dispositivo in modo che altri client possano seguire i progressi",
- "heteroAgent.executionTarget.infoTooltip": "Scegli un dispositivo remoto per controllare quella macchina dal web. \"Questo dispositivo\" esegue l'agente localmente ed è disponibile solo nell'app desktop.",
+ "heteroAgent.executionTarget.infoTooltip": "Scegli dove esegue questo Agente. Un dispositivo può leggere e scrivere file o operare su un computer; il Cloud Sandbox funziona in un ambiente temporaneo isolato.",
"heteroAgent.executionTarget.loading": "Caricamento dispositivi…",
"heteroAgent.executionTarget.local": "Questo dispositivo",
"heteroAgent.executionTarget.localDesc": "Esegui come processo locale su questa app desktop",
@@ -366,7 +368,7 @@
"heteroAgent.executionTarget.sandbox": "Sandbox cloud",
"heteroAgent.executionTarget.sandboxDesc": "Esegui in un sandbox cloud temporaneo",
"heteroAgent.executionTarget.sandboxUnsupported": "{{name}} attualmente funziona solo su un dispositivo locale o connesso",
- "heteroAgent.executionTarget.title": "Dispositivo di esecuzione",
+ "heteroAgent.executionTarget.title": "Ambiente di Esecuzione",
"heteroAgent.executionTarget.unknownDevice": "Dispositivo sconosciuto",
"heteroAgent.executionTarget.workspaceGroup": "Workspace",
"heteroAgent.fullAccess.label": "Accesso completo",
@@ -470,6 +472,8 @@
"input.sendWithCmdEnter": "Premi <key/> per inviare",
"input.sendWithEnter": "Premi <key/> per inviare",
"input.stop": "Ferma",
+ "input.viewOnlyAgent": "Hai accesso in sola lettura a questo agente, quindi non è possibile inviare messaggi. Chiedi al creatore o a un proprietario dello spazio di lavoro l'accesso.",
+ "input.viewOnlyGroup": "Hai accesso in sola lettura a questo gruppo, quindi non è possibile inviare messaggi. Chiedi al creatore o a un proprietario dello spazio di lavoro l'accesso.",
"input.warp": "Nuova Riga",
"input.warpWithKey": "Premi <key/> per inserire un'interruzione di riga",
"inputQueue.delete": "Elimina",
@@ -667,6 +671,8 @@
"pageCopilot.title": "Agente di pagina",
"pageSelection.lines": "Righe {{start}}-{{end}}",
"pageSelection.reference": "Testo selezionato",
+ "permission.configAccess.agentChatOnly": "Solo i collaboratori con permesso di Modifica possono configurare questo Agente. Sei stato reindirizzato alla chat.",
+ "permission.configAccess.groupChatOnly": "Solo i collaboratori con permesso di Modifica possono configurare questo Gruppo di Agenti. Sei stato reindirizzato alla chat.",
"pin": "Fissa",
"pinOff": "Rimuovi fissaggio",
"platformAgent.create.available": "Disponibile",
diff --git a/locales/it-IT/common.json b/locales/it-IT/common.json
index 8f3809287d6..22706f08e93 100644
--- a/locales/it-IT/common.json
+++ b/locales/it-IT/common.json
@@ -212,6 +212,7 @@
"copy": "Copia",
"copyFail": "Copia non riuscita",
"copySuccess": "Copiato",
+ "createdAt": "Creato il {{time}}",
"dataStatistics.messages": "Messaggi",
"dataStatistics.sessions": "Agenti",
"dataStatistics.today": "Nuovi di oggi",
@@ -219,6 +220,7 @@
"defaultAgent": "Agente personalizzato",
"defaultSession": "Agente personalizzato",
"delete": "Elimina",
+ "deleteSharedOwnerOnly": "Solo il proprietario di uno spazio di lavoro può eliminare questo elemento — contiene le conversazioni di altri membri",
"document": "Manuale utente",
"download": "Scarica",
"downloadingUpdate": "Scaricamento {{percent}}%",
diff --git a/locales/it-IT/home.json b/locales/it-IT/home.json
index 4dfd6c875df..a77a399a766 100644
--- a/locales/it-IT/home.json
+++ b/locales/it-IT/home.json
@@ -44,12 +44,16 @@
"homePromoBanner.cta": "Prova ora",
"homePromoBanner.dismiss": "Chiudi",
"homePromoBanner.label": "{{model}} è ora disponibile",
+ "inbox.author.scheduled": "Programmato",
"inbox.needsYou.title": "Ha bisogno di te",
"inbox.news.markAllRead": "Segna tutto come letto",
"inbox.news.subtitle": "Niente da decidere — solo uno sguardo",
"inbox.news.title": "Riepilogo quotidiano",
"inbox.running.title": "{{count}} attività in corso",
"inbox.running.title_plural": "{{count}} attività in corso",
+ "inbox.scope.mine": "Mio",
+ "inbox.scope.onlyMe": "Solo mio",
+ "inbox.scope.team": "Squadra",
"inbox.unread.followUp": "Segui",
"inbox.unread.followUpPlaceholder": "Rispondi per continuare questa conversazione…",
"inbox.unread.title": "Non letti",
diff --git a/locales/it-IT/setting.json b/locales/it-IT/setting.json
index b1732e82424..23f5321e99f 100644
--- a/locales/it-IT/setting.json
+++ b/locales/it-IT/setting.json
@@ -568,6 +568,23 @@
"notification.push.desc": "Invia notifiche push ai tuoi dispositivi mobili (è richiesta l'app mobile LobeHub)",
"notification.push.title": "Notifiche Push Mobile",
"notification.title": "Canali di Notifica",
+ "permission.accessTag.useOnlyTip": "Il tuo permesso di membro qui è \"Può usare\" — puoi visualizzarlo e usarlo, ma non modificarlo. Chiedi al creatore o a un proprietario dello spazio di lavoro l'accesso per modificare.",
+ "permission.accessTag.viewOnlyTip": "Il tuo permesso di membro qui è \"Può visualizzare\" — puoi visualizzarlo, ma non usarlo o modificarlo. Chiedi al creatore o a un proprietario dello spazio di lavoro un accesso maggiore.",
+ "permission.generalAccess.editable": "Può modificare",
+ "permission.generalAccess.editableDesc": "I membri possono visualizzare, utilizzare e modificare",
+ "permission.generalAccess.editableDocumentDesc": "I membri possono visualizzare e modificare",
+ "permission.generalAccess.label": "Permessi dei membri",
+ "permission.generalAccess.trigger": "Membri: {{level}}",
+ "permission.generalAccess.usable": "Può utilizzare",
+ "permission.generalAccess.usableDesc": "I membri possono visualizzare e utilizzare, ma non modificare",
+ "permission.generalAccess.viewable": "Può visualizzare",
+ "permission.generalAccess.viewableDesc": "I membri possono visualizzare, ma non utilizzare o modificare",
+ "permission.generalAccess.viewableDocumentDesc": "I membri possono visualizzare, ma non modificare",
+ "permission.loadFailed": "Impossibile caricare le impostazioni dei permessi",
+ "permission.noManagePermission": "Solo il creatore o un proprietario dello spazio di lavoro può modificare i permessi",
+ "permission.saveNoEditPermission": "Hai accesso in sola visualizzazione a questa pagina, quindi le tue modifiche non sono state salvate",
+ "permission.updateError": "Impossibile aggiornare i permessi",
+ "permission.viewOnlySendTip": "Hai accesso in sola visualizzazione e non puoi inviare messaggi",
"platformAgentConfig.availability.available": "Disponibile",
"platformAgentConfig.availability.checking": "Verifica in corso...",
"platformAgentConfig.availability.label": "Disponibilità",
@@ -627,6 +644,9 @@
"settingAgent.description.desc": "Una breve introduzione al tuo agente, non per l'impostazione del personaggio",
"settingAgent.description.placeholder": "Inserisci la descrizione dell'agente",
"settingAgent.description.title": "Descrizione Agente",
+ "settingAgent.devicePolicy.noPublicDevice": "Pubblica un dispositivo del workspace prima di fissarlo a questo Agente.",
+ "settingAgent.devicePolicy.selectTarget": "Seleziona ambiente",
+ "settingAgent.devicePolicy.title": "Dispositivo di esecuzione",
"settingAgent.export.dialogTitle": "Esporta profilo agente",
"settingAgent.export.enabledPlugins": "Abilità abilitate",
"settingAgent.export.error": "Esportazione del profilo agente fallita",
@@ -637,6 +657,8 @@
"settingAgent.export.tags": "Tag",
"settingAgent.export.untitled": "Agente senza titolo",
"settingAgent.export.untitledFileName": "profilo-agente",
+ "settingAgent.modelPolicy.fixedTip": "Il modello è fisso nel profilo dell'agente e non può essere cambiato durante la chat.",
+ "settingAgent.modelPolicy.title": "Modello",
"settingAgent.name.placeholder": "Inserisci il nome dell'agente",
"settingAgent.name.title": "Nome",
"settingAgent.prompt.desc": "Definisce chi è questo agente, di cosa è responsabile, come funziona e risponde. Serve come istruzione principale in ogni conversazione.",
@@ -644,11 +666,14 @@
"settingAgent.prompt.placeholder": "Inserisci le impostazioni dell'agente, premi / per aprire il menu comandi",
"settingAgent.prompt.title": "Profilo Agente",
"settingAgent.runtimeConfig.title": "Modello e Strumenti",
+ "settingAgent.selectionPolicy.membersCanSwitch": "I membri possono cambiare",
+ "settingAgent.selectionPolicy.membersCannotSwitch": "I membri non possono cambiare",
"settingAgent.submit": "Aggiorna Agente",
"settingAgent.tag.desc": "I tag dell'agente saranno visibili nella Community degli Agenti",
"settingAgent.tag.placeholder": "Inserisci tag",
"settingAgent.tag.title": "Tag",
"settingAgent.title": "Informazioni Agente",
+ "settingAgent.toolsConfig.title": "Strumenti",
"settingAppearance.animationMode.agile": "Agile",
"settingAppearance.animationMode.desc": "Seleziona la velocità dell'animazione per le azioni di risposta dell'applicazione",
"settingAppearance.animationMode.disabled": "Disattivato",
@@ -2274,6 +2299,7 @@
"workspace.member.manageAccess": "Gestisci accesso",
"workspace.member.manageAccessModal.current": "Attuale",
"workspace.member.manageAccessModal.failed": "Impossibile aggiornare l'accesso",
+ "workspace.member.manageAccessModal.memberLimitReached": "Questo workspace ha raggiunto il limite di {{limit}} membri. Aggiungi posti prima di cambiare questo utente in {{role}}.",
"workspace.member.manageAccessModal.save": "Salva Modifiche",
"workspace.member.manageAccessModal.success": "Accesso aggiornato",
"workspace.member.manageAccessModal.title": "Gestisci Accesso al Team",
diff --git a/locales/ja-JP/chat.json b/locales/ja-JP/chat.json
index 4f31a9c1d09..bb6a80f358a 100644
--- a/locales/ja-JP/chat.json
+++ b/locales/ja-JP/chat.json
@@ -3,6 +3,7 @@
"active": "アクティブ",
"addAgentFromMarket": "マーケットから追加",
"agent.publishToWorkspace": "ワークスペースに公開",
+ "agent.publishToWorkspaceErrorFixedPrivateDevice": "修正されたデバイスをワークスペースに公開するか、メンバーがデバイスを選択できるようにしてから、このエージェントを公開してください。",
"agent.publishToWorkspaceSuccess": "ワークスペースに公開しました",
"agentBuilder.installPlugin.authRequired": "クラウド MCP を使用するにはログインが必要です",
"agentBuilder.installPlugin.cancel": "キャンセル",
@@ -349,9 +350,10 @@
"heteroAgent.executionTarget.downloadDesktop": "デスクトップアプリを取得",
"heteroAgent.executionTarget.downloadDesktopDesc": "コンピュータにアクセスできるエージェントを実行",
"heteroAgent.executionTarget.downloadDesktopTitle": "デスクトップアプリを取得",
+ "heteroAgent.executionTarget.fixedTip": "このエージェントは、編集者によって固定された実行環境を使用します。編集者に変更を依頼してください。",
"heteroAgent.executionTarget.gateway": "ゲートウェイ",
"heteroAgent.executionTarget.gatewayDesc": "デバイスゲートウェイを通じて実行し、他のクライアントが進捗を追跡可能",
- "heteroAgent.executionTarget.infoTooltip": "ウェブからそのマシンを操作するためにリモートデバイスを選択してください。「このデバイス」はエージェントをローカルで実行し、デスクトップアプリ内でのみ利用可能です。",
+ "heteroAgent.executionTarget.infoTooltip": "このエージェントが実行される場所を選択してください。デバイスはファイルの読み書きやコンピュータの操作が可能です。クラウドサンドボックスは隔離された一時的な環境で実行されます。",
"heteroAgent.executionTarget.loading": "デバイスを読み込み中…",
"heteroAgent.executionTarget.local": "このデバイス",
"heteroAgent.executionTarget.localDesc": "このデスクトップアプリでローカルプロセスとして実行",
@@ -366,7 +368,7 @@
"heteroAgent.executionTarget.sandbox": "クラウドサンドボックス",
"heteroAgent.executionTarget.sandboxDesc": "一時的なクラウドサンドボックスで実行",
"heteroAgent.executionTarget.sandboxUnsupported": "{{name}} は現在、ローカルまたは接続されたデバイスでのみ動作します",
- "heteroAgent.executionTarget.title": "実行デバイス",
+ "heteroAgent.executionTarget.title": "実行環境",
"heteroAgent.executionTarget.unknownDevice": "不明なデバイス",
"heteroAgent.executionTarget.workspaceGroup": "ワークスペース",
"heteroAgent.fullAccess.label": "フルアクセス",
@@ -470,6 +472,8 @@
"input.sendWithCmdEnter": "<key/> を押して送信",
"input.sendWithEnter": "<key/> を押して送信",
"input.stop": "停止",
+ "input.viewOnlyAgent": "このエージェントには閲覧専用アクセス権しかありませんので、メッセージを送信することはできません。作成者またはワークスペースの所有者にアクセスを依頼してください。",
+ "input.viewOnlyGroup": "このグループには閲覧専用アクセス権しかありませんので、メッセージを送信することはできません。作成者またはワークスペースの所有者にアクセスを依頼してください。",
"input.warp": "改行",
"input.warpWithKey": "<key/> を押して改行",
"inputQueue.delete": "削除",
@@ -667,6 +671,8 @@
"pageCopilot.title": "ドキュメントコパイロット",
"pageSelection.lines": "行 {{start}}~{{end}}",
"pageSelection.reference": "選択されたテキスト",
+ "permission.configAccess.agentChatOnly": "このエージェントを設定できるのは「編集可能」権限を持つ共同作業者のみです。チャットに戻されました。",
+ "permission.configAccess.groupChatOnly": "このエージェントグループを設定できるのは「編集可能」権限を持つ共同作業者のみです。チャットに戻されました。",
"pin": "ピン留め",
"pinOff": "ピン留め解除",
"platformAgent.create.available": "利用可能",
diff --git a/locales/ja-JP/common.json b/locales/ja-JP/common.json
index 3a8ea166cc1..4b923f48e5f 100644
--- a/locales/ja-JP/common.json
+++ b/locales/ja-JP/common.json
@@ -212,6 +212,7 @@
"copy": "コピー",
"copyFail": "コピーに失敗しました",
"copySuccess": "コピーしました",
+ "createdAt": "{{time}} に作成されました",
"dataStatistics.messages": "メッセージ",
"dataStatistics.sessions": "アシスタント",
"dataStatistics.today": "今日追加",
@@ -219,6 +220,7 @@
"defaultAgent": "カスタムアシスタント",
"defaultSession": "カスタムアシスタント",
"delete": "削除",
+ "deleteSharedOwnerOnly": "これは他のメンバーの会話を含むため、ワークスペースのオーナーのみが削除できます",
"document": "ドキュメント",
"download": "ダウンロード",
"downloadingUpdate": "{{percent}}% をダウンロード中",
diff --git a/locales/ja-JP/home.json b/locales/ja-JP/home.json
index 1cd7c35a31d..503e37216cb 100644
--- a/locales/ja-JP/home.json
+++ b/locales/ja-JP/home.json
@@ -44,12 +44,16 @@
"homePromoBanner.cta": "今すぐ試す",
"homePromoBanner.dismiss": "閉じる",
"homePromoBanner.label": "{{model}}が利用可能になりました",
+ "inbox.author.scheduled": "予定済み",
"inbox.needsYou.title": "あなたが必要です",
"inbox.news.markAllRead": "すべて既読にする",
"inbox.news.subtitle": "決めることはありません — ただ一目見るだけ",
"inbox.news.title": "デイリーブリーフ",
"inbox.running.title": "{{count}} 件のタスクが実行中",
"inbox.running.title_plural": "{{count}} 件のタスクが実行中",
+ "inbox.scope.mine": "自分のもの",
+ "inbox.scope.onlyMe": "自分だけのもの",
+ "inbox.scope.team": "チーム",
"inbox.unread.followUp": "フォローアップ",
"inbox.unread.followUpPlaceholder": "返信してこのランを続行してください…",
"inbox.unread.title": "未読",
diff --git a/locales/ja-JP/setting.json b/locales/ja-JP/setting.json
index 5f0e5de30f9..9cbbc21b697 100644
--- a/locales/ja-JP/setting.json
+++ b/locales/ja-JP/setting.json
@@ -568,6 +568,23 @@
"notification.push.desc": "モバイルデバイスにプッシュ通知を送信します(LobeHubモバイルアプリが必要です)",
"notification.push.title": "モバイルプッシュ通知",
"notification.title": "通知チャンネル",
+ "permission.accessTag.useOnlyTip": "ここでのメンバー権限は「使用可能」です — 閲覧および使用はできますが、編集はできません。編集権限を希望する場合は、作成者またはワークスペースの所有者に依頼してください。",
+ "permission.accessTag.viewOnlyTip": "ここでのメンバー権限は「閲覧のみ」です — 閲覧はできますが、使用や編集はできません。より多くの権限を希望する場合は、作成者またはワークスペースの所有者に依頼してください。",
+ "permission.generalAccess.editable": "編集可能",
+ "permission.generalAccess.editableDesc": "メンバーは閲覧、使用、編集が可能です",
+ "permission.generalAccess.editableDocumentDesc": "メンバーは閲覧と編集が可能です",
+ "permission.generalAccess.label": "メンバー権限",
+ "permission.generalAccess.trigger": "メンバー: {{level}}",
+ "permission.generalAccess.usable": "使用可能",
+ "permission.generalAccess.usableDesc": "メンバーは閲覧と使用が可能ですが、編集はできません",
+ "permission.generalAccess.viewable": "閲覧可能",
+ "permission.generalAccess.viewableDesc": "メンバーは閲覧のみ可能で、使用や編集はできません",
+ "permission.generalAccess.viewableDocumentDesc": "メンバーは閲覧のみ可能で、編集はできません",
+ "permission.loadFailed": "権限設定の読み込みに失敗しました",
+ "permission.noManagePermission": "権限を変更できるのは作成者またはワークスペースの所有者のみです",
+ "permission.saveNoEditPermission": "このページには閲覧専用アクセス権しかないため、変更は保存されませんでした",
+ "permission.updateError": "権限の更新に失敗しました",
+ "permission.viewOnlySendTip": "閲覧専用アクセス権のため、メッセージを送信することはできません",
"platformAgentConfig.availability.available": "利用可能",
"platformAgentConfig.availability.checking": "確認中...",
"platformAgentConfig.availability.label": "可用性",
@@ -627,6 +644,9 @@
"settingAgent.description.desc": "あなたのアシスタントを簡単に紹介します。キャラクター設定ではありません",
"settingAgent.description.placeholder": "アシスタントの説明を入力してください",
"settingAgent.description.title": "説明",
+ "settingAgent.devicePolicy.noPublicDevice": "このエージェントに固定する前にワークスペースデバイスを公開してください。",
+ "settingAgent.devicePolicy.selectTarget": "環境を選択",
+ "settingAgent.devicePolicy.title": "実行デバイス",
"settingAgent.export.dialogTitle": "エージェントプロファイルをエクスポート",
"settingAgent.export.enabledPlugins": "有効なスキル",
"settingAgent.export.error": "エージェントプロファイルのエクスポートに失敗しました",
@@ -637,6 +657,8 @@
"settingAgent.export.tags": "タグ",
"settingAgent.export.untitled": "無題のエージェント",
"settingAgent.export.untitledFileName": "agent-profile",
+ "settingAgent.modelPolicy.fixedTip": "モデルはエージェントプロファイルで固定されており、チャット中に切り替えることはできません。",
+ "settingAgent.modelPolicy.title": "モデル",
"settingAgent.name.placeholder": "アシスタントの名前を入力してください",
"settingAgent.name.title": "名前",
"settingAgent.prompt.desc": "このエージェントが誰であるか、何を担当しているか、どのように動作し応答するかを定義します。これは、すべての会話における基本的な指示として機能します。",
@@ -644,11 +666,14 @@
"settingAgent.prompt.placeholder": "アシスタントの設定を入力し、「/」でコマンドメニューを開く",
"settingAgent.prompt.title": "アシスタント設定",
"settingAgent.runtimeConfig.title": "モデルとツール",
+ "settingAgent.selectionPolicy.membersCanSwitch": "メンバーは切り替え可能",
+ "settingAgent.selectionPolicy.membersCannotSwitch": "メンバーは切り替え不可",
"settingAgent.submit": "アシスタント情報を更新",
"settingAgent.tag.desc": "アシスタントのタグはコミュニティ内で表示されます",
"settingAgent.tag.placeholder": "タグを入力してください",
"settingAgent.tag.title": "タグ",
"settingAgent.title": "アシスタント情報",
+ "settingAgent.toolsConfig.title": "ツール",
"settingAppearance.animationMode.agile": "敏捷",
"settingAppearance.animationMode.desc": "アプリケーションの操作応答のアニメーション速度を選択します",
"settingAppearance.animationMode.disabled": "オフ",
@@ -2274,6 +2299,7 @@
"workspace.member.manageAccess": "アクセスを管理",
"workspace.member.manageAccessModal.current": "現在",
"workspace.member.manageAccessModal.failed": "アクセスの更新に失敗しました",
+ "workspace.member.manageAccessModal.memberLimitReached": "このワークスペースは{{limit}}人のメンバー制限に達しました。{{role}}にこのユーザーを変更する前に席を追加してください。",
"workspace.member.manageAccessModal.save": "変更を保存",
"workspace.member.manageAccessModal.success": "アクセスが更新されました",
"workspace.member.manageAccessModal.title": "チームアクセスを管理",
diff --git a/locales/ko-KR/chat.json b/locales/ko-KR/chat.json
index bb65cdaa008..24c528f802e 100644
--- a/locales/ko-KR/chat.json
+++ b/locales/ko-KR/chat.json
@@ -3,6 +3,7 @@
"active": "활성",
"addAgentFromMarket": "마켓에서 추가",
"agent.publishToWorkspace": "작업 공간에 게시",
+ "agent.publishToWorkspaceErrorFixedPrivateDevice": "수정된 장치를 워크스페이스에 게시하거나, 멤버들이 장치를 선택하도록 한 후 이 에이전트를 게시하세요.",
"agent.publishToWorkspaceSuccess": "작업 공간에 게시됨",
"agentBuilder.installPlugin.authRequired": "클라우드 MCP를 사용하려면 로그인이 필요합니다",
"agentBuilder.installPlugin.cancel": "취소",
@@ -349,9 +350,10 @@
"heteroAgent.executionTarget.downloadDesktop": "데스크톱 앱 받기",
"heteroAgent.executionTarget.downloadDesktopDesc": "컴퓨터에 액세스할 수 있는 에이전트를 실행하세요",
"heteroAgent.executionTarget.downloadDesktopTitle": "데스크톱 앱 받기",
+ "heteroAgent.executionTarget.fixedTip": "이 에이전트는 편집자가 고정한 실행 환경을 사용합니다. 편집자에게 변경을 요청하세요.",
"heteroAgent.executionTarget.gateway": "게이트웨이",
"heteroAgent.executionTarget.gatewayDesc": "장치 게이트웨이를 통해 실행하여 다른 클라이언트가 진행 상황을 따라갈 수 있도록 합니다",
- "heteroAgent.executionTarget.infoTooltip": "웹에서 해당 기계를 제어할 원격 장치를 선택하세요. \"이 장치\"는 에이전트를 로컬로 실행하며 데스크톱 앱 내부에서만 사용할 수 있습니다.",
+ "heteroAgent.executionTarget.infoTooltip": "이 에이전트가 실행되는 위치를 선택하세요. 장치는 파일을 읽고 쓰거나 컴퓨터를 작동시킬 수 있으며, 클라우드 샌드박스는 격리된 임시 환경에서 실행됩니다.",
"heteroAgent.executionTarget.loading": "장치 로드 중…",
"heteroAgent.executionTarget.local": "이 장치",
"heteroAgent.executionTarget.localDesc": "이 데스크톱 앱에서 로컬 프로세스로 실행",
@@ -366,7 +368,7 @@
"heteroAgent.executionTarget.sandbox": "클라우드 샌드박스",
"heteroAgent.executionTarget.sandboxDesc": "임시 클라우드 샌드박스에서 실행",
"heteroAgent.executionTarget.sandboxUnsupported": "{{name}}은 현재 로컬 또는 연결된 장치에서만 실행됩니다.",
- "heteroAgent.executionTarget.title": "실행 장치",
+ "heteroAgent.executionTarget.title": "실행 환경",
"heteroAgent.executionTarget.unknownDevice": "알 수 없는 장치",
"heteroAgent.executionTarget.workspaceGroup": "워크스페이스",
"heteroAgent.fullAccess.label": "전체 권한",
@@ -470,6 +472,8 @@
"input.sendWithCmdEnter": "<key/> 키를 눌러 전송",
"input.sendWithEnter": "<key/> 키를 눌러 전송",
"input.stop": "중지",
+ "input.viewOnlyAgent": "이 에이전트에 대한 보기 전용 액세스 권한만 있으므로 메시지를 보낼 수 없습니다. 생성자나 워크스페이스 소유자에게 액세스를 요청하세요.",
+ "input.viewOnlyGroup": "이 그룹에 대한 보기 전용 액세스 권한만 있으므로 메시지를 보낼 수 없습니다. 생성자나 워크스페이스 소유자에게 액세스를 요청하세요.",
"input.warp": "줄바꿈",
"input.warpWithKey": "<key/> 키를 눌러 줄 바꿈",
"inputQueue.delete": "삭제",
@@ -667,6 +671,8 @@
"pageCopilot.title": "문서 코파일럿",
"pageSelection.lines": "{{start}}-{{end}}줄",
"pageSelection.reference": "선택한 텍스트",
+ "permission.configAccess.agentChatOnly": "편집 권한이 있는 협업자만 이 에이전트를 구성할 수 있습니다. 채팅으로 되돌아갔습니다.",
+ "permission.configAccess.groupChatOnly": "편집 권한이 있는 협업자만 이 에이전트 그룹을 구성할 수 있습니다. 채팅으로 되돌아갔습니다.",
"pin": "고정",
"pinOff": "고정 해제",
"platformAgent.create.available": "사용 가능",
diff --git a/locales/ko-KR/common.json b/locales/ko-KR/common.json
index 23dcf5ba2b1..ed9f3471df7 100644
--- a/locales/ko-KR/common.json
+++ b/locales/ko-KR/common.json
@@ -212,6 +212,7 @@
"copy": "복사",
"copyFail": "복사 실패",
"copySuccess": "복사되었습니다",
+ "createdAt": "{{time}}에 생성됨",
"dataStatistics.messages": "메시지",
"dataStatistics.sessions": "도우미",
"dataStatistics.today": "오늘 추가됨",
@@ -219,6 +220,7 @@
"defaultAgent": "사용자 정의 도우미",
"defaultSession": "사용자 정의 도우미",
"delete": "삭제",
+ "deleteSharedOwnerOnly": "워크스페이스 소유자만 삭제할 수 있습니다 — 다른 멤버들의 대화가 포함되어 있습니다",
"document": "사용 설명서",
"download": "다운로드",
"downloadingUpdate": "{{percent}}% 다운로드 중",
diff --git a/locales/ko-KR/home.json b/locales/ko-KR/home.json
index ab2324ada33..9b95dce37a4 100644
--- a/locales/ko-KR/home.json
+++ b/locales/ko-KR/home.json
@@ -44,12 +44,16 @@
"homePromoBanner.cta": "지금 시도하기",
"homePromoBanner.dismiss": "닫기",
"homePromoBanner.label": "{{model}}이(가) 이제 사용 가능합니다",
+ "inbox.author.scheduled": "예약됨",
"inbox.needsYou.title": "당신이 필요합니다",
"inbox.news.markAllRead": "모두 읽음으로 표시",
"inbox.news.subtitle": "결정할 필요 없음 — 한눈에 보기",
"inbox.news.title": "일일 요약",
"inbox.running.title": "{{count}}개의 작업 실행 중",
"inbox.running.title_plural": "{{count}}개의 작업 실행 중",
+ "inbox.scope.mine": "내 것",
+ "inbox.scope.onlyMe": "나만의 것",
+ "inbox.scope.team": "팀",
"inbox.unread.followUp": "후속 조치",
"inbox.unread.followUpPlaceholder": "이 실행을 계속하려면 답장하세요…",
"inbox.unread.title": "읽지 않음",
diff --git a/locales/ko-KR/setting.json b/locales/ko-KR/setting.json
index 04cc9aa904b..740341206a0 100644
--- a/locales/ko-KR/setting.json
+++ b/locales/ko-KR/setting.json
@@ -568,6 +568,23 @@
"notification.push.desc": "모바일 장치로 푸시 알림을 보냅니다 (LobeHub 모바일 앱 필요)",
"notification.push.title": "모바일 푸시 알림",
"notification.title": "알림 채널",
+ "permission.accessTag.useOnlyTip": "여기에서 회원 권한은 \"사용 가능\"입니다 — 볼 수 있고 사용할 수 있지만 편집할 수는 없습니다. 편집 권한을 얻으려면 생성자나 워크스페이스 소유자에게 요청하세요.",
+ "permission.accessTag.viewOnlyTip": "여기에서 회원 권한은 \"보기 가능\"입니다 — 볼 수는 있지만 사용할 수 없으며 편집할 수도 없습니다. 더 많은 권한을 얻으려면 생성자나 워크스페이스 소유자에게 요청하세요.",
+ "permission.generalAccess.editable": "편집 가능",
+ "permission.generalAccess.editableDesc": "멤버는 보기, 사용 및 편집이 가능합니다",
+ "permission.generalAccess.editableDocumentDesc": "멤버는 보기 및 편집이 가능합니다",
+ "permission.generalAccess.label": "멤버 권한",
+ "permission.generalAccess.trigger": "멤버: {{level}}",
+ "permission.generalAccess.usable": "사용 가능",
+ "permission.generalAccess.usableDesc": "멤버는 보기 및 사용이 가능하지만 편집은 불가능합니다",
+ "permission.generalAccess.viewable": "보기 가능",
+ "permission.generalAccess.viewableDesc": "멤버는 보기만 가능하며 사용 또는 편집은 불가능합니다",
+ "permission.generalAccess.viewableDocumentDesc": "멤버는 보기만 가능하며 편집은 불가능합니다",
+ "permission.loadFailed": "권한 설정을 불러오는 데 실패했습니다",
+ "permission.noManagePermission": "권한 변경은 생성자나 워크스페이스 소유자만 가능합니다",
+ "permission.saveNoEditPermission": "이 페이지에 대한 보기 전용 권한만 있으므로 변경 사항이 저장되지 않았습니다",
+ "permission.updateError": "권한 업데이트에 실패했습니다",
+ "permission.viewOnlySendTip": "보기 전용 권한만 있어 메시지를 보낼 수 없습니다",
"platformAgentConfig.availability.available": "사용 가능",
"platformAgentConfig.availability.checking": "확인 중...",
"platformAgentConfig.availability.label": "가용성",
@@ -627,6 +644,9 @@
"settingAgent.description.desc": "도우미에 대한 간단한 설명입니다. 역할 프롬프트로 사용되지 않습니다.",
"settingAgent.description.placeholder": "도우미 설명을 입력하세요",
"settingAgent.description.title": "도우미 설명",
+ "settingAgent.devicePolicy.noPublicDevice": "이 에이전트에 고정하기 전에 워크스페이스 장치를 공개하십시오.",
+ "settingAgent.devicePolicy.selectTarget": "환경 선택",
+ "settingAgent.devicePolicy.title": "실행 장치",
"settingAgent.export.dialogTitle": "에이전트 프로필 내보내기",
"settingAgent.export.enabledPlugins": "활성화된 스킬",
"settingAgent.export.error": "에이전트 프로필 내보내기에 실패했습니다",
@@ -637,6 +657,8 @@
"settingAgent.export.tags": "태그",
"settingAgent.export.untitled": "제목 없는 에이전트",
"settingAgent.export.untitledFileName": "agent-profile",
+ "settingAgent.modelPolicy.fixedTip": "에이전트 프로필에서 모델이 고정되어 있으며 채팅 중에는 변경할 수 없습니다.",
+ "settingAgent.modelPolicy.title": "모델",
"settingAgent.name.placeholder": "도우미 이름을 입력하세요",
"settingAgent.name.title": "이름",
"settingAgent.prompt.desc": "이 에이전트가 누구인지, 무엇을 책임지는지, 어떻게 작동하고 응답하는지를 정의합니다. 모든 대화에서 핵심 지침으로 작용합니다.",
@@ -644,11 +666,14 @@
"settingAgent.prompt.placeholder": "도우미 설정을 입력하세요. / 키를 눌러 명령 메뉴를 여세요",
"settingAgent.prompt.title": "도우미 설정",
"settingAgent.runtimeConfig.title": "모델 및 도구",
+ "settingAgent.selectionPolicy.membersCanSwitch": "멤버가 전환할 수 있음",
+ "settingAgent.selectionPolicy.membersCannotSwitch": "멤버가 전환할 수 없음",
"settingAgent.submit": "도우미 정보 업데이트",
"settingAgent.tag.desc": "도우미 태그는 도우미 커뮤니티에 표시됩니다",
"settingAgent.tag.placeholder": "태그를 입력하세요",
"settingAgent.tag.title": "태그",
"settingAgent.title": "도우미 정보",
+ "settingAgent.toolsConfig.title": "도구",
"settingAppearance.animationMode.agile": "민첩",
"settingAppearance.animationMode.desc": "앱의 반응 애니메이션 속도를 선택하세요",
"settingAppearance.animationMode.disabled": "비활성화",
@@ -2274,6 +2299,7 @@
"workspace.member.manageAccess": "액세스 관리",
"workspace.member.manageAccessModal.current": "현재",
"workspace.member.manageAccessModal.failed": "액세스 업데이트에 실패했습니다",
+ "workspace.member.manageAccessModal.memberLimitReached": "이 워크스페이스는 {{limit}}명의 멤버 제한에 도달했습니다. 이 사용자를 {{role}}로 변경하기 전에 좌석을 추가하세요.",
"workspace.member.manageAccessModal.save": "변경 사항 저장",
"workspace.member.manageAccessModal.success": "액세스가 업데이트되었습니다",
"workspace.member.manageAccessModal.title": "팀 액세스 관리",
diff --git a/locales/nl-NL/chat.json b/locales/nl-NL/chat.json
index 0e93466fd8c..754c04c5a08 100644
--- a/locales/nl-NL/chat.json
+++ b/locales/nl-NL/chat.json
@@ -3,6 +3,7 @@
"active": "Actief",
"addAgentFromMarket": "Toevoegen vanuit de Markt",
"agent.publishToWorkspace": "Publiceren naar Werkruimte",
+ "agent.publishToWorkspaceErrorFixedPrivateDevice": "Publiceer het vaste apparaat naar de werkruimte, of laat leden een apparaat kiezen, voordat u deze Agent publiceert.",
"agent.publishToWorkspaceSuccess": "Gepubliceerd naar werkruimte",
"agentBuilder.installPlugin.authRequired": "Cloud MCP vereist inloggen om door te gaan",
"agentBuilder.installPlugin.cancel": "Annuleren",
@@ -349,9 +350,10 @@
"heteroAgent.executionTarget.downloadDesktop": "Download Desktop App",
"heteroAgent.executionTarget.downloadDesktopDesc": "Voer agents uit met toegang tot uw computer",
"heteroAgent.executionTarget.downloadDesktopTitle": "Download de desktop-app",
+ "heteroAgent.executionTarget.fixedTip": "Deze Agent gebruikt een uitvoeringsomgeving die is vastgelegd door de editor. Vraag een editor om deze te wijzigen.",
"heteroAgent.executionTarget.gateway": "Gateway",
"heteroAgent.executionTarget.gatewayDesc": "Voer uit via de apparaatgateway zodat andere clients de voortgang kunnen volgen",
- "heteroAgent.executionTarget.infoTooltip": "Kies een extern apparaat om die machine via het web aan te sturen. \"Dit apparaat\" voert de agent lokaal uit en is alleen beschikbaar in de desktop-app.",
+ "heteroAgent.executionTarget.infoTooltip": "Kies waar deze Agent wordt uitgevoerd. Een apparaat kan bestanden lezen en schrijven of een computer bedienen; Cloud Sandbox draait in een geïsoleerde tijdelijke omgeving.",
"heteroAgent.executionTarget.loading": "Apparaten laden…",
"heteroAgent.executionTarget.local": "Dit apparaat",
"heteroAgent.executionTarget.localDesc": "Voer uit als een lokaal proces in deze desktop-app",
@@ -366,7 +368,7 @@
"heteroAgent.executionTarget.sandbox": "Cloud-sandbox",
"heteroAgent.executionTarget.sandboxDesc": "Voer uit in een tijdelijke cloud-sandbox",
"heteroAgent.executionTarget.sandboxUnsupported": "{{name}} werkt momenteel alleen op een lokaal of verbonden apparaat",
- "heteroAgent.executionTarget.title": "Uitvoerapparaat",
+ "heteroAgent.executionTarget.title": "Uitvoeringsomgeving",
"heteroAgent.executionTarget.unknownDevice": "Onbekend apparaat",
"heteroAgent.executionTarget.workspaceGroup": "Werkruimte",
"heteroAgent.fullAccess.label": "Volledige toegang",
@@ -470,6 +472,8 @@
"input.sendWithCmdEnter": "Druk op <key/> om te verzenden",
"input.sendWithEnter": "Druk op <key/> om te verzenden",
"input.stop": "Stoppen",
+ "input.viewOnlyAgent": "U heeft alleen-lezen toegang tot deze agent, dus berichten kunnen niet worden verzonden. Vraag de maker of een eigenaar van de werkruimte om toegang.",
+ "input.viewOnlyGroup": "U heeft alleen-lezen toegang tot deze groep, dus berichten kunnen niet worden verzonden. Vraag de maker of een eigenaar van de werkruimte om toegang.",
"input.warp": "Nieuwe regel",
"input.warpWithKey": "Druk op <key/> om een regeleinde in te voegen",
"inputQueue.delete": "Verwijderen",
@@ -667,6 +671,8 @@
"pageCopilot.title": "Pagina-agent",
"pageSelection.lines": "Regels {{start}}-{{end}}",
"pageSelection.reference": "Geselecteerde Tekst",
+ "permission.configAccess.agentChatOnly": "Alleen medewerkers met Kan bewerken kunnen deze Agent configureren. U bent teruggebracht naar de chat.",
+ "permission.configAccess.groupChatOnly": "Alleen medewerkers met Kan bewerken kunnen deze Agentgroep configureren. U bent teruggebracht naar de chat.",
"pin": "Vastzetten",
"pinOff": "Losmaken",
"platformAgent.create.available": "Beschikbaar",
diff --git a/locales/nl-NL/common.json b/locales/nl-NL/common.json
index 808b564d93b..47ee7cc2130 100644
--- a/locales/nl-NL/common.json
+++ b/locales/nl-NL/common.json
@@ -212,6 +212,7 @@
"copy": "Kopiëren",
"copyFail": "Kopiëren mislukt",
"copySuccess": "Gekopieerd",
+ "createdAt": "Aangemaakt op {{time}}",
"dataStatistics.messages": "Berichten",
"dataStatistics.sessions": "Agents",
"dataStatistics.today": "Nieuw vandaag",
@@ -219,6 +220,7 @@
"defaultAgent": "Aangepaste Agent",
"defaultSession": "Aangepaste Agent",
"delete": "Verwijderen",
+ "deleteSharedOwnerOnly": "Alleen een werkruimte-eigenaar kan dit verwijderen — het bevat gesprekken van andere leden",
"document": "Gebruikershandleiding",
"download": "Downloaden",
"downloadingUpdate": "Downloaden {{percent}}%",
diff --git a/locales/nl-NL/home.json b/locales/nl-NL/home.json
index 7b2a5c09e17..8ddf4c98620 100644
--- a/locales/nl-NL/home.json
+++ b/locales/nl-NL/home.json
@@ -44,12 +44,16 @@
"homePromoBanner.cta": "Probeer nu",
"homePromoBanner.dismiss": "Sluiten",
"homePromoBanner.label": "{{model}} is nu beschikbaar",
+ "inbox.author.scheduled": "Gepland",
"inbox.needsYou.title": "Heeft je nodig",
"inbox.news.markAllRead": "Alles als gelezen markeren",
"inbox.news.subtitle": "Niets te beslissen — gewoon een blik",
"inbox.news.title": "Dagelijks overzicht",
"inbox.running.title": "{{count}} taak actief",
"inbox.running.title_plural": "{{count}} taken actief",
+ "inbox.scope.mine": "Mijn",
+ "inbox.scope.onlyMe": "Alleen van mij",
+ "inbox.scope.team": "Team",
"inbox.unread.followUp": "Volgen",
"inbox.unread.followUpPlaceholder": "Antwoord om deze sessie voort te zetten…",
"inbox.unread.title": "Ongelezen",
diff --git a/locales/nl-NL/setting.json b/locales/nl-NL/setting.json
index 18001d90a84..b97d01f8d28 100644
--- a/locales/nl-NL/setting.json
+++ b/locales/nl-NL/setting.json
@@ -568,6 +568,23 @@
"notification.push.desc": "Stuur pushmeldingen naar je mobiele apparaten (LobeHub mobiele app vereist)",
"notification.push.title": "Mobiele pushmeldingen",
"notification.title": "Meldingskanalen",
+ "permission.accessTag.useOnlyTip": "Uw lidmaatschapsrechten hier zijn \"Kan gebruiken\" — u kunt het bekijken en gebruiken, maar niet bewerken. Vraag de maker of een werkruimte-eigenaar om bewerkrechten.",
+ "permission.accessTag.viewOnlyTip": "Uw lidmaatschapsrechten hier zijn \"Kan bekijken\" — u kunt het bekijken, maar niet gebruiken of bewerken. Vraag de maker of een werkruimte-eigenaar om meer toegang.",
+ "permission.generalAccess.editable": "Kan bewerken",
+ "permission.generalAccess.editableDesc": "Leden kunnen bekijken, gebruiken en bewerken",
+ "permission.generalAccess.editableDocumentDesc": "Leden kunnen bekijken en bewerken",
+ "permission.generalAccess.label": "Lidmaatschapsrechten",
+ "permission.generalAccess.trigger": "Leden: {{level}}",
+ "permission.generalAccess.usable": "Kan gebruiken",
+ "permission.generalAccess.usableDesc": "Leden kunnen bekijken en gebruiken, maar niet bewerken",
+ "permission.generalAccess.viewable": "Kan bekijken",
+ "permission.generalAccess.viewableDesc": "Leden kunnen bekijken, maar niet gebruiken of bewerken",
+ "permission.generalAccess.viewableDocumentDesc": "Leden kunnen bekijken, maar niet bewerken",
+ "permission.loadFailed": "Het laden van de machtigingsinstellingen is mislukt",
+ "permission.noManagePermission": "Alleen de maker of een werkruimte-eigenaar kan machtigingen wijzigen",
+ "permission.saveNoEditPermission": "U heeft alleen-lezen toegang tot deze pagina, dus uw wijzigingen zijn niet opgeslagen",
+ "permission.updateError": "Het bijwerken van de machtiging is mislukt",
+ "permission.viewOnlySendTip": "U heeft alleen-lezen toegang en kunt geen berichten verzenden",
"platformAgentConfig.availability.available": "Beschikbaar",
"platformAgentConfig.availability.checking": "Controleren...",
"platformAgentConfig.availability.label": "Beschikbaarheid",
@@ -627,6 +644,9 @@
"settingAgent.description.desc": "Een korte introductie van je agent, niet bedoeld als karakterinstelling",
"settingAgent.description.placeholder": "Voer agentbeschrijving in",
"settingAgent.description.title": "Agentbeschrijving",
+ "settingAgent.devicePolicy.noPublicDevice": "Geen openbare apparaten",
+ "settingAgent.devicePolicy.selectTarget": "Selecteer omgeving",
+ "settingAgent.devicePolicy.title": "Uitvoeringsomgeving",
"settingAgent.export.dialogTitle": "Agentprofiel exporteren",
"settingAgent.export.enabledPlugins": "Ingeschakelde vaardigheden",
"settingAgent.export.error": "Het exporteren van het agentprofiel is mislukt",
@@ -637,6 +657,8 @@
"settingAgent.export.tags": "Tags",
"settingAgent.export.untitled": "Naamloze agent",
"settingAgent.export.untitledFileName": "agent-profiel",
+ "settingAgent.modelPolicy.fixedTip": "Het model is vast ingesteld in het Agentprofiel en kan niet worden gewijzigd tijdens het chatten.",
+ "settingAgent.modelPolicy.title": "Model",
"settingAgent.name.placeholder": "Voer agentnaam in",
"settingAgent.name.title": "Naam",
"settingAgent.prompt.desc": "Definieert wie deze agent is, waar hij verantwoordelijk voor is, en hoe hij werkt en reageert. Het dient als een kerninstructie in elk gesprek.",
@@ -644,11 +666,14 @@
"settingAgent.prompt.placeholder": "Voer agentinstellingen in, druk op / om het opdrachtmenu te openen",
"settingAgent.prompt.title": "Agentprofiel",
"settingAgent.runtimeConfig.title": "Model & Tools",
+ "settingAgent.selectionPolicy.membersCanSwitch": "Leden kunnen wisselen",
+ "settingAgent.selectionPolicy.membersCannotSwitch": "Leden kunnen niet wisselen",
"settingAgent.submit": "Agent bijwerken",
"settingAgent.tag.desc": "Agenttags worden weergegeven in de Agent Community",
"settingAgent.tag.placeholder": "Voer tag in",
"settingAgent.tag.title": "Tag",
"settingAgent.title": "Agentinformatie",
+ "settingAgent.toolsConfig.title": "Tools",
"settingAppearance.animationMode.agile": "Snel",
"settingAppearance.animationMode.desc": "Selecteer de animatiesnelheid voor reacties van de applicatie",
"settingAppearance.animationMode.disabled": "Uit",
@@ -2274,6 +2299,7 @@
"workspace.member.manageAccess": "Toegang beheren",
"workspace.member.manageAccessModal.current": "Huidig",
"workspace.member.manageAccessModal.failed": "Toegang bijwerken mislukt",
+ "workspace.member.manageAccessModal.memberLimitReached": "Deze werkruimte heeft de limiet van {{limit}} leden bereikt. Voeg plaatsen toe voordat u deze gebruiker wijzigt naar {{role}}.",
"workspace.member.manageAccessModal.save": "Wijzigingen Opslaan",
"workspace.member.manageAccessModal.success": "Toegang bijgewerkt",
"workspace.member.manageAccessModal.title": "Teamtoegang Beheren",
diff --git a/locales/pl-PL/chat.json b/locales/pl-PL/chat.json
index e6e1a661bea..a9bff8ad1f3 100644
--- a/locales/pl-PL/chat.json
+++ b/locales/pl-PL/chat.json
@@ -3,6 +3,7 @@
"active": "Aktywny",
"addAgentFromMarket": "Dodaj z Rynku",
"agent.publishToWorkspace": "Opublikuj w przestrzeni roboczej",
+ "agent.publishToWorkspaceErrorFixedPrivateDevice": "Opublikuj naprawione urządzenie w przestrzeni roboczej lub pozwól członkom wybrać urządzenie przed opublikowaniem tego Agenta.",
"agent.publishToWorkspaceSuccess": "Opublikowano w przestrzeni roboczej",
"agentBuilder.installPlugin.authRequired": "Aby kontynuować, zaloguj się do Cloud MCP",
"agentBuilder.installPlugin.cancel": "Anuluj",
@@ -349,9 +350,10 @@
"heteroAgent.executionTarget.downloadDesktop": "Pobierz aplikację na komputer",
"heteroAgent.executionTarget.downloadDesktopDesc": "Uruchamiaj agentów z dostępem do swojego komputera",
"heteroAgent.executionTarget.downloadDesktopTitle": "Pobierz aplikację na komputer",
+ "heteroAgent.executionTarget.fixedTip": "Ten Agent korzysta ze środowiska wykonawczego ustalonego przez jego edytora. Poproś edytora o zmianę.",
"heteroAgent.executionTarget.gateway": "Brama",
"heteroAgent.executionTarget.gatewayDesc": "Uruchom przez bramę urządzenia, aby inne klienty mogły śledzić postęp",
- "heteroAgent.executionTarget.infoTooltip": "Wybierz zdalne urządzenie, aby sterować tą maszyną z poziomu sieci. „To urządzenie” uruchamia agenta lokalnie i jest dostępne tylko w aplikacji desktopowej.",
+ "heteroAgent.executionTarget.infoTooltip": "Wybierz, gdzie działa ten Agent. Urządzenie może odczytywać i zapisywać pliki lub obsługiwać komputer; Cloud Sandbox działa w izolowanym tymczasowym środowisku.",
"heteroAgent.executionTarget.loading": "Ładowanie urządzeń…",
"heteroAgent.executionTarget.local": "To urządzenie",
"heteroAgent.executionTarget.localDesc": "Uruchom jako lokalny proces w tej aplikacji desktopowej",
@@ -366,7 +368,7 @@
"heteroAgent.executionTarget.sandbox": "Chmurowa piaskownica",
"heteroAgent.executionTarget.sandboxDesc": "Uruchom w efemerycznej chmurowej piaskownicy",
"heteroAgent.executionTarget.sandboxUnsupported": "{{name}} działa obecnie tylko na urządzeniu lokalnym lub podłączonym",
- "heteroAgent.executionTarget.title": "Urządzenie wykonawcze",
+ "heteroAgent.executionTarget.title": "Środowisko wykonawcze",
"heteroAgent.executionTarget.unknownDevice": "Nieznane urządzenie",
"heteroAgent.executionTarget.workspaceGroup": "Przestrzeń robocza",
"heteroAgent.fullAccess.label": "Pełny dostęp",
@@ -470,6 +472,8 @@
"input.sendWithCmdEnter": "Naciśnij <key/>, aby wysłać",
"input.sendWithEnter": "Naciśnij <key/>, aby wysłać",
"input.stop": "Zatrzymaj",
+ "input.viewOnlyAgent": "Masz dostęp tylko do podglądu tego agenta, więc wiadomości nie mogą być wysyłane. Poproś twórcę lub właściciela przestrzeni roboczej o dostęp.",
+ "input.viewOnlyGroup": "Masz dostęp tylko do podglądu tej grupy, więc wiadomości nie mogą być wysyłane. Poproś twórcę lub właściciela przestrzeni roboczej o dostęp.",
"input.warp": "Nowa linia",
"input.warpWithKey": "Naciśnij <key/>, aby wstawić nową linię",
"inputQueue.delete": "Usuń",
@@ -667,6 +671,8 @@
"pageCopilot.title": "Agent strony",
"pageSelection.lines": "Wiersze {{start}}–{{end}}",
"pageSelection.reference": "Zaznaczony tekst",
+ "permission.configAccess.agentChatOnly": "Tylko współpracownicy z uprawnieniami do edycji mogą konfigurować tego Agenta. Zostałeś przeniesiony z powrotem do czatu.",
+ "permission.configAccess.groupChatOnly": "Tylko współpracownicy z uprawnieniami do edycji mogą konfigurować tę Grupę Agentów. Zostałeś przeniesiony z powrotem do czatu.",
"pin": "Przypnij",
"pinOff": "Odepnij",
"platformAgent.create.available": "Dostępne",
diff --git a/locales/pl-PL/common.json b/locales/pl-PL/common.json
index 9051b64707d..a5f7852e857 100644
--- a/locales/pl-PL/common.json
+++ b/locales/pl-PL/common.json
@@ -212,6 +212,7 @@
"copy": "Kopiuj",
"copyFail": "Nie udało się skopiować",
"copySuccess": "Skopiowano",
+ "createdAt": "Utworzono o {{time}}",
"dataStatistics.messages": "Wiadomości",
"dataStatistics.sessions": "Agenci",
"dataStatistics.today": "Nowe dzisiaj",
@@ -219,6 +220,7 @@
"defaultAgent": "Własny agent",
"defaultSession": "Własny agent",
"delete": "Usuń",
+ "deleteSharedOwnerOnly": "Tylko właściciel przestrzeni roboczej może to usunąć — zawiera rozmowy innych członków",
"document": "Instrukcja obsługi",
"download": "Pobierz",
"downloadingUpdate": "Pobieranie {{percent}}%",
diff --git a/locales/pl-PL/home.json b/locales/pl-PL/home.json
index cbd492cb113..42872c8b0f2 100644
--- a/locales/pl-PL/home.json
+++ b/locales/pl-PL/home.json
@@ -44,12 +44,16 @@
"homePromoBanner.cta": "Wypróbuj teraz",
"homePromoBanner.dismiss": "Zamknij",
"homePromoBanner.label": "{{model}} jest już dostępny",
+ "inbox.author.scheduled": "Zaplanowane",
"inbox.needsYou.title": "Potrzebuje Cię",
"inbox.news.markAllRead": "Oznacz wszystkie jako przeczytane",
"inbox.news.subtitle": "Nic do zdecydowania — tylko rzut oka",
"inbox.news.title": "Codzienny przegląd",
"inbox.running.title": "{{count}} zadanie w toku",
"inbox.running.title_plural": "{{count}} zadań w toku",
+ "inbox.scope.mine": "Moje",
+ "inbox.scope.onlyMe": "Tylko moje",
+ "inbox.scope.team": "Zespół",
"inbox.unread.followUp": "Śledź dalej",
"inbox.unread.followUpPlaceholder": "Odpowiedz, aby kontynuować ten wątek…",
"inbox.unread.title": "Nieprzeczytane",
diff --git a/locales/pl-PL/setting.json b/locales/pl-PL/setting.json
index 84ac641612e..fc20b03ee97 100644
--- a/locales/pl-PL/setting.json
+++ b/locales/pl-PL/setting.json
@@ -568,6 +568,23 @@
"notification.push.desc": "Wysyłaj powiadomienia push na swoje urządzenia mobilne (wymagana aplikacja mobilna LobeHub)",
"notification.push.title": "Mobilne powiadomienia push",
"notification.title": "Kanały powiadomień",
+ "permission.accessTag.useOnlyTip": "Twoje uprawnienie członkowskie tutaj to „Może używać” — możesz to przeglądać i używać, ale nie edytować. Poproś twórcę lub właściciela przestrzeni roboczej o dostęp do edycji.",
+ "permission.accessTag.viewOnlyTip": "Twoje uprawnienie członkowskie tutaj to „Może przeglądać” — możesz to przeglądać, ale nie używać ani edytować. Poproś twórcę lub właściciela przestrzeni roboczej o większy dostęp.",
+ "permission.generalAccess.editable": "Może edytować",
+ "permission.generalAccess.editableDesc": "Członkowie mogą przeglądać, używać i edytować",
+ "permission.generalAccess.editableDocumentDesc": "Członkowie mogą przeglądać i edytować",
+ "permission.generalAccess.label": "Uprawnienia członków",
+ "permission.generalAccess.trigger": "Członkowie: {{level}}",
+ "permission.generalAccess.usable": "Może używać",
+ "permission.generalAccess.usableDesc": "Członkowie mogą przeglądać i używać, ale nie mogą edytować",
+ "permission.generalAccess.viewable": "Może przeglądać",
+ "permission.generalAccess.viewableDesc": "Członkowie mogą przeglądać, ale nie mogą używać ani edytować",
+ "permission.generalAccess.viewableDocumentDesc": "Członkowie mogą przeglądać, ale nie mogą edytować",
+ "permission.loadFailed": "Nie udało się załadować ustawień uprawnień",
+ "permission.noManagePermission": "Tylko twórca lub właściciel przestrzeni roboczej może zmieniać uprawnienia",
+ "permission.saveNoEditPermission": "Masz dostęp tylko do odczytu tej strony, więc Twoje zmiany nie zostały zapisane",
+ "permission.updateError": "Nie udało się zaktualizować uprawnień",
+ "permission.viewOnlySendTip": "Masz dostęp tylko do odczytu i nie możesz wysyłać wiadomości",
"platformAgentConfig.availability.available": "Dostępny",
"platformAgentConfig.availability.checking": "Sprawdzanie...",
"platformAgentConfig.availability.label": "Dostępność",
@@ -627,6 +644,9 @@
"settingAgent.description.desc": "Krótkie wprowadzenie do agenta, nie służy do ustawień charakteru",
"settingAgent.description.placeholder": "Wprowadź opis agenta",
"settingAgent.description.title": "Opis agenta",
+ "settingAgent.devicePolicy.noPublicDevice": "Opublikuj urządzenie przestrzeni roboczej przed jego ustaleniem dla tego Agenta.",
+ "settingAgent.devicePolicy.selectTarget": "Wybierz środowisko",
+ "settingAgent.devicePolicy.title": "Urządzenie wykonawcze",
"settingAgent.export.dialogTitle": "Eksportuj profil agenta",
"settingAgent.export.enabledPlugins": "Włączone umiejętności",
"settingAgent.export.error": "Nie udało się wyeksportować profilu agenta",
@@ -637,6 +657,8 @@
"settingAgent.export.tags": "Tagi",
"settingAgent.export.untitled": "Agent bez nazwy",
"settingAgent.export.untitledFileName": "profil-agenta",
+ "settingAgent.modelPolicy.fixedTip": "Model jest ustalony w profilu agenta i nie można go zmienić podczas rozmowy.",
+ "settingAgent.modelPolicy.title": "Model",
"settingAgent.name.placeholder": "Wprowadź nazwę agenta",
"settingAgent.name.title": "Nazwa",
"settingAgent.prompt.desc": "Określa, kim jest ten agent, za co jest odpowiedzialny, jak działa i odpowiada. Służy jako podstawowa instrukcja w każdej rozmowie.",
@@ -644,11 +666,14 @@
"settingAgent.prompt.placeholder": "Wprowadź ustawienia agenta, naciśnij /, aby otworzyć menu poleceń",
"settingAgent.prompt.title": "Profil agenta",
"settingAgent.runtimeConfig.title": "Model i Narzędzia",
+ "settingAgent.selectionPolicy.membersCanSwitch": "Członkowie mogą zmieniać",
+ "settingAgent.selectionPolicy.membersCannotSwitch": "Członkowie nie mogą zmieniać",
"settingAgent.submit": "Zaktualizuj agenta",
"settingAgent.tag.desc": "Tagi agenta będą widoczne w Społeczności Agentów",
"settingAgent.tag.placeholder": "Wprowadź tag",
"settingAgent.tag.title": "Tag",
"settingAgent.title": "Informacje o agencie",
+ "settingAgent.toolsConfig.title": "Narzędzia",
"settingAppearance.animationMode.agile": "Zwinny",
"settingAppearance.animationMode.desc": "Wybierz prędkość animacji dla reakcji aplikacji",
"settingAppearance.animationMode.disabled": "Wyłączone",
@@ -2274,6 +2299,7 @@
"workspace.member.manageAccess": "Zarządzaj dostępem",
"workspace.member.manageAccessModal.current": "Obecny",
"workspace.member.manageAccessModal.failed": "Nie udało się zaktualizować dostępu",
+ "workspace.member.manageAccessModal.memberLimitReached": "Ten obszar roboczy osiągnął limit {{limit}} członków. Dodaj miejsca, zanim zmienisz tego użytkownika na {{role}}.",
"workspace.member.manageAccessModal.save": "Zapisz zmiany",
"workspace.member.manageAccessModal.success": "Dostęp zaktualizowany",
"workspace.member.manageAccessModal.title": "Zarządzaj dostępem zespołu",
diff --git a/locales/pt-BR/chat.json b/locales/pt-BR/chat.json
index 76d6891206a..e1a21dc9240 100644
--- a/locales/pt-BR/chat.json
+++ b/locales/pt-BR/chat.json
@@ -3,6 +3,7 @@
"active": "Ativo",
"addAgentFromMarket": "Adicionar do Mercado",
"agent.publishToWorkspace": "Publicar no Espaço de Trabalho",
+ "agent.publishToWorkspaceErrorFixedPrivateDevice": "Publique o dispositivo fixo no espaço de trabalho ou deixe os membros escolherem um dispositivo antes de publicar este Agente.",
"agent.publishToWorkspaceSuccess": "Publicado no espaço de trabalho",
"agentBuilder.installPlugin.authRequired": "O Cloud MCP requer login para continuar",
"agentBuilder.installPlugin.cancel": "Cancelar",
@@ -349,9 +350,10 @@
"heteroAgent.executionTarget.downloadDesktop": "Obter Aplicativo para Desktop",
"heteroAgent.executionTarget.downloadDesktopDesc": "Execute agentes com acesso ao seu computador",
"heteroAgent.executionTarget.downloadDesktopTitle": "Obter o aplicativo para desktop",
+ "heteroAgent.executionTarget.fixedTip": "Este Agente utiliza um ambiente de execução fixado pelo seu editor. Solicite ao editor que o altere.",
"heteroAgent.executionTarget.gateway": "Gateway",
"heteroAgent.executionTarget.gatewayDesc": "Execute através do gateway do dispositivo para que outros clientes possam acompanhar o progresso",
- "heteroAgent.executionTarget.infoTooltip": "Escolha um dispositivo remoto para controlar essa máquina pela web. \"Este dispositivo\" executa o agente localmente e está disponível apenas no aplicativo desktop.",
+ "heteroAgent.executionTarget.infoTooltip": "Escolha onde este Agente será executado. Um dispositivo pode ler e escrever arquivos ou operar um computador; o Cloud Sandbox funciona em um ambiente temporário isolado.",
"heteroAgent.executionTarget.loading": "Carregando dispositivos…",
"heteroAgent.executionTarget.local": "Este dispositivo",
"heteroAgent.executionTarget.localDesc": "Executar como um processo local neste aplicativo desktop",
@@ -366,7 +368,7 @@
"heteroAgent.executionTarget.sandbox": "Sandbox na nuvem",
"heteroAgent.executionTarget.sandboxDesc": "Executar em um sandbox efêmero na nuvem",
"heteroAgent.executionTarget.sandboxUnsupported": "{{name}} atualmente funciona apenas em um dispositivo local ou conectado",
- "heteroAgent.executionTarget.title": "Dispositivo de Execução",
+ "heteroAgent.executionTarget.title": "Ambiente de Execução",
"heteroAgent.executionTarget.unknownDevice": "Dispositivo desconhecido",
"heteroAgent.executionTarget.workspaceGroup": "Espaço de Trabalho",
"heteroAgent.fullAccess.label": "Acesso total",
@@ -470,6 +472,8 @@
"input.sendWithCmdEnter": "Pressione <key/> para enviar",
"input.sendWithEnter": "Pressione <key/> para enviar",
"input.stop": "Parar",
+ "input.viewOnlyAgent": "Você tem acesso apenas para visualização deste agente, portanto, mensagens não podem ser enviadas. Solicite acesso ao criador ou ao proprietário do espaço de trabalho.",
+ "input.viewOnlyGroup": "Você tem acesso apenas para visualização deste grupo, portanto, mensagens não podem ser enviadas. Solicite acesso ao criador ou ao proprietário do espaço de trabalho.",
"input.warp": "Nova linha",
"input.warpWithKey": "Pressione <key/> para inserir uma quebra de linha",
"inputQueue.delete": "Excluir",
@@ -667,6 +671,8 @@
"pageCopilot.title": "Agente da Página",
"pageSelection.lines": "Linhas {{start}}-{{end}}",
"pageSelection.reference": "Texto Selecionado",
+ "permission.configAccess.agentChatOnly": "Somente colaboradores com permissão de edição podem configurar este Agente. Você foi retornado ao chat.",
+ "permission.configAccess.groupChatOnly": "Somente colaboradores com permissão de edição podem configurar este Grupo de Agentes. Você foi retornado ao chat.",
"pin": "Fixar",
"pinOff": "Desafixar",
"platformAgent.create.available": "Disponível",
diff --git a/locales/pt-BR/common.json b/locales/pt-BR/common.json
index 5c4a8031b5a..3d4fdee2f86 100644
--- a/locales/pt-BR/common.json
+++ b/locales/pt-BR/common.json
@@ -212,6 +212,7 @@
"copy": "Copiar",
"copyFail": "Falha ao copiar",
"copySuccess": "Copiado",
+ "createdAt": "Criado em {{time}}",
"dataStatistics.messages": "Mensagens",
"dataStatistics.sessions": "Agentes",
"dataStatistics.today": "Novos Hoje",
@@ -219,6 +220,7 @@
"defaultAgent": "Agente Personalizado",
"defaultSession": "Agente Personalizado",
"delete": "Excluir",
+ "deleteSharedOwnerOnly": "Somente o proprietário do espaço de trabalho pode excluir isso — ele contém conversas de outros membros",
"document": "Manual do Usuário",
"download": "Baixar",
"downloadingUpdate": "Baixando {{percent}}%",
diff --git a/locales/pt-BR/home.json b/locales/pt-BR/home.json
index 0ea66479f55..ade1f67b95f 100644
--- a/locales/pt-BR/home.json
+++ b/locales/pt-BR/home.json
@@ -44,12 +44,16 @@
"homePromoBanner.cta": "Experimente agora",
"homePromoBanner.dismiss": "Fechar",
"homePromoBanner.label": "{{model}} já está disponível",
+ "inbox.author.scheduled": "Agendado",
"inbox.needsYou.title": "Precisa de você",
"inbox.news.markAllRead": "Marcar tudo como lido",
"inbox.news.subtitle": "Nada para decidir — apenas um olhar",
"inbox.news.title": "Resumo diário",
"inbox.running.title": "{{count}} tarefa em execução",
"inbox.running.title_plural": "{{count}} tarefas em execução",
+ "inbox.scope.mine": "Meu",
+ "inbox.scope.onlyMe": "Somente meu",
+ "inbox.scope.team": "Equipe",
"inbox.unread.followUp": "Acompanhar",
"inbox.unread.followUpPlaceholder": "Responda para continuar esta conversa…",
"inbox.unread.title": "Não lido",
diff --git a/locales/pt-BR/setting.json b/locales/pt-BR/setting.json
index 67093f8f955..dd191fc9f92 100644
--- a/locales/pt-BR/setting.json
+++ b/locales/pt-BR/setting.json
@@ -568,6 +568,23 @@
"notification.push.desc": "Envie notificações push para seus dispositivos móveis (aplicativo móvel LobeHub necessário)",
"notification.push.title": "Notificações Push Móveis",
"notification.title": "Canais de Notificação",
+ "permission.accessTag.useOnlyTip": "Sua permissão de membro aqui é \"Pode usar\" — você pode visualizar e usar, mas não editar. Peça ao criador ou a um proprietário do espaço de trabalho acesso para edição.",
+ "permission.accessTag.viewOnlyTip": "Sua permissão de membro aqui é \"Pode visualizar\" — você pode visualizar, mas não usar ou editar. Peça ao criador ou a um proprietário do espaço de trabalho mais acesso.",
+ "permission.generalAccess.editable": "Pode editar",
+ "permission.generalAccess.editableDesc": "Os membros podem visualizar, usar e editar",
+ "permission.generalAccess.editableDocumentDesc": "Os membros podem visualizar e editar",
+ "permission.generalAccess.label": "Permissões de Membro",
+ "permission.generalAccess.trigger": "Membros: {{level}}",
+ "permission.generalAccess.usable": "Pode usar",
+ "permission.generalAccess.usableDesc": "Os membros podem visualizar e usar, mas não podem editar",
+ "permission.generalAccess.viewable": "Pode visualizar",
+ "permission.generalAccess.viewableDesc": "Os membros podem visualizar, mas não podem usar ou editar",
+ "permission.generalAccess.viewableDocumentDesc": "Os membros podem visualizar, mas não podem editar",
+ "permission.loadFailed": "Falha ao carregar as configurações de permissão",
+ "permission.noManagePermission": "Somente o criador ou um proprietário do espaço de trabalho pode alterar as permissões",
+ "permission.saveNoEditPermission": "Você tem acesso somente para visualização nesta página, então suas alterações não foram salvas",
+ "permission.updateError": "Falha ao atualizar a permissão",
+ "permission.viewOnlySendTip": "Você tem acesso somente para visualização e não pode enviar mensagens",
"platformAgentConfig.availability.available": "Disponível",
"platformAgentConfig.availability.checking": "Verificando...",
"platformAgentConfig.availability.label": "Disponibilidade",
@@ -627,6 +644,9 @@
"settingAgent.description.desc": "Uma breve introdução ao seu agente, não usada para definir personalidade",
"settingAgent.description.placeholder": "Insira a descrição do agente",
"settingAgent.description.title": "Descrição do Agente",
+ "settingAgent.devicePolicy.noPublicDevice": "Sem dispositivos públicos",
+ "settingAgent.devicePolicy.selectTarget": "Selecione o ambiente",
+ "settingAgent.devicePolicy.title": "Ambiente de execução",
"settingAgent.export.dialogTitle": "Exportar Perfil do Agente",
"settingAgent.export.enabledPlugins": "Habilidades Ativadas",
"settingAgent.export.error": "Falha ao exportar o perfil do agente",
@@ -637,6 +657,8 @@
"settingAgent.export.tags": "Tags",
"settingAgent.export.untitled": "Agente Sem Título",
"settingAgent.export.untitledFileName": "perfil-do-agente",
+ "settingAgent.modelPolicy.fixedTip": "O modelo está fixado no Perfil do Agente e não pode ser alterado durante o chat.",
+ "settingAgent.modelPolicy.title": "Modelo",
"settingAgent.name.placeholder": "Insira o nome do agente",
"settingAgent.name.title": "Nome",
"settingAgent.prompt.desc": "Define quem é este agente, o que ele é responsável por fazer, como funciona e responde. Serve como uma instrução central em cada conversa.",
@@ -644,11 +666,14 @@
"settingAgent.prompt.placeholder": "Insira as configurações do agente, pressione / para abrir o menu de comandos",
"settingAgent.prompt.title": "Perfil do Agente",
"settingAgent.runtimeConfig.title": "Modelo e Ferramentas",
+ "settingAgent.selectionPolicy.membersCanSwitch": "Os membros podem alternar",
+ "settingAgent.selectionPolicy.membersCannotSwitch": "Os membros não podem alternar",
"settingAgent.submit": "Atualizar Agente",
"settingAgent.tag.desc": "As tags do agente serão exibidas na Comunidade de Agentes",
"settingAgent.tag.placeholder": "Insira uma tag",
"settingAgent.tag.title": "Tag",
"settingAgent.title": "Informações do Agente",
+ "settingAgent.toolsConfig.title": "Ferramentas",
"settingAppearance.animationMode.agile": "Ágil",
"settingAppearance.animationMode.desc": "Selecione a velocidade da animação para ações de resposta do aplicativo",
"settingAppearance.animationMode.disabled": "Desativado",
@@ -2274,6 +2299,7 @@
"workspace.member.manageAccess": "Gerenciar acesso",
"workspace.member.manageAccessModal.current": "Atual",
"workspace.member.manageAccessModal.failed": "Falha ao atualizar acesso",
+ "workspace.member.manageAccessModal.memberLimitReached": "Este espaço de trabalho atingiu o limite de {{limit}} membros. Adicione vagas antes de alterar este usuário para {{role}}.",
"workspace.member.manageAccessModal.save": "Salvar Alterações",
"workspace.member.manageAccessModal.success": "Acesso atualizado",
"workspace.member.manageAccessModal.title": "Gerenciar Acesso da Equipe",
diff --git a/locales/ru-RU/chat.json b/locales/ru-RU/chat.json
index 66287216dc8..6bbb189712f 100644
--- a/locales/ru-RU/chat.json
+++ b/locales/ru-RU/chat.json
@@ -3,6 +3,7 @@
"active": "Активен",
"addAgentFromMarket": "Добавить из Маркета",
"agent.publishToWorkspace": "Опубликовать в рабочем пространстве",
+ "agent.publishToWorkspaceErrorFixedPrivateDevice": "Опубликуйте исправленное устройство в рабочую область или позвольте участникам выбрать устройство перед публикацией этого агента.",
"agent.publishToWorkspaceSuccess": "Опубликовано в рабочем пространстве",
"agentBuilder.installPlugin.authRequired": "Для продолжения требуется вход в Cloud MCP",
"agentBuilder.installPlugin.cancel": "Отмена",
@@ -349,9 +350,10 @@
"heteroAgent.executionTarget.downloadDesktop": "Скачать приложение для компьютера",
"heteroAgent.executionTarget.downloadDesktopDesc": "Запускайте агентов с доступом к вашему компьютеру",
"heteroAgent.executionTarget.downloadDesktopTitle": "Скачать приложение для компьютера",
+ "heteroAgent.executionTarget.fixedTip": "Этот агент использует среду выполнения, установленную его редактором. Попросите редактора изменить её.",
"heteroAgent.executionTarget.gateway": "Шлюз",
"heteroAgent.executionTarget.gatewayDesc": "Запуск через шлюз устройства, чтобы другие клиенты могли следить за прогрессом",
- "heteroAgent.executionTarget.infoTooltip": "Выберите удаленное устройство, чтобы управлять этой машиной через веб. \"Это устройство\" запускает агент локально и доступно только в настольном приложении.",
+ "heteroAgent.executionTarget.infoTooltip": "Выберите, где будет работать этот агент. Устройство может читать и записывать файлы или управлять компьютером; Cloud Sandbox работает в изолированной временной среде.",
"heteroAgent.executionTarget.loading": "Загрузка устройств…",
"heteroAgent.executionTarget.local": "Это устройство",
"heteroAgent.executionTarget.localDesc": "Запуск как локальный процесс в этом настольном приложении",
@@ -366,7 +368,7 @@
"heteroAgent.executionTarget.sandbox": "Облачная песочница",
"heteroAgent.executionTarget.sandboxDesc": "Запуск в временной облачной песочнице",
"heteroAgent.executionTarget.sandboxUnsupported": "{{name}} в настоящее время работает только на локальном или подключенном устройстве",
- "heteroAgent.executionTarget.title": "Устройство выполнения",
+ "heteroAgent.executionTarget.title": "Среда выполнения",
"heteroAgent.executionTarget.unknownDevice": "Неизвестное устройство",
"heteroAgent.executionTarget.workspaceGroup": "Рабочее пространство",
"heteroAgent.fullAccess.label": "Полный доступ",
@@ -470,6 +472,8 @@
"input.sendWithCmdEnter": "Нажмите <key/>, чтобы отправить",
"input.sendWithEnter": "Нажмите <key/>, чтобы отправить",
"input.stop": "Остановить",
+ "input.viewOnlyAgent": "У вас есть только доступ для просмотра этого агента, поэтому сообщения отправить нельзя. Попросите создателя или владельца рабочей области предоставить доступ.",
+ "input.viewOnlyGroup": "У вас есть только доступ для просмотра этой группы, поэтому сообщения отправить нельзя. Попросите создателя или владельца рабочей области предоставить доступ.",
"input.warp": "Новая строка",
"input.warpWithKey": "Нажмите <key/>, чтобы вставить перенос строки",
"inputQueue.delete": "Удалить",
@@ -667,6 +671,8 @@
"pageCopilot.title": "Агент страницы",
"pageSelection.lines": "Строки {{start}}–{{end}}",
"pageSelection.reference": "Выделенный текст",
+ "permission.configAccess.agentChatOnly": "Только сотрудники с правами «Может редактировать» могут настраивать этого агента. Вы были возвращены в чат.",
+ "permission.configAccess.groupChatOnly": "Только сотрудники с правами «Может редактировать» могут настраивать эту группу агентов. Вы были возвращены в чат.",
"pin": "Закрепить",
"pinOff": "Открепить",
"platformAgent.create.available": "Доступно",
diff --git a/locales/ru-RU/common.json b/locales/ru-RU/common.json
index 5ee8ba55c62..9a4042b1693 100644
--- a/locales/ru-RU/common.json
+++ b/locales/ru-RU/common.json
@@ -212,6 +212,7 @@
"copy": "Копировать",
"copyFail": "Не удалось скопировать",
"copySuccess": "Скопировано",
+ "createdAt": "Создано в {{time}}",
"dataStatistics.messages": "Сообщения",
"dataStatistics.sessions": "Агенты",
"dataStatistics.today": "Новые за сегодня",
@@ -219,6 +220,7 @@
"defaultAgent": "Пользовательский агент",
"defaultSession": "Пользовательский агент",
"delete": "Удалить",
+ "deleteSharedOwnerOnly": "Только владелец рабочего пространства может удалить это — здесь находятся разговоры других участников",
"document": "Руководство пользователя",
"download": "Скачать",
"downloadingUpdate": "Загрузка {{percent}}%",
diff --git a/locales/ru-RU/home.json b/locales/ru-RU/home.json
index 0ecfd3bd58d..ec308070723 100644
--- a/locales/ru-RU/home.json
+++ b/locales/ru-RU/home.json
@@ -44,12 +44,16 @@
"homePromoBanner.cta": "Попробовать сейчас",
"homePromoBanner.dismiss": "Закрыть",
"homePromoBanner.label": "{{model}} теперь доступен",
+ "inbox.author.scheduled": "Запланировано",
"inbox.needsYou.title": "Нуждается в вас",
"inbox.news.markAllRead": "Отметить все как прочитанные",
"inbox.news.subtitle": "Ничего решать — просто взгляд",
"inbox.news.title": "Ежедневная сводка",
"inbox.running.title": "{{count}} задача выполняется",
"inbox.running.title_plural": "{{count}} задач выполняется",
+ "inbox.scope.mine": "Мои",
+ "inbox.scope.onlyMe": "Только мои",
+ "inbox.scope.team": "Команда",
"inbox.unread.followUp": "Следить",
"inbox.unread.followUpPlaceholder": "Ответьте, чтобы продолжить этот разговор…",
"inbox.unread.title": "Непрочитанные",
diff --git a/locales/ru-RU/setting.json b/locales/ru-RU/setting.json
index 0c0a2e0f893..163299a9c3f 100644
--- a/locales/ru-RU/setting.json
+++ b/locales/ru-RU/setting.json
@@ -568,6 +568,23 @@
"notification.push.desc": "Отправляйте push-уведомления на свои мобильные устройства (требуется мобильное приложение LobeHub)",
"notification.push.title": "Мобильные push-уведомления",
"notification.title": "Каналы уведомлений",
+ "permission.accessTag.useOnlyTip": "Ваше разрешение участника здесь — «Может использовать» — вы можете просматривать и использовать, но не редактировать. Попросите создателя или владельца рабочего пространства предоставить доступ на редактирование.",
+ "permission.accessTag.viewOnlyTip": "Ваше разрешение участника здесь — «Может просматривать» — вы можете просматривать, но не использовать или редактировать. Попросите создателя или владельца рабочего пространства предоставить больше доступа.",
+ "permission.generalAccess.editable": "Может редактировать",
+ "permission.generalAccess.editableDesc": "Участники могут просматривать, использовать и редактировать",
+ "permission.generalAccess.editableDocumentDesc": "Участники могут просматривать и редактировать",
+ "permission.generalAccess.label": "Права участников",
+ "permission.generalAccess.trigger": "Участники: {{level}}",
+ "permission.generalAccess.usable": "Может использовать",
+ "permission.generalAccess.usableDesc": "Участники могут просматривать и использовать, но не редактировать",
+ "permission.generalAccess.viewable": "Может просматривать",
+ "permission.generalAccess.viewableDesc": "Участники могут просматривать, но не использовать и не редактировать",
+ "permission.generalAccess.viewableDocumentDesc": "Участники могут просматривать, но не редактировать",
+ "permission.loadFailed": "Не удалось загрузить настройки разрешений",
+ "permission.noManagePermission": "Только создатель или владелец рабочего пространства может изменять разрешения",
+ "permission.saveNoEditPermission": "У вас есть доступ только для просмотра этой страницы, поэтому ваши изменения не были сохранены",
+ "permission.updateError": "Не удалось обновить разрешение",
+ "permission.viewOnlySendTip": "У вас есть доступ только для просмотра и вы не можете отправлять сообщения",
"platformAgentConfig.availability.available": "Доступно",
"platformAgentConfig.availability.checking": "Проверка...",
"platformAgentConfig.availability.label": "Доступность",
@@ -627,6 +644,9 @@
"settingAgent.description.desc": "Краткое описание агента, не для настройки характера",
"settingAgent.description.placeholder": "Введите описание агента",
"settingAgent.description.title": "Описание агента",
+ "settingAgent.devicePolicy.noPublicDevice": "Опубликуйте устройство рабочего пространства перед его закреплением за этим агентом.",
+ "settingAgent.devicePolicy.selectTarget": "Выберите среду",
+ "settingAgent.devicePolicy.title": "Устройство выполнения",
"settingAgent.export.dialogTitle": "Экспорт профиля агента",
"settingAgent.export.enabledPlugins": "Включенные навыки",
"settingAgent.export.error": "Не удалось экспортировать профиль агента",
@@ -637,6 +657,8 @@
"settingAgent.export.tags": "Теги",
"settingAgent.export.untitled": "Безымянный агент",
"settingAgent.export.untitledFileName": "профиль-агента",
+ "settingAgent.modelPolicy.fixedTip": "Модель закреплена в профиле агента и не может быть изменена во время общения.",
+ "settingAgent.modelPolicy.title": "Модель",
"settingAgent.name.placeholder": "Введите имя агента",
"settingAgent.name.title": "Имя",
"settingAgent.prompt.desc": "Определяет, кто этот агент, за что он отвечает, как он работает и реагирует. Это служит основным инструктажем в каждом разговоре.",
@@ -644,11 +666,14 @@
"settingAgent.prompt.placeholder": "Введите настройки агента, нажмите / для открытия меню команд",
"settingAgent.prompt.title": "Профиль агента",
"settingAgent.runtimeConfig.title": "Модель и инструменты",
+ "settingAgent.selectionPolicy.membersCanSwitch": "Участники могут переключаться",
+ "settingAgent.selectionPolicy.membersCannotSwitch": "Участники не могут переключаться",
"settingAgent.submit": "Обновить агента",
"settingAgent.tag.desc": "Теги агента будут отображаться в сообществе агентов",
"settingAgent.tag.placeholder": "Введите тег",
"settingAgent.tag.title": "Тег",
"settingAgent.title": "Информация об агенте",
+ "settingAgent.toolsConfig.title": "Инструменты",
"settingAppearance.animationMode.agile": "Быстрый",
"settingAppearance.animationMode.desc": "Выберите скорость анимации для отклика приложения",
"settingAppearance.animationMode.disabled": "Отключено",
@@ -2274,6 +2299,7 @@
"workspace.member.manageAccess": "Управление доступом",
"workspace.member.manageAccessModal.current": "Текущий",
"workspace.member.manageAccessModal.failed": "Не удалось обновить доступ",
+ "workspace.member.manageAccessModal.memberLimitReached": "Этот рабочий пространство достигло лимита в {{limit}} участников. Добавьте места, прежде чем изменить роль этого пользователя на {{role}}.",
"workspace.member.manageAccessModal.save": "Сохранить изменения",
"workspace.member.manageAccessModal.success": "Доступ обновлен",
"workspace.member.manageAccessModal.title": "Управление доступом команды",
diff --git a/locales/tr-TR/chat.json b/locales/tr-TR/chat.json
index b66a6525a85..dcf2dcb4268 100644
--- a/locales/tr-TR/chat.json
+++ b/locales/tr-TR/chat.json
@@ -3,6 +3,7 @@
"active": "Aktif",
"addAgentFromMarket": "Pazardan Ekle",
"agent.publishToWorkspace": "Çalışma Alanına Yayınla",
+ "agent.publishToWorkspaceErrorFixedPrivateDevice": "Düzeltilmiş cihazı çalışma alanına yayınlayın veya üyelerin bir cihaz seçmesine izin verin, ardından bu Ajanı yayınlayın.",
"agent.publishToWorkspaceSuccess": "Çalışma alanına yayınlandı",
"agentBuilder.installPlugin.authRequired": "Cloud MCP devam etmek için oturum açmanızı gerektirir",
"agentBuilder.installPlugin.cancel": "İptal",
@@ -349,9 +350,10 @@
"heteroAgent.executionTarget.downloadDesktop": "Masaüstü Uygulamasını Edinin",
"heteroAgent.executionTarget.downloadDesktopDesc": "Bilgisayarınıza erişimi olan ajanları çalıştırın",
"heteroAgent.executionTarget.downloadDesktopTitle": "Masaüstü uygulamasını edinin",
+ "heteroAgent.executionTarget.fixedTip": "Bu Ajan, editörü tarafından sabitlenmiş bir çalışma ortamı kullanıyor. Bir editörden bunu değiştirmesini isteyin.",
"heteroAgent.executionTarget.gateway": "Ağ Geçidi",
"heteroAgent.executionTarget.gatewayDesc": "Diğer istemcilerin ilerlemeyi takip edebilmesi için cihaz ağ geçidi üzerinden çalıştırın",
- "heteroAgent.executionTarget.infoTooltip": "Web üzerinden bu makineyi çalıştırmak için bir uzak cihaz seçin. \"Bu cihaz\" ajanı yerel olarak çalıştırır ve yalnızca masaüstü uygulamasında kullanılabilir.",
+ "heteroAgent.executionTarget.infoTooltip": "Bu Ajanın nerede çalışacağını seçin. Bir cihaz dosya okuyabilir ve yazabilir veya bir bilgisayarı çalıştırabilir; Bulut Sandbox izole edilmiş geçici bir ortamda çalışır.",
"heteroAgent.executionTarget.loading": "Cihazlar yükleniyor…",
"heteroAgent.executionTarget.local": "Bu cihaz",
"heteroAgent.executionTarget.localDesc": "Bu masaüstü uygulamasında yerel bir işlem olarak çalıştır",
@@ -366,7 +368,7 @@
"heteroAgent.executionTarget.sandbox": "Bulut sandbox",
"heteroAgent.executionTarget.sandboxDesc": "Geçici bir bulut sandbox'ında çalıştır",
"heteroAgent.executionTarget.sandboxUnsupported": "{{name}} şu anda yalnızca yerel veya bağlı bir cihazda çalışıyor",
- "heteroAgent.executionTarget.title": "Çalıştırma Cihazı",
+ "heteroAgent.executionTarget.title": "Çalışma Ortamı",
"heteroAgent.executionTarget.unknownDevice": "Bilinmeyen cihaz",
"heteroAgent.executionTarget.workspaceGroup": "Çalışma Alanı",
"heteroAgent.fullAccess.label": "Tam erişim",
@@ -470,6 +472,8 @@
"input.sendWithCmdEnter": "Göndermek için <key/> tuşuna basın",
"input.sendWithEnter": "Göndermek için <key/> tuşuna basın",
"input.stop": "Durdur",
+ "input.viewOnlyAgent": "Bu ajana yalnızca görüntüleme erişiminiz var, bu nedenle mesajlar gönderilemez. Yaratıcıdan veya bir çalışma alanı sahibinden erişim isteyin.",
+ "input.viewOnlyGroup": "Bu gruba yalnızca görüntüleme erişiminiz var, bu nedenle mesajlar gönderilemez. Yaratıcıdan veya bir çalışma alanı sahibinden erişim isteyin.",
"input.warp": "Yeni Satır",
"input.warpWithKey": "Satır sonu eklemek için <key/> tuşuna basın",
"inputQueue.delete": "Sil",
@@ -667,6 +671,8 @@
"pageCopilot.title": "Sayfa Ajanı",
"pageSelection.lines": "{{start}}-{{end}} satırları",
"pageSelection.reference": "Seçilen Metin",
+ "permission.configAccess.agentChatOnly": "Yalnızca Düzenleme yapabilir iznine sahip işbirlikçiler bu Ajanı yapılandırabilir. Sohbete geri döndünüz.",
+ "permission.configAccess.groupChatOnly": "Yalnızca Düzenleme yapabilir iznine sahip işbirlikçiler bu Ajan Grubunu yapılandırabilir. Sohbete geri döndünüz.",
"pin": "Sabitle",
"pinOff": "Sabitlemeyi Kaldır",
"platformAgent.create.available": "Mevcut",
diff --git a/locales/tr-TR/common.json b/locales/tr-TR/common.json
index 51a9078b46c..47c1fc46f41 100644
--- a/locales/tr-TR/common.json
+++ b/locales/tr-TR/common.json
@@ -212,6 +212,7 @@
"copy": "Kopyala",
"copyFail": "Kopyalama başarısız",
"copySuccess": "Kopyalandı",
+ "createdAt": "{{time}} tarihinde oluşturuldu",
"dataStatistics.messages": "Mesajlar",
"dataStatistics.sessions": "Ajanlar",
"dataStatistics.today": "Bugünün Yenileri",
@@ -219,6 +220,7 @@
"defaultAgent": "Özel Ajan",
"defaultSession": "Özel Ajan",
"delete": "Sil",
+ "deleteSharedOwnerOnly": "Bunu yalnızca bir çalışma alanı sahibi silebilir — diğer üyelerin konuşmalarını içerir",
"document": "Kullanıcı Kılavuzu",
"download": "İndir",
"downloadingUpdate": "{{percent}}% İndiriliyor",
diff --git a/locales/tr-TR/home.json b/locales/tr-TR/home.json
index 2c7f262aec9..f088b26d6c2 100644
--- a/locales/tr-TR/home.json
+++ b/locales/tr-TR/home.json
@@ -44,12 +44,16 @@
"homePromoBanner.cta": "Şimdi deneyin",
"homePromoBanner.dismiss": "Kapat",
"homePromoBanner.label": "{{model}} artık mevcut",
+ "inbox.author.scheduled": "Planlanmış",
"inbox.needsYou.title": "Sana ihtiyaç var",
"inbox.news.markAllRead": "Tümünü okundu olarak işaretle",
"inbox.news.subtitle": "Karar vermeye gerek yok — sadece bir bakış",
"inbox.news.title": "Günlük özet",
"inbox.running.title": "{{count}} görev çalışıyor",
"inbox.running.title_plural": "{{count}} görev çalışıyor",
+ "inbox.scope.mine": "Benim",
+ "inbox.scope.onlyMe": "Sadece benim",
+ "inbox.scope.team": "Takım",
"inbox.unread.followUp": "Takip et",
"inbox.unread.followUpPlaceholder": "Bu çalışmaya devam etmek için yanıt verin…",
"inbox.unread.title": "Okunmamış",
diff --git a/locales/tr-TR/setting.json b/locales/tr-TR/setting.json
index ad3734045dc..7c417cc77ae 100644
--- a/locales/tr-TR/setting.json
+++ b/locales/tr-TR/setting.json
@@ -568,6 +568,23 @@
"notification.push.desc": "Mobil cihazlarınıza anlık bildirimler gönderin (LobeHub mobil uygulaması gereklidir)",
"notification.push.title": "Mobil Anlık Bildirimler",
"notification.title": "Bildirim Kanalları",
+ "permission.accessTag.useOnlyTip": "Buradaki üye izniniz \"Kullanabilir\" — görüntüleyebilir ve kullanabilirsiniz, ancak düzenleyemezsiniz. Düzenleme erişimi için oluşturucuya veya bir çalışma alanı sahibine başvurun.",
+ "permission.accessTag.viewOnlyTip": "Buradaki üye izniniz \"Görüntüleyebilir\" — görüntüleyebilirsiniz, ancak kullanamaz veya düzenleyemezsiniz. Daha fazla erişim için oluşturucuya veya bir çalışma alanı sahibine başvurun.",
+ "permission.generalAccess.editable": "Düzenleyebilir",
+ "permission.generalAccess.editableDesc": "Üyeler görüntüleyebilir, kullanabilir ve düzenleyebilir",
+ "permission.generalAccess.editableDocumentDesc": "Üyeler görüntüleyebilir ve düzenleyebilir",
+ "permission.generalAccess.label": "Üye İzinleri",
+ "permission.generalAccess.trigger": "Üyeler: {{level}}",
+ "permission.generalAccess.usable": "Kullanabilir",
+ "permission.generalAccess.usableDesc": "Üyeler görüntüleyebilir ve kullanabilir, ancak düzenleyemez",
+ "permission.generalAccess.viewable": "Görüntüleyebilir",
+ "permission.generalAccess.viewableDesc": "Üyeler görüntüleyebilir, ancak kullanamaz veya düzenleyemez",
+ "permission.generalAccess.viewableDocumentDesc": "Üyeler görüntüleyebilir, ancak düzenleyemez",
+ "permission.loadFailed": "İzin ayarları yüklenemedi",
+ "permission.noManagePermission": "Yalnızca oluşturucu veya bir çalışma alanı sahibi izinleri değiştirebilir",
+ "permission.saveNoEditPermission": "Bu sayfaya yalnızca görüntüleme erişiminiz var, bu nedenle değişiklikleriniz kaydedilmedi",
+ "permission.updateError": "İzin güncellenemedi",
+ "permission.viewOnlySendTip": "Yalnızca görüntüleme erişiminiz var ve mesaj gönderemezsiniz",
"platformAgentConfig.availability.available": "Mevcut",
"platformAgentConfig.availability.checking": "Kontrol ediliyor...",
"platformAgentConfig.availability.label": "Kullanılabilirlik",
@@ -627,6 +644,9 @@
"settingAgent.description.desc": "Temsilciniz hakkında kısa bir tanıtım, karakter ayarı için değildir",
"settingAgent.description.placeholder": "Temsilci açıklaması girin",
"settingAgent.description.title": "Temsilci Açıklaması",
+ "settingAgent.devicePolicy.noPublicDevice": "Halka açık cihaz yok",
+ "settingAgent.devicePolicy.selectTarget": "Ortam seçin",
+ "settingAgent.devicePolicy.title": "Çalışma ortamı",
"settingAgent.export.dialogTitle": "Ajan Profilini Dışa Aktar",
"settingAgent.export.enabledPlugins": "Etkin Beceriler",
"settingAgent.export.error": "Ajan profili dışa aktarılamadı",
@@ -637,6 +657,8 @@
"settingAgent.export.tags": "Etiketler",
"settingAgent.export.untitled": "Başlıksız Ajan",
"settingAgent.export.untitledFileName": "ajan-profili",
+ "settingAgent.modelPolicy.fixedTip": "Model, Temsilci Profilinde sabitlenmiştir ve sohbet sırasında değiştirilemez.",
+ "settingAgent.modelPolicy.title": "Model",
"settingAgent.name.placeholder": "Temsilci adı girin",
"settingAgent.name.title": "Ad",
"settingAgent.prompt.desc": "Bu ajanı tanımlar, neyle sorumlu olduğunu, nasıl çalıştığını ve nasıl yanıt verdiğini açıklar. Her konuşmada temel bir talimat olarak hizmet eder.",
@@ -644,11 +666,14 @@
"settingAgent.prompt.placeholder": "Temsilci ayarlarını girin, komut menüsünü açmak için / tuşuna basın",
"settingAgent.prompt.title": "Temsilci Profili",
"settingAgent.runtimeConfig.title": "Model ve Araçlar",
+ "settingAgent.selectionPolicy.membersCanSwitch": "Üyeler değiştirebilir",
+ "settingAgent.selectionPolicy.membersCannotSwitch": "Üyeler değiştiremez",
"settingAgent.submit": "Temsilciyi Güncelle",
"settingAgent.tag.desc": "Temsilci etiketleri, Temsilci Topluluğunda görüntülenecektir",
"settingAgent.tag.placeholder": "Etiket girin",
"settingAgent.tag.title": "Etiket",
"settingAgent.title": "Temsilci Bilgisi",
+ "settingAgent.toolsConfig.title": "Araçlar",
"settingAppearance.animationMode.agile": "Çevik",
"settingAppearance.animationMode.desc": "Uygulama yanıt animasyonları için hız seçin",
"settingAppearance.animationMode.disabled": "Kapalı",
@@ -2274,6 +2299,7 @@
"workspace.member.manageAccess": "Erişimi yönet",
"workspace.member.manageAccessModal.current": "Mevcut",
"workspace.member.manageAccessModal.failed": "Erişim güncellenemedi",
+ "workspace.member.manageAccessModal.memberLimitReached": "Bu çalışma alanı {{limit}} üye sınırına ulaşmıştır. Bu kullanıcıyı {{role}} olarak değiştirmeden önce koltuk ekleyin.",
"workspace.member.manageAccessModal.save": "Değişiklikleri Kaydet",
"workspace.member.manageAccessModal.success": "Erişim güncellendi",
"workspace.member.manageAccessModal.title": "Ekip Erişimini Yönet",
diff --git a/locales/vi-VN/chat.json b/locales/vi-VN/chat.json
index 6544fc95e8f..3f388370805 100644
--- a/locales/vi-VN/chat.json
+++ b/locales/vi-VN/chat.json
@@ -3,6 +3,7 @@
"active": "Đang hoạt động",
"addAgentFromMarket": "Thêm từ Thị trường",
"agent.publishToWorkspace": "Xuất bản vào Không gian làm việc",
+ "agent.publishToWorkspaceErrorFixedPrivateDevice": "Xuất bản thiết bị đã cố định vào không gian làm việc, hoặc để các thành viên chọn thiết bị, trước khi xuất bản Agent này.",
"agent.publishToWorkspaceSuccess": "Đã xuất bản vào không gian làm việc",
"agentBuilder.installPlugin.authRequired": "Cloud MCP yêu cầu đăng nhập để tiếp tục",
"agentBuilder.installPlugin.cancel": "Hủy",
@@ -349,9 +350,10 @@
"heteroAgent.executionTarget.downloadDesktop": "Tải ứng dụng máy tính",
"heteroAgent.executionTarget.downloadDesktopDesc": "Chạy các tác nhân với quyền truy cập vào máy tính của bạn",
"heteroAgent.executionTarget.downloadDesktopTitle": "Tải ứng dụng máy tính",
+ "heteroAgent.executionTarget.fixedTip": "Agent này sử dụng môi trường thực thi đã được cố định bởi người chỉnh sửa. Hãy yêu cầu người chỉnh sửa thay đổi nó.",
"heteroAgent.executionTarget.gateway": "Cổng",
"heteroAgent.executionTarget.gatewayDesc": "Chạy qua cổng thiết bị để các khách hàng khác có thể theo dõi tiến trình",
- "heteroAgent.executionTarget.infoTooltip": "Chọn một thiết bị từ xa để điều khiển máy đó từ web. \"Thiết bị này\" chạy tác nhân cục bộ và chỉ khả dụng trong ứng dụng máy tính để bàn.",
+ "heteroAgent.executionTarget.infoTooltip": "Chọn nơi Agent này chạy. Một thiết bị có thể đọc và ghi tệp hoặc vận hành máy tính; Cloud Sandbox chạy trong môi trường tạm thời cách ly.",
"heteroAgent.executionTarget.loading": "Đang tải thiết bị…",
"heteroAgent.executionTarget.local": "Thiết bị này",
"heteroAgent.executionTarget.localDesc": "Chạy như một quy trình cục bộ trên ứng dụng máy tính để bàn này",
@@ -366,7 +368,7 @@
"heteroAgent.executionTarget.sandbox": "Hộp cát đám mây",
"heteroAgent.executionTarget.sandboxDesc": "Chạy trong hộp cát đám mây tạm thời",
"heteroAgent.executionTarget.sandboxUnsupported": "{{name}} hiện chỉ chạy trên thiết bị cục bộ hoặc được kết nối",
- "heteroAgent.executionTarget.title": "Thiết bị thực thi",
+ "heteroAgent.executionTarget.title": "Môi trường Thực thi",
"heteroAgent.executionTarget.unknownDevice": "Thiết bị không xác định",
"heteroAgent.executionTarget.workspaceGroup": "Không gian làm việc",
"heteroAgent.fullAccess.label": "Toàn quyền truy cập",
@@ -470,6 +472,8 @@
"input.sendWithCmdEnter": "Nhấn <key/> để gửi",
"input.sendWithEnter": "Nhấn <key/> để gửi",
"input.stop": "Dừng",
+ "input.viewOnlyAgent": "Bạn chỉ có quyền xem đối với agent này, vì vậy không thể gửi tin nhắn. Hãy yêu cầu người tạo hoặc chủ sở hữu không gian làm việc cấp quyền truy cập.",
+ "input.viewOnlyGroup": "Bạn chỉ có quyền xem đối với nhóm này, vì vậy không thể gửi tin nhắn. Hãy yêu cầu người tạo hoặc chủ sở hữu không gian làm việc cấp quyền truy cập.",
"input.warp": "Dòng mới",
"input.warpWithKey": "Nhấn <key/> để xuống dòng",
"inputQueue.delete": "Xóa",
@@ -667,6 +671,8 @@
"pageCopilot.title": "Tác nhân trang",
"pageSelection.lines": "Dòng {{start}}-{{end}}",
"pageSelection.reference": "Văn bản đã chọn",
+ "permission.configAccess.agentChatOnly": "Chỉ những cộng tác viên có quyền Chỉnh sửa mới có thể cấu hình Agent này. Bạn đã được chuyển trở lại trò chuyện.",
+ "permission.configAccess.groupChatOnly": "Chỉ những cộng tác viên có quyền Chỉnh sửa mới có thể cấu hình Nhóm Agent này. Bạn đã được chuyển trở lại trò chuyện.",
"pin": "Ghim",
"pinOff": "Bỏ ghim",
"platformAgent.create.available": "Có sẵn",
diff --git a/locales/vi-VN/common.json b/locales/vi-VN/common.json
index 5dc4516b7cd..be747d6cd7a 100644
--- a/locales/vi-VN/common.json
+++ b/locales/vi-VN/common.json
@@ -212,6 +212,7 @@
"copy": "Sao chép",
"copyFail": "Sao chép thất bại",
"copySuccess": "Đã sao chép",
+ "createdAt": "Được tạo lúc {{time}}",
"dataStatistics.messages": "Tin nhắn",
"dataStatistics.sessions": "Tác nhân",
"dataStatistics.today": "Mới hôm nay",
@@ -219,6 +220,7 @@
"defaultAgent": "Tác nhân tùy chỉnh",
"defaultSession": "Tác nhân tùy chỉnh",
"delete": "Xóa",
+ "deleteSharedOwnerOnly": "Chỉ chủ sở hữu không gian làm việc mới có thể xóa điều này — nó chứa các cuộc trò chuyện của các thành viên khác",
"document": "Hướng dẫn sử dụng",
"download": "Tải xuống",
"downloadingUpdate": "Đang tải xuống {{percent}}%",
diff --git a/locales/vi-VN/home.json b/locales/vi-VN/home.json
index f6ea539a9e1..63f8515e1a5 100644
--- a/locales/vi-VN/home.json
+++ b/locales/vi-VN/home.json
@@ -44,12 +44,16 @@
"homePromoBanner.cta": "Thử ngay",
"homePromoBanner.dismiss": "Bỏ qua",
"homePromoBanner.label": "{{model}} hiện đã có sẵn",
+ "inbox.author.scheduled": "Đã lên lịch",
"inbox.needsYou.title": "Cần bạn",
"inbox.news.markAllRead": "Đánh dấu tất cả là đã đọc",
"inbox.news.subtitle": "Không có gì cần quyết định — chỉ cần nhìn qua",
"inbox.news.title": "Tóm tắt hàng ngày",
"inbox.running.title": "{{count}} nhiệm vụ đang chạy",
"inbox.running.title_plural": "{{count}} nhiệm vụ đang chạy",
+ "inbox.scope.mine": "Của tôi",
+ "inbox.scope.onlyMe": "Chỉ của tôi",
+ "inbox.scope.team": "Nhóm",
"inbox.unread.followUp": "Theo dõi",
"inbox.unread.followUpPlaceholder": "Trả lời để tiếp tục cuộc trò chuyện này…",
"inbox.unread.title": "Chưa đọc",
diff --git a/locales/vi-VN/setting.json b/locales/vi-VN/setting.json
index 8774a7af38a..35d80329616 100644
--- a/locales/vi-VN/setting.json
+++ b/locales/vi-VN/setting.json
@@ -568,6 +568,23 @@
"notification.push.desc": "Gửi thông báo đẩy đến các thiết bị di động của bạn (cần ứng dụng di động LobeHub)",
"notification.push.title": "Thông báo đẩy trên di động",
"notification.title": "Kênh Thông Báo",
+ "permission.accessTag.useOnlyTip": "Quyền thành viên của bạn ở đây là \"Có thể sử dụng\" — bạn có thể xem và sử dụng, nhưng không thể chỉnh sửa. Hãy yêu cầu người tạo hoặc chủ sở hữu không gian làm việc cấp quyền chỉnh sửa.",
+ "permission.accessTag.viewOnlyTip": "Quyền thành viên của bạn ở đây là \"Chỉ có thể xem\" — bạn có thể xem, nhưng không thể sử dụng hoặc chỉnh sửa. Hãy yêu cầu người tạo hoặc chủ sở hữu không gian làm việc cấp thêm quyền.",
+ "permission.generalAccess.editable": "Có thể chỉnh sửa",
+ "permission.generalAccess.editableDesc": "Thành viên có thể xem, sử dụng và chỉnh sửa",
+ "permission.generalAccess.editableDocumentDesc": "Thành viên có thể xem và chỉnh sửa",
+ "permission.generalAccess.label": "Quyền của thành viên",
+ "permission.generalAccess.trigger": "Thành viên: {{level}}",
+ "permission.generalAccess.usable": "Có thể sử dụng",
+ "permission.generalAccess.usableDesc": "Thành viên có thể xem và sử dụng, nhưng không thể chỉnh sửa",
+ "permission.generalAccess.viewable": "Có thể xem",
+ "permission.generalAccess.viewableDesc": "Thành viên có thể xem, nhưng không thể sử dụng hoặc chỉnh sửa",
+ "permission.generalAccess.viewableDocumentDesc": "Thành viên có thể xem, nhưng không thể chỉnh sửa",
+ "permission.loadFailed": "Không thể tải cài đặt quyền",
+ "permission.noManagePermission": "Chỉ người tạo hoặc chủ sở hữu không gian làm việc mới có thể thay đổi quyền",
+ "permission.saveNoEditPermission": "Bạn chỉ có quyền xem trang này, vì vậy các thay đổi của bạn không được lưu",
+ "permission.updateError": "Không thể cập nhật quyền",
+ "permission.viewOnlySendTip": "Bạn chỉ có quyền xem và không thể gửi tin nhắn",
"platformAgentConfig.availability.available": "Có sẵn",
"platformAgentConfig.availability.checking": "Đang kiểm tra...",
"platformAgentConfig.availability.label": "Tình trạng sẵn có",
@@ -627,6 +644,9 @@
"settingAgent.description.desc": "Giới thiệu ngắn gọn về tác nhân của bạn, không dùng để thiết lập tính cách",
"settingAgent.description.placeholder": "Nhập mô tả tác nhân",
"settingAgent.description.title": "Mô tả tác nhân",
+ "settingAgent.devicePolicy.noPublicDevice": "Xuất bản một thiết bị không gian làm việc trước khi cố định nó vào Tác nhân này.",
+ "settingAgent.devicePolicy.selectTarget": "Chọn môi trường",
+ "settingAgent.devicePolicy.title": "Thiết bị thực thi",
"settingAgent.export.dialogTitle": "Xuất hồ sơ tác nhân",
"settingAgent.export.enabledPlugins": "Kỹ năng đã bật",
"settingAgent.export.error": "Không thể xuất hồ sơ tác nhân",
@@ -637,6 +657,8 @@
"settingAgent.export.tags": "Thẻ",
"settingAgent.export.untitled": "Tác nhân chưa có tiêu đề",
"settingAgent.export.untitledFileName": "hồ-sơ-tác-nhân",
+ "settingAgent.modelPolicy.fixedTip": "Mô hình được cố định trong Hồ sơ Đại lý và không thể thay đổi trong khi trò chuyện.",
+ "settingAgent.modelPolicy.title": "Mô hình",
"settingAgent.name.placeholder": "Nhập tên tác nhân",
"settingAgent.name.title": "Tên",
"settingAgent.prompt.desc": "Xác định ai là tác nhân này, trách nhiệm của nó, cách nó hoạt động và phản hồi. Đây là hướng dẫn cốt lõi trong mọi cuộc trò chuyện.",
@@ -644,11 +666,14 @@
"settingAgent.prompt.placeholder": "Nhập thiết lập tác nhân, nhấn / để mở menu lệnh",
"settingAgent.prompt.title": "Hồ sơ tác nhân",
"settingAgent.runtimeConfig.title": "Mô hình & Công cụ",
+ "settingAgent.selectionPolicy.membersCanSwitch": "Thành viên có thể thay đổi",
+ "settingAgent.selectionPolicy.membersCannotSwitch": "Thành viên không thể thay đổi",
"settingAgent.submit": "Cập nhật tác nhân",
"settingAgent.tag.desc": "Thẻ tác nhân sẽ hiển thị trong Cộng đồng Tác nhân",
"settingAgent.tag.placeholder": "Nhập thẻ",
"settingAgent.tag.title": "Thẻ",
"settingAgent.title": "Thông tin tác nhân",
+ "settingAgent.toolsConfig.title": "Công cụ",
"settingAppearance.animationMode.agile": "Nhanh nhẹn",
"settingAppearance.animationMode.desc": "Chọn tốc độ hoạt ảnh cho các hành động phản hồi của ứng dụng",
"settingAppearance.animationMode.disabled": "Tắt",
@@ -2274,6 +2299,7 @@
"workspace.member.manageAccess": "Quản lý quyền truy cập",
"workspace.member.manageAccessModal.current": "Hiện tại",
"workspace.member.manageAccessModal.failed": "Không thể cập nhật quyền truy cập",
+ "workspace.member.manageAccessModal.memberLimitReached": "Không gian làm việc này đã đạt giới hạn {{limit}} thành viên. Vui lòng thêm chỗ trước khi thay đổi người dùng này thành {{role}}.",
"workspace.member.manageAccessModal.save": "Lưu thay đổi",
"workspace.member.manageAccessModal.success": "Quyền truy cập đã được cập nhật",
"workspace.member.manageAccessModal.title": "Quản lý quyền truy cập nhóm",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index fd75bfc6aae..17a250865e0 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -3,6 +3,7 @@
"active": "活跃",
"addAgentFromMarket": "从市场添加助理",
"agent.publishToWorkspace": "发布到工作区",
+ "agent.publishToWorkspaceErrorFixedPrivateDevice": "将修复的设备发布到工作区,或者让成员选择设备后再发布此代理。",
"agent.publishToWorkspaceSuccess": "已发布到工作区",
"agentBuilder.installPlugin.authRequired": "云端 MCP 需要登录后才能继续",
"agentBuilder.installPlugin.cancel": "取消",
@@ -349,9 +350,10 @@
"heteroAgent.executionTarget.downloadDesktop": "下载桌面端",
"heteroAgent.executionTarget.downloadDesktopDesc": "让 Agent 直接连接你的电脑",
"heteroAgent.executionTarget.downloadDesktopTitle": "下载桌面端",
+ "heteroAgent.executionTarget.fixedTip": "此代理使用由编辑者固定的执行环境。请联系编辑者进行更改。",
"heteroAgent.executionTarget.gateway": "网关",
"heteroAgent.executionTarget.gatewayDesc": "经由设备网关运行,其他客户端可跟踪进度",
- "heteroAgent.executionTarget.infoTooltip": "选择某台设备后,Agent 将以该设备为运行环境,读写文件、操作电脑。云端沙箱由 LobeHub Marketplace 提供服务",
+ "heteroAgent.executionTarget.infoTooltip": "选择此代理运行的位置。设备可以读取和写入文件或操作计算机;云沙盒在隔离的临时环境中运行。",
"heteroAgent.executionTarget.loading": "正在加载设备…",
"heteroAgent.executionTarget.local": "本地设备",
"heteroAgent.executionTarget.localDesc": "在当前桌面端以本地进程运行",
@@ -366,7 +368,7 @@
"heteroAgent.executionTarget.sandbox": "云端沙箱",
"heteroAgent.executionTarget.sandboxDesc": "在临时云端沙箱中运行",
"heteroAgent.executionTarget.sandboxUnsupported": "{{name}} 目前仅支持在本地设备或已连接设备上运行",
- "heteroAgent.executionTarget.title": "执行设备",
+ "heteroAgent.executionTarget.title": "执行环境",
"heteroAgent.executionTarget.unknownDevice": "未知设备",
"heteroAgent.executionTarget.workspaceGroup": "工作区设备",
"heteroAgent.fullAccess.label": "完全访问权限",
@@ -470,6 +472,8 @@
"input.sendWithCmdEnter": "按 <key/> 发送",
"input.sendWithEnter": "按 <key/> 发送",
"input.stop": "停止",
+ "input.viewOnlyAgent": "您对该代理只有查看权限,因此无法发送消息。请联系创建者或工作区所有者以获取访问权限。",
+ "input.viewOnlyGroup": "您对该组只有查看权限,因此无法发送消息。请联系创建者或工作区所有者以获取访问权限。",
"input.warp": "换行",
"input.warpWithKey": "按 <key/> 换行",
"inputQueue.delete": "删除",
@@ -667,6 +671,8 @@
"pageCopilot.title": "文稿助理",
"pageSelection.lines": "第 {{start}}-{{end}} 行",
"pageSelection.reference": "选中文本",
+ "permission.configAccess.agentChatOnly": "只有具有“可编辑”权限的协作者可以配置此代理。您已返回到聊天界面。",
+ "permission.configAccess.groupChatOnly": "只有具有“可编辑”权限的协作者可以配置此代理组。您已返回到聊天界面。",
"pin": "置顶",
"pinOff": "取消置顶",
"platformAgent.create.available": "可用",
@@ -1636,6 +1642,5 @@
"workingPanel.works.versionError": "版本加载失败",
"workingPanel.works.viewMode.history": "版本历史",
"workingPanel.works.viewMode.summary": "摘要卡片",
- "you": "你",
- "zenMode": "专注模式"
+ "you": "你"
}
diff --git a/locales/zh-CN/common.json b/locales/zh-CN/common.json
index 6865f6c0483..17f66df1383 100644
--- a/locales/zh-CN/common.json
+++ b/locales/zh-CN/common.json
@@ -212,6 +212,7 @@
"copy": "复制",
"copyFail": "复制失败",
"copySuccess": "已复制",
+ "createdAt": "创建于 {{time}}",
"dataStatistics.messages": "消息",
"dataStatistics.sessions": "助理",
"dataStatistics.today": "今日新增",
@@ -219,6 +220,7 @@
"defaultAgent": "自定义助理",
"defaultSession": "自定义助理",
"delete": "删除",
+ "deleteSharedOwnerOnly": "该资产承载了其他成员的会话,仅工作区 Owner 可删除",
"document": "使用文档",
"download": "下载",
"downloadingUpdate": "正在下载 {{percent}}%",
diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.json
index 0ed8d96c424..6790df7a6fe 100644
--- a/locales/zh-CN/setting.json
+++ b/locales/zh-CN/setting.json
@@ -568,6 +568,23 @@
"notification.push.desc": "向您的移动设备发送推送通知(需要安装 LobeHub 移动应用)",
"notification.push.title": "移动推送通知",
"notification.title": "通知渠道",
+ "permission.accessTag.useOnlyTip": "你在此处的成员权限为「可使用」:可以查看和使用,但不能编辑。如需编辑权限,请联系创建者或工作区管理员。",
+ "permission.accessTag.viewOnlyTip": "你在此处的成员权限为「可查看」:仅可查看,不能使用或编辑。如需更多权限,请联系创建者或工作区管理员。",
+ "permission.generalAccess.editable": "可编辑",
+ "permission.generalAccess.editableDesc": "成员可查看、使用和编辑",
+ "permission.generalAccess.editableDocumentDesc": "成员可查看和编辑",
+ "permission.generalAccess.label": "成员权限",
+ "permission.generalAccess.trigger": "成员权限:{{level}}",
+ "permission.generalAccess.usable": "可使用",
+ "permission.generalAccess.usableDesc": "成员可查看和使用,但不能编辑",
+ "permission.generalAccess.viewable": "可查看",
+ "permission.generalAccess.viewableDesc": "成员只能查看,不能使用或编辑",
+ "permission.generalAccess.viewableDocumentDesc": "成员只能查看,不能编辑",
+ "permission.loadFailed": "权限设置加载失败",
+ "permission.noManagePermission": "仅创建者或工作区所有者可以修改权限",
+ "permission.saveNoEditPermission": "你仅有该页面的查看权限,修改未保存",
+ "permission.updateError": "权限更新失败",
+ "permission.viewOnlySendTip": "你仅有查看权限,无法发送消息",
"platformAgentConfig.availability.available": "可用",
"platformAgentConfig.availability.checking": "检测中...",
"platformAgentConfig.availability.label": "可用性",
@@ -627,6 +644,9 @@
"settingAgent.description.desc": "简单介绍你的助理,不作为角色设定",
"settingAgent.description.placeholder": "请输入助理描述",
"settingAgent.description.title": "助理描述",
+ "settingAgent.devicePolicy.noPublicDevice": "暂无公开设备",
+ "settingAgent.devicePolicy.selectTarget": "选择环境",
+ "settingAgent.devicePolicy.title": "执行环境",
"settingAgent.export.dialogTitle": "导出助理档案",
"settingAgent.export.enabledPlugins": "已启用技能",
"settingAgent.export.error": "助理档案导出失败",
@@ -637,6 +657,8 @@
"settingAgent.export.tags": "标签",
"settingAgent.export.untitled": "未命名助理",
"settingAgent.export.untitledFileName": "助理档案",
+ "settingAgent.modelPolicy.fixedTip": "模型已在助理档案中固定,聊天时不可切换。",
+ "settingAgent.modelPolicy.title": "模型",
"settingAgent.name.placeholder": "请输入助理名称",
"settingAgent.name.title": "名称",
"settingAgent.prompt.desc": "定义这个助理的身份、职责、工作方式和回应风格。这里的设定会在每次对话中生效。",
@@ -644,11 +666,14 @@
"settingAgent.prompt.placeholder": "请输入助理指令",
"settingAgent.prompt.title": "核心指令",
"settingAgent.runtimeConfig.title": "模型与工具",
+ "settingAgent.selectionPolicy.membersCanSwitch": "成员可切换",
+ "settingAgent.selectionPolicy.membersCannotSwitch": "成员不可切换",
"settingAgent.submit": "更新助理信息",
"settingAgent.tag.desc": "助理标签将在助理社区中展示",
"settingAgent.tag.placeholder": "请输入标签",
"settingAgent.tag.title": "标签",
"settingAgent.title": "助理信息",
+ "settingAgent.toolsConfig.title": "工具",
"settingAppearance.animationMode.agile": "敏捷",
"settingAppearance.animationMode.desc": "选择应用程序的操作响应的动画速度",
"settingAppearance.animationMode.disabled": "关闭",
@@ -2274,6 +2299,7 @@
"workspace.member.manageAccess": "更改角色...",
"workspace.member.manageAccessModal.current": "当前",
"workspace.member.manageAccessModal.failed": "更新访问权限失败",
+ "workspace.member.manageAccessModal.memberLimitReached": "此工作区已达到 {{limit}} 名成员上限。请先增加席位,再将该成员改为{{role}}。",
"workspace.member.manageAccessModal.save": "保存更改",
"workspace.member.manageAccessModal.success": "访问权限已更新",
"workspace.member.manageAccessModal.title": "更改 {{username}} 的角色",
diff --git a/locales/zh-TW/chat.json b/locales/zh-TW/chat.json
index b9bdb571798..56ed80c9c62 100644
--- a/locales/zh-TW/chat.json
+++ b/locales/zh-TW/chat.json
@@ -3,6 +3,7 @@
"active": "活躍",
"addAgentFromMarket": "從市場添加",
"agent.publishToWorkspace": "發佈到工作區",
+ "agent.publishToWorkspaceErrorFixedPrivateDevice": "將修正的設備發佈到工作區,或讓成員選擇一個設備後,再發佈此代理。",
"agent.publishToWorkspaceSuccess": "已發佈到工作區",
"agentBuilder.installPlugin.authRequired": "雲端 MCP 外掛需要登入驗證",
"agentBuilder.installPlugin.cancel": "取消",
@@ -349,9 +350,10 @@
"heteroAgent.executionTarget.downloadDesktop": "下載桌面應用程式",
"heteroAgent.executionTarget.downloadDesktopDesc": "運行可訪問您電腦的代理",
"heteroAgent.executionTarget.downloadDesktopTitle": "下載桌面應用程式",
+ "heteroAgent.executionTarget.fixedTip": "此代理使用由其編輯者固定的執行環境。請聯繫編輯者進行更改。",
"heteroAgent.executionTarget.gateway": "網關",
"heteroAgent.executionTarget.gatewayDesc": "通過設備網關運行,以便其他客戶端可以跟蹤進度",
- "heteroAgent.executionTarget.infoTooltip": "選擇一個遠端設備以從網頁操作該機器。「本設備」在桌面應用程式內本地運行代理。",
+ "heteroAgent.executionTarget.infoTooltip": "選擇此代理運行的位置。一個設備可以讀寫文件或操作計算機;雲端沙盒則在一個隔離的臨時環境中運行。",
"heteroAgent.executionTarget.loading": "正在載入設備…",
"heteroAgent.executionTarget.local": "本設備",
"heteroAgent.executionTarget.localDesc": "在此桌面應用程式中作為本地進程運行",
@@ -366,7 +368,7 @@
"heteroAgent.executionTarget.sandbox": "雲端沙盒",
"heteroAgent.executionTarget.sandboxDesc": "在臨時雲端沙盒中運行",
"heteroAgent.executionTarget.sandboxUnsupported": "{{name}} 目前僅能在本地或連接的設備上運行",
- "heteroAgent.executionTarget.title": "執行設備",
+ "heteroAgent.executionTarget.title": "執行環境",
"heteroAgent.executionTarget.unknownDevice": "未知設備",
"heteroAgent.executionTarget.workspaceGroup": "工作區",
"heteroAgent.fullAccess.label": "完整存取",
@@ -470,6 +472,8 @@
"input.sendWithCmdEnter": "按 <key/> 鍵發送",
"input.sendWithEnter": "按 <key/> 鍵發送",
"input.stop": "停止",
+ "input.viewOnlyAgent": "您對此代理僅有檢視權限,因此無法發送消息。請聯繫創建者或工作區擁有者以獲取權限。",
+ "input.viewOnlyGroup": "您對此群組僅有檢視權限,因此無法發送消息。請聯繫創建者或工作區擁有者以獲取權限。",
"input.warp": "換行",
"input.warpWithKey": "按 <key/> 鍵換行",
"inputQueue.delete": "刪除",
@@ -667,6 +671,8 @@
"pageCopilot.title": "文稿助手",
"pageSelection.lines": "第 {{start}}-{{end}} 行",
"pageSelection.reference": "選取的文字",
+ "permission.configAccess.agentChatOnly": "只有具有「可編輯」權限的協作者才能配置此代理。您已被返回到聊天。",
+ "permission.configAccess.groupChatOnly": "只有具有「可編輯」權限的協作者才能配置此代理群組。您已被返回到聊天。",
"pin": "置頂",
"pinOff": "取消置頂",
"platformAgent.create.available": "可用",
diff --git a/locales/zh-TW/common.json b/locales/zh-TW/common.json
index 9543393da28..c6c90c24646 100644
--- a/locales/zh-TW/common.json
+++ b/locales/zh-TW/common.json
@@ -212,6 +212,7 @@
"copy": "複製",
"copyFail": "複製失敗",
"copySuccess": "已複製",
+ "createdAt": "建立於 {{time}}",
"dataStatistics.messages": "消息",
"dataStatistics.sessions": "助手",
"dataStatistics.today": "今日新增",
@@ -219,6 +220,7 @@
"defaultAgent": "預設助手",
"defaultSession": "預設助手",
"delete": "刪除",
+ "deleteSharedOwnerOnly": "只有工作區擁有者可以刪除此項目——它包含其他成員的對話",
"document": "使用說明文件",
"download": "下載",
"downloadingUpdate": "正在下載 {{percent}}%",
diff --git a/locales/zh-TW/home.json b/locales/zh-TW/home.json
index 471b4cb7474..90c31daf584 100644
--- a/locales/zh-TW/home.json
+++ b/locales/zh-TW/home.json
@@ -44,12 +44,16 @@
"homePromoBanner.cta": "立即嘗試",
"homePromoBanner.dismiss": "關閉",
"homePromoBanner.label": "{{model}} 現已推出",
+ "inbox.author.scheduled": "已排程",
"inbox.needsYou.title": "需要您",
"inbox.news.markAllRead": "全部標記為已讀",
"inbox.news.subtitle": "無需決定 — 只需一瞥",
"inbox.news.title": "每日簡報",
"inbox.running.title": "{{count}} 項任務正在執行",
"inbox.running.title_plural": "{{count}} 項任務正在執行",
+ "inbox.scope.mine": "我的",
+ "inbox.scope.onlyMe": "僅限我的",
+ "inbox.scope.team": "團隊",
"inbox.unread.followUp": "後續跟進",
"inbox.unread.followUpPlaceholder": "回覆以繼續此流程…",
"inbox.unread.title": "未讀",
diff --git a/locales/zh-TW/setting.json b/locales/zh-TW/setting.json
index 77fd294e693..02b3723a5b6 100644
--- a/locales/zh-TW/setting.json
+++ b/locales/zh-TW/setting.json
@@ -568,6 +568,23 @@
"notification.push.desc": "向您的行動裝置發送推播通知(需要 LobeHub 行動應用程式)",
"notification.push.title": "行動推播通知",
"notification.title": "通知頻道",
+ "permission.accessTag.useOnlyTip": "您的成員權限為「可使用」——您可以查看和使用,但無法編輯。請向創建者或工作區擁有者申請編輯權限。",
+ "permission.accessTag.viewOnlyTip": "您的成員權限為「僅可查看」——您可以查看,但無法使用或編輯。請向創建者或工作區擁有者申請更多權限。",
+ "permission.generalAccess.editable": "可編輯",
+ "permission.generalAccess.editableDesc": "成員可以查看、使用和編輯",
+ "permission.generalAccess.editableDocumentDesc": "成員可以查看和編輯",
+ "permission.generalAccess.label": "成員權限",
+ "permission.generalAccess.trigger": "成員:{{level}}",
+ "permission.generalAccess.usable": "可使用",
+ "permission.generalAccess.usableDesc": "成員可以查看和使用,但無法編輯",
+ "permission.generalAccess.viewable": "僅可查看",
+ "permission.generalAccess.viewableDesc": "成員可以查看,但無法使用或編輯",
+ "permission.generalAccess.viewableDocumentDesc": "成員可以查看,但無法編輯",
+ "permission.loadFailed": "無法載入權限設定",
+ "permission.noManagePermission": "只有創建者或工作區擁有者可以更改權限",
+ "permission.saveNoEditPermission": "您對此頁面的權限為僅可查看,因此您的更改未被保存",
+ "permission.updateError": "更新權限失敗",
+ "permission.viewOnlySendTip": "您僅有查看權限,無法發送消息",
"platformAgentConfig.availability.available": "可用",
"platformAgentConfig.availability.checking": "檢查中...",
"platformAgentConfig.availability.label": "可用性",
@@ -627,6 +644,9 @@
"settingAgent.description.desc": "簡單介紹你的助手,不作為角色設定",
"settingAgent.description.placeholder": "請輸入助手描述",
"settingAgent.description.title": "助手描述",
+ "settingAgent.devicePolicy.noPublicDevice": "無公共設備",
+ "settingAgent.devicePolicy.selectTarget": "選擇環境",
+ "settingAgent.devicePolicy.title": "執行環境",
"settingAgent.export.dialogTitle": "匯出代理檔案",
"settingAgent.export.enabledPlugins": "啟用的技能",
"settingAgent.export.error": "匯出代理檔案失敗",
@@ -637,6 +657,8 @@
"settingAgent.export.tags": "標籤",
"settingAgent.export.untitled": "未命名代理",
"settingAgent.export.untitledFileName": "代理檔案",
+ "settingAgent.modelPolicy.fixedTip": "模型已在代理檔案中固定,聊天時無法切換。",
+ "settingAgent.modelPolicy.title": "模型",
"settingAgent.name.placeholder": "請輸入助手名稱",
"settingAgent.name.title": "名稱",
"settingAgent.prompt.desc": "定義此代理的身份、責任以及其運作和回應方式。它在每次對話中都作為核心指令。",
@@ -644,11 +666,14 @@
"settingAgent.prompt.placeholder": "輸入助手設定,按 / 開啟指令選單",
"settingAgent.prompt.title": "助手設定",
"settingAgent.runtimeConfig.title": "模型與工具",
+ "settingAgent.selectionPolicy.membersCanSwitch": "成員可以切換",
+ "settingAgent.selectionPolicy.membersCannotSwitch": "成員無法切換",
"settingAgent.submit": "更新助手資訊",
"settingAgent.tag.desc": "助手標籤將會在助手社群中顯示",
"settingAgent.tag.placeholder": "請輸入標籤",
"settingAgent.tag.title": "標籤",
"settingAgent.title": "助手資訊",
+ "settingAgent.toolsConfig.title": "工具",
"settingAppearance.animationMode.agile": "敏捷",
"settingAppearance.animationMode.desc": "選擇應用程式操作回應的動畫速度",
"settingAppearance.animationMode.disabled": "關閉",
@@ -2274,6 +2299,7 @@
"workspace.member.manageAccess": "管理訪問",
"workspace.member.manageAccessModal.current": "當前",
"workspace.member.manageAccessModal.failed": "更新訪問失敗",
+ "workspace.member.manageAccessModal.memberLimitReached": "此工作區已達到 {{limit}} 位成員的限制。在將此使用者更改為 {{role}} 之前,請先增加席位。",
"workspace.member.manageAccessModal.save": "保存更改",
"workspace.member.manageAccessModal.success": "訪問已更新",
"workspace.member.manageAccessModal.title": "管理團隊訪問",
diff --git a/packages/database/src/models/__tests__/agent.privateVisibility.workspace.test.ts b/packages/database/src/models/__tests__/agent.privateVisibility.workspace.test.ts
index 1df651a1ac1..4581f45ee35 100644
--- a/packages/database/src/models/__tests__/agent.privateVisibility.workspace.test.ts
+++ b/packages/database/src/models/__tests__/agent.privateVisibility.workspace.test.ts
@@ -136,6 +136,30 @@ describe('AgentModel — private/public cross-user isolation', () => {
expect(await callerB.existsById('a-shared-public')).toBe(true);
expect(await callerB.getAgentConfig('a-shared-public')).not.toBeNull();
});
+
+ it('publishes only the creator own still-private agent', async () => {
+ await insertAgent({ id: 'a-to-publish', userId: userA, visibility: 'private', workspaceId });
+
+ const callerA = new AgentModel(serverDB, userA, workspaceId);
+ const result = await callerA.publishToWorkspace('a-to-publish');
+
+ expect(result.visibility).toBe('public');
+ });
+
+ it('rejects a zero-row publish of another member public agent', async () => {
+ await insertAgent({
+ id: 'a-already-shared',
+ userId: userA,
+ visibility: 'public',
+ workspaceId,
+ });
+
+ const callerB = new AgentModel(serverDB, userB, workspaceId);
+
+ await expect(callerB.publishToWorkspace('a-already-shared')).rejects.toThrow(
+ 'Agent not found, already published, or access denied',
+ );
+ });
});
describe('setVisibility group rehoming', () => {
diff --git a/packages/database/src/models/__tests__/agentDeviceBinding.test.ts b/packages/database/src/models/__tests__/agentDeviceBinding.test.ts
index 133528332fb..92e755faffa 100644
--- a/packages/database/src/models/__tests__/agentDeviceBinding.test.ts
+++ b/packages/database/src/models/__tests__/agentDeviceBinding.test.ts
@@ -22,7 +22,13 @@ beforeEach(async () => {
.values([{ id: wsId, name: 'WS', slug: 'ws', primaryOwnerId: userId }]);
await serverDB.insert(devices).values([
{ userId, deviceId: personalDeviceId, identitySource: 'machine-id' },
- { userId, workspaceId: wsId, deviceId: workspaceDeviceId, identitySource: 'machine-id' },
+ {
+ userId,
+ workspaceId: wsId,
+ deviceId: workspaceDeviceId,
+ identitySource: 'machine-id',
+ visibility: 'public',
+ },
]);
});
@@ -71,9 +77,85 @@ describe('AgentModel workspace device binding', () => {
}),
).rejects.toThrow(/Workspace agent can only bind devices/);
});
+
+ it('allows a fixed public workspace device target', async () => {
+ const wsModel = new AgentModel(serverDB, userId, wsId);
+ const agent = await wsModel.create({
+ title: 'Fixed WS agent',
+ agencyConfig: {
+ boundDeviceId: workspaceDeviceId,
+ executionTargetSelectionPolicy: 'fixed',
+ executionTarget: 'device',
+ },
+ });
+
+ expect(agent.agencyConfig?.executionTargetSelectionPolicy).toBe('fixed');
+ });
+
+ it.each(['auto', 'none', 'sandbox'] as const)(
+ 'allows a fixed shared %s target',
+ async (executionTarget) => {
+ const wsModel = new AgentModel(serverDB, userId, wsId);
+ const agent = await wsModel.create({
+ title: 'Fixed WS agent',
+ agencyConfig: { executionTarget, executionTargetSelectionPolicy: 'fixed' },
+ });
+
+ expect(agent.agencyConfig?.executionTargetSelectionPolicy).toBe('fixed');
+ expect(agent.agencyConfig?.executionTarget).toBe(executionTarget);
+ },
+ );
+
+ it('rejects fixing a client-local target for a workspace agent', async () => {
+ const wsModel = new AgentModel(serverDB, userId, wsId);
+ await expect(
+ wsModel.create({
+ title: 'Invalid fixed WS agent',
+ agencyConfig: { executionTarget: 'local', executionTargetSelectionPolicy: 'fixed' },
+ }),
+ ).rejects.toThrow(/requires a shared execution target/);
+ });
+
+ it('rejects fixed policy with a private workspace device', async () => {
+ const privateDeviceId = 'workspace-private-device';
+ await serverDB.insert(devices).values({
+ deviceId: privateDeviceId,
+ identitySource: 'machine-id',
+ userId,
+ visibility: 'private',
+ workspaceId: wsId,
+ });
+ const wsModel = new AgentModel(serverDB, userId, wsId);
+
+ await expect(
+ wsModel.create({
+ title: 'Private fixed WS agent',
+ agencyConfig: {
+ boundDeviceId: privateDeviceId,
+ executionTargetSelectionPolicy: 'fixed',
+ executionTarget: 'device',
+ },
+ }),
+ ).rejects.toThrow(/requires a public device/);
+ });
});
describe('updateConfig', () => {
+ it('enables fixed policy through the normal config update path', async () => {
+ const wsModel = new AgentModel(serverDB, userId, wsId);
+ const agent = await wsModel.create({
+ title: 'WS agent',
+ agencyConfig: { boundDeviceId: workspaceDeviceId, executionTarget: 'device' },
+ });
+
+ await wsModel.updateConfig(agent.id, {
+ agencyConfig: { executionTargetSelectionPolicy: 'fixed' },
+ });
+
+ const result = await serverDB.query.agents.findFirst({ where: eq(agents.id, agent.id) });
+ expect(result?.agencyConfig?.executionTargetSelectionPolicy).toBe('fixed');
+ });
+
it('allows clearing boundDeviceId on a workspace agent', async () => {
const wsModel = new AgentModel(serverDB, userId, wsId);
const agent = await wsModel.create({
@@ -141,6 +223,61 @@ describe('AgentModel workspace device binding', () => {
});
});
+ describe('publishToWorkspace', () => {
+ const createPrivateFixedAgent = async () => {
+ const wsModel = new AgentModel(serverDB, userId, wsId);
+ const agent = await wsModel.create({
+ agencyConfig: {
+ boundDeviceId: workspaceDeviceId,
+ executionTargetSelectionPolicy: 'fixed',
+ executionTarget: 'device',
+ },
+ title: 'Private fixed agent',
+ visibility: 'private',
+ });
+
+ return { agent, wsModel };
+ };
+
+ it('publishes a fixed agent while its device is public', async () => {
+ const { agent, wsModel } = await createPrivateFixedAgent();
+
+ const published = await wsModel.publishToWorkspace(agent.id);
+
+ expect(published.visibility).toBe('public');
+ });
+
+ it('blocks publishing when the fixed device is no longer public', async () => {
+ const { agent, wsModel } = await createPrivateFixedAgent();
+ await serverDB
+ .update(devices)
+ .set({ visibility: 'private' })
+ .where(eq(devices.deviceId, workspaceDeviceId));
+
+ await expect(wsModel.publishToWorkspace(agent.id)).rejects.toThrow(
+ /requires a public device/,
+ );
+
+ const stored = await serverDB.query.agents.findFirst({ where: eq(agents.id, agent.id) });
+ expect(stored?.visibility).toBe('private');
+ });
+
+ it('blocks the direct visibility API from bypassing the fixed-device check', async () => {
+ const { agent, wsModel } = await createPrivateFixedAgent();
+ await serverDB
+ .update(devices)
+ .set({ visibility: 'private' })
+ .where(eq(devices.deviceId, workspaceDeviceId));
+
+ await expect(wsModel.setVisibility(agent.id, 'public')).rejects.toThrow(
+ /requires a public device/,
+ );
+
+ const stored = await serverDB.query.agents.findFirst({ where: eq(agents.id, agent.id) });
+ expect(stored?.visibility).toBe('private');
+ });
+ });
+
describe('transferAgent', () => {
it('strips a personal-device binding when moving an agent into a workspace', async () => {
const personalModel = new AgentModel(serverDB, userId);
@@ -181,6 +318,42 @@ describe('AgentModel workspace device binding', () => {
expect(result?.agencyConfig?.workingDirByDevice?.[workspaceDeviceId]).toBe('/work');
});
+ it('downgrades an invalid fixed local target when moving into a workspace', async () => {
+ const personalModel = new AgentModel(serverDB, userId);
+ const agent = await personalModel.create({
+ title: 'Personal local agent',
+ agencyConfig: {
+ executionTarget: 'local',
+ executionTargetSelectionPolicy: 'fixed',
+ },
+ });
+
+ await personalModel.transferAgent(agent.id, wsId, userId);
+
+ const result = await serverDB.query.agents.findFirst({
+ where: eq(agents.id, agent.id),
+ });
+ expect(result?.agencyConfig?.executionTargetSelectionPolicy).toBe('member');
+ });
+
+ it('preserves a fixed sandbox target when moving into a workspace', async () => {
+ const personalModel = new AgentModel(serverDB, userId);
+ const agent = await personalModel.create({
+ title: 'Personal sandbox agent',
+ agencyConfig: {
+ executionTarget: 'sandbox',
+ executionTargetSelectionPolicy: 'fixed',
+ },
+ });
+
+ await personalModel.transferAgent(agent.id, wsId, userId);
+
+ const result = await serverDB.query.agents.findFirst({
+ where: eq(agents.id, agent.id),
+ });
+ expect(result?.agencyConfig?.executionTargetSelectionPolicy).toBe('fixed');
+ });
+
it('keeps the binding intact when moving back to personal scope', async () => {
const wsModel = new AgentModel(serverDB, userId, wsId);
const agent = await wsModel.create({
diff --git a/packages/database/src/models/__tests__/device.test.ts b/packages/database/src/models/__tests__/device.test.ts
index b128fe5d55e..a8e87e6e99d 100644
--- a/packages/database/src/models/__tests__/device.test.ts
+++ b/packages/database/src/models/__tests__/device.test.ts
@@ -3,7 +3,7 @@ import { and, eq } from 'drizzle-orm';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { getTestDB } from '../../core/getTestDB';
-import { devices, users, workspaces } from '../../schemas';
+import { agents, devices, users, workspaces } from '../../schemas';
import type { LobeChatDatabase } from '../../type';
import { DeviceModel, WorkspaceDevicePrivateConflictError } from '../device';
@@ -104,6 +104,16 @@ describe('DeviceModel', () => {
it('should return only the current user devices, newest lastSeen first', async () => {
await deviceModel.register({ deviceId: 'dev-old', identitySource: 'machine-id' });
await deviceModel.register({ deviceId: 'dev-new', identitySource: 'machine-id' });
+ // The in-memory test DB may assign both inserts the same millisecond.
+ // Pin distinct timestamps so this ordering assertion is deterministic.
+ await serverDB
+ .update(devices)
+ .set({ lastSeenAt: new Date('2026-01-01T00:00:00.000Z') })
+ .where(eq(devices.deviceId, 'dev-old'));
+ await serverDB
+ .update(devices)
+ .set({ lastSeenAt: new Date('2026-01-02T00:00:00.000Z') })
+ .where(eq(devices.deviceId, 'dev-new'));
// a device owned by another user must not leak
await new DeviceModel(serverDB, 'device-model-other-user').register({
deviceId: 'other-dev',
@@ -133,6 +143,49 @@ describe('DeviceModel', () => {
expect(personal.map((d) => d.deviceId)).toEqual(['p1']);
});
+ it('detects whether a workspace device is referenced by a fixed agent', async () => {
+ await serverDB.insert(devices).values({
+ deviceId: 'fixed-device',
+ identitySource: 'machine-id',
+ userId,
+ visibility: 'public',
+ workspaceId: wsId,
+ });
+ await serverDB.insert(agents).values({
+ agencyConfig: {
+ boundDeviceId: 'fixed-device',
+ executionTargetSelectionPolicy: 'fixed',
+ executionTarget: 'device',
+ },
+ id: 'fixed-agent',
+ title: 'Fixed agent',
+ userId,
+ workspaceId: wsId,
+ });
+
+ const wsModel = new DeviceModel(serverDB, userId, wsId);
+ expect(await wsModel.hasFixedAgentBinding('fixed-device')).toBe(true);
+ expect(await wsModel.hasFixedAgentBinding('other-device')).toBe(false);
+ expect(await deviceModel.hasFixedAgentBinding('fixed-device')).toBe(false);
+ });
+
+ it('ignores a stale device id on a fixed non-device target', async () => {
+ await serverDB.insert(agents).values({
+ agencyConfig: {
+ boundDeviceId: 'stale-device',
+ executionTarget: 'sandbox',
+ executionTargetSelectionPolicy: 'fixed',
+ },
+ id: 'fixed-sandbox-agent',
+ title: 'Fixed sandbox agent',
+ userId,
+ workspaceId: wsId,
+ });
+
+ const wsModel = new DeviceModel(serverDB, userId, wsId);
+ expect(await wsModel.hasFixedAgentBinding('stale-device')).toBe(false);
+ });
+
it('queryWorkspaceDevices returns every enrolled device (any owner), scoped to the workspace', async () => {
// enrolled by two different admins into the same workspace (public —
// another member's default-private enrollment is covered by the
diff --git a/packages/database/src/models/__tests__/document.privateVisibility.workspace.test.ts b/packages/database/src/models/__tests__/document.privateVisibility.workspace.test.ts
index 4325fbb553c..c5cb6794d99 100644
--- a/packages/database/src/models/__tests__/document.privateVisibility.workspace.test.ts
+++ b/packages/database/src/models/__tests__/document.privateVisibility.workspace.test.ts
@@ -222,7 +222,7 @@ describe('DocumentModel.create — workspace visibility defaults', () => {
expect(created.visibility).toBe('private');
});
- it('inherits the parent visibility for a nested document', async () => {
+ it('does not inherit visibility from a parent document', async () => {
const callerA = new DocumentModel(serverDB, userA, workspaceId);
const root = await callerA.create({
fileType: 'custom/folder',
@@ -232,14 +232,14 @@ describe('DocumentModel.create — workspace visibility defaults', () => {
totalCharCount: 0,
totalLineCount: 0,
});
- expect(root.visibility).toBe('private');
+ await callerA.setVisibility(root.id, 'public');
const child = await callerA.create({
fileType: 'text/plain',
parentId: root.id,
source: 'inline',
sourceType: 'api',
- title: 'inherited-child',
+ title: 'independent-child',
totalCharCount: 0,
totalLineCount: 0,
});
@@ -262,7 +262,7 @@ describe('DocumentModel.create — workspace visibility defaults', () => {
});
describe('DocumentModel.publishToWorkspace', () => {
- it('cascades the whole subtree to public in a single transaction', async () => {
+ it('publishes only the selected document', async () => {
const callerA = new DocumentModel(serverDB, userA, workspaceId);
const root = await callerA.create({
fileType: 'custom/folder',
@@ -295,12 +295,10 @@ describe('DocumentModel.publishToWorkspace', () => {
expect(grandchild.visibility).toBe('private');
const result = await callerA.publishToWorkspace(root.id);
- expect(result.documentIds.sort()).toEqual([root.id, child.id, grandchild.id].sort());
-
- for (const id of [root.id, child.id, grandchild.id]) {
- const row = await callerA.findById(id);
- expect(row?.visibility).toBe('public');
- }
+ expect(result.documentIds).toEqual([root.id]);
+ expect((await callerA.findById(root.id))?.visibility).toBe('public');
+ expect((await callerA.findById(child.id))?.visibility).toBe('private');
+ expect((await callerA.findById(grandchild.id))?.visibility).toBe('private');
});
it("refuses to flip another user's private subtree", async () => {
@@ -345,7 +343,7 @@ describe('DocumentModel.publishToWorkspace', () => {
});
describe('DocumentModel.setVisibility', () => {
- it('flips a whole public subtree back to private (owner-only cascade)', async () => {
+ it('makes only the selected public document private', async () => {
const callerA = new DocumentModel(serverDB, userA, workspaceId);
const root = await callerA.create({
fileType: 'custom/folder',
@@ -365,18 +363,12 @@ describe('DocumentModel.setVisibility', () => {
totalLineCount: 0,
});
await callerA.publishToWorkspace(root.id);
- for (const id of [root.id, child.id]) {
- const row = await callerA.findById(id);
- expect(row?.visibility).toBe('public');
- }
+ await callerA.publishToWorkspace(child.id);
const result = await callerA.setVisibility(root.id, 'private');
- expect(result.documentIds.sort()).toEqual([root.id, child.id].sort());
-
- for (const id of [root.id, child.id]) {
- const row = await callerA.findById(id);
- expect(row?.visibility).toBe('private');
- }
+ expect(result.documentIds).toEqual([root.id]);
+ expect((await callerA.findById(root.id))?.visibility).toBe('private');
+ expect((await callerA.findById(child.id))?.visibility).toBe('public');
});
it('refuses to flip another member’s public subtree (ownership scope filter)', async () => {
@@ -394,7 +386,7 @@ describe('DocumentModel.setVisibility', () => {
// B can see the row (it's public), but the user_id guard inside setVisibility
// makes the update a no-op. Ownership scope on collectSubtree also finds it.
const callerB = new DocumentModel(serverDB, userB, workspaceId);
- await callerB.setVisibility(ownerRoot.id, 'private');
+ await expect(callerB.setVisibility(ownerRoot.id, 'private')).rejects.toThrow(/not found/i);
const row = await callerA.findById(ownerRoot.id);
expect(row?.visibility).toBe('public');
@@ -422,10 +414,31 @@ describe('DocumentModel.setVisibility', () => {
const stillPublic = await callerA.findById(root.id);
expect(stillPublic?.visibility).toBe('public');
});
+
+ it('refuses to flip a workspace document from a personal (no-workspace) context', async () => {
+ const callerA = new DocumentModel(serverDB, userA, workspaceId);
+ const root = await callerA.create({
+ fileType: 'custom/folder',
+ source: '',
+ sourceType: 'api',
+ title: 'ws-scoped-root',
+ totalCharCount: 0,
+ totalLineCount: 0,
+ });
+
+ // Same user, but personal scope (workspace_id IS NULL) — ownership() must
+ // exclude the workspace row so a wrong-context request can't bypass the
+ // workspace's RBAC / resource_permissions flow.
+ const personalCaller = new DocumentModel(serverDB, userA);
+ await expect(personalCaller.setVisibility(root.id, 'public')).rejects.toThrow(/not found/i);
+
+ const row = await callerA.findById(root.id);
+ expect(row?.visibility).toBe('private');
+ });
});
-describe('DocumentModel.update — workspace parent-id move guard', () => {
- it('rejects moving a private document under a workspace parent (use publish instead)', async () => {
+describe('DocumentModel.update — independent parent visibility', () => {
+ it('allows moving a private document under a public parent', async () => {
const callerA = new DocumentModel(serverDB, userA, workspaceId);
const privateRoot = await callerA.create({
fileType: 'custom/folder',
@@ -445,12 +458,13 @@ describe('DocumentModel.update — workspace parent-id move guard', () => {
visibility: 'public',
});
- await expect(callerA.update(privateRoot.id, { parentId: publicRoot.id })).rejects.toThrow(
- /publishToWorkspace/,
- );
+ await expect(
+ callerA.update(privateRoot.id, { parentId: publicRoot.id }),
+ ).resolves.toBeDefined();
+ expect((await callerA.findById(privateRoot.id))?.visibility).toBe('private');
});
- it('rejects moving a workspace document under a private parent (no demote)', async () => {
+ it('allows moving a public document under a private parent', async () => {
const callerA = new DocumentModel(serverDB, userA, workspaceId);
const privateRoot = await callerA.create({
fileType: 'custom/folder',
@@ -470,9 +484,10 @@ describe('DocumentModel.update — workspace parent-id move guard', () => {
visibility: 'public',
});
- await expect(callerA.update(publicRoot.id, { parentId: privateRoot.id })).rejects.toThrow(
- /demoting/i,
- );
+ await expect(
+ callerA.update(publicRoot.id, { parentId: privateRoot.id }),
+ ).resolves.toBeDefined();
+ expect((await callerA.findById(publicRoot.id))?.visibility).toBe('public');
});
it('allows moving within the same visibility bucket', async () => {
diff --git a/packages/database/src/models/__tests__/resourcePermission.test.ts b/packages/database/src/models/__tests__/resourcePermission.test.ts
new file mode 100644
index 00000000000..aa628db3e86
--- /dev/null
+++ b/packages/database/src/models/__tests__/resourcePermission.test.ts
@@ -0,0 +1,111 @@
+// @vitest-environment node
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../core/getTestDB';
+import {
+ isResourceAccessLevelAllowed,
+ resourcePermissions,
+ users,
+ workspaces,
+} from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+import { ResourcePermissionModel } from '../resourcePermission';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const ownerId = 'rp-test-owner';
+const wsId = 'rp-test-ws';
+const wsId2 = 'rp-test-ws-2';
+const agentId = 'rp-test-agent';
+
+const model = new ResourcePermissionModel(serverDB, wsId);
+
+beforeEach(async () => {
+ await serverDB.delete(users);
+ await serverDB.delete(workspaces);
+ await serverDB.insert(users).values([{ fullName: 'Owner', id: ownerId }]);
+ await serverDB.insert(workspaces).values([
+ { id: wsId, name: 'WS', primaryOwnerId: ownerId, slug: 'rp-ws' },
+ { id: wsId2, name: 'WS2', primaryOwnerId: ownerId, slug: 'rp-ws-2' },
+ ]);
+});
+
+afterEach(async () => {
+ await serverDB.delete(resourcePermissions);
+ await serverDB.delete(workspaces);
+ await serverDB.delete(users);
+});
+
+describe('ResourcePermissionModel', () => {
+ it.each([
+ ['agent', 'use'],
+ ['agentGroup', 'use'],
+ ['document', 'view'],
+ ] as const)(
+ 'falls back to %s-specific default %s without a row',
+ async (resourceType, expected) => {
+ expect(await model.getAccessLevel(resourceType, agentId)).toBeNull();
+ expect(await model.getEffectiveAccessLevel(resourceType, agentId)).toBe(expected);
+ },
+ );
+
+ it.each([
+ ['agent', 'view'],
+ ['agent', 'use'],
+ ['agent', 'edit'],
+ ['agentGroup', 'view'],
+ ['agentGroup', 'use'],
+ ['agentGroup', 'edit'],
+ ['document', 'view'],
+ ['document', 'edit'],
+ ] as const)('explicitly stores %s %s access', async (resourceType, accessLevel) => {
+ await model.setAccessLevel(resourceType, agentId, accessLevel, ownerId);
+
+ expect(await model.getAccessLevel(resourceType, agentId)).toBe(accessLevel);
+ expect(await model.getEffectiveAccessLevel(resourceType, agentId)).toBe(accessLevel);
+ });
+
+ it.each([
+ ['agent', 'use', true],
+ ['agent', 'view', true],
+ ['agentGroup', 'use', true],
+ ['agentGroup', 'view', true],
+ ['document', 'view', true],
+ ['document', 'use', false],
+ ] as const)('validates %s %s as %s', (resourceType, accessLevel, expected) => {
+ expect(isResourceAccessLevelAllowed(resourceType, accessLevel)).toBe(expected);
+ });
+
+ it('keeps an explicit row when setting edit', async () => {
+ await model.setAccessLevel('agent', agentId, 'use', ownerId);
+ await model.setAccessLevel('agent', agentId, 'edit', ownerId);
+
+ expect(await model.getAccessLevel('agent', agentId)).toBe('edit');
+ const rows = await serverDB.select().from(resourcePermissions);
+ expect(rows).toHaveLength(1);
+ });
+
+ it('set is idempotent and updates the access level on conflict', async () => {
+ await model.setAccessLevel('agent', agentId, 'edit', ownerId);
+ await model.setAccessLevel('agent', agentId, 'use', ownerId);
+
+ expect(await model.getAccessLevel('agent', agentId)).toBe('use');
+ const rows = await serverDB.select().from(resourcePermissions);
+ expect(rows).toHaveLength(1);
+ });
+
+ it('is isolated per workspace and per resource type', async () => {
+ await model.setAccessLevel('agent', agentId, 'use', ownerId);
+
+ const otherWs = new ResourcePermissionModel(serverDB, wsId2);
+ expect(await otherWs.getAccessLevel('agent', agentId)).toBeNull();
+ expect(await model.getAccessLevel('agentGroup', agentId)).toBeNull();
+ });
+
+ it('removeAll clears every row of a resource', async () => {
+ await model.setAccessLevel('agent', agentId, 'use', ownerId);
+ await model.removeAll('agent', agentId);
+
+ expect(await model.getAccessLevel('agent', agentId)).toBeNull();
+ });
+});
diff --git a/packages/database/src/models/__tests__/session.test.ts b/packages/database/src/models/__tests__/session.test.ts
index 7d5bad75d95..f1ef42b6a68 100644
--- a/packages/database/src/models/__tests__/session.test.ts
+++ b/packages/database/src/models/__tests__/session.test.ts
@@ -671,6 +671,30 @@ describe('SessionModel', () => {
expect(await serverDB.select().from(sessions).where(eq(sessions.id, '1'))).toHaveLength(0);
expect(await serverDB.select().from(sessions).where(eq(sessions.id, '2'))).toHaveLength(1);
});
+
+ it('should report orphan-deleted agent ids so callers can clean permission rows', async () => {
+ await serverDB.insert(sessions).values([
+ { id: '1', userId },
+ { id: '2', userId },
+ ]);
+ await serverDB.insert(agents).values([
+ { id: 'orphaned', userId },
+ { id: 'still-linked', userId },
+ ]);
+ await serverDB.insert(agentsToSessions).values([
+ { agentId: 'orphaned', sessionId: '1', userId },
+ { agentId: 'still-linked', sessionId: '1', userId },
+ { agentId: 'still-linked', sessionId: '2', userId },
+ ]);
+
+ const { orphanedAgentIds } = await sessionModel.delete('1');
+
+ expect(orphanedAgentIds).toEqual(['orphaned']);
+ expect(await serverDB.select().from(agents).where(eq(agents.id, 'orphaned'))).toHaveLength(0);
+ expect(
+ await serverDB.select().from(agents).where(eq(agents.id, 'still-linked')),
+ ).toHaveLength(1);
+ });
});
describe('batchDelete', () => {
diff --git a/packages/database/src/models/__tests__/workspaceUserSettings.test.ts b/packages/database/src/models/__tests__/workspaceUserSettings.test.ts
index 96db31e85af..76377162a5a 100644
--- a/packages/database/src/models/__tests__/workspaceUserSettings.test.ts
+++ b/packages/database/src/models/__tests__/workspaceUserSettings.test.ts
@@ -93,20 +93,45 @@ describe('WorkspaceUserSettingsModel', () => {
});
});
+ it('deep-merges agentModelOverrides so a single-agent patch never drops other agents', async () => {
+ const model = new WorkspaceUserSettingsModel(serverDB, userA, workspaceId);
+ await model.updatePreference({
+ agentModelOverrides: {
+ agentX: { model: 'model-x', provider: 'provider-x' },
+ },
+ });
+
+ await model.updatePreference({
+ agentModelOverrides: {
+ agentY: { model: 'model-y', provider: 'provider-y' },
+ },
+ });
+
+ const preference = await model.getPreference();
+ expect(preference.agentModelOverrides).toEqual({
+ agentX: { model: 'model-x', provider: 'provider-x' },
+ agentY: { model: 'model-y', provider: 'provider-y' },
+ });
+ });
+
it("isolates users' rows so one caller can never observe another's preference", async () => {
const modelA = new WorkspaceUserSettingsModel(serverDB, userA, workspaceId);
const modelB = new WorkspaceUserSettingsModel(serverDB, userB, workspaceId);
await modelA.updatePreference({
agentDeviceOverrides: { shared: { boundDeviceId: 'A-device', executionTarget: 'device' } },
+ agentModelOverrides: { shared: { model: 'A-model', provider: 'A-provider' } },
});
await modelB.updatePreference({
agentDeviceOverrides: { shared: { boundDeviceId: 'B-device', executionTarget: 'device' } },
+ agentModelOverrides: { shared: { model: 'B-model', provider: 'B-provider' } },
});
const [prefA, prefB] = await Promise.all([modelA.getPreference(), modelB.getPreference()]);
expect(prefA.agentDeviceOverrides?.shared?.boundDeviceId).toBe('A-device');
expect(prefB.agentDeviceOverrides?.shared?.boundDeviceId).toBe('B-device');
+ expect(prefA.agentModelOverrides?.shared?.model).toBe('A-model');
+ expect(prefB.agentModelOverrides?.shared?.model).toBe('B-model');
});
it('cascades on workspace delete — FK removes every row for that workspace', async () => {
diff --git a/packages/database/src/models/agent.ts b/packages/database/src/models/agent.ts
index 96cb49972f0..5a3e419d68a 100644
--- a/packages/database/src/models/agent.ts
+++ b/packages/database/src/models/agent.ts
@@ -204,6 +204,58 @@ export class AgentModel {
}
};
+ /**
+ * A fixed workspace agent is a shared execution contract. It may use any
+ * server-resolvable shared target; a concrete device additionally has to be
+ * public in the same workspace. Use one generic device error for
+ * missing/private/cross-workspace rows so the write path never reveals a
+ * device the caller cannot otherwise see.
+ */
+ private assertFixedExecutionTarget = async (
+ agentWorkspaceId: string | null,
+ agencyConfig: LobeAgentAgencyConfig | null | undefined,
+ ): Promise<void> => {
+ if (!agentWorkspaceId || agencyConfig?.executionTargetSelectionPolicy !== 'fixed') return;
+
+ if (
+ !agencyConfig.executionTarget ||
+ !['auto', 'device', 'none', 'sandbox'].includes(agencyConfig.executionTarget)
+ ) {
+ throw new TRPCError({
+ cause: { data: { code: 'FixedAgentRequiresSharedExecutionTarget' } },
+ code: 'BAD_REQUEST',
+ message: 'A fixed workspace agent requires a shared execution target.',
+ });
+ }
+
+ if (agencyConfig.executionTarget !== 'device') return;
+
+ if (!agencyConfig.boundDeviceId) {
+ throw new TRPCError({
+ cause: { data: { code: 'FixedAgentRequiresDeviceTarget' } },
+ code: 'BAD_REQUEST',
+ message: 'A fixed device target requires a bound device.',
+ });
+ }
+
+ const row = await this.db.query.devices.findFirst({
+ columns: { deviceId: true },
+ where: and(
+ eq(devices.workspaceId, agentWorkspaceId),
+ eq(devices.deviceId, agencyConfig.boundDeviceId),
+ eq(devices.visibility, 'public'),
+ ),
+ });
+
+ if (!row) {
+ throw new TRPCError({
+ cause: { data: { code: 'FixedAgentRequiresPublicWorkspaceDevice' } },
+ code: 'PRECONDITION_FAILED',
+ message: 'A fixed workspace agent requires a public device from the same workspace.',
+ });
+ }
+ };
+
getAgentConfigById = async (id: string) => {
const agent = await this.db.query.agents.findFirst({
where: and(eq(agents.id, id), this.ownership()),
@@ -755,6 +807,7 @@ export class AgentModel {
*/
create = async (config: Partial<AgentItem>): Promise<AgentItem> => {
await this.assertWorkspaceDeviceBinding(this.workspaceId ?? null, config.agencyConfig);
+ await this.assertFixedExecutionTarget(this.workspaceId ?? null, config.agencyConfig);
const [result] = await this.db
.insert(agents)
@@ -779,6 +832,13 @@ export class AgentModel {
batchCreate = async (configs: Partial<AgentItem>[]): Promise<AgentItem[]> => {
if (configs.length === 0) return [];
+ await Promise.all(
+ configs.flatMap((config) => [
+ this.assertWorkspaceDeviceBinding(this.workspaceId ?? null, config.agencyConfig),
+ this.assertFixedExecutionTarget(this.workspaceId ?? null, config.agencyConfig),
+ ]),
+ );
+
return this.db
.insert(agents)
.values(
@@ -839,7 +899,26 @@ export class AgentModel {
* one with these authorization rules.
*/
publishToWorkspace = async (agentId: string) => {
- return this.db
+ const agent = await this.db.query.agents.findFirst({
+ columns: { agencyConfig: true, workspaceId: true },
+ where: and(
+ eq(agents.id, agentId),
+ this.ownership(),
+ eq(agents.userId, this.userId),
+ eq(agents.visibility, 'private'),
+ ),
+ });
+
+ if (!agent) {
+ throw new Error('Agent not found, already published, or access denied');
+ }
+
+ // Re-check at the publication boundary. A legacy/stale fixed target may
+ // predate the config-write guard; a concrete device must never be exposed
+ // when workspace members cannot resolve it.
+ await this.assertFixedExecutionTarget(agent.workspaceId, agent.agencyConfig);
+
+ const [result] = await this.db
.update(agents)
.set({ updatedAt: new Date(), visibility: 'public' })
.where(
@@ -849,7 +928,14 @@ export class AgentModel {
eq(agents.userId, this.userId),
eq(agents.visibility, 'private'),
),
- );
+ )
+ .returning();
+
+ if (!result) {
+ throw new Error('Agent not found, already published, or access denied');
+ }
+
+ return result;
};
/**
@@ -892,11 +978,22 @@ export class AgentModel {
// would be emitted nowhere and vanish from the sidebar. Rehome it to the
// ungrouped section of its new scope when the group no longer matches.
const [current] = await this.db
- .select({ groupVisibility: sessionGroups.visibility })
+ .select({
+ agencyConfig: agents.agencyConfig,
+ groupVisibility: sessionGroups.visibility,
+ workspaceId: agents.workspaceId,
+ })
.from(agents)
.leftJoin(sessionGroups, eq(agents.sessionGroupId, sessionGroups.id))
.where(and(eq(agents.id, agentId), this.ownership()))
.limit(1);
+
+ // `publishAgentToWorkspace` is the normal client path, but keep the
+ // bidirectional visibility mutation equally safe for direct API callers.
+ if (visibility === 'public' && current) {
+ await this.assertFixedExecutionTarget(current.workspaceId, current.agencyConfig);
+ }
+
const groupVisibility = current?.groupVisibility as 'private' | 'public' | null | undefined;
const clearGroup = groupVisibility != null && groupVisibility !== visibility;
@@ -1012,6 +1109,8 @@ export class AgentModel {
// `undefined`, which merge() skips — prune those keys so the delete persists.
pruneWorkingDirByDeviceDeletes(mergedValue.agencyConfig, data.agencyConfig);
+ await this.assertFixedExecutionTarget(agent.workspaceId, mergedValue.agencyConfig);
+
// Final cleanup: ensure no undefined or null values enter the database
if (mergedValue.params) {
const params = mergedValue.params as Record<string, any>;
@@ -1333,8 +1432,42 @@ export class AgentModel {
}
cleaned.workingDirByDevice = Object.keys(filtered).length > 0 ? filtered : undefined;
}
+ if (
+ cleaned.executionTargetSelectionPolicy === 'fixed' &&
+ cleaned.executionTarget === 'device' &&
+ (!cleaned.boundDeviceId || !allowed.has(cleaned.boundDeviceId))
+ ) {
+ cleaned.executionTargetSelectionPolicy = 'member';
+ }
nextAgencyConfig = cleaned;
}
+
+ if (
+ nextAgencyConfig.executionTargetSelectionPolicy === 'fixed' &&
+ (!nextAgencyConfig.executionTarget ||
+ !['auto', 'device', 'none', 'sandbox'].includes(nextAgencyConfig.executionTarget))
+ ) {
+ nextAgencyConfig.executionTargetSelectionPolicy = 'member';
+ }
+
+ if (
+ nextAgencyConfig.executionTargetSelectionPolicy === 'fixed' &&
+ nextAgencyConfig.executionTarget === 'device'
+ ) {
+ if (!nextAgencyConfig.boundDeviceId) {
+ nextAgencyConfig.executionTargetSelectionPolicy = 'member';
+ } else {
+ const publicDevice = await trx.query.devices.findFirst({
+ columns: { deviceId: true },
+ where: and(
+ eq(devices.workspaceId, targetWorkspaceId),
+ eq(devices.deviceId, nextAgencyConfig.boundDeviceId),
+ eq(devices.visibility, 'public'),
+ ),
+ });
+ if (!publicDevice) nextAgencyConfig.executionTargetSelectionPolicy = 'member';
+ }
+ }
}
// 4. Update the agent record.
diff --git a/packages/database/src/models/chatGroup.ts b/packages/database/src/models/chatGroup.ts
index b29f5b191d2..00e8d2dbd49 100644
--- a/packages/database/src/models/chatGroup.ts
+++ b/packages/database/src/models/chatGroup.ts
@@ -7,7 +7,7 @@ import type {
NewChatGroup,
NewChatGroupAgent,
} from '../schemas';
-import { agents, chatGroups, chatGroupsAgents } from '../schemas';
+import { agents, chatGroups, chatGroupsAgents, sessionGroups } from '../schemas';
import type { LobeChatDatabase } from '../type';
import { normalizeInboxAgentAvatar } from '../utils/inboxAgent';
import { buildWorkspacePayload, buildWorkspaceWhere } from '../utils/workspace';
@@ -282,6 +282,64 @@ export class ChatGroupModel {
return result;
}
+ /**
+ * Bidirectional visibility switch for the Permission panel. Router-level
+ * guards decide who may call this (creator-only demotion, manager/owner
+ * promotion) — this method only applies the ownership-scoped write.
+ *
+ * Mirrors AgentModel.setVisibility: a sidebar folder cannot mix
+ * visibilities, so the group is rehomed to the ungrouped section of its new
+ * scope when its folder no longer matches.
+ */
+ async setVisibility(id: string, visibility: 'private' | 'public'): Promise<ChatGroupItem | null> {
+ const [current] = await this.db
+ .select({ folderVisibility: sessionGroups.visibility })
+ .from(chatGroups)
+ .leftJoin(sessionGroups, eq(chatGroups.groupId, sessionGroups.id))
+ .where(and(eq(chatGroups.id, id), this.ownership()))
+ .limit(1);
+ const folderVisibility = current?.folderVisibility as 'private' | 'public' | null | undefined;
+ const clearFolder = folderVisibility != null && folderVisibility !== visibility;
+
+ const [updated] = await this.db
+ .update(chatGroups)
+ .set({
+ updatedAt: new Date(),
+ visibility,
+ ...(clearFolder ? { groupId: null } : {}),
+ })
+ .where(and(eq(chatGroups.id, id), this.ownership()))
+ .returning();
+
+ if (updated) {
+ // Keep the synthetic supervisor's visibility in lockstep (mirrors
+ // publishToWorkspace): a promoted group must expose its supervisor to
+ // members, a demoted group must not leave the supervisor public.
+ await this.db
+ .update(agents)
+ .set({ updatedAt: new Date(), visibility })
+ .where(
+ and(
+ ne(agents.visibility, visibility),
+ inArray(
+ agents.id,
+ this.db
+ .select({ id: chatGroupsAgents.agentId })
+ .from(chatGroupsAgents)
+ .where(
+ and(
+ eq(chatGroupsAgents.chatGroupId, id),
+ eq(chatGroupsAgents.role, 'supervisor'),
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+
+ return updated ?? null;
+ }
+
async addAgentToGroup(
groupId: string,
agentId: string,
@@ -522,6 +580,26 @@ export class ChatGroupModel {
.orderBy(chatGroupsAgents.order, chatGroupsAgents.createdAt, chatGroupsAgents.agentId);
}
+ /**
+ * Count still-private member agents of a group — the publish guard uses
+ * this to reject sharing a group whose members would leak on publish.
+ */
+ async countPrivateGroupAgents(groupId: string): Promise<number> {
+ const rows = await this.db
+ .select({ agentId: chatGroupsAgents.agentId })
+ .from(chatGroupsAgents)
+ .innerJoin(agents, eq(chatGroupsAgents.agentId, agents.id))
+ .where(
+ and(
+ eq(chatGroupsAgents.chatGroupId, groupId),
+ eq(agents.visibility, 'private'),
+ this.agentsOwnership(),
+ ),
+ );
+
+ return rows.length;
+ }
+
async getEnabledGroupAgents(groupId: string): Promise<ChatGroupAgentItem[]> {
return this.db.query.chatGroupsAgents.findMany({
orderBy: [chatGroupsAgents.order, chatGroupsAgents.createdAt, chatGroupsAgents.agentId],
diff --git a/packages/database/src/models/device.ts b/packages/database/src/models/device.ts
index 1653f630cd5..60f892e48f2 100644
--- a/packages/database/src/models/device.ts
+++ b/packages/database/src/models/device.ts
@@ -2,7 +2,7 @@ import type { WorkingDirEntry } from '@lobechat/types';
import { and, desc, eq, isNotNull, isNull, ne, sql } from 'drizzle-orm';
import type { DeviceItem } from '../schemas';
-import { devices, workspaces } from '../schemas';
+import { agents, devices, workspaces } from '../schemas';
import type { LobeChatDatabase } from '../type';
import { buildWorkspaceWhere } from '../utils/workspace';
@@ -67,6 +67,30 @@ export class DeviceModel {
this.workspaceId = workspaceId;
}
+ /**
+ * Whether this workspace device is the enforced target of any fixed agent.
+ * Returns only a boolean so device-management callers cannot infer private
+ * agent metadata from the reference guard.
+ */
+ hasFixedAgentBinding = async (deviceId: string): Promise<boolean> => {
+ if (!this.workspaceId) return false;
+
+ const [row] = await this.db
+ .select({ id: agents.id })
+ .from(agents)
+ .where(
+ and(
+ eq(agents.workspaceId, this.workspaceId),
+ sql`${agents.agencyConfig}->>'executionTargetSelectionPolicy' = 'fixed'`,
+ sql`${agents.agencyConfig}->>'executionTarget' = 'device'`,
+ sql`${agents.agencyConfig}->>'boundDeviceId' = ${deviceId}`,
+ ),
+ )
+ .limit(1);
+
+ return !!row;
+ };
+
/**
* Auto-register from desktop/CLI. Upserts on the (userId, deviceId) unique
* index. On conflict only the machine-reported fields + lastSeenAt are
diff --git a/packages/database/src/models/document.ts b/packages/database/src/models/document.ts
index 781c84028b2..b1219562ad6 100644
--- a/packages/database/src/models/document.ts
+++ b/packages/database/src/models/document.ts
@@ -77,9 +77,7 @@ export class DocumentModel {
create = async (params: Omit<NewDocument, 'userId'>): Promise<DocumentItem> => {
// Workspace-mode default for visibility:
// - explicit visibility wins
- // - else if parentId set: inherit parent's visibility (tree invariant —
- // a child must never have a visibility different from its root)
- // - else top-level user-authored Pages (`sourceType: 'api'`): default to
+ // - user-authored Pages (`sourceType: 'api'`) default to
// `'private'` so workspace members start drafts in their own space and
// publish when ready
// - all other top-level rows (web crawls, file ingests, topic snapshots,
@@ -88,13 +86,8 @@ export class DocumentModel {
// draft / publish lifecycle and were workspace-shared from day one
// Personal mode leaves it to the schema default; the filter ignores it.
let visibility = params.visibility;
- if (!visibility && this.workspaceId) {
- if (params.parentId) {
- const parent = await this.findById(params.parentId);
- visibility = parent?.visibility ?? 'private';
- } else if (params.sourceType === 'api') {
- visibility = 'private';
- }
+ if (!visibility && this.workspaceId && params.sourceType === 'api') {
+ visibility = 'private';
}
const result = (await this.db
@@ -249,24 +242,6 @@ export class DocumentModel {
// incoming value so callers can't sneak around the one-way rule.
const { visibility: _ignored, ...patch } = value;
- // Workspace-mode parent-id guard: a tree's whole subtree shares one
- // visibility (P1 strong consistency), so moving a node under a parent with
- // a different visibility would create a mixed subtree. Refuse the move and
- // point the caller at the proper one-way publish path when relevant.
- if (this.workspaceId && patch.parentId !== undefined) {
- const current = await this.findById(id);
- if (current && patch.parentId !== null) {
- const parent = await this.findById(patch.parentId);
- if (parent && parent.visibility !== current.visibility) {
- throw new Error(
- current.visibility === 'private'
- ? 'Cannot move a private document under a workspace document; use publishToWorkspace instead.'
- : 'Cannot move a workspace document under a private document; demoting to private is not allowed.',
- );
- }
- }
- }
-
return this.db
.update(documents)
.set({ ...patch, updatedAt: new Date() })
@@ -274,90 +249,51 @@ export class DocumentModel {
};
/**
- * Publish a private document subtree into the workspace. Convenience wrapper
+ * Publish one private document into the workspace. Convenience wrapper
* around `setVisibility(rootId, 'public')`; kept as a named method for the
* TRPC `publishDocumentToWorkspace` procedure and existing callers.
*
- * @returns the ids of the documents that were re-published.
+ * @returns the id of the document that was re-published.
*/
publishToWorkspace = async (rootId: string): Promise<{ documentIds: string[] }> => {
return this.setVisibility(rootId, 'public');
};
/**
- * Flip a document subtree's `visibility`. Bidirectional companion to
- * `publishToWorkspace`; both directions cascade the whole subtree so the
- * P1 tree-consistency invariant (private/public do not mix inside one tree)
- * holds after the transition.
- *
- * The `eq(user_id)` + `eq(visibility, fromVisibility)` guards keep the
- * operation creator-only and idempotent against rows that already sit at the
- * target visibility. Rows created by other workspace members inside the
- * subtree (rare — happens if a public tree gets nested workspace edits) are
- * intentionally left untouched: only the caller's own rows flip.
- *
- * Unpublishing is safe by design — after the flip, `buildWorkspaceWhere`
- * hides those rows from other members immediately; already-loaded content in
- * their client stays until they refresh.
+ * Flip one document's `visibility`. Documents do not inherit ACL or
+ * visibility from their parent: a parent may be used purely for navigation.
*/
setVisibility = async (
rootId: string,
visibility: 'private' | 'public',
): Promise<{ documentIds: string[] }> => {
- const fromVisibility = visibility === 'public' ? 'private' : 'public';
-
return this.db.transaction(async (trx) => {
- const scopedTrx = new DocumentModel(
- trx as LobeChatDatabase,
- this.userId,
- this.workspaceId,
- this.callerAgentVisibility,
- );
- const subtree = await scopedTrx.collectSubtree(rootId, trx as LobeChatDatabase);
- if (subtree.length === 0) throw new Error('Document not found');
-
- const ids = subtree.map((d) => d.id);
-
- const updatedDocuments = await (trx as LobeChatDatabase)
+ const result = await (trx as LobeChatDatabase)
.update(documents)
.set({ updatedAt: new Date(), visibility })
- .where(
- and(
- inArray(documents.id, ids),
- eq(documents.userId, this.userId),
- eq(documents.visibility, fromVisibility),
- ),
- )
+ .where(and(eq(documents.id, rootId), this.ownership(), eq(documents.userId, this.userId)))
.returning({ id: documents.id });
- const updatedDocumentIds = updatedDocuments.map(({ id }) => id);
- if (updatedDocumentIds.length > 0) {
- // Mirror visibility onto existing Work projections in the same
- // transaction. Scope without works.visibility so a promotion can
- // update rows that are currently private.
- await (trx as LobeChatDatabase)
- .update(works)
- .set({ visibility })
- .where(
- and(
- eq(works.resourceType, 'document'),
- inArray(works.resourceId, updatedDocumentIds),
- buildWorkspaceWhere(
- { userId: this.userId, workspaceId: this.workspaceId },
- { userId: works.userId, workspaceId: works.workspaceId },
- ),
- ),
- );
- }
+ if (result.length === 0) throw new Error('Document not found');
- // No child-table cascade needed here — Pages (`sourceType: 'api'`) hold
- // content inline in `documents.content` / `documents.pages`, and the
- // `document_chunks` junction has no read consumers on the RAG hot path
- // (that lane goes through `chunks` + `fileChunks` + `files`).
- // A future `document_chunks` visibility mirror + RAG filter will add
- // cascade when that lane is built.
+ // Mirror visibility onto existing Work projections in the same
+ // transaction. Scope without works.visibility so a promotion can
+ // update rows that are currently private.
+ await (trx as LobeChatDatabase)
+ .update(works)
+ .set({ visibility })
+ .where(
+ and(
+ eq(works.resourceType, 'document'),
+ eq(works.resourceId, rootId),
+ buildWorkspaceWhere(
+ { userId: this.userId, workspaceId: this.workspaceId },
+ { userId: works.userId, workspaceId: works.workspaceId },
+ ),
+ ),
+ );
- return { documentIds: ids };
+ return { documentIds: [rootId] };
});
};
@@ -449,8 +385,8 @@ export class DocumentModel {
const ids = subtree.map((d) => d.id);
const ownershipUpdate = { userId: targetUserId, workspaceId: targetWorkspaceId };
// Visibility only applies when landing in a workspace — personal scope
- // treats every row as implicitly private. Children mirror the parent's
- // visibility so the whole subtree flips together.
+ // treats every row as implicitly private. Transfer still moves the
+ // selected tree as one operation, while ordinary visibility changes do not cascade.
const visibilityUpdate =
targetWorkspaceId && targetVisibility ? { visibility: targetVisibility } : {};
diff --git a/packages/database/src/models/resourcePermission.ts b/packages/database/src/models/resourcePermission.ts
new file mode 100644
index 00000000000..b06b3c0b0a2
--- /dev/null
+++ b/packages/database/src/models/resourcePermission.ts
@@ -0,0 +1,90 @@
+import { and, eq } from 'drizzle-orm';
+
+import type { PermissionResourceType, ResourceAccessLevel } from '../schemas';
+import { getDefaultResourceAccessLevel, resourcePermissions } from '../schemas';
+import type { LobeChatDatabase } from '../type';
+
+/**
+ * Workspace-wide access policy for public resources. All methods are scoped
+ * to one workspace; the table is meaningless in personal mode.
+ */
+export class ResourcePermissionModel {
+ private db: LobeChatDatabase;
+ private workspaceId: string;
+
+ constructor(db: LobeChatDatabase, workspaceId: string) {
+ this.db = db;
+ this.workspaceId = workspaceId;
+ }
+
+ private accessMatch = (resourceType: PermissionResourceType, resourceId: string) =>
+ and(
+ eq(resourcePermissions.workspaceId, this.workspaceId),
+ eq(resourcePermissions.resourceType, resourceType),
+ eq(resourcePermissions.resourceId, resourceId),
+ );
+
+ /** The explicitly stored Workspace access level, if one exists. */
+ getAccessLevel = async (
+ resourceType: PermissionResourceType,
+ resourceId: string,
+ ): Promise<ResourceAccessLevel | null> => {
+ const [row] = await this.db
+ .select({ accessLevel: resourcePermissions.accessLevel })
+ .from(resourcePermissions)
+ .where(this.accessMatch(resourceType, resourceId))
+ .limit(1);
+
+ return row?.accessLevel ?? null;
+ };
+
+ /** Resolve a missing row through the resource-specific Workspace default. */
+ getEffectiveAccessLevel = async (
+ resourceType: PermissionResourceType,
+ resourceId: string,
+ ): Promise<ResourceAccessLevel> => {
+ return (
+ (await this.getAccessLevel(resourceType, resourceId)) ??
+ getDefaultResourceAccessLevel(resourceType)
+ );
+ };
+
+ /** Explicitly persist the Workspace access level for a public resource. */
+ setAccessLevel = async (
+ resourceType: PermissionResourceType,
+ resourceId: string,
+ accessLevel: ResourceAccessLevel,
+ createdBy: string,
+ ) => {
+ await this.db
+ .insert(resourcePermissions)
+ .values({
+ createdBy,
+ resourceId,
+ resourceType,
+ accessLevel,
+ workspaceId: this.workspaceId,
+ })
+ .onConflictDoUpdate({
+ set: { accessLevel, createdBy, updatedAt: new Date() },
+ target: [
+ resourcePermissions.workspaceId,
+ resourcePermissions.resourceType,
+ resourcePermissions.resourceId,
+ ],
+ });
+ };
+
+ /** Remove every permission row of a resource, e.g. when it is deleted. */
+ removeAll = async (resourceType: PermissionResourceType, resourceId: string) => {
+ await this.db
+ .delete(resourcePermissions)
+ .where(
+ and(
+ eq(resourcePermissions.workspaceId, this.workspaceId),
+ eq(resourcePermissions.resourceType, resourceType),
+ eq(resourcePermissions.resourceId, resourceId),
+ ),
+ );
+ };
+}
diff --git a/packages/database/src/models/session.ts b/packages/database/src/models/session.ts
index 55b224e59c6..0d912bfb0bd 100644
--- a/packages/database/src/models/session.ts
+++ b/packages/database/src/models/session.ts
@@ -382,9 +382,9 @@ export class SessionModel {
const result = await trx.delete(sessions).where(and(eq(sessions.id, id), this.ownership()));
// Delete orphaned agents
- await this.clearOrphanAgent(agentIds, trx);
+ const orphanedAgentIds = await this.clearOrphanAgent(agentIds, trx);
- return result;
+ return { orphanedAgentIds, result };
});
};
@@ -392,7 +392,7 @@ export class SessionModel {
* Batch delete sessions and their associated agent data if no longer referenced.
*/
batchDelete = async (ids: string[]) => {
- if (ids.length === 0) return { count: 0 };
+ if (ids.length === 0) return { orphanedAgentIds: [] as string[], result: { count: 0 } };
return this.db.transaction(async (trx) => {
// Get agent IDs associated with these sessions
@@ -414,9 +414,9 @@ export class SessionModel {
.where(and(inArray(sessions.id, ids), this.ownership()));
// Delete orphaned agents
- await this.clearOrphanAgent(agentIds, trx);
+ const orphanedAgentIds = await this.clearOrphanAgent(agentIds, trx);
- return result;
+ return { orphanedAgentIds, result };
});
};
@@ -431,8 +431,8 @@ export class SessionModel {
});
};
- clearOrphanAgent = async (agentIds: string[], trx: any) => {
- if (agentIds.length === 0) return;
+ clearOrphanAgent = async (agentIds: string[], trx: any): Promise<string[]> => {
+ if (agentIds.length === 0) return [];
// Batch query to find which agents still have sessions
const remainingLinks = (await trx
@@ -452,6 +452,8 @@ export class SessionModel {
.delete(agents)
.where(and(inArray(agents.id, orphanedAgentIds), this.agentsOwnership()));
}
+
+ return orphanedAgentIds;
};
// **************** Update *************** //
diff --git a/packages/database/src/models/workspaceUserSettings.ts b/packages/database/src/models/workspaceUserSettings.ts
index 5fd24f7c244..29890dc96bc 100644
--- a/packages/database/src/models/workspaceUserSettings.ts
+++ b/packages/database/src/models/workspaceUserSettings.ts
@@ -68,11 +68,11 @@ export class WorkspaceUserSettingsModel {
*/
updatePreference = async (patch: Partial<WorkspaceUserPreference>) => {
const current = (await this.getPreference()) ?? {};
- // `agentDeviceOverrides` merges one level deeper: clients patch a single
- // agent's override built from their LOCAL copy of the map, which may be
- // stale or empty (picker used before the preference fetch settled), and a
- // top-level replace would silently drop this user's saved choices for
- // every other agent. Individual per-agent entries still replace wholesale.
+ // Per-agent override maps merge one level deeper: clients patch a single
+ // agent's leaf from a local copy that may be stale or empty (for example a
+ // picker used before the preference fetch settles). A top-level replace
+ // would silently drop this user's choices for every other agent.
+ // Individual per-agent entries still replace wholesale.
const next: WorkspaceUserPreference = {
...current,
...patch,
@@ -84,6 +84,14 @@ export class WorkspaceUserSettingsModel {
},
}
: {}),
+ ...(patch.agentModelOverrides
+ ? {
+ agentModelOverrides: {
+ ...current.agentModelOverrides,
+ ...patch.agentModelOverrides,
+ },
+ }
+ : {}),
};
const [row] = await this.db
.insert(workspaceUserSettings)
diff --git a/packages/database/src/repositories/home/index.ts b/packages/database/src/repositories/home/index.ts
index f8cd4881ddd..d011c2aa3aa 100644
--- a/packages/database/src/repositories/home/index.ts
+++ b/packages/database/src/repositories/home/index.ts
@@ -282,7 +282,7 @@ export class HomeRepository {
}),
...chatGroupItems.map((g): EnrichedItem => ({
// If group has custom avatar, use it (string); otherwise fallback to member avatars (array)
- avatar: g.avatar ? g.avatar : (memberAvatarsMap.get(g.id) ?? null),
+ avatar: g.avatar || (memberAvatarsMap.get(g.id) ?? null),
backgroundColor: g.backgroundColor,
description: g.description,
groupAvatar: g.avatar,
@@ -295,6 +295,7 @@ export class HomeRepository {
type: 'group' as const,
unreadCount: groupUnread.get(g.id) ?? 0,
updatedAt: g.updatedAt,
+ userId: g.groupUserId,
visibility: g.visibility,
})),
];
@@ -387,6 +388,8 @@ export class HomeRepository {
slug: agents.slug,
title: agents.title,
updatedAt: agents.updatedAt,
+ userId: agents.userId,
+ visibility: agents.visibility,
})
.from(agents)
.leftJoin(agentsToSessions, eq(agents.id, agentsToSessions.agentId))
@@ -409,6 +412,8 @@ export class HomeRepository {
pinned: chatGroups.pinned,
title: chatGroups.title,
updatedAt: chatGroups.updatedAt,
+ userId: chatGroups.userId,
+ visibility: chatGroups.visibility,
})
.from(chatGroups)
.where(
@@ -443,11 +448,13 @@ export class HomeRepository {
title: meta.title,
type: 'agent' as const,
updatedAt: a.updatedAt,
+ userId: a.userId,
+ visibility: a.visibility,
});
}),
...chatGroupResults.map((g) =>
cleanObject({
- avatar: g.avatar ? g.avatar : (memberAvatarsMap.get(g.id) ?? null),
+ avatar: g.avatar || (memberAvatarsMap.get(g.id) ?? null),
backgroundColor: g.backgroundColor,
description: g.description,
id: g.id,
@@ -455,6 +462,8 @@ export class HomeRepository {
title: g.title,
type: 'group' as const,
updatedAt: g.updatedAt,
+ userId: g.userId,
+ visibility: g.visibility,
}),
),
] as SidebarAgentItem[];
diff --git a/packages/database/src/schemas/resourcePermission.ts b/packages/database/src/schemas/resourcePermission.ts
index ef6407bb005..beb312d4ce2 100644
--- a/packages/database/src/schemas/resourcePermission.ts
+++ b/packages/database/src/schemas/resourcePermission.ts
@@ -14,12 +14,12 @@ export type PermissionResourceType = (typeof PERMISSION_RESOURCE_TYPES)[number];
/**
* Workspace-wide access levels for a public resource:
- * - Agent / Agent Group: `use` or `edit`
+ * - Agent / Agent Group: `view`, `use`, or `edit`
* - Document: `view` or `edit`
*
* `use` grants chat execution without configuration access. `view` is the
- * document-only read state. `edit` grants collaborative content/configuration
- * editing but never resource ownership or permission management.
+ * read-only state. `edit` grants collaborative content/configuration editing
+ * but never resource ownership or permission management.
* Permission management is deliberately not an access level: it is derived
* from creator ownership or a workspace-scoped `:all` RBAC capability.
*/
@@ -27,8 +27,8 @@ export const RESOURCE_ACCESS_LEVELS = ['view', 'use', 'edit'] as const;
export type ResourceAccessLevel = (typeof RESOURCE_ACCESS_LEVELS)[number];
export const RESOURCE_ACCESS_LEVELS_BY_TYPE = {
- agent: ['use', 'edit'],
- agentGroup: ['use', 'edit'],
+ agent: ['view', 'use', 'edit'],
+ agentGroup: ['view', 'use', 'edit'],
document: ['view', 'edit'],
} as const satisfies Record<PermissionResourceType, readonly ResourceAccessLevel[]>;
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index 1a172024ad2..44cab6eb712 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -38,6 +38,10 @@ export default {
'agentDocument.openAsPage': 'Open as full page',
'agentNotFound.desc':
'This agent does not exist or is no longer accessible — it may have been deleted or set to private by its owner.',
+ 'permission.configAccess.agentChatOnly':
+ 'Only collaborators with Can edit can configure this Agent. You were returned to chat.',
+ 'permission.configAccess.groupChatOnly':
+ 'Only collaborators with Can edit can configure this Agent Group. You were returned to chat.',
'agentNotFound.title': 'Agent Unavailable',
'groupNotFound.desc':
'This group does not exist or is no longer accessible — it may have been deleted or set to private by its owner.',
@@ -402,8 +406,10 @@ export default {
'heteroAgent.executionTarget.auto': 'Auto',
'heteroAgent.executionTarget.autoDesc':
'Use an online device automatically, picking one when several are available',
+ 'heteroAgent.executionTarget.fixedTip':
+ 'This Agent uses an execution environment fixed by its editor. Ask an editor to change it.',
'heteroAgent.executionTarget.infoTooltip':
- 'Pick a device and the agent uses it as its runtime environment — reading and writing files and operating the computer. Cloud sandbox is provided by LobeHub Marketplace.',
+ 'Choose where this Agent runs. A device can read and write files or operate a computer; Cloud Sandbox runs in an isolated temporary environment.',
'heteroAgent.executionTarget.gateway': 'Gateway',
'heteroAgent.executionTarget.gatewayDesc':
'Run through the device gateway so other clients can follow progress',
@@ -426,7 +432,7 @@ export default {
'heteroAgent.executionTarget.downloadDesktop': 'Get Desktop App',
'heteroAgent.executionTarget.downloadDesktopDesc': 'Run agents with access to your computer',
'heteroAgent.executionTarget.downloadDesktopTitle': 'Get the desktop app',
- 'heteroAgent.executionTarget.title': 'Execution Device',
+ 'heteroAgent.executionTarget.title': 'Execution Environment',
'heteroAgent.executionTarget.unknownDevice': 'Unknown device',
'hideForYou':
"Direct message content is hidden. Please enable 'Show Direct Message Content' in settings to view.",
@@ -457,6 +463,10 @@ export default {
'input.inputCompletionError.title': 'Input suggestions paused',
'input.modelUnavailable':
'The current model is no longer available. Choose another model to continue.',
+ 'input.viewOnlyAgent':
+ 'You have view-only access to this agent, so messages cannot be sent. Ask the creator or a workspace owner for access.',
+ 'input.viewOnlyGroup':
+ 'You have view-only access to this group, so messages cannot be sent. Ask the creator or a workspace owner for access.',
'input.heteroPlus.tooltip': 'Formatting and scheduling',
'input.more': 'More',
'input.schedule.cancel': 'Cancel',
@@ -734,6 +744,8 @@ export default {
'newPlatformAgent': 'Connect Agent',
'newGroupChat': 'Create Group',
'agent.publishToWorkspace': 'Publish to Workspace',
+ 'agent.publishToWorkspaceErrorFixedPrivateDevice':
+ 'Publish the fixed device to the workspace, or let members choose a device, before publishing this Agent.',
'agent.publishToWorkspaceSuccess': 'Published to workspace',
'resources.publishToWorkspace.menu': 'Publish to Workspace',
'resources.publishToWorkspace.confirm':
diff --git a/packages/locales/src/default/common.ts b/packages/locales/src/default/common.ts
index 182f3e6d66a..ba80d54aede 100644
--- a/packages/locales/src/default/common.ts
+++ b/packages/locales/src/default/common.ts
@@ -289,6 +289,7 @@ export default {
'copy': 'Copy',
'copyFail': 'Copy failed',
'copySuccess': 'Copied',
+ 'createdAt': 'Created at {{time}}',
'saveAgentConfigFail': 'Failed to save agent settings. Your change was not applied.',
'promptTransform.action': 'Refine Idea',
'promptTransform.actions.rewrite': 'Expand Details',
@@ -436,6 +437,8 @@ export default {
'loading': 'Loading...',
'mail.business': 'Business Cooperation',
'mail.support': 'Email Support',
+ 'deleteSharedOwnerOnly':
+ "Only a workspace owner can delete this — it carries other members' conversations",
'manageOnlyCreator': 'Only the creator or a workspace owner can do this',
'operationFailed': 'Operation failed, please try again',
'addNew': 'Add new',
diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.ts
index f5500a3e7c3..b1cf47b5c4f 100644
--- a/packages/locales/src/default/setting.ts
+++ b/packages/locales/src/default/setting.ts
@@ -214,6 +214,26 @@ export default {
'agentTab.prompt': 'Agent Profile',
'agentTab.selfIteration': 'Self-Iteration',
'agentTab.tts': 'Voice Service',
+ 'permission.accessTag.useOnlyTip':
+ 'Your member permission here is "Can use" — you can view and use it, but not edit. Ask the creator or a workspace owner for edit access.',
+ 'permission.accessTag.viewOnlyTip':
+ 'Your member permission here is "Can view" — you can view it, but not use or edit. Ask the creator or a workspace owner for more access.',
+ 'permission.generalAccess.label': 'Member Permissions',
+ 'permission.generalAccess.trigger': 'Members: {{level}}',
+ 'permission.generalAccess.editable': 'Can edit',
+ 'permission.generalAccess.editableDesc': 'Members can view, use, and edit',
+ 'permission.generalAccess.editableDocumentDesc': 'Members can view and edit',
+ 'permission.generalAccess.usable': 'Can use',
+ 'permission.generalAccess.usableDesc': 'Members can view and use, but cannot edit',
+ 'permission.generalAccess.viewable': 'Can view',
+ 'permission.generalAccess.viewableDesc': 'Members can view, but cannot use or edit',
+ 'permission.generalAccess.viewableDocumentDesc': 'Members can view, but cannot edit',
+ 'permission.loadFailed': 'Failed to load permission settings',
+ 'permission.noManagePermission': 'Only the creator or a workspace owner can change permissions',
+ 'permission.saveNoEditPermission':
+ 'You have view-only access to this page, so your changes were not saved',
+ 'permission.updateError': 'Failed to update permission',
+ 'permission.viewOnlySendTip': 'You have view-only access and cannot send messages',
'agentDocuments.createSuccess': 'Documents created from template',
'agentDocuments.createWithTemplate': 'Create with this template',
'agentDocuments.columns.actions': 'Actions',
@@ -719,7 +739,16 @@ export default {
'settingAgent.agentTools.tabAgent': 'Agent Tools',
'settingAgent.agentTools.tabUser': 'User Tools',
'settingAgent.agentTools.tabWorkspace': 'Workspace Tools',
+ 'settingAgent.devicePolicy.noPublicDevice': 'No public devices',
+ 'settingAgent.devicePolicy.selectTarget': 'Select environment',
+ 'settingAgent.devicePolicy.title': 'Execution environment',
+ 'settingAgent.modelPolicy.fixedTip':
+ 'The model is fixed in Agent Profile and cannot be switched while chatting.',
+ 'settingAgent.modelPolicy.title': 'Model',
'settingAgent.runtimeConfig.title': 'Model & Tools',
+ 'settingAgent.selectionPolicy.membersCannotSwitch': "Members can't switch",
+ 'settingAgent.selectionPolicy.membersCanSwitch': 'Members can switch',
+ 'settingAgent.toolsConfig.title': 'Tools',
'settingAgent.submit': 'Update Agent',
'settingAgent.tag.desc': 'Agent tags will be displayed in the Agent Community',
'settingAgent.tag.placeholder': 'Enter tag',
@@ -2384,6 +2413,8 @@ When I am ___, I need ___
'workspace.member.manageAccess': 'Change role...',
'workspace.member.manageAccessModal.current': 'Current',
'workspace.member.manageAccessModal.failed': 'Failed to update access',
+ 'workspace.member.manageAccessModal.memberLimitReached':
+ 'This workspace has reached its {{limit}}-member limit. Add seats before changing this user to {{role}}.',
'workspace.member.manageAccessModal.save': 'Save Changes',
'workspace.member.manageAccessModal.success': 'Access updated',
'workspace.member.manageAccessModal.title': 'Change role for {{username}}',
diff --git a/packages/types/src/agent/agencyConfig.test.ts b/packages/types/src/agent/agencyConfig.test.ts
index 90ca30e2ad0..8a41c40a66d 100644
--- a/packages/types/src/agent/agencyConfig.test.ts
+++ b/packages/types/src/agent/agencyConfig.test.ts
@@ -436,6 +436,35 @@ describe('codex speed mode', () => {
});
describe('resolveAgencyConfig', () => {
+ it('ignores a member override when the shared execution target is fixed', () => {
+ const shared = {
+ boundDeviceId: 'fixed-device',
+ executionTargetSelectionPolicy: 'fixed' as const,
+ executionTarget: 'device' as const,
+ };
+
+ expect(
+ resolveAgencyConfig(shared, {
+ boundDeviceId: 'member-device',
+ executionTarget: 'sandbox',
+ }),
+ ).toEqual(shared);
+ });
+
+ it('keeps a fixed non-device target when a member requests a device', () => {
+ const shared = {
+ executionTarget: 'sandbox' as const,
+ executionTargetSelectionPolicy: 'fixed' as const,
+ };
+
+ expect(
+ resolveAgencyConfig(shared, {
+ boundDeviceId: 'member-device',
+ executionTarget: 'device',
+ }),
+ ).toEqual(shared);
+ });
+
it('returns the shared config unchanged when override is null / undefined', () => {
const shared = { boundDeviceId: 'ws-device', executionTarget: 'device' as const };
expect(resolveAgencyConfig(shared, undefined)).toEqual(shared);
diff --git a/packages/types/src/agent/agencyConfig.ts b/packages/types/src/agent/agencyConfig.ts
index 243dee9e1bd..1770af754ab 100644
--- a/packages/types/src/agent/agencyConfig.ts
+++ b/packages/types/src/agent/agencyConfig.ts
@@ -588,6 +588,25 @@ export const buildHeteroExecArgs = (
*/
export type DeviceExecutionTarget = 'auto' | 'device' | 'local' | 'none' | 'sandbox';
+/**
+ * Whether a workspace member may override the agent's shared execution target.
+ *
+ * - `member`: the shared config is a default; each member may override it
+ * - `fixed`: every caller must use the shared execution target
+ *
+ * Missing values intentionally resolve as `member` for backwards compatibility.
+ */
+export type ExecutionTargetSelectionPolicy = 'fixed' | 'member';
+
+/**
+ * Controls whether a workspace agent always uses its shared model or lets
+ * each member choose a personal model for that agent.
+ *
+ * Missing values intentionally resolve to `fixed` for backwards
+ * compatibility: existing shared agents keep the model their author chose.
+ */
+export type AgentModelSelectionPolicy = 'fixed' | 'member';
+
/**
* Agent agency configuration.
* Contains settings for agent execution modes and device binding.
@@ -605,7 +624,19 @@ export interface LobeAgentAgencyConfig {
* remote hetero providers).
*/
executionTarget?: DeviceExecutionTarget;
+ /**
+ * Workspace execution-target selection policy. A fixed `device` target is
+ * valid only with a public workspace device; other fixed targets do not bind
+ * a device.
+ */
+ executionTargetSelectionPolicy?: ExecutionTargetSelectionPolicy;
heterogeneousProvider?: HeterogeneousProviderConfig;
+ /**
+ * Workspace model-selection policy. `fixed` (and an omitted value) keeps
+ * the shared agent model authoritative; `member` enables a per-user model
+ * override stored in `workspace_user_settings.preference`.
+ */
+ modelSelectionPolicy?: AgentModelSelectionPolicy;
/**
* Default model used by sub-agents this agent spawns via
* `lobe-agent.callSubAgent`. When unset, sub-agents fall back to the global
@@ -658,6 +689,7 @@ export interface LobeAgentAgencyConfig {
* consistent "effective" config.
*
* Rules:
+ * - `fixed` shared config ignores the caller override entirely
* - `override.executionTarget` wins when set; falls back to shared
* - `override.boundDeviceId` wins when set; falls back to shared
* - Nothing else (heterogeneousProvider, verifyRubricId, workingDirByDevice)
@@ -672,6 +704,7 @@ export const resolveAgencyConfig = (
override: Pick<LobeAgentAgencyConfig, 'boundDeviceId' | 'executionTarget'> | null | undefined,
): LobeAgentAgencyConfig | undefined => {
const base = agencyConfig ?? undefined;
+ if (base?.executionTargetSelectionPolicy === 'fixed') return base;
if (!override) return base;
const hasTarget = override.executionTarget !== undefined;
const hasDevice = override.boundDeviceId !== undefined;
diff --git a/packages/types/src/agent/index.ts b/packages/types/src/agent/index.ts
index 771874c483c..0736910cd49 100644
--- a/packages/types/src/agent/index.ts
+++ b/packages/types/src/agent/index.ts
@@ -4,5 +4,6 @@ export * from './chatConfig';
export * from './document';
export * from './graph';
export * from './item';
+export * from './modelSelection';
export * from './pluginConfig';
export * from './tts';
diff --git a/packages/types/src/agent/modelSelection.test.ts b/packages/types/src/agent/modelSelection.test.ts
new file mode 100644
index 00000000000..ec5aeee4107
--- /dev/null
+++ b/packages/types/src/agent/modelSelection.test.ts
@@ -0,0 +1,56 @@
+import { describe, expect, it } from 'vitest';
+
+import { resolveAgentModelConfig } from './modelSelection';
+
+const shared = {
+ model: 'shared-model',
+ provider: 'shared-provider',
+};
+
+describe('resolveAgentModelConfig', () => {
+ it('treats a missing policy as fixed for existing workspace agents', () => {
+ expect(
+ resolveAgentModelConfig(shared, {
+ model: 'member-model',
+ provider: 'member-provider',
+ }),
+ ).toEqual({ model: 'shared-model', provider: 'shared-provider' });
+ });
+
+ it('ignores a retained member override while the policy is fixed', () => {
+ expect(
+ resolveAgentModelConfig(
+ { ...shared, agencyConfig: { modelSelectionPolicy: 'fixed' } },
+ { model: 'member-model', provider: 'member-provider' },
+ ),
+ ).toEqual({ model: 'shared-model', provider: 'shared-provider' });
+ });
+
+ it('uses the member override when the author allows member selection', () => {
+ expect(
+ resolveAgentModelConfig(
+ { ...shared, agencyConfig: { modelSelectionPolicy: 'member' } },
+ { model: 'member-model', provider: 'member-provider' },
+ ),
+ ).toEqual({ model: 'member-model', provider: 'member-provider' });
+ });
+
+ it('keeps the shared model when member selection is enabled but no choice was saved', () => {
+ expect(
+ resolveAgentModelConfig({
+ ...shared,
+ agencyConfig: { modelSelectionPolicy: 'member' },
+ }),
+ ).toEqual({ model: 'shared-model', provider: 'shared-provider' });
+ });
+
+ it('applies explicit per-run overrides after the member choice', () => {
+ expect(
+ resolveAgentModelConfig(
+ { ...shared, agencyConfig: { modelSelectionPolicy: 'member' } },
+ { model: 'member-model', provider: 'member-provider' },
+ { model: 'run-model' },
+ ),
+ ).toEqual({ model: 'run-model', provider: 'member-provider' });
+ });
+});
diff --git a/packages/types/src/agent/modelSelection.ts b/packages/types/src/agent/modelSelection.ts
new file mode 100644
index 00000000000..753cdb6d8d5
--- /dev/null
+++ b/packages/types/src/agent/modelSelection.ts
@@ -0,0 +1,39 @@
+import type { LobeAgentAgencyConfig } from './agencyConfig';
+
+/** A workspace member's personal model choice for one shared agent. */
+export interface AgentModelOverride {
+ model: string;
+ provider: string;
+}
+
+export interface AgentModelConfig {
+ agencyConfig?: Pick<LobeAgentAgencyConfig, 'modelSelectionPolicy'>;
+ model: string;
+ provider?: string;
+}
+
+/**
+ * Resolve the model used by an agent run.
+ *
+ * Precedence is deliberately centralized so the server runtime, client
+ * fallback, and chat UI cannot drift:
+ *
+ * explicit per-run override > allowed member override > shared agent model.
+ *
+ * An omitted policy is fixed. A member override is therefore dormant (but
+ * retained) while fixed and becomes effective again when the author reopens
+ * member selection.
+ */
+export const resolveAgentModelConfig = (
+ shared: AgentModelConfig,
+ memberOverride?: AgentModelOverride | null,
+ explicitOverride?: Partial<AgentModelOverride> | null,
+): Pick<AgentModelConfig, 'model' | 'provider'> => {
+ const effectiveMemberOverride =
+ shared.agencyConfig?.modelSelectionPolicy === 'member' ? memberOverride : undefined;
+
+ return {
+ model: explicitOverride?.model ?? effectiveMemberOverride?.model ?? shared.model,
+ provider: explicitOverride?.provider ?? effectiveMemberOverride?.provider ?? shared.provider,
+ };
+};
diff --git a/packages/types/src/agentGroup/index.ts b/packages/types/src/agentGroup/index.ts
index 407423f8b5e..0ea0ec0ffc0 100644
--- a/packages/types/src/agentGroup/index.ts
+++ b/packages/types/src/agentGroup/index.ts
@@ -116,6 +116,8 @@ export interface ChatGroupItem {
title?: string | null;
updatedAt: Date;
userId: string;
+ /** Workspace visibility; absent only on legacy/personal group payloads. */
+ visibility?: 'private' | 'public';
/** Owning workspace; null for personal (non-workspace) groups. */
workspaceId?: string | null;
}
diff --git a/packages/types/src/home.ts b/packages/types/src/home.ts
index 03b6eb93d9d..2373ca97071 100644
--- a/packages/types/src/home.ts
+++ b/packages/types/src/home.ts
@@ -67,7 +67,7 @@ export interface SidebarAgentItem {
updatedAt: Date;
/**
* Creator of the item. Lets the client gate creator-only actions (e.g.
- * pulling a published agent back to private). Absent for chat groups.
+ * pulling a published agent back to private or deleting an agent group).
*/
userId?: string | null;
/**
diff --git a/packages/types/src/user/preference.ts b/packages/types/src/user/preference.ts
index 1c3cb255263..981eb5b3296 100644
--- a/packages/types/src/user/preference.ts
+++ b/packages/types/src/user/preference.ts
@@ -2,6 +2,7 @@ import type { PartialDeep } from 'type-fest';
import { z } from 'zod';
import type { DeviceExecutionTarget } from '../agent/agencyConfig';
+import type { AgentModelOverride } from '../agent/modelSelection';
import type { Plans } from '../subscription';
import type { TopicGroupMode, TopicSortBy } from '../topic';
import type { UserAgentOnboarding } from './agentOnboarding';
@@ -46,6 +47,8 @@ export interface AgentDeviceOverride {
*/
export interface WorkspaceUserPreference {
agentDeviceOverrides?: Record<string /* agentId */, AgentDeviceOverride>;
+ /** Personal model choices for workspace agents that allow member selection. */
+ agentModelOverrides?: Record<string /* agentId */, AgentModelOverride>;
}
export interface LobeUser {
diff --git a/src/features/AgentHome/OpeningQuestions.tsx b/src/features/AgentHome/OpeningQuestions.tsx
index 4b873b62efd..aff7285a80a 100644
--- a/src/features/AgentHome/OpeningQuestions.tsx
+++ b/src/features/AgentHome/OpeningQuestions.tsx
@@ -1,11 +1,14 @@
'use client';
-import { Block, Flexbox } from '@lobehub/ui';
-import { createStaticStyles } from 'antd-style';
+import { Block, Flexbox, Tooltip } from '@lobehub/ui';
+import { createStaticStyles, cx } from 'antd-style';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import { useConversationStore } from '@/features/Conversation';
+import { useResourceAccess } from '@/features/ResourcePermission/useResourceAccess';
+import { useAgentStore } from '@/store/agent';
+import { builtinAgentSelectors } from '@/store/agent/selectors';
const styles = createStaticStyles(({ css, cssVar }) => ({
card: css`
@@ -13,6 +16,10 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
padding-inline: 16px;
border-radius: 48px;
`,
+ cardDisabled: css`
+ cursor: not-allowed;
+ opacity: 0.55;
+ `,
container: css`
padding-block: 0;
padding-inline: 0;
@@ -27,28 +34,53 @@ interface OpeningQuestionsProps {
}
const OpeningQuestions = memo<OpeningQuestionsProps>(({ questions }) => {
- const { t } = useTranslation('welcome');
+ const { t } = useTranslation(['welcome', 'chat']);
const [sendMessage] = useConversationStore((s) => [s.sendMessage]);
+ // Same per-resource General-access gating as the chat input below (see
+ // useChatInputResourceAccess): inbox and private agents are never gated.
+ const agentId = useAgentStore((s) => s.activeAgentId);
+ const inboxAgentId = useAgentStore(builtinAgentSelectors.inboxAgentId);
+ const agentVisibility = useAgentStore((s) =>
+ s.activeAgentId ? s.agentMap[s.activeAgentId]?.visibility : undefined,
+ );
+ const gatedResourceId =
+ agentId && agentId !== inboxAgentId && agentVisibility !== 'private' ? agentId : undefined;
+ const { canUseResource } = useResourceAccess('agent', gatedResourceId);
+
return (
<div className={styles.container}>
<p className={styles.title}>{t('guide.questions.title')}</p>
<Flexbox horizontal gap={8} wrap={'wrap'}>
- {questions.slice(0, 5).map((question) => (
- <Block
- clickable
- className={styles.card}
- key={question}
- paddingBlock={8}
- paddingInline={12}
- variant={'filled'}
- onClick={() => {
- sendMessage({ message: question });
- }}
- >
- {question}
- </Block>
- ))}
+ {questions.slice(0, 5).map((question) => {
+ const card = (
+ <Block
+ className={cx(styles.card, !canUseResource && styles.cardDisabled)}
+ clickable={canUseResource}
+ key={question}
+ paddingBlock={8}
+ paddingInline={12}
+ variant={'filled'}
+ onClick={
+ canUseResource
+ ? () => {
+ sendMessage({ message: question });
+ }
+ : undefined
+ }
+ >
+ {question}
+ </Block>
+ );
+
+ return canUseResource ? (
+ card
+ ) : (
+ <Tooltip key={question} title={t('input.viewOnlyAgent', { ns: 'chat' })}>
+ {card}
+ </Tooltip>
+ );
+ })}
</Flexbox>
</div>
);
diff --git a/src/features/AgentProfileCard/AgentProfilePopup.tsx b/src/features/AgentProfileCard/AgentProfilePopup.tsx
index baec6e4b34c..b6b45de2d06 100644
--- a/src/features/AgentProfileCard/AgentProfilePopup.tsx
+++ b/src/features/AgentProfileCard/AgentProfilePopup.tsx
@@ -11,7 +11,9 @@ import { useTranslation } from 'react-i18next';
import useSWR from 'swr';
import ModelSelect from '@/features/ModelSelect';
+import { useResourceAccess } from '@/features/ResourcePermission/useResourceAccess';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { usePermission } from '@/hooks/usePermission';
import { agentProfileKeys } from '@/libs/swr/keys';
import { agentService } from '@/services/agent';
import { useAgentGroupStore } from '@/store/agentGroup';
@@ -75,11 +77,21 @@ const AgentProfilePopup = memo<AgentProfilePopupProps>(
const navigate = useWorkspaceAwareNavigate();
const [open, setOpen] = useState(false);
const [loading, setLoading] = useState(false);
+ const { allowed: canEditContent } = usePermission('edit_own_content');
+ const { canEditResource: canEditAgent, isAccessResolved: isAgentAccessResolved } =
+ useResourceAccess('agent', open ? agentId : undefined);
+ const { canEditResource: canEditGroup, isAccessResolved: isGroupAccessResolved } =
+ useResourceAccess('agentGroup', open ? groupId : undefined);
+ const canConfigure =
+ canEditContent &&
+ isAgentAccessResolved &&
+ canEditAgent &&
+ (!groupId || (isGroupAccessResolved && canEditGroup));
const updateMemberAgentConfig = useAgentGroupStore((s) => s.updateMemberAgentConfig);
const { data: fetched, isLoading } = useSWR(
- open ? agentProfileKeys.detail(agentId) : null,
+ open && canConfigure ? agentProfileKeys.detail(agentId) : null,
() => agentService.getAgentConfigById(agentId) as Promise<FetchedAgent | null>,
{ revalidateOnFocus: false },
);
@@ -94,7 +106,7 @@ const AgentProfilePopup = memo<AgentProfilePopupProps>(
};
const handleModelChange = async (props: { model: string; provider: string }) => {
- if (!groupId) return;
+ if (!groupId || !canConfigure) return;
setLoading(true);
try {
await updateMemberAgentConfig(groupId, agentId, {
@@ -107,7 +119,8 @@ const AgentProfilePopup = memo<AgentProfilePopupProps>(
};
const handleSettings = () => {
- if (!groupId) return;
+ if (!groupId || !canConfigure) return;
+ if (!canConfigure) return;
setOpen(false);
navigate(`/group/${groupId}/profile?tab=${agentId}`);
};
@@ -125,60 +138,61 @@ const AgentProfilePopup = memo<AgentProfilePopupProps>(
const fileCount = fetched?.files?.length ?? 0;
const hasStats = pluginCount > 0 || knowledgeCount > 0 || fileCount > 0;
- const footerLoading = !groupId && isLoading && !fetched;
-
- const modelSection = groupId ? (
- merged.model && (
- <Flexbox className={styles.section} gap={4}>
- <div className={styles.sectionTitle}>{t('groupSidebar.agentProfile.model')}</div>
- <ModelSelect
- loading={loading}
- value={{ model: merged.model, provider: merged.provider ?? undefined }}
- onChange={handleModelChange}
- />
- </Flexbox>
- )
- ) : footerLoading ? (
- <Flexbox horizontal align={'center'} className={styles.footer} gap={14}>
- <Skeleton.Button active size={'small'} style={{ height: 16, width: 90 }} />
- <Skeleton.Button active size={'small'} style={{ height: 16, width: 60 }} />
- </Flexbox>
- ) : merged.model || hasStats ? (
- <Flexbox horizontal align={'center'} className={styles.footer} gap={14} wrap={'wrap'}>
- {merged.model && (
- <Flexbox horizontal align={'center'} className={styles.statItem} gap={6}>
- <ModelIcon model={merged.model} size={14} />
- <Text fontSize={12} type={'secondary'}>
- {merged.model}
- </Text>
- </Flexbox>
- )}
- {pluginCount > 0 && (
- <Flexbox horizontal align={'center'} className={styles.statItem} gap={4}>
- <Icon icon={SkillsIcon} size={13} />
- <Text fontSize={12} type={'secondary'}>
- {t('agentProfile.skills', { count: pluginCount })}
- </Text>
- </Flexbox>
- )}
- {knowledgeCount > 0 && (
- <Flexbox horizontal align={'center'} className={styles.statItem} gap={4}>
- <Icon icon={BookOpen} size={13} />
- <Text fontSize={12} type={'secondary'}>
- {t('agentProfile.knowledgeBases', { count: knowledgeCount })}
- </Text>
+ const footerLoading = canConfigure && !groupId && isLoading && !fetched;
+
+ const modelSection =
+ canConfigure && groupId ? (
+ merged.model && (
+ <Flexbox className={styles.section} gap={4}>
+ <div className={styles.sectionTitle}>{t('groupSidebar.agentProfile.model')}</div>
+ <ModelSelect
+ loading={loading}
+ value={{ model: merged.model, provider: merged.provider ?? undefined }}
+ onChange={handleModelChange}
+ />
</Flexbox>
- )}
- {fileCount > 0 && (
- <Flexbox horizontal align={'center'} className={styles.statItem} gap={4}>
- <Icon icon={FileText} size={13} />
- <Text fontSize={12} type={'secondary'}>
- {t('agentProfile.files', { count: fileCount })}
- </Text>
- </Flexbox>
- )}
- </Flexbox>
- ) : null;
+ )
+ ) : footerLoading ? (
+ <Flexbox horizontal align={'center'} className={styles.footer} gap={14}>
+ <Skeleton.Button active size={'small'} style={{ height: 16, width: 90 }} />
+ <Skeleton.Button active size={'small'} style={{ height: 16, width: 60 }} />
+ </Flexbox>
+ ) : canConfigure && (merged.model || hasStats) ? (
+ <Flexbox horizontal align={'center'} className={styles.footer} gap={14} wrap={'wrap'}>
+ {merged.model && (
+ <Flexbox horizontal align={'center'} className={styles.statItem} gap={6}>
+ <ModelIcon model={merged.model} size={14} />
+ <Text fontSize={12} type={'secondary'}>
+ {merged.model}
+ </Text>
+ </Flexbox>
+ )}
+ {pluginCount > 0 && (
+ <Flexbox horizontal align={'center'} className={styles.statItem} gap={4}>
+ <Icon icon={SkillsIcon} size={13} />
+ <Text fontSize={12} type={'secondary'}>
+ {t('agentProfile.skills', { count: pluginCount })}
+ </Text>
+ </Flexbox>
+ )}
+ {knowledgeCount > 0 && (
+ <Flexbox horizontal align={'center'} className={styles.statItem} gap={4}>
+ <Icon icon={BookOpen} size={13} />
+ <Text fontSize={12} type={'secondary'}>
+ {t('agentProfile.knowledgeBases', { count: knowledgeCount })}
+ </Text>
+ </Flexbox>
+ )}
+ {fileCount > 0 && (
+ <Flexbox horizontal align={'center'} className={styles.statItem} gap={4}>
+ <Icon icon={FileText} size={13} />
+ <Text fontSize={12} type={'secondary'}>
+ {t('agentProfile.files', { count: fileCount })}
+ </Text>
+ </Flexbox>
+ )}
+ </Flexbox>
+ ) : null;
const content = showSkeleton ? (
<div style={{ padding: 16, width: 280 }}>
@@ -192,7 +206,7 @@ const AgentProfilePopup = memo<AgentProfilePopupProps>(
loading={isLoading && !merged.description}
title={merged.title || t('defaultSession', { ns: 'common' })}
headerAction={
- groupId ? (
+ groupId && canConfigure ? (
<Flexbox horizontal align="center" justify="flex-end" style={{ paddingBlockStart: 0 }}>
<ActionIcon
icon={Settings}
@@ -203,7 +217,7 @@ const AgentProfilePopup = memo<AgentProfilePopupProps>(
</Flexbox>
) : undefined
}
- onHeaderClick={handleHeaderClick}
+ onHeaderClick={canConfigure ? handleHeaderClick : undefined}
>
{modelSection}
</AgentProfileCard>
diff --git a/src/features/AgentTasks/AgentTaskDetail/TopicChatDrawer/FeedbackInput.tsx b/src/features/AgentTasks/AgentTaskDetail/TopicChatDrawer/FeedbackInput.tsx
index 90e6a17a546..d191024a1e3 100644
--- a/src/features/AgentTasks/AgentTaskDetail/TopicChatDrawer/FeedbackInput.tsx
+++ b/src/features/AgentTasks/AgentTaskDetail/TopicChatDrawer/FeedbackInput.tsx
@@ -9,6 +9,7 @@ import { useTranslation } from 'react-i18next';
import { AttachmentUploadButton } from '@/features/AttachmentInput';
import { useConversationStore } from '@/features/Conversation';
import OpStatusTray from '@/features/Conversation/ChatInput/OpStatusTray';
+import { useConversationResourceAccess } from '@/features/Conversation/hooks/useConversationResourceAccess';
import { EditorCanvas } from '@/features/EditorCanvas';
import {
getAttachmentFileIdsFromEditor,
@@ -25,6 +26,9 @@ const FeedbackInput = memo(() => {
const [hasAttachments, setHasAttachments] = useState(false);
const [expanded, setExpanded] = useState(false);
const shouldSendOnEnter = useEnterToSend();
+ // Task follow-ups send into the shared agent's topic — view-only members
+ // can watch the run but get no reply composer.
+ const { canUseResource } = useConversationResourceAccess();
const canSubmit = hasContent || hasAttachments;
@@ -80,6 +84,8 @@ const FeedbackInput = memo(() => {
}
}, [editor, sendMessage, submitting]);
+ if (!canUseResource) return <OpStatusTray seamless />;
+
// Mirror Fleet's ReplyArea: surface the live running-op status flush above the
// reply affordance (seamless inline row that renders nothing when idle), so the
// user can watch the agent work without expanding the composer.
diff --git a/src/features/ChatInput/ActionBar/Clear/index.tsx b/src/features/ChatInput/ActionBar/Clear/index.tsx
index a081d3dc9f7..3224f0c701b 100644
--- a/src/features/ChatInput/ActionBar/Clear/index.tsx
+++ b/src/features/ChatInput/ActionBar/Clear/index.tsx
@@ -8,6 +8,7 @@ import { usePermission } from '@/hooks/usePermission';
import { useChatStore } from '@/store/chat';
import { useFileStore } from '@/store/file';
+import { useChatInputResourceAccess } from '../../hooks/useChatInputResourceAccess';
import Action from '../components/Action';
export const useClearCurrentMessages = () => {
@@ -26,7 +27,11 @@ const Clear = memo(() => {
const clearCurrentMessages = useClearCurrentMessages();
const [confirmOpened, updateConfirmOpened] = useState(false);
const mobile = useIsMobile();
- const { allowed: canCreate } = usePermission('create_content');
+ const { allowed: canCreateContent } = usePermission('create_content');
+ // Clearing deletes shared conversation messages — view-only members don't
+ // get the confirm at all (the trigger Action is already disabled too).
+ const { canUseResource } = useChatInputResourceAccess();
+ const canCreate = canCreateContent && canUseResource;
const actionTitle: any = confirmOpened ? void 0 : t('clearCurrentMessages', { ns: 'chat' });
diff --git a/src/features/ChatInput/ActionBar/Model/index.tsx b/src/features/ChatInput/ActionBar/Model/index.tsx
index ff69cf1b698..616273dcfb7 100644
--- a/src/features/ChatInput/ActionBar/Model/index.tsx
+++ b/src/features/ChatInput/ActionBar/Model/index.tsx
@@ -2,14 +2,14 @@ import { ModelIcon } from '@lobehub/icons';
import { Center, Tooltip } from '@lobehub/ui';
import { createStaticStyles, cx } from 'antd-style';
import { memo, useCallback } from 'react';
+import { useTranslation } from 'react-i18next';
-import { useBusinessModelModeConfig } from '@/business/client/hooks/useBusinessAgentMode';
import ModelSwitchPanel from '@/features/ModelSwitchPanel';
import { usePermission } from '@/hooks/usePermission';
-import { useAgentStore } from '@/store/agent';
-import { agentByIdSelectors } from '@/store/agent/selectors';
import { useAgentId } from '../../hooks/useAgentId';
+import { useAgentModelSelection } from '../../hooks/useAgentModelSelection';
+import { useChatInputResourceAccess } from '../../hooks/useChatInputResourceAccess';
import { useActionBarContext } from '../context';
const styles = createStaticStyles(({ css, cssVar }) => ({
@@ -47,31 +47,44 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
}));
const ModelSwitch = memo(() => {
+ const { t } = useTranslation('setting');
const { actionSize, dropdownPlacement } = useActionBarContext();
const blockSize = actionSize?.blockSize ?? 32;
const iconSize = actionSize?.size ?? 20;
const { allowed: canCreateContent, reason } = usePermission('create_content');
-
+ const { canConfigureResource, canUseResource, isAccessLoading } = useChatInputResourceAccess();
const agentId = useAgentId();
- const [model, provider, updateAgentConfigById] = useAgentStore((s) => [
- agentByIdSelectors.getAgentModelById(agentId)(s),
- agentByIdSelectors.getAgentModelProviderById(agentId)(s),
- s.updateAgentConfigById,
- ]);
- const applyBusinessModelModeConfig = useBusinessModelModeConfig();
+ const { isPreferenceLoading, isWorkspaceAgent, model, provider, selectionPolicy, selectModel } =
+ useAgentModelSelection(agentId);
+ const canSelectForAgent = isWorkspaceAgent
+ ? canUseResource && selectionPolicy === 'member'
+ : canConfigureResource;
+ const canSelectModel =
+ canCreateContent && canSelectForAgent && !isAccessLoading && !isPreferenceLoading;
+ const disabledReason = !canCreateContent
+ ? reason
+ : isAccessLoading || isPreferenceLoading
+ ? t('checkingPermissions')
+ : isWorkspaceAgent && !canUseResource
+ ? t('permission.accessTag.viewOnlyTip')
+ : isWorkspaceAgent && selectionPolicy === 'fixed'
+ ? t('settingAgent.modelPolicy.fixedTip')
+ : t('permission.accessTag.useOnlyTip');
const handleModelChange = useCallback(
async (params: { model: string; provider: string }) => {
- if (!canCreateContent) return;
+ if (!canSelectModel) return;
- await updateAgentConfigById(agentId, applyBusinessModelModeConfig(params));
+ await selectModel(params);
},
- [agentId, applyBusinessModelModeConfig, canCreateContent, updateAgentConfigById],
+ [canSelectModel, selectModel],
);
const trigger = (
<Center
- className={cx(styles.model, !canCreateContent && styles.modelDisabled)}
+ aria-disabled={!canSelectModel}
+ aria-label={model}
+ className={cx(styles.model, !canSelectModel && styles.modelDisabled)}
height={blockSize}
width={blockSize}
>
@@ -81,9 +94,9 @@ const ModelSwitch = memo(() => {
</Center>
);
- if (!canCreateContent)
+ if (!canSelectModel)
return (
- <Tooltip title={reason}>
+ <Tooltip title={`${model} · ${disabledReason}`}>
<div>{trigger}</div>
</Tooltip>
);
diff --git a/src/features/ChatInput/ActionBar/ModelLabel/index.tsx b/src/features/ChatInput/ActionBar/ModelLabel/index.tsx
index 5def6d1dff4..ddce16c1a25 100644
--- a/src/features/ChatInput/ActionBar/ModelLabel/index.tsx
+++ b/src/features/ChatInput/ActionBar/ModelLabel/index.tsx
@@ -2,15 +2,15 @@ import { Center, Flexbox, Tooltip } from '@lobehub/ui';
import { createStaticStyles, cx } from 'antd-style';
import { ChevronDownIcon } from 'lucide-react';
import { memo, useCallback } from 'react';
+import { useTranslation } from 'react-i18next';
-import { useBusinessModelModeConfig } from '@/business/client/hooks/useBusinessAgentMode';
import ModelSwitchPanel from '@/features/ModelSwitchPanel';
import { usePermission } from '@/hooks/usePermission';
-import { useAgentStore } from '@/store/agent';
-import { agentByIdSelectors } from '@/store/agent/selectors';
import { aiModelSelectors, useAiInfraStore } from '@/store/aiInfra';
import { useAgentId } from '../../hooks/useAgentId';
+import { useAgentModelSelection } from '../../hooks/useAgentModelSelection';
+import { useChatInputResourceAccess } from '../../hooks/useChatInputResourceAccess';
import { useActionBarContext } from '../context';
const styles = createStaticStyles(({ css, cssVar }) => ({
@@ -37,7 +37,6 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
`,
triggerDisabled: css`
cursor: not-allowed;
- opacity: 0.5;
:hover {
background: transparent;
@@ -46,33 +45,46 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
}));
const ModelLabel = memo(() => {
+ const { t } = useTranslation('setting');
const { dropdownPlacement } = useActionBarContext();
const { allowed: canCreateContent, reason } = usePermission('create_content');
-
+ const { canConfigureResource, canUseResource, isAccessLoading } = useChatInputResourceAccess();
const agentId = useAgentId();
- const [model, provider, updateAgentConfigById] = useAgentStore((s) => [
- agentByIdSelectors.getAgentModelById(agentId)(s),
- agentByIdSelectors.getAgentModelProviderById(agentId)(s),
- s.updateAgentConfigById,
- ]);
- const applyBusinessModelModeConfig = useBusinessModelModeConfig();
+ const { isPreferenceLoading, isWorkspaceAgent, model, provider, selectionPolicy, selectModel } =
+ useAgentModelSelection(agentId);
+ const canSelectForAgent = isWorkspaceAgent
+ ? canUseResource && selectionPolicy === 'member'
+ : canConfigureResource;
+ const canSelectModel =
+ canCreateContent && canSelectForAgent && !isAccessLoading && !isPreferenceLoading;
+ const disabledReason = !canCreateContent
+ ? reason
+ : isAccessLoading || isPreferenceLoading
+ ? t('checkingPermissions')
+ : isWorkspaceAgent && !canUseResource
+ ? t('permission.accessTag.viewOnlyTip')
+ : isWorkspaceAgent && selectionPolicy === 'fixed'
+ ? t('settingAgent.modelPolicy.fixedTip')
+ : t('permission.accessTag.useOnlyTip');
const enabledModel = useAiInfraStore(aiModelSelectors.getEnabledModelById(model, provider));
const displayName = enabledModel?.displayName || model;
const handleModelChange = useCallback(
async (params: { model: string; provider: string }) => {
- if (!canCreateContent) return;
+ if (!canSelectModel) return;
- await updateAgentConfigById(agentId, applyBusinessModelModeConfig(params));
+ await selectModel(params);
},
- [agentId, applyBusinessModelModeConfig, canCreateContent, updateAgentConfigById],
+ [canSelectModel, selectModel],
);
const trigger = (
<Center
horizontal
- className={cx(styles.trigger, !canCreateContent && styles.triggerDisabled)}
+ aria-disabled={!canSelectModel}
+ aria-label={displayName}
+ className={cx(styles.trigger, !canSelectModel && styles.triggerDisabled)}
height={28}
paddingInline={6}
>
@@ -83,9 +95,9 @@ const ModelLabel = memo(() => {
</Center>
);
- if (!canCreateContent)
+ if (!canSelectModel)
return (
- <Tooltip title={reason}>
+ <Tooltip title={disabledReason}>
<div>{trigger}</div>
</Tooltip>
);
diff --git a/src/features/ChatInput/ActionBar/Plus/index.tsx b/src/features/ChatInput/ActionBar/Plus/index.tsx
index 66c495d5a60..783480dc291 100644
--- a/src/features/ChatInput/ActionBar/Plus/index.tsx
+++ b/src/features/ChatInput/ActionBar/Plus/index.tsx
@@ -48,6 +48,7 @@ import { useUserStore } from '@/store/user';
import { settingsSelectors } from '@/store/user/selectors';
import { useAgentId } from '../../hooks/useAgentId';
+import { useChatInputResourceAccess } from '../../hooks/useChatInputResourceAccess';
import { useUpdateAgentConfig } from '../../hooks/useUpdateAgentConfig';
import { useChatInputStore } from '../../store';
import Action from '../components/Action';
@@ -289,6 +290,7 @@ const PlusAction = memo(() => {
const { t: tSetting } = useTranslation('setting');
const isDark = useIsDark();
const agentId = useAgentId();
+ const { canConfigureResource } = useChatInputResourceAccess();
const { updateAgentChatConfig } = useUpdateAgentConfig();
const [dropdownOpen, setDropdownOpen] = useState(false);
@@ -531,119 +533,131 @@ const PlusAction = memo(() => {
]
: [];
- const capabilityItems: ActionDropdownMenuItems = [
- // Memory toggle — trailing switch; toggle by clicking the switch or the whole row
- {
- checked: Boolean(isMemoryEnabled),
- icon: Brain,
- key: 'memory',
- label: t('memory.title'),
- onCheckedChange: handleToggleMemory,
- type: 'switch',
- },
- // Web search: simple toggle when 2 options, submenu when 3
- ...(showProviderSearch
- ? [
- {
- children: [
+ const capabilityItems: ActionDropdownMenuItems = canConfigureResource
+ ? [
+ // Memory toggle — trailing switch; toggle by clicking the switch or the whole row
+ {
+ checked: Boolean(isMemoryEnabled),
+ icon: Brain,
+ key: 'memory',
+ label: t('memory.title'),
+ onCheckedChange: handleToggleMemory,
+ type: 'switch',
+ },
+ // Web search: simple toggle when 2 options, submenu when 3
+ ...(showProviderSearch
+ ? [
{
- key: 'search-off',
- label: renderSearchOption(
- <Icon icon={GlobeOffIcon} size={18} />,
- t('plus.search.off'),
- t('plus.search.offDesc'),
- activeSearchOption === 'off',
+ children: [
+ {
+ key: 'search-off',
+ label: renderSearchOption(
+ <Icon icon={GlobeOffIcon} size={18} />,
+ t('plus.search.off'),
+ t('plus.search.offDesc'),
+ activeSearchOption === 'off',
+ ),
+ onClick: () => handleSelectSearch('off'),
+ },
+ {
+ key: 'search-app',
+ label: renderSearchOption(
+ <Icon
+ color={activeSearchOption === 'app' ? cssVar.colorInfo : undefined}
+ icon={SearchCheck}
+ size={18}
+ />,
+ t('plus.search.appSearch'),
+ t('plus.search.appSearchDesc'),
+ activeSearchOption === 'app',
+ ),
+ onClick: () => handleSelectSearch('app'),
+ },
+ {
+ key: 'search-provider',
+ label: renderSearchOption(
+ <Icon
+ color={activeSearchOption === 'provider' ? cssVar.colorInfo : undefined}
+ icon={CloudCog}
+ size={18}
+ />,
+ t('plus.search.modelSearch'),
+ t('plus.search.modelSearchDesc'),
+ activeSearchOption === 'provider',
+ ),
+ onClick: () => handleSelectSearch('provider'),
+ },
+ ],
+ extra: <Icon className="lobe-submenu-chevron" icon={ChevronRight} size={16} />,
+ icon: activeIcon(
+ activeSearchOption === 'off' ? GlobeOffIcon : Globe,
+ activeSearchOption !== 'off',
),
- onClick: () => handleSelectSearch('off'),
- },
+ key: 'search-group',
+ label: t('search.title'),
+ } as ActionDropdownMenuItems[number],
+ ]
+ : [
+ // Web search toggle — trailing switch; toggle by clicking the switch or the whole row
{
- key: 'search-app',
- label: renderSearchOption(
- <Icon
- color={activeSearchOption === 'app' ? cssVar.colorInfo : undefined}
- icon={SearchCheck}
- size={18}
- />,
- t('plus.search.appSearch'),
- t('plus.search.appSearchDesc'),
- activeSearchOption === 'app',
- ),
- onClick: () => handleSelectSearch('app'),
- },
+ checked: activeSearchOption !== 'off',
+ icon: Globe,
+ key: 'search-toggle',
+ label: t('search.title'),
+ onCheckedChange: (checked: boolean) =>
+ handleSelectSearch(checked ? 'app' : 'off'),
+ type: 'switch',
+ } as ActionDropdownMenuItems[number],
+ ]),
+ ...(enableGatewayMode
+ ? [
{
- key: 'search-provider',
- label: renderSearchOption(
- <Icon
- color={activeSearchOption === 'provider' ? cssVar.colorInfo : undefined}
- icon={CloudCog}
- size={18}
- />,
- t('plus.search.modelSearch'),
- t('plus.search.modelSearchDesc'),
- activeSearchOption === 'provider',
+ checked: isGatewayModeEnabled,
+ icon: Cloud,
+ key: 'gateway-mode',
+ label: (
+ <PopoverLabel
+ label={renderGatewayModeLabel()}
+ popoverContent={gatewayModeInfo}
+ // Clear the trailing toggle so the card sits to the right of the whole menu.
+ sideOffset={64}
+ />
),
- onClick: () => handleSelectSearch('provider'),
- },
- ],
- extra: <Icon className="lobe-submenu-chevron" icon={ChevronRight} size={16} />,
- icon: activeIcon(
- activeSearchOption === 'off' ? GlobeOffIcon : Globe,
- activeSearchOption !== 'off',
- ),
- key: 'search-group',
- label: t('search.title'),
- } as ActionDropdownMenuItems[number],
- ]
- : [
- // Web search toggle — trailing switch; toggle by clicking the switch or the whole row
- {
- checked: activeSearchOption !== 'off',
- icon: Globe,
- key: 'search-toggle',
- label: t('search.title'),
- onCheckedChange: (checked: boolean) => handleSelectSearch(checked ? 'app' : 'off'),
- type: 'switch',
- } as ActionDropdownMenuItems[number],
- ]),
- ...(enableGatewayMode
- ? [
- {
- checked: isGatewayModeEnabled,
- icon: Cloud,
- key: 'gateway-mode',
- label: (
- <PopoverLabel
- label={renderGatewayModeLabel()}
- popoverContent={gatewayModeInfo}
- // Clear the trailing toggle so the card sits to the right of the whole menu.
- sideOffset={64}
- />
- ),
- onCheckedChange: handleToggleGatewayMode,
- type: 'switch',
- } as ActionDropdownMenuItems[number],
- ]
- : []),
- { type: 'divider' },
- // Skills (with "Add Skills..." merged in) sits directly under the Web Search divider.
- ...toolsItems,
- // Formatting toolbar toggle — trailing switch; toggle by clicking the switch or the whole row
- {
- checked: Boolean(showTypoBar),
- icon: TypeIcon,
- key: 'typo',
- label: tEditor('actions.typobar.title'),
- onCheckedChange: (checked: boolean) => setShowTypoBar(checked),
- type: 'switch',
- },
- // Advanced parameter settings — mirrors ParamsPanelToggle in the agent header.
- {
- icon: Settings2Icon,
- key: 'params',
- label: renderActive(tSetting('settingModel.params.title'), isParamsPanelActive),
- onClick: handleToggleParams,
- },
- ];
+ onCheckedChange: handleToggleGatewayMode,
+ type: 'switch',
+ } as ActionDropdownMenuItems[number],
+ ]
+ : []),
+ { type: 'divider' },
+ // Skills (with "Add Skills..." merged in) sits directly under the Web Search divider.
+ ...toolsItems,
+ // Formatting toolbar toggle — trailing switch; toggle by clicking the switch or the whole row
+ {
+ checked: Boolean(showTypoBar),
+ icon: TypeIcon,
+ key: 'typo',
+ label: tEditor('actions.typobar.title'),
+ onCheckedChange: (checked: boolean) => setShowTypoBar(checked),
+ type: 'switch',
+ },
+ // Advanced parameter settings — mirrors ParamsPanelToggle in the agent header.
+ {
+ icon: Settings2Icon,
+ key: 'params',
+ label: renderActive(tSetting('settingModel.params.title'), isParamsPanelActive),
+ onClick: handleToggleParams,
+ },
+ ]
+ : [
+ {
+ checked: Boolean(showTypoBar),
+ icon: TypeIcon,
+ key: 'typo',
+ label: tEditor('actions.typobar.title'),
+ onCheckedChange: (checked: boolean) => setShowTypoBar(checked),
+ type: 'switch',
+ },
+ ];
// "Add Attachments..." merges file upload with the knowledge base (libraries / files).
// When the knowledge base is disabled there is no submenu, so Upload stays a top-level entry.
@@ -652,23 +666,28 @@ const PlusAction = memo(() => {
{
children: [
...uploadItems,
- ...(knowledgeItems.length > 0
+ ...(canConfigureResource && knowledgeItems.length > 0
? [{ type: 'divider' as const }, ...knowledgeItems]
- : [
- {
- disabled: true,
- key: 'knowledge-empty',
- label: t('knowledgeBase.related.empty'),
- },
- ]),
+ : canConfigureResource
+ ? [
+ {
+ disabled: true,
+ key: 'knowledge-empty',
+ label: t('knowledgeBase.related.empty'),
+ },
+ ]
+ : []),
],
// Trailing chevron (replaces base-ui's default triangle submenu arrow,
// which is hidden via the .lobe-submenu-chevron rule in ActionDropdown).
extra: <Icon className="lobe-submenu-chevron" icon={ChevronRight} size={16} />,
- footer: knowledgeFooter,
+ footer: canConfigureResource ? knowledgeFooter : undefined,
icon: LibraryBig,
key: 'attachments',
- label: renderLabelWithCount(t('plus.addAttachments'), knowledgeEnabledCount),
+ label: renderLabelWithCount(
+ t('plus.addAttachments'),
+ canConfigureResource ? knowledgeEnabledCount : 0,
+ ),
} as ActionDropdownMenuItems[number],
]
: uploadItems;
@@ -676,6 +695,8 @@ const PlusAction = memo(() => {
return [...attachmentsItems, ...capabilityItems];
}, [
activeSearchOption,
+ agentId,
+ canConfigureResource,
canUploadImage,
canUploadVideo,
canUploadAudio,
diff --git a/src/features/ChatInput/ActionBar/components/Action.tsx b/src/features/ChatInput/ActionBar/components/Action.tsx
index 96e4c625b28..ca354dfa539 100644
--- a/src/features/ChatInput/ActionBar/components/Action.tsx
+++ b/src/features/ChatInput/ActionBar/components/Action.tsx
@@ -4,11 +4,13 @@ import { type ActionIconProps, type PopoverTrigger } from '@lobehub/ui';
import { ActionIcon } from '@lobehub/ui';
import { isUndefined } from 'es-toolkit/compat';
import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
import useMergeState from 'use-merge-value';
import { usePermission } from '@/hooks/usePermission';
import { useServerConfigStore } from '@/store/serverConfig';
+import { useChatInputResourceAccess } from '../../hooks/useChatInputResourceAccess';
import { useActionBarContext } from '../context';
import { type ActionDropdownProps } from './ActionDropdown';
import ActionDropdown from './ActionDropdown';
@@ -47,8 +49,17 @@ const Action = memo<ActionProps>(
const mobile = useServerConfigStore((s) => s.isMobile);
const { actionSize, dropdownPlacement } = useActionBarContext();
const { allowed: canUseChatInputAction, reason } = usePermission('create_content');
- const blocked = disabled || !canUseChatInputAction;
- const tooltipTitle = canUseChatInputAction ? title : reason;
+ // View-only General access makes the whole input read-only: every action
+ // either sends or writes shared agent config, so the trigger goes inert
+ // (disabled, not hidden) — matching the editor/send-button gating.
+ const { canUseResource, isGroupContext } = useChatInputResourceAccess();
+ const { t } = useTranslation('chat');
+ const blocked = disabled || !canUseChatInputAction || !canUseResource;
+ const tooltipTitle = !canUseChatInputAction
+ ? reason
+ : canUseResource
+ ? title
+ : t(isGroupContext ? 'input.viewOnlyGroup' : 'input.viewOnlyAgent');
const iconNode = (
<ActionIcon
disabled={blocked}
diff --git a/src/features/ChatInput/ActionBar/filterChatOnlyActions.ts b/src/features/ChatInput/ActionBar/filterChatOnlyActions.ts
new file mode 100644
index 00000000000..d025fac4b2c
--- /dev/null
+++ b/src/features/ChatInput/ActionBar/filterChatOnlyActions.ts
@@ -0,0 +1,44 @@
+import type { ActionKey, ActionKeys } from './config';
+
+const CHAT_ONLY_ACTIONS = new Set<ActionKey>([
+ 'clear',
+ 'fileUpload',
+ 'history',
+ 'mention',
+ 'model',
+ 'modelLabel',
+ 'plus',
+ 'promptTransform',
+ 'typo',
+]);
+
+const normalizeChatOnlyAction = (action: ActionKey): ActionKey =>
+ action === 'model' ? 'modelLabel' : action;
+
+/**
+ * Chat-only members (no configuration access) keep attachments, formatting and
+ * chat operations while configuration actions are hidden. `model` degrades to
+ * the read-only `modelLabel`.
+ */
+export const filterChatOnlyActions = (actions: ActionKeys[]): ActionKeys[] => {
+ const visibleActions: ActionKeys[] = [];
+
+ for (const action of actions) {
+ if (Array.isArray(action)) {
+ const visibleGroup = action
+ .filter((item) => CHAT_ONLY_ACTIONS.has(item))
+ .map(normalizeChatOnlyAction);
+ if (visibleGroup.length > 0) visibleActions.push(visibleGroup);
+ continue;
+ }
+
+ if (action === '---') {
+ visibleActions.push(action);
+ continue;
+ }
+
+ if (CHAT_ONLY_ACTIONS.has(action)) visibleActions.push(normalizeChatOnlyAction(action));
+ }
+
+ return visibleActions;
+};
diff --git a/src/features/ChatInput/ActionBar/index.test.ts b/src/features/ChatInput/ActionBar/index.test.ts
new file mode 100644
index 00000000000..0627931fc7a
--- /dev/null
+++ b/src/features/ChatInput/ActionBar/index.test.ts
@@ -0,0 +1,24 @@
+import { describe, expect, it } from 'vitest';
+
+import { filterChatOnlyActions } from './filterChatOnlyActions';
+
+describe('filterChatOnlyActions', () => {
+ it('keeps attachments, formatting, and chat operations while hiding configuration actions', () => {
+ expect(
+ filterChatOnlyActions([
+ 'model',
+ 'search',
+ 'memory',
+ 'fileUpload',
+ 'tools',
+ '---',
+ ['typo', 'params', 'clear'],
+ ]),
+ ).toEqual(['modelLabel', 'fileUpload', '---', ['typo', 'clear']]);
+ });
+
+ it('shows the current model label instead of an icon-only selector for chat-only members', () => {
+ expect(filterChatOnlyActions(['model', 'plus'])).toEqual(['modelLabel', 'plus']);
+ expect(filterChatOnlyActions(['modelLabel', 'plus'])).toEqual(['modelLabel', 'plus']);
+ });
+});
diff --git a/src/features/ChatInput/ActionBar/index.tsx b/src/features/ChatInput/ActionBar/index.tsx
index fe64a657651..192fbd61ca2 100644
--- a/src/features/ChatInput/ActionBar/index.tsx
+++ b/src/features/ChatInput/ActionBar/index.tsx
@@ -9,9 +9,11 @@ import { labPreferSelectors } from '@/store/user/slices/preference/selectors';
import { type ActionKey, type ActionKeys } from '../ActionBar/config';
import { actionMap } from '../ActionBar/config';
+import { useChatInputResourceAccess } from '../hooks/useChatInputResourceAccess';
import { useChatInputStore } from '../store';
import { type DropdownPlacement } from './context';
import { ActionBarContext } from './context';
+import { filterChatOnlyActions } from './filterChatOnlyActions';
const mapActionToItem = (actionKey: ActionKey) => {
const Render = actionMap[actionKey];
@@ -62,10 +64,12 @@ const ActionToolbar = memo<ActionToolbarProps>(
s.toggleExpandInputActionbar,
]);
const enableRichRender = useUserStore(labPreferSelectors.enableInputMarkdown);
+ const { canConfigureResource } = useChatInputResourceAccess();
- const leftActions = useChatInputStore((s) =>
- s.leftActions.filter((item) => (enableRichRender ? true : item !== 'typo')),
- );
+ const leftActions = useChatInputStore((s) => {
+ const actions = s.leftActions.filter((item) => (enableRichRender ? true : item !== 'typo'));
+ return canConfigureResource ? actions : filterChatOnlyActions(actions);
+ });
const mobile = useChatInputStore((s) => s.mobile);
diff --git a/src/features/ChatInput/ChatInputNotice/useChatInputNotice.test.tsx b/src/features/ChatInput/ChatInputNotice/useChatInputNotice.test.tsx
index 9902d24b90e..1a3c286cfb1 100644
--- a/src/features/ChatInput/ChatInputNotice/useChatInputNotice.test.tsx
+++ b/src/features/ChatInput/ChatInputNotice/useChatInputNotice.test.tsx
@@ -27,6 +27,7 @@ const testState = vi.hoisted(() => ({
isInitAiProviderRuntimeState: false,
},
isDesktop: false,
+ resourceAccess: { canUseResource: true, isGroupContext: false },
}));
type StoreSelector<T = unknown, S = Record<PropertyKey, unknown>> = (state: S) => T;
@@ -41,6 +42,10 @@ vi.mock('@/features/ChatInput/hooks/useAgentId', () => ({
useAgentId: () => 'agent-id',
}));
+vi.mock('@/features/ChatInput/hooks/useChatInputResourceAccess', () => ({
+ useChatInputResourceAccess: () => testState.resourceAccess,
+}));
+
vi.mock('@/hooks/useEnabledChatModels', () => ({
useEnabledChatModels: () => testState.aiInfra.enabledChatModelList,
}));
@@ -76,6 +81,25 @@ describe('useChatInputNotice', () => {
testState.aiInfra.enabledChatModelList = [];
testState.aiInfra.isInitAiProviderRuntimeState = false;
testState.isDesktop = false;
+ testState.resourceAccess = { canUseResource: true, isGroupContext: false };
+ });
+
+ it('returns the agent view-only notice when the member lacks use access', () => {
+ testState.resourceAccess = { canUseResource: false, isGroupContext: false };
+
+ const { result } = renderHook(() => useChatInputNotice());
+
+ expect(result.current).toEqual({ key: 'input.viewOnlyAgent', type: 'warning' });
+ });
+
+ it('returns the group view-only notice in group context and outranks model notices', () => {
+ testState.resourceAccess = { canUseResource: false, isGroupContext: true };
+ // Would produce input.modelUnavailable on its own — view-only must win.
+ testState.aiInfra.isInitAiProviderRuntimeState = true;
+
+ const { result } = renderHook(() => useChatInputNotice());
+
+ expect(result.current).toEqual({ key: 'input.viewOnlyGroup', type: 'warning' });
});
it('does not return a notice before the model runtime config is ready', () => {
diff --git a/src/features/ChatInput/ChatInputNotice/useChatInputNotice.ts b/src/features/ChatInput/ChatInputNotice/useChatInputNotice.ts
index 0c254583a4d..6aa6806eb68 100644
--- a/src/features/ChatInput/ChatInputNotice/useChatInputNotice.ts
+++ b/src/features/ChatInput/ChatInputNotice/useChatInputNotice.ts
@@ -1,4 +1,5 @@
import { useAgentId } from '@/features/ChatInput/hooks/useAgentId';
+import { useChatInputResourceAccess } from '@/features/ChatInput/hooks/useChatInputResourceAccess';
import { useEnabledChatModels } from '@/hooks/useEnabledChatModels';
import { useAgentStore } from '@/store/agent';
import { agentByIdSelectors } from '@/store/agent/selectors';
@@ -7,8 +8,10 @@ import { type EnabledProviderWithModels } from '@/types/aiProvider';
interface ResolveChatInputNoticeParams {
currentChatModel?: unknown;
+ isGroupContext?: boolean;
isHeterogeneousAgent: boolean;
isModelConfigReady: boolean;
+ isResourceViewOnly?: boolean;
}
const findEnabledChatModel = (
@@ -23,9 +26,20 @@ const findEnabledChatModel = (
export const resolveChatInputNotice = ({
currentChatModel,
+ isGroupContext,
isHeterogeneousAgent,
isModelConfigReady,
+ isResourceViewOnly,
}: ResolveChatInputNoticeParams) => {
+ // View-level General access on the bound agent/group makes the whole input
+ // read-only — that outranks any model-config notice (nothing can be sent).
+ if (isResourceViewOnly)
+ return {
+ action: undefined,
+ key: isGroupContext ? 'input.viewOnlyGroup' : 'input.viewOnlyAgent',
+ type: 'warning',
+ } as const;
+
// Model-config notices don't apply to heterogeneous agents (own toolchain) or
// before the model runtime config is ready.
if (
@@ -54,10 +68,13 @@ export const useChatInputNotice = (): ChatInputNotice | undefined => {
aiProviderSelectors.isInitAiProviderRuntimeState(s),
);
const currentChatModel = findEnabledChatModel(enabledChatModelList, model, provider);
+ const { canUseResource, isGroupContext } = useChatInputResourceAccess();
return resolveChatInputNotice({
currentChatModel,
+ isGroupContext,
isHeterogeneousAgent,
isModelConfigReady,
+ isResourceViewOnly: !canUseResource,
});
};
diff --git a/src/features/ChatInput/ControlBar/ApprovalMode.tsx b/src/features/ChatInput/ControlBar/ApprovalMode.tsx
index a66237b1665..989fea0ce2a 100644
--- a/src/features/ChatInput/ControlBar/ApprovalMode.tsx
+++ b/src/features/ChatInput/ControlBar/ApprovalMode.tsx
@@ -7,6 +7,7 @@ import { type LucideIcon } from 'lucide-react';
import { memo, useCallback, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import { useChatInputResourceAccess } from '@/features/ChatInput/hooks/useChatInputResourceAccess';
import { usePermission } from '@/hooks/usePermission';
import { useUserStore } from '@/store/user';
import { toolInterventionSelectors } from '@/store/user/selectors';
@@ -61,6 +62,10 @@ const ModeSelector = memo(() => {
const { t } = useTranslation('chat');
const [dropdownOpen, setDropdownOpen] = useState(false);
const { allowed: canCreateContent, reason } = usePermission('create_content');
+ // View-only General access: nothing can be sent from this input, so the
+ // approval-mode picker is inert too (disabled, not hidden).
+ const { canUseResource, isGroupContext } = useChatInputResourceAccess();
+ const disabled = !canCreateContent || !canUseResource;
const approvalMode = useUserStore(toolInterventionSelectors.approvalMode);
const updateHumanIntervention = useUserStore((s) => s.updateHumanIntervention);
@@ -75,20 +80,20 @@ const ModeSelector = memo(() => {
const handleModeChange = useCallback(
async (mode: ApprovalMode) => {
- if (!canCreateContent) return;
+ if (disabled) return;
await updateHumanIntervention({ approvalMode: mode });
},
- [canCreateContent, updateHumanIntervention],
+ [disabled, updateHumanIntervention],
);
const handleOpenChange = useCallback(
(nextOpen: boolean) => {
- if (!canCreateContent) return;
+ if (disabled) return;
setDropdownOpen(nextOpen);
},
- [canCreateContent],
+ [disabled],
);
const menuItems = useMemo<MenuProps['items']>(
@@ -136,7 +141,7 @@ const ModeSelector = memo(() => {
const button = (
<Button
className={styles.modeButton}
- disabled={!canCreateContent}
+ disabled={disabled}
icon={ChevronDown}
iconPosition="end"
size="small"
@@ -146,9 +151,15 @@ const ModeSelector = memo(() => {
</Button>
);
- if (!canCreateContent)
+ if (disabled)
return (
- <Tooltip title={reason}>
+ <Tooltip
+ title={
+ !canCreateContent
+ ? reason
+ : t(isGroupContext ? 'input.viewOnlyGroup' : 'input.viewOnlyAgent')
+ }
+ >
<div className={styles.modeButtonDisabled}>{button}</div>
</Tooltip>
);
@@ -156,7 +167,7 @@ const ModeSelector = memo(() => {
return (
<DropdownMenu
items={menuItems}
- open={canCreateContent && dropdownOpen}
+ open={!disabled && dropdownOpen}
placement="bottomRight"
onOpenChange={handleOpenChange}
>
diff --git a/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx b/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx
index 0d8dddd2e1b..21e8312bb16 100644
--- a/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx
+++ b/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx
@@ -1,34 +1,33 @@
'use client';
-import { SiApple, SiLinux } from '@icons-pack/react-simple-icons';
import { isDesktop } from '@lobechat/const';
import {
HETEROGENEOUS_TYPE_LABELS,
isRemoteHeterogeneousType,
} from '@lobechat/heterogeneous-agents';
import type { DeviceExecutionTarget } from '@lobechat/types';
-import { Microsoft } from '@lobehub/icons';
import { Flexbox, Icon, Popover, Tooltip } from '@lobehub/ui';
import { createStaticStyles, cssVar, cx } from 'antd-style';
import {
- BoxIcon,
CheckIcon,
ChevronDownIcon,
ExternalLinkIcon,
InfoIcon,
- LaptopIcon,
MonitorDownIcon,
- MonitorIcon,
- MonitorOffIcon,
SettingsIcon,
- SparklesIcon,
} from 'lucide-react';
import { memo, type ReactNode, useCallback, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { DOWNLOAD_URL } from '@/const/url';
+import { useChatInputResourceAccess } from '@/features/ChatInput/hooks/useChatInputResourceAccess';
import { useSelectExecutionTarget } from '@/features/ChatInput/hooks/useSelectExecutionTarget';
import { useDeviceList } from '@/features/DeviceManager/useDeviceList';
+import {
+ ExecutionTargetDeviceStatus,
+ ExecutionTargetIcon,
+ groupExecutionTargetDevices,
+} from '@/features/ExecutionTargetPicker';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import {
isHeterogeneousSandboxExecutionAvailable,
@@ -63,6 +62,15 @@ const styles = createStaticStyles(({ css }) => ({
background: ${cssVar.colorFillSecondary};
}
`,
+ buttonDisabled: css`
+ cursor: not-allowed;
+ opacity: 0.5;
+
+ &:hover {
+ color: ${cssVar.colorTextSecondary};
+ background: transparent;
+ }
+ `,
buttonLabel: css`
overflow: hidden;
max-width: 120px;
@@ -82,25 +90,6 @@ const styles = createStaticStyles(({ css }) => ({
font-size: 11px;
color: ${cssVar.colorTextDescription};
`,
- dotOffline: css`
- flex: none;
-
- width: 6px;
- height: 6px;
- border-radius: 50%;
-
- background: ${cssVar.colorTextQuaternary};
- `,
- dotOnline: css`
- flex: none;
-
- width: 6px;
- height: 6px;
- border-radius: 50%;
-
- background: ${cssVar.colorSuccess};
- box-shadow: 0 0 0 2px ${cssVar.colorSuccessBg};
- `,
deviceList: css`
overflow-y: auto;
@@ -323,23 +312,6 @@ const OptionRow = memo<OptionRowProps>(({ active, desc, disabled, icon, label, o
OptionRow.displayName = 'HeteroDeviceSwitcher.OptionRow';
-const getDeviceIcon = (platform: string | null | undefined, size = 14): ReactNode => {
- switch (platform) {
- case 'darwin': {
- return <SiApple color="currentColor" size={size} />;
- }
- case 'linux': {
- return <SiLinux color="currentColor" size={size} />;
- }
- case 'win32': {
- return <Microsoft color="currentColor" size={size} />;
- }
- default: {
- return <Icon icon={MonitorIcon} size={size} />;
- }
- }
-};
-
interface HeteroDeviceSwitcherProps {
agentId: string;
}
@@ -348,6 +320,8 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {
const { t } = useTranslation('chat');
const [open, setOpen] = useState(false);
const navigate = useWorkspaceAwareNavigate();
+ const { canUseResource, isGroupContext } = useChatInputResourceAccess();
+ const viewOnly = !canUseResource;
const agentWorkspaceId = useAgentStore((s) => s.agentMap[agentId]?.workspaceId);
const isWorkspaceAgent = Boolean(agentWorkspaceId);
@@ -361,6 +335,9 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {
workspaceScoped,
} = useEffectiveAgencyConfig(agentId);
+ const isFixedExecutionTarget =
+ isWorkspaceAgent && agencyConfig?.executionTargetSelectionPolicy === 'fixed';
+
const heteroType = agencyConfig?.heterogeneousProvider?.type;
const boundDeviceId = agencyConfig?.boundDeviceId;
@@ -428,6 +405,10 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {
// default would clobber it.
useEffect(() => {
if (!isDesktop) return;
+ // View-only members must not write anything — not even the harmless
+ // per-user local-device default.
+ if (viewOnly) return;
+ if (isFixedExecutionTarget) return;
if (isWorkspacePreferenceLoading) return;
if (agencyConfig?.executionTarget !== undefined) return;
if (agencyConfig?.boundDeviceId !== undefined) return;
@@ -439,6 +420,8 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {
agencyConfig?.boundDeviceId,
currentDeviceId,
isWorkspacePreferenceLoading,
+ isFixedExecutionTarget,
+ viewOnly,
]);
// Don't render for remote hetero agents — they use RemoteAgentConfigCard in profile.
@@ -466,15 +449,10 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {
//
// Naming — Personal is reserved for the account-tier concept; workspace
// groupings say Private/Workspace (私人/工作区) instead.
- const privateDevices = isWorkspaceAgent
- ? (devices ?? []).filter((d) => d.scope === 'workspace' && d.visibility === 'private')
- : [];
- const workspaceDevices = isWorkspaceAgent
- ? (devices ?? []).filter((d) => d.scope === 'workspace' && d.visibility !== 'private')
- : [];
- const personalOnlyDevices = isWorkspaceAgent
- ? []
- : (devices ?? []).filter((d) => d.scope === 'personal');
+ const { personal, privateWorkspace, workspace } = groupExecutionTargetDevices(devices);
+ const privateDevices = isWorkspaceAgent ? privateWorkspace : [];
+ const workspaceDevices = isWorkspaceAgent ? workspace : [];
+ const personalOnlyDevices = isWorkspaceAgent ? [] : personal;
// Workspace agents always render the Private / Workspace group split (even
// when one side is empty — the labels tell the user which pool they're
// looking at). Personal mode stays flat.
@@ -495,20 +473,20 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {
const showWorkspaceEnrollHint = isWorkspaceAgent && hasNoDevices && !isLoading;
// Compute chip
- let chipIcon: ReactNode = <Icon icon={BoxIcon} size={14} />;
+ let chipIcon: ReactNode = <ExecutionTargetIcon target={'sandbox'} />;
let chipLabel = t('heteroAgent.executionTarget.sandbox');
if (executionTarget === 'none') {
- chipIcon = <Icon icon={MonitorOffIcon} size={14} />;
+ chipIcon = <ExecutionTargetIcon target={'none'} />;
chipLabel = t('heteroAgent.executionTarget.none');
} else if (executionTarget === 'auto') {
- chipIcon = <Icon icon={SparklesIcon} size={14} />;
+ chipIcon = <ExecutionTargetIcon target={'auto'} />;
chipLabel = t('heteroAgent.executionTarget.auto');
} else if (executionTarget === 'local') {
// 本机始终使用通用的本地电脑图标,不区分具体平台
- chipIcon = <Icon icon={LaptopIcon} size={14} />;
+ chipIcon = <ExecutionTargetIcon target={'local'} />;
chipLabel = t('heteroAgent.executionTarget.local');
} else if (executionTarget === 'device') {
- chipIcon = getDeviceIcon(boundDevice?.platform);
+ chipIcon = <ExecutionTargetIcon devicePlatform={boundDevice?.platform} target={'device'} />;
chipLabel =
boundDevice?.friendlyName ??
boundDevice?.hostname ??
@@ -521,14 +499,11 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {
};
const renderDeviceStatus = (d: NonNullable<typeof devices>[number]) => (
- <>
- <span className={d.online ? styles.dotOnline : styles.dotOffline} />
- <span>
- {d.online
- ? t('heteroAgent.executionTarget.online')
- : t('heteroAgent.executionTarget.offline')}
- </span>
- </>
+ <ExecutionTargetDeviceStatus
+ offlineLabel={t('heteroAgent.executionTarget.offline')}
+ online={d.online}
+ onlineLabel={t('heteroAgent.executionTarget.online')}
+ />
);
const renderDeviceRow = (d: NonNullable<typeof devices>[number]) => {
@@ -537,7 +512,7 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {
<OptionRow
active={isActive('device', d.deviceId)}
disabled={!d.online}
- icon={getDeviceIcon(d.platform)}
+ icon={<ExecutionTargetIcon devicePlatform={d.platform} target={'device'} />}
key={d.deviceId}
label={d.friendlyName || d.hostname || d.deviceId}
tag={isCurrentMachine ? t('heteroAgent.executionTarget.gateway') : undefined}
@@ -588,7 +563,7 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {
<OptionRow
active={isActive('none')}
desc={t('heteroAgent.executionTarget.noneDesc')}
- icon={<Icon icon={MonitorOffIcon} size={14} />}
+ icon={<ExecutionTargetIcon target={'none'} />}
label={t('heteroAgent.executionTarget.none')}
onClick={() => void handleSelect('none')}
/>
@@ -597,7 +572,7 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {
<OptionRow
active={isActive('auto')}
desc={t('heteroAgent.executionTarget.autoDesc')}
- icon={<Icon icon={SparklesIcon} size={14} />}
+ icon={<ExecutionTargetIcon target={'auto'} />}
label={t('heteroAgent.executionTarget.auto')}
onClick={() => void handleSelect('auto')}
/>
@@ -611,7 +586,7 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {
<OptionRow
active={isActive('local')}
desc={t('heteroAgent.executionTarget.localDesc')}
- icon={<Icon icon={LaptopIcon} size={14} />}
+ icon={<ExecutionTargetIcon target={'local'} />}
// 本机统一显示「本地设备」,不再带具体设备名称
label={t('heteroAgent.executionTarget.local')}
onClick={() => void handleSelect('local')}
@@ -620,7 +595,7 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {
<OptionRow
active={isActive('sandbox')}
disabled={!supportsSandbox}
- icon={<Icon icon={BoxIcon} size={14} />}
+ icon={<ExecutionTargetIcon target={'sandbox'} />}
label={t('heteroAgent.executionTarget.sandbox')}
desc={t(
supportsSandbox
@@ -698,6 +673,32 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {
</Flexbox>
);
+ const selectionDisabled = viewOnly || isFixedExecutionTarget;
+ const chip = (
+ <div className={cx(styles.button, selectionDisabled && styles.buttonDisabled)}>
+ {chipIcon}
+ <span className={styles.buttonLabel}>{chipLabel}</span>
+ <Icon icon={ChevronDownIcon} size={12} />
+ </div>
+ );
+
+ // View-level General access: the whole input area is read-only, so the
+ // execution-target picker stays visible but inert (disabled, not hidden).
+ if (selectionDisabled)
+ return (
+ <Tooltip
+ title={t(
+ isFixedExecutionTarget
+ ? 'heteroAgent.executionTarget.fixedTip'
+ : isGroupContext
+ ? 'input.viewOnlyGroup'
+ : 'input.viewOnlyAgent',
+ )}
+ >
+ {chip}
+ </Tooltip>
+ );
+
return (
<Popover
content={content}
@@ -707,11 +708,7 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {
trigger="click"
onOpenChange={setOpen}
>
- <div className={styles.button}>
- {chipIcon}
- <span className={styles.buttonLabel}>{chipLabel}</span>
- <Icon icon={ChevronDownIcon} size={12} />
- </div>
+ {chip}
</Popover>
);
});
diff --git a/src/features/ChatInput/ControlBar/HeteroModel.tsx b/src/features/ChatInput/ControlBar/HeteroModel.tsx
index 312336bdafe..46b5d16eb58 100644
--- a/src/features/ChatInput/ControlBar/HeteroModel.tsx
+++ b/src/features/ChatInput/ControlBar/HeteroModel.tsx
@@ -49,6 +49,7 @@ import { useAgentStore } from '@/store/agent';
import { agentByIdSelectors } from '@/store/agent/selectors';
import { useAgentId } from '../hooks/useAgentId';
+import { useChatInputResourceAccess } from '../hooks/useChatInputResourceAccess';
import { OpenCodeModelSelector } from './OpenCodeModelSelector';
type HeteroReasoningEffort =
@@ -402,11 +403,15 @@ const HeteroModel = memo(() => {
);
const updateAgentConfigById = useAgentStore((s) => s.updateAgentConfigById);
const { allowed: canCreateContent, reason } = usePermission('create_content');
+ // Model/effort picks write the shared agencyConfig — view-only General
+ // access disables the whole picker (disabled, not hidden).
+ const { canUseResource, isGroupContext } = useChatInputResourceAccess();
+ const enabled = canCreateContent && canUseResource;
const [open, setOpen] = useState(false);
const patchProvider = useCallback(
async (patch: Partial<Pick<HeterogeneousProviderConfig, 'effort' | 'model' | 'speed'>>) => {
- if (!canCreateContent || !agentId) return;
+ if (!enabled || !agentId) return;
const nextPatch: Partial<HeterogeneousProviderConfig> = { ...patch };
const providerType = provider?.type;
@@ -442,7 +447,7 @@ const HeteroModel = memo(() => {
agencyConfig: { heterogeneousProvider: nextPatch },
});
},
- [agentId, canCreateContent, provider?.args, provider?.type, updateAgentConfigById],
+ [agentId, enabled, provider?.args, provider?.type, updateAgentConfigById],
);
const closeMenu = useCallback(() => {
setOpen(false);
@@ -579,7 +584,7 @@ const HeteroModel = memo(() => {
const trigger = (
<div
- className={cx(styles.trigger, !canCreateContent && styles.triggerDisabled)}
+ className={cx(styles.trigger, !enabled && styles.triggerDisabled)}
aria-label={t('heteroAgent.modelSelector.ariaLabel', {
model: modelLabel,
reasoning: effortLabel,
@@ -591,9 +596,15 @@ const HeteroModel = memo(() => {
</div>
);
- if (!canCreateContent)
+ if (!enabled)
return (
- <Tooltip title={reason}>
+ <Tooltip
+ title={
+ !canCreateContent
+ ? reason
+ : t(isGroupContext ? 'input.viewOnlyGroup' : 'input.viewOnlyAgent')
+ }
+ >
<div>{trigger}</div>
</Tooltip>
);
diff --git a/src/features/ChatInput/ControlBar/ModeSelector.tsx b/src/features/ChatInput/ControlBar/ModeSelector.tsx
index b2374da4ccf..48d35f5ef5c 100644
--- a/src/features/ChatInput/ControlBar/ModeSelector.tsx
+++ b/src/features/ChatInput/ControlBar/ModeSelector.tsx
@@ -14,6 +14,7 @@ import { useTranslation } from 'react-i18next';
import { useBusinessAgentModeSync } from '@/business/client/hooks/useBusinessAgentMode';
import { useAgentId } from '@/features/ChatInput/hooks/useAgentId';
+import { useChatInputResourceAccess } from '@/features/ChatInput/hooks/useChatInputResourceAccess';
import { useEffectiveAgentMode } from '@/features/ChatInput/hooks/useEffectiveAgentMode';
import { useToggleAgentMode } from '@/features/ChatInput/hooks/useToggleAgentMode';
import { usePermission } from '@/hooks/usePermission';
@@ -138,6 +139,13 @@ const ModeSelector = memo(() => {
useBusinessAgentModeSync(agentId);
const [open, setOpen] = useState(false);
const { allowed: canCreateContent, reason } = usePermission('create_content');
+ // Per-resource General access: view-only members can't send, so switching the
+ // chat/agent mode (a shared agent-config write) is disabled too.
+ const { canUseResource, isGroupContext } = useChatInputResourceAccess();
+ const disabled = !canCreateContent || !canUseResource;
+ const disabledReason = !canCreateContent
+ ? reason
+ : t(isGroupContext ? 'input.viewOnlyGroup' : 'input.viewOnlyAgent');
const { canSelectAgentMode, currentMode, isAgentModeUnavailable } =
useEffectiveAgentMode(agentId);
@@ -145,22 +153,22 @@ const ModeSelector = memo(() => {
const handleSelect = useCallback(
async (mode: 'chat' | 'agent') => {
- if (!canCreateContent) return;
+ if (disabled) return;
if (mode === 'agent' && !canSelectAgentMode) return;
setOpen(false);
await toggleAgentMode(mode === 'agent');
},
- [canCreateContent, canSelectAgentMode, toggleAgentMode],
+ [disabled, canSelectAgentMode, toggleAgentMode],
);
const handleOpenChange = useCallback(
(nextOpen: boolean) => {
- if (!canCreateContent) return;
+ if (disabled) return;
setOpen(nextOpen);
},
- [canCreateContent],
+ [disabled],
);
const agentTooltip = (
@@ -236,16 +244,16 @@ const ModeSelector = memo(() => {
);
const button = (
- <div className={cx(styles.button, !canCreateContent && styles.buttonDisabled)}>
+ <div className={cx(styles.button, disabled && styles.buttonDisabled)}>
<Icon icon={CurrentIcon} size={14} />
<span>{t(`chatMode.${currentMode}`)}</span>
<Icon icon={ChevronDownIcon} size={12} />
</div>
);
- if (!canCreateContent)
+ if (disabled)
return (
- <Tooltip title={reason}>
+ <Tooltip title={disabledReason}>
<div>{button}</div>
</Tooltip>
);
@@ -254,7 +262,7 @@ const ModeSelector = memo(() => {
<Popover
className={styles.popoverPopup}
content={popoverContent}
- open={canCreateContent && open}
+ open={!disabled && open}
placement="topLeft"
trigger="click"
styles={{
diff --git a/src/features/ChatInput/ControlBar/WorkspaceControls.tsx b/src/features/ChatInput/ControlBar/WorkspaceControls.tsx
index 0fa5debaa0e..fa2c1354e9a 100644
--- a/src/features/ChatInput/ControlBar/WorkspaceControls.tsx
+++ b/src/features/ChatInput/ControlBar/WorkspaceControls.tsx
@@ -1,8 +1,11 @@
'use client';
import { isDesktop } from '@lobechat/const';
+import { Tooltip } from '@lobehub/ui';
import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+import { useChatInputResourceAccess } from '@/features/ChatInput/hooks/useChatInputResourceAccess';
import { resolveExecutionTarget } from '@/helpers/executionTarget';
import { useIsGatewayModeEnabled } from '@/helpers/gatewayMode';
import { useEffectiveAgencyConfig } from '@/hooks/useEffectiveAgencyConfig';
@@ -35,6 +38,8 @@ interface WorkspaceControlsProps {
*/
const WorkspaceControls = memo<WorkspaceControlsProps>(
({ agentId, alwaysShowWorkspace = false }) => {
+ const { t } = useTranslation('setting');
+ const { canConfigureResource, canUseResource } = useChatInputResourceAccess();
const runtimeMode = useAgentStore(chatConfigByIdSelectors.getRuntimeModeById(agentId));
const isHeterogeneous = useAgentStore(agentByIdSelectors.isAgentHeterogeneousById(agentId));
// Effective config = shared row + this member's device override (LOBE-11689),
@@ -72,10 +77,42 @@ const WorkspaceControls = memo<WorkspaceControlsProps>(
return null;
};
+ // The directory picker and git controls write shared agent config / run
+ // device git mutations, so members without edit access see the whole
+ // cluster disabled. The device switcher handles its own use-level gate.
+ const workspace = renderWorkspace();
+
return (
<>
<HeteroDeviceSwitcher agentId={agentId} />
- {renderWorkspace()}
+ {workspace &&
+ (canConfigureResource ? (
+ workspace
+ ) : (
+ <Tooltip
+ title={t(
+ canUseResource
+ ? 'permission.accessTag.useOnlyTip'
+ : 'permission.accessTag.viewOnlyTip',
+ )}
+ >
+ {/* Outer div catches hover for the tooltip; the inner one makes
+ the controls inert. */}
+ <div style={{ alignItems: 'center', display: 'flex', gap: 4 }}>
+ <div
+ style={{
+ alignItems: 'center',
+ display: 'flex',
+ gap: 4,
+ opacity: 0.5,
+ pointerEvents: 'none',
+ }}
+ >
+ {workspace}
+ </div>
+ </div>
+ </Tooltip>
+ ))}
</>
);
},
diff --git a/src/features/ChatInput/ControlBar/index.tsx b/src/features/ChatInput/ControlBar/index.tsx
index 2f18e0e1404..883b65e9642 100644
--- a/src/features/ChatInput/ControlBar/index.tsx
+++ b/src/features/ChatInput/ControlBar/index.tsx
@@ -7,9 +7,11 @@ import { agentByIdSelectors } from '@/store/agent/selectors';
import ContextWindow from '../ActionBar/Token';
import { useAgentId } from '../hooks/useAgentId';
+import { useChatInputResourceAccess } from '../hooks/useChatInputResourceAccess';
import { useEffectiveAgentMode } from '../hooks/useEffectiveAgentMode';
import { useChatInputStore } from '../store';
import ApprovalMode from './ApprovalMode';
+import HeteroDeviceSwitcher from './HeteroDeviceSwitcher';
import ModeSelector from './ModeSelector';
import WorkspaceControls from './WorkspaceControls';
@@ -41,6 +43,7 @@ const styles = createStaticStyles(({ css }) => ({
const ControlBar = memo(() => {
const agentId = useAgentId();
+ const { canConfigureResource, isAccessLoading } = useChatInputResourceAccess();
const showContextWindow = useChatInputStore((s) =>
s.rightActions.flat().includes('contextWindow'),
);
@@ -48,6 +51,8 @@ const ControlBar = memo(() => {
const isLoading = useAgentStore((s) => agentByIdSelectors.isAgentConfigLoadingById(agentId)(s));
const { isAgentRuntimeMode } = useEffectiveAgentMode(agentId);
+ if (isAccessLoading) return null;
+
// Skeleton placeholder to prevent layout jump during loading
if (!agentId || isLoading) {
return (
@@ -58,6 +63,18 @@ const ControlBar = memo(() => {
);
}
+ // Can-use members (and viewers, whose chat input is already disabled) see
+ // only the execution device. It is a per-member usage choice, not shared
+ // AgentConfig; fixed agents keep the same chip visible but disabled.
+ if (!canConfigureResource) {
+ if (!isAgentRuntimeMode) return null;
+ return (
+ <Flexbox horizontal align={'center'} className={styles.bar}>
+ <HeteroDeviceSwitcher agentId={agentId} />
+ </Flexbox>
+ );
+ }
+
return (
<Flexbox horizontal align={'center'} className={styles.bar} justify={'space-between'}>
{/* Left: chat-mode switcher + (agent-only) execution device + working directory */}
diff --git a/src/features/ChatInput/InputEditor/index.test.tsx b/src/features/ChatInput/InputEditor/index.test.tsx
index e4d235441ea..a0d01e52fa9 100644
--- a/src/features/ChatInput/InputEditor/index.test.tsx
+++ b/src/features/ChatInput/InputEditor/index.test.tsx
@@ -151,6 +151,9 @@ vi.mock('@/store/chat', () => ({
vi.mock('../hooks/useChatInputDraft', () => ({
useChatInputDraft: () => ({ restoreDraft: vi.fn(), saveDraftDebounced: vi.fn() }),
}));
+vi.mock('../hooks/useChatInputResourceAccess', () => ({
+ useChatInputResourceAccess: () => ({ canUseResource: true, isGroupContext: false }),
+}));
vi.mock('@/store/agent', () => ({
useAgentStore: <T,>(selector: StoreSelector<T>) => selector({}),
}));
diff --git a/src/features/ChatInput/InputEditor/index.tsx b/src/features/ChatInput/InputEditor/index.tsx
index 744417c2653..4ec3c987088 100644
--- a/src/features/ChatInput/InputEditor/index.tsx
+++ b/src/features/ChatInput/InputEditor/index.tsx
@@ -37,6 +37,7 @@ import {
import { useAgentId } from '../hooks/useAgentId';
import { useChatInputDraft } from '../hooks/useChatInputDraft';
import { useChatInputHistory } from '../hooks/useChatInputHistory';
+import { useChatInputResourceAccess } from '../hooks/useChatInputResourceAccess';
import { useChatInputStore, useStoreApi } from '../store';
import {
INSERT_ACTION_TAG_COMMAND,
@@ -108,6 +109,9 @@ const InputEditor = memo<{
const restoredDraftEditorRef = useRef<IEditor | null>(null);
const state = useEditorState(editor);
const { allowed: canCreateContent } = usePermission('create_content');
+ // view-level General access on the bound agent/group = full read-only input,
+ // matching the workspace-viewer treatment (ChatInputNotice explains why).
+ const { canUseResource } = useChatInputResourceAccess();
const hotkey = useUserStore(settingsSelectors.getHotkeyById(HotkeyEnum.AddUserMessage));
const userId = useUserStore(userProfileSelectors.userId);
const { enableScope, disableScope } = useHotkeysContext();
@@ -537,7 +541,7 @@ const InputEditor = memo<{
pasteAsPlainText
className={className}
content={''}
- editable={canCreateContent}
+ editable={canCreateContent && canUseResource}
editor={editor}
getPopupContainer={() => (slashMenuRef as any)?.current ?? null}
{...{ slashPlacement }}
diff --git a/src/features/ChatInput/SendArea/SendButton.tsx b/src/features/ChatInput/SendArea/SendButton.tsx
index dc2d908a392..857c964bb9e 100644
--- a/src/features/ChatInput/SendArea/SendButton.tsx
+++ b/src/features/ChatInput/SendArea/SendButton.tsx
@@ -2,12 +2,15 @@ import { SendButton as Send } from '@lobehub/editor/react';
import { Tooltip } from '@lobehub/ui';
import isEqual from 'fast-deep-equal';
import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
import { usePermission } from '@/hooks/usePermission';
+import { useChatInputResourceAccess } from '../hooks/useChatInputResourceAccess';
import { selectors, useChatInputStore } from '../store';
const SendButton = memo(() => {
+ const { t } = useTranslation('setting');
const sendMenu = useChatInputStore((s) => s.sendMenu);
const shape = useChatInputStore((s) => s.sendButtonProps?.shape);
const size = useChatInputStore((s) => s.sendButtonProps?.size);
@@ -19,21 +22,29 @@ const SendButton = memo(() => {
// visibly grays out and a tooltip explains why.
const { allowed: canCreate, reason } = usePermission('create_content');
+ // Per-resource General-access gating: a member with view-only access on the
+ // bound agent/group can read the conversation but the server rejects sends.
+ const { canUseResource } = useChatInputResourceAccess();
+ const viewOnly = !canUseResource;
+ const canSend = canCreate && !viewOnly;
+
const button = (
<Send
- disabled={disabled || !canCreate}
+ disabled={disabled || !canSend}
generating={generating}
- menu={canCreate ? (sendMenu as any) : undefined}
+ menu={canSend ? (sendMenu as any) : undefined}
placement={'topRight'}
shape={shape}
size={size}
trigger={['hover']}
- onClick={generating || !canCreate ? undefined : () => send()}
+ onClick={generating || !canSend ? undefined : () => send()}
onStop={() => handleStop()}
/>
);
- return canCreate ? button : <Tooltip title={reason}>{button}</Tooltip>;
+ if (!canCreate) return <Tooltip title={reason}>{button}</Tooltip>;
+ if (viewOnly) return <Tooltip title={t('permission.viewOnlySendTip')}>{button}</Tooltip>;
+ return button;
});
SendButton.displayName = 'SendButton';
diff --git a/src/features/ChatInput/hooks/useAgentModelSelection.test.ts b/src/features/ChatInput/hooks/useAgentModelSelection.test.ts
new file mode 100644
index 00000000000..5e35e501622
--- /dev/null
+++ b/src/features/ChatInput/hooks/useAgentModelSelection.test.ts
@@ -0,0 +1,142 @@
+import { renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useAgentModelSelection } from './useAgentModelSelection';
+
+const testState = vi.hoisted(() => ({
+ agent: {
+ agencyConfig: undefined as { modelSelectionPolicy?: 'fixed' | 'member' } | undefined,
+ isWorkspaceAgent: false,
+ model: 'shared-model',
+ provider: 'shared-provider',
+ updateAgentConfigById: vi.fn(),
+ },
+ user: {
+ fetchedPreference: undefined as
+ | {
+ agentModelOverrides?: Record<string, { model: string; provider: string }>;
+ }
+ | null
+ | undefined,
+ isLoading: false,
+ updateWorkspaceUserPreference: vi.fn(),
+ useFetchWorkspaceUserPreference: () => ({
+ data: testState.user.fetchedPreference,
+ isLoading: testState.user.isLoading,
+ }),
+ workspaceUserPreference: {} as {
+ agentModelOverrides?: Record<string, { model: string; provider: string }>;
+ },
+ },
+}));
+
+vi.mock('@/business/client/hooks/useBusinessAgentMode', () => ({
+ useBusinessModelModeConfig: () => (config: unknown) => config,
+}));
+
+vi.mock('@/store/agent', () => ({
+ useAgentStore: (selector: (s: typeof testState.agent) => unknown) => selector(testState.agent),
+}));
+
+vi.mock('@/store/agent/selectors', () => ({
+ agentByIdSelectors: {
+ getAgencyConfigById: () => (s: typeof testState.agent) => s.agencyConfig,
+ getAgentModelById: () => (s: typeof testState.agent) => s.model,
+ getAgentModelProviderById: () => (s: typeof testState.agent) => s.provider,
+ isWorkspaceAgentById: () => (s: typeof testState.agent) => s.isWorkspaceAgent,
+ },
+}));
+
+vi.mock('@/store/user', () => ({
+ useUserStore: (selector: (s: typeof testState.user) => unknown) => selector(testState.user),
+}));
+
+describe('useAgentModelSelection', () => {
+ beforeEach(() => {
+ testState.agent.agencyConfig = undefined;
+ testState.agent.isWorkspaceAgent = false;
+ testState.agent.model = 'shared-model';
+ testState.agent.provider = 'shared-provider';
+ testState.agent.updateAgentConfigById = vi.fn();
+ testState.user.fetchedPreference = undefined;
+ testState.user.isLoading = false;
+ testState.user.updateWorkspaceUserPreference = vi.fn();
+ testState.user.workspaceUserPreference = {};
+ });
+
+ it('keeps the legacy shared-config write for a personal Agent', async () => {
+ const { result } = renderHook(() => useAgentModelSelection('agent-1'));
+
+ await result.current.selectModel({ model: 'next-model', provider: 'next-provider' });
+
+ expect(result.current).toMatchObject({
+ isWorkspaceAgent: false,
+ model: 'shared-model',
+ provider: 'shared-provider',
+ });
+ expect(testState.agent.updateAgentConfigById).toHaveBeenCalledWith('agent-1', {
+ model: 'next-model',
+ provider: 'next-provider',
+ });
+ expect(testState.user.updateWorkspaceUserPreference).not.toHaveBeenCalled();
+ });
+
+ it('defaults a workspace Agent to fixed and ignores a retained personal choice', async () => {
+ testState.agent.isWorkspaceAgent = true;
+ 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({
+ model: 'shared-model',
+ provider: 'shared-provider',
+ selectionPolicy: 'fixed',
+ });
+ expect(testState.user.updateWorkspaceUserPreference).not.toHaveBeenCalled();
+ expect(testState.agent.updateAgentConfigById).not.toHaveBeenCalled();
+ });
+
+ it('shows and updates the caller override when member selection is enabled', async () => {
+ testState.agent.agencyConfig = { modelSelectionPolicy: 'member' };
+ testState.agent.isWorkspaceAgent = true;
+ testState.user.fetchedPreference = {
+ agentModelOverrides: {
+ 'agent-1': { model: 'member-model', provider: 'member-provider' },
+ 'other': { model: 'other-model', provider: 'other-provider' },
+ },
+ };
+ const { result } = renderHook(() => useAgentModelSelection('agent-1'));
+
+ await result.current.selectModel({ model: 'next-model', provider: 'next-provider' });
+
+ expect(result.current).toMatchObject({
+ model: 'member-model',
+ provider: 'member-provider',
+ selectionPolicy: 'member',
+ });
+ expect(testState.user.updateWorkspaceUserPreference).toHaveBeenCalledWith({
+ agentModelOverrides: {
+ 'agent-1': { model: 'next-model', provider: 'next-provider' },
+ 'other': { model: 'other-model', provider: 'other-provider' },
+ },
+ });
+ expect(testState.agent.updateAgentConfigById).not.toHaveBeenCalled();
+ });
+
+ it('does not overwrite preferences before the workspace bucket settles', async () => {
+ testState.agent.agencyConfig = { modelSelectionPolicy: 'member' };
+ testState.agent.isWorkspaceAgent = true;
+ testState.user.isLoading = true;
+ const { result } = renderHook(() => useAgentModelSelection('agent-1'));
+
+ await result.current.selectModel({ model: 'next-model', provider: 'next-provider' });
+
+ expect(result.current.isPreferenceLoading).toBe(true);
+ expect(testState.user.updateWorkspaceUserPreference).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/features/ChatInput/hooks/useAgentModelSelection.ts b/src/features/ChatInput/hooks/useAgentModelSelection.ts
new file mode 100644
index 00000000000..c9bc58b378f
--- /dev/null
+++ b/src/features/ChatInput/hooks/useAgentModelSelection.ts
@@ -0,0 +1,94 @@
+'use client';
+
+import type { AgentModelSelectionPolicy } from '@lobechat/types';
+import { resolveAgentModelConfig } from '@lobechat/types';
+import { useCallback } from 'react';
+
+import { useBusinessModelModeConfig } from '@/business/client/hooks/useBusinessAgentMode';
+import { useAgentStore } from '@/store/agent';
+import { agentByIdSelectors } from '@/store/agent/selectors';
+import { useUserStore } from '@/store/user';
+
+interface ModelSelection {
+ model: string;
+ provider: string;
+}
+
+export interface UseAgentModelSelectionResult extends ModelSelection {
+ isPreferenceLoading: boolean;
+ isWorkspaceAgent: boolean;
+ selectionPolicy: AgentModelSelectionPolicy;
+ selectModel: (selection: ModelSelection) => Promise<void>;
+}
+
+/**
+ * Read and update the model used by the current caller for one Agent.
+ *
+ * Personal Agents keep the legacy behavior: selecting a model updates the
+ * Agent row. Workspace Agents in member-selection mode instead write a
+ * per-user override, leaving the shared default untouched. The same hook is
+ * used by both chat model triggers so their displayed value and write target
+ * cannot diverge.
+ */
+export const useAgentModelSelection = (agentId: string): UseAgentModelSelectionResult => {
+ const sharedAgencyConfig = useAgentStore(agentByIdSelectors.getAgencyConfigById(agentId));
+ const sharedModel = useAgentStore(agentByIdSelectors.getAgentModelById(agentId));
+ const sharedProvider = useAgentStore(agentByIdSelectors.getAgentModelProviderById(agentId));
+ const isWorkspaceAgent = useAgentStore(agentByIdSelectors.isWorkspaceAgentById(agentId));
+ const updateAgentConfigById = useAgentStore((s) => s.updateAgentConfigById);
+
+ const updateWorkspaceUserPreference = useUserStore((s) => s.updateWorkspaceUserPreference);
+ const storePreference = useUserStore((s) => s.workspaceUserPreference);
+ const { data: fetchedPreference, isLoading } = useUserStore(
+ (s) => s.useFetchWorkspaceUserPreference,
+ )();
+ const preference = fetchedPreference === undefined ? storePreference : (fetchedPreference ?? {});
+ const memberOverride = isWorkspaceAgent ? preference.agentModelOverrides?.[agentId] : undefined;
+ const effectiveModel = resolveAgentModelConfig(
+ {
+ agencyConfig: sharedAgencyConfig,
+ model: sharedModel,
+ provider: sharedProvider,
+ },
+ memberOverride,
+ );
+ const selectionPolicy = sharedAgencyConfig?.modelSelectionPolicy ?? 'fixed';
+ const applyBusinessModelModeConfig = useBusinessModelModeConfig();
+
+ const selectModel = useCallback(
+ async (selection: ModelSelection) => {
+ if (isWorkspaceAgent) {
+ if (selectionPolicy !== 'member' || isLoading) return;
+
+ await updateWorkspaceUserPreference({
+ agentModelOverrides: {
+ ...preference.agentModelOverrides,
+ [agentId]: selection,
+ },
+ });
+ return;
+ }
+
+ await updateAgentConfigById(agentId, applyBusinessModelModeConfig(selection));
+ },
+ [
+ agentId,
+ applyBusinessModelModeConfig,
+ isLoading,
+ isWorkspaceAgent,
+ preference.agentModelOverrides,
+ selectionPolicy,
+ updateAgentConfigById,
+ updateWorkspaceUserPreference,
+ ],
+ );
+
+ return {
+ isPreferenceLoading: isWorkspaceAgent && isLoading,
+ isWorkspaceAgent,
+ model: effectiveModel.model,
+ provider: effectiveModel.provider ?? sharedProvider,
+ selectionPolicy,
+ selectModel,
+ };
+};
diff --git a/src/features/ChatInput/hooks/useChatInputResourceAccess.ts b/src/features/ChatInput/hooks/useChatInputResourceAccess.ts
new file mode 100644
index 00000000000..6fd5481645a
--- /dev/null
+++ b/src/features/ChatInput/hooks/useChatInputResourceAccess.ts
@@ -0,0 +1,55 @@
+'use client';
+
+import { useResourceAccess } from '@/features/ResourcePermission/useResourceAccess';
+import { usePermission } from '@/hooks/usePermission';
+import { useAgentStore } from '@/store/agent';
+import { builtinAgentSelectors } from '@/store/agent/selectors';
+import { useAgentGroupStore } from '@/store/agentGroup';
+import { agentGroupSelectors } from '@/store/agentGroup/selectors';
+
+import { useChatInputStore } from '../store';
+
+/**
+ * Per-resource General-access gating for the chat input: resolves which
+ * workspace resource this input sends to (the bound agent, or the group when
+ * the input reuses the supervisor's agentId as context — see useGroupContext)
+ * and reports whether the member may use it. Home/new-conversation inputs (no
+ * explicit agentId), the inbox agent, and private resources are never gated;
+ * loading defaults permissive — the server remains the enforcement point.
+ */
+export const useChatInputResourceAccess = () => {
+ const chatInputAgentId = useChatInputStore((s) => s.agentId);
+ const inboxAgentId = useAgentStore(builtinAgentSelectors.inboxAgentId);
+ const agentVisibility = useAgentStore((s) =>
+ chatInputAgentId ? s.agentMap[chatInputAgentId]?.visibility : undefined,
+ );
+ const activeGroup = useAgentGroupStore((s) =>
+ s.activeGroupId ? agentGroupSelectors.getGroupById(s.activeGroupId)(s) : undefined,
+ );
+ const isGroupContext =
+ !!chatInputAgentId && !!activeGroup && activeGroup.supervisorAgentId === chatInputAgentId;
+
+ const gatedResourceId = isGroupContext
+ ? activeGroup.visibility === 'private'
+ ? undefined
+ : activeGroup.id
+ : chatInputAgentId && chatInputAgentId !== inboxAgentId && agentVisibility !== 'private'
+ ? chatInputAgentId
+ : undefined;
+
+ const { allowed: canCreateContent } = usePermission('create_content');
+ const { allowed: canEditContent } = usePermission('edit_own_content');
+ const {
+ canEditResource,
+ canUseResource: canUseResourceLevel,
+ isAccessResolved,
+ isLoading: isAccessLoading,
+ } = useResourceAccess(isGroupContext ? 'agentGroup' : 'agent', gatedResourceId);
+
+ return {
+ canConfigureResource: isAccessResolved && canEditContent && canEditResource,
+ canUseResource: canCreateContent && canUseResourceLevel,
+ isAccessLoading,
+ isGroupContext,
+ };
+};
diff --git a/src/features/ChatInput/hooks/useSelectExecutionTarget.test.ts b/src/features/ChatInput/hooks/useSelectExecutionTarget.test.ts
index fe9363609e0..c4997dc83e3 100644
--- a/src/features/ChatInput/hooks/useSelectExecutionTarget.test.ts
+++ b/src/features/ChatInput/hooks/useSelectExecutionTarget.test.ts
@@ -8,6 +8,7 @@ const testState = vi.hoisted(() => ({
agencyConfig: undefined as
| {
boundDeviceId?: string;
+ executionTargetSelectionPolicy?: 'fixed' | 'member';
executionTarget?: string;
heterogeneousProvider?: { type: string };
}
@@ -165,6 +166,20 @@ describe('useSelectExecutionTarget', () => {
expect(testState.agent.updateAgentConfigById).not.toHaveBeenCalled();
});
+ it('does not write a member override while the shared execution target is fixed', async () => {
+ testState.agent.agencyConfig = {
+ boundDeviceId: 'fixed-device',
+ executionTargetSelectionPolicy: 'fixed',
+ executionTarget: 'device',
+ };
+ const { result } = renderHook(() => useSelectExecutionTarget('agent-id'));
+
+ await result.current('device', 'another-device');
+
+ expect(testState.user.updateWorkspaceUserPreference).not.toHaveBeenCalled();
+ expect(testState.agent.updateAgentConfigById).not.toHaveBeenCalled();
+ });
+
it("accepts 'local' for a workspace agent and stores it in the workspace-scoped preference", async () => {
testState.isDesktop = true;
testState.electron.gatewayDeviceInfo = { deviceId: 'this-machine' };
diff --git a/src/features/ChatInput/hooks/useSelectExecutionTarget.ts b/src/features/ChatInput/hooks/useSelectExecutionTarget.ts
index 9684964b7f4..5ea7dd22c13 100644
--- a/src/features/ChatInput/hooks/useSelectExecutionTarget.ts
+++ b/src/features/ChatInput/hooks/useSelectExecutionTarget.ts
@@ -57,6 +57,11 @@ export const useSelectExecutionTarget = (agentId: string) => {
return useCallback(
async (target: DeviceExecutionTarget, deviceId?: string) => {
+ // Fixed workspace agents are author-controlled. Keep any existing member
+ // override dormant (so switching back to member choice restores it), but
+ // never let this picker create or update an override while fixed.
+ if (isWorkspaceAgent && agencyConfig?.executionTargetSelectionPolicy === 'fixed') return;
+
const boundDeviceId = agencyConfig?.boundDeviceId;
let nextBoundDeviceId = target === 'device' ? deviceId : boundDeviceId;
if (target === 'local') {
diff --git a/src/features/Conversation/ChatInput/QueueTray.tsx b/src/features/Conversation/ChatInput/QueueTray.tsx
index 3515934e742..0eb51e9bd9b 100644
--- a/src/features/Conversation/ChatInput/QueueTray.tsx
+++ b/src/features/Conversation/ChatInput/QueueTray.tsx
@@ -17,6 +17,7 @@ import {
import { messageMapKey } from '@/store/chat/utils/messageMapKey';
import { useFileStore } from '@/store/file';
+import { useConversationResourceAccess } from '../hooks/useConversationResourceAccess';
import { useConversationStore } from '../store';
const PREVIEW_SIZE = 28;
@@ -124,6 +125,7 @@ const QueuedFilePreview = memo<QueuedFilePreviewProps>(({ file }) => {
QueuedFilePreview.displayName = 'QueuedFilePreview';
const QueueTray = memo(() => {
+ const { canUseResource } = useConversationResourceAccess();
const { t } = useTranslation('chat');
const context = useConversationStore((s) => s.context);
@@ -220,6 +222,10 @@ const QueueTray = memo(() => {
);
if (queuedMessages.length === 0) return null;
+ // Defense-in-depth: normally a view-only member can't enqueue at all, but a
+ // mid-session access downgrade could leave items behind — never offer
+ // "send now" then.
+ if (!canUseResource) return null;
return (
<Flexbox className={styles.container} gap={0}>
diff --git a/src/features/Conversation/Error/index.tsx b/src/features/Conversation/Error/index.tsx
index f824b0caf26..52036546f8c 100644
--- a/src/features/Conversation/Error/index.tsx
+++ b/src/features/Conversation/Error/index.tsx
@@ -12,6 +12,7 @@ import useBusinessErrorAlertConfig from '@/business/client/hooks/useBusinessErro
import useBusinessErrorContent from '@/business/client/hooks/useBusinessErrorContent';
import useRenderBusinessChatErrorMessageExtra from '@/business/client/hooks/useRenderBusinessChatErrorMessageExtra';
import ErrorContent from '@/features/Conversation/ChatItem/components/ErrorContent';
+import { useConversationResourceAccess } from '@/features/Conversation/hooks/useConversationResourceAccess';
import { dataSelectors, useConversationStore } from '@/features/Conversation/store';
import HeterogeneousAgentStatusGuide from '@/features/Electron/HeterogeneousAgent/StatusGuide';
import type { HeterogeneousAgentScheduleState } from '@/features/Electron/HeterogeneousAgent/StatusGuide/types';
@@ -252,7 +253,11 @@ const ErrorMessageExtra = memo<ErrorExtraProps>(
const enableBusinessFeatures = useServerConfigStore(
serverConfigSelectors.enableBusinessFeatures,
);
- const { allowed: canCreate } = usePermission('create_content');
+ const { allowed: canCreateContent } = usePermission('create_content');
+ // Retry re-sends into the shared conversation — requires use-level General
+ // access on top of the workspace-role capability.
+ const { canUseResource } = useConversationResourceAccess();
+ const canCreate = canCreateContent && canUseResource;
const sessionErrorBody = error?.body;
const rawErrorMessage = getRawErrorMessage(error) || alertError?.message;
diff --git a/src/features/Conversation/MessageForward/ForwardMessageDispatcher.tsx b/src/features/Conversation/MessageForward/ForwardMessageDispatcher.tsx
index 0c67361eee4..8f90709869a 100644
--- a/src/features/Conversation/MessageForward/ForwardMessageDispatcher.tsx
+++ b/src/features/Conversation/MessageForward/ForwardMessageDispatcher.tsx
@@ -6,6 +6,7 @@ import { useLocation } from 'react-router';
import { useAgentStore } from '@/store/agent';
import { agentSelectors } from '@/store/agent/selectors';
+import { useConversationResourceAccess } from '../hooks/useConversationResourceAccess';
import { useConversationStore } from '../store';
import { canConsumePendingForward } from './forwardDispatch';
import { useForwardDispatchStore } from './forwardDispatchStore';
@@ -27,6 +28,10 @@ const ForwardMessageDispatcher = () => {
s.pendingForward,
s.clearPendingForward,
]);
+ // The target picker doesn't know each candidate's General-access level, so
+ // the dispatcher is the enforcement point: a view-only target drops the
+ // parked forward instead of sending. Wait for the settled value.
+ const { canUseResource, isAccessLoading } = useConversationResourceAccess();
const routeAgentId = useMemo(() => {
const match = location.pathname?.match(/^\/agent\/([^#/?]+)/);
@@ -48,17 +53,23 @@ const ForwardMessageDispatcher = () => {
return;
}
+ if (isAccessLoading) return;
+
if (lastProcessedRef.current === pendingForward!.dispatchId) return;
lastProcessedRef.current = pendingForward!.dispatchId;
const { content, dispatchId } = pendingForward!;
clearPendingForward(dispatchId);
+ if (!canUseResource) return;
+
void sendMessage({ message: content });
}, [
agentId,
+ canUseResource,
clearPendingForward,
context.topicId,
+ isAccessLoading,
isAgentConfigLoading,
pendingForward,
routeAgentId,
diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/ApprovalActions.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/ApprovalActions.tsx
index 54786015f1a..f43fed5f51f 100644
--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/ApprovalActions.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/ApprovalActions.tsx
@@ -8,6 +8,7 @@ import { useTranslation } from 'react-i18next';
import { useUserStore } from '@/store/user';
+import { useConversationResourceAccess } from '../../../../../hooks/useConversationResourceAccess';
import { useConversationStore } from '../../../../../store';
import { type ApprovalMode } from './index';
@@ -134,6 +135,9 @@ const ApprovalActions = memo<ApprovalActionsProps>(
const isMessageCreating = messageId.startsWith('tmp_');
const isAllowListMode = approvalMode === 'allow-list';
+ // Workspace topics are shared: a view-only member can be LOOKING at a
+ // teammate's running conversation — they must not drive its tool approvals.
+ const { canUseResource } = useConversationResourceAccess();
// Ordered choices drive both the numbered rows and the 1/2/3 shortcuts.
// "Approve & don't ask again" is a first-class option (allow-list only)
@@ -150,7 +154,7 @@ const ApprovalActions = memo<ApprovalActionsProps>(
const addToolToAllowList = useUserStore((s) => s.addToolToAllowList);
const handleSubmit = useCallback(async () => {
- if (loading || isMessageCreating) return;
+ if (loading || isMessageCreating || !canUseResource) return;
setLoading(true);
try {
if (choice === 'reject') {
@@ -170,6 +174,7 @@ const ApprovalActions = memo<ApprovalActionsProps>(
apiName,
approveToolCall,
assistantGroupId,
+ canUseResource,
choice,
identifier,
isAllowListMode,
@@ -193,6 +198,7 @@ const ApprovalActions = memo<ApprovalActionsProps>(
// typing anywhere on the page so we never hijack the main chat composer.
// The reject input has its own onKeyDown for Enter / ↑.
useEffect(() => {
+ if (!canUseResource) return;
const handler = (e: KeyboardEvent) => {
const target = e.target as HTMLElement | null;
if (target) {
@@ -234,7 +240,7 @@ const ApprovalActions = memo<ApprovalActionsProps>(
return () => {
window.removeEventListener('keydown', handler);
};
- }, [choices, handleSubmit]);
+ }, [canUseResource, choices, handleSubmit]);
const handleRejectInputKeyDown = (e: ReactKeyboardEvent<HTMLInputElement>) => {
if (e.metaKey || e.ctrlKey || e.altKey) return;
@@ -257,6 +263,10 @@ const ApprovalActions = memo<ApprovalActionsProps>(
'approve-remember': t('tool.intervention.optionApproveRemember'),
};
+ // View-only members see the pending intervention but get no approval
+ // controls — the run belongs to a member who can use the agent.
+ if (!canUseResource) return null;
+
return (
<Flexbox className={styles.container}>
<div className={styles.optionList} role="radiogroup">
diff --git a/src/features/Conversation/Messages/components/MessageActionBar/useBuildActions.ts b/src/features/Conversation/Messages/components/MessageActionBar/useBuildActions.ts
index ea935951768..8b397532eed 100644
--- a/src/features/Conversation/Messages/components/MessageActionBar/useBuildActions.ts
+++ b/src/features/Conversation/Messages/components/MessageActionBar/useBuildActions.ts
@@ -1,3 +1,4 @@
+import { useConversationResourceAccess } from '../../../hooks/useConversationResourceAccess';
import { type MessageActionItem } from '../../../types';
import { branchingAction } from './actions/branching';
import { collapseAction } from './actions/collapse';
@@ -25,18 +26,42 @@ import { type MessageActionContext } from './types';
*/
export const useBuildActions = (
ctx: MessageActionContext,
-): Record<string, MessageActionItem | null> => ({
- branching: branchingAction.useBuild(ctx),
- collapse: collapseAction.useBuild(ctx),
- continueGeneration: continueGenerationAction.useBuild(ctx),
- copy: copyAction.useBuild(ctx),
- del: delAction.useBuild(ctx),
- delAndRegenerate: delAndRegenerateAction.useBuild(ctx),
- edit: editAction.useBuild(ctx),
- regenerate: regenerateAction.useBuild(ctx),
- restoreToInput: restoreToInputAction.useBuild(ctx),
- select: selectAction.useBuild(ctx),
- share: shareAction.useBuild(ctx),
- translate: translateAction.useBuild(ctx),
- tts: ttsAction.useBuild(ctx),
-});
+): Record<string, MessageActionItem | null> => {
+ // View-only General access on the conversation's agent/group: mutating
+ // actions (send/regenerate/edit/delete/translate/tts/branch) don't apply —
+ // same "absent when not applicable" rule as the role checks above.
+ const { canUseResource } = useConversationResourceAccess();
+
+ const actions: Record<string, MessageActionItem | null> = {
+ branching: branchingAction.useBuild(ctx),
+ collapse: collapseAction.useBuild(ctx),
+ continueGeneration: continueGenerationAction.useBuild(ctx),
+ copy: copyAction.useBuild(ctx),
+ del: delAction.useBuild(ctx),
+ delAndRegenerate: delAndRegenerateAction.useBuild(ctx),
+ edit: editAction.useBuild(ctx),
+ regenerate: regenerateAction.useBuild(ctx),
+ restoreToInput: restoreToInputAction.useBuild(ctx),
+ select: selectAction.useBuild(ctx),
+ share: shareAction.useBuild(ctx),
+ translate: translateAction.useBuild(ctx),
+ tts: ttsAction.useBuild(ctx),
+ };
+
+ if (!canUseResource) {
+ for (const key of [
+ 'branching',
+ 'continueGeneration',
+ 'del',
+ 'delAndRegenerate',
+ 'edit',
+ 'regenerate',
+ 'translate',
+ 'tts',
+ ]) {
+ actions[key] = null;
+ }
+ }
+
+ return actions;
+};
diff --git a/src/features/Conversation/components/Reaction/ReactionPicker.tsx b/src/features/Conversation/components/Reaction/ReactionPicker.tsx
index c86897581c8..0d015d00b4f 100644
--- a/src/features/Conversation/components/Reaction/ReactionPicker.tsx
+++ b/src/features/Conversation/components/Reaction/ReactionPicker.tsx
@@ -13,6 +13,7 @@ import { usePermission } from '@/hooks/usePermission';
import { useGlobalStore } from '@/store/global';
import { globalGeneralSelectors } from '@/store/global/selectors';
+import { useConversationResourceAccess } from '../../hooks/useConversationResourceAccess';
import { useConversationStore } from '../../store';
const QUICK_REACTIONS = ['👍', '👎', '❤️', '😄', '😂', '😅', '🎉', '😢', '🤔', '🚀'];
@@ -72,12 +73,15 @@ const ReactionPicker: FC<ReactionPickerProps> = memo(({ messageId, trigger }) =>
const { t } = useTranslation('chat');
const theme = useTheme();
const { allowed: canEdit } = usePermission('edit_own_content');
+ const { canUseResource } = useConversationResourceAccess();
const locale = useGlobalStore(globalGeneralSelectors.currentLanguage);
const addReaction = useConversationStore((s) => s.addReaction);
const [open, setOpen] = useState(false);
const [showFullPicker, setShowFullPicker] = useState(false);
- if (!canEdit) return null;
+ // Reactions write to the shared conversation — view-only members don't get
+ // the affordance (same absent-when-not-applicable rule as message actions).
+ if (!canEdit || !canUseResource) return null;
const handleSelect = (emoji: string) => {
addReaction(messageId, emoji);
diff --git a/src/features/Conversation/hooks/useChatItemContextMenu.tsx b/src/features/Conversation/hooks/useChatItemContextMenu.tsx
index 3dcbf935c9d..4a917315df3 100644
--- a/src/features/Conversation/hooks/useChatItemContextMenu.tsx
+++ b/src/features/Conversation/hooks/useChatItemContextMenu.tsx
@@ -30,6 +30,7 @@ import {
useConversationStoreApi,
} from '../store';
import { useChatListActionsBar } from './useChatListActionsBar';
+import { useConversationResourceAccess } from './useConversationResourceAccess';
interface ActionMenuItem extends ActionIconGroupItemType {
children?: { key: string; label: ReactNode }[];
@@ -56,8 +57,13 @@ export const useChatItemContextMenu = ({
const contextMenuMode = useUserStore(userGeneralSettingsSelectors.contextMenuMode);
const { message } = App.useApp();
const { t } = useTranslation('common');
- const { allowed: canCreate } = usePermission('create_content');
- const { allowed: canEdit } = usePermission('edit_own_content');
+ const { allowed: canCreateContent } = usePermission('create_content');
+ const { allowed: canEditContent } = usePermission('edit_own_content');
+ // Mutating menu entries need the workspace-role capability AND use-level
+ // General access on this conversation's agent/group (view-only = read-only).
+ const { canUseResource } = useConversationResourceAccess();
+ const canCreate = canCreateContent && canUseResource;
+ const canEdit = canEditContent && canUseResource;
const selectedTextRef = useRef<string | undefined>(undefined);
diff --git a/src/features/Conversation/hooks/useConversationResourceAccess.ts b/src/features/Conversation/hooks/useConversationResourceAccess.ts
new file mode 100644
index 00000000000..883359fb59f
--- /dev/null
+++ b/src/features/Conversation/hooks/useConversationResourceAccess.ts
@@ -0,0 +1,56 @@
+'use client';
+
+import { useResourceAccess } from '@/features/ResourcePermission/useResourceAccess';
+import { usePermission } from '@/hooks/usePermission';
+import { useAgentStore } from '@/store/agent';
+import { builtinAgentSelectors } from '@/store/agent/selectors';
+import { useAgentGroupStore } from '@/store/agentGroup';
+import { agentGroupSelectors } from '@/store/agentGroup/selectors';
+
+import { useConversationStore } from '../store';
+
+/**
+ * Per-resource General-access gating for the CURRENT conversation, resolved
+ * from the ConversationStore context (the agent, or the group for group
+ * conversations). The counterpart of `useChatInputResourceAccess` for
+ * surfaces that live outside the ChatInput store tree — message actions,
+ * intervention approvals, queue tray, URL/forward auto-send dispatchers.
+ *
+ * Workspace topics are shared across members, so a `view`-level member can
+ * open a teammate's conversation — every mutating affordance must check
+ * `canUseResource` before firing. Inbox and private resources are never
+ * gated; loading defaults permissive (`isAccessLoading` lets auto-send
+ * dispatchers wait for the settled value instead).
+ */
+export const useConversationResourceAccess = () => {
+ const [agentId, groupId] = useConversationStore((s) => [s.context?.agentId, s.context?.groupId]);
+ const isGroupContext = !!groupId;
+
+ const inboxAgentId = useAgentStore(builtinAgentSelectors.inboxAgentId);
+ const agentVisibility = useAgentStore((s) =>
+ agentId ? s.agentMap[agentId]?.visibility : undefined,
+ );
+ const group = useAgentGroupStore((s) =>
+ groupId ? agentGroupSelectors.getGroupById(groupId)(s) : undefined,
+ );
+
+ const gatedResourceId = isGroupContext
+ ? group?.visibility === 'private'
+ ? undefined
+ : groupId
+ : agentId && agentId !== inboxAgentId && agentVisibility !== 'private'
+ ? agentId
+ : undefined;
+
+ const { allowed: canCreateContent } = usePermission('create_content');
+ const { canUseResource, isLoading } = useResourceAccess(
+ isGroupContext ? 'agentGroup' : 'agent',
+ gatedResourceId,
+ );
+
+ return {
+ canUseResource: canCreateContent && canUseResource,
+ isAccessLoading: isLoading,
+ isGroupContext,
+ };
+};
diff --git a/src/features/ExecutionTargetPicker/index.test.ts b/src/features/ExecutionTargetPicker/index.test.ts
new file mode 100644
index 00000000000..c7b7bd792e5
--- /dev/null
+++ b/src/features/ExecutionTargetPicker/index.test.ts
@@ -0,0 +1,69 @@
+import type { DeviceListItem } from '@lobechat/types';
+import { describe, expect, it } from 'vitest';
+
+import {
+ executionTargetValue,
+ groupExecutionTargetDevices,
+ isSharedExecutionTarget,
+ parseExecutionTargetValue,
+} from './index';
+
+const device = (overrides: Partial<DeviceListItem>): DeviceListItem =>
+ ({
+ channels: [],
+ defaultCwd: null,
+ deviceId: 'device',
+ enroller: null,
+ friendlyName: null,
+ hostname: null,
+ identitySource: null,
+ lastSeen: '',
+ online: false,
+ platform: null,
+ registered: true,
+ scope: 'personal',
+ visibility: null,
+ workingDirs: [],
+ ...overrides,
+ }) as DeviceListItem;
+
+describe('ExecutionTargetPicker helpers', () => {
+ it('round-trips shared targets and device ids', () => {
+ expect(parseExecutionTargetValue(executionTargetValue('sandbox'))).toEqual({
+ target: 'sandbox',
+ });
+ expect(parseExecutionTargetValue(executionTargetValue('device', 'workspace-device'))).toEqual({
+ deviceId: 'workspace-device',
+ target: 'device',
+ });
+ });
+
+ it('separates personal, private workspace, and public workspace devices', () => {
+ const personal = device({ deviceId: 'personal' });
+ const privateWorkspace = device({
+ deviceId: 'private',
+ scope: 'workspace',
+ visibility: 'private',
+ });
+ const publicWorkspace = device({
+ deviceId: 'public',
+ scope: 'workspace',
+ visibility: 'public',
+ });
+
+ expect(groupExecutionTargetDevices([personal, privateWorkspace, publicWorkspace])).toEqual({
+ personal: [personal],
+ privateWorkspace: [privateWorkspace],
+ publicWorkspace: [publicWorkspace],
+ workspace: [publicWorkspace],
+ });
+ });
+
+ it('allows only server-resolvable targets as shared defaults', () => {
+ expect(isSharedExecutionTarget('none')).toBe(true);
+ expect(isSharedExecutionTarget('auto')).toBe(true);
+ expect(isSharedExecutionTarget('sandbox')).toBe(true);
+ expect(isSharedExecutionTarget('device')).toBe(true);
+ expect(isSharedExecutionTarget('local')).toBe(false);
+ });
+});
diff --git a/src/features/ExecutionTargetPicker/index.tsx b/src/features/ExecutionTargetPicker/index.tsx
new file mode 100644
index 00000000000..c3fea484cc5
--- /dev/null
+++ b/src/features/ExecutionTargetPicker/index.tsx
@@ -0,0 +1,120 @@
+'use client';
+
+import type { DeviceExecutionTarget, DeviceListItem } from '@lobechat/types';
+import { Icon } from '@lobehub/ui';
+import { createStaticStyles, cssVar } from 'antd-style';
+import { BoxIcon, LaptopIcon, MonitorOffIcon, SparklesIcon } from 'lucide-react';
+import { memo } from 'react';
+
+import { getDeviceIcon } from '@/features/DeviceManager/getDeviceIcon';
+
+const styles = createStaticStyles(({ css }) => ({
+ dotOffline: css`
+ flex: none;
+
+ width: 6px;
+ height: 6px;
+ border-radius: 50%;
+
+ background: ${cssVar.colorTextQuaternary};
+ `,
+ dotOnline: css`
+ flex: none;
+
+ width: 6px;
+ height: 6px;
+ border-radius: 50%;
+
+ background: ${cssVar.colorSuccess};
+ box-shadow: 0 0 0 2px ${cssVar.colorSuccessBg};
+ `,
+ status: css`
+ display: inline-flex;
+ gap: 6px;
+ align-items: center;
+ `,
+}));
+
+export const SHARED_EXECUTION_TARGETS = ['auto', 'device', 'none', 'sandbox'] as const;
+
+export const isSharedExecutionTarget = (
+ target: DeviceExecutionTarget | undefined,
+): target is Exclude<DeviceExecutionTarget, 'local'> =>
+ !!target &&
+ SHARED_EXECUTION_TARGETS.includes(target as (typeof SHARED_EXECUTION_TARGETS)[number]);
+
+export const executionTargetValue = (target: DeviceExecutionTarget, deviceId?: string) =>
+ target === 'device' && deviceId ? `device:${deviceId}` : `target:${target}`;
+
+export const parseExecutionTargetValue = (
+ value: string,
+): { deviceId?: string; target: DeviceExecutionTarget } | undefined => {
+ if (value.startsWith('device:')) {
+ const deviceId = value.slice('device:'.length);
+ return deviceId ? { deviceId, target: 'device' } : undefined;
+ }
+
+ if (!value.startsWith('target:')) return undefined;
+ const target = value.slice('target:'.length) as DeviceExecutionTarget;
+ return ['auto', 'local', 'none', 'sandbox'].includes(target) ? { target } : undefined;
+};
+
+export const groupExecutionTargetDevices = (devices: DeviceListItem[] | undefined) => ({
+ personal: (devices ?? []).filter((device) => device.scope === 'personal'),
+ privateWorkspace: (devices ?? []).filter(
+ (device) => device.scope === 'workspace' && device.visibility === 'private',
+ ),
+ publicWorkspace: (devices ?? []).filter(
+ (device) => device.scope === 'workspace' && device.visibility === 'public',
+ ),
+ workspace: (devices ?? []).filter(
+ (device) => device.scope === 'workspace' && device.visibility !== 'private',
+ ),
+});
+
+interface ExecutionTargetIconProps {
+ devicePlatform?: string | null;
+ size?: number;
+ target: DeviceExecutionTarget;
+}
+
+export const ExecutionTargetIcon = memo<ExecutionTargetIconProps>(
+ ({ devicePlatform, size = 14, target }) => {
+ switch (target) {
+ case 'auto': {
+ return <Icon icon={SparklesIcon} size={size} />;
+ }
+ case 'device': {
+ return <>{getDeviceIcon(devicePlatform, size)}</>;
+ }
+ case 'local': {
+ return <Icon icon={LaptopIcon} size={size} />;
+ }
+ case 'none': {
+ return <Icon icon={MonitorOffIcon} size={size} />;
+ }
+ case 'sandbox': {
+ return <Icon icon={BoxIcon} size={size} />;
+ }
+ }
+ },
+);
+
+ExecutionTargetIcon.displayName = 'ExecutionTargetPicker.ExecutionTargetIcon';
+
+interface ExecutionTargetDeviceStatusProps {
+ offlineLabel: string;
+ online: boolean;
+ onlineLabel: string;
+}
+
+export const ExecutionTargetDeviceStatus = memo<ExecutionTargetDeviceStatusProps>(
+ ({ offlineLabel, online, onlineLabel }) => (
+ <span className={styles.status}>
+ <span aria-hidden className={online ? styles.dotOnline : styles.dotOffline} />
+ <span>{online ? onlineLabel : offlineLabel}</span>
+ </span>
+ ),
+);
+
+ExecutionTargetDeviceStatus.displayName = 'ExecutionTargetPicker.ExecutionTargetDeviceStatus';
diff --git a/src/features/PageEditor/Header/useMenu.test.tsx b/src/features/PageEditor/Header/useMenu.test.tsx
index bda22be79f9..779810ed844 100644
--- a/src/features/PageEditor/Header/useMenu.test.tsx
+++ b/src/features/PageEditor/Header/useMenu.test.tsx
@@ -2,7 +2,6 @@
* @vitest-environment happy-dom
*/
import { renderHook } from '@testing-library/react';
-import { renderToStaticMarkup } from 'react-dom/server';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { useMenu } from './useMenu';
@@ -12,17 +11,9 @@ const permissionMock = vi.hoisted(() => ({
edit_own_content: true,
}));
-const headerMock = vi.hoisted(() => ({
- activeWorkspaceId: 'workspace-1' as string | undefined,
- authorName: undefined as string | undefined,
- currentUserId: 'user-1',
- document: {
- id: 'doc-1',
- updatedAt: undefined as string | undefined,
- userId: 'user-1',
- visibility: 'private' as 'private' | 'public',
- },
- transferMenuItems: vi.fn(() => [{ key: 'transfer-document', label: 'Move' }]),
+const resourcePermissionMenuItemMock = vi.hoisted(() => ({
+ args: [] as unknown[],
+ item: null as null | { key: string; label: string },
}));
vi.mock('react-i18next', () => ({
@@ -31,13 +22,7 @@ vi.mock('react-i18next', () => ({
language: 'en-US',
resolvedLanguage: 'en-US',
},
- t: (key: string, options?: Record<string, unknown>) => {
- if (key === 'pageEditor.editedAtBy') {
- return `Last edited on ${options?.time} by ${options?.name}`;
- }
-
- return key;
- },
+ t: (key: string) => key,
}),
}));
@@ -79,21 +64,28 @@ vi.mock('antd-style', () => ({
}));
vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({
- useActiveWorkspaceId: () => headerMock.activeWorkspaceId,
+ useActiveWorkspaceId: () => undefined,
}));
vi.mock('@/business/client/hooks/useAuthorInfo', () => ({
- useAuthorInfo: () => ({ fullName: headerMock.authorName }),
+ useAuthorInfo: () => undefined,
}));
vi.mock('@/business/client/hooks/useDocumentTransferMenuItem', () => ({
- useDocumentTransferMenuItem: headerMock.transferMenuItems,
+ useDocumentTransferMenuItem: () => null,
}));
vi.mock('@/features/VisibilityConfirmContent', () => ({
default: () => null,
}));
+vi.mock('@/features/ResourcePermission/useResourcePermissionMenuItem', () => ({
+ useResourcePermissionMenuItem: (...args: unknown[]) => {
+ resourcePermissionMenuItemMock.args = args;
+ return resourcePermissionMenuItemMock.item;
+ },
+}));
+
vi.mock('@/hooks/usePermission', () => ({
usePermission: (action: 'create_content' | 'edit_own_content') => ({
allowed: permissionMock[action],
@@ -107,7 +99,7 @@ vi.mock('@/store/document', () => ({
vi.mock('@/store/page', () => ({
pageSelectors: {
- getDocumentById: (_id: string) => (_s: unknown) => headerMock.document,
+ getDocumentById: (_id: string) => (_s: unknown) => undefined,
},
usePageStore: (selector: (state: Record<string, unknown>) => unknown) =>
selector({
@@ -117,13 +109,12 @@ vi.mock('@/store/page', () => ({
}));
vi.mock('@/store/user', () => ({
- useUserStore: (selector: (state: { user: { id: string } }) => unknown) =>
- selector({ user: { id: headerMock.currentUserId } }),
+ useUserStore: (selector: (state: Record<string, unknown>) => unknown) => selector({}),
}));
vi.mock('@/store/user/selectors', () => ({
userProfileSelectors: {
- userId: (state: { user: { id: string } }) => state.user.id,
+ userId: () => undefined,
},
}));
@@ -178,38 +169,22 @@ describe('PageEditor header menu', () => {
beforeEach(() => {
permissionMock.create_content = true;
permissionMock.edit_own_content = true;
- headerMock.activeWorkspaceId = 'workspace-1';
- headerMock.authorName = undefined;
- headerMock.document.updatedAt = undefined;
- headerMock.document.userId = headerMock.currentUserId;
- headerMock.document.visibility = 'private';
- headerMock.transferMenuItems.mockClear();
+ resourcePermissionMenuItemMock.args = [];
+ resourcePermissionMenuItemMock.item = null;
});
- it('uses the Move action and does not expose a separate publish action', () => {
- const { result } = renderHook(() => useMenu());
-
- expect(headerMock.transferMenuItems).toHaveBeenCalledWith('doc-1', {
- defaultTargetVisibility: 'private',
- preferCurrentWorkspace: true,
- transferLabel: 'pageEditor.menu.move',
- });
- expect(getMenuItem(result.current.menuItems, 'transfer-document')).toMatchObject({
- label: 'Move',
- });
- expect(getMenuItem(result.current.menuItems, 'publish-to-workspace')).toBeUndefined();
- });
-
- it('renders the last edit footer as natural language without an icon', () => {
- headerMock.authorName = 'Lin';
- headerMock.document.updatedAt = '2026-07-15T08:30:00.000Z';
+ it('places workspace member permission settings in the overflow menu', () => {
+ resourcePermissionMenuItemMock.item = {
+ key: 'member-permissions',
+ label: 'Members: Can view',
+ };
const { result } = renderHook(() => useMenu());
- const infoItem = getMenuItem(result.current.menuItems, 'page-info');
- expect(infoItem?.icon).toBeUndefined();
- expect(renderToStaticMarkup(infoItem?.label)).toContain('Last edited on');
- expect(renderToStaticMarkup(infoItem?.label)).toContain('by Lin');
+ expect(getMenuItem(result.current.menuItems, 'member-permissions')).toMatchObject({
+ label: 'Members: Can view',
+ });
+ expect(resourcePermissionMenuItemMock.args[2]).toEqual({ showReadOnly: true });
});
it('disables mutating page actions for workspace viewers', () => {
diff --git a/src/features/PageEditor/Header/useMenu.tsx b/src/features/PageEditor/Header/useMenu.tsx
index e71d6202ed2..cfb7a8afe89 100644
--- a/src/features/PageEditor/Header/useMenu.tsx
+++ b/src/features/PageEditor/Header/useMenu.tsx
@@ -4,13 +4,23 @@ import { Icon } from '@lobehub/ui';
import { confirmModal } from '@lobehub/ui/base-ui';
import { App } from 'antd';
import { cssVar, useResponsive } from 'antd-style';
-import { Clock3Icon, CopyPlus, Download, EyeOffIcon, Link2, Maximize2, Trash2 } from 'lucide-react';
+import {
+ Clock3Icon,
+ CopyPlus,
+ Download,
+ EyeOffIcon,
+ Link2,
+ Maximize2,
+ Trash2,
+ UsersIcon,
+} from 'lucide-react';
import { useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
import { useAuthorInfo } from '@/business/client/hooks/useAuthorInfo';
import { useDocumentTransferMenuItem } from '@/business/client/hooks/useDocumentTransferMenuItem';
+import { useResourcePermissionMenuItem } from '@/features/ResourcePermission/useResourcePermissionMenuItem';
import VisibilityConfirmContent from '@/features/VisibilityConfirmContent';
import { usePermission } from '@/hooks/usePermission';
import { useDocumentStore } from '@/store/document';
@@ -63,10 +73,19 @@ export const useMenu = (): { menuItems: any[] } => {
transferLabel: t('pageEditor.menu.move'),
}) as DropdownItem[] | null;
+ const publishPageToWorkspace = usePageStore((s) => s.publishPageToWorkspace);
const setPageVisibility = usePageStore((s) => s.setPageVisibility);
+ const canPublish = Boolean(
+ activeWorkspaceId && isOwnPage && pageDocument?.visibility === 'private' && canEditPage,
+ );
const canMakePrivate = Boolean(
activeWorkspaceId && isOwnPage && pageDocument?.visibility === 'public' && canEditPage,
);
+ const memberPermissionMenuItem = useResourcePermissionMenuItem(
+ 'document',
+ activeWorkspaceId && pageDocument?.visibility === 'public' ? documentId : undefined,
+ { showReadOnly: true },
+ ) as DropdownItem | null;
const [togglePageAgentPanel, wideScreen, toggleWideScreen] = useGlobalStore((s) => [
s.togglePageAgentPanel,
@@ -89,6 +108,32 @@ export const useMenu = (): { menuItems: any[] } => {
}
}, [canCreatePage, documentId, duplicateDocument, message, t]);
+ const handlePublish = useCallback(() => {
+ if (!canPublish || !documentId) return;
+ const accessLevelRef: { current: 'edit' | 'view' } = { current: 'view' };
+ confirmModal({
+ cancelText: t('cancel', { ns: 'common' }),
+ content: (
+ <VisibilityConfirmContent
+ accessLevelRef={accessLevelRef}
+ resourceType="document"
+ variant="publish"
+ />
+ ),
+ okText: t('continue', { ns: 'common' }),
+ onOk: async () => {
+ try {
+ await publishPageToWorkspace(documentId, accessLevelRef.current);
+ message.success(t('pageList.publishSuccess'));
+ } catch (error) {
+ console.error('Failed to publish page:', error);
+ message.error(t('pageList.publishError'));
+ }
+ },
+ title: t('pageList.publishConfirm.title'),
+ });
+ }, [canPublish, documentId, publishPageToWorkspace, message, t]);
+
const handleMakePrivate = useCallback(() => {
if (!canMakePrivate || !documentId) return;
confirmModal({
@@ -160,6 +205,22 @@ export const useMenu = (): { menuItems: any[] } => {
},
]
: []),
+ ...(memberPermissionMenuItem || canMakePrivate
+ ? [
+ ...(memberPermissionMenuItem ? [memberPermissionMenuItem] : []),
+ ...(canMakePrivate
+ ? [
+ {
+ icon: <Icon icon={EyeOffIcon} />,
+ key: 'make-private',
+ label: t('makePrivate', { ns: 'common' }),
+ onClick: handleMakePrivate,
+ } as DropdownItem,
+ ]
+ : []),
+ { type: 'divider' as const },
+ ]
+ : []),
{
disabled: !canCreatePage,
icon: <Icon icon={CopyPlus} />,
@@ -201,13 +262,13 @@ export const useMenu = (): { menuItems: any[] } => {
type: 'divider' as const,
},
...((transferMenuItems ?? []) as DropdownItem[]),
- ...(canMakePrivate
+ ...(canPublish
? [
{
- icon: <Icon icon={EyeOffIcon} />,
- key: 'make-private',
- label: t('makePrivate', { ns: 'common' }),
- onClick: handleMakePrivate,
+ icon: <Icon icon={UsersIcon} />,
+ key: 'publish-to-workspace',
+ label: t('pageList.publishToWorkspace'),
+ onClick: handlePublish,
} as DropdownItem,
]
: []),
@@ -266,9 +327,12 @@ export const useMenu = (): { menuItems: any[] } => {
toggleWideScreen,
togglePageAgentPanel,
showViewModeSwitch,
+ canPublish,
handleDuplicate,
handleMakePrivate,
+ handlePublish,
handleExportMarkdown,
+ memberPermissionMenuItem,
transferMenuItems,
]);
diff --git a/src/features/PageEditor/useDocumentLock.ts b/src/features/PageEditor/useDocumentLock.ts
index 7df8e229320..1ec01cfafef 100644
--- a/src/features/PageEditor/useDocumentLock.ts
+++ b/src/features/PageEditor/useDocumentLock.ts
@@ -3,6 +3,7 @@
import { useEffect, useMemo, useRef } from 'react';
import { type EditLockClient, useEditLock } from '@/features/EditLock';
+import { useResourceAccess } from '@/features/ResourcePermission/useResourceAccess';
import { usePermission } from '@/hooks/usePermission';
import { mutate } from '@/libs/swr';
import { documentService } from '@/services/document';
@@ -57,7 +58,13 @@ export const useDocumentLock = () => {
documentId ? editorSelectors.saveBlockedByLock(documentId)(s) : false,
);
- const workspacePage = Boolean(documentId && canEdit && isWorkspacePage);
+ // A view-level member can't write, so never try to acquire the edit lock —
+ // holding it would only block actual editors (permissive while loading).
+ const { canEditResource } = useResourceAccess(
+ 'document',
+ isWorkspacePage && documentId ? documentId : undefined,
+ );
+ const workspacePage = Boolean(documentId && canEdit && canEditResource && isWorkspacePage);
const ownerId = useMemo(
() => (documentId ? createLockOwnerId(documentId) : undefined),
[documentId],
diff --git a/src/features/PageEditor/usePageEditable.ts b/src/features/PageEditor/usePageEditable.ts
index 30a44646487..c85ea799416 100644
--- a/src/features/PageEditor/usePageEditable.ts
+++ b/src/features/PageEditor/usePageEditable.ts
@@ -1,5 +1,6 @@
'use client';
+import { useResourceAccess } from '@/features/ResourcePermission/useResourceAccess';
import { usePermission } from '@/hooks/usePermission';
import { useDocumentStore } from '@/store/document';
import { editorSelectors } from '@/store/document/slices/editor';
@@ -30,6 +31,14 @@ export const usePageEditable = (): boolean => {
documentId ? editorSelectors.saveBlockedByLock(documentId)(s) : false,
);
const pendingLock = isWorkspacePage && isLockPending;
+ // A workspace member whose General access on this page is view level can't
+ // edit it (defaults permissive while loading — server enforces).
+ const { canEditResource } = useResourceAccess(
+ 'document',
+ isWorkspacePage && documentId ? documentId : undefined,
+ );
- return hasEditPermission && !isLockedByOther && !pendingLock && !saveBlockedByLock;
+ return (
+ hasEditPermission && canEditResource && !isLockedByOther && !pendingLock && !saveBlockedByLock
+ );
};
diff --git a/src/features/Pages/PageLayout/Body/List/Item/useDropdownMenu.tsx b/src/features/Pages/PageLayout/Body/List/Item/useDropdownMenu.tsx
index 2cbb6e90523..25b9e5b4ecb 100644
--- a/src/features/Pages/PageLayout/Body/List/Item/useDropdownMenu.tsx
+++ b/src/features/Pages/PageLayout/Body/List/Item/useDropdownMenu.tsx
@@ -100,15 +100,22 @@ export const useDropdownMenu = ({
// Copy intentionally does not mention nested pages: Pages sidebar is a
// flat list, so users can't see (and don't reliably know about) a
- // subtree — surfacing a "N sub-pages" count only creates confusion. The
- // server still cascades the whole subtree on the write path.
+ // subtree — surfacing a "N sub-pages" count only creates confusion.
+ // Visibility is changed only for this page; descendants stay independent.
+ const accessLevelRef: { current: 'edit' | 'view' } = { current: 'view' };
confirmModal({
cancelText: t('cancel'),
- content: <VisibilityConfirmContent variant="publish" />,
+ content: (
+ <VisibilityConfirmContent
+ accessLevelRef={accessLevelRef}
+ resourceType="document"
+ variant="publish"
+ />
+ ),
okText: t('continue'),
onOk: async () => {
try {
- await publishPageToWorkspace(pageId);
+ await publishPageToWorkspace(pageId, accessLevelRef.current);
message.success(t('pageList.publishSuccess', { ns: 'file' }));
} catch (error) {
console.error('Failed to publish page:', error);
diff --git a/src/features/ResourcePermission/AccessLevelTag.tsx b/src/features/ResourcePermission/AccessLevelTag.tsx
new file mode 100644
index 00000000000..a112421c0f3
--- /dev/null
+++ b/src/features/ResourcePermission/AccessLevelTag.tsx
@@ -0,0 +1,47 @@
+'use client';
+
+import { Icon, Tag, Tooltip } from '@lobehub/ui';
+import { EyeIcon, PlayIcon } from 'lucide-react';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useHasActiveWorkspace } from '@/business/client/hooks/useHasActiveWorkspace';
+import type { PermissionResourceType } from '@/services/resourcePermission';
+
+import { useResourcePermission } from './useResourcePermission';
+
+export interface AccessLevelTagProps {
+ resourceId?: string;
+ resourceType: PermissionResourceType;
+}
+
+/**
+ * At-a-glance "why is this read-only" badge for members below `edit` access:
+ * shows the granted level (view / use) with a tooltip explaining what it means
+ * and who to ask for more. Renders nothing for creators/owners, `edit` level,
+ * personal mode, or while the level is still loading — surfaces with no
+ * restriction stay visually unchanged.
+ */
+const AccessLevelTag = memo<AccessLevelTagProps>(({ resourceId, resourceType }) => {
+ const { t } = useTranslation('setting');
+ const hasActiveWorkspace = useHasActiveWorkspace();
+ const { data } = useResourcePermission(resourceType, hasActiveWorkspace ? resourceId : undefined);
+
+ if (!data || data.canManage || data.accessLevel === 'edit') return null;
+
+ const viewOnly = data.accessLevel === 'view';
+
+ return (
+ <Tooltip
+ title={t(viewOnly ? 'permission.accessTag.viewOnlyTip' : 'permission.accessTag.useOnlyTip')}
+ >
+ <Tag icon={<Icon icon={viewOnly ? EyeIcon : PlayIcon} />}>
+ {t(viewOnly ? 'permission.generalAccess.viewable' : 'permission.generalAccess.usable')}
+ </Tag>
+ </Tooltip>
+ );
+});
+
+AccessLevelTag.displayName = 'AccessLevelTag';
+
+export default AccessLevelTag;
diff --git a/src/features/ResourcePermission/ResourceConfigAccessGate.test.tsx b/src/features/ResourcePermission/ResourceConfigAccessGate.test.tsx
new file mode 100644
index 00000000000..49f67f75e5a
--- /dev/null
+++ b/src/features/ResourcePermission/ResourceConfigAccessGate.test.tsx
@@ -0,0 +1,53 @@
+import { render, waitFor } from '@testing-library/react';
+import type { ReactNode } from 'react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import ResourceConfigAccessGate from './ResourceConfigAccessGate';
+
+const mocks = vi.hoisted(() => ({
+ navigate: vi.fn(),
+ toastInfo: vi.fn(),
+}));
+
+vi.mock('@lobehub/ui/base-ui', () => ({ toast: { info: mocks.toastInfo } }));
+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
+vi.mock('@/components/AsyncBoundary', () => ({
+ default: ({ children }: { children: ReactNode }) => children,
+}));
+vi.mock('@/components/Loading/BrandTextLoading', () => ({ default: () => null }));
+vi.mock('@/features/Workspace/useWorkspaceAwareNavigate', () => ({
+ useWorkspaceAwareNavigate: () => mocks.navigate,
+}));
+vi.mock('@/hooks/usePermission', () => ({ usePermission: () => ({ allowed: true }) }));
+vi.mock('./useResourceAccess', () => ({
+ useResourceAccess: () => ({
+ accessError: undefined,
+ canEditResource: false,
+ isAccessResolved: true,
+ isLoading: false,
+ retryAccess: vi.fn(),
+ }),
+}));
+
+describe('ResourceConfigAccessGate', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('uses workspace-aware navigation when returning a chat-only collaborator to chat', async () => {
+ render(
+ <ResourceConfigAccessGate
+ redirectPath="/agent/agent-1"
+ resourceId="agent-1"
+ resourceType="agent"
+ >
+ <div>Agent config</div>
+ </ResourceConfigAccessGate>,
+ );
+
+ await waitFor(() => {
+ expect(mocks.navigate).toHaveBeenCalledWith('/agent/agent-1', { replace: true });
+ });
+ expect(mocks.toastInfo).toHaveBeenCalledWith('permission.configAccess.agentChatOnly');
+ });
+});
diff --git a/src/features/ResourcePermission/ResourceConfigAccessGate.tsx b/src/features/ResourcePermission/ResourceConfigAccessGate.tsx
new file mode 100644
index 00000000000..231886b0033
--- /dev/null
+++ b/src/features/ResourcePermission/ResourceConfigAccessGate.tsx
@@ -0,0 +1,64 @@
+'use client';
+
+import { toast } from '@lobehub/ui/base-ui';
+import { memo, type ReactNode, useEffect, useRef } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import AsyncBoundary from '@/components/AsyncBoundary';
+import Loading from '@/components/Loading/BrandTextLoading';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { usePermission } from '@/hooks/usePermission';
+
+import { useResourceAccess } from './useResourceAccess';
+
+interface ResourceConfigAccessGateProps {
+ children: ReactNode;
+ redirectPath: string;
+ resourceId?: string;
+ resourceType: 'agent' | 'agentGroup';
+}
+
+const ResourceConfigAccessGate = memo<ResourceConfigAccessGateProps>(
+ ({ children, redirectPath, resourceId, resourceType }) => {
+ const { t } = useTranslation('chat');
+ const navigate = useWorkspaceAwareNavigate();
+ const hasRedirected = useRef(false);
+ const { allowed: canEditContent } = usePermission('edit_own_content');
+ const { accessError, canEditResource, isAccessResolved, isLoading, retryAccess } =
+ useResourceAccess(resourceType, resourceId);
+
+ const accessReady = !!resourceId && isAccessResolved && !isLoading;
+ const canConfigure = accessReady && canEditContent && canEditResource;
+
+ useEffect(() => {
+ if (!accessReady || accessError || canConfigure || hasRedirected.current) return;
+
+ hasRedirected.current = true;
+ toast.info(
+ t(
+ resourceType === 'agent'
+ ? 'permission.configAccess.agentChatOnly'
+ : 'permission.configAccess.groupChatOnly',
+ ),
+ );
+ navigate(redirectPath, { replace: true });
+ }, [accessError, accessReady, canConfigure, navigate, redirectPath, resourceType, t]);
+
+ return (
+ <AsyncBoundary
+ data={accessReady ? true : undefined}
+ error={accessError}
+ errorVariant={'page'}
+ isLoading={!accessReady && !accessError}
+ loading={<Loading debugId="ResourceConfigAccessGate" />}
+ onRetry={() => void retryAccess()}
+ >
+ {canConfigure ? children : <Loading debugId="ResourceConfigAccessRedirect" />}
+ </AsyncBoundary>
+ );
+ },
+);
+
+ResourceConfigAccessGate.displayName = 'ResourceConfigAccessGate';
+
+export default ResourceConfigAccessGate;
diff --git a/src/features/ResourcePermission/useResourceAccess.ts b/src/features/ResourcePermission/useResourceAccess.ts
new file mode 100644
index 00000000000..ba5be319786
--- /dev/null
+++ b/src/features/ResourcePermission/useResourceAccess.ts
@@ -0,0 +1,38 @@
+import { useHasActiveWorkspace } from '@/business/client/hooks/useHasActiveWorkspace';
+import { useClientDataSWR } from '@/libs/swr';
+import type { PermissionResourceType } from '@/services/resourcePermission';
+import { resourcePermissionService } from '@/services/resourcePermission';
+
+// Same SWR key as useResourcePermission so both hooks share one fetch/cache entry.
+const FETCH_RESOURCE_PERMISSION_KEY = 'resource-permission';
+
+/**
+ * Read-side derivation of the workspace General-access level for a resource.
+ *
+ * Edit/use checks stay permissive while workspace access is loading so chat
+ * input does not flash disabled. Management checks are deliberately
+ * fail-closed: destructive/ownership controls must not appear until the
+ * server confirms creator/owner access. Personal mode keeps full access.
+ */
+export const useResourceAccess = (
+ resourceType: PermissionResourceType,
+ resourceId: string | undefined,
+) => {
+ const hasActiveWorkspace = useHasActiveWorkspace();
+ const enabled = hasActiveWorkspace && !!resourceId;
+
+ const { data, error, isLoading, mutate } = useClientDataSWR(
+ enabled ? [FETCH_RESOURCE_PERMISSION_KEY, resourceType, resourceId] : null,
+ () => resourcePermissionService.getGeneralAccess(resourceType, resourceId!),
+ );
+
+ return {
+ accessError: error,
+ canEditResource: !enabled || !data ? true : data.canManage || data.accessLevel === 'edit',
+ canManageResource: !enabled || data?.canManage === true,
+ canUseResource: !enabled || !data ? true : data.canManage || data.accessLevel !== 'view',
+ isAccessResolved: !enabled || !!data,
+ isLoading,
+ retryAccess: mutate,
+ };
+};
diff --git a/src/features/ResourcePermission/useResourcePermission.ts b/src/features/ResourcePermission/useResourcePermission.ts
new file mode 100644
index 00000000000..d36f32e3265
--- /dev/null
+++ b/src/features/ResourcePermission/useResourcePermission.ts
@@ -0,0 +1,72 @@
+import { App } from 'antd';
+import { useCallback, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useClientDataSWR } from '@/libs/swr';
+import type { PermissionResourceType, ResourceAccessLevel } from '@/services/resourcePermission';
+import { resourcePermissionService } from '@/services/resourcePermission';
+
+const FETCH_RESOURCE_PERMISSION_KEY = 'resource-permission';
+
+/**
+ * State + handlers of the Permission panel: publicity and the workspace
+ * General-access level (Notion-style Share).
+ */
+export const useResourcePermission = (
+ resourceType: PermissionResourceType,
+ resourceId: string | undefined,
+) => {
+ const { t } = useTranslation('setting');
+ const { message } = App.useApp();
+ const [updating, setUpdating] = useState(false);
+
+ const { data, error, isLoading, mutate } = useClientDataSWR(
+ resourceId ? [FETCH_RESOURCE_PERMISSION_KEY, resourceType, resourceId] : null,
+ () => resourcePermissionService.getGeneralAccess(resourceType, resourceId!),
+ );
+
+ const run = useCallback(
+ async (
+ action: () => Promise<Awaited<ReturnType<typeof resourcePermissionService.getGeneralAccess>>>,
+ optimisticData: Awaited<ReturnType<typeof resourcePermissionService.getGeneralAccess>>,
+ ) => {
+ const previousData = data;
+ setUpdating(true);
+ await mutate(optimisticData, false);
+ try {
+ const result = await action();
+ await mutate(result, false);
+ } catch (e) {
+ await mutate(previousData, false);
+ console.error('[ResourcePermission]', e);
+ message.error((e as Error)?.message || t('permission.updateError'));
+ } finally {
+ setUpdating(false);
+ }
+ },
+ [data, mutate, message, t],
+ );
+
+ const setAccessLevel = useCallback(
+ (accessLevel: ResourceAccessLevel) => {
+ if (!data) return;
+ return run(
+ () => resourcePermissionService.setAccessLevel(resourceType, resourceId!, accessLevel),
+ {
+ ...data,
+ accessLevel,
+ generalAccess: accessLevel === 'edit' ? 'editor' : 'viewer',
+ },
+ );
+ },
+ [data, run, resourceType, resourceId],
+ );
+
+ return {
+ data,
+ error,
+ isLoading,
+ setAccessLevel,
+ updating,
+ };
+};
diff --git a/src/features/ResourcePermission/useResourcePermissionMenuItem.test.tsx b/src/features/ResourcePermission/useResourcePermissionMenuItem.test.tsx
new file mode 100644
index 00000000000..880cedfc14e
--- /dev/null
+++ b/src/features/ResourcePermission/useResourcePermissionMenuItem.test.tsx
@@ -0,0 +1,92 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useResourcePermissionMenuItem } from './useResourcePermissionMenuItem';
+
+const permissionMock = vi.hoisted(() => ({
+ data: {
+ accessLevel: 'view',
+ canManage: false,
+ },
+}));
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string) => key,
+ }),
+}));
+
+vi.mock('@lobehub/ui', () => ({
+ Flexbox: ({ children }: { children: React.ReactNode }) => children,
+ Icon: () => null,
+}));
+
+vi.mock('./useResourcePermission', () => ({
+ useResourcePermission: () => ({
+ data: permissionMock.data,
+ error: undefined,
+ isLoading: false,
+ setAccessLevel: vi.fn(),
+ updating: false,
+ }),
+}));
+
+describe('useResourcePermissionMenuItem', () => {
+ beforeEach(() => {
+ permissionMock.data = {
+ accessLevel: 'view',
+ canManage: false,
+ };
+ });
+
+ it('keeps non-manageable permissions hidden by default', () => {
+ const { result } = renderHook(() => useResourcePermissionMenuItem('document', 'doc-1'));
+
+ expect(result.current).toBeNull();
+ });
+
+ it('shows the current permission as a disabled overflow item when requested', () => {
+ const { result } = renderHook(() =>
+ useResourcePermissionMenuItem('document', 'doc-1', { showReadOnly: true }),
+ );
+
+ expect(result.current).toMatchObject({
+ disabled: true,
+ key: 'member-permissions',
+ label: 'permission.generalAccess.trigger',
+ });
+ });
+
+ it('offers only edit and use access for manageable agents', () => {
+ permissionMock.data = {
+ accessLevel: 'use',
+ canManage: true,
+ };
+
+ const { result } = renderHook(() => useResourcePermissionMenuItem('agent', 'agent-1'));
+ const item = result.current as { children: { key: string }[] };
+
+ expect(item.children.map(({ key }) => key)).toEqual([
+ 'member-permission-edit',
+ 'member-permission-use',
+ ]);
+ });
+
+ it('keeps edit and view access for manageable documents', () => {
+ permissionMock.data = {
+ accessLevel: 'view',
+ canManage: true,
+ };
+
+ const { result } = renderHook(() => useResourcePermissionMenuItem('document', 'doc-1'));
+ const item = result.current as { children: { key: string }[] };
+
+ expect(item.children.map(({ key }) => key)).toEqual([
+ 'member-permission-edit',
+ 'member-permission-view',
+ ]);
+ });
+});
diff --git a/src/features/ResourcePermission/useResourcePermissionMenuItem.tsx b/src/features/ResourcePermission/useResourcePermissionMenuItem.tsx
new file mode 100644
index 00000000000..9bf09b4048c
--- /dev/null
+++ b/src/features/ResourcePermission/useResourcePermissionMenuItem.tsx
@@ -0,0 +1,110 @@
+import { Flexbox, Icon, type MenuProps } from '@lobehub/ui';
+import { CheckIcon, EyeIcon, type LucideIcon, PencilIcon, PlayIcon, UsersIcon } from 'lucide-react';
+import { useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import type { PermissionResourceType, ResourceAccessLevel } from '@/services/resourcePermission';
+
+import { useResourcePermission } from './useResourcePermission';
+
+type MenuItem = NonNullable<MenuProps['items']>[number];
+
+interface ResourcePermissionMenuItemOptions {
+ showReadOnly?: boolean;
+}
+
+export const useResourcePermissionMenuItem = (
+ resourceType: PermissionResourceType,
+ resourceId?: string,
+ options: ResourcePermissionMenuItemOptions = {},
+): MenuItem | null => {
+ const { t } = useTranslation('setting');
+ const { data, error, isLoading, setAccessLevel, updating } = useResourcePermission(
+ resourceType,
+ resourceId,
+ );
+
+ const accessOptions = useMemo(() => {
+ const levels: {
+ desc: string;
+ icon: LucideIcon;
+ label: string;
+ value: ResourceAccessLevel;
+ }[] = [
+ {
+ desc: t(
+ resourceType === 'document'
+ ? 'permission.generalAccess.editableDocumentDesc'
+ : 'permission.generalAccess.editableDesc',
+ ),
+ icon: PencilIcon,
+ label: t('permission.generalAccess.editable'),
+ value: 'edit',
+ },
+ ];
+ if (resourceType === 'document') {
+ levels.push({
+ desc: t('permission.generalAccess.viewableDocumentDesc'),
+ icon: EyeIcon,
+ label: t('permission.generalAccess.viewable'),
+ value: 'view',
+ });
+ } else {
+ levels.push({
+ desc: t('permission.generalAccess.usableDesc'),
+ icon: PlayIcon,
+ label: t('permission.generalAccess.usable'),
+ value: 'use',
+ });
+ }
+ return levels;
+ }, [resourceType, t]);
+
+ if (!resourceId || !data || (!data.canManage && !options.showReadOnly)) return null;
+
+ const accessLevel = data?.accessLevel;
+ const selectedOption =
+ accessOptions.find((option) => option.value === accessLevel) ??
+ (accessLevel === 'view'
+ ? {
+ icon: EyeIcon,
+ label: t('permission.generalAccess.viewable'),
+ }
+ : undefined);
+
+ if (!data.canManage) {
+ return {
+ disabled: true,
+ icon: selectedOption ? <Icon icon={selectedOption.icon} /> : <Icon icon={UsersIcon} />,
+ key: 'member-permissions',
+ label: selectedOption
+ ? t('permission.generalAccess.trigger', { level: selectedOption.label })
+ : t('permission.generalAccess.label'),
+ };
+ }
+
+ return {
+ children: accessOptions.map(({ desc, icon, label, value }) => ({
+ desc,
+ disabled: updating,
+ icon: <Icon icon={icon} />,
+ key: `member-permission-${value}`,
+ label: (
+ <Flexbox horizontal align={'center'} gap={16} justify={'space-between'}>
+ <span>{label}</span>
+ {value === accessLevel && <Icon icon={CheckIcon} />}
+ </Flexbox>
+ ),
+ onClick: () => {
+ if (updating || value === accessLevel) return;
+ void setAccessLevel(value);
+ },
+ })),
+ disabled: isLoading || !!error,
+ icon: <Icon icon={UsersIcon} />,
+ key: 'member-permissions',
+ label: selectedOption
+ ? t('permission.generalAccess.trigger', { level: selectedOption.label })
+ : t('permission.generalAccess.label'),
+ };
+};
diff --git a/src/features/VisibilityConfirmContent/index.test.tsx b/src/features/VisibilityConfirmContent/index.test.tsx
index b95b6185ddb..7ea64139855 100644
--- a/src/features/VisibilityConfirmContent/index.test.tsx
+++ b/src/features/VisibilityConfirmContent/index.test.tsx
@@ -18,6 +18,25 @@ vi.mock('@lobehub/ui', () => ({
Icon: ({ size }: { icon: unknown; size?: number }) => (
<span data-icon-size={size} data-testid="icon" />
),
+ Text: ({ children }: { children?: ReactNode }) => <span>{children}</span>,
+}));
+
+vi.mock('@lobehub/ui/base-ui', () => ({
+ Select: ({
+ options,
+ value,
+ }: {
+ options: { label: ReactNode; value: string }[];
+ value: string;
+ }) => (
+ <div data-testid="access-select" data-value={value}>
+ {options.map((option) => (
+ <div data-option={option.value} key={option.value}>
+ {option.label}
+ </div>
+ ))}
+ </div>
+ ),
}));
describe('VisibilityConfirmContent', () => {
@@ -39,4 +58,34 @@ describe('VisibilityConfirmContent', () => {
expect(screen.getByText('visibilityConfirm.publish.itemLoaded')).toBeTruthy();
expect(screen.getAllByText('visibilityConfirm.irreversible')).toHaveLength(1);
});
+
+ it('offers only edit/use and defaults to use when publishing an agent', () => {
+ render(
+ <VisibilityConfirmContent
+ accessLevelRef={{ current: 'use' }}
+ resourceType="agent"
+ variant="publish"
+ />,
+ );
+
+ expect(screen.getByTestId('access-select').dataset.value).toBe('use');
+ expect(document.querySelector('[data-option="edit"]')).toBeTruthy();
+ expect(document.querySelector('[data-option="use"]')).toBeTruthy();
+ expect(document.querySelector('[data-option="view"]')).toBeNull();
+ });
+
+ it('offers edit/view and defaults to view when publishing a document', () => {
+ render(
+ <VisibilityConfirmContent
+ accessLevelRef={{ current: 'view' }}
+ resourceType="document"
+ variant="publish"
+ />,
+ );
+
+ expect(screen.getByTestId('access-select').dataset.value).toBe('view');
+ expect(document.querySelector('[data-option="edit"]')).toBeTruthy();
+ expect(document.querySelector('[data-option="use"]')).toBeNull();
+ expect(document.querySelector('[data-option="view"]')).toBeTruthy();
+ });
});
diff --git a/src/features/VisibilityConfirmContent/index.tsx b/src/features/VisibilityConfirmContent/index.tsx
index d40b0796167..e124d47f3dd 100644
--- a/src/features/VisibilityConfirmContent/index.tsx
+++ b/src/features/VisibilityConfirmContent/index.tsx
@@ -1,21 +1,36 @@
'use client';
-import { Icon } from '@lobehub/ui';
-import { createStaticStyles } from 'antd-style';
+import { Flexbox, Icon, Text } from '@lobehub/ui';
+import { Select } from '@lobehub/ui/base-ui';
+import { createStaticStyles, cssVar } from 'antd-style';
import {
AlertTriangleIcon,
CheckIcon,
+ EyeIcon,
EyeOffIcon,
InfoIcon,
type LucideIcon,
+ PencilIcon,
+ PlayIcon,
UsersIcon,
} from 'lucide-react';
-import { memo } from 'react';
+import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import type { PermissionResourceType, ResourceAccessLevel } from '@/services/resourcePermission';
+
export type VisibilityConfirmVariant = 'makePrivate' | 'publish';
export interface VisibilityConfirmContentProps {
+ /**
+ * When provided on the `publish` variant, renders a Notion-style General
+ * access select (resource-specific edit/use or edit/view choices) and writes
+ * the choice into the ref so the caller's `onOk` can apply it after the
+ * publish succeeds. A plain ref (not state) because `confirmModal` content
+ * lives outside the caller's render tree.
+ */
+ accessLevelRef?: { current: ResourceAccessLevel };
+ resourceType?: PermissionResourceType;
variant: VisibilityConfirmVariant;
}
@@ -126,6 +141,19 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
suffix: css`
color: ${cssVar.colorTextTertiary};
`,
+ optionRow: css`
+ padding-block: 2px;
+ `,
+ // The trigger's value text span shrink-wraps its content by default, which
+ // leaves `marginInlineStart: auto` on the option desc with no free space —
+ // stretch it so the selected option's desc stays right-aligned like in the
+ // dropdown list.
+ selectValue: css`
+ > span {
+ flex: 1;
+ min-width: 0;
+ }
+ `,
}));
const rowIconClass = (tone: Tone) => {
@@ -152,30 +180,132 @@ const rowIconClass = (tone: Tone) => {
* carried by the destructive vs primary button colour, so we don't need a
* separate hero icon here.
*/
-const VisibilityConfirmContent = memo<VisibilityConfirmContentProps>(({ variant }) => {
- const { t } = useTranslation('common');
- const config = CONFIG[variant];
- const irreversibleSuffix = t('visibilityConfirm.irreversible');
-
- return (
- <ul className={styles.list}>
- {config.items.map((item) => {
- const ItemIcon = item.icon;
- return (
- <li className={styles.row} key={item.key}>
- <span className={`${styles.rowIcon} ${rowIconClass(item.tone)}`}>
- <Icon icon={ItemIcon} size={14} />
- </span>
- <span className={item.emphasis ? styles.emphasis : undefined}>
- {t(item.key as any)}
- {item.showIrreversible && <span className={styles.suffix}>{irreversibleSuffix}</span>}
- </span>
- </li>
- );
- })}
- </ul>
- );
-});
+const VisibilityConfirmContent = memo<VisibilityConfirmContentProps>(
+ ({ accessLevelRef, resourceType, variant }) => {
+ const { t } = useTranslation(['common', 'setting']);
+ const config = CONFIG[variant];
+ const irreversibleSuffix = t('visibilityConfirm.irreversible');
+ const [accessLevel, setAccessLevel] = useState<ResourceAccessLevel>(
+ accessLevelRef?.current ?? (resourceType === 'document' ? 'view' : 'use'),
+ );
+ const showAccessSelect = variant === 'publish' && !!accessLevelRef && !!resourceType;
+
+ return (
+ <Flexbox gap={12}>
+ <ul className={styles.list}>
+ {config.items.map((item) => {
+ const ItemIcon = item.icon;
+ return (
+ <li className={styles.row} key={item.key}>
+ <span className={`${styles.rowIcon} ${rowIconClass(item.tone)}`}>
+ <Icon icon={ItemIcon} size={14} />
+ </span>
+ <span className={item.emphasis ? styles.emphasis : undefined}>
+ {t(item.key as any)}
+ {item.showIrreversible && (
+ <span className={styles.suffix}>{irreversibleSuffix}</span>
+ )}
+ </span>
+ </li>
+ );
+ })}
+ </ul>
+ {showAccessSelect && (
+ <Flexbox gap={6}>
+ <Text style={{ fontSize: 13, fontWeight: 500 }}>
+ {t('permission.generalAccess.label', { ns: 'setting' })}
+ </Text>
+ <Select
+ classNames={{ value: styles.selectValue }}
+ style={{ width: '100%' }}
+ value={accessLevel}
+ options={[
+ {
+ label: (
+ <Flexbox horizontal align={'center'} className={styles.optionRow} gap={8}>
+ <Icon icon={PencilIcon} size={14} />
+ <Text style={{ fontSize: 13, fontWeight: 500 }}>
+ {t('permission.generalAccess.editable', { ns: 'setting' })}
+ </Text>
+ <Text
+ style={{
+ color: cssVar.colorTextTertiary,
+ fontSize: 12,
+ marginInlineStart: 'auto',
+ }}
+ >
+ {t('permission.generalAccess.editableDesc', { ns: 'setting' })}
+ </Text>
+ </Flexbox>
+ ),
+ title: t('permission.generalAccess.editable', { ns: 'setting' }),
+ value: 'edit',
+ },
+ ...(resourceType !== 'document'
+ ? [
+ {
+ label: (
+ <Flexbox horizontal align={'center'} className={styles.optionRow} gap={8}>
+ <Icon icon={PlayIcon} size={14} />
+ <Text style={{ fontSize: 13, fontWeight: 500 }}>
+ {t('permission.generalAccess.usable', { ns: 'setting' })}
+ </Text>
+ <Text
+ style={{
+ color: cssVar.colorTextTertiary,
+ fontSize: 12,
+ marginInlineStart: 'auto',
+ }}
+ >
+ {t('permission.generalAccess.usableDesc', { ns: 'setting' })}
+ </Text>
+ </Flexbox>
+ ),
+ title: t('permission.generalAccess.usable', { ns: 'setting' }),
+ value: 'use' as const,
+ },
+ ]
+ : []),
+ ...(resourceType === 'document'
+ ? [
+ {
+ label: (
+ <Flexbox horizontal align={'center'} className={styles.optionRow} gap={8}>
+ <Icon icon={EyeIcon} size={14} />
+ <Text style={{ fontSize: 13, fontWeight: 500 }}>
+ {t('permission.generalAccess.viewable', { ns: 'setting' })}
+ </Text>
+ <Text
+ style={{
+ color: cssVar.colorTextTertiary,
+ fontSize: 12,
+ marginInlineStart: 'auto',
+ }}
+ >
+ {t('permission.generalAccess.viewableDocumentDesc', {
+ ns: 'setting',
+ })}
+ </Text>
+ </Flexbox>
+ ),
+ title: t('permission.generalAccess.viewable', { ns: 'setting' }),
+ value: 'view' as const,
+ },
+ ]
+ : []),
+ ]}
+ onChange={(nextAccessLevel) => {
+ if (!nextAccessLevel) return;
+ setAccessLevel(nextAccessLevel as ResourceAccessLevel);
+ accessLevelRef!.current = nextAccessLevel as ResourceAccessLevel;
+ }}
+ />
+ </Flexbox>
+ )}
+ </Flexbox>
+ );
+ },
+);
VisibilityConfirmContent.displayName = 'VisibilityConfirmContent';
diff --git a/src/helpers/executionTarget.test.ts b/src/helpers/executionTarget.test.ts
index 5eb1ada290c..a052f0b31bf 100644
--- a/src/helpers/executionTarget.test.ts
+++ b/src/helpers/executionTarget.test.ts
@@ -365,6 +365,35 @@ describe('resolveExecutionPlan', () => {
const ONLINE_A = ['device-a'];
const ONLINE_AB = ['device-a', 'device-b'];
+ it('ignores an explicit request override when the shared execution target is fixed', () => {
+ expect(
+ resolveExecutionPlan({
+ agencyConfig: cfg({
+ boundDeviceId: 'device-a',
+ executionTargetSelectionPolicy: 'fixed',
+ executionTarget: 'device',
+ }),
+ clientExecutionAvailable: false,
+ onlineDeviceIds: ONLINE_AB,
+ requestedDeviceId: 'device-b',
+ }),
+ ).toEqual({ deviceId: 'device-a', kind: 'device', target: 'device' });
+ });
+
+ it('keeps a fixed sandbox target when a request asks for a device', () => {
+ expect(
+ resolveExecutionPlan({
+ agencyConfig: cfg({
+ executionTarget: 'sandbox',
+ executionTargetSelectionPolicy: 'fixed',
+ }),
+ clientExecutionAvailable: false,
+ onlineDeviceIds: ONLINE_AB,
+ requestedDeviceId: 'device-b',
+ }),
+ ).toEqual({ kind: 'sandbox', target: 'sandbox' });
+ });
+
describe('none — never routes to a device', () => {
it('stays none even with a bound device and exactly one device online', () => {
// the historical bug: single-online-device auto-activation used to
diff --git a/src/helpers/executionTarget.ts b/src/helpers/executionTarget.ts
index 08cc3e4e7f7..2f6b43831eb 100644
--- a/src/helpers/executionTarget.ts
+++ b/src/helpers/executionTarget.ts
@@ -336,8 +336,8 @@ export interface ResolveExecutionPlanParams {
onlineDeviceIds?: string[];
/**
* Explicit per-request device override (e.g. the desktop preset, or a
- * batch-task `deviceId`). Always wins: it forces device routing regardless
- * of the stored target.
+ * batch-task `deviceId`). It forces device routing regardless of the stored
+ * target unless the shared workspace policy is `fixed`.
*/
requestedDeviceId?: string;
/** See {@link ResolveExecutionTargetOptions.sandboxExecutionAvailable}. */
@@ -358,9 +358,9 @@ export interface ResolveExecutionPlanParams {
* Resolve the execution plan for a run. This is THE device decision — every
* rule about which device (if any) a run touches lives here:
*
- * 1. `requestedDeviceId` forces device routing; otherwise the resolved
- * `executionTarget` decides (`auto` / `local` route to a device too — the
- * local machine is just a device).
+ * 1. `requestedDeviceId` forces device routing unless the shared policy is
+ * `fixed`; otherwise the resolved `executionTarget` decides (`auto` /
+ * `local` route to a device too — the local machine is just a device).
* 2. `none` / `sandbox` NEVER route to a device — no auto-activation, no
* step-level re-injection, no exceptions.
* 3. `canUseDevice === false` degrades any device-capable target to `none`
@@ -406,8 +406,13 @@ export const resolveExecutionPlan = (params: ResolveExecutionPlanParams): Execut
const sandboxAvailable =
sandboxExecutionAvailable ??
isHeterogeneousSandboxExecutionAvailable(agencyConfig?.heterogeneousProvider?.type);
+ // A fixed workspace execution target is an author-controlled contract. A
+ // stale member preference or an explicit task/request override must never
+ // route the run somewhere else.
+ const effectiveRequestedDeviceId =
+ agencyConfig?.executionTargetSelectionPolicy === 'fixed' ? undefined : requestedDeviceId;
const wantsDevice =
- !!requestedDeviceId || target === 'device' || target === 'local' || target === 'auto';
+ !!effectiveRequestedDeviceId || target === 'device' || target === 'local' || target === 'auto';
if (!wantsDevice || !canUseDevice) {
if (target === 'sandbox') return { kind: 'sandbox', target: 'sandbox' };
@@ -425,7 +430,7 @@ export const resolveExecutionPlan = (params: ResolveExecutionPlanParams): Execut
// a stale binding left over from a previous `device` selection can't pin the
// run. An explicit `requestedDeviceId` still wins everywhere.
const boundDeviceId =
- requestedDeviceId || (target === 'auto' ? undefined : agencyConfig?.boundDeviceId);
+ effectiveRequestedDeviceId || (target === 'auto' ? undefined : agencyConfig?.boundDeviceId);
// requestedDeviceId may force device routing over a non-device stored target;
// keep `auto` / `local` distinct, everything else collapses to `device`.
const effectiveTarget = target === 'local' ? 'local' : target === 'auto' ? 'auto' : 'device';
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Header/Nav.test.tsx b/src/routes/(main)/agent/_layout/Sidebar/Header/Nav.test.tsx
index 61e367f2e5b..537ff4f436a 100644
--- a/src/routes/(main)/agent/_layout/Sidebar/Header/Nav.test.tsx
+++ b/src/routes/(main)/agent/_layout/Sidebar/Header/Nav.test.tsx
@@ -16,6 +16,11 @@ const useParamsMock = vi.hoisted(() => vi.fn());
const usePathnameMock = vi.hoisted(() => vi.fn());
const permissionMock = vi.hoisted(() => ({
create_content: true,
+ edit_own_content: true,
+}));
+
+vi.mock('@/features/ResourcePermission/useResourceAccess', () => ({
+ useResourceAccess: () => ({ canEditResource: true, isAccessResolved: true }),
}));
vi.mock('@lobehub/ui', () => ({
@@ -86,7 +91,7 @@ vi.mock('@/libs/swr', () => ({
}));
vi.mock('@/hooks/usePermission', () => ({
- usePermission: (action: 'create_content') => ({
+ usePermission: (action: keyof typeof permissionMock) => ({
allowed: permissionMock[action],
reason: permissionMock[action] ? '' : 'requires member',
}),
@@ -138,6 +143,7 @@ describe('Agent sidebar header nav', () => {
useParamsMock.mockReset();
usePathnameMock.mockReset();
permissionMock.create_content = true;
+ permissionMock.edit_own_content = true;
useParamsMock.mockReturnValue({ aid: 'agt_eH4zL98zBx5u', topicId: 'tpc_2FCHvjS7d4CA' });
});
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Header/Nav.tsx b/src/routes/(main)/agent/_layout/Sidebar/Header/Nav.tsx
index de9695bedbb..779d208595a 100644
--- a/src/routes/(main)/agent/_layout/Sidebar/Header/Nav.tsx
+++ b/src/routes/(main)/agent/_layout/Sidebar/Header/Nav.tsx
@@ -14,6 +14,7 @@ import { useParams } from 'react-router';
import urlJoin from 'url-join';
import NavItem from '@/features/NavPanel/components/NavItem';
+import { useResourceAccess } from '@/features/ResourcePermission/useResourceAccess';
import { usePermission } from '@/hooks/usePermission';
import { useQueryRoute } from '@/hooks/useQueryRoute';
import { usePathname } from '@/libs/router/navigation';
@@ -39,12 +40,14 @@ const Nav = memo(() => {
const isTopicsActive = pathname.endsWith('/topics');
const router = useQueryRoute();
const { allowed: canCreateTopic } = usePermission('create_content');
+ const { allowed: canEditContent } = usePermission('edit_own_content');
+ const { canEditResource, isAccessResolved } = useResourceAccess('agent', agentId);
const { isAgentEditable } = useServerConfigStore(featureFlagsSelectors);
const toggleCommandMenu = useGlobalStore((s) => s.toggleCommandMenu);
const heterogeneousProviderType = useAgentStore(
agentSelectors.currentAgentHeterogeneousProviderType,
);
- const hideProfile = !isAgentEditable;
+ const hideProfile = !isAgentEditable || !isAccessResolved || !canEditContent || !canEditResource;
// Claude Code agents can use message channels; other hetero providers (e.g. codex) still hide it.
const hideChannel =
hideProfile || (!!heterogeneousProviderType && heterogeneousProviderType !== 'claude-code');
diff --git a/src/routes/(main)/agent/channel/index.tsx b/src/routes/(main)/agent/channel/index.tsx
index 84c5515e006..404d930e657 100644
--- a/src/routes/(main)/agent/channel/index.tsx
+++ b/src/routes/(main)/agent/channel/index.tsx
@@ -8,6 +8,7 @@ import { useNavigate, useParams } from 'react-router';
import NotFound from '@/components/404';
import AsyncBoundary from '@/components/AsyncBoundary';
import Loading from '@/components/Loading/BrandTextLoading';
+import ResourceConfigAccessGate from '@/features/ResourcePermission/ResourceConfigAccessGate';
import { usePermission } from '@/hooks/usePermission';
import { useAgentStore } from '@/store/agent';
import { useUserStore } from '@/store/user';
@@ -33,7 +34,7 @@ const styles = createStaticStyles(({ css }) => ({
`,
}));
-const ChannelPage = memo(() => {
+const ChannelContent = memo(() => {
const { aid, platform } = useParams<{ aid?: string; platform?: string }>();
const navigate = useNavigate();
const { allowed: canEdit } = usePermission('edit_own_content');
@@ -174,4 +175,18 @@ const ChannelPage = memo(() => {
);
});
+const ChannelPage = memo(() => {
+ const { aid } = useParams<{ aid?: string }>();
+
+ return (
+ <ResourceConfigAccessGate
+ redirectPath={`/agent/${aid ?? ''}`}
+ resourceId={aid}
+ resourceType="agent"
+ >
+ <ChannelContent />
+ </ResourceConfigAccessGate>
+ );
+});
+
export default ChannelPage;
diff --git a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/HeteroControlBar.tsx b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/HeteroControlBar.tsx
index 366766ff2c9..940030d8d57 100644
--- a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/HeteroControlBar.tsx
+++ b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/HeteroControlBar.tsx
@@ -12,8 +12,10 @@ import { ActivityIcon, CircleAlertIcon, RadioTowerIcon, TimerResetIcon } from 'l
import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import HeteroDeviceSwitcher from '@/features/ChatInput/ControlBar/HeteroDeviceSwitcher';
import WorkspaceControls from '@/features/ChatInput/ControlBar/WorkspaceControls';
import { useAgentId } from '@/features/ChatInput/hooks/useAgentId';
+import { useChatInputResourceAccess } from '@/features/ChatInput/hooks/useChatInputResourceAccess';
import { resolveExecutionTarget } from '@/helpers/executionTarget';
import { useEffectiveAgencyConfig } from '@/hooks/useEffectiveAgencyConfig';
import { useAgentStore } from '@/store/agent';
@@ -120,6 +122,7 @@ const visibleSdkRuntimeStates = new Set<HeterogeneousAgentRuntimeState>([
const HeteroControlBar = memo(() => {
const { t: tChat } = useTranslation('chat');
const agentId = useAgentId();
+ const { canConfigureResource, isAccessLoading } = useChatInputResourceAccess();
const [runtimeStatus, setRuntimeStatus] = useState<HeterogeneousAgentRuntimeStatus>();
useWatchBroadcast('heteroAgentRuntimeStatus', (status) => {
@@ -133,6 +136,19 @@ const HeteroControlBar = memo(() => {
// so the quota badges gate on where THIS member's run actually executes.
const { agencyConfig, workspaceScoped } = useEffectiveAgencyConfig(agentId);
+ if (isAccessLoading) return null;
+
+ // A can-use collaborator may choose only their execution device; working
+ // directory, git, quota and runtime details remain author/editor config.
+ if (!canConfigureResource) {
+ if (!agentId || isLoading) return null;
+ return (
+ <Flexbox horizontal align={'center'} className={styles.bar}>
+ <HeteroDeviceSwitcher agentId={agentId} />
+ </Flexbox>
+ );
+ }
+
// On web there's no full-access badge / skeleton — just the workspace controls
// (the cloud repo switcher is rendered inside WorkspaceControls). The CLI
// model + thinking-effort selector now lives in the input's bottom-left action
diff --git a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu.test.tsx b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu.test.tsx
index b923618de65..bc0c98ae68b 100644
--- a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu.test.tsx
+++ b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu.test.tsx
@@ -42,6 +42,17 @@ vi.mock('@/features/ChatInput/ControlBar/WorkspaceControls', () => ({
vi.mock('@/features/ChatInput/hooks/useAgentId', () => ({ useAgentId: () => 'agent-1' }));
+// Resource-access gating is out of scope for quota tests — keep it permissive
+// so HeteroControlBar renders its full quota UI without the ChatInput store.
+vi.mock('@/features/ChatInput/hooks/useChatInputResourceAccess', () => ({
+ useChatInputResourceAccess: () => ({
+ canConfigureResource: true,
+ canSendMessage: true,
+ canUseResource: true,
+ isAccessLoading: false,
+ }),
+}));
+
vi.mock('@/hooks/useEffectiveAgencyConfig', () => ({
useEffectiveAgencyConfig: () => ({
agencyConfig: effectiveAgencyConfig.current,
@@ -83,13 +94,21 @@ vi.mock('react-i18next', () => ({
}),
}));
-vi.mock('antd-style', () => ({
- createStaticStyles: (
- create: (utils: { css: (...args: unknown[]) => string }) => Record<string, string>,
- ) => create({ css: () => 'cls' }),
- cssVar: new Proxy({}, { get: (_target, prop) => `var(--${String(prop)})` }),
- cx: (...args: unknown[]) => args.filter(Boolean).join(' '),
-}));
+vi.mock('antd-style', async (importOriginal) => {
+ const actual = (await importOriginal()) as Record<string, unknown>;
+ const mockCssVar = new Proxy({}, { get: (_target, prop) => `var(--${String(prop)})` });
+ return {
+ ...actual,
+ createStaticStyles: (
+ create: (utils: {
+ css: (...args: unknown[]) => string;
+ cssVar: Record<string, string>;
+ }) => Record<string, string>,
+ ) => create({ css: () => 'cls', cssVar: mockCssVar }),
+ cssVar: mockCssVar,
+ cx: (...args: unknown[]) => args.filter(Boolean).join(' '),
+ };
+});
vi.mock('@lobehub/ui', () => ({
ActionIcon: ({ disabled, onClick }: { disabled?: boolean; onClick?: () => void }) => (
diff --git a/src/routes/(main)/agent/features/Conversation/MainChatInput/MessageFromUrl.tsx b/src/routes/(main)/agent/features/Conversation/MainChatInput/MessageFromUrl.tsx
index 0300a67ce60..ad9af34e44e 100644
--- a/src/routes/(main)/agent/features/Conversation/MainChatInput/MessageFromUrl.tsx
+++ b/src/routes/(main)/agent/features/Conversation/MainChatInput/MessageFromUrl.tsx
@@ -4,6 +4,7 @@ import { useEffect, useMemo, useRef } from 'react';
import { useLocation, useSearchParams } from 'react-router';
import { useConversationStore } from '@/features/Conversation';
+import { useConversationResourceAccess } from '@/features/Conversation/hooks/useConversationResourceAccess';
import { overlayCaptureUploadPool } from '@/features/Electron/ScreenCapture/overlayCaptureUploadPool';
import { canConsumePendingOverlayDispatch } from '@/features/Electron/ScreenCapture/overlayDispatch';
import { useOverlayDispatchStore } from '@/features/Electron/ScreenCapture/overlayDispatchStore';
@@ -30,6 +31,10 @@ const MessageFromUrl = () => {
const isAgentConfigLoading = useAgentStore(agentSelectors.isAgentConfigLoading);
const { allowed: canCreate } = usePermission('create_content');
const { allowed: canEdit } = usePermission('edit_own_content');
+ // Per-resource General access: view-only members must not auto-send into a
+ // shared agent, whatever the URL says. Wait for the settled value — the
+ // permissive loading default would otherwise let the send race through.
+ const { canUseResource, isAccessLoading } = useConversationResourceAccess();
const [pendingDispatch, clearPendingDispatch] = useOverlayDispatchStore((s) => [
s.pendingDispatch,
s.clearPendingDispatch,
@@ -64,6 +69,8 @@ const MessageFromUrl = () => {
const isReady = !isAgentConfigLoading && (isNewConversation || messagesInit);
if (!isReady) return;
+ if (isAccessLoading) return;
+
const signature = `${agentId}::${message}`;
if (lastProcessedSignatureRef.current === signature) return;
lastProcessedSignatureRef.current = signature;
@@ -78,6 +85,10 @@ const MessageFromUrl = () => {
{ replace: true },
);
+ // View-only: consume the param (so it doesn't linger in the URL) but
+ // never send.
+ if (!canUseResource) return;
+
// Send the message
sendMessage({ message });
}, [
@@ -86,6 +97,8 @@ const MessageFromUrl = () => {
sendMessage,
agentId,
canCreate,
+ canUseResource,
+ isAccessLoading,
context.topicId,
isAgentConfigLoading,
messagesInit,
@@ -95,6 +108,7 @@ const MessageFromUrl = () => {
useEffect(() => {
if (!pendingDispatch) return;
if (!canCreate) return;
+ if (isAccessLoading) return;
if (
!canConsumePendingOverlayDispatch({
@@ -112,6 +126,14 @@ const MessageFromUrl = () => {
if (lastProcessedOverlayDispatchIdRef.current === pendingDispatch.dispatchId) return;
lastProcessedOverlayDispatchIdRef.current = pendingDispatch.dispatchId;
+ // View-only: drop the parked dispatch instead of sending / writing config.
+ if (!canUseResource) {
+ const { captureIds, dispatchId } = pendingDispatch;
+ for (const captureId of captureIds) overlayCaptureUploadPool.remove(captureId);
+ clearPendingDispatch(dispatchId);
+ return;
+ }
+
const { captureIds, modelId, prompt, provider } = pendingDispatch;
const captureEntries = captureIds
.map((id) => ({ entry: overlayCaptureUploadPool.get(id), id }))
@@ -145,8 +167,10 @@ const MessageFromUrl = () => {
agentId,
canCreate,
canEdit,
+ canUseResource,
clearPendingDispatch,
context.topicId,
+ isAccessLoading,
isAgentConfigLoading,
messagesInit,
pendingDispatch,
diff --git a/src/routes/(main)/agent/features/Conversation/index.tsx b/src/routes/(main)/agent/features/Conversation/index.tsx
index de12725e73a..5514bf5cdd8 100644
--- a/src/routes/(main)/agent/features/Conversation/index.tsx
+++ b/src/routes/(main)/agent/features/Conversation/index.tsx
@@ -5,9 +5,14 @@ import React, { memo, Suspense, useCallback } from 'react';
import DragUploadZone, { type DroppedLocalPath, useUploadFiles } from '@/components/DragUploadZone';
import Loading from '@/components/Loading/BrandTextLoading';
import { insertLocalPathTags } from '@/features/ChatInput/InputEditor/insertLocalFileTags';
+import { useResourceAccess } from '@/features/ResourcePermission/useResourceAccess';
import { useEffectiveWorkingDirectory } from '@/hooks/useEffectiveWorkingDirectory';
import { useAgentStore } from '@/store/agent';
-import { agentChatConfigSelectors, agentSelectors } from '@/store/agent/selectors';
+import {
+ agentChatConfigSelectors,
+ agentSelectors,
+ builtinAgentSelectors,
+} from '@/store/agent/selectors';
import { useChatStore } from '@/store/chat';
import ConversationArea from './ConversationArea';
@@ -26,6 +31,17 @@ const ChatConversation = memo(() => {
const isHeterogeneous = useAgentStore(agentSelectors.isCurrentAgentHeterogeneous);
const isLocalSystemEnabled = useAgentStore(agentChatConfigSelectors.isLocalSystemEnabled);
+ // Drag-drop upload bypasses the (view-only-disabled) input editor, so the
+ // drop zone itself follows the same per-resource General-access rules as the
+ // chat input: inbox and private agents are never gated.
+ const inboxAgentId = useAgentStore(builtinAgentSelectors.inboxAgentId);
+ const agentVisibility = useAgentStore((s) =>
+ agentId ? s.agentMap[agentId]?.visibility : undefined,
+ );
+ const gatedResourceId =
+ agentId && agentId !== inboxAgentId && agentVisibility !== 'private' ? agentId : undefined;
+ const { canUseResource } = useResourceAccess('agent', gatedResourceId);
+
const { handleUploadFiles } = useUploadFiles({ agentId, model, provider });
const workingDirectory = useEffectiveWorkingDirectory(agentId);
@@ -38,20 +54,28 @@ const ChatConversation = memo(() => {
insertLocalPathTags(editor, paths);
}, []);
+ const content = (
+ <Flexbox flex={1} height={'100%'} style={{ minWidth: 0 }}>
+ <TooltipGroup>
+ <ConversationArea />
+ </TooltipGroup>
+ </Flexbox>
+ );
+
return (
<Suspense fallback={<Loading debugId="Agent > ChatConversation" />}>
- <DragUploadZone
- enableLocalPathReference={enableLocalPathReference}
- style={wrapperStyle}
- onLocalPaths={enableLocalPathReference ? handleLocalPaths : undefined}
- onUploadFiles={handleUploadFiles}
- >
- <Flexbox flex={1} height={'100%'} style={{ minWidth: 0 }}>
- <TooltipGroup>
- <ConversationArea />
- </TooltipGroup>
- </Flexbox>
- </DragUploadZone>
+ {canUseResource ? (
+ <DragUploadZone
+ enableLocalPathReference={enableLocalPathReference}
+ style={wrapperStyle}
+ onLocalPaths={enableLocalPathReference ? handleLocalPaths : undefined}
+ onUploadFiles={handleUploadFiles}
+ >
+ {content}
+ </DragUploadZone>
+ ) : (
+ <div style={wrapperStyle}>{content}</div>
+ )}
</Suspense>
);
});
diff --git a/src/routes/(main)/agent/profile/features/EditorCanvas/index.tsx b/src/routes/(main)/agent/profile/features/EditorCanvas/index.tsx
index fd47b13930d..c9a0f14f7aa 100644
--- a/src/routes/(main)/agent/profile/features/EditorCanvas/index.tsx
+++ b/src/routes/(main)/agent/profile/features/EditorCanvas/index.tsx
@@ -13,6 +13,7 @@ import { message } from '@/components/AntdStaticMethods';
import AutoSaveHint from '@/components/Editor/AutoSaveHint';
import { createChatInputRichPlugins } from '@/features/ChatInput/InputEditor/plugins';
import { EditingIndicator } from '@/features/EditLock';
+import { useResourceAccess } from '@/features/ResourcePermission/useResourceAccess';
import { usePermission } from '@/hooks/usePermission';
import { EMPTY_EDITOR_STATE } from '@/libs/editor/constants';
import { useAgentStore } from '@/store/agent';
@@ -63,7 +64,7 @@ interface ProgrammaticDocument {
const AgentEditorCanvas = memo<AgentEditorCanvasProps>(({ agentId }) => {
const { t } = useTranslation('setting');
- const { allowed: canEdit } = usePermission('edit_own_content');
+ const { allowed: hasEditPermission } = usePermission('edit_own_content');
const [editorInit, setEditorInit] = useState(false);
const [contentInit, setContentInit] = useState(false);
const config = useAgentStore((s) => s.agentMap[agentId], isEqual);
@@ -116,6 +117,13 @@ const AgentEditorCanvas = memo<AgentEditorCanvasProps>(({ agentId }) => {
const promptSaveStatus = useProfileStore(profileSelectors.promptSaveStatus);
const retryPromptSave = useProfileStore((s) => s.retryPromptSave);
const setHasEdited = useProfileStore((s) => s.setHasEdited);
+ // A workspace member whose General access on this agent is view/use level
+ // can't edit the prompt (defaults permissive while loading — server enforces).
+ const { canEditResource } = useResourceAccess(
+ 'agent',
+ config?.visibility === 'private' ? undefined : agentId,
+ );
+ const canEdit = hasEditPermission && canEditResource;
// Read-only until the lock resolves, so the user can't start typing on an agent
// that turns out to be locked and get bounced mid-edit.
const editable = canEdit && !lockedByOther && !lockPending;
diff --git a/src/routes/(main)/agent/profile/features/Header/index.test.tsx b/src/routes/(main)/agent/profile/features/Header/index.test.tsx
index ae61fb9945e..00c45dbd682 100644
--- a/src/routes/(main)/agent/profile/features/Header/index.test.tsx
+++ b/src/routes/(main)/agent/profile/features/Header/index.test.tsx
@@ -9,18 +9,22 @@ import Header from './index';
const mocks = vi.hoisted(() => ({
agentState: {
activeAgentId: 'agent-1',
+ authorId: undefined as string | undefined,
config: {
model: 'gpt-4o',
plugins: ['lobe-web-browsing'],
provider: 'openai',
},
+ isInbox: false,
isCurrentAgentHeterogeneous: false,
meta: {
description: 'Test description',
tags: ['test'],
title: 'Test Agent',
},
+ createdAt: undefined as Date | undefined,
systemRole: 'You are helpful.',
+ visibility: 'public' as 'private' | 'public',
},
globalState: {
isStatusInit: true,
@@ -35,6 +39,7 @@ const mocks = vi.hoisted(() => ({
editor: undefined as { getDocument: (format: string) => string | undefined } | undefined,
lockState: { holderId: null as string | null, lockedByOther: false, pending: false },
},
+ resourcePermissionMenuItemArgs: [] as unknown[],
}));
vi.mock('@lobechat/const', async (importOriginal) => ({
@@ -144,6 +149,27 @@ vi.mock('@/features/AgentBreadcrumb', () => ({
default: () => null,
}));
+vi.mock('@/business/client/hooks/useHasActiveWorkspace', () => ({
+ useHasActiveWorkspace: () => true,
+}));
+
+vi.mock('@/features/ResourcePermission/AccessLevelTag', () => ({
+ default: ({ resourceId }: { resourceId?: string }) => (
+ <span data-testid="access-level-resource-id">{resourceId}</span>
+ ),
+}));
+
+vi.mock('@/features/ResourcePermission/useResourceAccess', () => ({
+ useResourceAccess: () => ({ canEditResource: true, canManageResource: true }),
+}));
+
+vi.mock('@/features/ResourcePermission/useResourcePermissionMenuItem', () => ({
+ useResourcePermissionMenuItem: (...args: unknown[]) => {
+ mocks.resourcePermissionMenuItemArgs = args;
+ return { key: 'member-permissions', label: 'Members: Can use' };
+ },
+}));
+
vi.mock('@/features/NavHeader', () => ({
default: ({
left,
@@ -174,12 +200,18 @@ vi.mock('@/store/agent', () => ({
vi.mock('@/store/agent/selectors', () => ({
agentSelectors: {
+ currentAgentAuthorId: (state: typeof mocks.agentState) => state.authorId,
currentAgentConfig: (state: typeof mocks.agentState) => state.config,
+ currentAgentCreatedAt: (state: typeof mocks.agentState) => state.createdAt,
currentAgentMeta: (state: typeof mocks.agentState) => state.meta,
currentAgentSystemRole: (state: typeof mocks.agentState) => state.systemRole,
+ currentAgentVisibility: (state: typeof mocks.agentState) => state.visibility,
isCurrentAgentHeterogeneous: (state: typeof mocks.agentState) =>
state.isCurrentAgentHeterogeneous,
},
+ builtinAgentSelectors: {
+ isInboxAgent: (state: typeof mocks.agentState) => state.isInbox,
+ },
}));
vi.mock('@/store/global', () => ({
@@ -226,7 +258,10 @@ describe('Agent profile Header', () => {
vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:agent-profile');
vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => {});
mocks.agentState.isCurrentAgentHeterogeneous = false;
+ mocks.agentState.isInbox = false;
mocks.agentState.systemRole = 'You are helpful.';
+ mocks.agentState.visibility = 'public';
+ mocks.resourcePermissionMenuItemArgs = [];
mocks.globalState.showAgentBuilderPanel = false;
mocks.profileState.editor = undefined;
});
@@ -251,6 +286,16 @@ describe('Agent profile Header', () => {
).toBeInTheDocument();
});
+ it('shows workspace resource permission controls for the LobeAI inbox agent', () => {
+ mocks.agentState.isInbox = true;
+
+ render(<Header />);
+
+ expect(mocks.resourcePermissionMenuItemArgs).toEqual(['agent', 'agent-1']);
+ expect(screen.getByRole('button', { name: 'Members: Can use' })).toBeInTheDocument();
+ expect(screen.getByTestId('access-level-resource-id')).toHaveTextContent('agent-1');
+ });
+
it('should export the current agent profile as markdown', async () => {
render(<Header />);
diff --git a/src/routes/(main)/agent/profile/features/Header/index.tsx b/src/routes/(main)/agent/profile/features/Header/index.tsx
index 0258893400e..644c71d0157 100644
--- a/src/routes/(main)/agent/profile/features/Header/index.tsx
+++ b/src/routes/(main)/agent/profile/features/Header/index.tsx
@@ -2,6 +2,7 @@ import { isDesktop } from '@lobechat/const';
import { getActivePluginIds } from '@lobechat/types';
import { ActionIcon, DropdownMenu, Flexbox, Icon } from '@lobehub/ui';
import { confirmModal, type ModalInstance } from '@lobehub/ui/base-ui';
+import { cssVar } from 'antd-style';
import isEqual from 'fast-deep-equal';
import type { TFunction } from 'i18next';
import {
@@ -11,21 +12,28 @@ import {
MoreHorizontal,
Settings2Icon,
Trash,
+ UserRound,
} from 'lucide-react';
import { memo, useCallback, useEffect, useMemo, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { useAgentTransferMenuItem } from '@/business/client/hooks/useAgentTransferMenuItem';
+import { useAuthorInfo } from '@/business/client/hooks/useAuthorInfo';
import { useBusinessAgentImportMenuItem } from '@/business/client/hooks/useBusinessAgentImportMenuItem';
+import { useHasActiveWorkspace } from '@/business/client/hooks/useHasActiveWorkspace';
import { message } from '@/components/AntdStaticMethods';
import { DESKTOP_HEADER_ICON_SMALL_SIZE } from '@/const/layoutTokens';
import AgentBreadcrumb from '@/features/AgentBreadcrumb';
import NavHeader from '@/features/NavHeader';
+import { formatPageEditorInfoTime } from '@/features/PageEditor/formatPageEditorInfoTime';
+import AccessLevelTag from '@/features/ResourcePermission/AccessLevelTag';
+import { useResourceAccess } from '@/features/ResourcePermission/useResourceAccess';
+import { useResourcePermissionMenuItem } from '@/features/ResourcePermission/useResourcePermissionMenuItem';
import ToggleRightPanelButton from '@/features/RightPanel/ToggleRightPanelButton';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { usePermission } from '@/hooks/usePermission';
import { useAgentStore } from '@/store/agent';
-import { agentSelectors } from '@/store/agent/selectors';
+import { agentSelectors, builtinAgentSelectors } from '@/store/agent/selectors';
import { useGlobalStore } from '@/store/global';
import { systemStatusSelectors } from '@/store/global/selectors';
import { useHomeStore } from '@/store/home';
@@ -92,7 +100,8 @@ const buildAgentProfileMarkdown = (params: {
};
const Header = memo(() => {
- const { t } = useTranslation(['setting', 'chat', 'file', 'common', 'spend']);
+ const { i18n, t } = useTranslation(['setting', 'chat', 'file', 'common', 'spend']);
+ const dateLocale = i18n?.resolvedLanguage || i18n?.language;
const navigate = useWorkspaceAwareNavigate();
const meta = useAgentStore(agentSelectors.currentAgentMeta, isEqual);
@@ -100,6 +109,16 @@ const Header = memo(() => {
const systemRole = useAgentStore(agentSelectors.currentAgentSystemRole);
const activeAgentId = useAgentStore((s) => s.activeAgentId);
const isHeterogeneous = useAgentStore(agentSelectors.isCurrentAgentHeterogeneous);
+ const isInbox = useAgentStore(builtinAgentSelectors.isInboxAgent);
+ const visibility = useAgentStore(agentSelectors.currentAgentVisibility);
+ const authorId = useAgentStore(agentSelectors.currentAgentAuthorId);
+ const createdAt = useAgentStore(agentSelectors.currentAgentCreatedAt);
+ const authorName = useAuthorInfo(authorId)?.fullName;
+ const hasActiveWorkspace = useHasActiveWorkspace();
+ // Resource permissions apply to every public workspace agent, including the
+ // workspace-scoped LobeAI row. Builtin restrictions only prevent visibility
+ // changes; they must not hide the independent General-access control.
+ const showPermissionsEntry = hasActiveWorkspace && !!activeAgentId && visibility !== 'private';
const [showAgentBuilderPanel, toggleAgentBuilderPanel, isStatusInit] = useGlobalStore((s) => [
systemStatusSelectors.showAgentBuilderPanel(s),
s.toggleAgentBuilderPanel,
@@ -109,10 +128,17 @@ const Header = memo(() => {
const editor = useProfileStore((s) => s.editor);
const lockedByOther = useProfileStore(profileSelectors.lockedByOther);
const lockPending = useProfileStore(profileSelectors.lockPending);
- const { allowed: canEdit } = usePermission('edit_own_content');
+ const { allowed: hasEditPermission } = usePermission('edit_own_content');
+ // A workspace member without edit-level General access on this agent gets the
+ // same disabled-with-tooltip treatment as a role viewer (server enforces).
+ const { canEditResource, canManageResource } = useResourceAccess(
+ 'agent',
+ showPermissionsEntry ? activeAgentId : undefined,
+ );
+ const canManage = hasEditPermission && canManageResource;
const handleDelete = useCallback(() => {
- if (!canEdit || !activeAgentId) return;
+ if (!canManage || !activeAgentId) return;
confirmModal({
okButtonProps: { danger: true },
onOk: async () => {
@@ -122,7 +148,7 @@ const Header = memo(() => {
},
title: t('confirmRemoveSessionItemAlert', { ns: 'chat' }),
});
- }, [activeAgentId, canEdit, navigate, removeAgent, t]);
+ }, [activeAgentId, canManage, navigate, removeAgent, t]);
const handleExportMarkdown = useCallback(async () => {
try {
@@ -175,6 +201,10 @@ const Header = memo(() => {
const importMenuItem = useBusinessAgentImportMenuItem(activeAgentId ?? undefined);
const transferMenuItems = useAgentTransferMenuItem(activeAgentId ?? undefined, meta);
+ const memberPermissionMenuItem = useResourcePermissionMenuItem(
+ 'agent',
+ showPermissionsEntry ? activeAgentId : undefined,
+ );
const settingsModalRef = useRef<ModalInstance | null>(null);
useEffect(
@@ -190,10 +220,14 @@ const Header = memo(() => {
return [
{
+ // View/use-level members can't edit the agent config — keep the entry
+ // visible but disabled (project convention: disabled, not hidden).
+ disabled: !canEditResource,
icon: <Icon icon={Settings2Icon} />,
key: 'advanced-settings',
label: t('advancedSettings', { ns: 'setting' }),
onClick: () => {
+ if (!canEditResource) return;
settingsModalRef.current?.close();
settingsModalRef.current = openAgentSettingsModal();
},
@@ -206,6 +240,7 @@ const Header = memo(() => {
if (activeAgentId) navigate(`/agent/${activeAgentId}/stats`);
},
},
+ memberPermissionMenuItem,
{ type: 'divider' as const },
{
children: [
@@ -223,21 +258,54 @@ const Header = memo(() => {
importMenuItem,
businessTransferMenuItems.length > 0 ? { type: 'divider' as const } : null,
...businessTransferMenuItems,
- { type: 'divider' as const },
- {
- danger: true,
- disabled: !canEdit,
- icon: <Icon icon={Trash} />,
- key: 'delete',
- label: t('delete', { ns: 'common' }),
- onClick: handleDelete,
- },
+ canManage ? { type: 'divider' as const } : null,
+ canManage
+ ? {
+ danger: true,
+ icon: <Icon icon={Trash} />,
+ key: 'delete',
+ label: t('delete', { ns: 'common' }),
+ onClick: handleDelete,
+ }
+ : null,
+ // Author / creation info footer, mirroring the page editor menu.
+ ...(!isInbox && (authorName || createdAt)
+ ? [
+ { type: 'divider' as const },
+ {
+ disabled: true,
+ icon: authorName ? <Icon icon={UserRound} /> : undefined,
+ key: 'agent-info',
+ label: (
+ <span style={{ color: cssVar.colorTextTertiary, fontSize: 12, lineHeight: 1.6 }}>
+ {[
+ authorName,
+ createdAt
+ ? t('createdAt', {
+ ns: 'common',
+ time: formatPageEditorInfoTime(createdAt, dateLocale),
+ })
+ : '',
+ ]
+ .filter(Boolean)
+ .join(' · ')}
+ </span>
+ ),
+ },
+ ]
+ : []),
].filter(Boolean);
}, [
activeAgentId,
- canEdit,
+ authorName,
+ canEditResource,
+ canManage,
+ createdAt,
+ dateLocale,
handleExportMarkdown,
handleDelete,
+ isInbox,
+ memberPermissionMenuItem,
navigate,
t,
importMenuItem,
@@ -254,6 +322,10 @@ const Header = memo(() => {
<AgentStatusTag />
<AgentVersionReviewTag />
<AgentForkTag />
+ <AccessLevelTag
+ resourceId={showPermissionsEntry ? (activeAgentId ?? undefined) : undefined}
+ resourceType={'agent'}
+ />
</Flexbox>
}
right={
diff --git a/src/routes/(main)/agent/profile/features/ProfileEditor/RemoteAgentConfigCard.tsx b/src/routes/(main)/agent/profile/features/ProfileEditor/RemoteAgentConfigCard.tsx
index 7686b51495e..73df321384a 100644
--- a/src/routes/(main)/agent/profile/features/ProfileEditor/RemoteAgentConfigCard.tsx
+++ b/src/routes/(main)/agent/profile/features/ProfileEditor/RemoteAgentConfigCard.tsx
@@ -115,7 +115,8 @@ const ChangeDeviceContent = memo<ChangeDeviceContentProps>(
const { data: devices, isLoading: loadingDevices } = useDeviceList();
const onlineDevices = (devices ?? []).filter(
- (d) => d.online && (!isWorkspaceAgent || d.scope === 'workspace'),
+ (d) =>
+ d.online && (!isWorkspaceAgent || (d.scope === 'workspace' && d.visibility === 'public')),
);
const checkCapability = useCallback(
diff --git a/src/routes/(main)/agent/profile/features/ProfileEditor/WorkspaceAgentDevicePolicy.test.tsx b/src/routes/(main)/agent/profile/features/ProfileEditor/WorkspaceAgentDevicePolicy.test.tsx
new file mode 100644
index 00000000000..5ecc1f69997
--- /dev/null
+++ b/src/routes/(main)/agent/profile/features/ProfileEditor/WorkspaceAgentDevicePolicy.test.tsx
@@ -0,0 +1,149 @@
+import { act, fireEvent, render, screen } from '@testing-library/react';
+import type { ReactNode } from 'react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import WorkspaceAgentDevicePolicy from './WorkspaceAgentDevicePolicy';
+
+const testState = vi.hoisted(() => ({
+ agent: {
+ agentMap: {
+ 'agent-1': {
+ agencyConfig: {
+ executionTarget: 'auto' as const,
+ executionTargetSelectionPolicy: 'member' as const,
+ },
+ workspaceId: 'workspace-1',
+ },
+ },
+ updateAgentConfigById: vi.fn(),
+ },
+ mutateDevices: vi.fn(),
+}));
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+vi.mock('@lobehub/ui/base-ui', () => ({
+ Button: ({
+ 'aria-label': ariaLabel,
+ children,
+ disabled,
+ title,
+ }: {
+ 'aria-label'?: string;
+ 'children': ReactNode;
+ 'disabled'?: boolean;
+ 'title'?: string;
+ }) => (
+ <button aria-label={ariaLabel} disabled={disabled} title={title} type="button">
+ {children}
+ </button>
+ ),
+ DropdownMenu: ({
+ children,
+ items,
+ }: {
+ children: ReactNode;
+ items: {
+ disabled?: boolean;
+ key: string;
+ label: ReactNode;
+ onClick?: () => void;
+ }[];
+ }) => (
+ <div>
+ {children}
+ <div role="menu">
+ {items.map((item) => (
+ <button
+ disabled={item.disabled}
+ key={item.key}
+ role="menuitem"
+ type="button"
+ onClick={item.onClick}
+ >
+ {item.label}
+ </button>
+ ))}
+ </div>
+ </div>
+ ),
+ Select: ({
+ disabled,
+ loading,
+ popupMatchSelectWidth,
+ }: {
+ disabled?: boolean;
+ loading?: boolean;
+ popupMatchSelectWidth?: boolean | number;
+ }) => (
+ <button
+ data-popup-match-select-width={String(popupMatchSelectWidth)}
+ disabled={disabled || loading}
+ role="combobox"
+ />
+ ),
+}));
+
+vi.mock('@/features/DeviceManager/useDeviceList', () => ({
+ useDeviceList: () => ({
+ data: undefined,
+ error: undefined,
+ isLoading: true,
+ mutate: testState.mutateDevices,
+ }),
+}));
+
+vi.mock('@/store/agent', () => ({
+ useAgentStore: (selector: (state: typeof testState.agent) => unknown) =>
+ selector(testState.agent),
+}));
+
+describe('WorkspaceAgentDevicePolicy', () => {
+ beforeEach(() => {
+ testState.agent.updateAgentConfigById.mockReset();
+ testState.mutateDevices.mockReset();
+ });
+
+ it('keeps static targets and the selection policy menu interactive while saves are pending', async () => {
+ let finishSave: (() => void) | undefined;
+ testState.agent.updateAgentConfigById.mockImplementation(
+ () =>
+ new Promise<void>((resolve) => {
+ finishSave = resolve;
+ }),
+ );
+
+ render(<WorkspaceAgentDevicePolicy agentId="agent-1" />);
+
+ expect(screen.getByText('settingAgent.devicePolicy.title')).toBeTruthy();
+ expect(screen.queryByText('settingAgent.devicePolicy.defaultTarget')).toBeNull();
+ expect(screen.queryByText('settingAgent.devicePolicy.defaultTargetDesc')).toBeNull();
+ expect(screen.queryByRole('switch')).toBeNull();
+
+ const select = screen.getByRole('combobox') as HTMLButtonElement;
+ const policyButton = screen.getByRole('button', {
+ name: 'settingAgent.selectionPolicy.membersCanSwitch',
+ }) as HTMLButtonElement;
+ expect(select.disabled).toBe(false);
+ expect(select.dataset.popupMatchSelectWidth).toBe('true');
+ expect(policyButton.disabled).toBe(false);
+
+ fireEvent.click(policyButton);
+ fireEvent.click(
+ screen.getByRole('menuitem', {
+ name: 'settingAgent.selectionPolicy.membersCannotSwitch',
+ }),
+ );
+
+ expect(testState.agent.updateAgentConfigById).toHaveBeenCalledWith('agent-1', {
+ agencyConfig: {
+ executionTarget: 'auto',
+ executionTargetSelectionPolicy: 'fixed',
+ },
+ });
+
+ await act(async () => finishSave?.());
+ });
+});
diff --git a/src/routes/(main)/agent/profile/features/ProfileEditor/WorkspaceAgentDevicePolicy.tsx b/src/routes/(main)/agent/profile/features/ProfileEditor/WorkspaceAgentDevicePolicy.tsx
new file mode 100644
index 00000000000..de70d5d223b
--- /dev/null
+++ b/src/routes/(main)/agent/profile/features/ProfileEditor/WorkspaceAgentDevicePolicy.tsx
@@ -0,0 +1,408 @@
+'use client';
+
+import { HETEROGENEOUS_TYPE_LABELS } from '@lobechat/heterogeneous-agents';
+import type { DeviceExecutionTarget, DeviceListItem, LobeAgentAgencyConfig } from '@lobechat/types';
+import { Flexbox } from '@lobehub/ui';
+import type { SelectOptions } from '@lobehub/ui/base-ui';
+import { Select } from '@lobehub/ui/base-ui';
+import { createStaticStyles, cssVar } from 'antd-style';
+import { MonitorSmartphone } from 'lucide-react';
+import { memo, useCallback, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import AsyncError from '@/components/AsyncError';
+import { useDeviceList } from '@/features/DeviceManager/useDeviceList';
+import {
+ ExecutionTargetDeviceStatus,
+ ExecutionTargetIcon,
+ executionTargetValue,
+ groupExecutionTargetDevices,
+ isSharedExecutionTarget,
+ parseExecutionTargetValue,
+} from '@/features/ExecutionTargetPicker';
+import { isHeterogeneousSandboxExecutionAvailable } from '@/helpers/executionTarget';
+import { useAgentStore } from '@/store/agent';
+
+import {
+ WorkspaceAgentPolicyCard,
+ WorkspaceAgentSelectionPolicyMenu,
+} from './WorkspaceAgentPolicyCard';
+
+const styles = createStaticStyles(({ css }) => ({
+ option: css`
+ display: flex;
+ flex: 1;
+ gap: 8px;
+ align-items: center;
+
+ min-width: 0;
+ `,
+ optionDescription: css`
+ font-size: 12px;
+ line-height: 16px;
+ color: ${cssVar.colorTextDescription};
+ `,
+ optionIcon: css`
+ display: flex;
+ flex: none;
+ align-items: center;
+ justify-content: center;
+
+ width: 24px;
+ height: 24px;
+ border: 1px solid ${cssVar.colorBorderSecondary};
+ border-radius: ${cssVar.borderRadius};
+
+ color: ${cssVar.colorText};
+
+ background: ${cssVar.colorBgElevated};
+ `,
+ optionName: css`
+ overflow: hidden;
+
+ font-size: 14px;
+ font-weight: 500;
+ line-height: 20px;
+ color: ${cssVar.colorText};
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ `,
+ selectItem: css`
+ min-height: 40px;
+ `,
+ selectPopup: css`
+ max-width: calc(100vw - 24px);
+ `,
+ selectValue: css`
+ > span {
+ display: flex;
+ flex: 1;
+ min-width: 0;
+ }
+ `,
+ triggerIcon: css`
+ display: flex;
+ flex: none;
+ align-items: center;
+ justify-content: center;
+
+ width: 20px;
+ height: 20px;
+
+ color: ${cssVar.colorTextSecondary};
+ `,
+ triggerLabel: css`
+ display: flex;
+ flex: 1;
+ gap: 8px;
+ align-items: center;
+
+ min-width: 0;
+ `,
+ triggerName: css`
+ overflow: hidden;
+ flex: 1;
+
+ text-align: start;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ `,
+}));
+
+interface ExecutionTargetLabelProps {
+ compact?: boolean;
+ description: string;
+ device?: DeviceListItem;
+ label: string;
+ offlineLabel: string;
+ onlineLabel: string;
+ target: DeviceExecutionTarget;
+}
+
+const ExecutionTargetLabel = memo<ExecutionTargetLabelProps>(
+ ({ compact, description, device, label, offlineLabel, onlineLabel, target }) => {
+ const icon = <ExecutionTargetIcon devicePlatform={device?.platform} target={target} />;
+ const secondary = device ? (
+ <ExecutionTargetDeviceStatus
+ offlineLabel={offlineLabel}
+ online={device.online}
+ onlineLabel={onlineLabel}
+ />
+ ) : (
+ description
+ );
+
+ if (compact) {
+ return (
+ <span className={styles.triggerLabel}>
+ <span aria-hidden className={styles.triggerIcon}>
+ {icon}
+ </span>
+ <span className={styles.triggerName}>{label}</span>
+ {device ? <span className={styles.optionDescription}>{secondary}</span> : null}
+ </span>
+ );
+ }
+
+ return (
+ <span className={styles.option}>
+ <span aria-hidden className={styles.optionIcon}>
+ {icon}
+ </span>
+ <Flexbox flex={1} style={{ minWidth: 0 }}>
+ <span className={styles.optionName}>{label}</span>
+ <span className={styles.optionDescription}>{secondary}</span>
+ </Flexbox>
+ </span>
+ );
+ },
+);
+
+ExecutionTargetLabel.displayName = 'WorkspaceAgentDevicePolicy.ExecutionTargetLabel';
+
+interface WorkspaceAgentDevicePolicyProps {
+ agentId: string;
+ showDevicePicker?: boolean;
+}
+
+const WorkspaceAgentDevicePolicy = memo<WorkspaceAgentDevicePolicyProps>(
+ ({ agentId, showDevicePicker = true }) => {
+ const { t } = useTranslation(['setting', 'chat']);
+ const config = useAgentStore((s) => s.agentMap[agentId]);
+ const updateAgentConfigById = useAgentStore((s) => s.updateAgentConfigById);
+
+ const { data: devices, error, isLoading, mutate } = useDeviceList();
+ const { publicWorkspace: publicWorkspaceDevices } = useMemo(
+ () => groupExecutionTargetDevices(devices),
+ [devices],
+ );
+ const agencyConfig = config?.agencyConfig;
+ const heterogeneousType = agencyConfig?.heterogeneousProvider?.type;
+ const isHeterogeneous = !!heterogeneousType;
+ const supportsSandbox = isHeterogeneousSandboxExecutionAvailable(heterogeneousType);
+ const boundDevice = publicWorkspaceDevices.find(
+ (device) => device.deviceId === agencyConfig?.boundDeviceId,
+ );
+ const isFixed = agencyConfig?.executionTargetSelectionPolicy === 'fixed';
+
+ const targetLabels = useMemo(
+ () => ({
+ auto: {
+ description: t('chat:heteroAgent.executionTarget.autoDesc'),
+ label: t('chat:heteroAgent.executionTarget.auto'),
+ },
+ none: {
+ description: t('chat:heteroAgent.executionTarget.noneDesc'),
+ label: t('chat:heteroAgent.executionTarget.none'),
+ },
+ sandbox: {
+ description: t(
+ supportsSandbox
+ ? 'chat:heteroAgent.executionTarget.sandboxDesc'
+ : 'chat:heteroAgent.executionTarget.sandboxUnsupported',
+ {
+ name: heterogeneousType ? HETEROGENEOUS_TYPE_LABELS[heterogeneousType] : undefined,
+ },
+ ),
+ label: t('chat:heteroAgent.executionTarget.sandbox'),
+ },
+ }),
+ [heterogeneousType, supportsSandbox, t],
+ );
+
+ const renderTargetLabel = useCallback(
+ (target: 'auto' | 'none' | 'sandbox', compact = false) => (
+ <ExecutionTargetLabel
+ compact={compact}
+ description={targetLabels[target].description}
+ label={targetLabels[target].label}
+ offlineLabel={t('chat:heteroAgent.executionTarget.offline')}
+ onlineLabel={t('chat:heteroAgent.executionTarget.online')}
+ target={target}
+ />
+ ),
+ [t, targetLabels],
+ );
+
+ const renderDeviceLabel = useCallback(
+ (device: DeviceListItem, compact = false) => (
+ <ExecutionTargetLabel
+ compact={compact}
+ description=""
+ device={device}
+ label={device.friendlyName || device.hostname || device.deviceId}
+ offlineLabel={t('chat:heteroAgent.executionTarget.offline')}
+ onlineLabel={t('chat:heteroAgent.executionTarget.online')}
+ target={'device'}
+ />
+ ),
+ [t],
+ );
+
+ const targetOptions = useMemo<SelectOptions<string>>(() => {
+ const sharedTargets: SelectOptions<string> = [
+ ...(!isHeterogeneous
+ ? [
+ {
+ label: renderTargetLabel('none'),
+ title: targetLabels.none.label,
+ value: executionTargetValue('none'),
+ },
+ {
+ label: renderTargetLabel('auto'),
+ title: targetLabels.auto.label,
+ value: executionTargetValue('auto'),
+ },
+ ]
+ : []),
+ {
+ disabled: !supportsSandbox,
+ label: renderTargetLabel('sandbox'),
+ title: targetLabels.sandbox.label,
+ value: executionTargetValue('sandbox'),
+ },
+ ];
+
+ const workspaceOptions = isLoading
+ ? [
+ {
+ disabled: true,
+ label: t('chat:heteroAgent.executionTarget.loading'),
+ value: 'status:loading',
+ },
+ ]
+ : publicWorkspaceDevices.length > 0
+ ? publicWorkspaceDevices.map((device) => ({
+ label: renderDeviceLabel(device),
+ title: device.friendlyName || device.hostname || device.deviceId,
+ value: executionTargetValue('device', device.deviceId),
+ }))
+ : [
+ {
+ disabled: true,
+ label: t('settingAgent.devicePolicy.noPublicDevice'),
+ value: 'status:empty',
+ },
+ ];
+
+ return [
+ ...sharedTargets,
+ ...(!error
+ ? [
+ {
+ label: t('chat:heteroAgent.executionTarget.workspaceGroup'),
+ options: workspaceOptions,
+ },
+ ]
+ : []),
+ ];
+ }, [
+ error,
+ isLoading,
+ isHeterogeneous,
+ publicWorkspaceDevices,
+ renderDeviceLabel,
+ renderTargetLabel,
+ supportsSandbox,
+ t,
+ targetLabels,
+ ]);
+
+ const configuredTarget = agencyConfig?.executionTarget;
+ const selectedTarget =
+ configuredTarget === 'device' && boundDevice
+ ? { deviceId: boundDevice.deviceId, target: 'device' as const }
+ : isSharedExecutionTarget(configuredTarget) && configuredTarget !== 'device'
+ ? { target: configuredTarget }
+ : configuredTarget === undefined && !isHeterogeneous
+ ? { target: 'none' as const }
+ : undefined;
+ const selectedValue = selectedTarget
+ ? executionTargetValue(selectedTarget.target, selectedTarget.deviceId)
+ : undefined;
+ const canLockCurrentTarget =
+ !!selectedTarget && (selectedTarget.target !== 'sandbox' || supportsSandbox);
+
+ const saveAgencyConfig = useCallback(
+ (patch: Partial<LobeAgentAgencyConfig>) =>
+ updateAgentConfigById(agentId, { agencyConfig: patch }),
+ [agentId, updateAgentConfigById],
+ );
+
+ if (!config?.workspaceId) return null;
+
+ return (
+ <WorkspaceAgentPolicyCard
+ icon={MonitorSmartphone}
+ title={t('settingAgent.devicePolicy.title')}
+ action={
+ <WorkspaceAgentSelectionPolicyMenu
+ locked={isFixed}
+ lockedDisabled={!isFixed && !canLockCurrentTarget}
+ lockedLabel={t('settingAgent.selectionPolicy.membersCannotSwitch')}
+ unlockedLabel={t('settingAgent.selectionPolicy.membersCanSwitch')}
+ onChange={(locked) => {
+ if (!locked) {
+ void saveAgencyConfig({ executionTargetSelectionPolicy: 'member' });
+ return;
+ }
+ if (!selectedTarget) return;
+
+ void saveAgencyConfig({
+ ...(selectedTarget.deviceId ? { boundDeviceId: selectedTarget.deviceId } : {}),
+ executionTarget: selectedTarget.target,
+ executionTargetSelectionPolicy: 'fixed',
+ });
+ }}
+ />
+ }
+ >
+ {showDevicePicker ? (
+ <Select
+ optionRender={(option) => option.label}
+ options={targetOptions}
+ placeholder={t('settingAgent.devicePolicy.selectTarget')}
+ popupMatchSelectWidth={true}
+ value={selectedValue}
+ classNames={{
+ item: styles.selectItem,
+ popup: styles.selectPopup,
+ value: styles.selectValue,
+ }}
+ labelRender={(option) => {
+ if (typeof option.value !== 'string') return option.label;
+ const selection = parseExecutionTargetValue(option.value);
+ if (!selection) return option.label;
+ if (selection.target === 'device') {
+ const device = publicWorkspaceDevices.find(
+ (item) => item.deviceId === selection.deviceId,
+ );
+ return device ? renderDeviceLabel(device, true) : option.label;
+ }
+ if (selection.target === 'local') return option.label;
+ return renderTargetLabel(selection.target, true);
+ }}
+ onChange={(value) => {
+ if (typeof value !== 'string') return;
+ const selection = parseExecutionTargetValue(value);
+ if (!selection) return;
+
+ void saveAgencyConfig({
+ ...(selection.deviceId ? { boundDeviceId: selection.deviceId } : {}),
+ executionTarget: selection.target,
+ });
+ }}
+ />
+ ) : null}
+
+ {error ? (
+ <AsyncError error={error} variant={'inline'} onRetry={() => void mutate()} />
+ ) : null}
+ </WorkspaceAgentPolicyCard>
+ );
+ },
+);
+
+WorkspaceAgentDevicePolicy.displayName = 'WorkspaceAgentDevicePolicy';
+
+export default WorkspaceAgentDevicePolicy;
diff --git a/src/routes/(main)/agent/profile/features/ProfileEditor/WorkspaceAgentModelPolicy.tsx b/src/routes/(main)/agent/profile/features/ProfileEditor/WorkspaceAgentModelPolicy.tsx
new file mode 100644
index 00000000000..950002a749d
--- /dev/null
+++ b/src/routes/(main)/agent/profile/features/ProfileEditor/WorkspaceAgentModelPolicy.tsx
@@ -0,0 +1,71 @@
+'use client';
+
+import isEqual from 'fast-deep-equal';
+import { Bot } from 'lucide-react';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import ModelSelect from '@/features/ModelSelect';
+import { usePermission } from '@/hooks/usePermission';
+import { useAgentStore } from '@/store/agent';
+import { agentByIdSelectors, agentSelectors } from '@/store/agent/selectors';
+
+import {
+ WorkspaceAgentPolicyCard,
+ WorkspaceAgentSelectionPolicyMenu,
+} from './WorkspaceAgentPolicyCard';
+
+interface WorkspaceAgentModelPolicyProps {
+ agentId: string;
+}
+
+export const WorkspaceAgentModelPolicy = memo<WorkspaceAgentModelPolicyProps>(({ agentId }) => {
+ const { t } = useTranslation('setting');
+ const { allowed: canEdit } = usePermission('edit_own_content');
+ const config = useAgentStore(agentSelectors.getAgentConfigById(agentId), isEqual);
+ const isWorkspaceAgent = useAgentStore(agentByIdSelectors.isWorkspaceAgentById(agentId));
+ const updateAgentConfigById = useAgentStore((s) => s.updateAgentConfigById);
+ const isLocked = config.agencyConfig?.modelSelectionPolicy !== 'member';
+
+ if (!isWorkspaceAgent) return null;
+
+ return (
+ <WorkspaceAgentPolicyCard
+ icon={Bot}
+ title={t('settingAgent.modelPolicy.title')}
+ action={
+ <WorkspaceAgentSelectionPolicyMenu
+ disabled={!canEdit}
+ locked={isLocked}
+ lockedLabel={t('settingAgent.selectionPolicy.membersCannotSwitch')}
+ unlockedLabel={t('settingAgent.selectionPolicy.membersCanSwitch')}
+ onChange={(locked) => {
+ if (!canEdit) return;
+
+ void updateAgentConfigById(agentId, {
+ agencyConfig: {
+ modelSelectionPolicy: locked ? 'fixed' : 'member',
+ },
+ });
+ }}
+ />
+ }
+ >
+ <ModelSelect
+ disabled={!canEdit}
+ style={{ width: '100%' }}
+ value={{
+ model: config.model,
+ provider: config.provider,
+ }}
+ onChange={(value) => {
+ if (!canEdit) return;
+
+ void updateAgentConfigById(agentId, value);
+ }}
+ />
+ </WorkspaceAgentPolicyCard>
+ );
+});
+
+WorkspaceAgentModelPolicy.displayName = 'WorkspaceAgentModelPolicy';
diff --git a/src/routes/(main)/agent/profile/features/ProfileEditor/WorkspaceAgentPolicyCard.tsx b/src/routes/(main)/agent/profile/features/ProfileEditor/WorkspaceAgentPolicyCard.tsx
new file mode 100644
index 00000000000..6312a893bc6
--- /dev/null
+++ b/src/routes/(main)/agent/profile/features/ProfileEditor/WorkspaceAgentPolicyCard.tsx
@@ -0,0 +1,124 @@
+'use client';
+
+import { Flexbox, Icon, Text, Tooltip } from '@lobehub/ui';
+import type { DropdownItem } from '@lobehub/ui/base-ui';
+import { Button, DropdownMenu } from '@lobehub/ui/base-ui';
+import { createStaticStyles, cssVar, cx } from 'antd-style';
+import type { LucideIcon } from 'lucide-react';
+import { CheckIcon, ChevronDownIcon, LockIcon, UsersIcon } from 'lucide-react';
+import type { ReactNode } from 'react';
+import { memo, useState } from 'react';
+
+const styles = createStaticStyles(({ css }) => ({
+ card: css`
+ align-self: flex-start;
+
+ width: calc(50% - 4px);
+ padding: 16px;
+ border: 1px solid ${cssVar.colorBorderSecondary};
+ border-radius: ${cssVar.borderRadiusLG};
+
+ background: ${cssVar.colorBgContainer};
+
+ @container (max-width: 840px) {
+ width: 100%;
+ }
+ `,
+ fullWidth: css`
+ width: 100%;
+ `,
+ policyButton: css`
+ color: ${cssVar.colorTextSecondary};
+ `,
+ title: css`
+ font-size: 14px;
+ font-weight: 500;
+ `,
+}));
+
+interface WorkspaceAgentPolicyCardProps {
+ action?: ReactNode;
+ children?: ReactNode;
+ fullWidth?: boolean;
+ icon: LucideIcon;
+ title: ReactNode;
+}
+
+interface WorkspaceAgentSelectionPolicyMenuProps {
+ disabled?: boolean;
+ locked: boolean;
+ lockedDisabled?: boolean;
+ lockedLabel: string;
+ onChange: (locked: boolean) => void;
+ unlockedLabel: string;
+}
+
+export const WorkspaceAgentSelectionPolicyMenu = memo<WorkspaceAgentSelectionPolicyMenuProps>(
+ ({ disabled, locked, lockedDisabled, lockedLabel, onChange, unlockedLabel }) => {
+ const [menuOpen, setMenuOpen] = useState(false);
+ const currentLabel = locked ? lockedLabel : unlockedLabel;
+ const menuItems: DropdownItem[] = [
+ {
+ extra: !locked ? <Icon icon={CheckIcon} size={14} /> : undefined,
+ icon: UsersIcon,
+ key: 'member',
+ label: unlockedLabel,
+ onClick: () => {
+ if (locked) onChange(false);
+ },
+ },
+ {
+ disabled: lockedDisabled,
+ extra: locked ? <Icon icon={CheckIcon} size={14} /> : undefined,
+ icon: LockIcon,
+ key: 'fixed',
+ label: lockedLabel,
+ onClick: () => {
+ if (!locked) onChange(true);
+ },
+ },
+ ];
+
+ return (
+ <DropdownMenu
+ items={menuItems}
+ open={menuOpen}
+ placement={'bottomRight'}
+ popupProps={{ style: { minWidth: 180 } }}
+ onOpenChange={setMenuOpen}
+ >
+ <Tooltip disabled={menuOpen} title={currentLabel}>
+ <Button
+ aria-label={currentLabel}
+ className={styles.policyButton}
+ disabled={disabled}
+ icon={locked ? LockIcon : UsersIcon}
+ size={'small'}
+ type={'text'}
+ >
+ <Icon aria-hidden icon={ChevronDownIcon} size={12} />
+ </Button>
+ </Tooltip>
+ </DropdownMenu>
+ );
+ },
+);
+
+WorkspaceAgentSelectionPolicyMenu.displayName = 'WorkspaceAgentSelectionPolicyMenu';
+
+export const WorkspaceAgentPolicyCard = memo<WorkspaceAgentPolicyCardProps>(
+ ({ action, children, fullWidth, icon, title }) => (
+ <Flexbox className={cx(styles.card, fullWidth && styles.fullWidth)} gap={12}>
+ <Flexbox horizontal align={'center'} justify={'space-between'}>
+ <Flexbox horizontal align={'center'} gap={8}>
+ <Icon icon={icon} size={16} />
+ <Text className={styles.title}>{title}</Text>
+ </Flexbox>
+ {action}
+ </Flexbox>
+ {children}
+ </Flexbox>
+ ),
+);
+
+WorkspaceAgentPolicyCard.displayName = 'WorkspaceAgentPolicyCard';
diff --git a/src/routes/(main)/agent/profile/features/ProfileEditor/index.tsx b/src/routes/(main)/agent/profile/features/ProfileEditor/index.tsx
index c4701a85a50..5253791c459 100644
--- a/src/routes/(main)/agent/profile/features/ProfileEditor/index.tsx
+++ b/src/routes/(main)/agent/profile/features/ProfileEditor/index.tsx
@@ -3,9 +3,11 @@
import { isDesktop } from '@lobechat/const';
import { isRemoteHeterogeneousType } from '@lobechat/heterogeneous-agents';
import { Flexbox } from '@lobehub/ui';
-import { Tabs, type TabsItem } from '@lobehub/ui/base-ui';
+import type { TabsItem } from '@lobehub/ui/base-ui';
+import { Tabs } from '@lobehub/ui/base-ui';
import { createStaticStyles, cssVar } from 'antd-style';
import isEqual from 'fast-deep-equal';
+import { Wrench } from 'lucide-react';
import React, { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -13,7 +15,7 @@ import ModelSelect from '@/features/ModelSelect';
import RunPriorityHint from '@/features/ProfileEditor/AgentUserTools/RunPriorityHint';
import { usePermission } from '@/hooks/usePermission';
import { useAgentStore } from '@/store/agent';
-import { agentSelectors } from '@/store/agent/selectors';
+import { agentByIdSelectors, agentSelectors } from '@/store/agent/selectors';
import EditorCanvas from '../EditorCanvas';
import AgentHeader from './AgentHeader';
@@ -21,6 +23,9 @@ import AgentTool from './AgentTool';
import CloudHeterogeneousConfig from './CloudHeterogeneousConfig';
import HeterogeneousAgentStatusCard from './HeterogeneousAgentStatusCard';
import RemoteAgentConfigCard from './RemoteAgentConfigCard';
+import WorkspaceAgentDevicePolicy from './WorkspaceAgentDevicePolicy';
+import { WorkspaceAgentModelPolicy } from './WorkspaceAgentModelPolicy';
+import { WorkspaceAgentPolicyCard } from './WorkspaceAgentPolicyCard';
const styles = createStaticStyles(({ css }) => ({
configLabel: css`
@@ -28,12 +33,13 @@ const styles = createStaticStyles(({ css }) => ({
line-height: 1;
color: ${cssVar.colorTextTertiary};
`,
+ configStack: css`
+ container-type: inline-size;
+ `,
configPanel: css`
- padding-block: 12px;
- padding-inline: 14px;
+ padding: 16px;
border: 1px solid ${cssVar.colorBorderSecondary};
border-radius: ${cssVar.borderRadiusLG};
-
background: ${cssVar.colorFillQuaternary};
`,
topArea: css`
@@ -47,6 +53,7 @@ const ProfileEditor = memo(() => {
const { allowed: canEdit } = usePermission('edit_own_content');
const agentId = useAgentStore((s) => s.activeAgentId || '');
const config = useAgentStore(agentSelectors.getAgentConfigById(agentId), isEqual);
+ const isWorkspaceAgent = useAgentStore(agentByIdSelectors.isWorkspaceAgentById(agentId));
const updateAgentConfigById = useAgentStore((s) => s.updateAgentConfigById);
const isHeterogeneous = useAgentStore(agentSelectors.isCurrentAgentHeterogeneous);
const heterogeneousProvider = config.agencyConfig?.heterogeneousProvider;
@@ -73,7 +80,7 @@ const ProfileEditor = memo(() => {
const updateBoundDeviceId = async (boundDeviceId: string) => {
await updateAgentConfigById(agentId, {
- agencyConfig: { ...config.agencyConfig, boundDeviceId },
+ agencyConfig: { ...config.agencyConfig, boundDeviceId, executionTarget: 'device' },
});
};
@@ -122,23 +129,40 @@ const ProfileEditor = memo(() => {
>
{/* Header: Avatar + Name + Description */}
<AgentHeader />
- {isRemoteHetero && heterogeneousProvider ? (
- // Remote platform agents (openclaw / hermes): show device config panel
- <Flexbox paddingBlock={'8px 0'}>
+ <Flexbox
+ className={styles.configStack}
+ gap={8}
+ paddingBlock={isRemoteHetero ? '8px 0' : undefined}
+ >
+ {isRemoteHetero && heterogeneousProvider ? (
+ // Remote platform agents (openclaw / hermes): show device config panel
<RemoteAgentConfigCard
provider={heterogeneousProvider}
onBoundDeviceChange={updateBoundDeviceId}
/>
- </Flexbox>
- ) : isHeterogeneous && heterogeneousProvider ? (
- // Local CLI agents: Claude Code supports cloud config; Codex is desktop-only for now.
- <Tabs
- defaultActiveKey={isDesktop || !showCloudHeterogeneousTab ? 'desktop' : 'cloud'}
- items={heterogeneousTabItems}
- size="small"
- />
- ) : (
- <>
+ ) : isHeterogeneous && heterogeneousProvider ? (
+ // Local CLI agents: Claude Code supports cloud config; Codex is desktop-only for now.
+ <Tabs
+ defaultActiveKey={isDesktop || !showCloudHeterogeneousTab ? 'desktop' : 'cloud'}
+ items={heterogeneousTabItems}
+ size="small"
+ />
+ ) : isWorkspaceAgent ? (
+ <>
+ <Flexbox horizontal gap={8} wrap={'wrap'}>
+ <WorkspaceAgentModelPolicy agentId={agentId} />
+ <WorkspaceAgentDevicePolicy agentId={agentId} />
+ </Flexbox>
+ <WorkspaceAgentPolicyCard
+ fullWidth
+ action={<RunPriorityHint agentId={agentId} />}
+ icon={Wrench}
+ title={t('settingAgent.toolsConfig.title')}
+ >
+ <AgentTool />
+ </WorkspaceAgentPolicyCard>
+ </>
+ ) : (
<Flexbox className={styles.configPanel} gap={10}>
<Flexbox horizontal align={'center'} gap={12} justify={'space-between'}>
<div className={styles.configLabel}>{t('settingAgent.runtimeConfig.title')}</div>
@@ -156,14 +180,17 @@ const ProfileEditor = memo(() => {
onChange={(value) => {
if (!canEdit) return;
- updateAgentConfigById(agentId, value);
+ void updateAgentConfigById(agentId, value);
}}
/>
</Flexbox>
<AgentTool />
</Flexbox>
- </>
- )}
+ )}
+ {isHeterogeneous ? (
+ <WorkspaceAgentDevicePolicy agentId={agentId} showDevicePicker={!isRemoteHetero} />
+ ) : null}
+ </Flexbox>
</Flexbox>
{/* Main Content: Prompt Editor — built-in model runtime only. Hetero agents
(Claude Code / Codex + remote platforms) run an external CLI with its own
diff --git a/src/routes/(main)/agent/profile/index.tsx b/src/routes/(main)/agent/profile/index.tsx
index 8b5a501eea0..b8e9dc1521e 100644
--- a/src/routes/(main)/agent/profile/index.tsx
+++ b/src/routes/(main)/agent/profile/index.tsx
@@ -3,10 +3,12 @@
import { Flexbox } from '@lobehub/ui';
import { type FC } from 'react';
import { memo, Suspense } from 'react';
+import { useParams } from 'react-router';
import AsyncBoundary from '@/components/AsyncBoundary';
import Loading from '@/components/Loading/BrandTextLoading';
import AgentBuilder from '@/features/AgentBuilder';
+import ResourceConfigAccessGate from '@/features/ResourcePermission/ResourceConfigAccessGate';
import WideScreenContainer from '@/features/WideScreenContainer';
import { usePermission } from '@/hooks/usePermission';
import { useAgentStore } from '@/store/agent';
@@ -103,14 +105,22 @@ const AgentBuilderSlot = memo(() => {
});
const AgentProfile: FC = () => {
+ const { aid } = useParams<{ aid: string }>();
+
return (
<Suspense fallback={<Loading debugId="AgentProfile" />}>
- <ProfileProvider>
- <Flexbox horizontal height={'100%'} width={'100%'}>
- <ProfileArea />
- <AgentBuilderSlot />
- </Flexbox>
- </ProfileProvider>
+ <ResourceConfigAccessGate
+ redirectPath={`/agent/${aid ?? ''}`}
+ resourceId={aid}
+ resourceType="agent"
+ >
+ <ProfileProvider>
+ <Flexbox horizontal height={'100%'} width={'100%'}>
+ <ProfileArea />
+ <AgentBuilderSlot />
+ </Flexbox>
+ </ProfileProvider>
+ </ResourceConfigAccessGate>
</Suspense>
);
};
diff --git a/src/routes/(main)/group/_layout/Sidebar/GroupConfig/GroupMember.tsx b/src/routes/(main)/group/_layout/Sidebar/GroupConfig/GroupMember.tsx
index b8760db9444..2fbdca7a637 100644
--- a/src/routes/(main)/group/_layout/Sidebar/GroupConfig/GroupMember.tsx
+++ b/src/routes/(main)/group/_layout/Sidebar/GroupConfig/GroupMember.tsx
@@ -10,13 +10,12 @@ import { useLocation } from 'react-router';
import { DEFAULT_AVATAR } from '@/const/meta';
import AgentProfilePopup from '@/features/AgentProfileCard/AgentProfilePopup';
import NavItem from '@/features/NavPanel/components/NavItem';
+import { useResourceAccess } from '@/features/ResourcePermission/useResourceAccess';
import UserAvatar from '@/features/User/UserAvatar';
import { usePermission } from '@/hooks/usePermission';
import { useQueryRoute } from '@/hooks/useQueryRoute';
import { useAgentGroupStore } from '@/store/agentGroup';
import { agentGroupSelectors } from '@/store/agentGroup/selectors';
-import { useChatStore } from '@/store/chat';
-import { PortalViewType } from '@/store/chat/slices/portal/initialState';
import { useUserStore } from '@/store/user';
import { userProfileSelectors } from '@/store/user/slices/auth/selectors';
@@ -46,7 +45,9 @@ interface GroupMemberProps {
*/
const GroupMember = memo<GroupMemberProps>(({ addModalOpen, onAddModalOpenChange, groupId }) => {
const { t } = useTranslation('chat');
- const { allowed: canEdit, reason } = usePermission('edit_own_content');
+ const { allowed: hasEditPermission, reason } = usePermission('edit_own_content');
+ const { canEditResource } = useResourceAccess('agentGroup', groupId);
+ const canEdit = hasEditPermission && canEditResource;
const router = useQueryRoute();
const location = useLocation();
const [nickname, username] = useUserStore((s) => [
@@ -55,8 +56,6 @@ const GroupMember = memo<GroupMemberProps>(({ addModalOpen, onAddModalOpenChange
]);
const addAgentsToGroup = useAgentGroupStore((s) => s.addAgentsToGroup);
const removeAgentFromGroup = useAgentGroupStore((s) => s.removeAgentFromGroup);
- const toggleThread = useAgentGroupStore((s) => s.toggleThread);
- const pushPortalView = useChatStore((s) => s.pushPortalView);
const groupMembers = useAgentGroupStore(agentGroupSelectors.getGroupMembers(groupId || ''));
@@ -101,13 +100,8 @@ const GroupMember = memo<GroupMemberProps>(({ addModalOpen, onAddModalOpenChange
await withRemovingFlag(memberId, () => removeAgentFromGroup(groupId, memberId));
};
- const handleMemberClick = (agentId: string) => {
- toggleThread(agentId);
- pushPortalView({ agentId, type: PortalViewType.GroupThread });
- };
-
const handleMemberDoubleClick = (agentId: string) => {
- if (!groupId) return;
+ if (!groupId || !canEdit) return;
router.push(`/group/${groupId}/profile`, { query: { tab: agentId }, replace: true });
};
diff --git a/src/routes/(main)/group/_layout/Sidebar/Header/Nav.tsx b/src/routes/(main)/group/_layout/Sidebar/Header/Nav.tsx
index efa05e8f98d..f4c7ccadfb9 100644
--- a/src/routes/(main)/group/_layout/Sidebar/Header/Nav.tsx
+++ b/src/routes/(main)/group/_layout/Sidebar/Header/Nav.tsx
@@ -9,6 +9,8 @@ import { useParams } from 'react-router';
import urlJoin from 'url-join';
import NavItem from '@/features/NavPanel/components/NavItem';
+import { useResourceAccess } from '@/features/ResourcePermission/useResourceAccess';
+import { usePermission } from '@/hooks/usePermission';
import { useQueryRoute } from '@/hooks/useQueryRoute';
import { usePathname } from '@/libs/router/navigation';
import { useAgentGroupStore } from '@/store/agentGroup';
@@ -25,6 +27,8 @@ const Nav = memo(() => {
const isProfileActive = pathname.includes('/profile');
const router = useQueryRoute();
const { isAgentEditable } = useServerConfigStore(featureFlagsSelectors);
+ const { allowed: canEditContent } = usePermission('edit_own_content');
+ const { canEditResource, isAccessResolved } = useResourceAccess('agentGroup', groupId);
const toggleCommandMenu = useGlobalStore((s) => s.toggleCommandMenu);
const switchTopic = useChatStore((s) => s.switchTopic);
const switchToNewTopic = useAgentGroupStore((s) => s.switchToNewTopic);
@@ -36,7 +40,7 @@ const Nav = memo(() => {
title={tTopic('actions.addNewTopic')}
onClick={switchToNewTopic}
/>
- {isAgentEditable && (
+ {isAgentEditable && isAccessResolved && canEditContent && canEditResource && (
<NavItem
active={isProfileActive}
icon={BotPromptIcon}
diff --git a/src/routes/(main)/group/_layout/Sidebar/Members/index.tsx b/src/routes/(main)/group/_layout/Sidebar/Members/index.tsx
index 244a9653554..5686470de36 100644
--- a/src/routes/(main)/group/_layout/Sidebar/Members/index.tsx
+++ b/src/routes/(main)/group/_layout/Sidebar/Members/index.tsx
@@ -6,6 +6,7 @@ import { type MouseEvent } from 'react';
import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import { useResourceAccess } from '@/features/ResourcePermission/useResourceAccess';
import { useInitGroupConfig } from '@/hooks/useInitGroupConfig';
import { usePermission } from '@/hooks/usePermission';
import { useAgentGroupStore } from '@/store/agentGroup';
@@ -20,11 +21,13 @@ interface MembersProps {
const Members = memo<MembersProps>(({ itemKey }) => {
const { t } = useTranslation('chat');
- const { allowed: canEdit, reason } = usePermission('edit_own_content');
+ const { allowed: hasEditPermission, reason } = usePermission('edit_own_content');
const [addModalOpen, setAddModalOpen] = useState(false);
const [sortModalOpen, setSortModalOpen] = useState(false);
const activeGroupId = useAgentGroupStore(agentGroupSelectors.activeGroupId);
+ const { canEditResource } = useResourceAccess('agentGroup', activeGroupId);
+ const canEdit = hasEditPermission && canEditResource;
const membersCount = useAgentGroupStore(
agentGroupSelectors.getGroupAgentCount(activeGroupId || ''),
);
diff --git a/src/routes/(main)/group/features/Conversation/AgentWelcome/OpeningQuestions.tsx b/src/routes/(main)/group/features/Conversation/AgentWelcome/OpeningQuestions.tsx
index 14861d38592..1844ac67ee1 100644
--- a/src/routes/(main)/group/features/Conversation/AgentWelcome/OpeningQuestions.tsx
+++ b/src/routes/(main)/group/features/Conversation/AgentWelcome/OpeningQuestions.tsx
@@ -1,11 +1,14 @@
'use client';
-import { Block, Flexbox } from '@lobehub/ui';
-import { createStaticStyles, responsive } from 'antd-style';
+import { Block, Flexbox, Tooltip } from '@lobehub/ui';
+import { createStaticStyles, cx, responsive } from 'antd-style';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import { useConversationStore } from '@/features/Conversation';
+import { useResourceAccess } from '@/features/ResourcePermission/useResourceAccess';
+import { useAgentGroupStore } from '@/store/agentGroup';
+import { agentGroupSelectors } from '@/store/agentGroup/selectors';
const styles = createStaticStyles(({ css, cssVar }) => ({
card: css`
@@ -19,6 +22,11 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
}
`,
+ cardDisabled: css`
+ cursor: not-allowed;
+ opacity: 0.55;
+ `,
+
container: css`
padding-block: 0;
padding-inline: 0;
@@ -35,29 +43,50 @@ interface OpeningQuestionsProps {
}
const OpeningQuestions = memo<OpeningQuestionsProps>(({ mobile, questions }) => {
- const { t } = useTranslation('welcome');
+ const { t } = useTranslation(['welcome', 'chat']);
const [sendMessage] = useConversationStore((s) => [s.sendMessage]);
+ // Same per-resource General-access gating as the chat input (see
+ // useChatInputResourceAccess): private groups are never gated.
+ const activeGroup = useAgentGroupStore((s) =>
+ s.activeGroupId ? agentGroupSelectors.getGroupById(s.activeGroupId)(s) : undefined,
+ );
+ const gatedResourceId =
+ activeGroup && activeGroup.visibility !== 'private' ? activeGroup.id : undefined;
+ const { canUseResource } = useResourceAccess('agentGroup', gatedResourceId);
+
return (
<div className={styles.container}>
<p className={styles.title}>{t('guide.questions.title')}</p>
<Flexbox horizontal gap={8} wrap={'wrap'}>
{questions.slice(0, mobile ? 2 : 5).map((question) => {
- return (
+ const card = (
<Block
- clickable
- className={styles.card}
+ className={cx(styles.card, !canUseResource && styles.cardDisabled)}
+ clickable={canUseResource}
key={question}
paddingBlock={8}
paddingInline={12}
variant={'filled'}
- onClick={() => {
- sendMessage({ message: question });
- }}
+ onClick={
+ canUseResource
+ ? () => {
+ sendMessage({ message: question });
+ }
+ : undefined
+ }
>
{question}
</Block>
);
+
+ return canUseResource ? (
+ card
+ ) : (
+ <Tooltip key={question} title={t('input.viewOnlyGroup', { ns: 'chat' })}>
+ {card}
+ </Tooltip>
+ );
})}
</Flexbox>
</div>
diff --git a/src/routes/(main)/group/features/Conversation/MainChatInput/MessageFromUrl.tsx b/src/routes/(main)/group/features/Conversation/MainChatInput/MessageFromUrl.tsx
index eda56e5ea90..d23e825d964 100644
--- a/src/routes/(main)/group/features/Conversation/MainChatInput/MessageFromUrl.tsx
+++ b/src/routes/(main)/group/features/Conversation/MainChatInput/MessageFromUrl.tsx
@@ -4,6 +4,8 @@ import { useEffect, useRef } from 'react';
import { useSearchParams } from 'react-router';
import { useConversationStore } from '@/features/Conversation';
+import { useConversationResourceAccess } from '@/features/Conversation/hooks/useConversationResourceAccess';
+import { usePermission } from '@/hooks/usePermission';
/**
* MessageFromUrl
@@ -14,6 +16,11 @@ import { useConversationStore } from '@/features/Conversation';
const MessageFromUrl = () => {
const [sendMessage, agentId] = useConversationStore((s) => [s.sendMessage, s.context.agentId]);
const [searchParams, setSearchParams] = useSearchParams();
+ const { allowed: canCreate } = usePermission('create_content');
+ // Per-resource General access: view-only members must not auto-send into a
+ // shared group, whatever the URL says. Wait for the settled value — the
+ // permissive loading default would otherwise let the send race through.
+ const { canUseResource, isAccessLoading } = useConversationResourceAccess();
// Track if we've processed the initial message to prevent duplicate sends
const hasProcessedRef = useRef(false);
@@ -28,6 +35,9 @@ const MessageFromUrl = () => {
// Wait for agentId to be available before sending
if (!agentId) return;
+ if (!canCreate) return;
+ if (isAccessLoading) return;
+
hasProcessedRef.current = true;
// Use functional update to safely remove message param without affecting other params
@@ -40,9 +50,20 @@ const MessageFromUrl = () => {
{ replace: true },
);
+ // View-only: consume the param (so it doesn't linger in the URL) but never send.
+ if (!canUseResource) return;
+
// Send the message
sendMessage({ message });
- }, [searchParams, setSearchParams, sendMessage, agentId]);
+ }, [
+ searchParams,
+ setSearchParams,
+ sendMessage,
+ agentId,
+ canCreate,
+ canUseResource,
+ isAccessLoading,
+ ]);
return null;
};
diff --git a/src/routes/(main)/group/profile/features/GroupProfile/index.tsx b/src/routes/(main)/group/profile/features/GroupProfile/index.tsx
index a1f6c7b9281..41034053848 100644
--- a/src/routes/(main)/group/profile/features/GroupProfile/index.tsx
+++ b/src/routes/(main)/group/profile/features/GroupProfile/index.tsx
@@ -11,8 +11,12 @@ import { useParams } from 'react-router';
import urlJoin from 'url-join';
import { useAgentGroupTransferMenuItem } from '@/business/client/hooks/useAgentGroupTransferMenuItem';
+import { useHasActiveWorkspace } from '@/business/client/hooks/useHasActiveWorkspace';
import { EditingIndicator, type EditLockClient, useEditLock } from '@/features/EditLock';
import { EditorCanvas } from '@/features/EditorCanvas';
+import AccessLevelTag from '@/features/ResourcePermission/AccessLevelTag';
+import { useResourceAccess } from '@/features/ResourcePermission/useResourceAccess';
+import { useResourcePermissionMenuItem } from '@/features/ResourcePermission/useResourcePermissionMenuItem';
import { usePermission } from '@/hooks/usePermission';
import { useQueryRoute } from '@/hooks/useQueryRoute';
import { lambdaClient } from '@/libs/trpc/client';
@@ -38,14 +42,42 @@ const groupLockClient: EditLockClient = {
const GroupProfile = memo(() => {
const { t } = useTranslation(['setting', 'chat']);
- const { allowed: canEdit } = usePermission('edit_own_content');
+ const { allowed: hasEditPermission } = usePermission('edit_own_content');
const theme = useTheme();
const { gid } = useParams<{ gid: string }>();
const groupId = useAgentGroupStore(agentGroupSelectors.activeGroupId);
+ const hasActiveWorkspace = useHasActiveWorkspace();
const currentGroup = useAgentGroupStore((s) => agentGroupSelectors.getGroupById(gid ?? '')(s));
const updateGroup = useAgentGroupStore((s) => s.updateGroup);
const router = useQueryRoute();
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).
+ const { canEditResource } = useResourceAccess(
+ 'agentGroup',
+ currentGroup?.visibility === 'private' ? undefined : (groupId ?? undefined),
+ );
+ 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],
+ );
const settingsModalRef = useRef<ModalInstance | null>(null);
useEffect(
@@ -136,6 +168,14 @@ const GroupProfile = memo(() => {
<GroupStatusTag />
<GroupVersionReviewTag />
<GroupForkTag />
+ <AccessLevelTag
+ resourceType={'agentGroup'}
+ resourceId={
+ hasActiveWorkspace && currentGroup?.visibility !== 'private'
+ ? (groupId ?? undefined)
+ : undefined
+ }
+ />
</Flexbox>
</Flexbox>
{/* Header: Group Avatar + Title */}
@@ -158,8 +198,8 @@ const GroupProfile = memo(() => {
>
{t('startConversation')}
</Button>
- {!!transferMenuItems?.length && (
- <DropdownMenu items={transferMenuItems}>
+ {moreMenuItems.length > 0 && (
+ <DropdownMenu items={moreMenuItems}>
<ActionIcon
icon={MoreHorizontalIcon}
size={'small'}
diff --git a/src/routes/(main)/group/profile/index.tsx b/src/routes/(main)/group/profile/index.tsx
index 0befb1e374a..eb4fdd871c5 100644
--- a/src/routes/(main)/group/profile/index.tsx
+++ b/src/routes/(main)/group/profile/index.tsx
@@ -3,8 +3,10 @@
import { Flexbox } from '@lobehub/ui';
import { type FC } from 'react';
import { memo, Suspense } from 'react';
+import { useParams } from 'react-router';
import Loading from '@/components/Loading/BrandTextLoading';
+import ResourceConfigAccessGate from '@/features/ResourcePermission/ResourceConfigAccessGate';
import WideScreenContainer from '@/features/WideScreenContainer';
import { useAgentGroupStore } from '@/store/agentGroup';
import { agentGroupSelectors } from '@/store/agentGroup/selectors';
@@ -50,13 +52,21 @@ const ProfileArea = memo(() => {
});
const GroupProfile: FC = () => {
+ const { gid } = useParams<{ gid: string }>();
+
return (
<Suspense fallback={<Loading debugId="GroupProfile" />}>
- <StoreSync />
- <Flexbox horizontal height={'100%'} width={'100%'}>
- <ProfileArea />
- <AgentBuilder />
- </Flexbox>
+ <ResourceConfigAccessGate
+ redirectPath={`/group/${gid ?? ''}`}
+ resourceId={gid}
+ resourceType="agentGroup"
+ >
+ <StoreSync />
+ <Flexbox horizontal height={'100%'} width={'100%'}>
+ <ProfileArea />
+ <AgentBuilder />
+ </Flexbox>
+ </ResourceConfigAccessGate>
</Suspense>
);
};
diff --git a/src/routes/(main)/home/_layout/Body/Agent/List/AgentGroupItem/index.tsx b/src/routes/(main)/home/_layout/Body/Agent/List/AgentGroupItem/index.tsx
index 35f074ef06c..a6c673435ef 100644
--- a/src/routes/(main)/home/_layout/Body/Agent/List/AgentGroupItem/index.tsx
+++ b/src/routes/(main)/home/_layout/Body/Agent/List/AgentGroupItem/index.tsx
@@ -24,7 +24,7 @@ interface GroupItemProps {
}
const GroupItem = memo<GroupItemProps>(({ item, style, className, onNavigate }) => {
- const { id, avatar, backgroundColor, description, title, pinned } = item;
+ const { id, avatar, backgroundColor, description, title, pinned, userId } = item;
const { t } = useTranslation('chat');
const [anchor, setAnchor] = useState<HTMLElement | null>(null);
@@ -113,6 +113,7 @@ const GroupItem = memo<GroupItemProps>(({ item, style, className, onNavigate })
memberAvatars,
pinned: pinned ?? false,
title: displayTitle,
+ userId,
});
return (
diff --git a/src/routes/(main)/home/_layout/Body/Agent/List/AgentGroupItem/useDropdownMenu.tsx b/src/routes/(main)/home/_layout/Body/Agent/List/AgentGroupItem/useDropdownMenu.tsx
index 707df9297df..d175bc63590 100644
--- a/src/routes/(main)/home/_layout/Body/Agent/List/AgentGroupItem/useDropdownMenu.tsx
+++ b/src/routes/(main)/home/_layout/Body/Agent/List/AgentGroupItem/useDropdownMenu.tsx
@@ -8,10 +8,12 @@ import { useTranslation } from 'react-i18next';
import { useAgentGroupTransferMenuItem } from '@/business/client/hooks/useAgentGroupTransferMenuItem';
import { openEditingPopover } from '@/features/EditingPopover/store';
+import { useResourceAccess } from '@/features/ResourcePermission/useResourceAccess';
import { usePermission } from '@/hooks/usePermission';
+import { useResourceManageable } from '@/hooks/useResourceManageable';
import { useGlobalStore } from '@/store/global';
import { useHomeStore } from '@/store/home';
-import { isForbiddenError } from '@/utils/forbiddenError';
+import { isForbiddenError, isOwnerOnlyForbiddenError } from '@/utils/forbiddenError';
interface UseGroupDropdownMenuParams {
anchor: HTMLElement | null;
@@ -22,6 +24,7 @@ interface UseGroupDropdownMenuParams {
memberAvatars?: { avatar?: string; background?: string }[];
pinned: boolean;
title: string;
+ userId?: string | null;
}
export const useGroupDropdownMenu = ({
@@ -33,10 +36,14 @@ export const useGroupDropdownMenu = ({
memberAvatars,
pinned,
title,
+ userId,
}: UseGroupDropdownMenuParams): (() => MenuProps['items']) => {
const { t } = useTranslation(['chat', 'common']);
const { message } = App.useApp();
const { allowed: canEdit } = usePermission('edit_own_content');
+ const { canEditResource, isAccessResolved } = useResourceAccess('agentGroup', id);
+ const canConfigure = canEdit && isAccessResolved && canEditResource;
+ const canManage = useResourceManageable(userId);
const openAgentInNewWindow = useGlobalStore((s) => s.openAgentInNewWindow);
const [pinAgentGroup, duplicateAgentGroup, removeAgentGroup] = useHomeStore((s) => [
@@ -55,51 +62,44 @@ export const useGroupDropdownMenu = ({
return useMemo(
() => () =>
[
- {
- disabled: !canEdit,
- icon: <Icon icon={pinned ? PinOff : Pin} />,
- key: 'pin',
- label: t(pinned ? 'pinOff' : 'pin'),
- onClick: () => {
- if (!canEdit) return;
-
- pinAgentGroup(id, !pinned);
- },
- },
- {
- disabled: !canEdit,
- icon: <Icon icon={Pen} />,
- key: 'rename',
- label: t('rename', { ns: 'common' }),
- onClick: (info: any) => {
- info.domEvent?.stopPropagation();
- if (!canEdit) return;
-
- if (anchor) {
- openEditingPopover({
- anchor,
- avatar,
- backgroundColor,
- id,
- memberAvatars,
- title,
- type: 'agentGroup',
- });
- }
- },
- },
- {
- disabled: !canEdit,
- icon: <Icon icon={LucideCopy} />,
- key: 'duplicate',
- label: t('duplicate', { ns: 'common' }),
- onClick: ({ domEvent }: any) => {
- domEvent.stopPropagation();
- if (!canEdit) return;
-
- duplicateAgentGroup(id);
- },
- },
+ ...(canConfigure
+ ? [
+ {
+ icon: <Icon icon={pinned ? PinOff : Pin} />,
+ key: 'pin',
+ label: t(pinned ? 'pinOff' : 'pin'),
+ onClick: () => pinAgentGroup(id, !pinned),
+ },
+ {
+ icon: <Icon icon={Pen} />,
+ key: 'rename',
+ label: t('rename', { ns: 'common' }),
+ onClick: (info: any) => {
+ info.domEvent?.stopPropagation();
+ if (anchor) {
+ openEditingPopover({
+ anchor,
+ avatar,
+ backgroundColor,
+ id,
+ memberAvatars,
+ title,
+ type: 'agentGroup',
+ });
+ }
+ },
+ },
+ {
+ icon: <Icon icon={LucideCopy} />,
+ key: 'duplicate',
+ label: t('duplicate', { ns: 'common' }),
+ onClick: ({ domEvent }: any) => {
+ domEvent.stopPropagation();
+ duplicateAgentGroup(id);
+ },
+ },
+ ]
+ : []),
{
icon: <Icon icon={PictureInPicture2Icon} />,
key: 'openInNewWindow',
@@ -109,46 +109,51 @@ export const useGroupDropdownMenu = ({
openAgentInNewWindow(id);
},
},
- { type: 'divider' },
- ...(transferMenuItems ?? []),
- ...(transferMenuItems?.length ? [{ type: 'divider' as const }] : []),
- {
- danger: true,
- disabled: !canEdit,
- icon: <Icon icon={Trash} />,
- key: 'delete',
- label: t('delete', { ns: 'common' }),
- onClick: ({ domEvent }: any) => {
- domEvent.stopPropagation();
- if (!canEdit) return;
-
- confirmModal({
- cancelText: t('cancel', { ns: 'common' }),
- content: t('confirmRemoveChatGroupItemAlert'),
- okButtonProps: { danger: true },
- okText: t('delete', { ns: 'common' }),
- onOk: async () => {
- try {
- await removeAgentGroup(id);
- message.success(t('confirmRemoveGroupSuccess'));
- } catch (error) {
- message.error(
- isForbiddenError(error)
- ? t('manageOnlyCreator', { ns: 'common' })
- : t('operationFailed', { ns: 'common' }),
- );
- }
+ ...(canConfigure && transferMenuItems?.length
+ ? [{ type: 'divider' as const }, ...transferMenuItems]
+ : []),
+ ...(canConfigure && canManage
+ ? [
+ { type: 'divider' as const },
+ {
+ danger: true,
+ icon: <Icon icon={Trash} />,
+ key: 'delete',
+ label: t('delete', { ns: 'common' }),
+ onClick: ({ domEvent }: any) => {
+ domEvent.stopPropagation();
+ confirmModal({
+ cancelText: t('cancel', { ns: 'common' }),
+ content: t('confirmRemoveChatGroupItemAlert'),
+ okButtonProps: { danger: true },
+ okText: t('delete', { ns: 'common' }),
+ onOk: async () => {
+ try {
+ await removeAgentGroup(id);
+ message.success(t('confirmRemoveGroupSuccess'));
+ } catch (error) {
+ message.error(
+ isOwnerOnlyForbiddenError(error)
+ ? t('deleteSharedOwnerOnly', { ns: 'common' })
+ : isForbiddenError(error)
+ ? t('manageOnlyCreator', { ns: 'common' })
+ : t('operationFailed', { ns: 'common' }),
+ );
+ }
+ },
+ title: t('delete', { ns: 'common' }),
+ });
+ },
},
- title: t('delete', { ns: 'common' }),
- });
- },
- },
+ ]
+ : []),
] as MenuProps['items'],
[
anchor,
avatar,
backgroundColor,
- canEdit,
+ canConfigure,
+ canManage,
memberAvatars,
t,
pinned,
diff --git a/src/routes/(main)/home/_layout/Body/Agent/List/AgentItem/agentMenuVisibility.test.ts b/src/routes/(main)/home/_layout/Body/Agent/List/AgentItem/agentMenuVisibility.test.ts
index 667e31e481f..3d1be6383ac 100644
--- a/src/routes/(main)/home/_layout/Body/Agent/List/AgentItem/agentMenuVisibility.test.ts
+++ b/src/routes/(main)/home/_layout/Body/Agent/List/AgentItem/agentMenuVisibility.test.ts
@@ -2,7 +2,22 @@
import { describe, expect, it } from 'vitest';
-import { shouldShowAgentDeleteMenuItem } from './agentMenuVisibility';
+import { getAgentPublishErrorKey, shouldShowAgentDeleteMenuItem } from './agentMenuVisibility';
+
+describe('getAgentPublishErrorKey', () => {
+ it('maps the fixed private-device precondition to actionable publish copy', () => {
+ expect(
+ getAgentPublishErrorKey({
+ data: { errorData: { code: 'FixedAgentRequiresPublicWorkspaceDevice' } },
+ }),
+ ).toBe('agent.publishToWorkspaceErrorFixedPrivateDevice');
+ });
+
+ it('keeps unrelated publish failures on the generic fallback', () => {
+ expect(getAgentPublishErrorKey({ data: { code: 'FORBIDDEN' } })).toBeUndefined();
+ expect(getAgentPublishErrorKey(new Error('network failure'))).toBeUndefined();
+ });
+});
describe('shouldShowAgentDeleteMenuItem', () => {
it('shows Delete only when the agent can be edited and managed', () => {
diff --git a/src/routes/(main)/home/_layout/Body/Agent/List/AgentItem/agentMenuVisibility.ts b/src/routes/(main)/home/_layout/Body/Agent/List/AgentItem/agentMenuVisibility.ts
index ad52f9c4ddf..14ad2a52f18 100644
--- a/src/routes/(main)/home/_layout/Body/Agent/List/AgentItem/agentMenuVisibility.ts
+++ b/src/routes/(main)/home/_layout/Body/Agent/List/AgentItem/agentMenuVisibility.ts
@@ -3,5 +3,16 @@ interface AgentDeleteMenuVisibility {
canManage: boolean;
}
+export type AgentPublishErrorKey = 'agent.publishToWorkspaceErrorFixedPrivateDevice';
+
+export const getAgentPublishErrorKey = (error: unknown): AgentPublishErrorKey | undefined => {
+ if (typeof error !== 'object' || error === null) return;
+
+ const data = (error as { data?: { errorData?: { code?: unknown } } }).data;
+ if (data?.errorData?.code === 'FixedAgentRequiresPublicWorkspaceDevice') {
+ return 'agent.publishToWorkspaceErrorFixedPrivateDevice';
+ }
+};
+
export const shouldShowAgentDeleteMenuItem = ({ canEdit, canManage }: AgentDeleteMenuVisibility) =>
canEdit && canManage;
diff --git a/src/routes/(main)/home/_layout/Body/Agent/List/AgentItem/useDropdownMenu.tsx b/src/routes/(main)/home/_layout/Body/Agent/List/AgentItem/useDropdownMenu.tsx
index 7883cfbdc48..5f3424eceb1 100644
--- a/src/routes/(main)/home/_layout/Body/Agent/List/AgentItem/useDropdownMenu.tsx
+++ b/src/routes/(main)/home/_layout/Body/Agent/List/AgentItem/useDropdownMenu.tsx
@@ -24,6 +24,7 @@ import { useTranslation } from 'react-i18next';
import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
import { useAgentTransferMenuItem } from '@/business/client/hooks/useAgentTransferMenuItem';
import { openEditingPopover } from '@/features/EditingPopover/store';
+import { useResourceAccess } from '@/features/ResourcePermission/useResourceAccess';
import VisibilityConfirmContent from '@/features/VisibilityConfirmContent';
import { usePermission } from '@/hooks/usePermission';
import { useResourceManageable } from '@/hooks/useResourceManageable';
@@ -33,10 +34,10 @@ import { useHomeStore } from '@/store/home';
import { homeAgentListSelectors } from '@/store/home/selectors';
import { useUserStore } from '@/store/user';
import { userProfileSelectors } from '@/store/user/selectors';
-import { isForbiddenError } from '@/utils/forbiddenError';
+import { isForbiddenError, isOwnerOnlyForbiddenError } from '@/utils/forbiddenError';
import { useRevealSidebarSection } from '../../../../hooks';
-import { shouldShowAgentDeleteMenuItem } from './agentMenuVisibility';
+import { getAgentPublishErrorKey } from './agentMenuVisibility';
const BUILTIN_SLUGS = new Set<string>(Object.values(BUILTIN_AGENT_SLUGS));
@@ -108,18 +109,16 @@ export const useAgentDropdownMenu = ({
!!currentUserId &&
userId === currentUserId;
- // Viewer has no write permissions on agents — disable non-destructive
- // mutating items while keeping the menu visible so they can still inspect
- // what actions exist. Delete is hidden entirely when unavailable.
- // `openInNewWindow` is a pure read so it stays enabled.
+ // Chat-only resource access hides configuration mutations entirely. The
+ // pure navigation action remains available to Can use members and viewers.
const { allowed: canEdit } = usePermission('edit_own_content');
const { allowed: canCreate } = usePermission('create_content');
+ const { canEditResource, isAccessResolved } = useResourceAccess('agent', id);
+ const canConfigure = canEdit && isAccessResolved && canEditResource;
- // Row-level ownership: in workspace mode only the creator or a workspace
- // owner may rename or delete a shared agent — mirrors the server-side
- // enforcement.
+ // Row-level ownership: delete/transfer/visibility management stays scoped
+ // to the creator or a workspace owner, separate from collaborative editing.
const canManage = useResourceManageable(userId);
- const showDeleteAction = shouldShowAgentDeleteMenuItem({ canEdit, canManage });
// Cross-workspace Transfer to… / Copy to… items (null when workspace
// feature is off or the viewer lacks permission for this agent)
@@ -144,38 +143,40 @@ export const useAgentDropdownMenu = ({
return useMemo(
() => () =>
[
- {
- disabled: !canEdit,
- icon: <Icon icon={pinned ? PinOff : Pin} />,
- key: 'pin',
- label: t(pinned ? 'pinOff' : 'pin'),
- onClick: () => pinAgent(id, !pinned),
- },
- {
- // Renaming is config co-editing, which stays collaborative for
- // shared agents — only delete below is creator/owner-scoped.
- disabled: !canEdit,
- icon: <Icon icon={Pen} />,
- key: 'rename',
- label: t('rename', { ns: 'common' }),
- onClick: (info: any) => {
- info.domEvent?.stopPropagation();
- if (!canEdit) return;
- if (anchor) {
- openEditingPopover({ anchor, avatar, id, title, type: 'agent' });
- }
- },
- },
- {
- disabled: !canCreate,
- icon: <Icon icon={LucideCopy} />,
- key: 'duplicate',
- label: t('duplicate', { ns: 'common' }),
- onClick: ({ domEvent }: any) => {
- domEvent.stopPropagation();
- duplicateAgent(id);
- },
- },
+ ...(canConfigure
+ ? [
+ {
+ icon: <Icon icon={pinned ? PinOff : Pin} />,
+ key: 'pin',
+ label: t(pinned ? 'pinOff' : 'pin'),
+ onClick: () => pinAgent(id, !pinned),
+ },
+ {
+ // Renaming is config co-editing, which stays collaborative for
+ // shared agents — only ownership actions remain creator/owner-scoped.
+ icon: <Icon icon={Pen} />,
+ key: 'rename',
+ label: t('rename', { ns: 'common' }),
+ onClick: (info: any) => {
+ info.domEvent?.stopPropagation();
+ if (anchor) {
+ openEditingPopover({ anchor, avatar, id, title, type: 'agent' });
+ }
+ },
+ },
+ {
+ disabled: !canCreate,
+ icon: <Icon icon={LucideCopy} />,
+ key: 'duplicate',
+ label: t('duplicate', { ns: 'common' }),
+ onClick: ({ domEvent }: any) => {
+ domEvent.stopPropagation();
+ if (!canCreate) return;
+ duplicateAgent(id);
+ },
+ },
+ ]
+ : []),
{
icon: <Icon icon={PictureInPicture2Icon} />,
key: 'openInNewWindow',
@@ -185,158 +186,182 @@ export const useAgentDropdownMenu = ({
openAgentInNewWindow(id);
},
},
- { type: 'divider' },
- {
- disabled: !canEdit,
- children: [
- ...sessionCustomGroups.map(({ id: groupId, name }) => ({
- icon: group === groupId ? <Icon icon={Check} /> : <div />,
- key: groupId,
- label: name,
- onClick: () => updateAgentGroup(id, groupId),
- })),
- {
- icon: isDefault ? <Icon icon={Check} /> : <div />,
- key: 'defaultList',
- label: t('defaultList'),
- onClick: () => updateAgentGroup(id, SessionDefaultGroup.Default),
- },
- { type: 'divider' as const },
- {
- icon: <Icon icon={LucidePlus} />,
- key: 'createGroup',
- label: <div>{t('sessionGroup.createGroup')}</div>,
- onClick: ({ domEvent }: any) => {
- domEvent.stopPropagation();
- openCreateGroupModal();
- },
- },
- ],
- icon: <Icon icon={FolderInputIcon} />,
- key: 'moveGroup',
- label: t('sessionGroup.moveGroup'),
- },
- ...(transferMenuItems?.length ? [{ type: 'divider' as const }, ...transferMenuItems] : []),
- ...(showPublishAction
+ ...(canConfigure
? [
{ type: 'divider' as const },
{
- disabled: !canEdit,
- icon: <Icon icon={GlobeIcon} />,
- key: 'publishToWorkspace',
- label: t('agent.publishToWorkspace', { defaultValue: 'Publish to Workspace' }),
- onClick: async ({ domEvent }: any) => {
- domEvent?.stopPropagation();
- if (!canEdit) return;
- confirmModal({
- cancelText: t('cancel', { ns: 'common' }),
- content: <VisibilityConfirmContent variant="publish" />,
- okText: t('agent.publishToWorkspace', {
- defaultValue: 'Publish to Workspace',
- }),
- onOk: async () => {
- try {
- await agentService.publishAgentToWorkspace(id);
- await refreshAgentList();
- revealSidebarSection('agent');
- message.success(
- t('agent.publishToWorkspaceSuccess', {
- defaultValue: 'Published to workspace',
- }),
- );
- } catch (error) {
- console.error('Failed to publish agent:', error);
- message.error(
- t('error', { ns: 'common', defaultValue: 'Operation failed' }),
- );
- }
+ children: [
+ ...sessionCustomGroups.map(({ id: groupId, name }) => ({
+ icon: group === groupId ? <Icon icon={Check} /> : <div />,
+ key: groupId,
+ label: name,
+ onClick: () => updateAgentGroup(id, groupId),
+ })),
+ {
+ icon: isDefault ? <Icon icon={Check} /> : <div />,
+ key: 'defaultList',
+ label: t('defaultList'),
+ onClick: () => updateAgentGroup(id, SessionDefaultGroup.Default),
+ },
+ { type: 'divider' as const },
+ {
+ icon: <Icon icon={LucidePlus} />,
+ key: 'createGroup',
+ label: <div>{t('sessionGroup.createGroup')}</div>,
+ onClick: ({ domEvent }: any) => {
+ domEvent.stopPropagation();
+ openCreateGroupModal();
},
- title: t('agent.publishToWorkspace', {
- defaultValue: 'Publish to Workspace',
- }),
- });
- },
+ },
+ ],
+ icon: <Icon icon={FolderInputIcon} />,
+ key: 'moveGroup',
+ label: t('sessionGroup.moveGroup'),
},
- ]
- : []),
- ...(showMakePrivateAction
- ? [
- { type: 'divider' as const },
- {
- disabled: !canEdit,
- icon: <Icon icon={EyeOffIcon} />,
- key: 'makePrivate',
- label: t('makePrivate', { ns: 'common' }),
- onClick: async ({ domEvent }: any) => {
- domEvent?.stopPropagation();
- if (!canEdit) return;
- confirmModal({
- cancelText: t('cancel', { ns: 'common' }),
- content: <VisibilityConfirmContent variant="makePrivate" />,
- okButtonProps: { danger: true },
- okText: t('makePrivate.confirm.ok', { ns: 'common' }),
- onOk: async () => {
- try {
- await agentService.setAgentVisibility(id, 'private');
- await refreshAgentList();
- revealSidebarSection('private');
- message.success(t('makePrivate.success', { ns: 'common' }));
- } catch (error) {
- console.error('Failed to make agent private:', error);
- message.error(t('makePrivate.error', { ns: 'common' }));
- }
+ ...(transferMenuItems?.length
+ ? [{ type: 'divider' as const }, ...transferMenuItems]
+ : []),
+ ...(showPublishAction
+ ? [
+ { type: 'divider' as const },
+ {
+ icon: <Icon icon={GlobeIcon} />,
+ key: 'publishToWorkspace',
+ label: t('agent.publishToWorkspace', {
+ defaultValue: 'Publish to Workspace',
+ }),
+ onClick: async ({ domEvent }: any) => {
+ domEvent?.stopPropagation();
+ const accessLevelRef: { current: 'edit' | 'use' } = { current: 'use' };
+ confirmModal({
+ cancelText: t('cancel', { ns: 'common' }),
+ content: (
+ <VisibilityConfirmContent
+ accessLevelRef={accessLevelRef}
+ resourceType="agent"
+ variant="publish"
+ />
+ ),
+ okText: t('agent.publishToWorkspace', {
+ defaultValue: 'Publish to Workspace',
+ }),
+ onOk: async () => {
+ try {
+ await agentService.publishAgentToWorkspace(
+ id,
+ accessLevelRef.current,
+ );
+ await refreshAgentList();
+ revealSidebarSection('agent');
+ message.success(
+ t('agent.publishToWorkspaceSuccess', {
+ defaultValue: 'Published to workspace',
+ }),
+ );
+ } catch (error) {
+ console.error('Failed to publish agent:', error);
+ const publishErrorKey = getAgentPublishErrorKey(error);
+ message.error(
+ publishErrorKey
+ ? t(publishErrorKey)
+ : t('error', {
+ ns: 'common',
+ defaultValue: 'Operation failed',
+ }),
+ );
+ }
+ },
+ title: t('agent.publishToWorkspace', {
+ defaultValue: 'Publish to Workspace',
+ }),
+ });
+ },
},
- title: t('makePrivate.confirm.title', { ns: 'common' }),
- });
- },
- },
- ]
- : []),
- ...(showDeleteAction
- ? [
- { type: 'divider' as const },
- {
- danger: true,
- icon: <Icon icon={Trash} />,
- key: 'delete',
- label: t('delete', { ns: 'common' }),
- onClick: ({ domEvent }: any) => {
- domEvent.stopPropagation();
- if (!canEdit || !canManage) return;
- confirmModal({
- cancelText: t('cancel', { ns: 'common' }),
- content: t('confirmRemoveSessionItemAlert'),
- okButtonProps: { danger: true },
- okText: t('delete', { ns: 'common' }),
- onOk: async () => {
- try {
- await removeAgent(id);
- message.success(t('confirmRemoveSessionSuccess'));
- } catch (error) {
- message.error(
- isForbiddenError(error)
- ? t('manageOnlyCreator', { ns: 'common' })
- : t('operationFailed', { ns: 'common' }),
- );
- }
+ ]
+ : []),
+ ...(showMakePrivateAction
+ ? [
+ { type: 'divider' as const },
+ {
+ icon: <Icon icon={EyeOffIcon} />,
+ key: 'makePrivate',
+ label: t('makePrivate', { ns: 'common' }),
+ onClick: async ({ domEvent }: any) => {
+ domEvent?.stopPropagation();
+ confirmModal({
+ cancelText: t('cancel', { ns: 'common' }),
+ content: <VisibilityConfirmContent variant="makePrivate" />,
+ okButtonProps: { danger: true },
+ okText: t('makePrivate.confirm.ok', { ns: 'common' }),
+ onOk: async () => {
+ try {
+ await agentService.setAgentVisibility(id, 'private');
+ await refreshAgentList();
+ revealSidebarSection('private');
+ message.success(t('makePrivate.success', { ns: 'common' }));
+ } catch (error) {
+ console.error('Failed to make agent private:', error);
+ message.error(t('makePrivate.error', { ns: 'common' }));
+ }
+ },
+ title: t('makePrivate.confirm.title', { ns: 'common' }),
+ });
+ },
},
- title: t('delete', { ns: 'common' }),
- });
- },
- },
+ ]
+ : []),
+ ...(canManage
+ ? [
+ { type: 'divider' as const },
+ {
+ danger: true,
+ icon: <Icon icon={Trash} />,
+ key: 'delete',
+ label: t('delete', { ns: 'common' }),
+ onClick: ({ domEvent }: any) => {
+ domEvent.stopPropagation();
+ confirmModal({
+ cancelText: t('cancel', { ns: 'common' }),
+ content: t('confirmRemoveSessionItemAlert'),
+ okButtonProps: { danger: true },
+ okText: t('delete', { ns: 'common' }),
+ onOk: async () => {
+ try {
+ await removeAgent(id);
+ message.success(t('confirmRemoveSessionSuccess'));
+ } catch (error) {
+ message.error(
+ isOwnerOnlyForbiddenError(error)
+ ? t('deleteSharedOwnerOnly', { ns: 'common' })
+ : isForbiddenError(error)
+ ? t('manageOnlyCreator', { ns: 'common' })
+ : t('operationFailed', { ns: 'common' }),
+ );
+ }
+ },
+ title: t('delete', { ns: 'common' }),
+ });
+ },
+ },
+ ]
+ : []),
]
: []),
] as MenuProps['items'],
[
anchor,
canCreate,
- canEdit,
+ canConfigure,
canManage,
pinned,
id,
avatar,
- backgroundColor,
title,
+ pinAgent,
+ duplicateAgent,
+ updateAgentGroup,
+ removeAgent,
+ openAgentInNewWindow,
sessionCustomGroups,
group,
isDefault,
@@ -345,7 +370,6 @@ export const useAgentDropdownMenu = ({
transferMenuItems,
showPublishAction,
showMakePrivateAction,
- showDeleteAction,
refreshAgentList,
revealSidebarSection,
t,
diff --git a/src/routes/(main)/home/features/InputArea/useSend.ts b/src/routes/(main)/home/features/InputArea/useSend.ts
index 157b98051c7..7d5072868b5 100644
--- a/src/routes/(main)/home/features/InputArea/useSend.ts
+++ b/src/routes/(main)/home/features/InputArea/useSend.ts
@@ -4,10 +4,12 @@ import { useCallback } from 'react';
import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';
import type { SendButtonHandler } from '@/features/ChatInput/store/initialState';
import { buildMessageContextSelections } from '@/features/ChatInput/utils/contextSelections';
+import { useResourceAccess } from '@/features/ResourcePermission/useResourceAccess';
import { useHomeDailyBrief } from '@/hooks/useHomeDailyBrief';
import { useQueryRoute } from '@/hooks/useQueryRoute';
import { agentService } from '@/services/agent';
import { useAgentStore } from '@/store/agent';
+import { builtinAgentSelectors } from '@/store/agent/selectors';
import { useChatStore } from '@/store/chat';
import { fileChatSelectors, useFileStore } from '@/store/file';
import { useHomeStore } from '@/store/home';
@@ -51,6 +53,19 @@ export const useSend = () => {
// on the same browser) back to inbox so we don't try to send to a missing id.
const { agentId: activeAgentId } = useResolvedHomeAgentId();
+ // Per-resource General access on the selected agent (same rules as the chat
+ // input: inbox and private agents are never gated) — a view-only shared
+ // agent picked from AgentSelect must not receive sends from home.
+ const inboxAgentId = useAgentStore(builtinAgentSelectors.inboxAgentId);
+ const agentVisibility = useAgentStore((s) =>
+ activeAgentId ? s.agentMap[activeAgentId]?.visibility : undefined,
+ );
+ const gatedResourceId =
+ activeAgentId && activeAgentId !== inboxAgentId && agentVisibility !== 'private'
+ ? activeAgentId
+ : undefined;
+ const { canUseResource } = useResourceAccess('agent', gatedResourceId);
+
// Daily-brief hint paired with the home WelcomeText. Pressing Enter on an
// empty input "accepts" the hint as the message — like a smart-compose
// suggestion — and rotates to the next pair.
@@ -92,6 +107,10 @@ export const useSend = () => {
// Require input content (except for default inbox which can have files/context)
if (!message && fileList.length === 0 && contextList.length === 0) return;
+ // View-only selected agent: bail before the try/finally so the composer
+ // content isn't wiped. Only the default branch targets activeAgentId.
+ if (!inputActiveMode && !canUseResource) return;
+
try {
const { contextSelections, pageSelections } = buildMessageContextSelections(contextList);
@@ -173,6 +192,7 @@ export const useSend = () => {
[
activeAgentId,
activeWorkspaceSlug,
+ canUseResource,
sendMessage,
clearChatContextSelections,
clearChatUploadFileList,
diff --git a/src/routes/(mobile)/(home)/features/SessionListContent/List/Item/Actions.tsx b/src/routes/(mobile)/(home)/features/SessionListContent/List/Item/Actions.tsx
index 163d84d7984..48ab3c0b9dd 100644
--- a/src/routes/(mobile)/(home)/features/SessionListContent/List/Item/Actions.tsx
+++ b/src/routes/(mobile)/(home)/features/SessionListContent/List/Item/Actions.tsx
@@ -25,7 +25,7 @@ import { useSessionStore } from '@/store/session';
import { sessionHelpers } from '@/store/session/helpers';
import { sessionGroupSelectors, sessionSelectors } from '@/store/session/selectors';
import { SessionDefaultGroup } from '@/types/index';
-import { isForbiddenError } from '@/utils/forbiddenError';
+import { isForbiddenError, isOwnerOnlyForbiddenError } from '@/utils/forbiddenError';
interface ActionProps {
group: string | undefined;
@@ -185,9 +185,11 @@ const Actions = memo<ActionProps>(({ group, id, openCreateGroupModal, parentType
}
} catch (error) {
message.error(
- isForbiddenError(error)
- ? t('manageOnlyCreator', { ns: 'common' })
- : t('operationFailed', { ns: 'common' }),
+ isOwnerOnlyForbiddenError(error)
+ ? t('deleteSharedOwnerOnly', { ns: 'common' })
+ : isForbiddenError(error)
+ ? t('manageOnlyCreator', { ns: 'common' })
+ : t('operationFailed', { ns: 'common' }),
);
}
},
diff --git a/src/services/agent.ts b/src/services/agent.ts
index 8bf63767b4e..19489ac5e2c 100644
--- a/src/services/agent.ts
+++ b/src/services/agent.ts
@@ -129,8 +129,8 @@ class AgentService {
* the shared list. The inverse (public → private) goes through
* {@link setAgentVisibility}.
*/
- publishAgentToWorkspace = async (id: string): Promise<void> => {
- await lambdaClient.agent.publishAgentToWorkspace.mutate({ id });
+ publishAgentToWorkspace = async (id: string, accessLevel?: 'use' | 'edit'): Promise<void> => {
+ await lambdaClient.agent.publishAgentToWorkspace.mutate({ accessLevel, id });
};
/**
@@ -302,9 +302,11 @@ class AgentService {
agentId: string,
targetWorkspaceId: string | null,
targetVisibility?: 'private' | 'public',
+ targetAccessLevel?: 'edit' | 'use',
): Promise<{ agentId: string; slug: string | null }> => {
return lambdaClient.agent.transferAgent.mutate({
agentId,
+ targetAccessLevel,
targetVisibility,
targetWorkspaceId,
});
diff --git a/src/services/chat/mecha/agentConfigResolver.test.ts b/src/services/chat/mecha/agentConfigResolver.test.ts
index dbabad1ba1c..6f3d0d1f847 100644
--- a/src/services/chat/mecha/agentConfigResolver.test.ts
+++ b/src/services/chat/mecha/agentConfigResolver.test.ts
@@ -10,6 +10,7 @@ import * as agentStore from '@/store/agent';
import * as agentSelectors from '@/store/agent/selectors';
import * as agentGroupStore from '@/store/agentGroup';
import * as agentGroupSelectors from '@/store/agentGroup/selectors';
+import { useUserStore } from '@/store/user';
import * as userSelectors from '@/store/user/selectors';
import { resolveAgentConfig } from './agentConfigResolver';
@@ -45,9 +46,13 @@ describe('resolveAgentConfig', () => {
vi.spyOn(agentSelectors.agentSelectors, 'getAgentConfigById').mockReturnValue(
() => mockAgentConfig as any,
);
+ vi.spyOn(agentSelectors.agentByIdSelectors, 'isWorkspaceAgentById').mockReturnValue(
+ () => false,
+ );
vi.spyOn(agentSelectors.chatConfigByIdSelectors, 'getChatConfigById').mockReturnValue(
() => mockChatConfig as any,
);
+ useUserStore.setState({ workspaceUserPreference: {} });
});
describe('regular agent (non-builtin)', () => {
@@ -145,6 +150,53 @@ describe('resolveAgentConfig', () => {
expect(result.chatConfig).toEqual(mockChatConfig);
});
+ it('uses the current member model override for a workspace Agent that allows it', () => {
+ vi.spyOn(agentSelectors.agentByIdSelectors, 'isWorkspaceAgentById').mockReturnValue(
+ () => true,
+ );
+ vi.spyOn(agentSelectors.agentSelectors, 'getAgentConfigById').mockReturnValue(
+ () =>
+ ({
+ ...mockAgentConfig,
+ agencyConfig: { modelSelectionPolicy: 'member' },
+ provider: 'openai',
+ }) as any,
+ );
+ useUserStore.setState({
+ 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 missing', () => {
+ vi.spyOn(agentSelectors.agentByIdSelectors, 'isWorkspaceAgentById').mockReturnValue(
+ () => true,
+ );
+ vi.spyOn(agentSelectors.agentSelectors, 'getAgentConfigById').mockReturnValue(
+ () => ({ ...mockAgentConfig, provider: 'openai' }) as any,
+ );
+ useUserStore.setState({
+ workspaceUserPreference: {
+ agentModelOverrides: {
+ 'test-agent': { model: 'member-model', provider: 'member-provider' },
+ },
+ },
+ });
+
+ const result = resolveAgentConfig({ agentId: 'test-agent' });
+
+ expect(result.agentConfig.model).toBe('gpt-4');
+ expect(result.agentConfig.provider).toBe('openai');
+ });
+
describe('params adjustment based on chatConfig', () => {
const mockAgentConfigWithParams = {
model: 'gpt-4',
diff --git a/src/services/chat/mecha/agentConfigResolver.ts b/src/services/chat/mecha/agentConfigResolver.ts
index a43a405a889..ccbc5cf2a9e 100644
--- a/src/services/chat/mecha/agentConfigResolver.ts
+++ b/src/services/chat/mecha/agentConfigResolver.ts
@@ -9,12 +9,17 @@ import {
type LobeAgentChatConfig,
type LobeAgentConfig,
type MessageMapScope,
+ resolveAgentModelConfig,
} from '@lobechat/types';
import debug from 'debug';
import { produce } from 'immer';
import { getAgentStoreState } from '@/store/agent';
-import { agentSelectors, chatConfigByIdSelectors } from '@/store/agent/selectors';
+import {
+ agentByIdSelectors,
+ agentSelectors,
+ chatConfigByIdSelectors,
+} from '@/store/agent/selectors';
import { getChatGroupStoreState } from '@/store/agentGroup';
import { agentGroupByIdSelectors, agentGroupSelectors } from '@/store/agentGroup/selectors';
import { useUserStore } from '@/store/user';
@@ -183,7 +188,15 @@ export const resolveAgentConfig = (ctx: AgentConfigResolverContext): ResolvedAge
const agentStoreState = getAgentStoreState();
// Get base config from store
- const agentConfig = agentSelectors.getAgentConfigById(agentId)(agentStoreState);
+ const sharedAgentConfig = agentSelectors.getAgentConfigById(agentId)(agentStoreState);
+ const isWorkspaceAgent = agentByIdSelectors.isWorkspaceAgentById(agentId)(agentStoreState);
+ const memberModelOverride = isWorkspaceAgent
+ ? useUserStore.getState().workspaceUserPreference.agentModelOverrides?.[agentId]
+ : undefined;
+ const agentConfig = {
+ ...sharedAgentConfig,
+ ...resolveAgentModelConfig(sharedAgentConfig, memberModelOverride),
+ };
const chatConfig = chatConfigByIdSelectors.getChatConfigById(agentId)(agentStoreState);
// Base plugins from agent config (pinned identifiers only — disabled entries excluded)
diff --git a/src/services/chatGroup/index.ts b/src/services/chatGroup/index.ts
index f72b27cf91f..96cbf8ba34e 100644
--- a/src/services/chatGroup/index.ts
+++ b/src/services/chatGroup/index.ts
@@ -156,9 +156,11 @@ class ChatGroupService {
groupId: string,
targetWorkspaceId: string | null,
targetVisibility?: 'private' | 'public',
+ targetAccessLevel?: 'edit' | 'use',
): Promise<{ groupId: string } | null> => {
return lambdaClient.group.transferGroup.mutate({
groupId,
+ targetAccessLevel,
targetVisibility,
targetWorkspaceId,
});
diff --git a/src/services/document/index.ts b/src/services/document/index.ts
index 249c5f0730c..3e21521c9a6 100644
--- a/src/services/document/index.ts
+++ b/src/services/document/index.ts
@@ -289,8 +289,11 @@ export class DocumentService {
* Thin wrapper around `setDocumentVisibility(id, 'public')`; kept for
* existing callers.
*/
- async publishDocumentToWorkspace(id: string): Promise<{ documentIds: string[] }> {
- return lambdaClient.document.publishDocumentToWorkspace.mutate({ id });
+ async publishDocumentToWorkspace(
+ id: string,
+ accessLevel?: 'view' | 'edit',
+ ): Promise<{ documentIds: string[] }> {
+ return lambdaClient.document.publishDocumentToWorkspace.mutate({ accessLevel, id });
}
/**
diff --git a/src/services/resourcePermission.ts b/src/services/resourcePermission.ts
new file mode 100644
index 00000000000..b31484148e1
--- /dev/null
+++ b/src/services/resourcePermission.ts
@@ -0,0 +1,36 @@
+import { lambdaClient } from '@/libs/trpc/client';
+
+export type PermissionResourceType = 'agent' | 'agentGroup' | 'document';
+export type ResourceAccessLevel = 'edit' | 'use' | 'view';
+
+export interface ResourceGeneralAccess {
+ accessLevel: ResourceAccessLevel;
+ canManage: boolean;
+ creatorId: string;
+ /** @deprecated Compatibility value returned for released clients. */
+ generalAccess: 'editor' | 'viewer';
+ visibility: 'private' | 'public';
+}
+
+class ResourcePermissionService {
+ getGeneralAccess = async (
+ resourceType: PermissionResourceType,
+ resourceId: string,
+ ): Promise<ResourceGeneralAccess> => {
+ return lambdaClient.resourcePermission.getGeneralAccess.query({ resourceId, resourceType });
+ };
+
+ setAccessLevel = async (
+ resourceType: PermissionResourceType,
+ resourceId: string,
+ accessLevel: ResourceAccessLevel,
+ ): Promise<ResourceGeneralAccess> => {
+ return lambdaClient.resourcePermission.setGeneralAccess.mutate({
+ accessLevel,
+ resourceId,
+ resourceType,
+ });
+ };
+}
+
+export const resourcePermissionService = new ResourcePermissionService();
diff --git a/src/store/agent/selectors/selectors.ts b/src/store/agent/selectors/selectors.ts
index 77873c07b06..e75bb327217 100644
--- a/src/store/agent/selectors/selectors.ts
+++ b/src/store/agent/selectors/selectors.ts
@@ -54,6 +54,12 @@ const currentAgentBackgroundColor = (s: AgentStoreState) =>
const currentAgentTags = (s: AgentStoreState) => currentAgentData(s)?.tags || [];
+const currentAgentAuthorId = (s: AgentStoreState) => currentAgentData(s)?.userId;
+
+const currentAgentCreatedAt = (s: AgentStoreState) => currentAgentData(s)?.createdAt;
+
+const currentAgentVisibility = (s: AgentStoreState) => currentAgentData(s)?.visibility;
+
/**
* Get complete meta data for the current agent
* Used to replace sessionMetaSelectors.currentAgentMeta
@@ -335,8 +341,10 @@ const getAgentDocumentsById = (agentId: string) => (s: AgentStoreState) =>
export const agentSelectors = {
currentAgentExecutionTarget,
currentAgentHeterogeneousProviderType,
+ currentAgentAuthorId,
currentAgentAvatar,
currentAgentBackgroundColor,
+ currentAgentCreatedAt,
currentAgentConfig,
currentAgentConfigError,
currentAgentDescription,
@@ -354,6 +362,7 @@ export const agentSelectors = {
currentAgentTTSVoice,
currentAgentTags,
currentAgentTitle,
+ currentAgentVisibility,
currentAgentWorkingDirectory,
currentEnabledKnowledge,
currentKnowledgeIds,
diff --git a/src/store/document/slices/editor/action.ts b/src/store/document/slices/editor/action.ts
index f79e5135abd..dcb6911defc 100644
--- a/src/store/document/slices/editor/action.ts
+++ b/src/store/document/slices/editor/action.ts
@@ -3,7 +3,9 @@
import type { IEditor } from '@lobehub/editor';
import type { EditorState as LobehubEditorState } from '@lobehub/editor/react';
import isEqual from 'fast-deep-equal';
+import { t } from 'i18next';
+import { message } from '@/components/AntdStaticMethods';
import { EMPTY_EDITOR_STATE } from '@/libs/editor/constants';
import { isValidEditorData } from '@/libs/editor/isValidEditorData';
import { documentService } from '@/services/document';
@@ -355,7 +357,13 @@ export class EditorActionImpl {
// actively editing (CONFLICT). Surface it as a lock block so the editor can
// flip to read-only at once instead of silently dropping the edit, and keep
// `isDirty` so the unsaved content stays visible to copy out.
- const lockBlocked = (error as { data?: { code?: string } })?.data?.code === 'CONFLICT';
+ const errorCode = (error as { data?: { code?: string } })?.data?.code;
+ const lockBlocked = errorCode === 'CONFLICT';
+ // A view-level workspace member has no edit right on this document
+ // (FORBIDDEN). Tell the user instead of silently dropping the edit.
+ if (errorCode === 'FORBIDDEN') {
+ message.error(t('permission.saveNoEditPermission', { ns: 'setting' }));
+ }
if (!lockBlocked) console.error('[DocumentStore] Failed to save:', error);
internal_dispatchDocument({
id,
diff --git a/src/store/page/slices/list/action.ts b/src/store/page/slices/list/action.ts
index 6283c2b6df1..c26cd3a1920 100644
--- a/src/store/page/slices/list/action.ts
+++ b/src/store/page/slices/list/action.ts
@@ -145,8 +145,11 @@ export class ListActionImpl {
* "Workspace" immediately. Errors bubble up so the caller can surface a
* localized toast without swallowing the reason.
*/
- publishPageToWorkspace = async (pageId: string): Promise<{ documentIds: string[] }> => {
- const result = await documentService.publishDocumentToWorkspace(pageId);
+ publishPageToWorkspace = async (
+ pageId: string,
+ accessLevel?: 'view' | 'edit',
+ ): Promise<{ documentIds: string[] }> => {
+ const result = await documentService.publishDocumentToWorkspace(pageId, accessLevel);
await this.#get().refreshDocuments();
return result;
};
diff --git a/src/store/user/slices/workspaceUserSettings/action.test.ts b/src/store/user/slices/workspaceUserSettings/action.test.ts
new file mode 100644
index 00000000000..a0c2c423ebb
--- /dev/null
+++ b/src/store/user/slices/workspaceUserSettings/action.test.ts
@@ -0,0 +1,60 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { workspaceUserSettingsService } from '@/services/workspaceUserSettings';
+
+import { WorkspaceUserSettingsActionImpl } from './action';
+
+const { mockMutate } = vi.hoisted(() => ({ mockMutate: vi.fn() }));
+
+vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({
+ getActiveWorkspaceId: () => 'workspace-1',
+ useActiveWorkspaceId: () => 'workspace-1',
+}));
+
+vi.mock('@/libs/swr', () => ({
+ mutate: mockMutate,
+ useClientDataSWR: vi.fn(),
+}));
+
+describe('WorkspaceUserSettingsActionImpl', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('optimistically deep-merges one Agent model choice without dropping other choices', async () => {
+ const state = {
+ workspaceUserPreference: {
+ agentDeviceOverrides: {
+ deviceAgent: { executionTarget: 'sandbox' as const },
+ },
+ agentModelOverrides: {
+ existing: { model: 'existing-model', provider: 'existing-provider' },
+ },
+ },
+ };
+ const set = vi.fn((patch: Partial<typeof state>) => Object.assign(state, patch));
+ const action = new WorkspaceUserSettingsActionImpl(set as never, () => state as never);
+ vi.spyOn(workspaceUserSettingsService, 'updatePreference').mockResolvedValue();
+
+ await action.updateWorkspaceUserPreference({
+ agentModelOverrides: {
+ selected: { model: 'selected-model', provider: 'selected-provider' },
+ },
+ });
+
+ expect(state.workspaceUserPreference).toEqual({
+ agentDeviceOverrides: {
+ deviceAgent: { executionTarget: 'sandbox' },
+ },
+ agentModelOverrides: {
+ existing: { model: 'existing-model', provider: 'existing-provider' },
+ selected: { model: 'selected-model', provider: 'selected-provider' },
+ },
+ });
+ expect(mockMutate).toHaveBeenCalledWith(
+ ['FETCH_WORKSPACE_USER_SETTINGS', 'workspace-1'],
+ state.workspaceUserPreference,
+ { revalidate: false },
+ );
+ });
+});
diff --git a/src/store/user/slices/workspaceUserSettings/action.ts b/src/store/user/slices/workspaceUserSettings/action.ts
index 3cab8d18595..54d9ea345b8 100644
--- a/src/store/user/slices/workspaceUserSettings/action.ts
+++ b/src/store/user/slices/workspaceUserSettings/action.ts
@@ -79,7 +79,26 @@ export class WorkspaceUserSettingsActionImpl {
// workspace-keyed SWR data over this un-keyed bucket (see
// `useEffectiveAgencyConfig`) must observe the optimistic value as well.
const previous = this.#get().workspaceUserPreference;
- const optimistic: WorkspaceUserPreference = { ...previous, ...patch };
+ const optimistic: WorkspaceUserPreference = {
+ ...previous,
+ ...patch,
+ ...(patch.agentDeviceOverrides
+ ? {
+ agentDeviceOverrides: {
+ ...previous.agentDeviceOverrides,
+ ...patch.agentDeviceOverrides,
+ },
+ }
+ : {}),
+ ...(patch.agentModelOverrides
+ ? {
+ agentModelOverrides: {
+ ...previous.agentModelOverrides,
+ ...patch.agentModelOverrides,
+ },
+ }
+ : {}),
+ };
const workspaceId = getActiveWorkspaceId();
const swrKey = workspaceId ? [WORKSPACE_USER_SETTINGS_SWR_KEY, workspaceId] : null;
this.#set(
diff --git a/src/store/user/slices/workspaceUserSettings/selectors.ts b/src/store/user/slices/workspaceUserSettings/selectors.ts
index 1f70ccb11e6..61d1f6720ae 100644
--- a/src/store/user/slices/workspaceUserSettings/selectors.ts
+++ b/src/store/user/slices/workspaceUserSettings/selectors.ts
@@ -1,4 +1,4 @@
-import type { AgentDeviceOverride } from '@lobechat/types';
+import type { AgentDeviceOverride, AgentModelOverride } from '@lobechat/types';
import { type UserStore } from '@/store/user';
@@ -13,6 +13,13 @@ const agentDeviceOverrideById =
(s: UserStore): AgentDeviceOverride | undefined =>
s.workspaceUserPreference.agentDeviceOverrides?.[agentId];
+/** The caller's personal model choice for one agent in the active workspace. */
+const agentModelOverrideById =
+ (agentId: string) =>
+ (s: UserStore): AgentModelOverride | undefined =>
+ s.workspaceUserPreference.agentModelOverrides?.[agentId];
+
export const workspaceUserSettingsSelectors = {
agentDeviceOverrideById,
+ agentModelOverrideById,
};
diff --git a/src/utils/forbiddenError.ts b/src/utils/forbiddenError.ts
index 7065cac8ca8..f5c3551d736 100644
--- a/src/utils/forbiddenError.ts
+++ b/src/utils/forbiddenError.ts
@@ -9,3 +9,16 @@ export const isForbiddenError = (error: unknown): boolean => {
const data = (error as { data?: { code?: unknown; httpStatus?: unknown } }).data;
return data?.code === 'FORBIDDEN' || data?.httpStatus === 403;
};
+
+/**
+ * Detect the owner-only FORBIDDEN variant: the caller may be the resource's
+ * creator, but the delete/transfer would take other members' conversations
+ * with it (`transferHasForeignRows` guards). These need a different toast than
+ * the generic "only the creator can do this" copy.
+ */
+export const isOwnerOnlyForbiddenError = (error: unknown): boolean => {
+ if (!isForbiddenError(error)) return false;
+
+ const data = (error as { data?: { errorData?: { code?: unknown } } }).data;
+ return data?.errorData?.code === 'OWNER_ONLY';
+};