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(sidebar): merge workspace agents with team and personal pins (#22973)

Rdmclin254382b5c8e81
diff --git a/apps/server/src/routers/lambda/__tests__/agent.teamPin.test.ts b/apps/server/src/routers/lambda/__tests__/agent.teamPin.test.ts
new file mode 100644
index 00000000000..36b20d6f15a
--- /dev/null
+++ b/apps/server/src/routers/lambda/__tests__/agent.teamPin.test.ts
@@ -0,0 +1,201 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { AgentModel } from '@/database/models/agent';
+import { ResourcePermissionModel } from '@/database/models/resourcePermission';
+import { WorkspaceUserSettingsModel } from '@/database/models/workspaceUserSettings';
+import { AgentService } from '@/server/services/agent';
+import { getWorkspaceScopedPermissionMatches } from '@/server/services/workspacePermission';
+
+import { agentRouter } from '../agent';
+
+vi.mock('@/server/services/resourceEvents', () => ({ publishResourceEvent: vi.fn() }));
+vi.mock('../_helpers/workspaceAgentGuard', () => ({
+ getWorkspaceAgentParentGroupIds: vi.fn().mockResolvedValue([]),
+}));
+vi.mock('@/database/models/user', () => ({ UserModel: { findById: vi.fn() } }));
+vi.mock('@/database/models/agent', () => ({ AgentModel: vi.fn() }));
+vi.mock('@/database/models/session', () => ({ SessionModel: vi.fn() }));
+vi.mock('@/database/models/task', () => ({ TaskModel: vi.fn() }));
+vi.mock('@/database/models/chatGroup', () => ({ ChatGroupModel: vi.fn() }));
+vi.mock('@/database/models/file', () => ({ FileModel: vi.fn() }));
+vi.mock('@/database/models/knowledgeBase', () => ({ KnowledgeBaseModel: vi.fn() }));
+vi.mock('@/database/models/resourcePermission', () => ({ ResourcePermissionModel: vi.fn() }));
+vi.mock('@/database/models/workspaceUserSettings', () => ({
+ WorkspaceUserSettingsModel: vi.fn(),
+}));
+vi.mock('@/server/services/agent', () => ({ AgentService: vi.fn() }));
+vi.mock('@/server/services/workspacePermission', () => ({
+ getWorkspaceScopedPermissionMatches: vi.fn(),
+ hasWorkspaceScopedPermission: vi.fn(),
+ isWorkspacePrimaryOwner: vi.fn(),
+}));
+vi.mock('@/database/core/db-adaptor', () => ({ getServerDB: vi.fn(() => ({})) }));
+vi.mock('@/server/services/resourcePermission', () => ({
+ assertCanEditResource: vi.fn(),
+ assertCanPerformResourceAction: vi.fn(),
+ buildResourcePermissionState: vi.fn((params: unknown) => params),
+ canPerformResourceAction: vi.fn(),
+ getResourceMeta: vi.fn(),
+ isCollaborativeBuiltinAgent: vi.fn(() => false),
+}));
+
+const userId = 'member-1';
+const matches = vi.mocked(getWorkspaceScopedPermissionMatches);
+
+describe('agentRouter team pins', () => {
+ let agentModel: Record<string, ReturnType<typeof vi.fn>>;
+ let preference: {
+ getPreference: ReturnType<typeof vi.fn>;
+ updatePreference: ReturnType<typeof vi.fn>;
+ };
+ let ctx: Record<string, unknown>;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ agentModel = {
+ getAgentVisibilityMeta: vi.fn(),
+ publishToWorkspace: vi.fn().mockResolvedValue({ id: 'agent-1', visibility: 'public' }),
+ update: vi.fn(),
+ };
+ vi.mocked(AgentModel).mockImplementation(function () {
+ return agentModel as never;
+ });
+ preference = {
+ getPreference: vi.fn().mockResolvedValue({ sidebarPinnedItemIds: ['older'] }),
+ updatePreference: vi.fn(),
+ };
+ vi.mocked(WorkspaceUserSettingsModel).mockImplementation(function () {
+ return preference as never;
+ });
+ vi.mocked(ResourcePermissionModel).mockImplementation(function () {
+ return {
+ getAccessLevel: vi.fn().mockResolvedValue(undefined),
+ setAccessLevel: vi.fn(),
+ } as never;
+ });
+ vi.mocked(AgentService).mockImplementation(function () {
+ return {} as never;
+ });
+ ctx = { agentModel, userId, workspaceId: 'ws-1' };
+ });
+
+ describe('updateAgentPinned', () => {
+ it('refuses a member pinning a public workspace agent (team pin)', async () => {
+ agentModel.getAgentVisibilityMeta.mockResolvedValue({
+ pinned: false,
+ slug: null,
+ userId: 'creator-1',
+ visibility: 'public',
+ });
+ matches.mockResolvedValue({ hasAllScope: false, hasOwnerScope: true });
+
+ await expect(
+ agentRouter.createCaller(ctx as never).updateAgentPinned({ id: 'agent-1', pinned: true }),
+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });
+ expect(agentModel.update).not.toHaveBeenCalled();
+ });
+
+ it('lets an owner/admin (agent:update:all) pin a public workspace agent', async () => {
+ agentModel.getAgentVisibilityMeta.mockResolvedValue({
+ pinned: false,
+ slug: null,
+ userId: 'creator-1',
+ visibility: 'public',
+ });
+ matches.mockResolvedValue({ hasAllScope: true, hasOwnerScope: false });
+
+ await agentRouter
+ .createCaller(ctx as never)
+ .updateAgentPinned({ id: 'agent-1', pinned: true });
+
+ expect(matches).toHaveBeenCalledWith(
+ expect.objectContaining({ action: 'AGENT_UPDATE', userId, workspaceId: 'ws-1' }),
+ );
+ expect(agentModel.update).toHaveBeenCalledWith('agent-1', { pinned: true });
+ });
+
+ it('keeps a private agent pin open to its creator without the team check', async () => {
+ agentModel.getAgentVisibilityMeta.mockResolvedValue({
+ pinned: false,
+ slug: null,
+ userId,
+ visibility: 'private',
+ });
+
+ await agentRouter
+ .createCaller(ctx as never)
+ .updateAgentPinned({ id: 'agent-1', pinned: true });
+
+ expect(matches).not.toHaveBeenCalled();
+ expect(agentModel.update).toHaveBeenCalledWith('agent-1', { pinned: true });
+ });
+
+ it('leaves personal mode unchanged', async () => {
+ await agentRouter
+ .createCaller({ ...ctx, workspaceId: undefined } as never)
+ .updateAgentPinned({ id: 'agent-1', pinned: true });
+
+ expect(agentModel.getAgentVisibilityMeta).not.toHaveBeenCalled();
+ expect(agentModel.update).toHaveBeenCalledWith('agent-1', { pinned: true });
+ });
+ });
+
+ describe('publishAgentToWorkspace', () => {
+ it('moves a private pin to the creator personal list instead of making it a team pin', async () => {
+ agentModel.getAgentVisibilityMeta.mockResolvedValue({
+ pinned: true,
+ slug: null,
+ userId,
+ visibility: 'private',
+ });
+
+ await agentRouter.createCaller(ctx as never).publishAgentToWorkspace({ id: 'agent-1' });
+
+ expect(preference.updatePreference).toHaveBeenCalledWith({
+ sidebarPinnedItemIds: ['agent-1', 'older'],
+ });
+ expect(agentModel.update).toHaveBeenCalledWith('agent-1', { pinned: false });
+ // Personal entry, then column, then publish: no step can leave a public
+ // pinned row (an unauthorized team pin) behind.
+ expect(preference.updatePreference.mock.invocationCallOrder[0]).toBeLessThan(
+ agentModel.update.mock.invocationCallOrder[0],
+ );
+ expect(agentModel.update.mock.invocationCallOrder[0]).toBeLessThan(
+ agentModel.publishToWorkspace.mock.invocationCallOrder[0],
+ );
+ });
+
+ it('keeps the private pin when publishing fails', async () => {
+ agentModel.getAgentVisibilityMeta.mockResolvedValue({
+ pinned: true,
+ slug: null,
+ userId,
+ visibility: 'private',
+ });
+ agentModel.publishToWorkspace.mockRejectedValue(new Error('publish failed'));
+
+ await expect(
+ agentRouter.createCaller(ctx as never).publishAgentToWorkspace({ id: 'agent-1' }),
+ ).rejects.toThrow('publish failed');
+ // The row stays private and the pin survives in the personal list.
+ expect(preference.updatePreference).toHaveBeenCalledWith({
+ sidebarPinnedItemIds: ['agent-1', 'older'],
+ });
+ });
+
+ it('leaves an unpinned agent alone', async () => {
+ agentModel.getAgentVisibilityMeta.mockResolvedValue({
+ pinned: false,
+ slug: null,
+ userId,
+ visibility: 'private',
+ });
+
+ await agentRouter.createCaller(ctx as never).publishAgentToWorkspace({ id: 'agent-1' });
+
+ expect(preference.updatePreference).not.toHaveBeenCalled();
+ expect(agentModel.update).not.toHaveBeenCalled();
+ });
+ });
+});
diff --git a/apps/server/src/routers/lambda/__tests__/agent.test.ts b/apps/server/src/routers/lambda/__tests__/agent.test.ts
index bbbe66d1ad0..dfb2ac315a6 100644
--- a/apps/server/src/routers/lambda/__tests__/agent.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/agent.test.ts
@@ -91,6 +91,7 @@ vi.mock('@/server/services/agent', () => ({
}));
vi.mock('@/server/services/workspacePermission', () => ({
+ getWorkspaceScopedPermissionMatches: vi.fn(),
hasWorkspaceScopedPermission: vi.fn(),
isWorkspacePrimaryOwner: vi.fn(),
}));
@@ -189,6 +190,7 @@ describe('agentRouter', () => {
findBySessionId: vi.fn(),
getAgentAssignedKnowledge: vi.fn(),
getAgentVisibility: vi.fn().mockResolvedValue(null),
+ getAgentVisibilityMeta: vi.fn().mockResolvedValue(null),
publishToWorkspace: vi.fn(),
resolveIdBySlug: vi.fn().mockResolvedValue(null),
toggleFile: vi.fn(),
@@ -920,6 +922,26 @@ describe('agentRouter', () => {
},
);
+ it('drops a team pin even when the policy strip rebuilds the patch', async () => {
+ agentServiceMock.updateAgentConfig = vi.fn().mockResolvedValue({ id: 'agent-1' });
+ vi.spyOn(EditLockService.prototype, 'getBlockingHolder').mockResolvedValue(null);
+
+ await agentRouter.createCaller(wsCtx()).updateAgentConfig({
+ agentId: 'agent-1',
+ value: {
+ agencyConfig: { boundDeviceId: 'device-1', modelSelectionPolicy: 'fixed' },
+ pinned: true,
+ },
+ });
+
+ // `pinned` is the owner/admin team pin; only `updateAgentPinned` writes it.
+ expect(agentServiceMock.updateAgentConfig).toHaveBeenCalledWith(
+ 'agent-1',
+ { agencyConfig: { boundDeviceId: 'device-1' } },
+ undefined,
+ );
+ });
+
it('strips fully merged stale policies before a collaborator update', async () => {
agentServiceMock.updateAgentConfig = vi.fn().mockResolvedValue({ id: 'agent-1' });
vi.spyOn(EditLockService.prototype, 'getBlockingHolder').mockResolvedValue(null);
diff --git a/apps/server/src/routers/lambda/__tests__/agentGroup.test.ts b/apps/server/src/routers/lambda/__tests__/agentGroup.test.ts
index 2c180122f34..ff9d378145a 100644
--- a/apps/server/src/routers/lambda/__tests__/agentGroup.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/agentGroup.test.ts
@@ -14,6 +14,7 @@ import { EditLockService } from '@/server/services/editLock';
import { publishResourceEvent } from '@/server/services/resourceEvents';
import { canPerformResourceAction } from '@/server/services/resourcePermission';
import {
+ getWorkspaceScopedPermissionMatches,
hasWorkspaceScopedPermission,
isWorkspacePrimaryOwner,
} from '@/server/services/workspacePermission';
@@ -27,6 +28,7 @@ import { agentGroupRouter } from '../agentGroup';
vi.mock('@/server/services/resourceEvents', () => ({ publishResourceEvent: vi.fn() }));
// Both read the DB directly; `mockCtx.serverDB` is a bare object.
vi.mock('@/server/services/workspacePermission', () => ({
+ getWorkspaceScopedPermissionMatches: vi.fn(),
hasWorkspaceScopedPermission: vi.fn().mockResolvedValue(true),
isWorkspacePrimaryOwner: vi.fn().mockResolvedValue(true),
}));
@@ -900,6 +902,95 @@ describe('agentGroupRouter', () => {
});
});
+ describe('team pin', () => {
+ const wsCtx = () => ({ serverDB: {}, userId, workspaceId: 'ws-1' });
+
+ beforeEach(() => {
+ vi.spyOn(EditLockService.prototype, 'getBlockingHolder').mockResolvedValue(null);
+ chatGroupModelMock.update.mockResolvedValue({ id: 'group-1' });
+ });
+
+ it('refuses a member pinning a public workspace group', async () => {
+ chatGroupModelMock.findById.mockResolvedValue({ id: 'group-1', visibility: 'public' });
+ vi.mocked(getWorkspaceScopedPermissionMatches).mockResolvedValue({
+ hasAllScope: false,
+ hasOwnerScope: true,
+ });
+
+ await expect(
+ agentGroupRouter.createCaller(wsCtx()).updateGroup({
+ id: 'group-1',
+ value: { pinned: true },
+ }),
+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });
+ expect(chatGroupModelMock.update).not.toHaveBeenCalled();
+ });
+
+ it('lets an owner/admin pin a public workspace group for the team', async () => {
+ chatGroupModelMock.findById.mockResolvedValue({ id: 'group-1', visibility: 'public' });
+ vi.mocked(getWorkspaceScopedPermissionMatches).mockResolvedValue({
+ hasAllScope: true,
+ hasOwnerScope: false,
+ });
+
+ await agentGroupRouter
+ .createCaller(wsCtx())
+ .updateGroup({ id: 'group-1', value: { pinned: true } });
+
+ expect(chatGroupModelMock.update).toHaveBeenCalledWith(
+ 'group-1',
+ expect.objectContaining({ pinned: true }),
+ );
+ });
+
+ it('never creates a public workspace group already pinned', async () => {
+ agentGroupRepoMock.createGroupWithSupervisor.mockResolvedValue({
+ group: { id: 'group-1', visibility: 'private' },
+ supervisorAgentId: 'sup-1',
+ });
+
+ const caller = agentGroupRouter.createCaller(wsCtx());
+ await caller.createGroup({ pinned: true, title: 'Team' });
+ await caller.createGroup({ pinned: true, title: 'Mine', visibility: 'private' });
+
+ expect(agentGroupRepoMock.createGroupWithSupervisor.mock.calls[0][0]).toMatchObject({
+ pinned: false,
+ });
+ // A private group's pin is its creator's own and stays.
+ expect(agentGroupRepoMock.createGroupWithSupervisor.mock.calls[1][0]).toMatchObject({
+ pinned: true,
+ });
+ });
+
+ it('never creates a public workspace group already pinned from members either', async () => {
+ agentModelMock.batchCreate.mockResolvedValue([]);
+ agentGroupRepoMock.createGroupWithSupervisor.mockResolvedValue({
+ group: { id: 'group-1', visibility: 'private' },
+ supervisorAgentId: 'sup-1',
+ });
+
+ await agentGroupRouter.createCaller(wsCtx()).createGroupWithMembers({
+ groupConfig: { pinned: true, title: 'Team' },
+ members: [],
+ });
+
+ expect(agentGroupRepoMock.createGroupWithSupervisor.mock.calls[0][0]).toMatchObject({
+ pinned: false,
+ });
+ });
+
+ it('keeps a private group pin and other edits free of the team check', async () => {
+ chatGroupModelMock.findById.mockResolvedValue({ id: 'group-1', visibility: 'private' });
+
+ const caller = agentGroupRouter.createCaller(wsCtx());
+ await caller.updateGroup({ id: 'group-1', value: { pinned: true } });
+ await caller.updateGroup({ id: 'group-1', value: { title: 'New' } });
+
+ expect(getWorkspaceScopedPermissionMatches).not.toHaveBeenCalled();
+ expect(chatGroupModelMock.update).toHaveBeenCalledTimes(2);
+ });
+ });
+
describe('edit lock', () => {
const wsCtx = () => ({ serverDB: {}, userId, workspaceId: 'ws-1' });
diff --git a/apps/server/src/routers/lambda/_helpers/sidebarPin.ts b/apps/server/src/routers/lambda/_helpers/sidebarPin.ts
new file mode 100644
index 00000000000..b4e63cc60db
--- /dev/null
+++ b/apps/server/src/routers/lambda/_helpers/sidebarPin.ts
@@ -0,0 +1,73 @@
+import { TRPCError } from '@trpc/server';
+
+import { WorkspaceUserSettingsModel } from '@/database/models/workspaceUserSettings';
+import type { LobeChatDatabase } from '@/database/type';
+import { getWorkspaceScopedPermissionMatches } from '@/server/services/workspacePermission';
+
+/** Upper bound for one member's personal pin list in a workspace. */
+export const MAX_SIDEBAR_PINNED_ITEMS = 200;
+
+export const TEAM_PIN_FORBIDDEN_MESSAGE = 'Only workspace owners and admins can change team pins';
+
+interface TeamPinCtx {
+ serverDB: LobeChatDatabase;
+ userId: string;
+ workspaceId?: string | null;
+}
+
+/**
+ * In a workspace, `pinned` on a PUBLIC Agent / chat group is the team pin every
+ * member sees in the fixed section of the Agents sidebar, so only roles holding
+ * the all-resource `agent:update` grant (owner, admin) may write it. Members
+ * pin for themselves through `workspace_user_settings.sidebarPinnedItemIds`.
+ * Personal mode and private rows (only their creator can see them) are not
+ * team pins and skip this check.
+ */
+export const assertCanWriteTeamPin = async (ctx: TeamPinCtx): Promise<void> => {
+ if (!ctx.workspaceId) return;
+
+ const { hasAllScope } = await getWorkspaceScopedPermissionMatches({
+ action: 'AGENT_UPDATE',
+ db: ctx.serverDB,
+ // Injected by the Cloud workspace auth middleware; resolved from the DB otherwise.
+ grantedPermissions: (ctx as { workspacePermissionCodes?: string[] }).workspacePermissionCodes,
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
+ });
+
+ if (!hasAllScope) {
+ throw new TRPCError({ code: 'FORBIDDEN', message: TEAM_PIN_FORBIDDEN_MESSAGE });
+ }
+};
+
+/**
+ * A private row's `pinned` column is its creator's own pin. Once the row is
+ * published that column would read as a team pin no owner/admin chose, so the
+ * pin moves to the creator's personal list and the column is cleared: the
+ * creator keeps it pinned, nobody else gets it pinned. Callers run this BEFORE
+ * flipping visibility. The personal entry is written first, so a failure at
+ * any step leaves the pin either on the column of a still-private row or in
+ * the personal list — never as an unauthorized team pin, never lost.
+ */
+export const releasePrivatePin = async ({
+ clearPinned,
+ creatorId,
+ db,
+ itemId,
+ workspaceId,
+}: {
+ clearPinned: () => Promise<unknown>;
+ creatorId: string;
+ db: LobeChatDatabase;
+ itemId: string;
+ workspaceId: string;
+}): Promise<void> => {
+ const model = new WorkspaceUserSettingsModel(db, creatorId, workspaceId);
+ const current = (await model.getPreference()).sidebarPinnedItemIds ?? [];
+ if (!current.includes(itemId)) {
+ await model.updatePreference({
+ sidebarPinnedItemIds: [itemId, ...current].slice(0, MAX_SIDEBAR_PINNED_ITEMS),
+ });
+ }
+ await clearPinned();
+};
diff --git a/apps/server/src/routers/lambda/agent/config.ts b/apps/server/src/routers/lambda/agent/config.ts
index 14f9ff90064..d39c221f4a0 100644
--- a/apps/server/src/routers/lambda/agent/config.ts
+++ b/apps/server/src/routers/lambda/agent/config.ts
@@ -181,6 +181,14 @@ export const configRouter = router({
if (!canUpdatePolicies) safeValue = stripAgentPermissionPolicies(input.value);
}
+
+ // `pinned` is the team pin in a workspace and has its own owner/admin
+ // gated route (`updateAgentPinned`); a config patch must not set it.
+ // Applied last so no earlier rewrite of `safeValue` can restore it.
+ if ('pinned' in safeValue) {
+ const { pinned: _pinned, ...rest } = safeValue as Record<string, unknown>;
+ safeValue = rest;
+ }
}
// Collaborative edit lock: reject writes to a workspace agent another
diff --git a/apps/server/src/routers/lambda/agent/lifecycle.ts b/apps/server/src/routers/lambda/agent/lifecycle.ts
index 3e9b13d9cb8..ce7056f6178 100644
--- a/apps/server/src/routers/lambda/agent/lifecycle.ts
+++ b/apps/server/src/routers/lambda/agent/lifecycle.ts
@@ -15,6 +15,7 @@ import { TrashService } from '@/server/services/trash';
import { TransferErrorCode } from '@/types/transferError';
import { isWorkspaceNonOwner } from '../_helpers/assertWorkspaceRowManageable';
+import { assertCanWriteTeamPin } from '../_helpers/sidebarPin';
import { agentProcedure } from './procedures';
export const lifecycleRouter = router({
@@ -292,6 +293,14 @@ export const lifecycleRouter = router({
}),
)
.mutation(async ({ input, ctx }) => {
+ // A public workspace row's pin is the team pin every member sees, so it
+ // is owner/admin-only. A private row is visible to its creator alone, so
+ // its pin stays personal and any role that can update it may write it.
+ if (ctx.workspaceId) {
+ const meta = await ctx.agentModel.getAgentVisibilityMeta(input.id);
+ if (!meta) throw new TRPCError({ code: 'NOT_FOUND', message: 'Agent not found' });
+ if (meta.visibility !== 'private') await assertCanWriteTeamPin(ctx);
+ }
return ctx.agentModel.update(input.id, { pinned: input.pinned });
}),
});
diff --git a/apps/server/src/routers/lambda/agent/visibility.ts b/apps/server/src/routers/lambda/agent/visibility.ts
index aebf85d894b..a4f59dff2e5 100644
--- a/apps/server/src/routers/lambda/agent/visibility.ts
+++ b/apps/server/src/routers/lambda/agent/visibility.ts
@@ -14,6 +14,7 @@ import {
buildResourcePermissionState,
} from '@/server/services/resourcePermission';
+import { releasePrivatePin } from '../_helpers/sidebarPin';
import { agentProcedure } from './procedures';
export const visibilityRouter = router({
@@ -32,6 +33,21 @@ export const visibilityRouter = router({
}),
)
.mutation(async ({ input, ctx }) => {
+ // Hand a private pin to the creator's personal list BEFORE the row goes
+ // public: done afterwards, a failure in between would leave a public
+ // pinned row — a team pin no owner/admin chose.
+ if (ctx.workspaceId) {
+ const meta = await ctx.agentModel.getAgentVisibilityMeta(input.id);
+ if (meta?.pinned && meta.visibility === 'private') {
+ await releasePrivatePin({
+ clearPinned: () => ctx.agentModel.update(input.id, { pinned: false }),
+ creatorId: meta.userId,
+ db: ctx.serverDB,
+ itemId: input.id,
+ workspaceId: ctx.workspaceId,
+ });
+ }
+ }
const result = await ctx.agentModel.publishToWorkspace(input.id);
if (ctx.workspaceId) {
const permissionModel = new ResourcePermissionModel(ctx.serverDB, ctx.workspaceId);
@@ -157,6 +173,18 @@ export const visibilityRouter = router({
}
}
+ // Before the row turns public, so a failure never leaves a team pin
+ // nobody with the role set (see `publishAgentToWorkspace`).
+ if (input.visibility === 'public' && meta.pinned) {
+ await releasePrivatePin({
+ clearPinned: () => ctx.agentModel.update(input.id, { pinned: false }),
+ creatorId: meta.userId,
+ db: ctx.serverDB,
+ itemId: input.id,
+ workspaceId: ctx.workspaceId,
+ });
+ }
+
const updated = await ctx.agentModel.setVisibility(input.id, input.visibility);
if (!updated) throw new TRPCError({ code: 'NOT_FOUND', message: 'Agent not found' });
diff --git a/apps/server/src/routers/lambda/agentGroup/lifecycle.ts b/apps/server/src/routers/lambda/agentGroup/lifecycle.ts
index 085d819abec..d02e3271fc2 100644
--- a/apps/server/src/routers/lambda/agentGroup/lifecycle.ts
+++ b/apps/server/src/routers/lambda/agentGroup/lifecycle.ts
@@ -15,6 +15,7 @@ import {
import { TransferErrorCode } from '@/types/transferError';
import { isWorkspaceNonOwner } from '../_helpers/assertWorkspaceRowManageable';
+import { assertCanWriteTeamPin } from '../_helpers/sidebarPin';
import {
agentGroupProcedureWrite,
agentMemberInputSchema,
@@ -33,6 +34,9 @@ export const lifecycleRouter = router({
const { group, supervisorAgentId } = await ctx.agentGroupRepo.createGroupWithSupervisor({
...input,
config: ctx.agentGroupService.normalizeGroupConfig(input.config as ChatGroupConfig | null),
+ // A public workspace group's pin is the owner/admin team pin, set only
+ // through `updateGroup`; creating one never carries it.
+ ...(ctx.workspaceId && input.visibility !== 'private' ? { pinned: false } : {}),
});
if (ctx.workspaceId && group.visibility !== 'private') {
@@ -140,6 +144,11 @@ export const lifecycleRouter = router({
{
...input.groupConfig,
config: normalizedConfig,
+ // Same rule as `createGroup`: a public workspace group never starts
+ // as a team pin.
+ ...(ctx.workspaceId && input.groupConfig.visibility !== 'private'
+ ? { pinned: false }
+ : {}),
},
memberAgentIds,
supervisorConfig as any,
@@ -237,6 +246,14 @@ export const lifecycleRouter = router({
workspaceId: ctx.workspaceId ?? undefined,
});
+ // A public workspace group's pin is the team pin every member sees:
+ // owner/admin only. A private group's pin stays its creator's own.
+ if (ctx.workspaceId && input.value.pinned !== undefined) {
+ const group = await ctx.chatGroupModel.findById(input.id);
+ if (!group) throw new TRPCError({ code: 'NOT_FOUND', message: 'Group not found' });
+ if (group.visibility !== 'private') await assertCanWriteTeamPin(ctx);
+ }
+
// 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/agentGroup/visibility.ts b/apps/server/src/routers/lambda/agentGroup/visibility.ts
index 525b86362bc..95b71ac7f90 100644
--- a/apps/server/src/routers/lambda/agentGroup/visibility.ts
+++ b/apps/server/src/routers/lambda/agentGroup/visibility.ts
@@ -12,6 +12,7 @@ import {
buildResourcePermissionState,
} from '@/server/services/resourcePermission';
+import { releasePrivatePin } from '../_helpers/sidebarPin';
import { getWorkspaceGroupVirtualAgentIds } from '../_helpers/workspaceAgentGuard';
import { agentGroupProcedureWrite, PERMISSION_WRITE_CONCURRENCY } from './procedures';
@@ -86,6 +87,20 @@ export const visibilityRouter = router({
});
}
+ // Release a private pin before the group goes public, as
+ // `publishAgentToWorkspace` does.
+ if (ctx.workspaceId) {
+ const before = await ctx.chatGroupModel.findById(input.id);
+ if (before?.pinned && before.visibility === 'private' && before.userId === ctx.userId) {
+ await releasePrivatePin({
+ clearPinned: () => ctx.chatGroupModel.update(input.id, { pinned: false }),
+ creatorId: before.userId,
+ db: ctx.serverDB,
+ itemId: input.id,
+ workspaceId: ctx.workspaceId,
+ });
+ }
+ }
const result = await ctx.chatGroupModel.publishToWorkspace(input.id);
if (ctx.workspaceId) {
const permissionModel = new ResourcePermissionModel(ctx.serverDB, ctx.workspaceId);
@@ -190,6 +205,17 @@ export const visibilityRouter = router({
});
}
+ // Before the group turns public (see `publishGroupToWorkspace`).
+ if (input.visibility === 'public' && group.pinned) {
+ await releasePrivatePin({
+ clearPinned: () => ctx.chatGroupModel.update(input.id, { pinned: false }),
+ creatorId: group.userId,
+ db: ctx.serverDB,
+ itemId: input.id,
+ workspaceId: ctx.workspaceId,
+ });
+ }
+
const updated = await ctx.chatGroupModel.setVisibility(input.id, input.visibility);
if (!updated) throw new TRPCError({ code: 'NOT_FOUND', message: 'Group not found' });
diff --git a/apps/server/src/routers/lambda/session.ts b/apps/server/src/routers/lambda/session.ts
index 73be7e92a53..c46d888c813 100644
--- a/apps/server/src/routers/lambda/session.ts
+++ b/apps/server/src/routers/lambda/session.ts
@@ -56,7 +56,10 @@ export const sessionRouter = router({
...config,
fewShots: config.fewShots ?? examples,
marketIdentifier: config.marketIdentifier ?? identifier,
- pinned: input.session.pinned,
+ // A public workspace row's pin is the owner/admin team pin, set only
+ // through `agent.updateAgentPinned`; creating one never carries it.
+ pinned:
+ ctx.workspaceId && config.visibility !== 'private' ? undefined : input.session.pinned,
},
groupId: groupId && groupId !== 'default' ? groupId : undefined,
visibility: config.visibility,
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index 1f0e908b46a..3b242cbf7b6 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -1986,6 +1986,8 @@
"piInstallGuide.reason": "LobeHub could not start Pi: {{message}}",
"piInstallGuide.title": "Install Pi CLI",
"pin": "Pin",
+ "pinForTeam": "Pin for team",
+ "pinForTeamForbidden": "Only workspace owners and admins can change team pins",
"pinOff": "Unpin",
"platformAgent.deviceGuard.configure": "Configure",
"platformAgent.deviceGuard.deviceOffline.desc": "The bound device is not connected. Run `lh connect` on that machine then refresh.",
@@ -3125,6 +3127,7 @@
"turnProcess.ranFor_other": "Ran {{count}} steps ({{duration}})",
"turnProcess.viewFullRecordWithSteps_one": "Executed {{count}} step · View full record",
"turnProcess.viewFullRecordWithSteps_other": "Executed {{count}} steps · View full record",
+ "unpinForTeam": "Unpin for team",
"untitledAgent": "Untitled Agent",
"untitledGroup": "Untitled Group",
"updateAgent": "Update Agent Information",
diff --git a/locales/en-US/common.json b/locales/en-US/common.json
index f6e555490e2..62fd1a85f03 100644
--- a/locales/en-US/common.json
+++ b/locales/en-US/common.json
@@ -12,7 +12,9 @@
"agentViewAll.form.ordering": "Ordering",
"agentViewAll.form.showSidebarHidden": "Show agents hidden from my sidebar",
"agentViewAll.groupBy.author": "Author",
+ "agentViewAll.groupBy.folder": "Category",
"agentViewAll.groupBy.label": "Label",
+ "agentViewAll.groupBy.noFolder": "No category",
"agentViewAll.groupBy.noLabel": "No label",
"agentViewAll.groupBy.none": "No grouping",
"agentViewAll.groupBy.unknownAuthor": "Unknown author",
@@ -378,16 +380,22 @@
"more": "More",
"navPanel.agent": "Agents",
"navPanel.bottomDivider": "Items below anchor to bottom",
+ "navPanel.browseAllAgents": "All agents",
+ "navPanel.createPrivateFolder": "New private category",
+ "navPanel.createWorkspaceAgent": "New workspace agent",
"navPanel.customizeSidebar": "Customize Sidebar",
"navPanel.displayItems": "Display Items",
"navPanel.hidden": "Hidden",
"navPanel.hideSection": "Hide Section",
"navPanel.library": "Library",
+ "navPanel.managePrivateFolders": "Manage private categories",
"navPanel.moveDown": "Move Down",
"navPanel.moveUp": "Move Up",
+ "navPanel.myPinned": "Pinned",
"navPanel.openMenu": "Open menu",
"navPanel.pinned": "Pinned",
"navPanel.privateAgents": "Private",
+ "navPanel.privateTooltip": "Private · only you can see this",
"navPanel.publicAgents": "Workspace",
"navPanel.resetDefault": "Reset to Default",
"navPanel.searchAgent": "Search Agent...",
@@ -396,8 +404,12 @@
"navPanel.searchResultEmpty": "No search results found",
"navPanel.shortcuts": "Shortcuts",
"navPanel.show": "Show",
+ "navPanel.showLessTeamPinned": "Show less",
+ "navPanel.showMoreTeamPinned": "Show {{count}} more",
"navPanel.switcherAll": "All",
"navPanel.switcherRecent": "Recent",
+ "navPanel.teamPinned": "Pinned for team",
+ "navPanel.teamPinnedHint": "Pinned by admins for everyone in this workspace",
"navPanel.viewAllAgents": "View all",
"navPanel.visible": "Visible",
"new": "New",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 3f7f75f2470..bdccde7693a 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -1986,6 +1986,8 @@
"piInstallGuide.reason": "LobeHub 无法启动 Pi:{{message}}",
"piInstallGuide.title": "安装 Pi CLI",
"pin": "置顶",
+ "pinForTeam": "为团队置顶",
+ "pinForTeamForbidden": "仅工作区所有者和管理员可以修改团队置顶",
"pinOff": "取消置顶",
"platformAgent.deviceGuard.configure": "去配置",
"platformAgent.deviceGuard.deviceOffline.desc": "绑定的设备未连接,请在目标机器上运行 `lh connect` 后刷新。",
@@ -3125,6 +3127,7 @@
"turnProcess.ranFor_other": "共运行 {{count}} 步 ({{duration}})",
"turnProcess.viewFullRecordWithSteps_one": "共执行 {{count}} 步 · 点击查看完整记录",
"turnProcess.viewFullRecordWithSteps_other": "共执行 {{count}} 步 · 点击查看完整记录",
+ "unpinForTeam": "取消团队置顶",
"untitledAgent": "未命名助理",
"untitledGroup": "未命名群组",
"updateAgent": "更新助理信息",
diff --git a/locales/zh-CN/common.json b/locales/zh-CN/common.json
index 961e3fa6eaf..8b575a36d7e 100644
--- a/locales/zh-CN/common.json
+++ b/locales/zh-CN/common.json
@@ -12,7 +12,9 @@
"agentViewAll.form.ordering": "排序",
"agentViewAll.form.showSidebarHidden": "显示已从我的侧边栏隐藏的助手",
"agentViewAll.groupBy.author": "作者",
+ "agentViewAll.groupBy.folder": "分组",
"agentViewAll.groupBy.label": "标签",
+ "agentViewAll.groupBy.noFolder": "未归入分组",
"agentViewAll.groupBy.noLabel": "无标签",
"agentViewAll.groupBy.none": "不分组",
"agentViewAll.groupBy.unknownAuthor": "未知作者",
@@ -378,16 +380,22 @@
"more": "更多",
"navPanel.agent": "助理",
"navPanel.bottomDivider": "下方条目锚定到底部",
+ "navPanel.browseAllAgents": "全部助理",
+ "navPanel.createPrivateFolder": "新建私人分组",
+ "navPanel.createWorkspaceAgent": "新建工作区助理",
"navPanel.customizeSidebar": "自定义侧边栏",
"navPanel.displayItems": "显示条目",
"navPanel.hidden": "已隐藏",
"navPanel.hideSection": "隐藏分组",
"navPanel.library": "资源库",
+ "navPanel.managePrivateFolders": "管理私人分组",
"navPanel.moveDown": "下移",
"navPanel.moveUp": "上移",
+ "navPanel.myPinned": "我的置顶",
"navPanel.openMenu": "打开菜单",
"navPanel.pinned": "已固定",
"navPanel.privateAgents": "私人",
+ "navPanel.privateTooltip": "私人 · 仅自己可见",
"navPanel.publicAgents": "工作区",
"navPanel.resetDefault": "恢复默认",
"navPanel.searchAgent": "搜索助理…",
@@ -396,8 +404,12 @@
"navPanel.searchResultEmpty": "暂无搜索结果",
"navPanel.shortcuts": "快捷入口",
"navPanel.show": "显示",
+ "navPanel.showLessTeamPinned": "收起",
+ "navPanel.showMoreTeamPinned": "再显示 {{count}} 个",
"navPanel.switcherAll": "全部",
"navPanel.switcherRecent": "最近",
+ "navPanel.teamPinned": "团队置顶",
+ "navPanel.teamPinnedHint": "由管理员为工作区所有成员置顶",
"navPanel.viewAllAgents": "查看全部",
"navPanel.visible": "显示中",
"new": "新",
diff --git a/packages/database/src/models/__tests__/agent.characterization.test.ts b/packages/database/src/models/__tests__/agent.characterization.test.ts
index 5ee57aac80f..3fa1af3c448 100644
--- a/packages/database/src/models/__tests__/agent.characterization.test.ts
+++ b/packages/database/src/models/__tests__/agent.characterization.test.ts
@@ -223,15 +223,21 @@ describe('AgentModel - characterization', () => {
expect(await model.getAgentAgencyConfig('foreign-slug')).toBeNull();
});
- it('getAgentVisibilityMeta returns slug, author and visibility', async () => {
+ it('getAgentVisibilityMeta returns pin, slug, author and visibility', async () => {
const model = new AgentModel(serverDB, userId);
expect(await model.getAgentVisibilityMeta('own-private')).toEqual({
+ pinned: false,
slug: 'own-private-slug',
userId,
visibility: 'private',
});
expect(await model.getAgentVisibilityMeta('foreign')).toBeNull();
+
+ // Publishing reads this flag to move a private pin onto the creator's
+ // personal pin list instead of turning it into a team pin.
+ await serverDB.update(agents).set({ pinned: true }).where(eq(agents.id, 'own-private'));
+ expect(await model.getAgentVisibilityMeta('own-private')).toMatchObject({ pinned: true });
});
it('resolveIdBySlug trims, and ignores blank or foreign slugs', async () => {
diff --git a/packages/database/src/models/__tests__/agent.duplicatePin.test.ts b/packages/database/src/models/__tests__/agent.duplicatePin.test.ts
new file mode 100644
index 00000000000..d668f2ffafa
--- /dev/null
+++ b/packages/database/src/models/__tests__/agent.duplicatePin.test.ts
@@ -0,0 +1,77 @@
+// @vitest-environment node
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../core/getTestDB';
+import { AgentGroupRepository } from '../../repositories/agentGroup';
+import { agents, chatGroups, users, workspaces } from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+import { AgentModel } from '../agent';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const userId = 'duplicate-pin-user';
+const workspaceId = 'duplicate-pin-ws';
+
+beforeEach(async () => {
+ await serverDB.delete(users);
+ await serverDB.insert(users).values({ id: userId });
+ await serverDB
+ .insert(workspaces)
+ .values({ id: workspaceId, name: 'ws', primaryOwnerId: userId, slug: workspaceId });
+});
+
+afterEach(async () => {
+ await serverDB.delete(chatGroups);
+ await serverDB.delete(agents);
+ await serverDB.delete(workspaces);
+ await serverDB.delete(users);
+});
+
+// In a workspace, `pinned` on a public row is the team pin only owners/admins
+// may set, so duplicating a team-pinned row must not mint another one.
+describe('duplicating a pinned row', () => {
+ it('keeps the pin on a personal agent copy', async () => {
+ await serverDB.insert(agents).values({ id: 'src', pinned: true, title: 'A', userId });
+
+ const result = await new AgentModel(serverDB, userId).duplicate('src');
+ const copy = await serverDB.query.agents.findFirst({ where: eq(agents.id, result!.agentId) });
+
+ expect(copy?.pinned).toBe(true);
+ });
+
+ it('drops the team pin on a workspace agent copy', async () => {
+ await serverDB.insert(agents).values({
+ id: 'src',
+ pinned: true,
+ title: 'A',
+ userId,
+ visibility: 'public',
+ workspaceId,
+ });
+
+ const result = await new AgentModel(serverDB, userId, workspaceId).duplicate('src');
+ const copy = await serverDB.query.agents.findFirst({ where: eq(agents.id, result!.agentId) });
+
+ expect(copy?.workspaceId).toBe(workspaceId);
+ expect(copy?.pinned).toBe(false);
+ });
+
+ it('drops the team pin on a workspace chat group copy', async () => {
+ await serverDB.insert(chatGroups).values({
+ id: 'grp',
+ pinned: true,
+ title: 'G',
+ userId,
+ visibility: 'public',
+ workspaceId,
+ });
+
+ const copy = await new AgentGroupRepository(serverDB, userId, workspaceId).duplicate('grp');
+ const row = await serverDB.query.chatGroups.findFirst({
+ where: eq(chatGroups.id, copy!.groupId),
+ });
+
+ expect(row?.pinned).toBe(false);
+ });
+});
diff --git a/packages/database/src/models/agent/create.ts b/packages/database/src/models/agent/create.ts
index e03d3c6547c..db5260174d9 100644
--- a/packages/database/src/models/agent/create.ts
+++ b/packages/database/src/models/agent/create.ts
@@ -147,7 +147,9 @@ export const duplicate = async (
openingMessage: sourceAgent.openingMessage,
openingQuestions: sourceAgent.openingQuestions,
params: sourceAgent.params,
- pinned: sourceAgent.pinned,
+ // In a workspace a public row's `pinned` is the owner/admin team pin, so a
+ // copy never inherits it — copying is not a way to create team pins.
+ pinned: ctx.workspaceId ? false : sourceAgent.pinned,
// Config
plugins: sourceAgent.plugins,
provider: sourceAgent.provider,
diff --git a/packages/database/src/models/agent/find.ts b/packages/database/src/models/agent/find.ts
index 64df463ca65..cca02b1e91e 100644
--- a/packages/database/src/models/agent/find.ts
+++ b/packages/database/src/models/agent/find.ts
@@ -210,15 +210,26 @@ export const getTopicShareSubject = async (
export const getAgentVisibilityMeta = async (
ctx: AgentModelContext,
id: string,
-): Promise<{ slug: string | null; userId: string; visibility: 'private' | 'public' } | null> => {
+): Promise<{
+ pinned: boolean;
+ slug: string | null;
+ userId: string;
+ visibility: 'private' | 'public';
+} | null> => {
const rows = await ctx.db
- .select({ slug: agents.slug, userId: agents.userId, visibility: agents.visibility })
+ .select({
+ pinned: agents.pinned,
+ slug: agents.slug,
+ userId: agents.userId,
+ visibility: agents.visibility,
+ })
.from(agents)
.where(and(eq(agents.id, id), ctx.ownership()))
.limit(1);
const row = rows[0];
if (!row) return null;
return {
+ pinned: !!row.pinned,
slug: row.slug,
userId: row.userId,
visibility: row.visibility,
diff --git a/packages/database/src/repositories/agentGroup/copy.ts b/packages/database/src/repositories/agentGroup/copy.ts
index 0c9e49f0a3d..80fc8934d17 100644
--- a/packages/database/src/repositories/agentGroup/copy.ts
+++ b/packages/database/src/repositories/agentGroup/copy.ts
@@ -101,7 +101,9 @@ export const duplicateGroup = async (
// public item's folder only against public folders, so the copy would
// land in Ungrouped rather than beside its source.
visibility: sourceGroup.visibility,
- pinned: sourceGroup.pinned,
+ // In a workspace `pinned` on a public group is the owner/admin team pin;
+ // a copy never inherits it.
+ pinned: scope.workspaceId ? false : sourceGroup.pinned,
title: newTitle || (sourceGroup.title ? `${sourceGroup.title} (Copy)` : 'Copy'),
userId: scope.userId,
workspaceId: scope.workspaceId ?? null,
@@ -349,7 +351,8 @@ export const copyGroupToWorkspace = async (
content: sourceGroup.content,
description: sourceGroup.description,
editorData: sourceGroup.editorData,
- pinned: sourceGroup.pinned,
+ // A workspace copy never inherits a pin: there `pinned` is the team pin.
+ pinned: targetWorkspaceId ? false : sourceGroup.pinned,
title: options.newTitle || (sourceGroup.title ? `${sourceGroup.title} (Copy)` : 'Copy'),
userId: targetUserId,
...(targetVisibility ? { visibility: targetVisibility } : {}),
diff --git a/packages/database/src/repositories/agentGroup/utils.ts b/packages/database/src/repositories/agentGroup/utils.ts
index 7be5d4956a4..7ab8b6c666e 100644
--- a/packages/database/src/repositories/agentGroup/utils.ts
+++ b/packages/database/src/repositories/agentGroup/utils.ts
@@ -18,7 +18,8 @@ export const buildCopiedAgent = (
openingMessage: source?.openingMessage,
openingQuestions: source?.openingQuestions,
params: source?.params,
- pinned: source?.pinned,
+ // In a workspace `pinned` is the owner/admin team pin; copies never inherit it.
+ pinned: targetWorkspaceId ? false : source?.pinned,
plugins: source?.plugins,
provider: source?.provider,
systemRole: source?.systemRole,
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index 6a378c0496c..27eba043917 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -1654,6 +1654,9 @@ export default {
'textSelection.title': 'Message selection',
'pin': 'Pin',
'pinOff': 'Unpin',
+ 'pinForTeam': 'Pin for team',
+ 'pinForTeamForbidden': 'Only workspace owners and admins can change team pins',
+ 'unpinForTeam': 'Unpin for team',
'rag.referenceChunks': 'Reference Source',
'rag.userQuery.actions.delete': 'Delete Query Rewrite',
'rag.userQuery.actions.regenerate': 'Regenerate Query',
diff --git a/packages/locales/src/default/common.ts b/packages/locales/src/default/common.ts
index 995fb116882..5d90ef21fa4 100644
--- a/packages/locales/src/default/common.ts
+++ b/packages/locales/src/default/common.ts
@@ -1,6 +1,8 @@
export default {
'about': 'About',
'advanceSettings': 'Advanced Settings',
+ 'agentViewAll.groupBy.folder': 'Category',
+ 'agentViewAll.groupBy.noFolder': 'No category',
'alert.cloud.action': 'Try now',
'alert.cloud.desc':
'All registered users get ${{credit}} of free usage per month—no setup needed. Includes global cloud sync and advanced web search.',
@@ -56,6 +58,7 @@ export default {
'Current topic is not saved, please save it first to use subtopic feature',
'forkRequiresSavedTopic': 'Current topic is not saved. Save it first to fork a new topic',
'forkTopic': 'Continue in new topic',
+ 'navPanel.browseAllAgents': 'All agents',
'supportAgent.troubleshoot.question': 'This message failed. Please help me troubleshoot it.',
'viewExecutionDetails': 'View execution details',
'cancel': 'Cancel',
@@ -463,6 +466,15 @@ export default {
'taskNav.all': 'All tasks',
'taskNav.noProjects': 'No projects yet',
'navPanel.agent': 'Agents',
+ 'navPanel.createPrivateFolder': 'New private category',
+ 'navPanel.createWorkspaceAgent': 'New workspace agent',
+ 'navPanel.managePrivateFolders': 'Manage private categories',
+ 'navPanel.myPinned': 'Pinned',
+ 'navPanel.privateTooltip': 'Private · only you can see this',
+ 'navPanel.showLessTeamPinned': 'Show less',
+ 'navPanel.showMoreTeamPinned': 'Show {{count}} more',
+ 'navPanel.teamPinned': 'Pinned for team',
+ 'navPanel.teamPinnedHint': 'Pinned by admins for everyone in this workspace',
'navPanel.bottomDivider': 'Items below anchor to bottom',
'navPanel.customizeSidebar': 'Customize Sidebar',
'navPanel.openMenu': 'Open menu',
diff --git a/packages/types/src/user/preference.ts b/packages/types/src/user/preference.ts
index 329f601865f..1c6658ae538 100644
--- a/packages/types/src/user/preference.ts
+++ b/packages/types/src/user/preference.ts
@@ -112,6 +112,16 @@ export interface WorkspaceUserPreference {
* section, its items included — they stay reachable from the agents list.
*/
sidebarHiddenGroupIds?: string[];
+ /**
+ * Agents / chat groups this member pinned for themselves in the merged
+ * workspace "Agents" section (newest first). Personal: it never changes
+ * another member's sidebar. Team pins — the ones every member sees — stay on
+ * the shared `agents.pinned` / `chat_groups.pinned` columns, which only
+ * workspace owners and admins may write for public rows. A private row's
+ * own `pinned` column is read as this member's pin too, since only its
+ * creator can see it.
+ */
+ sidebarPinnedItemIds?: string[];
/**
* Per-member pins for sidebar items.
*
diff --git a/src/features/AgentViewAll/AgentViewAllPage.tsx b/src/features/AgentViewAll/AgentViewAllPage.tsx
index cffa2244d48..eaeb6a774f5 100644
--- a/src/features/AgentViewAll/AgentViewAllPage.tsx
+++ b/src/features/AgentViewAll/AgentViewAllPage.tsx
@@ -33,6 +33,7 @@ import {
AgentViewAllSidebarSectionSkeleton,
} from '@/components/Skeleton/AgentViewAll';
import { useKeepSidebarGroupsListed } from '@/features/HomeSidebar/Body/Agent/List/useAgentList';
+import { useWorkspaceSidebarItemIds } from '@/features/HomeSidebar/Body/Agent/List/useWorkspaceAgentSections';
import { AgentModalProvider } from '@/features/HomeSidebar/Body/Agent/ModalProvider';
import { useSidebarItemVisibility } from '@/features/HomeSidebar/Body/Agent/useSidebarItemVisibility';
import { useCreateMenuItems } from '@/features/HomeSidebar/hooks';
@@ -51,6 +52,7 @@ import { useUserStore } from '@/store/user';
import AgentCard, { AgentCardGrid } from './AgentCard';
import AgentRow, { type AgentRowAuthor } from './AgentRow';
import { flattenAgentBuckets } from './flattenBuckets';
+import { groupItemsByFolder } from './groupByFolder';
import ListConfig from './ListConfig';
import { type AgentListViewOptions, normalizeAgentListViewOptions } from './listViewOptions';
import SidebarAgentsSection from './SidebarAgentsSection';
@@ -172,6 +174,8 @@ const AgentViewAllPage = memo(() => {
[setSearchParams],
);
const [keyword, setKeyword] = useState('');
+ // While searching, sections open and empty folders drop out so matches show.
+ const searching = keyword.trim().length > 0;
// Card vs list rendering — persisted in systemStatus so the page reopens
// in the last chosen mode (same mechanism as imageTopicViewMode & friends).
@@ -186,15 +190,25 @@ const AgentViewAllPage = memo(() => {
// view mode so the page keeps its display config (same as taskListViewOptions).
const rawViewOptions = useGlobalStore(systemStatusSelectors.agentListViewOptions);
const viewOptions = useMemo(
- () => normalizeAgentListViewOptions(rawViewOptions),
- [rawViewOptions],
+ () => normalizeAgentListViewOptions(rawViewOptions, activeWorkspaceId ? 'folder' : 'none'),
+ [activeWorkspaceId, rawViewOptions],
);
const setViewOptions = useCallback(
(updater: (prev: AgentListViewOptions) => AgentListViewOptions) => {
const next = normalizeAgentListViewOptions(updater(viewOptions));
- updateSystemStatus({ agentListViewOptions: next }, 'updateAgentListViewOptions');
+ // The setting is shared by workspace and personal mode, so keep the
+ // grouping unset until the member actually picks one; otherwise the
+ // workspace's folder default would leak into personal mode.
+ const keepDefaultGroupBy =
+ rawViewOptions?.groupBy === undefined && next.groupBy === viewOptions.groupBy;
+ updateSystemStatus(
+ {
+ agentListViewOptions: keepDefaultGroupBy ? { ...next, groupBy: undefined } : next,
+ },
+ 'updateAgentListViewOptions',
+ );
},
- [updateSystemStatus, viewOptions],
+ [rawViewOptions?.groupBy, updateSystemStatus, viewOptions],
);
// The sidebar usually owns these fetches, but this page must survive a
@@ -217,6 +231,15 @@ const AgentViewAllPage = memo(() => {
const { isSidebarItemVisible, setSidebarItemVisible } = useSidebarItemVisibility();
const keepGroups = useKeepSidebarGroupsListed();
+ // In a workspace the sidebar lists only what the member pinned, created,
+ // used recently or added; ask the sidebar's own layout instead of the
+ // plain hide list.
+ const workspaceSidebarIds = useWorkspaceSidebarItemIds();
+ const isListed = useCallback(
+ (item: SidebarAgentItem) =>
+ workspaceSidebarIds ? workspaceSidebarIds.listed.has(item.id) : isSidebarItemVisible(item),
+ [isSidebarItemVisible, workspaceSidebarIds],
+ );
const workspaceItems = useMemo(
() => flattenAgentBuckets(pinnedAgents, agentGroups, ungroupedAgents),
@@ -238,29 +261,34 @@ const AgentViewAllPage = memo(() => {
// flattened lists: hiding a Category removes its whole section from the
// sidebar, so its agents are not "in sidebar" either. The page's own list
// deliberately keeps showing them — hiding is a sidebar-only preference.
- const inSidebar = [
- ...flattenAgentBuckets(pinnedAgents, keepGroups(agentGroups), ungroupedAgents),
- ...flattenAgentBuckets(
- privatePinnedAgents,
- keepGroups(privateAgentGroups),
- privateUngroupedAgents,
- ),
- ];
+ const inSidebar = workspaceSidebarIds
+ ? [...workspaceItems, ...privateItems]
+ : [
+ ...flattenAgentBuckets(pinnedAgents, keepGroups(agentGroups), ungroupedAgents),
+ ...flattenAgentBuckets(
+ privatePinnedAgents,
+ keepGroups(privateAgentGroups),
+ privateUngroupedAgents,
+ ),
+ ];
const seen = new Set<string>();
return inSidebar.filter((item) => {
- if (seen.has(item.id) || !isSidebarItemVisible(item)) return false;
+ if (seen.has(item.id) || !isListed(item)) return false;
seen.add(item.id);
return true;
});
}, [
agentGroups,
- isSidebarItemVisible,
+ isListed,
keepGroups,
pinnedAgents,
privateAgentGroups,
+ privateItems,
privatePinnedAgents,
privateUngroupedAgents,
ungroupedAgents,
+ workspaceItems,
+ workspaceSidebarIds,
]);
// Author info (column, grouping, sorting) only means something on the
@@ -293,9 +321,9 @@ const AgentViewAllPage = memo(() => {
// searching narrows the list below, it doesn't shrink the buckets.
const bucketCounts = useMemo(() => {
const count = (list: SidebarAgentItem[]) =>
- showSidebarHidden ? list.length : list.filter(isSidebarItemVisible).length;
+ showSidebarHidden ? list.length : list.filter(isListed).length;
return { private: count(privateItems), workspace: count(workspaceItems) };
- }, [workspaceItems, privateItems, showSidebarHidden, isSidebarItemVisible]);
+ }, [workspaceItems, privateItems, showSidebarHidden, isListed]);
// Label grouping works on every tab (labels exist in personal mode too);
// author grouping only makes sense where the author column shows.
@@ -324,7 +352,7 @@ const AgentViewAllPage = memo(() => {
: items;
if (!showSidebarHidden) {
- matched = matched.filter(isSidebarItemVisible);
+ matched = matched.filter(isListed);
}
const authorName = (item: SidebarAgentItem) =>
@@ -339,15 +367,7 @@ const AgentViewAllPage = memo(() => {
if (orderBy === 'author') return direction * authorName(a).localeCompare(authorName(b));
return direction * (dayjs(a.updatedAt).valueOf() - dayjs(b.updatedAt).valueOf());
});
- }, [
- items,
- keyword,
- orderBy,
- orderDirection,
- showSidebarHidden,
- isSidebarItemVisible,
- authorByUserId,
- ]);
+ }, [items, keyword, orderBy, orderDirection, showSidebarHidden, isListed, authorByUserId]);
// Author sections (workspace tab only — every private item is the viewer's
// own, so author buckets would be a single redundant group): items are
@@ -376,6 +396,25 @@ const AgentViewAllPage = memo(() => {
return groups.sort((a, b) => a.label.localeCompare(b.label));
}
+ if (groupBy === 'folder') {
+ const folders = segment === 'private' ? privateAgentGroups : agentGroups;
+ const sections = groupItemsByFolder(
+ filteredItems,
+ activeWorkspaceId ? folders : [...agentGroups, ...privateAgentGroups],
+ t('agentViewAll.groupBy.noFolder'),
+ ).filter((section) => !searching || section.items.length > 0);
+ // Without any folder the grouping would be a single bucket: stay flat.
+ if (sections.every((section) => !section.folder)) return null;
+
+ return sections.map((section) => ({
+ avatar: null as string | null,
+ color: undefined as string | null | undefined,
+ items: section.items,
+ key: section.key,
+ label: section.label,
+ }));
+ }
+
if (groupBy === 'label') {
// Label sections: an agent carrying several labels appears once per
// label (mirrors Linear); unlabeled items collect in a trailing bucket.
@@ -417,7 +456,17 @@ const AgentViewAllPage = memo(() => {
}
return null;
- }, [activeWorkspaceId, groupBy, segment, filteredItems, authorByUserId, t]);
+ }, [
+ activeWorkspaceId,
+ agentGroups,
+ groupBy,
+ privateAgentGroups,
+ searching,
+ segment,
+ filteredItems,
+ authorByUserId,
+ t,
+ ]);
// Group collapse state — groups default to COLLAPSED (mirrors Linear), so
// the EXPANDED keys are what persists (systemStatus): a reload keeps opened
@@ -440,7 +489,7 @@ const AgentViewAllPage = memo(() => {
const handleToggleSidebar = useCallback(
async (item: SidebarAgentItem) => {
try {
- await setSidebarItemVisible(item.id, !isSidebarItemVisible(item));
+ await setSidebarItemVisible(item.id, !isListed(item));
} catch (error) {
// Personal mode writes the preference optimistically and never rolls
// back, workspace mode rolls back silently — either way the row's
@@ -449,7 +498,7 @@ const AgentViewAllPage = memo(() => {
toast.error(t('operationFailed'));
}
},
- [isSidebarItemVisible, setSidebarItemVisible, t],
+ [isListed, setSidebarItemVisible, t],
);
// The `im_layout` rail has no agent sidebar, so its "in sidebar" curation
// (the section and every per-item toggle) does not apply there.
@@ -462,11 +511,11 @@ const AgentViewAllPage = memo(() => {
item={item}
key={item.id}
owner={showAuthor && item.userId ? authorByUserId.get(item.userId) : undefined}
- sidebarHidden={!isSidebarItemVisible(item)}
- onToggleSidebar={toggleSidebar}
+ sidebarHidden={!isListed(item)}
+ onToggleSidebar={workspaceSidebarIds?.fixed.has(item.id) ? undefined : toggleSidebar}
/>
),
- [showAuthor, authorByUserId, toggleSidebar, isSidebarItemVisible],
+ [showAuthor, authorByUserId, toggleSidebar, isListed, workspaceSidebarIds],
);
const renderRow = useCallback(
@@ -476,11 +525,11 @@ const AgentViewAllPage = memo(() => {
item={item}
key={item.id}
showAuthor={showAuthor}
- sidebarHidden={!isSidebarItemVisible(item)}
- onToggleSidebar={toggleSidebar}
+ sidebarHidden={!isListed(item)}
+ onToggleSidebar={workspaceSidebarIds?.fixed.has(item.id) ? undefined : toggleSidebar}
/>
),
- [showAuthor, authorByUserId, toggleSidebar, isSidebarItemVisible],
+ [showAuthor, authorByUserId, toggleSidebar, isListed, workspaceSidebarIds],
);
const { allowed: canCreate, reason: createBlockedReason } = usePermission('create_content');
@@ -547,7 +596,11 @@ const AgentViewAllPage = memo(() => {
>
{!imLayout && !isInit && !keyword.trim() && <AgentViewAllSidebarSectionSkeleton />}
{!imLayout && isInit && !keyword.trim() && sidebarItems.length > 0 && (
- <SidebarAgentsSection items={sidebarItems} onToggleSidebar={handleToggleSidebar} />
+ <SidebarAgentsSection
+ fixedIds={workspaceSidebarIds?.fixed}
+ items={sidebarItems}
+ onToggleSidebar={handleToggleSidebar}
+ />
)}
<Flexbox horizontal align={'center'} gap={12} justify={'space-between'}>
{/* The workspace/private split only exists inside a workspace;
@@ -625,7 +678,7 @@ const AgentViewAllPage = memo(() => {
groupedItems ? (
<Flexbox gap={8}>
{groupedItems.map((group, index) => {
- const collapsed = !expandedGroupSet.has(group.key);
+ const collapsed = !searching && !expandedGroupSet.has(group.key);
return (
<Flexbox gap={12} key={group.key}>
<GroupHeader
@@ -651,7 +704,7 @@ const AgentViewAllPage = memo(() => {
<Flexbox gap={groupedItems ? 8 : 2}>
{groupedItems
? groupedItems.map((group, index) => {
- const collapsed = !expandedGroupSet.has(group.key);
+ const collapsed = !searching && !expandedGroupSet.has(group.key);
return (
<Flexbox gap={2} key={group.key}>
<GroupHeader
diff --git a/src/features/AgentViewAll/ItemActions.tsx b/src/features/AgentViewAll/ItemActions.tsx
index b8753b91cbe..649ff8c8e81 100644
--- a/src/features/AgentViewAll/ItemActions.tsx
+++ b/src/features/AgentViewAll/ItemActions.tsx
@@ -167,7 +167,7 @@ AgentItemActions.displayName = 'AgentItemActions';
const GroupItemActions = memo<ItemActionsProps>(({ anchor, item, ...rest }) => {
const { t } = useTranslation('common');
- const { avatar, backgroundColor, description, id, pinned, title, userId } = item;
+ const { avatar, backgroundColor, description, id, pinned, title, userId, visibility } = item;
const customAvatar = typeof avatar === 'string' ? avatar : undefined;
const memberAvatars = Array.isArray(avatar) ? avatar : [];
@@ -182,6 +182,7 @@ const GroupItemActions = memo<ItemActionsProps>(({ anchor, item, ...rest }) => {
pinned: pinned ?? false,
title: title || t('agentViewAll.untitled'),
userId,
+ visibility,
});
return <ActionsDropdown getMenuItems={getGroupMenu} item={item} {...rest} />;
diff --git a/src/features/AgentViewAll/ListConfig.tsx b/src/features/AgentViewAll/ListConfig.tsx
index 660858132f5..6bd30b4ceee 100644
--- a/src/features/AgentViewAll/ListConfig.tsx
+++ b/src/features/AgentViewAll/ListConfig.tsx
@@ -60,6 +60,7 @@ const ListConfig = memo<ListConfigProps>(
...(showAuthor
? [{ label: t('agentViewAll.groupBy.author'), value: 'author' as const }]
: []),
+ { label: t('agentViewAll.groupBy.folder'), value: 'folder' as const },
{ label: t('agentViewAll.groupBy.label'), value: 'label' },
],
[showAuthor, t],
diff --git a/src/features/AgentViewAll/SidebarAgentsSection.tsx b/src/features/AgentViewAll/SidebarAgentsSection.tsx
index 05e017ee9fb..0d5cd332940 100644
--- a/src/features/AgentViewAll/SidebarAgentsSection.tsx
+++ b/src/features/AgentViewAll/SidebarAgentsSection.tsx
@@ -170,64 +170,73 @@ const SidebarMiniCard = memo<SidebarMiniCardProps>(({ item, onToggleSidebar }) =
SidebarMiniCard.displayName = 'SidebarMiniCard';
interface SidebarAgentsSectionProps {
+ /** Rows pinned for the team: fixed in the sidebar, so no remove toggle. */
+ fixedIds?: ReadonlySet<string>;
items: SidebarAgentItem[];
onToggleSidebar?: (item: SidebarAgentItem) => void;
}
-const SidebarAgentsSection = memo<SidebarAgentsSectionProps>(({ items, onToggleSidebar }) => {
- const { t } = useTranslation('common');
- const collapsed = useGlobalStore(systemStatusSelectors.agentListSidebarSectionCollapsed);
- const updateSystemStatus = useGlobalStore((s) => s.updateSystemStatus);
- const toggle = useCallback(
- () =>
- updateSystemStatus(
- { agentListSidebarSectionCollapsed: !collapsed },
- 'toggleAgentListSidebarSection',
- ),
- [collapsed, updateSystemStatus],
- );
-
- return (
- <Flexbox className={styles.container} gap={12}>
- <Flexbox
- horizontal
- align={'center'}
- className={styles.header}
- gap={8}
- justify={'space-between'}
- onClick={toggle}
- >
- <Flexbox horizontal align={'center'} gap={8}>
- <Text fontSize={13} weight={500}>
- {t('agentViewAll.sidebarSection.title')}
- </Text>
- <Text fontSize={12} type={'secondary'}>
- {items.length}
- </Text>
- </Flexbox>
- <Flexbox horizontal align={'center'} gap={4}>
- <Text fontSize={12} type={'secondary'}>
- {collapsed
- ? t('agentViewAll.sidebarSection.expand')
- : t('agentViewAll.sidebarSection.collapse')}
- </Text>
- <Icon
- color={cssVar.colorTextSecondary}
- icon={collapsed ? ChevronDownIcon : ChevronUpIcon}
- size={14}
- />
+const SidebarAgentsSection = memo<SidebarAgentsSectionProps>(
+ ({ fixedIds, items, onToggleSidebar }) => {
+ const { t } = useTranslation('common');
+ const collapsed = useGlobalStore(systemStatusSelectors.agentListSidebarSectionCollapsed);
+ const updateSystemStatus = useGlobalStore((s) => s.updateSystemStatus);
+ const toggle = useCallback(
+ () =>
+ updateSystemStatus(
+ { agentListSidebarSectionCollapsed: !collapsed },
+ 'toggleAgentListSidebarSection',
+ ),
+ [collapsed, updateSystemStatus],
+ );
+
+ return (
+ <Flexbox className={styles.container} gap={12}>
+ <Flexbox
+ horizontal
+ align={'center'}
+ className={styles.header}
+ gap={8}
+ justify={'space-between'}
+ onClick={toggle}
+ >
+ <Flexbox horizontal align={'center'} gap={8}>
+ <Text fontSize={13} weight={500}>
+ {t('agentViewAll.sidebarSection.title')}
+ </Text>
+ <Text fontSize={12} type={'secondary'}>
+ {items.length}
+ </Text>
+ </Flexbox>
+ <Flexbox horizontal align={'center'} gap={4}>
+ <Text fontSize={12} type={'secondary'}>
+ {collapsed
+ ? t('agentViewAll.sidebarSection.expand')
+ : t('agentViewAll.sidebarSection.collapse')}
+ </Text>
+ <Icon
+ color={cssVar.colorTextSecondary}
+ icon={collapsed ? ChevronDownIcon : ChevronUpIcon}
+ size={14}
+ />
+ </Flexbox>
</Flexbox>
+ {!collapsed && (
+ <div className={styles.grid}>
+ {items.map((item) => (
+ <SidebarMiniCard
+ item={item}
+ key={item.id}
+ // Team pins are fixed for every member: nothing to remove.
+ onToggleSidebar={fixedIds?.has(item.id) ? undefined : onToggleSidebar}
+ />
+ ))}
+ </div>
+ )}
</Flexbox>
- {!collapsed && (
- <div className={styles.grid}>
- {items.map((item) => (
- <SidebarMiniCard item={item} key={item.id} onToggleSidebar={onToggleSidebar} />
- ))}
- </div>
- )}
- </Flexbox>
- );
-});
+ );
+ },
+);
SidebarAgentsSection.displayName = 'SidebarAgentsSection';
diff --git a/src/features/AgentViewAll/groupByFolder.test.ts b/src/features/AgentViewAll/groupByFolder.test.ts
new file mode 100644
index 00000000000..c1b75206e6e
--- /dev/null
+++ b/src/features/AgentViewAll/groupByFolder.test.ts
@@ -0,0 +1,43 @@
+import type { SidebarAgentItem, SidebarGroup } from '@lobechat/types';
+import { describe, expect, it } from 'vitest';
+
+import { groupItemsByFolder } from './groupByFolder';
+
+const item = (id: string, groupId?: string) =>
+ ({
+ groupId,
+ id,
+ pinned: false,
+ title: id,
+ type: 'agent',
+ updatedAt: new Date(),
+ }) as SidebarAgentItem;
+const folder = (id: string) => ({ id, items: [], name: id.toUpperCase(), sort: 0 }) as SidebarGroup;
+
+describe('groupItemsByFolder', () => {
+ it('buckets rows by folder in folder order, loose rows last', () => {
+ const sections = groupItemsByFolder(
+ [item('a', 'f2'), item('b'), item('c', 'f1'), item('d', 'f2')],
+ [folder('f1'), folder('f2')],
+ 'No folder',
+ );
+
+ expect(sections.map((s) => [s.key, s.label, s.items.map((i) => i.id)])).toEqual([
+ ['folder:f1', 'F1', ['c']],
+ ['folder:f2', 'F2', ['a', 'd']],
+ ['folder:none', 'No folder', ['b']],
+ ]);
+ });
+
+ it('keeps empty folders in the shared catalogue', () => {
+ const sections = groupItemsByFolder([], [folder('empty')], 'No folder');
+
+ expect(sections.map((s) => s.key)).toEqual(['folder:empty']);
+ });
+
+ it('treats a row pointing at an unknown folder as loose', () => {
+ const sections = groupItemsByFolder([item('a', 'gone')], [], 'No folder');
+
+ expect(sections.map((s) => s.key)).toEqual(['folder:none']);
+ });
+});
diff --git a/src/features/AgentViewAll/groupByFolder.ts b/src/features/AgentViewAll/groupByFolder.ts
new file mode 100644
index 00000000000..1352e20f7d8
--- /dev/null
+++ b/src/features/AgentViewAll/groupByFolder.ts
@@ -0,0 +1,45 @@
+import type { SidebarAgentItem, SidebarGroup } from '@lobechat/types';
+
+export interface FolderSection {
+ /** The folder itself; absent for the trailing "No folder" bucket. */
+ folder?: SidebarGroup;
+ items: SidebarAgentItem[];
+ key: string;
+ label: string;
+}
+
+/**
+ * Bucket the (already filtered and sorted) page items by their sidebar folder.
+ * Folders keep their shared order and stay listed even when empty, so the
+ * shared catalogue reads the same for everyone; rows outside any folder
+ * collect in a trailing bucket.
+ */
+export const groupItemsByFolder = (
+ items: SidebarAgentItem[],
+ folders: SidebarGroup[],
+ noFolderLabel: string,
+): FolderSection[] => {
+ const known = new Set(folders.map((folder) => folder.id));
+ const byFolder = new Map<string, SidebarAgentItem[]>();
+ const loose: SidebarAgentItem[] = [];
+
+ for (const item of items) {
+ if (item.groupId && known.has(item.groupId)) {
+ const bucket = byFolder.get(item.groupId);
+ if (bucket) bucket.push(item);
+ else byFolder.set(item.groupId, [item]);
+ } else {
+ loose.push(item);
+ }
+ }
+
+ const sections: FolderSection[] = folders.map((folder) => ({
+ folder,
+ items: byFolder.get(folder.id) ?? [],
+ key: `folder:${folder.id}`,
+ label: folder.name,
+ }));
+ if (loose.length > 0) sections.push({ items: loose, key: 'folder:none', label: noFolderLabel });
+
+ return sections;
+};
diff --git a/src/features/AgentViewAll/listViewOptions.ts b/src/features/AgentViewAll/listViewOptions.ts
index 8212b562fed..08121efbf0c 100644
--- a/src/features/AgentViewAll/listViewOptions.ts
+++ b/src/features/AgentViewAll/listViewOptions.ts
@@ -1,4 +1,4 @@
-export type AgentGroupBy = 'author' | 'label' | 'none';
+export type AgentGroupBy = 'author' | 'folder' | 'label' | 'none';
export type AgentOrderBy = 'author' | 'title' | 'updatedAt';
export type AgentOrderDirection = 'asc' | 'desc';
@@ -17,18 +17,24 @@ export const DEFAULT_AGENT_LIST_VIEW_OPTIONS: AgentListViewOptions = {
showSidebarHidden: true,
};
-const AGENT_GROUP_BY_SET = new Set<AgentGroupBy>(['author', 'label', 'none']);
+const AGENT_GROUP_BY_SET = new Set<AgentGroupBy>(['author', 'folder', 'label', 'none']);
const AGENT_ORDER_BY_SET = new Set<AgentOrderBy>(['author', 'title', 'updatedAt']);
const AGENT_ORDER_DIRECTION_SET = new Set<AgentOrderDirection>(['asc', 'desc']);
+/**
+ * @param defaultGroupBy - grouping used until the member picks one. A
+ * workspace browses its shared folders here (its sidebar lists only pinned
+ * ones), so it opens grouped by folder; personal mode keeps a flat list.
+ */
export const normalizeAgentListViewOptions = (
value?: Partial<AgentListViewOptions> | null,
+ defaultGroupBy: AgentGroupBy = DEFAULT_AGENT_LIST_VIEW_OPTIONS.groupBy,
): AgentListViewOptions => {
const next = value ?? {};
return {
groupBy: AGENT_GROUP_BY_SET.has(next.groupBy as AgentGroupBy)
? (next.groupBy as AgentGroupBy)
- : DEFAULT_AGENT_LIST_VIEW_OPTIONS.groupBy,
+ : defaultGroupBy,
orderBy: AGENT_ORDER_BY_SET.has(next.orderBy as AgentOrderBy)
? (next.orderBy as AgentOrderBy)
: DEFAULT_AGENT_LIST_VIEW_OPTIONS.orderBy,
diff --git a/src/features/HomeSidebar/Body/Agent/List/AgentGroupItem/index.tsx b/src/features/HomeSidebar/Body/Agent/List/AgentGroupItem/index.tsx
index 73c35f8dff6..608ee28bdc1 100644
--- a/src/features/HomeSidebar/Body/Agent/List/AgentGroupItem/index.tsx
+++ b/src/features/HomeSidebar/Body/Agent/List/AgentGroupItem/index.tsx
@@ -12,7 +12,9 @@ import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
import { useGlobalStore } from '@/store/global';
import { useHomeStore } from '@/store/home';
+import { useSidebarPinState } from '../../useSidebarPinState';
import Actions from '../Item/Actions';
+import PrivateLockIcon from '../PrivateLockIcon';
import { useGroupDropdownMenu } from './useDropdownMenu';
interface GroupItemProps {
@@ -23,9 +25,11 @@ interface GroupItemProps {
}
const GroupItem = memo<GroupItemProps>(({ item, style, className, onNavigate }) => {
- const { id, avatar, backgroundColor, description, title, pinned, userId } = item;
+ const { id, avatar, backgroundColor, description, title, pinned, userId, visibility } = item;
const { t } = useTranslation('chat');
const [anchor, setAnchor] = useState<HTMLElement | null>(null);
+ const { isMyPinned, isPrivate, isTeamPinned } = useSidebarPinState({ id, pinned, visibility });
+ const showPinIcon = isTeamPinned || isMyPinned;
const openAgentInNewWindow = useGlobalStore((s) => s.openAgentInNewWindow);
@@ -70,13 +74,19 @@ const GroupItem = memo<GroupItemProps>(({ item, style, className, onNavigate })
[id, openAgentInNewWindow],
);
- // Memoize pin icon
+ // The lock sits with the pin in the fixed trailing slot so a long title
+ // can't truncate it out of view.
const pinIcon = useMemo(
() =>
- pinned ? (
- <ActionIcon icon={PinIcon} size={12} style={{ opacity: 0.5, pointerEvents: 'none' }} />
+ showPinIcon || isPrivate ? (
+ <>
+ {isPrivate && <PrivateLockIcon />}
+ {showPinIcon && (
+ <ActionIcon icon={PinIcon} size={12} style={{ opacity: 0.5, pointerEvents: 'none' }} />
+ )}
+ </>
) : undefined,
- [pinned],
+ [isPrivate, showPinIcon],
);
// Memoize avatar icon (show loader when updating)
@@ -113,6 +123,7 @@ const GroupItem = memo<GroupItemProps>(({ item, style, className, onNavigate })
pinned: pinned ?? false,
title: displayTitle,
userId,
+ visibility,
});
return (
diff --git a/src/features/HomeSidebar/Body/Agent/List/AgentGroupItem/useDropdownMenu.tsx b/src/features/HomeSidebar/Body/Agent/List/AgentGroupItem/useDropdownMenu.tsx
index 0fd16372413..1c817e0a48c 100644
--- a/src/features/HomeSidebar/Body/Agent/List/AgentGroupItem/useDropdownMenu.tsx
+++ b/src/features/HomeSidebar/Body/Agent/List/AgentGroupItem/useDropdownMenu.tsx
@@ -1,9 +1,11 @@
+import type { SidebarVisibility } from '@lobechat/types';
import { type DropdownItem } from '@lobehub/ui';
import { confirmModal, Icon, toast } from '@lobehub/ui';
import { LucideCopy, Pen, PictureInPicture2Icon, Pin, PinOff, Trash } from 'lucide-react';
import { useMemo } from 'react';
import { useTranslation } from 'react-i18next';
+import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
import { useAgentGroupTransferMenuItem } from '@/business/client/hooks/useAgentGroupTransferMenuItem';
import { useAgentGroupTransferToMemberMenuItem } from '@/business/client/hooks/useAgentGroupTransferToMemberMenuItem';
import { openEditingPopover } from '@/features/EditingPopover/store';
@@ -14,6 +16,8 @@ import { useGlobalStore } from '@/store/global';
import { useHomeStore } from '@/store/home';
import { getDeleteErrorMessageKey } from '@/utils/forbiddenError';
+import { useSidebarPinMenuItems } from '../../useSidebarPinMenuItems';
+
interface UseGroupDropdownMenuParams {
anchor: HTMLElement | null;
avatar?: string;
@@ -24,6 +28,7 @@ interface UseGroupDropdownMenuParams {
pinned: boolean;
title: string;
userId?: string | null;
+ visibility?: SidebarVisibility;
}
export const useGroupDropdownMenu = ({
@@ -36,6 +41,7 @@ export const useGroupDropdownMenu = ({
pinned,
title,
userId,
+ visibility,
}: UseGroupDropdownMenuParams): (() => DropdownItem[]) => {
const { t } = useTranslation(['chat', 'common']);
@@ -63,18 +69,33 @@ export const useGroupDropdownMenu = ({
title,
});
+ const activeWorkspaceId = useActiveWorkspaceId();
+ // Workspace: personal pin for every member + owner/admin team pin on public
+ // groups. Personal mode keeps the single column-backed pin.
+ const { menuItems: workspacePinItems } = useSidebarPinMenuItems({
+ id,
+ pinned,
+ type: 'group',
+ visibility,
+ });
+
return useMemo(
() => () =>
[
+ ...(activeWorkspaceId ? workspacePinItems : []),
...(canConfigure
? [
- {
- icon: <Icon icon={pinned ? PinOff : Pin} />,
- key: 'pin',
- label: t(pinned ? 'pinOff' : 'pin'),
- onClick: () => pinAgentGroup(id, !pinned),
- sfSymbol: pinned ? 'pin.slash' : 'pin',
- },
+ ...(activeWorkspaceId
+ ? []
+ : [
+ {
+ icon: <Icon icon={pinned ? PinOff : Pin} />,
+ key: 'pin',
+ label: t(pinned ? 'pinOff' : 'pin'),
+ onClick: () => pinAgentGroup(id, !pinned),
+ sfSymbol: pinned ? 'pin.slash' : 'pin',
+ },
+ ]),
{
icon: <Icon icon={Pen} />,
key: 'rename',
@@ -156,6 +177,8 @@ export const useGroupDropdownMenu = ({
: []),
] as DropdownItem[],
[
+ activeWorkspaceId,
+ workspacePinItems,
anchor,
avatar,
backgroundColor,
diff --git a/src/features/HomeSidebar/Body/Agent/List/AgentItem/index.tsx b/src/features/HomeSidebar/Body/Agent/List/AgentItem/index.tsx
index efba609e10d..735c7e1f652 100644
--- a/src/features/HomeSidebar/Body/Agent/List/AgentItem/index.tsx
+++ b/src/features/HomeSidebar/Body/Agent/List/AgentItem/index.tsx
@@ -18,7 +18,9 @@ import { useGlobalStore } from '@/store/global';
import { useHomeStore } from '@/store/home';
import { useAgentModal } from '../../ModalProvider';
+import { useSidebarPinState } from '../../useSidebarPinState';
import Actions from '../Item/Actions';
+import PrivateLockIcon from '../PrivateLockIcon';
import { usePreservedAgentUrl } from '../usePreservedAgentUrl';
import { useAgentDropdownMenu } from './useDropdownMenu';
@@ -127,13 +129,25 @@ const AgentItem = memo<AgentItemProps>(({ item, style, className, onNavigate, se
openCreateGroupModal(id, visibility);
}, [id, openCreateGroupModal, visibility]);
+ // In a workspace the row's column is the team pin (public) or the creator's
+ // own pin (private); the member's own pins live in their preference.
+ const { isMyPinned, isPrivate, isTeamPinned } = useSidebarPinState({ id, pinned, visibility });
+ const showPinIcon = isTeamPinned || isMyPinned;
+
// Memoize pin icon
+ // The lock sits with the pin in the fixed trailing slot rather than after
+ // the title, where a long name or role tag would truncate it out of view.
const pinIcon = useMemo(
() =>
- pinned ? (
- <ActionIcon icon={PinIcon} size={12} style={{ opacity: 0.5, pointerEvents: 'none' }} />
+ showPinIcon || isPrivate ? (
+ <>
+ {isPrivate && <PrivateLockIcon />}
+ {showPinIcon && (
+ <ActionIcon icon={PinIcon} size={12} style={{ opacity: 0.5, pointerEvents: 'none' }} />
+ )}
+ </>
) : undefined,
- [pinned],
+ [isPrivate, showPinIcon],
);
// Memoize avatar icon (show loader when updating, running spinner or unread badge at bottom-right)
diff --git a/src/features/HomeSidebar/Body/Agent/List/AgentItem/useDropdownMenu.test.tsx b/src/features/HomeSidebar/Body/Agent/List/AgentItem/useDropdownMenu.test.tsx
index 1d7c6289615..51b49099450 100644
--- a/src/features/HomeSidebar/Body/Agent/List/AgentItem/useDropdownMenu.test.tsx
+++ b/src/features/HomeSidebar/Body/Agent/List/AgentItem/useDropdownMenu.test.tsx
@@ -11,6 +11,8 @@ const mocks = vi.hoisted(() => ({
canEditResource: false,
canManageResource: false,
canManage: false,
+ canManageSettings: false,
+ myPinnedIds: [] as string[],
confirmModal: vi.fn(),
copyToClipboard: vi.fn(),
toastError: vi.fn(),
@@ -19,6 +21,8 @@ const mocks = vi.hoisted(() => ({
home: {
duplicateAgent: vi.fn(),
pinAgent: vi.fn(),
+ pinAgentGroup: vi.fn(),
+ pinItemForMe: vi.fn(),
refreshAgentList: vi.fn(),
removeAgent: vi.fn(),
toggleAgentLabel: vi.fn(),
@@ -84,8 +88,13 @@ vi.mock('@/features/Workspace/useWorkspaceAwareNavigate', () => ({
}));
vi.mock('@/hooks/usePermission', () => ({
- usePermission: (action: 'create_content' | 'edit_own_content') => ({
- allowed: action === 'create_content' ? mocks.canCreate : mocks.canEdit,
+ usePermission: (action: 'create_content' | 'edit_own_content' | 'manage_settings') => ({
+ allowed:
+ action === 'create_content'
+ ? mocks.canCreate
+ : action === 'manage_settings'
+ ? mocks.canManageSettings
+ : mocks.canEdit,
reason: '',
}),
}));
@@ -119,13 +128,25 @@ vi.mock('@/store/home/selectors', () => ({
},
}));
+interface UserStateMock {
+ userId: string;
+ workspaceUserPreference: { sidebarPinnedItemIds: string[] };
+}
+
vi.mock('@/store/user', () => ({
- useUserStore: (selector: (state: { userId: string }) => unknown) =>
- selector({ userId: 'member-1' }),
+ useUserStore: (selector: (state: UserStateMock) => unknown) =>
+ selector({
+ userId: 'member-1',
+ workspaceUserPreference: { sidebarPinnedItemIds: mocks.myPinnedIds },
+ }),
}));
vi.mock('@/store/user/selectors', () => ({
- userProfileSelectors: { userId: (state: { userId: string }) => state.userId },
+ userProfileSelectors: { userId: (state: UserStateMock) => state.userId },
+ workspaceUserSettingsSelectors: {
+ sidebarPinnedItemIds: (state: UserStateMock) =>
+ state.workspaceUserPreference.sidebarPinnedItemIds,
+ },
}));
vi.mock('../../../../hooks', () => ({ useRevealSidebarSection: () => vi.fn() }));
@@ -157,13 +178,19 @@ const getMenuItem = (
type PublicAgentMenuOptions = Partial<
Pick<
Parameters<typeof useAgentDropdownMenu>[0],
- 'id' | 'labelsEnabled' | 'sidebarVisibilityEnabled'
+ 'id' | 'labelsEnabled' | 'pinned' | 'sidebarVisibilityEnabled' | 'visibility'
>
>;
const renderPublicAgentMenu = (
userId: string,
- { id = 'agent-1', labelsEnabled, sidebarVisibilityEnabled }: PublicAgentMenuOptions = {},
+ {
+ id = 'agent-1',
+ labelsEnabled,
+ pinned = false,
+ sidebarVisibilityEnabled,
+ visibility = 'public',
+ }: PublicAgentMenuOptions = {},
) =>
renderHook(() =>
useAgentDropdownMenu({
@@ -171,11 +198,11 @@ const renderPublicAgentMenu = (
id,
...(labelsEnabled === undefined ? {} : { labelsEnabled }),
openCreateGroupModal: vi.fn(),
- pinned: false,
+ pinned,
...(sidebarVisibilityEnabled === undefined ? {} : { sidebarVisibilityEnabled }),
title: 'Public Agent',
userId,
- visibility: 'public',
+ visibility,
}),
);
@@ -188,9 +215,81 @@ describe('useAgentDropdownMenu', () => {
mocks.canEditResource = false;
mocks.canManageResource = false;
mocks.canManage = false;
+ mocks.canManageSettings = false;
+ mocks.myPinnedIds = [];
mocks.transferMenuItems = null;
});
+ describe('workspace pins', () => {
+ it('offers a personal pin but no team pin to a member', async () => {
+ const { result } = renderPublicAgentMenu('creator-1');
+ const keys = getMenuKeys(result.current());
+
+ expect(keys).toContain('pin');
+ expect(keys).not.toContain('pinForTeam');
+
+ await getMenuItem(result.current(), 'pin').onClick({
+ domEvent: { stopPropagation: vi.fn() },
+ });
+ expect(mocks.home.pinItemForMe).toHaveBeenCalledWith(
+ { id: 'agent-1', pinned: false, type: 'agent', visibility: 'public' },
+ true,
+ );
+ // A member's pin never touches the shared column.
+ expect(mocks.home.pinAgent).not.toHaveBeenCalled();
+ });
+
+ it('lets an owner/admin pin a public agent for the team', async () => {
+ mocks.canManageSettings = true;
+
+ const { result } = renderPublicAgentMenu('creator-1');
+ expect(getMenuKeys(result.current())).toEqual(expect.arrayContaining(['pin', 'pinForTeam']));
+
+ await getMenuItem(result.current(), 'pinForTeam').onClick({
+ domEvent: { stopPropagation: vi.fn() },
+ });
+ expect(mocks.home.pinAgent).toHaveBeenCalledWith('agent-1', true);
+ });
+
+ it('shows a team-pinned agent as fixed: no hide, no personal pin, admin can unpin', () => {
+ mocks.canManageSettings = true;
+
+ const { result } = renderPublicAgentMenu('creator-1', { pinned: true });
+ const keys = getMenuKeys(result.current());
+
+ expect(keys).toContain('pinForTeam');
+ expect(keys).not.toContain('pin');
+ expect(keys).not.toContain('hideFromSidebar');
+ });
+
+ it('gives a member no pin control over a team-pinned agent', () => {
+ const { result } = renderPublicAgentMenu('creator-1', { pinned: true });
+ const keys = getMenuKeys(result.current());
+
+ expect(keys).not.toContain('pin');
+ expect(keys).not.toContain('pinForTeam');
+ });
+
+ it('never offers a team pin on a private agent', () => {
+ mocks.canManageSettings = true;
+
+ const { result } = renderPublicAgentMenu('member-1', { visibility: 'private' });
+ const keys = getMenuKeys(result.current());
+
+ expect(keys).toContain('pin');
+ expect(keys).not.toContain('pinForTeam');
+ });
+
+ it('reads a personal pin from the member preference', () => {
+ mocks.myPinnedIds = ['agent-1'];
+
+ const { result } = renderPublicAgentMenu('creator-1');
+ const pinItem = getMenuItem(result.current(), 'pin') as unknown as { label: string };
+
+ expect(pinItem.label).toBe('pinOff');
+ });
+ });
+
it('keeps non-config actions available to a use-only Workspace member', () => {
const { result } = renderPublicAgentMenu('creator-1');
@@ -237,7 +336,9 @@ describe('useAgentDropdownMenu', () => {
const { result } = renderPublicAgentMenu('creator-1');
+ // A personal pin only writes the viewer's own preference, so it stays.
expect(getMenuKeys(result.current())).toEqual([
+ 'pin',
'hideFromSidebar',
'openInNewWindow',
'copyAgentId',
diff --git a/src/features/HomeSidebar/Body/Agent/List/AgentItem/useDropdownMenu.tsx b/src/features/HomeSidebar/Body/Agent/List/AgentItem/useDropdownMenu.tsx
index 432476f1d02..2964550b400 100644
--- a/src/features/HomeSidebar/Body/Agent/List/AgentItem/useDropdownMenu.tsx
+++ b/src/features/HomeSidebar/Body/Agent/List/AgentItem/useDropdownMenu.tsx
@@ -48,6 +48,7 @@ import { getDeleteErrorMessageKey } from '@/utils/forbiddenError';
import { useRevealSidebarSection } from '../../../../hooks';
import { useSidebarItemVisibility } from '../../useSidebarItemVisibility';
+import { useSidebarPinMenuItems } from '../../useSidebarPinMenuItems';
import { getAgentPublishErrorKey } from './agentMenuVisibility';
const BUILTIN_SLUGS = new Set<string>(Object.values(BUILTIN_AGENT_SLUGS));
@@ -149,6 +150,7 @@ export const useAgentDropdownMenu = ({
const activeWorkspaceId = useActiveWorkspaceId();
const currentUserId = useUserStore(userProfileSelectors.userId);
const { isSidebarItemVisible, setSidebarItemVisible } = useSidebarItemVisibility();
+ const refreshWorkspaceUserPreference = useUserStore((s) => s.refreshWorkspaceUserPreference);
const isShownInSidebar =
sidebarVisibilityEnabled && isSidebarItemVisible({ id, slug, type: 'agent', userId });
const isPrivate = visibility === 'private';
@@ -207,21 +209,34 @@ export const useAgentDropdownMenu = ({
// vanish from the sidebar.
const revealSidebarSection = useRevealSidebarSection();
+ // Workspace: a personal pin for every member plus an owner/admin-only team
+ // pin on public rows. Personal mode keeps the single column-backed pin.
+ const { isTeamPinned, menuItems: workspacePinItems } = useSidebarPinMenuItems({
+ id,
+ pinned,
+ type: 'agent',
+ visibility,
+ });
+
return useMemo(
() => () =>
[
- ...(canEdit
- ? [
- {
- icon: <Icon icon={pinned ? PinOff : Pin} />,
- key: 'pin',
- label: t(pinned ? 'pinOff' : 'pin'),
- onClick: () => pinAgent(id, !pinned),
- sfSymbol: pinned ? 'pin.slash' : 'pin',
- },
- ]
- : []),
- ...(isShownInSidebar
+ ...(activeWorkspaceId
+ ? workspacePinItems
+ : canEdit
+ ? [
+ {
+ icon: <Icon icon={pinned ? PinOff : Pin} />,
+ key: 'pin',
+ label: t(pinned ? 'pinOff' : 'pin'),
+ onClick: () => pinAgent(id, !pinned),
+ sfSymbol: pinned ? 'pin.slash' : 'pin',
+ },
+ ]
+ : []),
+ // Team-pinned rows are the fixed section every member sees; hiding
+ // them would do nothing there.
+ ...(isShownInSidebar && !isTeamPinned
? [
{
icon: <Icon icon={EyeOffIcon} />,
@@ -501,7 +516,12 @@ export const useAgentDropdownMenu = ({
onOk: async () => {
try {
await agentService.publishAgentToWorkspace(id);
- await refreshAgentList();
+ // Publishing moves a private pin into this
+ // member's personal pin list server-side.
+ await Promise.all([
+ refreshAgentList(),
+ refreshWorkspaceUserPreference(),
+ ]);
revealSidebarSection('agent');
toast.success(
t('agent.publishToWorkspaceSuccess', {
@@ -549,7 +569,7 @@ export const useAgentDropdownMenu = ({
try {
await agentService.setAgentVisibility(id, 'private');
await refreshAgentList();
- revealSidebarSection('private');
+ revealSidebarSection('agent');
toast.success(t('makePrivate.success', { ns: 'common' }));
} catch (error) {
console.error('Failed to make agent private:', error);
@@ -598,6 +618,8 @@ export const useAgentDropdownMenu = ({
] as DropdownItem[],
[
activeWorkspaceId,
+ workspacePinItems,
+ isTeamPinned,
canCreate,
canConfigure,
canEdit,
@@ -633,6 +655,7 @@ export const useAgentDropdownMenu = ({
isShownInSidebar,
setSidebarItemVisible,
refreshAgentList,
+ refreshWorkspaceUserPreference,
revealSidebarSection,
t,
],
diff --git a/src/features/HomeSidebar/Body/Agent/List/Group/Item.tsx b/src/features/HomeSidebar/Body/Agent/List/Group/Item.tsx
index 82bef8db6b5..b14934a0c84 100644
--- a/src/features/HomeSidebar/Body/Agent/List/Group/Item.tsx
+++ b/src/features/HomeSidebar/Body/Agent/List/Group/Item.tsx
@@ -16,11 +16,13 @@ import * as stylex from '@stylexjs/stylex';
import { HashIcon } from 'lucide-react';
import React, { memo, useCallback, useMemo, useState } from 'react';
+import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
import { useHomeStore } from '@/store/home';
import { useCreateMenuItems } from '../../../../hooks';
import { useAgentModal } from '../../ModalProvider';
import SessionList from '../List';
+import PrivateLockIcon from '../PrivateLockIcon';
import Actions from './Actions';
import { useGroupDropdownMenu } from './useDropdownMenu';
@@ -29,6 +31,8 @@ const styles = stylex.create({ item: { paddingInlineStart: '14px' } });
const GroupItem = memo<SidebarGroup>(({ items, id, name, visibility }) => {
const [anchor, setAnchor] = useState<HTMLElement | null>(null);
const isUpdating = useHomeStore((s) => s.groupUpdatingId === id);
+ // Public and private folders share one Agents section in a workspace.
+ const isPrivateFolder = !!useActiveWorkspaceId() && visibility === 'private';
// Modal management
const { openConfigGroupModal } = useAgentModal();
@@ -64,9 +68,11 @@ const GroupItem = memo<SidebarGroup>(({ items, id, name, visibility }) => {
<AccordionTrigger style={{ paddingBlock: 4, paddingInline: '8px 4px' }}>
<Flexbox horizontal align="center" gap={6} style={{ overflow: 'hidden' }}>
{groupIcon}
- <Text ellipsis fontSize={12} style={{ flex: 1 }} type={'secondary'} weight={500}>
+ <Text ellipsis fontSize={12} type={'secondary'} weight={500}>
{name}
</Text>
+ {/* Outside the ellipsis so a long name can't push it out of view. */}
+ {isPrivateFolder && <PrivateLockIcon />}
</Flexbox>
</AccordionTrigger>
<div
diff --git a/src/features/HomeSidebar/Body/Agent/List/PrivateLockIcon.tsx b/src/features/HomeSidebar/Body/Agent/List/PrivateLockIcon.tsx
new file mode 100644
index 00000000000..57468a6763b
--- /dev/null
+++ b/src/features/HomeSidebar/Body/Agent/List/PrivateLockIcon.tsx
@@ -0,0 +1,38 @@
+'use client';
+
+import { Icon, Tooltip } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import { LockIcon } from 'lucide-react';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+/**
+ * Marks a private Agent / chat group / folder in the merged workspace Agents
+ * section, where private and shared rows are listed together.
+ */
+const PrivateLockIcon = memo(() => {
+ const { t } = useTranslation('common');
+ const label = t('navPanel.privateTooltip');
+
+ return (
+ <Tooltip title={label}>
+ <span
+ aria-label={label}
+ data-testid="sidebar-private-lock"
+ role="img"
+ style={{
+ color: cssVar.colorTextTertiary,
+ display: 'inline-flex',
+ flex: 'none',
+ verticalAlign: 'middle',
+ }}
+ >
+ <Icon icon={LockIcon} size={12} />
+ </span>
+ </Tooltip>
+ );
+});
+
+PrivateLockIcon.displayName = 'PrivateLockIcon';
+
+export default PrivateLockIcon;
diff --git a/src/features/HomeSidebar/Body/Agent/List/WorkspaceAgentListContent.tsx b/src/features/HomeSidebar/Body/Agent/List/WorkspaceAgentListContent.tsx
new file mode 100644
index 00000000000..4383cfd4558
--- /dev/null
+++ b/src/features/HomeSidebar/Body/Agent/List/WorkspaceAgentListContent.tsx
@@ -0,0 +1,162 @@
+'use client';
+
+import { Flexbox, Icon, Text, Tooltip } from '@lobehub/ui';
+import { ChevronDown, ChevronUp, MoreHorizontal, PinIcon, UsersIcon } from 'lucide-react';
+import { type ReactNode } from 'react';
+import { memo, useMemo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import NavItem from '@/features/NavPanel/components/NavItem';
+import SkeletonList from '@/features/NavPanel/components/SkeletonList';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { useGlobalStore } from '@/store/global';
+import { systemStatusSelectors } from '@/store/global/selectors';
+import { useHomeStore } from '@/store/home';
+import { homeAgentListSelectors } from '@/store/home/selectors';
+import { useUserStore } from '@/store/user';
+import { authSelectors } from '@/store/user/slices/auth/selectors';
+
+import CreateAgentButton from '../CreateAgentButton';
+import { resolveAgentListContentState } from './agentListContentState';
+import Group from './Group';
+import InboxItem from './InboxItem';
+import SessionList from './List';
+import { useWorkspaceAgentSections } from './useWorkspaceAgentSections';
+
+/** Team pins beyond this many fold behind a "show more" row. */
+export const TEAM_PINNED_VISIBLE_LIMIT = 5;
+
+const SubHeader = memo<{ icon: typeof PinIcon; testId: string; title: string; tooltip?: string }>(
+ ({ icon, testId, title, tooltip }) => {
+ const node: ReactNode = (
+ <Flexbox
+ horizontal
+ align={'center'}
+ data-testid={testId}
+ gap={6}
+ style={{ paddingBlock: '6px 2px', paddingInline: 10 }}
+ >
+ <Icon icon={icon} size={12} style={{ opacity: 0.5 }} />
+ <Text ellipsis fontSize={11} type={'secondary'} weight={500}>
+ {title}
+ </Text>
+ </Flexbox>
+ );
+
+ return tooltip ? (
+ <Tooltip placement={'right'} title={tooltip}>
+ {node}
+ </Tooltip>
+ ) : (
+ node
+ );
+ },
+);
+
+SubHeader.displayName = 'WorkspaceAgentSubHeader';
+
+/**
+ * The merged workspace "Agents" section body (replacing the former separate
+ * "Workspace" and "Private" accordions): Inbox → team pins (fixed, set by
+ * owners/admins for everyone) → my pins → folders → the rest. Private rows
+ * carry a lock icon wherever they appear. Personal mode keeps rendering
+ * `AgentListContent`.
+ */
+const WorkspaceAgentListContent = memo<{ hideInbox?: boolean }>(({ hideInbox }) => {
+ const { t } = useTranslation(['common', 'chat']);
+ const isInit = useHomeStore(homeAgentListSelectors.isAgentListInit);
+ const authLoaded = useUserStore(authSelectors.isLoaded);
+ const isLogin = useUserStore(authSelectors.isLogin);
+ const contentState = resolveAgentListContentState({
+ authLoaded: !!authLoaded,
+ isInit,
+ isLogin: !!isLogin,
+ });
+
+ const agentPageSize = useGlobalStore(systemStatusSelectors.agentPageSize);
+ const navigate = useWorkspaceAwareNavigate();
+ const [teamExpanded, setTeamExpanded] = useState(false);
+
+ const resolved = useWorkspaceAgentSections();
+ const sections = useMemo(
+ () => ({
+ ...resolved,
+ hasMore: resolved.rest.length > agentPageSize,
+ rest: resolved.rest.slice(0, agentPageSize),
+ }),
+ [agentPageSize, resolved],
+ );
+
+ if (contentState !== 'ready')
+ return (
+ <>
+ {!hideInbox && <InboxItem style={{ minHeight: 36 }} />}
+ {contentState === 'loading' && <SkeletonList rows={3} />}
+ </>
+ );
+
+ const { folders, hasMore, myPinned, rest, teamPinned } = sections;
+ const teamOverflow = teamPinned.length > TEAM_PINNED_VISIBLE_LIMIT;
+ const visibleTeamPinned =
+ teamOverflow && !teamExpanded ? teamPinned.slice(0, TEAM_PINNED_VISIBLE_LIMIT) : teamPinned;
+
+ return (
+ <>
+ {!hideInbox && <InboxItem style={{ minHeight: 36 }} />}
+ {teamPinned.length > 0 && (
+ <Flexbox data-testid={'sidebar-team-pinned'} gap={1}>
+ <SubHeader
+ icon={UsersIcon}
+ testId={'sidebar-team-pinned-header'}
+ title={t('navPanel.teamPinned')}
+ tooltip={t('navPanel.teamPinnedHint')}
+ />
+ <SessionList dataSource={visibleTeamPinned} />
+ {teamOverflow && (
+ <NavItem
+ icon={teamExpanded ? ChevronUp : ChevronDown}
+ title={
+ teamExpanded
+ ? t('navPanel.showLessTeamPinned')
+ : t('navPanel.showMoreTeamPinned', {
+ count: teamPinned.length - TEAM_PINNED_VISIBLE_LIMIT,
+ })
+ }
+ onClick={() => setTeamExpanded((expanded) => !expanded)}
+ />
+ )}
+ </Flexbox>
+ )}
+ {myPinned.length > 0 && (
+ <Flexbox data-testid={'sidebar-my-pinned'} gap={1}>
+ <SubHeader
+ icon={PinIcon}
+ testId={'sidebar-my-pinned-header'}
+ title={t('navPanel.myPinned')}
+ />
+ <SessionList dataSource={myPinned} />
+ </Flexbox>
+ )}
+ {folders.length > 0 && <Group dataSource={folders} />}
+ {rest.length > 0 && (
+ <Flexbox data-testid={'sidebar-agents-rest'} gap={1}>
+ <SessionList dataSource={rest} />
+ </Flexbox>
+ )}
+ {/* Shared folders and teammates' agents live on the Agents page, so
+ the way there is always offered, not only when the list overflows. */}
+ <NavItem
+ icon={MoreHorizontal}
+ title={hasMore ? t('input.more', { ns: 'chat' }) : t('navPanel.browseAllAgents')}
+ onClick={() => navigate('/agents')}
+ />
+ {/* New agents from the sidebar start private, the safe default; the
+ "+" menu also offers a workspace agent. */}
+ <CreateAgentButton visibility={'private'} />
+ </>
+ );
+});
+
+WorkspaceAgentListContent.displayName = 'WorkspaceAgentListContent';
+
+export default WorkspaceAgentListContent;
diff --git a/src/features/HomeSidebar/Body/Agent/List/index.tsx b/src/features/HomeSidebar/Body/Agent/List/index.tsx
index b701535ed7a..4ea3c3db7ba 100644
--- a/src/features/HomeSidebar/Body/Agent/List/index.tsx
+++ b/src/features/HomeSidebar/Body/Agent/List/index.tsx
@@ -2,10 +2,12 @@
import { memo } from 'react';
+import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
import { useHomeStore } from '@/store/home';
import AllAgentsDrawer from '../AllAgentsDrawer';
import AgentListContent from './AgentListContent';
+import WorkspaceAgentListContent from './WorkspaceAgentListContent';
// The Home sidebar owns the all-agents drawer; other surfaces should import AgentListContent directly.
const AgentList = memo<{ onMoreClick?: () => void }>(({ onMoreClick }) => {
@@ -13,10 +15,17 @@ const AgentList = memo<{ onMoreClick?: () => void }>(({ onMoreClick }) => {
s.allAgentsDrawerOpen,
s.closeAllAgentsDrawer,
]);
+ // A workspace merges shared and private rows into one Agents section with
+ // team / personal pin groups; personal mode keeps the original layout.
+ const activeWorkspaceId = useActiveWorkspaceId();
return (
<>
- <AgentListContent onMoreClick={onMoreClick} />
+ {activeWorkspaceId ? (
+ <WorkspaceAgentListContent />
+ ) : (
+ <AgentListContent onMoreClick={onMoreClick} />
+ )}
<AllAgentsDrawer open={allAgentsDrawerOpen} onClose={closeAllAgentsDrawer} />
</>
);
diff --git a/src/features/HomeSidebar/Body/Agent/List/useWorkspaceAgentSections.ts b/src/features/HomeSidebar/Body/Agent/List/useWorkspaceAgentSections.ts
new file mode 100644
index 00000000000..7bfe44abf10
--- /dev/null
+++ b/src/features/HomeSidebar/Body/Agent/List/useWorkspaceAgentSections.ts
@@ -0,0 +1,109 @@
+'use client';
+
+import isEqual from 'fast-deep-equal';
+import { useMemo } from 'react';
+
+import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
+import { useHomeStore } from '@/store/home';
+import { homeAgentListSelectors } from '@/store/home/selectors';
+import { useUserStore } from '@/store/user';
+import { userProfileSelectors, workspaceUserSettingsSelectors } from '@/store/user/selectors';
+
+import { useKeepSidebarGroupsListed, useKeepSidebarListed } from './useAgentList';
+import {
+ resolveWorkspaceAgentSections,
+ type WorkspaceAgentSections,
+} from './workspaceAgentSections';
+
+/**
+ * The merged workspace Agents section as the member's sidebar shows it, with
+ * their explicit hides applied (the team section stays fixed). The rest is not
+ * truncated to the page size. Shared by the sidebar and the Agents page, so
+ * "is this in my sidebar" has a single answer.
+ */
+export const useWorkspaceAgentSections = (): WorkspaceAgentSections => {
+ const pinned = useHomeStore(homeAgentListSelectors.pinnedAgents, isEqual);
+ const privatePinned = useHomeStore(homeAgentListSelectors.privatePinnedAgents, isEqual);
+ const groups = useHomeStore(homeAgentListSelectors.agentGroups, isEqual);
+ const privateGroups = useHomeStore(homeAgentListSelectors.privateAgentGroups, isEqual);
+ const ungrouped = useHomeStore(homeAgentListSelectors.ungroupedAgents, isEqual);
+ const privateUngrouped = useHomeStore(homeAgentListSelectors.privateUngroupedAgents, isEqual);
+ const myPinnedIds = useUserStore(workspaceUserSettingsSelectors.sidebarPinnedItemIds, isEqual);
+ const visibilityOverrides = useUserStore(
+ workspaceUserSettingsSelectors.sidebarAgentVisibilityOverrides,
+ isEqual,
+ );
+ const currentUserId = useUserStore(userProfileSelectors.userId);
+
+ const keep = useKeepSidebarListed();
+ const keepGroups = useKeepSidebarGroupsListed();
+
+ return useMemo(() => {
+ const resolved = resolveWorkspaceAgentSections({
+ currentUserId,
+ groups,
+ myPinnedIds,
+ pinned,
+ privateGroups,
+ privatePinned,
+ privateUngrouped,
+ ungrouped,
+ visibilityOverrides,
+ });
+
+ // The team section is fixed: a member's own "remove from sidebar" does
+ // not apply to it. Every other section honors the member's hides.
+ return {
+ folders: keepGroups(resolved.folders).map((group) => ({
+ ...group,
+ items: keep(group.items),
+ })),
+ myPinned: keep(resolved.myPinned),
+ rest: keep(resolved.rest),
+ teamPinned: resolved.teamPinned,
+ };
+ }, [
+ currentUserId,
+ groups,
+ keep,
+ keepGroups,
+ myPinnedIds,
+ pinned,
+ privateGroups,
+ privatePinned,
+ privateUngrouped,
+ ungrouped,
+ visibilityOverrides,
+ ]);
+};
+
+export interface WorkspaceSidebarItemIds {
+ /** Rows under "Pinned for team": fixed for every member, no personal hide. */
+ fixed: ReadonlySet<string>;
+ /** Every row the member's sidebar lists. */
+ listed: ReadonlySet<string>;
+}
+
+/**
+ * Ids of the Agents / chat groups listed in the member's workspace sidebar,
+ * or `null` outside a workspace (personal mode keeps its own hide list).
+ */
+export const useWorkspaceSidebarItemIds = (): WorkspaceSidebarItemIds | null => {
+ const isWorkspace = !!useActiveWorkspaceId();
+ const sections = useWorkspaceAgentSections();
+
+ return useMemo(() => {
+ if (!isWorkspace) return null;
+
+ const fixed = new Set(sections.teamPinned.map((item) => item.id));
+
+ const ids = new Set<string>();
+ const add = (list: { id: string }[]) => list.forEach((item) => ids.add(item.id));
+ add(sections.teamPinned);
+ add(sections.myPinned);
+ add(sections.rest);
+ for (const folder of sections.folders) add(folder.items);
+
+ return { fixed, listed: ids };
+ }, [isWorkspace, sections]);
+};
diff --git a/src/features/HomeSidebar/Body/Agent/List/workspaceAgentSections.test.ts b/src/features/HomeSidebar/Body/Agent/List/workspaceAgentSections.test.ts
new file mode 100644
index 00000000000..0ebf3919560
--- /dev/null
+++ b/src/features/HomeSidebar/Body/Agent/List/workspaceAgentSections.test.ts
@@ -0,0 +1,180 @@
+import type { SidebarAgentItem, SidebarGroup } from '@lobechat/types';
+import { describe, expect, it } from 'vitest';
+
+import {
+ isListedInWorkspaceSidebar,
+ resolveWorkspaceAgentSections,
+} from './workspaceAgentSections';
+
+const ME = 'me';
+
+const item = (
+ id: string,
+ visibility: 'private' | 'public',
+ updatedAt: string,
+ extra: Partial<SidebarAgentItem> = {},
+): SidebarAgentItem =>
+ ({
+ id,
+ pinned: false,
+ title: id,
+ type: 'agent',
+ updatedAt: new Date(updatedAt),
+ // Private rows are always the caller's; public rows default to a teammate.
+ userId: visibility === 'private' ? ME : 'teammate',
+ visibility,
+ ...extra,
+ }) as SidebarAgentItem;
+
+const mine = { userId: ME };
+
+const folder = (id: string, visibility: 'private' | 'public', items: SidebarAgentItem[]) =>
+ ({ id, items, name: id, sort: 0, visibility }) as SidebarGroup;
+
+const ids = (items: { id: string }[]) => items.map((i) => i.id);
+
+const base = {
+ currentUserId: ME,
+ groups: [] as SidebarGroup[],
+ myPinnedIds: [] as string[],
+ pinned: [] as SidebarAgentItem[],
+ privateGroups: [] as SidebarGroup[],
+ privatePinned: [] as SidebarAgentItem[],
+ privateUngrouped: [] as SidebarAgentItem[],
+ ungrouped: [] as SidebarAgentItem[],
+ visibilityOverrides: {} as Record<string, boolean>,
+};
+
+describe('isListedInWorkspaceSidebar', () => {
+ const membership = { currentUserId: ME, visibilityOverrides: {} };
+
+ it('lists the member’s own rows: private ones and ones they created', () => {
+ expect(isListedInWorkspaceSidebar(item('p', 'private', '2026-01-01'), membership)).toBe(true);
+ expect(isListedInWorkspaceSidebar(item('c', 'public', '2026-01-01', mine), membership)).toBe(
+ true,
+ );
+ });
+
+ it('leaves a teammate’s shared row on the Agents page until the member adds it', () => {
+ expect(isListedInWorkspaceSidebar(item('t', 'public', '2026-01-01'), membership)).toBe(false);
+ });
+
+ it('lets an explicit choice win over the default', () => {
+ const overrides = { added: true, hiddenOwn: false };
+ const withOverrides = { currentUserId: ME, visibilityOverrides: overrides };
+
+ expect(isListedInWorkspaceSidebar(item('added', 'public', '2026-01-01'), withOverrides)).toBe(
+ true,
+ );
+ // A member can hide even a row they created.
+ expect(
+ isListedInWorkspaceSidebar(item('hiddenOwn', 'public', '2026-01-01', mine), withOverrides),
+ ).toBe(false);
+ });
+});
+
+describe('resolveWorkspaceAgentSections', () => {
+ it('puts team pins, my pins, private folders and the rest in that order of sections', () => {
+ const sections = resolveWorkspaceAgentSections({
+ ...base,
+ groups: [folder('pub-folder', 'public', [item('in-pub-folder', 'public', '2026-01-01')])],
+ myPinnedIds: ['pub-mine'],
+ pinned: [item('team', 'public', '2026-01-01', { pinned: true })],
+ privateGroups: [
+ folder('priv-folder', 'private', [item('in-priv-folder', 'private', '2026-01-01')]),
+ ],
+ privatePinned: [item('legacy-private-pin', 'private', '2026-01-02', { pinned: true })],
+ privateUngrouped: [item('priv-rest', 'private', '2026-01-05')],
+ ungrouped: [
+ item('pub-mine', 'public', '2026-01-03'),
+ item('pub-rest', 'public', '2026-01-04', mine),
+ ],
+ });
+
+ expect(ids(sections.teamPinned)).toEqual(['team']);
+ // Preference order first, then private rows pinned through their column.
+ expect(ids(sections.myPinned)).toEqual(['pub-mine', 'legacy-private-pin']);
+ // Only private folders stay in the sidebar.
+ expect(ids(sections.folders)).toEqual(['priv-folder']);
+ // Public and private rows interleave, newest first.
+ expect(ids(sections.rest)).toEqual(['priv-rest', 'pub-rest']);
+ });
+
+ it('keeps every pre-existing pin: public column → team, private column → mine', () => {
+ const sections = resolveWorkspaceAgentSections({
+ ...base,
+ pinned: [item('old-public-pin', 'public', '2026-01-01', { pinned: true })],
+ privatePinned: [item('old-private-pin', 'private', '2026-01-01', { pinned: true })],
+ });
+
+ expect(ids(sections.teamPinned)).toEqual(['old-public-pin']);
+ expect(ids(sections.myPinned)).toEqual(['old-private-pin']);
+ });
+
+ it('moves public folders off the sidebar but keeps the member’s own and added rows', () => {
+ const sections = resolveWorkspaceAgentSections({
+ ...base,
+ groups: [
+ folder('catalogue', 'public', [
+ item('teammates', 'public', '2026-01-01'),
+ item('i-created', 'public', '2026-01-02', mine),
+ item('i-added', 'public', '2026-01-03'),
+ ]),
+ ],
+ visibilityOverrides: { 'i-added': true },
+ });
+
+ expect(sections.folders).toEqual([]);
+ expect(ids(sections.rest)).toEqual(['i-added', 'i-created']);
+ });
+
+ it('lists every row once: a personal pin leaves its folder and the rest', () => {
+ const sections = resolveWorkspaceAgentSections({
+ ...base,
+ myPinnedIds: ['a', 'c'],
+ privateGroups: [
+ folder('f', 'private', [
+ item('a', 'private', '2026-01-01'),
+ item('b', 'private', '2026-01-01'),
+ ]),
+ ],
+ ungrouped: [item('c', 'public', '2026-01-01'), item('d', 'public', '2026-01-01', mine)],
+ });
+
+ expect(ids(sections.myPinned)).toEqual(['a', 'c']);
+ expect(ids(sections.folders[0].items)).toEqual(['b']);
+ expect(ids(sections.rest)).toEqual(['d']);
+ });
+
+ it('never repeats a team pin under my pins', () => {
+ const sections = resolveWorkspaceAgentSections({
+ ...base,
+ myPinnedIds: ['team'],
+ pinned: [item('team', 'public', '2026-01-01', { pinned: true })],
+ });
+
+ expect(ids(sections.teamPinned)).toEqual(['team']);
+ expect(sections.myPinned).toEqual([]);
+ });
+
+ it('skips dangling personal pins of rows that no longer exist', () => {
+ const sections = resolveWorkspaceAgentSections({
+ ...base,
+ myPinnedIds: ['deleted', 'kept'],
+ ungrouped: [item('kept', 'public', '2026-01-01')],
+ });
+
+ expect(ids(sections.myPinned)).toEqual(['kept']);
+ });
+
+ it('dedupes a private pin recorded both in the preference and on the column', () => {
+ const pinnedPrivate = item('p', 'private', '2026-01-01', { pinned: true });
+ const sections = resolveWorkspaceAgentSections({
+ ...base,
+ myPinnedIds: ['p'],
+ privatePinned: [pinnedPrivate],
+ });
+
+ expect(ids(sections.myPinned)).toEqual(['p']);
+ });
+});
diff --git a/src/features/HomeSidebar/Body/Agent/List/workspaceAgentSections.ts b/src/features/HomeSidebar/Body/Agent/List/workspaceAgentSections.ts
new file mode 100644
index 00000000000..fc663899764
--- /dev/null
+++ b/src/features/HomeSidebar/Body/Agent/List/workspaceAgentSections.ts
@@ -0,0 +1,133 @@
+import type { SidebarAgentItem, SidebarGroup } from '@lobechat/types';
+
+export interface WorkspaceSidebarMembership {
+ /** Signed-in member. */
+ currentUserId?: string | null;
+ /** Explicit per-item choice: `true` adds a row, `false` removes it. */
+ visibilityOverrides: Readonly<Record<string, boolean>>;
+}
+
+export interface WorkspaceAgentSectionsInput extends WorkspaceSidebarMembership {
+ /** Public folders. */
+ groups: SidebarGroup[];
+ /** Ids the member pinned for themselves (agents, chat groups, folders), newest first. */
+ myPinnedIds: readonly string[];
+ /** Public rows whose shared `pinned` column is set — the team pins. */
+ pinned: SidebarAgentItem[];
+ /** The member's private folders. */
+ privateGroups: SidebarGroup[];
+ /** The member's private rows whose own `pinned` column is set. */
+ privatePinned: SidebarAgentItem[];
+ /** The member's private rows outside any folder. */
+ privateUngrouped: SidebarAgentItem[];
+ /** Public rows outside any folder. */
+ ungrouped: SidebarAgentItem[];
+}
+
+export interface WorkspaceAgentSections {
+ /** The member's private folders; my-pinned rows taken out. */
+ folders: SidebarGroup[];
+ /** The member's own pinned rows, in their pin order. */
+ myPinned: SidebarAgentItem[];
+ /**
+ * Rows outside the member's private folders that are their own or that they
+ * added explicitly — public and private together, newest first.
+ */
+ rest: SidebarAgentItem[];
+ /** Rows pinned for everyone by an owner/admin. */
+ teamPinned: SidebarAgentItem[];
+}
+
+const updatedAtMs = (item: SidebarAgentItem) => new Date(item.updatedAt).getTime() || 0;
+
+/**
+ * Whether a row outside the pinned sections belongs in the member's sidebar.
+ *
+ * Shared workspace rows are a catalogue, not the member's own list. By default
+ * a row is listed only when it is the member's own — private (only its creator
+ * sees it) or created by them — until they hide it. A teammate's shared row is
+ * listed only when the member adds it explicitly. An explicit choice from the
+ * row menu or the Agents page (`sidebarAgentVisibilityOverrides`) always wins;
+ * the release seeded such choices once for the shared rows each member was
+ * using. The legacy hidden-id list is applied separately by the caller.
+ */
+export const isListedInWorkspaceSidebar = (
+ item: Pick<SidebarAgentItem, 'id' | 'userId' | 'visibility'>,
+ { currentUserId, visibilityOverrides }: WorkspaceSidebarMembership,
+): boolean => {
+ const override = visibilityOverrides[item.id];
+ if (override !== undefined) return override;
+
+ return item.visibility === 'private' || (!!currentUserId && item.userId === currentUserId);
+};
+
+/**
+ * Lay out the merged workspace "Agents" section from the server's per-bucket
+ * sidebar list:
+ *
+ * 1. Team pins — public rows with the shared `pinned` column, set by
+ * owners/admins.
+ * 2. My pins — ids in the member's `sidebarPinnedItemIds` that are still
+ * listed (dangling ids are skipped), then the member's private rows pinned
+ * through their own column by earlier clients. A team pin never repeats.
+ * 3. Folders — only the member's private folders. Public folders are shared
+ * catalogue structure browsed on the Agents page.
+ * 4. The rest — rows outside the private folders (including rows inside a
+ * public folder) that {@link isListedInWorkspaceSidebar} keeps, newest
+ * first.
+ *
+ * Every row appears at most once.
+ */
+export const resolveWorkspaceAgentSections = ({
+ currentUserId,
+ groups,
+ myPinnedIds,
+ pinned,
+ privateGroups,
+ privatePinned,
+ privateUngrouped,
+ ungrouped,
+ visibilityOverrides,
+}: WorkspaceAgentSectionsInput): WorkspaceAgentSections => {
+ const teamPinned = pinned;
+ const teamIds = new Set(teamPinned.map((item) => item.id));
+
+ const publicFolderItems = groups.flatMap((g) => g.items);
+
+ const candidates = new Map<string, SidebarAgentItem>();
+ for (const item of [
+ ...privatePinned,
+ ...groups.flatMap((group) => group.items),
+ ...privateGroups.flatMap((group) => group.items),
+ ...ungrouped,
+ ...privateUngrouped,
+ ]) {
+ if (!teamIds.has(item.id) && !candidates.has(item.id)) candidates.set(item.id, item);
+ }
+
+ const myPinned: SidebarAgentItem[] = [];
+ const myIds = new Set<string>();
+ const addMine = (item: SidebarAgentItem | undefined) => {
+ if (!item || myIds.has(item.id) || teamIds.has(item.id)) return;
+ myIds.add(item.id);
+ myPinned.push(item);
+ };
+ for (const id of myPinnedIds) addMine(candidates.get(id));
+ for (const item of [...privatePinned].sort((a, b) => updatedAtMs(b) - updatedAtMs(a))) {
+ addMine(item);
+ }
+
+ const notPinned = (item: SidebarAgentItem) => !myIds.has(item.id) && !teamIds.has(item.id);
+
+ const folders = privateGroups.map((group) => ({
+ ...group,
+ items: group.items.filter(notPinned),
+ }));
+
+ const membership = { currentUserId, visibilityOverrides };
+ const rest = [...ungrouped, ...privateUngrouped, ...publicFolderItems]
+ .filter((item) => notPinned(item) && isListedInWorkspaceSidebar(item, membership))
+ .sort((a, b) => updatedAtMs(b) - updatedAtMs(a));
+
+ return { folders, myPinned, rest, teamPinned };
+};
diff --git a/src/features/HomeSidebar/Body/Agent/index.tsx b/src/features/HomeSidebar/Body/Agent/index.tsx
index 458f4554d1e..405174240a3 100644
--- a/src/features/HomeSidebar/Body/Agent/index.tsx
+++ b/src/features/HomeSidebar/Body/Agent/index.tsx
@@ -22,6 +22,7 @@ import SkeletonList from '@/features/NavPanel/components/SkeletonList';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { useFetchAgentLabels } from '@/hooks/useFetchAgentLabels';
import { useFetchAgentList } from '@/hooks/useFetchAgentList';
+import { usePermission } from '@/hooks/usePermission';
import { useCreateMenuItems } from '../../hooks';
import Actions from './Actions';
@@ -38,22 +39,69 @@ const Agent = memo<AgentProps>(({ itemKey }) => {
const { isRevalidating } = useFetchAgentList();
// Keep the label registry warm so the per-item "Labels" submenu opens populated.
useFetchAgentLabels();
- // In workspace mode the section pairs with the "Private" bucket, so the
- // public/shared agents are labeled "Public" to make the contrast obvious.
- // Personal mode has no such duality — keep the existing "Agents" label.
+ // One "Agents" section in both modes. In a workspace it lists shared and
+ // private rows together (private ones carry a lock icon).
const activeWorkspaceId = useActiveWorkspaceId();
- const titleKey = activeWorkspaceId ? 'navPanel.publicAgents' : 'navPanel.agent';
const { openConfigGroupModal } = useAgentModal();
// Create menu items
- const { createTopLevelMenuItems, isLoading } = useCreateMenuItems();
+ const {
+ createAgentListMenuItem,
+ createAgentMenuItem,
+ createConnectAgentMenuItem,
+ createGroupChatMenuItem,
+ createMarketAgentMenuItem,
+ createTopLevelMenuItems,
+ isLoading,
+ } = useCreateMenuItems();
+ const { allowed: canCreatePublic } = usePermission('create_content');
- const addMenuItems = useMemo(() => createTopLevelMenuItems(), [createTopLevelMenuItems]);
+ const addMenuItems = useMemo(() => {
+ if (!activeWorkspaceId) return createTopLevelMenuItems();
- const handleOpenConfigGroupModal = useCallback(() => {
- openConfigGroupModal();
- }, [openConfigGroupModal]);
+ // Workspace: new agents start private (the safe default the former
+ // Private section used); a workspace agent is one explicit entry away.
+ const connectItem = createConnectAgentMenuItem({ visibility: 'private' });
+ const workspaceAgentItem = canCreatePublic
+ ? createAgentMenuItem({ visibility: 'public' })
+ : undefined;
+
+ return [
+ createAgentMenuItem({ visibility: 'private' }),
+ ...(workspaceAgentItem
+ ? [
+ {
+ ...workspaceAgentItem,
+ key: 'newWorkspaceAgent',
+ label: t('navPanel.createWorkspaceAgent'),
+ },
+ ]
+ : []),
+ createGroupChatMenuItem({ visibility: 'private' }),
+ ...(connectItem ? [{ type: 'divider' as const }, connectItem] : []),
+ { type: 'divider' as const },
+ createAgentListMenuItem(),
+ createMarketAgentMenuItem(),
+ ];
+ }, [
+ activeWorkspaceId,
+ canCreatePublic,
+ createAgentListMenuItem,
+ createAgentMenuItem,
+ createConnectAgentMenuItem,
+ createGroupChatMenuItem,
+ createMarketAgentMenuItem,
+ createTopLevelMenuItems,
+ t,
+ ]);
+
+ const handleOpenConfigGroupModal = useCallback(
+ (scope?: 'private' | 'public') => {
+ openConfigGroupModal(scope);
+ },
+ [openConfigGroupModal],
+ );
const dropdownMenu = useAgentActionsDropdownMenu({
openConfigGroupModal: handleOpenConfigGroupModal,
@@ -76,7 +124,7 @@ const Agent = memo<AgentProps>(({ itemKey }) => {
<AccordionTrigger style={{ paddingBlock: 4, paddingInline: '8px 4px' }}>
<Flexbox horizontal align="center" gap={4}>
<Text ellipsis fontSize={12} type={'secondary'} weight={500}>
- {t(titleKey)}
+ {t('navPanel.agent')}
</Text>
{isRevalidating && <Spin size="small" variant="network" />}
</Flexbox>
diff --git a/src/features/HomeSidebar/Body/Agent/useDropdownMenu.tsx b/src/features/HomeSidebar/Body/Agent/useDropdownMenu.tsx
index 0da9bb41ea6..0bd1bf7c6eb 100644
--- a/src/features/HomeSidebar/Body/Agent/useDropdownMenu.tsx
+++ b/src/features/HomeSidebar/Body/Agent/useDropdownMenu.tsx
@@ -4,6 +4,7 @@ import { Hash, LucideCheck, SlidersHorizontalIcon } from 'lucide-react';
import { useMemo } from 'react';
import { useTranslation } from 'react-i18next';
+import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
import { openCustomizeSidebarModal } from '@/features/HomeSidebar/Body/CustomizeSidebarModal';
import { useGlobalStore } from '@/store/global';
import { systemStatusSelectors } from '@/store/global/selectors';
@@ -11,7 +12,7 @@ import { systemStatusSelectors } from '@/store/global/selectors';
import { useCreateMenuItems } from '../../hooks';
interface AgentActionsDropdownMenuProps {
- openConfigGroupModal: () => void;
+ openConfigGroupModal: (scope?: 'private' | 'public') => void;
}
export const useAgentActionsDropdownMenu = ({
@@ -24,10 +25,26 @@ export const useAgentActionsDropdownMenu = ({
// Create menu items
const { createSessionGroupMenuItem, configMenuItem } = useCreateMenuItems();
+ // The workspace Agents section also holds the member's private folders
+ // (formerly managed from the separate Private section).
+ const isWorkspace = !!useActiveWorkspaceId();
return useMemo(() => {
const createSessionGroupItem = createSessionGroupMenuItem();
- const configItem = configMenuItem(openConfigGroupModal);
+ const configItem = configMenuItem(() => openConfigGroupModal('public'));
+ const privateFolderItems = isWorkspace
+ ? [
+ {
+ ...createSessionGroupMenuItem({ visibility: 'private' }),
+ label: t('navPanel.createPrivateFolder'),
+ },
+ {
+ ...configMenuItem(() => openConfigGroupModal('private')),
+ key: 'configPrivate',
+ label: t('navPanel.managePrivateFolders'),
+ },
+ ]
+ : [];
const pageSizeOptions = [5, 10, 15, 20];
const pageSizeItems = pageSizeOptions.map((size) => ({
@@ -42,6 +59,7 @@ export const useAgentActionsDropdownMenu = ({
return [
createSessionGroupItem,
configItem,
+ ...privateFolderItems,
{ type: 'divider' as const },
{
children: pageSizeItems,
@@ -64,6 +82,7 @@ export const useAgentActionsDropdownMenu = ({
createSessionGroupMenuItem,
configMenuItem,
openConfigGroupModal,
+ isWorkspace,
t,
]);
};
diff --git a/src/features/HomeSidebar/Body/Agent/useSidebarPinMenuItems.tsx b/src/features/HomeSidebar/Body/Agent/useSidebarPinMenuItems.tsx
new file mode 100644
index 00000000000..6f051ab26a6
--- /dev/null
+++ b/src/features/HomeSidebar/Body/Agent/useSidebarPinMenuItems.tsx
@@ -0,0 +1,116 @@
+'use client';
+
+import type { SidebarVisibility } from '@lobechat/types';
+import { type DropdownItem, Icon, toast } from '@lobehub/ui';
+import { Pin, PinOff, UsersIcon } from 'lucide-react';
+import { useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { usePermission } from '@/hooks/usePermission';
+import { useHomeStore } from '@/store/home';
+
+import { useSidebarPinState } from './useSidebarPinState';
+
+interface UseSidebarPinMenuItemsParams {
+ id: string;
+ /** The row's own `pinned` column. */
+ pinned: boolean;
+ type: 'agent' | 'group';
+ visibility?: SidebarVisibility;
+}
+
+const isForbidden = (error: unknown) =>
+ (error as { data?: { code?: string } } | undefined)?.data?.code === 'FORBIDDEN';
+
+/**
+ * Workspace pin entries for an Agent / chat group row menu:
+ *
+ * - "Pin" / "Unpin" — the member's own pin, available to every role. Offered
+ * on a team-pinned row only to undo an earlier personal pin, since the team
+ * section already keeps it on top.
+ * - "Pin for team" / "Unpin for team" — writes the shared column every member
+ * sees. Owner/admin only (`manage_settings`, mirrored by the server's
+ * `agent:update:all` check) and never on private rows, which nobody else
+ * can see.
+ *
+ * Returns no items outside a workspace; personal mode keeps its own pin.
+ */
+export const useSidebarPinMenuItems = ({
+ id,
+ pinned,
+ type,
+ visibility,
+}: UseSidebarPinMenuItemsParams) => {
+ const { t } = useTranslation(['chat', 'common']);
+ const { isMyPinned, isPrivate, isTeamPinned, isWorkspace } = useSidebarPinState({
+ id,
+ pinned,
+ visibility,
+ });
+ const { allowed: canManageTeamPins } = usePermission('manage_settings');
+ const [pinItemForMe, pinAgent, pinAgentGroup] = useHomeStore((s) => [
+ s.pinItemForMe,
+ s.pinAgent,
+ s.pinAgentGroup,
+ ]);
+
+ const menuItems = useMemo<DropdownItem[]>(() => {
+ if (!isWorkspace) return [];
+
+ const items: DropdownItem[] = [];
+
+ if (!isTeamPinned || isMyPinned) {
+ items.push({
+ icon: <Icon icon={isMyPinned ? PinOff : Pin} />,
+ key: 'pin',
+ label: t(isMyPinned ? 'pinOff' : 'pin'),
+ onClick: async () => {
+ try {
+ await pinItemForMe({ id, pinned, type, visibility }, !isMyPinned);
+ } catch (error) {
+ console.error('Failed to update personal pin:', error);
+ toast.error(t('operationFailed', { ns: 'common' }));
+ }
+ },
+ } as DropdownItem);
+ }
+
+ if (canManageTeamPins && !isPrivate) {
+ items.push({
+ icon: <Icon icon={isTeamPinned ? PinOff : UsersIcon} />,
+ key: 'pinForTeam',
+ label: t(isTeamPinned ? 'unpinForTeam' : 'pinForTeam'),
+ onClick: async () => {
+ try {
+ await (type === 'group' ? pinAgentGroup : pinAgent)(id, !isTeamPinned);
+ } catch (error) {
+ console.error('Failed to update team pin:', error);
+ toast.error(
+ t(isForbidden(error) ? 'pinForTeamForbidden' : 'operationFailed', {
+ ns: isForbidden(error) ? 'chat' : 'common',
+ }),
+ );
+ }
+ },
+ } as DropdownItem);
+ }
+
+ return items;
+ }, [
+ canManageTeamPins,
+ id,
+ isMyPinned,
+ isPrivate,
+ isTeamPinned,
+ isWorkspace,
+ pinAgent,
+ pinAgentGroup,
+ pinItemForMe,
+ pinned,
+ t,
+ type,
+ visibility,
+ ]);
+
+ return { isMyPinned, isTeamPinned, menuItems };
+};
diff --git a/src/features/HomeSidebar/Body/Agent/useSidebarPinState.test.ts b/src/features/HomeSidebar/Body/Agent/useSidebarPinState.test.ts
new file mode 100644
index 00000000000..b38a226363f
--- /dev/null
+++ b/src/features/HomeSidebar/Body/Agent/useSidebarPinState.test.ts
@@ -0,0 +1,38 @@
+import { describe, expect, it } from 'vitest';
+
+import { resolveSidebarPinState } from './useSidebarPinState';
+
+describe('resolveSidebarPinState', () => {
+ it('personal mode: the column is the user own pin, no team pins', () => {
+ expect(
+ resolveSidebarPinState(
+ { id: 'a', pinned: true, visibility: 'public' },
+ { isWorkspace: false, myPinnedIds: [] },
+ ),
+ ).toEqual({ isMyPinned: true, isPrivate: false, isTeamPinned: false, isWorkspace: false });
+ });
+
+ it('workspace public row: the column is the team pin, the preference is mine', () => {
+ expect(
+ resolveSidebarPinState(
+ { id: 'a', pinned: true, visibility: 'public' },
+ { isWorkspace: true, myPinnedIds: [] },
+ ),
+ ).toMatchObject({ isMyPinned: false, isTeamPinned: true });
+ expect(
+ resolveSidebarPinState(
+ { id: 'a', pinned: false, visibility: 'public' },
+ { isWorkspace: true, myPinnedIds: ['a'] },
+ ),
+ ).toMatchObject({ isMyPinned: true, isTeamPinned: false });
+ });
+
+ it('workspace private row: its column is the creator own pin, never a team pin', () => {
+ expect(
+ resolveSidebarPinState(
+ { id: 'p', pinned: true, visibility: 'private' },
+ { isWorkspace: true, myPinnedIds: [] },
+ ),
+ ).toEqual({ isMyPinned: true, isPrivate: true, isTeamPinned: false, isWorkspace: true });
+ });
+});
diff --git a/src/features/HomeSidebar/Body/Agent/useSidebarPinState.ts b/src/features/HomeSidebar/Body/Agent/useSidebarPinState.ts
new file mode 100644
index 00000000000..98b5ab31ac8
--- /dev/null
+++ b/src/features/HomeSidebar/Body/Agent/useSidebarPinState.ts
@@ -0,0 +1,52 @@
+'use client';
+
+import type { SidebarVisibility } from '@lobechat/types';
+
+import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
+import { useUserStore } from '@/store/user';
+import { workspaceUserSettingsSelectors } from '@/store/user/selectors';
+
+interface SidebarPinStateInput {
+ id: string;
+ /** The row's own `pinned` column. */
+ pinned?: boolean | null;
+ visibility?: SidebarVisibility | null;
+}
+
+export interface SidebarPinState {
+ isMyPinned: boolean;
+ isPrivate: boolean;
+ isTeamPinned: boolean;
+ isWorkspace: boolean;
+}
+
+/**
+ * Pure resolver behind {@link useSidebarPinState}.
+ *
+ * - Personal mode: the column is the user's own pin.
+ * - Workspace, public row: the column is the team pin (owner/admin managed);
+ * the member's own pin lives in `sidebarPinnedItemIds`.
+ * - Workspace, private row: only the creator sees it, so its column is the
+ * creator's own pin — read alongside `sidebarPinnedItemIds`.
+ */
+export const resolveSidebarPinState = (
+ { id, pinned, visibility }: SidebarPinStateInput,
+ { isWorkspace, myPinnedIds }: { isWorkspace: boolean; myPinnedIds: readonly string[] },
+): SidebarPinState => {
+ const isPrivate = isWorkspace && visibility === 'private';
+ if (!isWorkspace) return { isMyPinned: !!pinned, isPrivate, isTeamPinned: false, isWorkspace };
+
+ return {
+ isMyPinned: myPinnedIds.includes(id) || (isPrivate && !!pinned),
+ isPrivate,
+ isTeamPinned: !isPrivate && !!pinned,
+ isWorkspace,
+ };
+};
+
+export const useSidebarPinState = (input: SidebarPinStateInput): SidebarPinState => {
+ const isWorkspace = !!useActiveWorkspaceId();
+ const myPinnedIds = useUserStore(workspaceUserSettingsSelectors.sidebarPinnedItemIds);
+
+ return resolveSidebarPinState(input, { isWorkspace, myPinnedIds });
+};
diff --git a/src/features/HomeSidebar/Body/CustomizeSidebarModal.tsx b/src/features/HomeSidebar/Body/CustomizeSidebarModal.tsx
index b657697a63a..342c128330c 100644
--- a/src/features/HomeSidebar/Body/CustomizeSidebarModal.tsx
+++ b/src/features/HomeSidebar/Body/CustomizeSidebarModal.tsx
@@ -75,7 +75,6 @@ const ALL_SIDEBAR_ITEMS: SidebarItemConfig[] = [
{ id: 'favorites', labelKey: 'favorite.section' },
{ id: 'recents', labelKey: 'recents' },
{ id: 'project', labelKey: 'tab.projects', routeId: 'project' },
- { id: 'private', labelKey: 'navPanel.privateAgents' },
{ alwaysVisible: true, id: 'agent', labelKey: 'navPanel.agent' },
{ id: 'image', labelKey: 'tab.generation', routeId: 'image' },
{ id: 'community', labelKey: 'tab.community', routeId: 'community' },
@@ -83,9 +82,6 @@ const ALL_SIDEBAR_ITEMS: SidebarItemConfig[] = [
{ id: 'memory', labelKey: 'tab.memory', routeId: 'memory' },
];
-// Private is workspace-only; in personal mode every row is implicitly
-// owner-private, so hide it from the customizer where toggling it on
-// would render an empty accordion no user can populate.
// Dashboards also stay out until the `dashboard` feature flag is on for the
// user, and Goals until the user turns on its lab; a dropped id is restored by
// `withAllKnownKeys` once it is.
@@ -100,7 +96,6 @@ export const getAvailableSidebarItems = (
if (item.id === 'dashboard' && !dashboardEnabled) return false;
if (item.id === 'goals' && !goalsEnabled) return false;
if (isWorkspaceMode && (item.id === 'memory' || item.id === 'dashboard')) return false;
- if (!isWorkspaceMode && item.id === 'private') return false;
return true;
});
@@ -187,12 +182,8 @@ const SortableItem = memo<{
onToggle: (key: string) => void;
}>(({ id, hiddenSections, onToggle }) => {
const { t } = useTranslation('common');
- const isWorkspaceMode = !!useActiveWorkspaceSlug();
const item = ITEM_MAP.get(id);
- // In workspace mode the Agent bucket pairs with Private, so the label
- // switches to "Public" — mirroring the sidebar header.
- const labelKey =
- item?.id === 'agent' && isWorkspaceMode ? 'navPanel.publicAgents' : item?.labelKey;
+ const labelKey = item?.labelKey;
const {
attributes,
isDragging,
@@ -346,8 +337,7 @@ const AccordionGroup = memo<{ children: React.ReactNode }>(({ children }) => {
const OverlayItem = memo<{ id: string }>(({ id }) => {
const { t } = useTranslation('common');
- const isWorkspaceMode = !!useActiveWorkspaceSlug();
- const agentLabelKey = isWorkspaceMode ? 'navPanel.publicAgents' : 'navPanel.agent';
+ const agentLabelKey = 'navPanel.agent';
// Accordion group overlay: render a compact representation
if (id === ACCORDION_GROUP_ID) {
diff --git a/src/features/HomeSidebar/Body/Private/List.tsx b/src/features/HomeSidebar/Body/Private/List.tsx
deleted file mode 100644
index 29ef158e014..00000000000
--- a/src/features/HomeSidebar/Body/Private/List.tsx
+++ /dev/null
@@ -1,92 +0,0 @@
-'use client';
-
-import { Flexbox } from '@lobehub/ui';
-import isEqual from 'fast-deep-equal';
-import { MoreHorizontal } from 'lucide-react';
-import { memo } from 'react';
-import { useTranslation } from 'react-i18next';
-
-import NavItem from '@/features/NavPanel/components/NavItem';
-import SkeletonList from '@/features/NavPanel/components/SkeletonList';
-import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
-import { useGlobalStore } from '@/store/global';
-import { systemStatusSelectors } from '@/store/global/selectors';
-import { useHomeStore } from '@/store/home';
-import { homeAgentListSelectors } from '@/store/home/selectors';
-
-import CreateAgentButton from '../Agent/CreateAgentButton';
-import Group from '../Agent/List/Group';
-import SessionList from '../Agent/List/List';
-import { useKeepSidebarGroupsListed, useKeepSidebarListed } from '../Agent/List/useAgentList';
-
-interface PrivateListProps {
- hideCreateButton?: boolean;
- onMoreClick?: () => void;
-}
-
-// Renders only the workspace-private bucket: pinned private items, then
-// private folders, then ungrouped agents/chat groups. The server already filters out
-// items the viewer can't see (other members' private rows), so this list
-// is always the viewer's own.
-const PrivateList = memo<PrivateListProps>(({ hideCreateButton, onMoreClick }) => {
- const { t } = useTranslation('chat');
- const isInit = useHomeStore(homeAgentListSelectors.isAgentListInit);
- const rawPrivatePinned = useHomeStore(homeAgentListSelectors.privatePinnedAgents, isEqual);
- const rawPrivateGroups = useHomeStore(homeAgentListSelectors.privateAgentGroups, isEqual);
- const privateAgentPageSize = useGlobalStore(systemStatusSelectors.privateAgentPageSize);
- const rawPrivateUngrouped = useHomeStore(homeAgentListSelectors.privateUngroupedAgents, isEqual);
- const navigate = useWorkspaceAwareNavigate();
- const keep = useKeepSidebarListed();
- const keepGroups = useKeepSidebarGroupsListed();
-
- if (!isInit) return <SkeletonList rows={2} />;
-
- // Drop the caller's sidebar-hidden items BEFORE the page-size cut so a
- // removal doesn't shrink the visible page below `privateAgentPageSize`.
- const privatePinned = keep(rawPrivatePinned);
- // Hidden Categories drop out here too, the same way the public list does —
- // otherwise hiding one from Category Management saves the preference and
- // changes nothing on screen.
- const privateGroups = keepGroups(rawPrivateGroups).map((group) => ({
- ...group,
- items: keep(group.items),
- }));
- const filteredUngrouped = keep(rawPrivateUngrouped);
- const privateUngrouped = filteredUngrouped.slice(0, privateAgentPageSize);
-
- const hasPinned = privatePinned.length > 0;
- const hasGroups = privateGroups.length > 0;
- const hasUngrouped = privateUngrouped.length > 0;
- const hasMore = filteredUngrouped.length > privateAgentPageSize;
- // The shared AllAgentsDrawer lists the workspace bucket, so the private
- // overflow routes to the private view-all tab instead; compact reusers
- // (e.g. the agent-detail switcher) pass their own navigation handler.
- const handleMoreClick = onMoreClick ?? (() => navigate('/agents?tab=private'));
-
- // Empty state still surfaces the create-button so a fresh user has an
- // obvious affordance for their first private agent.
- if (!hasPinned && !hasGroups && !hasUngrouped) {
- if (hideCreateButton) return null;
- return (
- <Flexbox gap={1} paddingBlock={1}>
- <CreateAgentButton visibility={'private'} />
- </Flexbox>
- );
- }
-
- return (
- <Flexbox gap={1} paddingBlock={1}>
- {hasPinned && <SessionList dataSource={privatePinned} />}
- {hasGroups && <Group dataSource={privateGroups} />}
- {hasUngrouped && <SessionList dataSource={privateUngrouped} />}
- {hasMore && (
- <NavItem icon={MoreHorizontal} title={t('input.more')} onClick={handleMoreClick} />
- )}
- {!hideCreateButton && <CreateAgentButton visibility={'private'} />}
- </Flexbox>
- );
-});
-
-PrivateList.displayName = 'PrivateList';
-
-export default PrivateList;
diff --git a/src/features/HomeSidebar/Body/Private/index.tsx b/src/features/HomeSidebar/Body/Private/index.tsx
deleted file mode 100644
index 07331dbecee..00000000000
--- a/src/features/HomeSidebar/Body/Private/index.tsx
+++ /dev/null
@@ -1,147 +0,0 @@
-'use client';
-
-import {
- AccordionHeader,
- AccordionItem,
- AccordionPanel,
- accordionStyles,
- AccordionTrigger,
- ActionIcon,
- ContextMenuTrigger,
- cx,
- Flexbox,
- Spin,
- Text,
-} from '@lobehub/ui';
-import { ArrowRight } from 'lucide-react';
-import React, { memo, type MouseEvent, Suspense, useCallback, useMemo } from 'react';
-import { useTranslation } from 'react-i18next';
-
-import SkeletonList from '@/features/NavPanel/components/SkeletonList';
-import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
-import { useFetchAgentList } from '@/hooks/useFetchAgentList';
-
-import { useCreateMenuItems } from '../../hooks';
-import Actions from '../Agent/Actions';
-import { useAgentModal } from '../Agent/ModalProvider';
-import PrivateList from './List';
-import { usePrivateActionsDropdownMenu } from './useDropdownMenu';
-
-interface PrivateProps {
- itemKey: string;
-}
-
-// Top-level "Private" sidebar section, structurally mirroring the Agent
-// accordion. Everything created from the `+` button is hard-pinned to
-// `visibility: 'private'`, so users get a predictable bucket for personal
-// work without ever having to think about visibility flags.
-//
-// Sidebar-level controls (manage groups, move up/down, customize sidebar)
-// live in the "More" dropdown so private management stays consistent with
-// the workspace-public Agent section.
-const Private = memo<PrivateProps>(({ itemKey }) => {
- const { t } = useTranslation('common');
- const { isRevalidating } = useFetchAgentList();
-
- const { openConfigGroupModal } = useAgentModal();
-
- const {
- createAgentListMenuItem,
- createAgentMenuItem,
- createConnectAgentMenuItem,
- createGroupChatMenuItem,
- createMarketAgentMenuItem,
- isLoading,
- } = useCreateMenuItems();
-
- // Mirror the public Agent "+" menu so the create surface is consistent
- // across both buckets — heterogeneous and platform agents are hard-pinned
- // to private here. Session-group creation lives in the "More" dropdown.
- const addMenuItems = useMemo(() => {
- const connectItem = createConnectAgentMenuItem({ visibility: 'private' });
-
- return [
- createAgentMenuItem({ visibility: 'private' }),
- createGroupChatMenuItem({ visibility: 'private' }),
- ...(connectItem ? [{ type: 'divider' as const }, connectItem] : []),
- // Same discovery entries as the workspace-public section — the agent
- // list opens on the Private tab so the surface matches this bucket.
- { type: 'divider' as const },
- createAgentListMenuItem({ visibility: 'private' }),
- createMarketAgentMenuItem(),
- ];
- }, [
- createAgentListMenuItem,
- createAgentMenuItem,
- createConnectAgentMenuItem,
- createGroupChatMenuItem,
- createMarketAgentMenuItem,
- ]);
-
- const handleOpenConfigGroupModal = useCallback(() => {
- openConfigGroupModal('private');
- }, [openConfigGroupModal]);
-
- const dropdownMenu = usePrivateActionsDropdownMenu({
- openConfigGroupModal: handleOpenConfigGroupModal,
- });
-
- const navigate = useWorkspaceAwareNavigate();
- const handleViewAll = useCallback(
- (e: MouseEvent) => {
- // Stop the click from toggling the accordion header.
- e.stopPropagation();
- // Land the view-all page on the tab matching this section.
- navigate('/agents?tab=private');
- },
- [navigate],
- );
-
- return (
- <AccordionItem value={itemKey}>
- <ContextMenuTrigger items={dropdownMenu}>
- <AccordionHeader>
- <AccordionTrigger style={{ paddingBlock: 4, paddingInline: '8px 4px' }}>
- <Flexbox horizontal align="center" gap={4}>
- <Text ellipsis fontSize={12} type={'secondary'} weight={500}>
- {t('navPanel.privateAgents', { defaultValue: 'Private' })}
- </Text>
- {isRevalidating && <Spin size="small" variant="network" />}
- </Flexbox>
- </AccordionTrigger>
- <Flexbox
- horizontal
- align="center"
- gap={2}
- className={cx(
- 'accordion-action',
- accordionStyles.action,
- accordionStyles.actionBorderless,
- )}
- >
- <ActionIcon
- icon={ArrowRight}
- size={'small'}
- title={t('navPanel.viewAllAgents')}
- onClick={handleViewAll}
- />
- <Actions
- addMenuItems={addMenuItems}
- dropdownMenu={dropdownMenu}
- isLoading={isLoading}
- />
- </Flexbox>
- </AccordionHeader>
- </ContextMenuTrigger>
- <AccordionPanel>
- <Suspense fallback={<SkeletonList rows={3} />}>
- <PrivateList />
- </Suspense>
- </AccordionPanel>
- </AccordionItem>
- );
-});
-
-Private.displayName = 'Private';
-
-export default Private;
diff --git a/src/features/HomeSidebar/Body/Private/useDropdownMenu.tsx b/src/features/HomeSidebar/Body/Private/useDropdownMenu.tsx
deleted file mode 100644
index b1ead8b2e47..00000000000
--- a/src/features/HomeSidebar/Body/Private/useDropdownMenu.tsx
+++ /dev/null
@@ -1,108 +0,0 @@
-import { type DropdownItem } from '@lobehub/ui';
-import { Icon } from '@lobehub/ui';
-import { ArrowDownIcon, ArrowUpIcon, Hash, LucideCheck, SlidersHorizontalIcon } from 'lucide-react';
-import { useCallback, useMemo } from 'react';
-import { useTranslation } from 'react-i18next';
-
-import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
-import { openCustomizeSidebarModal } from '@/features/HomeSidebar/Body/CustomizeSidebarModal';
-import { useGlobalStore } from '@/store/global';
-import { systemStatusSelectors } from '@/store/global/selectors';
-import { reorderSidebarItems } from '@/store/global/selectors/systemStatus';
-
-import { useCreateMenuItems } from '../../hooks';
-
-interface PrivateActionsDropdownMenuProps {
- openConfigGroupModal: () => void;
-}
-
-export const usePrivateActionsDropdownMenu = ({
- openConfigGroupModal,
-}: PrivateActionsDropdownMenuProps): DropdownItem[] => {
- const { t } = useTranslation('common');
-
- const activeWorkspaceId = useActiveWorkspaceId();
- const privateAgentPageSize = useGlobalStore(systemStatusSelectors.privateAgentPageSize);
- const sidebarItems = useGlobalStore(systemStatusSelectors.sidebarItems(activeWorkspaceId));
- const hiddenSections = useGlobalStore(
- systemStatusSelectors.hiddenSidebarSections(activeWorkspaceId),
- );
- const updateSystemStatus = useGlobalStore((s) => s.updateSystemStatus);
-
- const visibleItems = sidebarItems.filter((k) => !hiddenSections.includes(k));
- const visibleIndex = visibleItems.indexOf('private');
- const isFirst = visibleIndex <= 0;
- const isLast = visibleIndex === visibleItems.length - 1;
-
- const moveSection = useCallback(
- (direction: 'up' | 'down') => {
- const idx = sidebarItems.indexOf('private');
- if (idx === -1) return;
- const next = reorderSidebarItems(sidebarItems, idx, direction === 'up' ? idx - 1 : idx + 1);
- if (next === sidebarItems) return;
- updateSystemStatus({ sidebarItems: next });
- },
- [sidebarItems, updateSystemStatus],
- );
-
- const { createSessionGroupMenuItem, configMenuItem } = useCreateMenuItems();
-
- return useMemo(() => {
- const createSessionGroupItem = createSessionGroupMenuItem({ visibility: 'private' });
- const configItem = configMenuItem(openConfigGroupModal);
-
- const pageSizeOptions = [5, 10, 15, 20];
- const pageSizeItems = pageSizeOptions.map((size) => ({
- icon: privateAgentPageSize === size ? <Icon icon={LucideCheck} /> : <div />,
- key: `pageSize-${size}`,
- label: t('pageSizeItem', { count: size }),
- onClick: () => {
- updateSystemStatus({ privateAgentPageSize: size });
- },
- }));
-
- return [
- createSessionGroupItem,
- configItem,
- { type: 'divider' as const },
- {
- children: pageSizeItems,
- extra: privateAgentPageSize,
- icon: <Icon icon={Hash} />,
- key: 'show',
- label: t('navPanel.show'),
- },
- {
- disabled: isFirst,
- icon: <Icon icon={ArrowUpIcon} />,
- key: 'moveUp',
- label: t('navPanel.moveUp'),
- onClick: () => moveSection('up'),
- },
- {
- disabled: isLast,
- icon: <Icon icon={ArrowDownIcon} />,
- key: 'moveDown',
- label: t('navPanel.moveDown'),
- onClick: () => moveSection('down'),
- },
- { type: 'divider' as const },
- {
- icon: <Icon icon={SlidersHorizontalIcon} />,
- key: 'customizeSidebar',
- label: t('navPanel.customizeSidebar'),
- onClick: () => openCustomizeSidebarModal(),
- },
- ].filter(Boolean) as DropdownItem[];
- }, [
- privateAgentPageSize,
- updateSystemStatus,
- createSessionGroupMenuItem,
- configMenuItem,
- openConfigGroupModal,
- isFirst,
- isLast,
- moveSection,
- t,
- ]);
-};
diff --git a/src/features/HomeSidebar/Body/index.test.tsx b/src/features/HomeSidebar/Body/index.test.tsx
index d7110312e51..f435d0fd210 100644
--- a/src/features/HomeSidebar/Body/index.test.tsx
+++ b/src/features/HomeSidebar/Body/index.test.tsx
@@ -101,10 +101,6 @@ vi.mock('./Agent', () => ({
default: ({ itemKey }: { itemKey: string }) => <div data-testid={`sidebar-item-${itemKey}`} />,
}));
-vi.mock('./Private', () => ({
- default: ({ itemKey }: { itemKey: string }) => <div data-testid={`sidebar-item-${itemKey}`} />,
-}));
-
vi.mock('./CustomizeSidebarModal', () => ({
openCustomizeSidebarModal: vi.fn(),
}));
diff --git a/src/features/HomeSidebar/Body/index.tsx b/src/features/HomeSidebar/Body/index.tsx
index adcd6826ab5..ec4ce748004 100644
--- a/src/features/HomeSidebar/Body/index.tsx
+++ b/src/features/HomeSidebar/Body/index.tsx
@@ -26,7 +26,6 @@ import { isModifierClick } from '@/utils/navigation';
import Agent from './Agent';
import { openCustomizeSidebarModal } from './CustomizeSidebarModal';
import Favorites from './Favorites';
-import Private from './Private';
import { useSyncWorkspaceSidebarPreference } from './useSyncWorkspaceSidebarPreference';
export enum GroupKey {
@@ -34,18 +33,12 @@ export enum GroupKey {
Community = 'community',
Favorites = 'favorites',
Pages = 'pages',
- Private = 'private',
Project = 'project',
Recents = 'recents',
Resource = 'resource',
}
-const ACCORDION_KEYS = new Set<string>([
- GroupKey.Favorites,
- GroupKey.Recents,
- GroupKey.Agent,
- GroupKey.Private,
-]);
+const ACCORDION_KEYS = new Set<string>([GroupKey.Favorites, GroupKey.Recents, GroupKey.Agent]);
/** Keys rendered in the header — must be excluded from the body to avoid duplicates
* when migrating users whose persisted sidebarItems still include them. */
@@ -55,7 +48,6 @@ const SECTION_GAP = 8;
const accordionComponents: Record<string, (key: string) => ReactElement> = {
[GroupKey.Agent]: (key) => <Agent itemKey={key} key={key} />,
[GroupKey.Favorites]: (key) => <Favorites itemKey={key} key={key} />,
- [GroupKey.Private]: (key) => <Private itemKey={key} key={key} />,
[GroupKey.Recents]: (key) => <Recents itemKey={key} key={key} />,
};
@@ -80,11 +72,8 @@ const Body = memo(() => {
const tab = useActiveTabKey();
const navigate = useWorkspaceAwareNavigate();
const { topNavItems, bottomMenuItems } = useNavLayout();
- // Personal mode has no notion of "private vs workspace-public" — every row
- // is implicitly the owner's. Hide the Private section entirely there so the
- // sidebar doesn't sprout an empty accordion users can't populate.
const activeWorkspaceId = useActiveWorkspaceId();
- // The Agent/Private sections subtract the caller's sidebar-hidden items,
+ // The Agents section subtracts the caller's sidebar-hidden items,
// and the section layout syncs per-member — both live in the workspace
// user preference, so load it alongside the sidebar.
const useFetchWorkspaceUserPreference = useUserStore((s) => s.useFetchWorkspaceUserPreference);
@@ -141,13 +130,9 @@ const Body = memo(() => {
// Items that must always be visible regardless of hiddenSections
const isVisible = useCallback(
(k: string) => {
- // Private accordion is workspace-only. In personal mode every row is
- // implicitly owner-private, so a dedicated bucket would be a noisy
- // empty section.
- if (k === GroupKey.Private && !activeWorkspaceId) return false;
return k === GroupKey.Agent || k === SIDEBAR_SPACER_ID || !hiddenSections.includes(k);
},
- [hiddenSections, activeWorkspaceId],
+ [hiddenSections],
);
const visibleKeys = useMemo(
diff --git a/src/features/HomeSidebar/Body/useSyncWorkspaceSidebarPreference.test.tsx b/src/features/HomeSidebar/Body/useSyncWorkspaceSidebarPreference.test.tsx
index 4d6ea39e71d..542f16880a5 100644
--- a/src/features/HomeSidebar/Body/useSyncWorkspaceSidebarPreference.test.tsx
+++ b/src/features/HomeSidebar/Body/useSyncWorkspaceSidebarPreference.test.tsx
@@ -88,4 +88,32 @@ describe('useSyncWorkspaceSidebarPreference', () => {
expect(workspace?.sidebarItems).toEqual(['projects', 'agents']);
expect(workspace?.hiddenSidebarSections).toEqual(['recents']);
});
+
+ it('writes a layout that still names the former Private section back merged', () => {
+ const updateWorkspaceUserPreference = vi.fn().mockResolvedValue(undefined);
+ useUserStore.setState({
+ updateWorkspaceUserPreference,
+ workspaceUserPreference: {
+ sidebar: {
+ hiddenSections: ['recents', 'private'],
+ items: ['recents', 'private', 'agent', '__spacer__', 'image'],
+ },
+ },
+ workspaceUserPreferenceWorkspaceId: 'ws-b',
+ });
+
+ renderHook(() => useSyncWorkspaceSidebarPreference('ws-b'));
+
+ const workspace = useGlobalStore.getState().status.workspace;
+ // Read side: one Agents section, no empty or duplicate one.
+ expect(workspace?.sidebarItems).toEqual(['recents', 'agent', '__spacer__', 'image']);
+ expect(workspace?.hiddenSidebarSections).toEqual(['recents']);
+ // Write side: the normalized layout is persisted once, replacing `private`.
+ expect(updateWorkspaceUserPreference).toHaveBeenCalledWith({
+ sidebar: {
+ hiddenSections: ['recents'],
+ items: ['recents', 'agent', '__spacer__', 'image'],
+ },
+ });
+ });
});
diff --git a/src/features/HomeSidebar/Body/useSyncWorkspaceSidebarPreference.ts b/src/features/HomeSidebar/Body/useSyncWorkspaceSidebarPreference.ts
index 991587c957e..796fc08727c 100644
--- a/src/features/HomeSidebar/Body/useSyncWorkspaceSidebarPreference.ts
+++ b/src/features/HomeSidebar/Body/useSyncWorkspaceSidebarPreference.ts
@@ -3,6 +3,10 @@ import isEqual from 'fast-deep-equal';
import { useEffect } from 'react';
import { useGlobalStore } from '@/store/global';
+import {
+ normalizeLegacyAgentItems,
+ normalizeLegacyHiddenSections,
+} from '@/store/global/selectors/systemStatus';
import { useUserStore } from '@/store/user';
import { workspaceUserSettingsSelectors } from '@/store/user/selectors';
@@ -31,13 +35,32 @@ export const useSyncWorkspaceSidebarPreference = (workspaceId: string | null) =>
// before that, `serverSidebar` may be the previous workspace's value (or
// an unfetched placeholder) and must not be pulled or cleared from.
if (!workspaceId || loadedWorkspaceId !== workspaceId) return;
+ // Saved layouts may still name the former "Private" section, merged into
+ // "Agents" since. Normalize on the way in so the sidebar renders one
+ // Agents section, and write the merged layout back once so the stored
+ // preference stops carrying the legacy key. (The push effect below only
+ // reacts to later overlay edits, so it would not persist this on its own.)
+ const items = serverSidebar?.items ? normalizeLegacyAgentItems(serverSidebar.items) : undefined;
+ const hiddenSections = serverSidebar?.hiddenSections
+ ? normalizeLegacyHiddenSections(serverSidebar.hiddenSections)
+ : undefined;
+
// Replace wholesale: a field the server preference does not carry must be
// DELETED from the shared overlay bucket (not left behind by a deep
// merge), or the previous workspace's layout leaks into this one.
useGlobalStore.getState().setWorkspaceSidebarOverlay({
- hiddenSidebarSections: serverSidebar?.hiddenSections,
- sidebarItems: serverSidebar?.items,
+ hiddenSidebarSections: hiddenSections,
+ sidebarItems: items,
});
+
+ if (items !== serverSidebar?.items || hiddenSections !== serverSidebar?.hiddenSections) {
+ void useUserStore.getState().updateWorkspaceUserPreference({
+ sidebar: {
+ ...(hiddenSections ? { hiddenSections } : {}),
+ ...(items ? { items } : {}),
+ },
+ });
+ }
}, [workspaceId, serverSidebar, loadedWorkspaceId]);
// Push: persist local overlay edits (and seed the server from a
diff --git a/src/features/HomeSidebar/hooks/useRevealSidebarSection.test.ts b/src/features/HomeSidebar/hooks/useRevealSidebarSection.test.ts
index d19d49aaece..391c48cd114 100644
--- a/src/features/HomeSidebar/hooks/useRevealSidebarSection.test.ts
+++ b/src/features/HomeSidebar/hooks/useRevealSidebarSection.test.ts
@@ -4,36 +4,25 @@ import { buildRevealSidebarSectionPatch } from './useRevealSidebarSection';
describe('buildRevealSidebarSectionPatch ', () => {
it('expands a collapsed section', () => {
- // Stale persisted keys from before the Private section shipped.
- expect(buildRevealSidebarSectionPatch('private', ['recents', 'agent'], [])).toEqual({
- sidebarExpandedKeys: ['recents', 'agent', 'private'],
+ expect(buildRevealSidebarSectionPatch('agent', ['recents'], [])).toEqual({
+ sidebarExpandedKeys: ['recents', 'agent'],
});
});
it('un-hides a hidden section', () => {
- expect(
- buildRevealSidebarSectionPatch('private', ['recents', 'agent', 'private'], ['private']),
- ).toEqual({
+ expect(buildRevealSidebarSectionPatch('agent', ['recents', 'agent'], ['agent'])).toEqual({
hiddenSidebarSections: [],
});
});
it('expands and un-hides in one patch', () => {
- expect(buildRevealSidebarSectionPatch('private', ['agent'], ['recents', 'private'])).toEqual({
+ expect(buildRevealSidebarSectionPatch('agent', ['favorites'], ['recents', 'agent'])).toEqual({
hiddenSidebarSections: ['recents'],
- sidebarExpandedKeys: ['agent', 'private'],
+ sidebarExpandedKeys: ['favorites', 'agent'],
});
});
it('returns null when the section is already visible', () => {
- expect(
- buildRevealSidebarSectionPatch('private', ['recents', 'agent', 'private'], ['recents']),
- ).toBeNull();
- });
-
- it('handles the workspace (agent) section for the publish direction', () => {
- expect(buildRevealSidebarSectionPatch('agent', ['recents', 'private'], [])).toEqual({
- sidebarExpandedKeys: ['recents', 'private', 'agent'],
- });
+ expect(buildRevealSidebarSectionPatch('agent', ['recents', 'agent'], ['recents'])).toBeNull();
});
});
diff --git a/src/features/HomeSidebar/hooks/useRevealSidebarSection.ts b/src/features/HomeSidebar/hooks/useRevealSidebarSection.ts
index 99726424ba3..6924f7b9e88 100644
--- a/src/features/HomeSidebar/hooks/useRevealSidebarSection.ts
+++ b/src/features/HomeSidebar/hooks/useRevealSidebarSection.ts
@@ -10,7 +10,7 @@ import { systemStatusSelectors } from '@/store/global/selectors';
* `../Body` — not imported from there to avoid a hooks ⇄ Body import cycle
* (Body renders sections that consume these hooks).
*/
-export type RevealableSidebarSection = 'agent' | 'private';
+export type RevealableSidebarSection = 'agent';
/**
* Compute the system-status patch that makes a sidebar section visible after
@@ -18,12 +18,10 @@ export type RevealableSidebarSection = 'agent' | 'private';
* user-applied section hide. Returns `null` when the section is already
* fully visible so callers can skip the store write.
*
- * Why this exists: `sidebarExpandedKeys` is persisted, so
- * accounts whose keys were saved before a section shipped (e.g. `private`,
- * added with workspace private agents) never include the new key — the
- * section stays collapsed forever. "Make private" then moves the agent into
- * a collapsed (or hidden) Private section with zero visual feedback, which
- * reads as the agent silently disappearing.
+ * Why this exists: `sidebarExpandedKeys` is persisted, so a collapsed or
+ * hidden Agents section would swallow an agent that "Publish to Workspace" /
+ * "Make private" just regrouped, with zero visual feedback — which reads as
+ * the agent silently disappearing.
*/
export const buildRevealSidebarSectionPatch = (
section: RevealableSidebarSection,
diff --git a/src/features/MessageList/GroupConversation.tsx b/src/features/MessageList/GroupConversation.tsx
index d364978f990..f247767a1b3 100644
--- a/src/features/MessageList/GroupConversation.tsx
+++ b/src/features/MessageList/GroupConversation.tsx
@@ -18,7 +18,7 @@ interface GroupConversationProps {
const GroupConversation = memo<GroupConversationProps>(({ active, conversation }) => {
const { item, preview, activeAt } = conversation;
- const { id, avatar, backgroundColor, description, pinned, userId } = item;
+ const { id, avatar, backgroundColor, description, pinned, userId, visibility } = item;
const { t } = useTranslation('chat');
const title = item.title || t('untitledAgent');
const customAvatar = typeof avatar === 'string' ? avatar : undefined;
@@ -36,6 +36,7 @@ const GroupConversation = memo<GroupConversationProps>(({ active, conversation }
pinned: pinned ?? false,
title,
userId,
+ visibility,
});
return (
diff --git a/src/store/global/initialState.ts b/src/store/global/initialState.ts
index ac4466405a9..be63b30f491 100644
--- a/src/store/global/initialState.ts
+++ b/src/store/global/initialState.ts
@@ -154,7 +154,7 @@ export type TaskViewMode = 'kanban' | 'list';
/** How topics inside one byProject sidebar group are sectioned. */
export type ProjectTopicSubGroupMode = 'none' | 'byDevice' | 'byTime' | 'byStatus';
-export const DEFAULT_HOME_SIDEBAR_EXPANDED_KEYS = ['favorites', 'recents', 'agent', 'private'];
+export const DEFAULT_HOME_SIDEBAR_EXPANDED_KEYS = ['favorites', 'recents', 'agent'];
/** How the agent document tree orders sibling rows. */
export interface AgentDocumentSort {
@@ -228,7 +228,8 @@ export interface SystemStatus {
* Display options of the agent view-all page (grouping / ordering / hidden-agent visibility)
*/
agentListViewOptions?: {
- groupBy: 'author' | 'label' | 'none';
+ /** Unset until the member picks one; the page then defaults per mode. */
+ groupBy?: 'author' | 'folder' | 'label' | 'none';
orderBy: 'author' | 'title' | 'updatedAt';
orderDirection: 'asc' | 'desc';
showSidebarHidden: boolean;
@@ -654,7 +655,6 @@ export const INITIAL_STATUS = {
agentListSidebarSectionCollapsed: false,
agentListViewMode: 'card' as const,
agentListViewOptions: {
- groupBy: 'none' as const,
orderBy: 'updatedAt' as const,
orderDirection: 'desc' as const,
showSidebarHidden: true,
diff --git a/src/store/global/selectors/systemStatus.legacyAgentKeys.test.ts b/src/store/global/selectors/systemStatus.legacyAgentKeys.test.ts
new file mode 100644
index 00000000000..c32577da954
--- /dev/null
+++ b/src/store/global/selectors/systemStatus.legacyAgentKeys.test.ts
@@ -0,0 +1,112 @@
+import { describe, expect, it } from 'vitest';
+
+import { merge } from '@/utils/merge';
+
+import type { GlobalState } from '../initialState';
+import { initialState } from '../initialState';
+import {
+ normalizeLegacyAgentItems,
+ normalizeLegacyExpandedKeys,
+ normalizeLegacyHiddenSections,
+ SIDEBAR_SPACER_ID,
+ systemStatusSelectors,
+} from './systemStatus';
+
+// The workspace "Private" accordion (`private`) was merged into the single
+// "Agents" section (`agent`). Saved layouts from before must keep working.
+describe('legacy `private` sidebar key', () => {
+ describe('normalizeLegacyAgentItems', () => {
+ it('drops `private` when `agent` is already in the order', () => {
+ expect(normalizeLegacyAgentItems(['recents', 'private', 'agent', 'image'])).toEqual([
+ 'recents',
+ 'agent',
+ 'image',
+ ]);
+ });
+
+ it('puts `agent` where `private` was when the order has no `agent`', () => {
+ expect(normalizeLegacyAgentItems(['tasks', 'private', 'recents'])).toEqual([
+ 'tasks',
+ 'agent',
+ 'recents',
+ ]);
+ });
+
+ it('returns the same reference when there is nothing to migrate', () => {
+ const items = ['recents', 'agent'];
+ expect(normalizeLegacyAgentItems(items)).toBe(items);
+ });
+ });
+
+ it('drops `private` from hidden sections (Agents is always shown)', () => {
+ expect(normalizeLegacyHiddenSections(['recents', 'private'])).toEqual(['recents']);
+ const untouched = ['recents'];
+ expect(normalizeLegacyHiddenSections(untouched)).toBe(untouched);
+ });
+
+ it('keeps Agents expanded when either former section was expanded', () => {
+ expect(normalizeLegacyExpandedKeys(['recents', 'private'])).toEqual(['recents', 'agent']);
+ expect(normalizeLegacyExpandedKeys(['agent', 'private'])).toEqual(['agent']);
+ const untouched = ['recents'];
+ expect(normalizeLegacyExpandedKeys(untouched)).toBe(untouched);
+ });
+
+ describe('selectors', () => {
+ const legacyWorkspace: GlobalState = merge(initialState, {
+ status: {
+ workspace: {
+ hiddenSidebarSections: ['recents', 'private'],
+ sidebarExpandedKeys: ['favorites', 'private'],
+ sidebarItems: [
+ 'tasks',
+ 'favorites',
+ 'recents',
+ 'private',
+ 'agent',
+ SIDEBAR_SPACER_ID,
+ 'image',
+ ],
+ },
+ },
+ });
+
+ it('renders exactly one Agents section for a saved workspace layout', () => {
+ const items = systemStatusSelectors.sidebarItems('ws-1')(legacyWorkspace);
+
+ expect(items).not.toContain('private');
+ expect(items.filter((key) => key === 'agent')).toHaveLength(1);
+ // Stays in the accordion block, right above the spacer.
+ expect(items[items.indexOf(SIDEBAR_SPACER_ID) - 1]).toBe('agent');
+ });
+
+ it('does not resurrect `private` through the missing-key backfill', () => {
+ const s: GlobalState = merge(initialState, {
+ status: { sidebarItems: ['private', 'recents'] },
+ });
+ const items = systemStatusSelectors.sidebarItems(null)(s);
+
+ expect(items).not.toContain('private');
+ expect(items.filter((key) => key === 'agent')).toHaveLength(1);
+ });
+
+ it('normalizes hidden and expanded keys', () => {
+ expect(systemStatusSelectors.hiddenSidebarSections('ws-1')(legacyWorkspace)).toEqual([
+ 'recents',
+ ]);
+ expect(systemStatusSelectors.sidebarExpandedKeys('ws-1')(legacyWorkspace)).toEqual([
+ 'favorites',
+ 'agent',
+ ]);
+ });
+
+ it('normalizes a legacy `sidebarSectionOrder` too', () => {
+ const s: GlobalState = merge(initialState, {
+ status: { sidebarSectionOrder: ['private', 'recents'] },
+ });
+ const items = systemStatusSelectors.sidebarItems(null)(s);
+
+ expect(items).not.toContain('private');
+ expect(items.indexOf('agent')).toBeLessThan(items.indexOf('recents'));
+ });
+ });
+});
diff --git a/src/store/global/selectors/systemStatus.test.ts b/src/store/global/selectors/systemStatus.test.ts
index 8f5d3b54f5e..dece38ace00 100644
--- a/src/store/global/selectors/systemStatus.test.ts
+++ b/src/store/global/selectors/systemStatus.test.ts
@@ -282,7 +282,6 @@ describe('systemStatusSelectors', () => {
'project',
'dashboard',
'favorites',
- 'private',
'agent',
'recents',
SIDEBAR_SPACER_ID,
@@ -315,7 +314,10 @@ describe('systemStatusSelectors', () => {
const s: GlobalState = merge(initialState, {
status: { sidebarItems: stored },
});
- expect(systemStatusSelectors.sidebarItems(null)(s)).toEqual(stored);
+ // The former Private section is merged into Agents.
+ expect(systemStatusSelectors.sidebarItems(null)(s)).toEqual(
+ stored.filter((key) => key !== 'private'),
+ );
});
it('should re-anchor the spacer when stored above the accordion', () => {
@@ -344,7 +346,6 @@ describe('systemStatusSelectors', () => {
'dashboard',
'favorites',
'recents',
- 'private',
'agent',
SIDEBAR_SPACER_ID,
'image',
@@ -381,7 +382,6 @@ describe('systemStatusSelectors', () => {
'resource',
'favorites',
'recents',
- 'private',
'agent',
SIDEBAR_SPACER_ID,
'image',
@@ -417,7 +417,6 @@ describe('systemStatusSelectors', () => {
'resource',
'favorites',
'recents',
- 'private',
'agent',
SIDEBAR_SPACER_ID,
'image',
@@ -428,7 +427,10 @@ describe('systemStatusSelectors', () => {
const s: GlobalState = merge(initialState, {
status: { sidebarItems: stored },
});
- expect(systemStatusSelectors.sidebarItems(null)(s)).toEqual(stored);
+ // The former Private section is merged into Agents.
+ expect(systemStatusSelectors.sidebarItems(null)(s)).toEqual(
+ stored.filter((key) => key !== 'private'),
+ );
});
it('should slot missing top-group defaults before the accordion block', () => {
@@ -460,7 +462,7 @@ describe('systemStatusSelectors', () => {
status: { sidebarSectionOrder: ['agent', 'recents'] },
});
const items = systemStatusSelectors.sidebarItems(null)(s);
- // accordion slot uses the user's legacy order; `private` (added after
+ // accordion slot uses the user's legacy order; `favorites` (added after
// the legacy state was saved) is backfilled at the head of the block.
expect(items).toEqual([
'tasks',
@@ -469,7 +471,6 @@ describe('systemStatusSelectors', () => {
'dashboard',
'resource',
'favorites',
- 'private',
'agent',
'recents',
SIDEBAR_SPACER_ID,
@@ -484,8 +485,7 @@ describe('systemStatusSelectors', () => {
status: { sidebarSectionOrder: ['recents', 'agent'] },
});
const items = systemStatusSelectors.sidebarItems(null)(s);
- // `private` (new accordion entry not present in legacy state) is
- // backfilled at the head of the block; recents/agent keep legacy order.
+ // recents/agent keep their legacy order.
expect(items).toEqual([
'tasks',
'goals',
@@ -493,7 +493,6 @@ describe('systemStatusSelectors', () => {
'dashboard',
'resource',
'favorites',
- 'private',
'recents',
'agent',
SIDEBAR_SPACER_ID,
diff --git a/src/store/global/selectors/systemStatus.ts b/src/store/global/selectors/systemStatus.ts
index c8d974b381f..accfce2555c 100644
--- a/src/store/global/selectors/systemStatus.ts
+++ b/src/store/global/selectors/systemStatus.ts
@@ -207,24 +207,26 @@ const hiddenSidebarSections =
const overlay = s.status.workspace?.hiddenSidebarSections;
// Once the user touches sidebar visibility in this workspace the overlay
// owns the list — including an explicit empty array meaning "show all".
- if (overlay !== undefined) return overlay;
+ if (overlay !== undefined) return normalizeLegacyHiddenSections(overlay);
// Untouched workspace: inherit any personal-mode hides and layer the
// workspace defaults on top so `recents` starts collapsed.
const personal = s.status.hiddenSidebarSections ?? DEFAULT_HIDDEN_SECTIONS;
- const merged = [...personal];
+ const merged = [...normalizeLegacyHiddenSections(personal)];
for (const k of WORKSPACE_DEFAULT_HIDDEN_SECTIONS) {
if (!merged.includes(k)) merged.push(k);
}
return merged;
}
- return s.status.hiddenSidebarSections ?? DEFAULT_HIDDEN_SECTIONS;
+ return normalizeLegacyHiddenSections(s.status.hiddenSidebarSections ?? DEFAULT_HIDDEN_SECTIONS);
};
const sidebarExpandedKeys =
(workspaceId: string | null) =>
(s: GlobalState): string[] =>
- readOverridableField(s.status, 'sidebarExpandedKeys', workspaceId) ??
- DEFAULT_HOME_SIDEBAR_EXPANDED_KEYS;
+ normalizeLegacyExpandedKeys(
+ readOverridableField(s.status, 'sidebarExpandedKeys', workspaceId) ??
+ DEFAULT_HOME_SIDEBAR_EXPANDED_KEYS,
+ );
/** Sentinel id representing the flex spacer slot. Its position in `sidebarItems`
* determines where the sidebar pushes items to the bottom. */
@@ -238,7 +240,6 @@ export const DEFAULT_SIDEBAR_ITEMS: string[] = [
'resource',
'favorites',
'recents',
- 'private',
'agent',
SIDEBAR_SPACER_ID,
'image',
@@ -246,10 +247,54 @@ export const DEFAULT_SIDEBAR_ITEMS: string[] = [
'memory',
];
-/** Items that must stay contiguous in the sidebar list (accordion block).
- * `private` sits above `agent` so workspace users see their personal items
- * first, with the workspace-shared agents right below. */
-export const SIDEBAR_ACCORDION_KEYS = new Set(['favorites', 'recents', 'private', 'agent']);
+/** Items that must stay contiguous in the sidebar list (accordion block). */
+export const SIDEBAR_ACCORDION_KEYS = new Set(['favorites', 'recents', 'agent']);
+
+/**
+ * Section key of the former workspace "Private" accordion. It was merged into
+ * the single "Agents" (`agent`) section; saved layouts may still carry it.
+ */
+export const LEGACY_PRIVATE_SECTION_KEY = 'private';
+const AGENT_SECTION_KEY = 'agent';
+
+/**
+ * Map a saved section order onto the merged Agents section: `private` is
+ * dropped, and when the order has no `agent` yet, `agent` takes the slot
+ * `private` held. Returns the input reference when nothing changes.
+ */
+export const normalizeLegacyAgentItems = (items: string[]): string[] => {
+ const privateIndex = items.indexOf(LEGACY_PRIVATE_SECTION_KEY);
+ if (privateIndex === -1) return items;
+
+ if (items.includes(AGENT_SECTION_KEY)) {
+ return items.filter((key) => key !== LEGACY_PRIVATE_SECTION_KEY);
+ }
+ const next = [...items];
+ next[privateIndex] = AGENT_SECTION_KEY;
+ return next.filter((key) => key !== LEGACY_PRIVATE_SECTION_KEY);
+};
+
+/**
+ * Hidden sections: `private` no longer exists and the Agents section is always
+ * shown, so the key is simply dropped.
+ */
+export const normalizeLegacyHiddenSections = (hidden: string[]): string[] =>
+ hidden.includes(LEGACY_PRIVATE_SECTION_KEY)
+ ? hidden.filter((key) => key !== LEGACY_PRIVATE_SECTION_KEY)
+ : hidden;
+
+/**
+ * Expanded sections: the merged Agents section stays expanded when either of
+ * the two former sections was.
+ */
+export const normalizeLegacyExpandedKeys = (keys: string[]): string[] => {
+ if (!keys.includes(LEGACY_PRIVATE_SECTION_KEY)) return keys;
+
+ const withoutPrivate = keys.filter((key) => key !== LEGACY_PRIVATE_SECTION_KEY);
+ return withoutPrivate.includes(AGENT_SECTION_KEY)
+ ? withoutPrivate
+ : [...withoutPrivate, AGENT_SECTION_KEY];
+};
const DEFAULT_BOTTOM_KEYS = new Set(
DEFAULT_SIDEBAR_ITEMS.slice(DEFAULT_SIDEBAR_ITEMS.indexOf(SIDEBAR_SPACER_ID) + 1),
@@ -425,12 +470,13 @@ const sidebarItems =
(workspaceId: string | null) =>
(s: GlobalState): string[] => {
const items = readOverridableField(s.status, 'sidebarItems', workspaceId);
- if (items && items.length > 0) return withAllKnownKeys(items);
+ if (items && items.length > 0) return withAllKnownKeys(normalizeLegacyAgentItems(items));
// Migrate from the legacy `sidebarSectionOrder` (canary) which only stored the
// accordion order (e.g. ['agent', 'recents']). Apply that order to the accordion
// slot inside the default list so users keep their custom accordion arrangement.
- const legacy = s.status.sidebarSectionOrder;
+ const legacy =
+ s.status.sidebarSectionOrder && normalizeLegacyAgentItems(s.status.sidebarSectionOrder);
if (legacy && legacy.length > 0) {
const legacyAcc = legacy.filter((k) => SIDEBAR_ACCORDION_KEYS.has(k));
if (legacyAcc.length > 0) {
diff --git a/src/store/home/slices/sidebarUI/action.pinItemForMe.test.ts b/src/store/home/slices/sidebarUI/action.pinItemForMe.test.ts
new file mode 100644
index 00000000000..14f09ab835e
--- /dev/null
+++ b/src/store/home/slices/sidebarUI/action.pinItemForMe.test.ts
@@ -0,0 +1,74 @@
+import { act } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { agentService } from '@/services/agent';
+import { chatGroupService } from '@/services/chatGroup';
+import { useHomeStore } from '@/store/home';
+import { useUserStore } from '@/store/user';
+
+vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({
+ getActiveWorkspaceId: vi.fn(() => 'ws-1'),
+ useActiveWorkspaceId: vi.fn(() => 'ws-1'),
+}));
+
+const updatePreference = vi.fn();
+
+beforeEach(() => {
+ updatePreference.mockReset().mockResolvedValue(undefined);
+ vi.spyOn(agentService, 'updateAgentPinned').mockResolvedValue(undefined as any);
+ vi.spyOn(chatGroupService, 'updateGroup').mockResolvedValue(undefined as any);
+ vi.spyOn(useHomeStore.getState(), 'refreshAgentList').mockResolvedValue(undefined);
+ useUserStore.setState({
+ updateWorkspaceUserPreference: updatePreference,
+ workspaceUserPreference: { sidebarPinnedItemIds: ['older'] },
+ } as any);
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+const pinForMe = (...args: Parameters<ReturnType<typeof useHomeStore.getState>['pinItemForMe']>) =>
+ act(() => useHomeStore.getState().pinItemForMe(...args));
+
+describe('pinItemForMe', () => {
+ it('pins a public agent in the member preference only, newest first', async () => {
+ await pinForMe({ id: 'pub', pinned: false, type: 'agent', visibility: 'public' }, true);
+
+ expect(updatePreference).toHaveBeenCalledWith({ sidebarPinnedItemIds: ['pub', 'older'] });
+ // The shared column is the team pin — a member's pin must not touch it.
+ expect(agentService.updateAgentPinned).not.toHaveBeenCalled();
+ });
+
+ it('unpins a public agent from the member preference only', async () => {
+ useUserStore.setState({ workspaceUserPreference: { sidebarPinnedItemIds: ['pub', 'older'] } });
+
+ await pinForMe({ id: 'pub', pinned: true, type: 'agent', visibility: 'public' }, false);
+
+ expect(updatePreference).toHaveBeenCalledWith({ sidebarPinnedItemIds: ['older'] });
+ // Even when the row is team-pinned, a personal unpin leaves the team pin.
+ expect(agentService.updateAgentPinned).not.toHaveBeenCalled();
+ });
+
+ it('keeps a private agent column in sync with its preference entry', async () => {
+ await pinForMe({ id: 'priv', pinned: false, type: 'agent', visibility: 'private' }, true);
+
+ expect(updatePreference).toHaveBeenCalledWith({ sidebarPinnedItemIds: ['priv', 'older'] });
+ expect(agentService.updateAgentPinned).toHaveBeenCalledWith('priv', true);
+ });
+
+ it('clears a legacy private pin that exists only on the column', async () => {
+ await pinForMe({ id: 'legacy', pinned: true, type: 'agent', visibility: 'private' }, false);
+
+ // Not in the preference: nothing to write there.
+ expect(updatePreference).not.toHaveBeenCalled();
+ expect(agentService.updateAgentPinned).toHaveBeenCalledWith('legacy', false);
+ });
+
+ it('routes a private chat group through the group column', async () => {
+ await pinForMe({ id: 'grp', pinned: false, type: 'group', visibility: 'private' }, true);
+
+ expect(chatGroupService.updateGroup).toHaveBeenCalledWith('grp', { pinned: true });
+ expect(agentService.updateAgentPinned).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/store/home/slices/sidebarUI/action.ts b/src/store/home/slices/sidebarUI/action.ts
index 03e407545cc..be78790660e 100644
--- a/src/store/home/slices/sidebarUI/action.ts
+++ b/src/store/home/slices/sidebarUI/action.ts
@@ -9,11 +9,23 @@ import { getAgentStoreState } from '@/store/agent';
import { evictMessageCache } from '@/store/chat/utils/evictMessageCache';
import { type HomeStore } from '@/store/home/store';
import { type StoreSetter } from '@/store/types';
+import { getUserStoreState } from '@/store/user';
import { type SessionGroupItemBase } from '@/types/session';
import { setNamespace } from '@/utils/storeDebug';
const n = setNamespace('sidebarUI');
+/** Upper bound for one member's personal pin list (mirrors the server cap). */
+export const MAX_SIDEBAR_PINNED_ITEMS = 200;
+
+export interface PersonalPinTarget {
+ id: string;
+ /** Current value of the row's own `pinned` column. */
+ pinned?: boolean | null;
+ type: 'agent' | 'group';
+ visibility?: 'private' | 'public' | null;
+}
+
type Setter = StoreSetter<HomeStore>;
export const createSidebarUISlice = (set: Setter, get: () => HomeStore, _api?: unknown) =>
new SidebarUIActionImpl(set, get, _api);
@@ -70,10 +82,11 @@ export class SidebarUIActionImpl {
return result.groupId;
};
- // Pinning is part of the SHARED sidebar arrangement in workspace mode — it
- // writes the same `agents.pinned` / `chat_groups.pinned` columns as personal
- // mode, so every member sees the same pinned section. A member who doesn't
- // want an item in their own sidebar hides it instead (personal layer).
+ // Writes the `agents.pinned` / `chat_groups.pinned` column. In personal
+ // mode that is the user's own pin. In a workspace it is the TEAM pin on a
+ // public row (owner/admin only, enforced server-side) and the creator's own
+ // pin on a private row (only they can see it). Members pin public rows for
+ // themselves through `pinItemForMe` instead.
pinAgent = async (agentId: string, pinned: boolean): Promise<void> => {
await agentService.updateAgentPinned(agentId, pinned);
await this.#get().refreshAgentList();
@@ -84,6 +97,34 @@ export class SidebarUIActionImpl {
await this.#get().refreshAgentList();
};
+ /**
+ * Pin / unpin an Agent or chat group for the current member only, in the
+ * merged workspace Agents section. The member's pin order lives in their
+ * `sidebarPinnedItemIds` preference (newest first); the shared column on a
+ * public row is the team pin and is left alone. A private row additionally
+ * keeps its own column in sync — only its creator can see it, earlier
+ * clients read it as the pin, and a rollback keeps showing it. Unpinning
+ * clears both places.
+ */
+ pinItemForMe = async (item: PersonalPinTarget, pinned: boolean): Promise<void> => {
+ const userStore = getUserStoreState();
+ const current = userStore.workspaceUserPreference.sidebarPinnedItemIds ?? [];
+ const isPrivate = item.visibility === 'private';
+ const writeColumn = (value: boolean) =>
+ item.type === 'group' ? this.pinAgentGroup(item.id, value) : this.pinAgent(item.id, value);
+
+ const nextIds = pinned
+ ? [item.id, ...current.filter((id) => id !== item.id)].slice(0, MAX_SIDEBAR_PINNED_ITEMS)
+ : current.filter((id) => id !== item.id);
+ const listChanged =
+ nextIds.length !== current.length || nextIds.some((id, i) => id !== current[i]);
+
+ if (listChanged) {
+ await userStore.updateWorkspaceUserPreference({ sidebarPinnedItemIds: nextIds });
+ }
+ if (isPrivate && !!item.pinned !== pinned) await writeColumn(pinned);
+ };
+
removeAgent = async (agentId: string): Promise<void> => {
await agentService.removeAgent(agentId);
await this.#get().refreshAgentList();
diff --git a/src/store/user/slices/workspaceUserSettings/action.ts b/src/store/user/slices/workspaceUserSettings/action.ts
index 1eb938e6be1..387e19536cb 100644
--- a/src/store/user/slices/workspaceUserSettings/action.ts
+++ b/src/store/user/slices/workspaceUserSettings/action.ts
@@ -8,7 +8,7 @@ import {
getActiveWorkspaceId,
useActiveWorkspaceId,
} from '@/business/client/hooks/useActiveWorkspaceId';
-import { createReplicaSlice, type ReplicaLens } from '@/libs/replica';
+import { createReplicaSlice, type ReplicaLens, revalidateReplica } from '@/libs/replica';
import { workspaceUserSettingsService } from '@/services/workspaceUserSettings';
import { refreshAgentDeviceBindings } from '@/store/device/agentDeviceBinding';
import { type StoreSetter } from '@/store/types';
@@ -194,6 +194,19 @@ export class WorkspaceUserSettingsActionImpl {
};
};
+ /**
+ * Re-read the active workspace's preference from the server. Call it after
+ * a server-side write to this member's preference that the client did not
+ * make itself (e.g. publishing a pinned private Agent moves its pin into
+ * `sidebarPinnedItemIds`), so the next local whole-array write is not based
+ * on a stale copy.
+ */
+ refreshWorkspaceUserPreference = async (): Promise<void> => {
+ const workspaceId = getActiveWorkspaceId();
+ if (!workspaceId) return;
+ await revalidateReplica(getWorkspaceUserPreferenceResource(), workspaceId);
+ };
+
updateWorkspaceUserPreference = async (
patch: Partial<WorkspaceUserPreference>,
): Promise<void> => {
diff --git a/src/store/user/slices/workspaceUserSettings/selectors.ts b/src/store/user/slices/workspaceUserSettings/selectors.ts
index 04011df9e8a..9d1a592f1e1 100644
--- a/src/store/user/slices/workspaceUserSettings/selectors.ts
+++ b/src/store/user/slices/workspaceUserSettings/selectors.ts
@@ -47,6 +47,13 @@ const isAgentHiddenFromSidebar =
(s: UserStore): boolean =>
!!s.workspaceUserPreference.sidebarHiddenAgentIds?.includes(agentId);
+/**
+ * Agents / chat groups the caller pinned for themselves in the active
+ * workspace's merged Agents section, newest first.
+ */
+const sidebarPinnedItemIds = (s: UserStore): string[] =>
+ s.workspaceUserPreference.sidebarPinnedItemIds ?? EMPTY_HIDDEN;
+
/** Per-member sidebar sections layout for the active workspace. */
const sidebarLayout = (s: UserStore) => s.workspaceUserPreference.sidebar;
@@ -62,4 +69,5 @@ export const workspaceUserSettingsSelectors = {
sidebarHiddenAgentIds,
sidebarHiddenGroupIds,
sidebarLayout,
+ sidebarPinnedItemIds,
};