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): recommend agents to the workspace instead of pinning them for everyone (#23520)

Rdmclin2fadcba625afd
diff --git a/apps/server/src/routers/lambda/__tests__/home.recommendedAgents.test.ts b/apps/server/src/routers/lambda/__tests__/home.recommendedAgents.test.ts
new file mode 100644
index 00000000000..e5a92d8d8ec
--- /dev/null
+++ b/apps/server/src/routers/lambda/__tests__/home.recommendedAgents.test.ts
@@ -0,0 +1,72 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { HomeRepository } from '@/database/repositories/home';
+import { getWorkspaceScopedPermissionMatches } from '@/server/services/workspacePermission';
+
+import { homeRouter } from '../home';
+
+vi.mock('@/database/models/agent', () => ({ AgentModel: vi.fn() }));
+vi.mock('@/database/repositories/home', () => ({ HomeRepository: vi.fn() }));
+vi.mock('@/server/services/home', () => ({ HomeService: vi.fn() }));
+vi.mock('@/server/services/ftsSearch', () => ({ createFtsSearchRepo: vi.fn() }));
+vi.mock('@/server/services/workspacePermission', () => ({
+ getWorkspaceScopedPermissionMatches: vi.fn(),
+ hasWorkspaceScopedPermission: vi.fn(),
+}));
+vi.mock('@/database/core/db-adaptor', () => ({ getServerDB: vi.fn(() => ({})) }));
+
+const matches = vi.mocked(getWorkspaceScopedPermissionMatches);
+
+describe('homeRouter.updateRecommendedAgents', () => {
+ let updateRecommendedIds: ReturnType<typeof vi.fn>;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ updateRecommendedIds = vi.fn();
+ vi.mocked(HomeRepository).mockImplementation(function () {
+ return { updateRecommendedIds } as never;
+ });
+ });
+
+ it('refuses a workspace member changing the recommended agents', async () => {
+ matches.mockResolvedValue({ hasAllScope: false } as never);
+ const caller = homeRouter.createCaller({ userId: 'member-1', workspaceId: 'ws-1' } as never);
+
+ await expect(caller.updateRecommendedAgents({ ids: ['a'] })).rejects.toMatchObject({
+ code: 'FORBIDDEN',
+ message: 'Only workspace owners and admins can change recommended agents',
+ });
+ expect(updateRecommendedIds).not.toHaveBeenCalled();
+ });
+
+ it('lets a workspace owner/admin save the list in order', async () => {
+ matches.mockResolvedValue({ hasAllScope: true } as never);
+ const caller = homeRouter.createCaller({ userId: 'admin-1', workspaceId: 'ws-1' } as never);
+
+ await caller.updateRecommendedAgents({ ids: ['b', 'a'] });
+
+ expect(updateRecommendedIds).toHaveBeenCalledWith(['b', 'a']);
+ });
+
+ it('rejects the call outside a workspace', async () => {
+ const caller = homeRouter.createCaller({ userId: 'user-1' } as never);
+
+ await expect(caller.updateRecommendedAgents({ ids: ['a'] })).rejects.toMatchObject({
+ code: 'BAD_REQUEST',
+ });
+ expect(updateRecommendedIds).not.toHaveBeenCalled();
+ });
+
+ it('accepts a list as long as the team pins it starts from', async () => {
+ // Until a list is saved the team pins are the list, so admins must be able
+ // to save it back — trimmed or reordered — however many there are.
+ matches.mockResolvedValue({ hasAllScope: true } as never);
+ const ids = Array.from({ length: 500 }, (_, index) => `agent-${index}`);
+ const caller = homeRouter.createCaller({ userId: 'admin-1', workspaceId: 'ws-1' } as never);
+
+ await caller.updateRecommendedAgents({ ids });
+
+ expect(updateRecommendedIds).toHaveBeenCalledWith(ids);
+ });
+});
diff --git a/apps/server/src/routers/lambda/__tests__/workspaceUserSettings.test.ts b/apps/server/src/routers/lambda/__tests__/workspaceUserSettings.test.ts
index fcfe95faeaa..51af7d7f5df 100644
--- a/apps/server/src/routers/lambda/__tests__/workspaceUserSettings.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/workspaceUserSettings.test.ts
@@ -11,15 +11,29 @@ vi.mock('@/database/core/db-adaptor', () => ({
const mockUpdatePreference = vi.fn();
const mockSetWorktreeModeDir = vi.fn();
+const mockGetPreference = vi.fn();
+const mockInitializeSidebar = vi.fn();
+const mockGetJoinedAt = vi.fn();
vi.mock('@/database/models/workspaceUserSettings', () => ({
WorkspaceUserSettingsModel: vi.fn(function () {
return {
+ getJoinedAt: mockGetJoinedAt,
+ getPreference: mockGetPreference,
+ initializeSidebar: mockInitializeSidebar,
setWorktreeModeDir: mockSetWorktreeModeDir,
updatePreference: mockUpdatePreference,
};
}),
}));
+const mockGetTeamPinnedIds = vi.fn();
+const mockGetRecommendedIds = vi.fn();
+vi.mock('@/database/repositories/home', () => ({
+ HomeRepository: vi.fn(function () {
+ return { getRecommendedIds: mockGetRecommendedIds, getTeamPinnedIds: mockGetTeamPinnedIds };
+ }),
+}));
+
const mockUpdateSessionGroupId = vi.fn();
vi.mock('@/database/models/agent', () => ({
AgentModel: vi.fn(function () {
@@ -201,3 +215,79 @@ describe('workspaceUserSettingsRouter.setWorktreeModeDir', () => {
await expect(caller.setWorktreeModeDir({ enabled: true, key: '' })).rejects.toThrow();
});
});
+
+describe('workspaceUserSettingsRouter.getPreference', () => {
+ const ctx: any = { serverDB: {}, userId: 'user-member', workspaceId: 'ws-1' };
+ const joinedBefore = new Date('2026-01-01T00:00:00Z');
+ const joinedAfter = new Date('2026-12-01T00:00:00Z');
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('keeps the team pins as the own pins of a member who joined while they were shown', async () => {
+ mockGetPreference.mockResolvedValue({ sidebarPinnedItemIds: ['mine'] });
+ mockGetJoinedAt.mockResolvedValue(joinedBefore);
+ mockGetTeamPinnedIds.mockResolvedValue(['team-1', 'team-2']);
+ const seeded = {
+ sidebarInitialized: true,
+ sidebarPinnedItemIds: ['mine', 'team-1', 'team-2'],
+ };
+ mockInitializeSidebar.mockResolvedValue(seeded);
+
+ const result = await workspaceUserSettingsRouter.createCaller(ctx).getPreference();
+
+ expect(mockInitializeSidebar).toHaveBeenCalledWith({
+ final: true,
+ pinIds: ['team-1', 'team-2'],
+ });
+ expect(mockGetRecommendedIds).not.toHaveBeenCalled();
+ expect(result).toEqual(seeded);
+ });
+
+ it('lists the recommended Agents, unpinned, for a member who joined later', async () => {
+ mockGetPreference.mockResolvedValue({});
+ mockGetJoinedAt.mockResolvedValue(joinedAfter);
+ mockGetRecommendedIds.mockResolvedValue(['rec-1']);
+ const seeded = { sidebarAgentVisibilityOverrides: { 'rec-1': true }, sidebarInitialized: true };
+ mockInitializeSidebar.mockResolvedValue(seeded);
+
+ const result = await workspaceUserSettingsRouter.createCaller(ctx).getPreference();
+
+ expect(mockInitializeSidebar).toHaveBeenCalledWith({ listIds: ['rec-1'] });
+ expect(mockGetTeamPinnedIds).not.toHaveBeenCalled();
+ expect(result).toEqual(seeded);
+ });
+
+ it('never sets the sidebar up again once it was', async () => {
+ const preference = { sidebarInitialized: true, sidebarPinnedItemIds: ['mine'] };
+ mockGetPreference.mockResolvedValue(preference);
+
+ const result = await workspaceUserSettingsRouter.createCaller(ctx).getPreference();
+
+ expect(result).toEqual(preference);
+ expect(mockGetJoinedAt).not.toHaveBeenCalled();
+ expect(mockInitializeSidebar).not.toHaveBeenCalled();
+ });
+
+ it('leaves a caller who is not a member alone', async () => {
+ mockGetPreference.mockResolvedValue({});
+ mockGetJoinedAt.mockResolvedValue(undefined);
+
+ const result = await workspaceUserSettingsRouter.createCaller(ctx).getPreference();
+
+ expect(result).toEqual({});
+ expect(mockInitializeSidebar).not.toHaveBeenCalled();
+ });
+
+ it('still returns the preference when the setup fails', async () => {
+ const spy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ mockGetPreference.mockResolvedValue({ sidebarPinnedItemIds: ['mine'] });
+ mockGetJoinedAt.mockRejectedValue(new Error('db down'));
+
+ const result = await workspaceUserSettingsRouter.createCaller(ctx).getPreference();
+
+ expect(result).toEqual({ sidebarPinnedItemIds: ['mine'] });
+ spy.mockRestore();
+ });
+});
diff --git a/apps/server/src/routers/lambda/_helpers/sidebarPin.ts b/apps/server/src/routers/lambda/_helpers/sidebarPin.ts
index b4e63cc60db..e1d123828a7 100644
--- a/apps/server/src/routers/lambda/_helpers/sidebarPin.ts
+++ b/apps/server/src/routers/lambda/_helpers/sidebarPin.ts
@@ -1,11 +1,29 @@
import { TRPCError } from '@trpc/server';
import { WorkspaceUserSettingsModel } from '@/database/models/workspaceUserSettings';
+import { MAX_PINNED_ORDER_ITEMS } from '@/database/repositories/home/pinnedOrder';
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;
+/**
+ * Upper bound for one member's pin list in a workspace. It may be seeded with
+ * every team pin, so this matches the team order cap.
+ */
+export const MAX_SIDEBAR_PINNED_ITEMS = MAX_PINNED_ORDER_ITEMS;
+
+/**
+ * When the workspace sidebar stopped showing team pins to every member and
+ * started recommending Agents instead (lobehub/lobehub#23520). Members who
+ * joined before keep the team pins as their own pins the first time their
+ * sidebar is set up; members who join later start from the recommended
+ * Agents, unpinned. A member who joined between this date and the deploy
+ * reaching their server is treated as new, which is the intended behavior
+ * anyway.
+ */
+export const TEAM_PINS_RETIRED_AT = new Date('2026-11-24T00:00:00Z');
+
+export const RECOMMENDED_AGENTS_FORBIDDEN_MESSAGE =
+ 'Only workspace owners and admins can change recommended agents';
export const TEAM_PIN_FORBIDDEN_MESSAGE = 'Only workspace owners and admins can change team pins';
@@ -16,14 +34,19 @@ interface TeamPinCtx {
}
/**
- * 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
+ * In a workspace, `pinned` on a PUBLIC Agent / chat group is a legacy team
+ * pin (still read for members who joined while it was shown, and as the
+ * recommended Agents until a list is saved), 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.
+ * team pins and skip this check. The workspace's recommended Agents list is
+ * gated the same way (pass {@link RECOMMENDED_AGENTS_FORBIDDEN_MESSAGE}).
*/
-export const assertCanWriteTeamPin = async (ctx: TeamPinCtx): Promise<void> => {
+export const assertCanWriteTeamPin = async (
+ ctx: TeamPinCtx,
+ message = TEAM_PIN_FORBIDDEN_MESSAGE,
+): Promise<void> => {
if (!ctx.workspaceId) return;
const { hasAllScope } = await getWorkspaceScopedPermissionMatches({
@@ -36,7 +59,7 @@ export const assertCanWriteTeamPin = async (ctx: TeamPinCtx): Promise<void> => {
});
if (!hasAllScope) {
- throw new TRPCError({ code: 'FORBIDDEN', message: TEAM_PIN_FORBIDDEN_MESSAGE });
+ throw new TRPCError({ code: 'FORBIDDEN', message });
}
};
diff --git a/apps/server/src/routers/lambda/home.ts b/apps/server/src/routers/lambda/home.ts
index cacc87efdb4..e0bd3ccdae3 100644
--- a/apps/server/src/routers/lambda/home.ts
+++ b/apps/server/src/routers/lambda/home.ts
@@ -1,17 +1,21 @@
+import { TRPCError } from '@trpc/server';
import { z } from 'zod';
import { withScopedPermission } from '@/business/server/trpc-middlewares/rbacPermission';
import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';
import { AgentModel } from '@/database/models/agent';
import { HomeRepository } from '@/database/repositories/home';
-import { MAX_PINNED_ORDER_ITEMS } from '@/database/repositories/home/pinnedOrder';
+import {
+ MAX_PINNED_ORDER_ITEMS,
+ MAX_RECOMMENDED_ITEMS,
+} from '@/database/repositories/home/pinnedOrder';
import { router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
import { createFtsSearchRepo } from '@/server/services/ftsSearch';
import { type HomeBriefData, HomeService } from '@/server/services/home';
import { hasWorkspaceScopedPermission } from '@/server/services/workspacePermission';
-import { assertCanWriteTeamPin } from './_helpers/sidebarPin';
+import { assertCanWriteTeamPin, RECOMMENDED_AGENTS_FORBIDDEN_MESSAGE } from './_helpers/sidebarPin';
const homeProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {
const { ctx } = opts;
@@ -108,6 +112,24 @@ export const homeRouter = router({
await ctx.homeRepository.updatePinnedOrder(input.ids);
}),
+ /**
+ * Replace the workspace's recommended Agents / chat groups (in order). Every
+ * member sees the list on the Agents page and new members start with it in
+ * their sidebar, so only owners/admins may change it.
+ */
+ updateRecommendedAgents: homeProcedure
+ .input(z.object({ ids: z.array(z.string().max(255)).max(MAX_RECOMMENDED_ITEMS) }))
+ .mutation(async ({ input, ctx }) => {
+ if (!ctx.workspaceId) {
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message: 'Recommended agents only exist in a workspace',
+ });
+ }
+ await assertCanWriteTeamPin(ctx, RECOMMENDED_AGENTS_FORBIDDEN_MESSAGE);
+ await ctx.homeRepository.updateRecommendedIds(input.ids);
+ }),
+
updateAgentSessionGroupId: homeProcedure
.use(withScopedPermission('agent:update'))
.input(
diff --git a/apps/server/src/routers/lambda/workspaceUserSettings.ts b/apps/server/src/routers/lambda/workspaceUserSettings.ts
index c2134a4e6c2..b3e3bdc8cc2 100644
--- a/apps/server/src/routers/lambda/workspaceUserSettings.ts
+++ b/apps/server/src/routers/lambda/workspaceUserSettings.ts
@@ -8,12 +8,16 @@ import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceA
import { AgentModel } from '@/database/models/agent';
import { ChatGroupModel } from '@/database/models/chatGroup';
import { WorkspaceUserSettingsModel } from '@/database/models/workspaceUserSettings';
+import { HomeRepository } from '@/database/repositories/home';
+import type { LobeChatDatabase } from '@/database/type';
import { router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
import { EditLockService } from '@/server/services/editLock';
import { assertCanEditResource } from '@/server/services/resourcePermission';
import { hasWorkspaceScopedPermission } from '@/server/services/workspacePermission';
+import { TEAM_PINS_RETIRED_AT } from './_helpers/sidebarPin';
+
/**
* Per-user preferences scoped to the current workspace. Every procedure is
* scoped to `(ctx.workspaceId, ctx.userId)` — the caller can only ever read
@@ -47,6 +51,48 @@ const workspaceUserSettingsProcedure = wsCompatProcedure.use(serverDatabase).use
// type layer already constrains the write paths.
const preferencePatchSchema = z.object({}).passthrough().partial();
+/**
+ * Set a member's sidebar up from the workspace the first time their
+ * preference is read (lazy, so every way of joining a workspace is covered):
+ *
+ * - A member who joined while team pins were shown
+ * ({@link TEAM_PINS_RETIRED_AT}) keeps them as their own pins, after the
+ * pins they already had — nothing they saw disappears.
+ * - Anyone else gets the workspace's recommended Agents added to their
+ * sidebar, unpinned.
+ *
+ * A failure only logs: the sidebar then shows the member's own choices and
+ * the next read tries again.
+ */
+const initializeSidebar = async (
+ ctx: {
+ serverDB: LobeChatDatabase;
+ userId: string;
+ workspaceId: string;
+ workspaceUserSettingsModel: WorkspaceUserSettingsModel;
+ },
+ preference: WorkspaceUserPreference,
+): Promise<WorkspaceUserPreference> => {
+ try {
+ const joinedAt = await ctx.workspaceUserSettingsModel.getJoinedAt();
+ if (!joinedAt) return preference;
+
+ const homeRepository = new HomeRepository(ctx.serverDB, ctx.userId, ctx.workspaceId);
+ if (joinedAt < TEAM_PINS_RETIRED_AT) {
+ // Settled even without team pins: such a member never gets the
+ // recommended list, so a later read has nothing to add.
+ const pinIds = await homeRepository.getTeamPinnedIds();
+ return await ctx.workspaceUserSettingsModel.initializeSidebar({ final: true, pinIds });
+ }
+
+ const listIds = await homeRepository.getRecommendedIds();
+ return await ctx.workspaceUserSettingsModel.initializeSidebar({ listIds });
+ } catch (error) {
+ console.error('[workspaceUserSettings:initializeSidebar]', error);
+ return preference;
+ }
+};
+
export const workspaceUserSettingsRouter = router({
/**
* Fetch the caller's preference for the current workspace. Returns an
@@ -56,7 +102,10 @@ export const workspaceUserSettingsRouter = router({
getPreference: workspaceUserSettingsProcedure.query(
async ({ ctx }): Promise<WorkspaceUserPreference> => {
try {
- return await ctx.workspaceUserSettingsModel.getPreference();
+ const preference = await ctx.workspaceUserSettingsModel.getPreference();
+ if (preference.sidebarInitialized) return preference;
+
+ return await initializeSidebar(ctx, preference);
} catch (error) {
console.error('[workspaceUserSettings:getPreference]', error);
throw new TRPCError({
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index ab68f7527b2..c542bc7d535 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -2133,8 +2133,6 @@
"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.",
@@ -2194,6 +2192,9 @@
"reasoningEffort.mode.standard": "Standard",
"reasoningEffort.title": "Reasoning Effort",
"reasoningEffort.updateFailed": "Failed to update reasoning effort, please try again",
+ "recommendAgent": "Add to recommended agents",
+ "recommendAgentForbidden": "Only workspace owners and admins can change recommended agents",
+ "recommendAgentSuccess": "Added to recommended agents. New members will start with it in their sidebar",
"regenerate": "Regenerate",
"resource.artifacts.buildLog.copy": "Copy logs",
"resource.artifacts.buildLog.copySuccess": "Build logs copied",
@@ -3364,7 +3365,8 @@
"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",
+ "unrecommendAgent": "Remove from recommended agents",
+ "unrecommendAgentSuccess": "Removed from recommended agents",
"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 f41f813056b..edaf03bf783 100644
--- a/locales/en-US/common.json
+++ b/locales/en-US/common.json
@@ -23,6 +23,8 @@
"agentViewAll.orderBy.title": "Title",
"agentViewAll.orderBy.updatedAt": "Updated at",
"agentViewAll.pendant.official": "Official",
+ "agentViewAll.recommendedSection.empty": "No recommended agents yet. Use “Add to recommended agents” in an agent’s menu.",
+ "agentViewAll.recommendedSection.title": "Recommended agents",
"agentViewAll.removeFromSidebar": "Hide from my sidebar",
"agentViewAll.sidebarSection.collapse": "Fold",
"agentViewAll.sidebarSection.expand": "Unfold",
@@ -370,7 +372,6 @@
"navPanel.managePrivateFolders": "Manage private categories",
"navPanel.moveDown": "Move Down",
"navPanel.moveUp": "Move Up",
- "navPanel.myPinned": "Pinned",
"navPanel.newChat": "New chat",
"navPanel.openMenu": "Open menu",
"navPanel.pinned": "Pinned",
@@ -384,12 +385,8 @@
"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 d7d249416cb..14ce2f37c0f 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -2133,8 +2133,6 @@
"piInstallGuide.reason": "LobeHub 无法启动 Pi:{{message}}",
"piInstallGuide.title": "安装 Pi CLI",
"pin": "置顶",
- "pinForTeam": "为团队置顶",
- "pinForTeamForbidden": "仅工作区所有者和管理员可以修改团队置顶",
"pinOff": "取消置顶",
"platformAgent.deviceGuard.configure": "去配置",
"platformAgent.deviceGuard.deviceOffline.desc": "绑定的设备未连接,请在目标机器上运行 `lh connect` 后刷新。",
@@ -2194,6 +2192,9 @@
"reasoningEffort.mode.standard": "标准",
"reasoningEffort.title": "推理强度",
"reasoningEffort.updateFailed": "推理强度更新失败,请重试",
+ "recommendAgent": "加入推荐 Agents",
+ "recommendAgentForbidden": "仅工作区所有者和管理员可以修改推荐 Agents",
+ "recommendAgentSuccess": "已加入推荐 Agents,新成员的侧边栏会默认显示它",
"regenerate": "重新生成",
"resource.artifacts.buildLog.copy": "复制日志",
"resource.artifacts.buildLog.copySuccess": "构建日志已复制",
@@ -3364,7 +3365,8 @@
"turnProcess.ranFor_other": "共运行 {{count}} 步 ({{duration}})",
"turnProcess.viewFullRecordWithSteps_one": "共执行 {{count}} 步 · 点击查看完整记录",
"turnProcess.viewFullRecordWithSteps_other": "共执行 {{count}} 步 · 点击查看完整记录",
- "unpinForTeam": "取消团队置顶",
+ "unrecommendAgent": "移出推荐 Agents",
+ "unrecommendAgentSuccess": "已移出推荐 Agents",
"untitledAgent": "未命名助理",
"untitledGroup": "未命名群组",
"updateAgent": "更新助理信息",
diff --git a/locales/zh-CN/common.json b/locales/zh-CN/common.json
index 2beb12e479e..5d27bad1917 100644
--- a/locales/zh-CN/common.json
+++ b/locales/zh-CN/common.json
@@ -23,6 +23,8 @@
"agentViewAll.orderBy.title": "标题",
"agentViewAll.orderBy.updatedAt": "更新时间",
"agentViewAll.pendant.official": "官方",
+ "agentViewAll.recommendedSection.empty": "还没有推荐的 Agent。在 Agent 的菜单里选择「加入推荐 Agents」即可添加。",
+ "agentViewAll.recommendedSection.title": "推荐 Agents",
"agentViewAll.removeFromSidebar": "在我的侧边栏隐藏",
"agentViewAll.sidebarSection.collapse": "收起",
"agentViewAll.sidebarSection.expand": "展开",
@@ -370,7 +372,6 @@
"navPanel.managePrivateFolders": "管理私人分组",
"navPanel.moveDown": "下移",
"navPanel.moveUp": "上移",
- "navPanel.myPinned": "我的置顶",
"navPanel.newChat": "新对话",
"navPanel.openMenu": "打开菜单",
"navPanel.pinned": "已固定",
@@ -384,12 +385,8 @@
"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__/workspaceUserSettings.test.ts b/packages/database/src/models/__tests__/workspaceUserSettings.test.ts
index 99ebd9421a7..0ca22e611b5 100644
--- a/packages/database/src/models/__tests__/workspaceUserSettings.test.ts
+++ b/packages/database/src/models/__tests__/workspaceUserSettings.test.ts
@@ -1,8 +1,8 @@
// @vitest-environment node
-import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { getTestDB } from '../../core/getTestDB';
-import { users, workspaces, workspaceUserSettings } from '../../schemas';
+import { users, workspaceMembers, workspaces, workspaceUserSettings } from '../../schemas';
import type { LobeChatDatabase } from '../../type';
import { WorkspaceUserSettingsModel } from '../workspaceUserSettings';
@@ -13,6 +13,7 @@ const userA = 'ws-us-user-a';
const userB = 'ws-us-user-b';
const cleanup = async () => {
+ await serverDB.delete(workspaceMembers);
await serverDB.delete(workspaceUserSettings);
await serverDB.delete(workspaces);
await serverDB.delete(users);
@@ -238,4 +239,110 @@ describe('WorkspaceUserSettingsModel', () => {
await serverDB.delete(users);
expect(await model.get()).toBeUndefined();
});
+
+ describe('initializeSidebar', () => {
+ it('adds the recommended Agents to a new member’s sidebar, unpinned', async () => {
+ const model = new WorkspaceUserSettingsModel(serverDB, userA, workspaceId);
+
+ const result = await model.initializeSidebar({ listIds: ['rec-1', 'rec-2'] });
+
+ expect(result).toEqual({
+ sidebarAgentVisibilityOverrides: { 'rec-1': true, 'rec-2': true },
+ sidebarInitialized: true,
+ });
+ expect(await model.getPreference()).toEqual(result);
+ });
+
+ it('never overrides a sidebar choice the member already made', async () => {
+ const model = new WorkspaceUserSettingsModel(serverDB, userA, workspaceId);
+ await model.updatePreference({ sidebarAgentVisibilityOverrides: { 'rec-1': false } });
+
+ await model.initializeSidebar({ listIds: ['rec-1', 'rec-2'] });
+
+ expect((await model.getPreference()).sidebarAgentVisibilityOverrides).toEqual({
+ 'rec-1': false,
+ 'rec-2': true,
+ });
+ });
+
+ it('appends team pins after an existing member’s own pins, once', async () => {
+ const model = new WorkspaceUserSettingsModel(serverDB, userA, workspaceId);
+ await model.updatePreference({
+ sidebarHiddenGroupIds: ['g'],
+ sidebarPinnedItemIds: ['mine', 'team-2'],
+ });
+
+ await model.initializeSidebar({ pinIds: ['team-1', 'team-2'] });
+ // A later call — for example after admins change the list — is a no-op.
+ await model.initializeSidebar({ listIds: ['rec-3'], pinIds: ['team-3'] });
+
+ expect(await model.getPreference()).toEqual({
+ sidebarHiddenGroupIds: ['g'],
+ sidebarInitialized: true,
+ sidebarPinnedItemIds: ['mine', 'team-2', 'team-1'],
+ });
+ });
+
+ it('leaves the member not set up while there is nothing to add', async () => {
+ const model = new WorkspaceUserSettingsModel(serverDB, userA, workspaceId);
+
+ expect(await model.initializeSidebar({})).toEqual({});
+ expect(await model.get()).toBeUndefined();
+ });
+
+ it('never loses the first setup to a preference write that read before it', async () => {
+ const setup = new WorkspaceUserSettingsModel(serverDB, userA, workspaceId);
+ const write = new WorkspaceUserSettingsModel(serverDB, userA, workspaceId);
+ // The setup commits right after the write has read the (still empty)
+ // preference — the interleaving two concurrent first writes can take.
+ // A write that reads under the row lock never gives the setup that
+ // chance; the setup then simply runs after it.
+ const read = write.getPreference;
+ let setupRan = false;
+ vi.spyOn(write, 'getPreference').mockImplementation(async () => {
+ const stale = await read();
+ await setup.initializeSidebar({ listIds: ['rec-1'] });
+ setupRan = true;
+ return stale;
+ });
+
+ await write.updatePreference({ sidebarPinnedItemIds: ['mine'] });
+ if (!setupRan) await setup.initializeSidebar({ listIds: ['rec-1'] });
+
+ expect(await setup.getPreference()).toEqual({
+ sidebarAgentVisibilityOverrides: { 'rec-1': true },
+ sidebarInitialized: true,
+ sidebarPinnedItemIds: ['mine'],
+ });
+ });
+
+ it('marks the member as set up when nothing can ever be added', async () => {
+ const model = new WorkspaceUserSettingsModel(serverDB, userA, workspaceId);
+
+ expect(await model.initializeSidebar({ final: true, pinIds: [] })).toEqual({
+ sidebarInitialized: true,
+ });
+ expect(await model.getPreference()).toEqual({ sidebarInitialized: true });
+ });
+ });
+
+ describe('getJoinedAt', () => {
+ it('reads the member’s join date, and nothing for a non-member or a removed member', async () => {
+ const joinedAt = new Date('2026-01-02T03:04:05Z');
+ await serverDB.insert(workspaceMembers).values([
+ { joinedAt, userId: userA, workspaceId },
+ { deletedAt: new Date(), userId: userB, workspaceId },
+ ]);
+
+ expect(
+ await new WorkspaceUserSettingsModel(serverDB, userA, workspaceId).getJoinedAt(),
+ ).toEqual(joinedAt);
+ expect(
+ await new WorkspaceUserSettingsModel(serverDB, userB, workspaceId).getJoinedAt(),
+ ).toBeUndefined();
+ expect(
+ await new WorkspaceUserSettingsModel(serverDB, userA, 'ws-other').getJoinedAt(),
+ ).toBeUndefined();
+ });
+ });
});
diff --git a/packages/database/src/models/workspaceUserSettings.ts b/packages/database/src/models/workspaceUserSettings.ts
index 3a44168072c..4842b8f2694 100644
--- a/packages/database/src/models/workspaceUserSettings.ts
+++ b/packages/database/src/models/workspaceUserSettings.ts
@@ -9,11 +9,88 @@ import {
applyWorktreeModeDir,
} from '@lobechat/types';
import { mergeNotificationSettings } from '@lobechat/utils/mergeNotificationSettings';
-import { and, eq } from 'drizzle-orm';
+import { and, eq, isNull } from 'drizzle-orm';
-import { workspaceUserSettings } from '../schemas/workspace';
+import { MAX_PINNED_ORDER_ITEMS } from '../repositories/home/pinnedOrder';
+import { workspaceMembers, workspaceUserSettings } from '../schemas/workspace';
import type { LobeChatDatabase } from '../type';
+/**
+ * `patch` merged on top of `current`. Top-level keys replace; per-agent and
+ * per-item maps merge one level deeper (see the comments inside).
+ */
+const mergePreferencePatch = (
+ current: WorkspaceUserPreference,
+ patch: Partial<WorkspaceUserPreference>,
+): WorkspaceUserPreference => {
+ // Per-agent override maps merge one level deeper: clients patch a single
+ // agent's leaf from a local copy that may be stale or empty (for example a
+ // picker used before the preference fetch settles). A top-level replace
+ // would silently drop this user's choices for every other agent.
+ // Individual per-agent entries still replace wholesale.
+ return {
+ ...current,
+ ...patch,
+ ...(patch.agentDeviceOverrides
+ ? {
+ agentDeviceOverrides: {
+ ...current.agentDeviceOverrides,
+ ...patch.agentDeviceOverrides,
+ },
+ }
+ : {}),
+ ...(patch.agentModelOverrides
+ ? {
+ agentModelOverrides: {
+ ...current.agentModelOverrides,
+ ...patch.agentModelOverrides,
+ },
+ }
+ : {}),
+ ...(patch.notification
+ ? { notification: mergeNotificationSettings(current.notification, patch.notification) }
+ : {}),
+ ...(patch.agentModeOverrides
+ ? {
+ agentModeOverrides: {
+ ...current.agentModeOverrides,
+ ...patch.agentModeOverrides,
+ },
+ }
+ : {}),
+ ...(patch.sidebarAgentVisibilityOverrides
+ ? {
+ sidebarAgentVisibilityOverrides: {
+ ...current.sidebarAgentVisibilityOverrides,
+ ...patch.sidebarAgentVisibilityOverrides,
+ },
+ }
+ : {}),
+ // Deprecated, but still merged: the fields stay on the API, so a client
+ // from before the shared-sidebar change can still patch a single item.
+ // A top-level replace would let one such write shred the rest of that
+ // user's saved map — which is exactly the data the deprecation promises
+ // to leave intact for a rollback. Drop these two once the fields leave
+ // `WorkspaceUserPreference`.
+ ...(patch.sidebarGroupAssignments
+ ? {
+ sidebarGroupAssignments: {
+ ...current.sidebarGroupAssignments,
+ ...patch.sidebarGroupAssignments,
+ },
+ }
+ : {}),
+ ...(patch.sidebarPinnedOverrides
+ ? {
+ sidebarPinnedOverrides: {
+ ...current.sidebarPinnedOverrides,
+ ...patch.sidebarPinnedOverrides,
+ },
+ }
+ : {}),
+ };
+};
+
/**
* Per-user preferences scoped to a specific workspace — the workspace-scoped
* counterpart to `UserSettingsModel`. Rows live in `workspace_user_settings`
@@ -66,98 +143,21 @@ export class WorkspaceUserSettingsModel {
/**
* Merge `patch` on top of the caller's current preference and persist the
- * result via UPSERT. The merge is done at the application layer (read →
- * merge → write) because only the caller writes their own row, so the
- * lost-update surface is limited to the same user racing themselves in
- * multiple tabs — an acceptable trade for simple code.
+ * result. Read → merge → write runs under the row lock (see
+ * {@link mutatePreference}), so it never interleaves with the server's own
+ * writes to the same row — for example the one-time sidebar setup on the
+ * first read — nor with the caller's other tabs.
*
* The first call for a `(workspace, user)` pair creates the row; subsequent
* calls update the `preference` column in place, replacing the whole jsonb
* with the newly merged object (so setting a top-level key to `undefined`
* in the patch is a no-op — pass an explicit `{}` to clear it).
*/
- updatePreference = async (patch: Partial<WorkspaceUserPreference>) => {
- const current = await this.getPreference();
- // Per-agent override maps merge one level deeper: clients patch a single
- // agent's leaf from a local copy that may be stale or empty (for example a
- // picker used before the preference fetch settles). A top-level replace
- // would silently drop this user's choices for every other agent.
- // Individual per-agent entries still replace wholesale.
- const next: WorkspaceUserPreference = {
- ...current,
- ...patch,
- ...(patch.agentDeviceOverrides
- ? {
- agentDeviceOverrides: {
- ...current.agentDeviceOverrides,
- ...patch.agentDeviceOverrides,
- },
- }
- : {}),
- ...(patch.agentModelOverrides
- ? {
- agentModelOverrides: {
- ...current.agentModelOverrides,
- ...patch.agentModelOverrides,
- },
- }
- : {}),
- ...(patch.notification
- ? { notification: mergeNotificationSettings(current.notification, patch.notification) }
- : {}),
- ...(patch.agentModeOverrides
- ? {
- agentModeOverrides: {
- ...current.agentModeOverrides,
- ...patch.agentModeOverrides,
- },
- }
- : {}),
- ...(patch.sidebarAgentVisibilityOverrides
- ? {
- sidebarAgentVisibilityOverrides: {
- ...current.sidebarAgentVisibilityOverrides,
- ...patch.sidebarAgentVisibilityOverrides,
- },
- }
- : {}),
- // Deprecated, but still merged: the fields stay on the API, so a client
- // from before the shared-sidebar change can still patch a single item.
- // A top-level replace would let one such write shred the rest of that
- // user's saved map — which is exactly the data the deprecation promises
- // to leave intact for a rollback. Drop these two once the fields leave
- // `WorkspaceUserPreference`.
- ...(patch.sidebarGroupAssignments
- ? {
- sidebarGroupAssignments: {
- ...current.sidebarGroupAssignments,
- ...patch.sidebarGroupAssignments,
- },
- }
- : {}),
- ...(patch.sidebarPinnedOverrides
- ? {
- sidebarPinnedOverrides: {
- ...current.sidebarPinnedOverrides,
- ...patch.sidebarPinnedOverrides,
- },
- }
- : {}),
- };
- const [row] = await this.db
- .insert(workspaceUserSettings)
- .values({
- preference: next,
- userId: this.userId,
- workspaceId: this.workspaceId,
- })
- .onConflictDoUpdate({
- set: { preference: next, updatedAt: new Date() },
- target: [workspaceUserSettings.workspaceId, workspaceUserSettings.userId],
- })
- .returning();
- return row;
- };
+ updatePreference = async (patch: Partial<WorkspaceUserPreference>) =>
+ this.mutatePreference((current) => {
+ const next = mergePreferencePatch(current, patch);
+ return { next, result: { preference: next } };
+ });
/**
* Turn the composer's "New worktree" switch on or off for one directory and
@@ -197,11 +197,85 @@ export class WorkspaceUserSettingsModel {
return { next: { ...current, heteroPermissionModeDirs }, result: heteroPermissionModeDirs };
});
- /** Read → change → write this member's preference under the row lock. */
+ /**
+ * When this member joined the workspace, or `undefined` when they are not
+ * a member (any more).
+ */
+ getJoinedAt = async (): Promise<Date | undefined> => {
+ const [row] = await this.db
+ .select({ joinedAt: workspaceMembers.joinedAt })
+ .from(workspaceMembers)
+ .where(
+ and(
+ eq(workspaceMembers.workspaceId, this.workspaceId),
+ eq(workspaceMembers.userId, this.userId),
+ isNull(workspaceMembers.deletedAt),
+ ),
+ );
+ return row?.joinedAt;
+ };
+
+ /**
+ * Set this member's sidebar up from the workspace once:
+ * - `pinIds` go after the member's own pins (`sidebarPinnedItemIds`), so a
+ * member keeps what they saw: their pins first, then the team's;
+ * - `listIds` are added to the sidebar unpinned
+ * (`sidebarAgentVisibilityOverrides`), never overriding a choice the
+ * member already made.
+ *
+ * The preference is then marked `sidebarInitialized`, after which the
+ * sidebar is the member's alone. Nothing happens while both lists are
+ * empty, so a member who loads the sidebar before the workspace has
+ * anything to offer still gets it later — unless `final` says nothing can
+ * ever be added, which marks the member as set up anyway. Returns the
+ * stored preference.
+ */
+ initializeSidebar = async ({
+ final = false,
+ listIds = [],
+ pinIds = [],
+ }: {
+ final?: boolean;
+ listIds?: readonly string[];
+ pinIds?: readonly string[];
+ }): Promise<WorkspaceUserPreference> => {
+ if (!final && listIds.length === 0 && pinIds.length === 0) return this.getPreference();
+
+ return this.mutatePreference((current) => {
+ if (current.sidebarInitialized) return { next: current, result: current };
+
+ const next: WorkspaceUserPreference = { ...current, sidebarInitialized: true };
+ if (pinIds.length > 0) {
+ next.sidebarPinnedItemIds = [
+ ...new Set([...(current.sidebarPinnedItemIds ?? []), ...pinIds]),
+ ].slice(0, MAX_PINNED_ORDER_ITEMS);
+ }
+ if (listIds.length > 0) {
+ next.sidebarAgentVisibilityOverrides = {
+ ...Object.fromEntries(listIds.map((id) => [id, true])),
+ ...current.sidebarAgentVisibilityOverrides,
+ };
+ }
+ return { next, result: next };
+ });
+ };
+
+ /**
+ * Read → change → write this member's preference under the row lock. The
+ * row is created first when missing: `FOR UPDATE` locks nothing on an
+ * absent row, so two first writes would otherwise both read `{}` and the
+ * later upsert would drop the earlier one's change.
+ */
private mutatePreference = async <T>(
change: (current: WorkspaceUserPreference) => { next: WorkspaceUserPreference; result: T },
): Promise<T> =>
this.db.transaction(async (trx) => {
+ await trx
+ .insert(workspaceUserSettings)
+ .values({ preference: {}, userId: this.userId, workspaceId: this.workspaceId })
+ .onConflictDoNothing({
+ target: [workspaceUserSettings.workspaceId, workspaceUserSettings.userId],
+ });
const [row] = await trx
.select({ preference: workspaceUserSettings.preference })
.from(workspaceUserSettings)
diff --git a/packages/database/src/repositories/home/__tests__/sidebarPinnedOrder.test.ts b/packages/database/src/repositories/home/__tests__/sidebarPinnedOrder.test.ts
index 1e8c068e397..371c34ba6e7 100644
--- a/packages/database/src/repositories/home/__tests__/sidebarPinnedOrder.test.ts
+++ b/packages/database/src/repositories/home/__tests__/sidebarPinnedOrder.test.ts
@@ -92,4 +92,58 @@ describe('HomeRepository pinned order', () => {
// The workspace team order is untouched.
expect(await new HomeRepository(clientDB, owner, ws).getPinnedOrder()).toEqual([]);
});
+
+ it('lists the workspace default pins in the team order, public rows only', async () => {
+ const model = new AgentModel(clientDB, owner, ws);
+ const a = await createPinned(model, 'A');
+ const b = await createPinned(model, 'B');
+ const privateAgent = await model.create({
+ systemRole: '',
+ title: 'P',
+ visibility: 'private',
+ } as any);
+ await model.update(privateAgent.id, { pinned: true });
+ await model.create({ systemRole: '', title: 'Unpinned', visibility: 'public' } as any);
+ const repo = new HomeRepository(clientDB, owner, ws);
+
+ // Without a saved order, newest first.
+ expect(await repo.getTeamPinnedIds()).toEqual([b, a]);
+
+ await repo.updatePinnedOrder([a, b]);
+ expect(await repo.getTeamPinnedIds()).toEqual([a, b]);
+ // Personal mode has no default pins.
+ expect(await new HomeRepository(clientDB, owner).getTeamPinnedIds()).toEqual([]);
+ });
+
+ it('recommends the team pins until a list is saved, then the saved list', async () => {
+ const model = new AgentModel(clientDB, owner, ws);
+ const a = await createPinned(model, 'A');
+ const b = await createPinned(model, 'B');
+ const repo = new HomeRepository(clientDB, owner, ws);
+ await repo.updatePinnedOrder([a, b]);
+
+ expect(await repo.getRecommendedIds()).toEqual([a, b]);
+ expect((await repo.getSidebarAgentList()).recommendedIds).toEqual([a, b]);
+
+ await repo.updateRecommendedIds(['x', b, 'x']);
+ expect(await repo.getRecommendedIds()).toEqual(['x', b]);
+ expect((await repo.getSidebarAgentList()).recommendedIds).toEqual(['x', b]);
+ // An emptied list stays empty instead of falling back to the team pins.
+ await repo.updateRecommendedIds([]);
+ expect(await repo.getRecommendedIds()).toEqual([]);
+
+ const [row] = await clientDB
+ .select({ settings: Schema.workspaces.settings })
+ .from(Schema.workspaces)
+ .where(eq(Schema.workspaces.id, ws));
+ expect(row.settings).toEqual({
+ apiKey: { memberCreation: 'admins_only' },
+ sidebar: { other: true, recommendedAgentIds: [], teamPinnedOrder: [a, b] },
+ });
+ // Personal mode has no recommended list.
+ expect(await new HomeRepository(clientDB, owner).getRecommendedIds()).toEqual([]);
+ expect((await new HomeRepository(clientDB, owner).getSidebarAgentList()).recommendedIds).toBe(
+ undefined,
+ );
+ });
});
diff --git a/packages/database/src/repositories/home/index.ts b/packages/database/src/repositories/home/index.ts
index 792b45e6558..da2f3f101b4 100644
--- a/packages/database/src/repositories/home/index.ts
+++ b/packages/database/src/repositories/home/index.ts
@@ -30,10 +30,16 @@ import {
import { inJsonStringArray } from '../../utils/inJsonStringArray';
import { ilikeContains } from '../../utils/like';
import { notShareVisitorTopic } from '../../utils/shareVisitor';
+import { notTrashed } from '../../utils/softDelete';
import { CHANNEL_TOPIC_TRIGGER } from '../../utils/topicVisibility';
import { buildWorkspaceWhere } from '../../utils/workspace';
import type { FtsSearchCandidateSource } from '../ftsSearch';
-import { applyPinnedOrder, MAX_PINNED_ORDER_ITEMS, parsePinnedOrder } from './pinnedOrder';
+import {
+ applyPinnedOrder,
+ MAX_PINNED_ORDER_ITEMS,
+ MAX_RECOMMENDED_ITEMS,
+ parsePinnedOrder,
+} from './pinnedOrder';
// Mirrors the main chat sidebar's system-topic exclusions, plus the legacy
// task_manager trigger. These topics are surfaced in their own product surfaces,
@@ -223,9 +229,107 @@ export class HomeRepository {
result.pinned = applyPinnedOrder(result.pinned, await this.getPinnedOrder());
}
+ // 6. A workspace recommends Agents to every member; until owners/admins
+ // save that list, the team pins (just laid out in team order) stand in.
+ if (this.workspaceId) {
+ result.recommendedIds =
+ (await this.getStoredRecommendedIds()) ?? result.pinned.map((item) => item.id);
+ }
+
return result;
}
+ /**
+ * The workspace's saved recommended Agents / chat groups
+ * (`settings.sidebar.recommendedAgentIds`), or `null` while owners/admins
+ * never saved one.
+ */
+ private async getStoredRecommendedIds(): Promise<string[] | null> {
+ if (!this.workspaceId) return null;
+
+ const [row] = await this.db
+ .select({
+ ids: sql<unknown>`${workspaces.settings} #> '{sidebar,recommendedAgentIds}'`,
+ })
+ .from(workspaces)
+ .where(eq(workspaces.id, this.workspaceId));
+ return Array.isArray(row?.ids) ? parsePinnedOrder(row.ids) : null;
+ }
+
+ /**
+ * The Agents / chat groups owners and admins recommend to every member of
+ * the workspace, in their order. Until a list is saved, the team pins
+ * (public rows with the shared `pinned` column, in team order) are the
+ * list. Empty outside a workspace.
+ */
+ async getRecommendedIds(): Promise<string[]> {
+ if (!this.workspaceId) return [];
+ return (await this.getStoredRecommendedIds()) ?? this.getTeamPinnedIds();
+ }
+
+ /**
+ * Replace the workspace's recommended list (see {@link getRecommendedIds}).
+ * One UPDATE that rewrites only this key. Callers authorize the write: it
+ * changes what every member is recommended.
+ */
+ async updateRecommendedIds(ids: string[]): Promise<void> {
+ if (!this.workspaceId) return;
+
+ const list = JSON.stringify([...new Set(ids)].slice(0, MAX_RECOMMENDED_ITEMS));
+ await this.db
+ .update(workspaces)
+ .set({
+ settings: sql`coalesce(${workspaces.settings}, '{}'::jsonb) || jsonb_build_object(
+ 'sidebar',
+ coalesce(${workspaces.settings} -> 'sidebar', '{}'::jsonb)
+ || jsonb_build_object('recommendedAgentIds', ${list}::jsonb)
+ )`,
+ })
+ .where(eq(workspaces.id, this.workspaceId));
+ }
+
+ /**
+ * Ids of the workspace's team pins — public Agents / chat groups whose
+ * shared `pinned` column owners/admins set — in the team order. Members who
+ * joined while team pins were shown keep them as their own pins (see
+ * `WorkspaceUserSettingsModel.initializeSidebar`). Empty outside a
+ * workspace.
+ */
+ async getTeamPinnedIds(): Promise<string[]> {
+ if (!this.workspaceId) return [];
+
+ const pinnedAgents = await this.db
+ .select({ id: agents.id, updatedAt: agents.updatedAt })
+ .from(agents)
+ .where(
+ and(
+ eq(agents.workspaceId, this.workspaceId),
+ eq(agents.visibility, 'public'),
+ eq(agents.pinned, true),
+ notTrashed(agents.isDeleted),
+ sql`${agents.virtual} IS NOT TRUE`,
+ ),
+ );
+ const pinnedGroups = await this.db
+ .select({ id: chatGroups.id, updatedAt: chatGroups.updatedAt })
+ .from(chatGroups)
+ .where(
+ and(
+ eq(chatGroups.workspaceId, this.workspaceId),
+ eq(chatGroups.visibility, 'public'),
+ eq(chatGroups.pinned, true),
+ notTrashed(chatGroups.isDeleted),
+ ),
+ );
+
+ const rows = [...pinnedAgents, ...pinnedGroups].sort(
+ (a, b) => b.updatedAt.getTime() - a.updatedAt.getTime(),
+ );
+ if (rows.length === 0) return [];
+
+ return applyPinnedOrder(rows, await this.getPinnedOrder()).map((row) => row.id);
+ }
+
/**
* The saved order of the `pinned` bucket. In a workspace those rows are the
* team pins every member sees, so the order is shared and lives on the
diff --git a/packages/database/src/repositories/home/pinnedOrder.ts b/packages/database/src/repositories/home/pinnedOrder.ts
index 30e8763f04a..3d896e03e5b 100644
--- a/packages/database/src/repositories/home/pinnedOrder.ts
+++ b/packages/database/src/repositories/home/pinnedOrder.ts
@@ -6,6 +6,13 @@
*/
export const MAX_PINNED_ORDER_ITEMS = 2000;
+/**
+ * Upper bound for a workspace's recommended Agents list. Until a list is
+ * saved, the team pins are the list, so it matches their order's cap: admins
+ * must be able to save that list back, trimmed or reordered.
+ */
+export const MAX_RECOMMENDED_ITEMS = MAX_PINNED_ORDER_ITEMS;
+
/** Reads a stored order defensively: anything but a string array is no order. */
export const parsePinnedOrder = (value: unknown): string[] =>
Array.isArray(value) ? value.filter((id): id is string => typeof id === 'string') : [];
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index b63e6f63b4a..e1705a9e668 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -1794,9 +1794,12 @@ export default {
'textSelection.quote': 'Quote',
'pin': 'Pin',
'pinOff': 'Unpin',
- 'pinForTeam': 'Pin for team',
- 'pinForTeamForbidden': 'Only workspace owners and admins can change team pins',
- 'unpinForTeam': 'Unpin for team',
+ 'recommendAgent': 'Add to recommended agents',
+ 'recommendAgentSuccess':
+ 'Added to recommended agents. New members will start with it in their sidebar',
+ 'recommendAgentForbidden': 'Only workspace owners and admins can change recommended agents',
+ 'unrecommendAgent': 'Remove from recommended agents',
+ 'unrecommendAgentSuccess': 'Removed from recommended agents',
'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 c5a779e61c1..a978a7fe0af 100644
--- a/packages/locales/src/default/common.ts
+++ b/packages/locales/src/default/common.ts
@@ -30,6 +30,9 @@ export default {
'agentViewAll.orderBy.updatedAt': 'Updated at',
'agentViewAll.pendant.official': 'Official',
'agentViewAll.removeFromSidebar': 'Hide from my sidebar',
+ 'agentViewAll.recommendedSection.title': 'Recommended agents',
+ 'agentViewAll.recommendedSection.empty':
+ 'No recommended agents yet. Use “Add to recommended agents” in an agent’s menu.',
'agentViewAll.sidebarSection.collapse': 'Fold',
'agentViewAll.sidebarSection.expand': 'Unfold',
'agentViewAll.sidebarSection.title': 'In Sidebar',
@@ -450,13 +453,8 @@ export default {
'navPanel.agent': 'Agents',
'navPanel.createPrivateFolder': 'New private category',
'navPanel.managePrivateFolders': 'Manage private categories',
- 'navPanel.myPinned': 'Pinned',
'navPanel.newChat': 'New chat',
'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.customizeSidebar': 'Customize Sidebar',
'navPanel.openMenu': 'Open menu',
'navPanel.shortcuts': 'Shortcuts',
diff --git a/packages/types/src/home.ts b/packages/types/src/home.ts
index c9ee837012c..08623c5f81e 100644
--- a/packages/types/src/home.ts
+++ b/packages/types/src/home.ts
@@ -156,5 +156,12 @@ export interface SidebarAgentListResponse {
* user. Empty array in personal mode.
*/
privateUngrouped: SidebarAgentItem[];
+ /**
+ * Workspace-only: the Agents / chat groups owners and admins recommend to
+ * every member, in their order. New members start with them in their
+ * sidebar (unpinned); the Agents page lists them on top. Absent in personal
+ * mode.
+ */
+ recommendedIds?: string[];
ungrouped: SidebarAgentItem[];
}
diff --git a/packages/types/src/user/preference.ts b/packages/types/src/user/preference.ts
index 67b18723610..c04879f27f3 100644
--- a/packages/types/src/user/preference.ts
+++ b/packages/types/src/user/preference.ts
@@ -126,13 +126,24 @@ export interface WorkspaceUserPreference {
*/
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.
+ * Whether this member's sidebar was set up from the workspace once. The
+ * server does it the first time the member's preference is read:
+ * - a member who joined before team pins were retired keeps the team pins
+ * (public rows with the shared `pinned` column) as their own pins;
+ * - anyone else gets the workspace's recommended Agents
+ * (`settings.sidebar.recommendedAgentIds`) added to their sidebar,
+ * unpinned, through `sidebarAgentVisibilityOverrides`.
+ * Nothing is written while there is nothing to add, so a later list still
+ * reaches the member. Changes to the list never reach a member set up before.
+ */
+ sidebarInitialized?: boolean;
+ /**
+ * Agents / chat groups pinned in this member's merged workspace "Agents"
+ * section, in the member's own order. Personal: it never changes another
+ * member's sidebar. A member who joined before team pins were retired has
+ * them copied in once (see `sidebarInitialized`); after that the member
+ * alone decides what it holds. A private row's own `pinned` column is read
+ * as this member's pin too, since only its creator can see it.
*/
sidebarPinnedItemIds?: string[];
/**
diff --git a/src/components/Skeleton/AgentViewAll.test.ts b/src/components/Skeleton/AgentViewAll.test.ts
index ac5f39185d8..c19a98bed73 100644
--- a/src/components/Skeleton/AgentViewAll.test.ts
+++ b/src/components/Skeleton/AgentViewAll.test.ts
@@ -9,7 +9,7 @@ import AgentViewAllSkeleton from './AgentViewAll';
const setCollapsed = (collapsed: boolean) =>
useGlobalStore.setState((s) => ({
- status: { ...s.status, agentListSidebarSectionCollapsed: collapsed },
+ status: { ...s.status, agentListSidebarSectionExpanded: !collapsed },
}));
const render = () => {
@@ -21,11 +21,12 @@ const render = () => {
};
describe('AgentViewAllSkeleton', () => {
- afterEach(() => setCollapsed(false));
+ afterEach(() => setCollapsed(true));
// The loaded page puts the "In sidebar" block above the toolbar; a skeleton
// without it dropped the toolbar and rows by the block's height on load.
it('reserves the expanded "In sidebar" block above the toolbar', () => {
+ setCollapsed(false);
const { count, unmount } = render();
expect(count('agent-view-all-sidebar-skeleton')).toBe(1);
@@ -41,4 +42,20 @@ describe('AgentViewAllSkeleton', () => {
expect(count('agent-view-all-sidebar-card-skeleton')).toBe(0);
unmount();
});
+
+ it('starts collapsed for everyone, whatever earlier builds persisted', () => {
+ // Earlier builds persisted `agentListSidebarSectionCollapsed: false` as
+ // the default for every account; it must not keep the block open.
+ useGlobalStore.setState((s) => ({
+ status: {
+ ...s.status,
+ agentListSidebarSectionCollapsed: false,
+ agentListSidebarSectionExpanded: undefined,
+ },
+ }));
+ const { count, unmount } = render();
+
+ expect(count('agent-view-all-sidebar-card-skeleton')).toBe(0);
+ unmount();
+ });
});
diff --git a/src/features/AgentViewAll/AgentViewAllPage.tsx b/src/features/AgentViewAll/AgentViewAllPage.tsx
index e62dae4381f..0b59edef77c 100644
--- a/src/features/AgentViewAll/AgentViewAllPage.tsx
+++ b/src/features/AgentViewAll/AgentViewAllPage.tsx
@@ -57,6 +57,7 @@ import { flattenAgentBuckets } from './flattenBuckets';
import { groupItemsByFolder } from './groupByFolder';
import ListConfig from './ListConfig';
import { type AgentListViewOptions, normalizeAgentListViewOptions } from './listViewOptions';
+import RecommendedAgentsSection from './RecommendedAgentsSection';
import SidebarAgentsSection from './SidebarAgentsSection';
type SegmentValue = 'private' | 'workspace';
@@ -227,6 +228,7 @@ const AgentViewAllPage = memo(() => {
const isInit = useHomeStore(homeAgentListSelectors.isAgentListInit);
const pinnedAgents = useHomeStore(homeAgentListSelectors.pinnedAgents, isEqual);
+ const recommendedIds = useHomeStore(homeAgentListSelectors.recommendedAgentIds, isEqual);
const agentGroups = useHomeStore(homeAgentListSelectors.agentGroups, isEqual);
const ungroupedAgents = useHomeStore(homeAgentListSelectors.ungroupedAgents, isEqual);
const privatePinnedAgents = useHomeStore(homeAgentListSelectors.privatePinnedAgents, isEqual);
@@ -259,6 +261,15 @@ const AgentViewAllPage = memo(() => {
const items = activeWorkspaceId && segment === 'private' ? privateItems : workspaceItems;
+ // The workspace's recommended Agents, in the owners'/admins' order; ids of
+ // rows that no longer exist (or turned private) are skipped.
+ const recommendedItems = useMemo(() => {
+ if (!activeWorkspaceId) return [];
+ const byId = new Map(workspaceItems.map((item) => [item.id, item]));
+ return recommendedIds.flatMap((id) => byId.get(id) ?? []);
+ }, [activeWorkspaceId, recommendedIds, workspaceItems]);
+ const { allowed: canEditRecommended } = usePermission('manage_settings');
+
// "In sidebar" overview data: everything visible in the sidebar across BOTH
// the workspace and private buckets — the block answers "what's in my
// sidebar right now", so it ignores the tab and the search keyword (it
@@ -522,10 +533,10 @@ const AgentViewAllPage = memo(() => {
key={item.id}
owner={showAuthor && item.userId ? authorByUserId.get(item.userId) : undefined}
sidebarHidden={!isListed(item)}
- onToggleSidebar={workspaceSidebarIds?.fixed.has(item.id) ? undefined : handleToggleSidebar}
+ onToggleSidebar={handleToggleSidebar}
/>
),
- [showAuthor, authorByUserId, handleToggleSidebar, isListed, workspaceSidebarIds],
+ [showAuthor, authorByUserId, handleToggleSidebar, isListed],
);
const renderRow = useCallback(
@@ -536,10 +547,10 @@ const AgentViewAllPage = memo(() => {
key={item.id}
showAuthor={showAuthor}
sidebarHidden={!isListed(item)}
- onToggleSidebar={workspaceSidebarIds?.fixed.has(item.id) ? undefined : handleToggleSidebar}
+ onToggleSidebar={handleToggleSidebar}
/>
),
- [showAuthor, authorByUserId, handleToggleSidebar, isListed, workspaceSidebarIds],
+ [showAuthor, authorByUserId, handleToggleSidebar, isListed],
);
const { allowed: canCreate, reason: createBlockedReason } = usePermission('create_content');
@@ -607,13 +618,19 @@ const AgentViewAllPage = memo(() => {
paddingInline={16}
wrapperStyle={{ flex: 1, overflowY: 'auto' }}
>
+ {isInit &&
+ !keyword.trim() &&
+ (recommendedItems.length > 0 || (!!activeWorkspaceId && canEditRecommended)) && (
+ <RecommendedAgentsSection
+ canEdit={canEditRecommended}
+ isListed={isListed}
+ items={recommendedItems}
+ onToggleSidebar={handleToggleSidebar}
+ />
+ )}
{!isInit && !keyword.trim() && <AgentViewAllSidebarSectionSkeleton />}
{isInit && !keyword.trim() && sidebarItems.length > 0 && (
- <SidebarAgentsSection
- fixedIds={workspaceSidebarIds?.fixed}
- items={sidebarItems}
- onToggleSidebar={handleToggleSidebar}
- />
+ <SidebarAgentsSection items={sidebarItems} onToggleSidebar={handleToggleSidebar} />
)}
<Flexbox horizontal align={'center'} gap={12} justify={'space-between'}>
{/* The workspace/private split only exists inside a workspace;
diff --git a/src/features/AgentViewAll/RecommendedAgentsSection.tsx b/src/features/AgentViewAll/RecommendedAgentsSection.tsx
new file mode 100644
index 00000000000..c505205ee1f
--- /dev/null
+++ b/src/features/AgentViewAll/RecommendedAgentsSection.tsx
@@ -0,0 +1,216 @@
+'use client';
+
+import { closestCenter, DndContext, type DragEndEvent, useSensor, useSensors } from '@dnd-kit/core';
+import {
+ arrayMove,
+ rectSortingStrategy,
+ SortableContext,
+ sortableKeyboardCoordinates,
+ useSortable,
+} from '@dnd-kit/sortable';
+import { CSS } from '@dnd-kit/utilities';
+import type { SidebarAgentItem } from '@lobechat/types';
+import { ActionIcon, cssVar, Flexbox, Icon, Text, toast } from '@lobehub/ui';
+import { CheckIcon, ChevronDownIcon, ChevronUpIcon, PlusIcon } from 'lucide-react';
+import { memo, type MouseEvent, useCallback, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import {
+ RowKeyboardSensor,
+ RowMouseSensor,
+ RowTouchSensor,
+ suppressNextClick,
+} from '@/features/HomeSidebar/Body/sortableRow';
+import { useGlobalStore } from '@/store/global';
+import { systemStatusSelectors } from '@/store/global/selectors';
+import { useHomeStore } from '@/store/home';
+
+import { agentSectionStyles, SidebarMiniCard } from './SidebarAgentsSection';
+
+interface RecommendedCardProps {
+ isListed: (item: SidebarAgentItem) => boolean;
+ item: SidebarAgentItem;
+ onToggleSidebar: (item: SidebarAgentItem) => void;
+}
+
+/** A recommended Agent with a one-click "add to my sidebar" toggle. */
+const RecommendedCard = memo<RecommendedCardProps>(({ isListed, item, onToggleSidebar }) => {
+ const { t } = useTranslation('common');
+ const listed = isListed(item);
+
+ const handleToggle = useCallback(
+ (event: MouseEvent) => {
+ // The card is a link to the Agent; the button only toggles the sidebar.
+ event.preventDefault();
+ event.stopPropagation();
+ onToggleSidebar(item);
+ },
+ [item, onToggleSidebar],
+ );
+
+ return (
+ <SidebarMiniCard
+ item={item}
+ listed={listed}
+ extra={
+ <ActionIcon
+ data-row-action
+ active={listed}
+ icon={listed ? CheckIcon : PlusIcon}
+ size={'small'}
+ title={listed ? t('agentViewAll.removeFromSidebar') : t('agentViewAll.addToSidebar')}
+ onClick={handleToggle}
+ />
+ }
+ onToggleSidebar={onToggleSidebar}
+ />
+ );
+});
+
+RecommendedCard.displayName = 'RecommendedCard';
+
+const SortableCard = memo<RecommendedCardProps>((props) => {
+ const { attributes, isDragging, listeners, setNodeRef, transform, transition } = useSortable({
+ id: props.item.id,
+ });
+
+ return (
+ <div
+ ref={setNodeRef}
+ style={{
+ opacity: isDragging ? 0.4 : undefined,
+ transform: CSS.Translate.toString(transform),
+ transition,
+ userSelect: 'none',
+ }}
+ {...attributes}
+ {...listeners}
+ onDragStart={(event) => event.preventDefault()}
+ >
+ <RecommendedCard {...props} />
+ </div>
+ );
+});
+
+SortableCard.displayName = 'SortableRecommendedCard';
+
+interface RecommendedAgentsSectionProps {
+ /** Owners/admins arrange the list; everyone else only reads it. */
+ canEdit: boolean;
+ isListed: (item: SidebarAgentItem) => boolean;
+ /** The recommended Agents / chat groups that still exist, in order. */
+ items: SidebarAgentItem[];
+ onToggleSidebar: (item: SidebarAgentItem) => void;
+}
+
+/**
+ * "Recommended agents" on top of the Agents page: the Agents owners/admins
+ * recommend to every member of the workspace. New members start with them in
+ * their sidebar (unpinned); anyone can add one to their sidebar from here.
+ * Owners/admins drag the cards to reorder and add / remove Agents from an
+ * Agent's menu ("Add to recommended agents").
+ */
+const RecommendedAgentsSection = memo<RecommendedAgentsSectionProps>(
+ ({ canEdit, isListed, items, onToggleSidebar }) => {
+ const { t } = useTranslation('common');
+ const updateRecommendedAgents = useHomeStore((s) => s.updateRecommendedAgents);
+ const collapsed = useGlobalStore(systemStatusSelectors.agentListRecommendedSectionCollapsed);
+ const updateSystemStatus = useGlobalStore((s) => s.updateSystemStatus);
+ const toggleCollapsed = useCallback(
+ () =>
+ updateSystemStatus(
+ { agentListRecommendedSectionCollapsed: !collapsed },
+ 'toggleAgentListRecommendedSection',
+ ),
+ [collapsed, updateSystemStatus],
+ );
+ const ids = useMemo(() => items.map((item) => item.id), [items]);
+
+ const sensors = useSensors(
+ useSensor(RowMouseSensor, { activationConstraint: { distance: 5 } }),
+ useSensor(RowTouchSensor, { activationConstraint: { delay: 250, tolerance: 5 } }),
+ useSensor(RowKeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates }),
+ );
+
+ const handleDragEnd = useCallback(
+ async ({ active, over }: DragEndEvent) => {
+ suppressNextClick();
+ if (!over || active.id === over.id) return;
+
+ const next = arrayMove(ids, ids.indexOf(String(active.id)), ids.indexOf(String(over.id)));
+ try {
+ await updateRecommendedAgents(next);
+ } catch (error) {
+ console.error('[agents] failed to save the recommended order', error);
+ toast.error(t('operationFailed'));
+ }
+ },
+ [ids, t, updateRecommendedAgents],
+ );
+
+ const cardProps = { isListed, onToggleSidebar };
+
+ return (
+ <Flexbox className={agentSectionStyles.container} data-testid={'recommended-agents'} gap={12}>
+ <Flexbox
+ horizontal
+ align={'center'}
+ className={agentSectionStyles.header}
+ gap={8}
+ justify={'space-between'}
+ onClick={toggleCollapsed}
+ >
+ <Flexbox horizontal align={'center'} gap={8}>
+ <Text fontSize={13} weight={500}>
+ {t('agentViewAll.recommendedSection.title')}
+ </Text>
+ <Text fontSize={12} type={'secondary'}>
+ {items.length}
+ </Text>
+ </Flexbox>
+ <Flexbox horizontal align={'center'} flex={'none'} 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 ? null : items.length === 0 ? (
+ <Text fontSize={12} type={'secondary'}>
+ {t('agentViewAll.recommendedSection.empty')}
+ </Text>
+ ) : canEdit ? (
+ <DndContext
+ collisionDetection={closestCenter}
+ sensors={sensors}
+ onDragEnd={handleDragEnd}
+ >
+ <SortableContext items={ids} strategy={rectSortingStrategy}>
+ <div className={agentSectionStyles.grid}>
+ {items.map((item) => (
+ <SortableCard item={item} key={item.id} {...cardProps} />
+ ))}
+ </div>
+ </SortableContext>
+ </DndContext>
+ ) : (
+ <div className={agentSectionStyles.grid}>
+ {items.map((item) => (
+ <RecommendedCard item={item} key={item.id} {...cardProps} />
+ ))}
+ </div>
+ )}
+ </Flexbox>
+ );
+ },
+);
+
+RecommendedAgentsSection.displayName = 'RecommendedAgentsSection';
+
+export default RecommendedAgentsSection;
diff --git a/src/features/AgentViewAll/SidebarAgentsSection.tsx b/src/features/AgentViewAll/SidebarAgentsSection.tsx
index c5ca6fc1a6f..cc819c9c83c 100644
--- a/src/features/AgentViewAll/SidebarAgentsSection.tsx
+++ b/src/features/AgentViewAll/SidebarAgentsSection.tsx
@@ -15,7 +15,7 @@ import {
Text,
} from '@lobehub/ui';
import { ChevronDownIcon, ChevronUpIcon } from 'lucide-react';
-import { memo, useCallback, useRef, useState } from 'react';
+import { memo, type ReactNode, useCallback, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
@@ -30,7 +30,7 @@ import SidebarItemAvatar from './SidebarItemAvatar';
// "In sidebar" overview: a collapsible card grid pinned above the main list
// so the user can see at a glance which agents currently show in the sidebar
// (mirrors the enabled-providers block on the provider settings page).
-const styles = createStaticStyles(({ css, cssVar }) => ({
+export const agentSectionStyles = createStaticStyles(({ css, cssVar }) => ({
/* The headless ItemActions still renders an empty span; keeping it out of
the flex flow stops it from claiming a `gap` and shifting the centering. */
actions: css`
@@ -98,146 +98,146 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
}));
interface SidebarMiniCardProps {
+ /** Shown at the end of the title line, e.g. a quick "add to sidebar" button. */
+ extra?: ReactNode;
item: SidebarAgentItem;
+ /** Whether the item is in the member's sidebar (drives the menu's toggle). */
+ listed?: boolean;
onToggleSidebar?: (item: SidebarAgentItem) => void;
}
// Deliberately minimal (avatar + name + description only) — the block answers
// "what's in my sidebar", so the full card's labels/author/date are noise here.
// Actions live entirely in the right-click menu (same as rows/cards).
-const SidebarMiniCard = memo<SidebarMiniCardProps>(({ item, onToggleSidebar }) => {
- const { t } = useTranslation('common');
- const { description, id, type } = item;
- // Groups have no personal name, so this resolves to their title.
- const displayTitle = agentDisplayName(item, t('agentViewAll.untitled'));
- const roleTag = agentSecondaryDisplayName(item);
- const [anchor, setAnchor] = useState<HTMLElement | null>(null);
-
- const [menuActivated, setMenuActivated] = useState(false);
- const activateMenu = useCallback(() => setMenuActivated(true), []);
- const menuItemsRef = useRef<(() => DropdownItem[]) | null>(null);
- const handleMenuReady = useCallback((getItems: () => DropdownItem[]) => {
- menuItemsRef.current = getItems;
- }, []);
- const getContextMenuItems = useCallback(() => menuItemsRef.current?.() ?? [], []);
+export const SidebarMiniCard = memo<SidebarMiniCardProps>(
+ ({ extra, item, listed = true, onToggleSidebar }) => {
+ const { t } = useTranslation('common');
+ const { description, id, type } = item;
+ // Groups have no personal name, so this resolves to their title.
+ const displayTitle = agentDisplayName(item, t('agentViewAll.untitled'));
+ const roleTag = agentSecondaryDisplayName(item);
+ const [anchor, setAnchor] = useState<HTMLElement | null>(null);
+
+ const [menuActivated, setMenuActivated] = useState(false);
+ const activateMenu = useCallback(() => setMenuActivated(true), []);
+ const menuItemsRef = useRef<(() => DropdownItem[]) | null>(null);
+ const handleMenuReady = useCallback((getItems: () => DropdownItem[]) => {
+ menuItemsRef.current = getItems;
+ }, []);
+ const getContextMenuItems = useCallback(() => menuItemsRef.current?.() ?? [], []);
- return (
- <ContextMenuTrigger items={getContextMenuItems}>
- {/* Single child: the trigger wraps exactly one element, and the grid
+ return (
+ <ContextMenuTrigger items={getContextMenuItems}>
+ {/* Single child: the trigger wraps exactly one element, and the grid
treats it as one cell. The headless ItemActions lives INSIDE it —
rendering it as a sibling would add a phantom grid item. */}
- <WorkspaceLink
- aria-label={displayTitle}
- className={styles.link}
- ref={setAnchor}
- to={type === 'group' ? GROUP_CHAT_URL(id) : AGENT_CHAT_URL(id, false)}
- onPointerEnter={activateMenu}
- >
- <Block clickable className={styles.card} height={'100%'} variant={'outlined'}>
- <Flexbox horizontal align={'center'} gap={8} style={{ minWidth: 0 }}>
- <SidebarItemAvatar item={item} size={24} />
- <Text ellipsis style={{ minWidth: 0 }} weight={600}>
- {displayTitle}
- </Text>
- {roleTag ? (
- <Tag size={'small'} style={{ flex: 'none' }}>
- {roleTag}
- </Tag>
+ <WorkspaceLink
+ aria-label={displayTitle}
+ className={agentSectionStyles.link}
+ ref={setAnchor}
+ to={type === 'group' ? GROUP_CHAT_URL(id) : AGENT_CHAT_URL(id, false)}
+ onPointerEnter={activateMenu}
+ >
+ <Block clickable className={agentSectionStyles.card} height={'100%'} variant={'outlined'}>
+ <Flexbox horizontal align={'center'} gap={8} style={{ minWidth: 0 }}>
+ <SidebarItemAvatar item={item} size={24} />
+ <Text ellipsis style={{ minWidth: 0 }} weight={600}>
+ {displayTitle}
+ </Text>
+ {roleTag ? (
+ <Tag size={'small'} style={{ flex: 'none' }}>
+ {roleTag}
+ </Tag>
+ ) : null}
+ {extra ? (
+ <span style={{ flex: 'none', marginInlineStart: 'auto' }}>{extra}</span>
+ ) : null}
+ </Flexbox>
+ {description ? (
+ <Text className={agentSectionStyles.description} fontSize={12} type={'secondary'}>
+ {description}
+ </Text>
) : null}
- </Flexbox>
- {description ? (
- <Text className={styles.description} fontSize={12} type={'secondary'}>
- {description}
- </Text>
- ) : null}
- <span className={styles.actions}>
- <ItemActions
- hideTrigger
- includeSidebarToggle
- anchor={anchor}
- forceActivated={menuActivated}
- item={item}
- sidebarHidden={false}
- onMenuReady={handleMenuReady}
- onToggleSidebar={onToggleSidebar}
- />
- </span>
- </Block>
- </WorkspaceLink>
- </ContextMenuTrigger>
- );
-});
+ <span className={agentSectionStyles.actions}>
+ <ItemActions
+ hideTrigger
+ includeSidebarToggle
+ anchor={anchor}
+ forceActivated={menuActivated}
+ item={item}
+ sidebarHidden={!listed}
+ onMenuReady={handleMenuReady}
+ onToggleSidebar={onToggleSidebar}
+ />
+ </span>
+ </Block>
+ </WorkspaceLink>
+ </ContextMenuTrigger>
+ );
+ },
+);
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>(
- ({ 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],
- );
+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(
+ { agentListSidebarSectionExpanded: 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>
+ return (
+ <Flexbox className={agentSectionStyles.container} gap={12}>
+ <Flexbox
+ horizontal
+ align={'center'}
+ className={agentSectionStyles.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>
- {!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={agentSectionStyles.grid}>
+ {items.map((item) => (
+ <SidebarMiniCard item={item} key={item.id} onToggleSidebar={onToggleSidebar} />
+ ))}
+ </div>
+ )}
+ </Flexbox>
+ );
+});
SidebarAgentsSection.displayName = 'SidebarAgentsSection';
diff --git a/src/features/HomeSidebar/Body/Agent/List/AgentGroupItem/index.tsx b/src/features/HomeSidebar/Body/Agent/List/AgentGroupItem/index.tsx
index 556b7864671..6cc141d2e8e 100644
--- a/src/features/HomeSidebar/Body/Agent/List/AgentGroupItem/index.tsx
+++ b/src/features/HomeSidebar/Body/Agent/List/AgentGroupItem/index.tsx
@@ -28,8 +28,7 @@ const GroupItem = memo<GroupItemProps>(({ item, style, className, onNavigate })
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 { isMyPinned, isPrivate } = useSidebarPinState({ id, pinned, visibility });
const openAgentInNewWindow = useGlobalStore((s) => s.openAgentInNewWindow);
@@ -78,15 +77,15 @@ const GroupItem = memo<GroupItemProps>(({ item, style, className, onNavigate })
// can't truncate it out of view.
const pinIcon = useMemo(
() =>
- showPinIcon || isPrivate ? (
+ isMyPinned || isPrivate ? (
<>
{isPrivate && <PrivateLockIcon />}
- {showPinIcon && (
+ {isMyPinned && (
<ActionIcon icon={PinIcon} size={12} style={{ opacity: 0.5, pointerEvents: 'none' }} />
)}
</>
) : undefined,
- [isPrivate, showPinIcon],
+ [isMyPinned, isPrivate],
);
// Memoize avatar icon (show loader when updating)
diff --git a/src/features/HomeSidebar/Body/Agent/List/AgentGroupItem/useDropdownMenu.test.tsx b/src/features/HomeSidebar/Body/Agent/List/AgentGroupItem/useDropdownMenu.test.tsx
index 82abf4ce0bc..14d74c97ed7 100644
--- a/src/features/HomeSidebar/Body/Agent/List/AgentGroupItem/useDropdownMenu.test.tsx
+++ b/src/features/HomeSidebar/Body/Agent/List/AgentGroupItem/useDropdownMenu.test.tsx
@@ -14,7 +14,6 @@ const mocks = vi.hoisted(() => ({
removeAgentGroup: vi.fn(),
},
isSidebarItemVisible: vi.fn(() => true),
- isTeamPinned: false,
openAgentInNewWindow: vi.fn(),
setSidebarItemVisible: vi.fn(),
toastError: vi.fn(),
@@ -70,7 +69,6 @@ vi.mock('../../useSidebarItemVisibility', () => ({
vi.mock('../../useSidebarPinMenuItems', () => ({
useSidebarPinMenuItems: () => ({
- isTeamPinned: mocks.isTeamPinned,
menuItems: mocks.activeWorkspaceId ? [{ key: 'pin', label: 'pin' }] : [],
}),
}));
@@ -102,7 +100,6 @@ describe('useGroupDropdownMenu', () => {
mocks.canEditResource = true;
mocks.canManage = true;
mocks.isSidebarItemVisible.mockReturnValue(true);
- mocks.isTeamPinned = false;
});
it('hides a group through the caller sidebar preference, like an Agent row', async () => {
@@ -159,11 +156,10 @@ describe('useGroupDropdownMenu', () => {
expect(getMenuKeys(result.current())).not.toContain('hideFromSidebar');
});
- it('omits hide on a team-pinned workspace group, which every member sees', () => {
+ it('offers hide on a workspace group that is a default pin for new members', () => {
mocks.activeWorkspaceId = 'workspace-1';
- mocks.isTeamPinned = true;
const { result } = renderGroupMenu({ pinned: true, visibility: 'public' });
- expect(getMenuKeys(result.current())).not.toContain('hideFromSidebar');
+ expect(getMenuKeys(result.current())).toContain('hideFromSidebar');
});
});
diff --git a/src/features/HomeSidebar/Body/Agent/List/AgentGroupItem/useDropdownMenu.tsx b/src/features/HomeSidebar/Body/Agent/List/AgentGroupItem/useDropdownMenu.tsx
index 8a580f71b31..1ec10b24aaa 100644
--- a/src/features/HomeSidebar/Body/Agent/List/AgentGroupItem/useDropdownMenu.tsx
+++ b/src/features/HomeSidebar/Body/Agent/List/AgentGroupItem/useDropdownMenu.tsx
@@ -81,7 +81,7 @@ export const useGroupDropdownMenu = ({
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 { isTeamPinned, menuItems: workspacePinItems } = useSidebarPinMenuItems({
+ const { menuItems: workspacePinItems } = useSidebarPinMenuItems({
id,
pinned,
type: 'group',
@@ -110,9 +110,7 @@ export const useGroupDropdownMenu = ({
},
]
: []),
- // Team-pinned rows are the fixed section every member sees; hiding
- // them would do nothing there.
- ...(isShownInSidebar && !isTeamPinned
+ ...(isShownInSidebar
? [
{
icon: <Icon icon={EyeOffIcon} />,
@@ -217,7 +215,6 @@ export const useGroupDropdownMenu = ({
activeWorkspaceId,
workspacePinItems,
isShownInSidebar,
- isTeamPinned,
setSidebarItemVisible,
anchor,
avatar,
diff --git a/src/features/HomeSidebar/Body/Agent/List/AgentItem/index.tsx b/src/features/HomeSidebar/Body/Agent/List/AgentItem/index.tsx
index 943fc916e0b..b9e6486574b 100644
--- a/src/features/HomeSidebar/Body/Agent/List/AgentItem/index.tsx
+++ b/src/features/HomeSidebar/Body/Agent/List/AgentItem/index.tsx
@@ -150,25 +150,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;
+ // In a workspace the row's column is a default pin for new members (public)
+ // or the creator's own pin (private); the member's own pins live in their
+ // preference.
+ const { isMyPinned, isPrivate } = useSidebarPinState({ id, pinned, visibility });
// 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(
() =>
- showPinIcon || isPrivate ? (
+ isMyPinned || isPrivate ? (
<>
{isPrivate && <PrivateLockIcon />}
- {showPinIcon && (
+ {isMyPinned && (
<ActionIcon icon={PinIcon} size={12} style={{ opacity: 0.5, pointerEvents: 'none' }} />
)}
</>
) : undefined,
- [isPrivate, showPinIcon],
+ [isMyPinned, isPrivate],
);
// 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 61630eb900e..01e7700f19a 100644
--- a/src/features/HomeSidebar/Body/Agent/List/AgentItem/useDropdownMenu.test.tsx
+++ b/src/features/HomeSidebar/Body/Agent/List/AgentItem/useDropdownMenu.test.tsx
@@ -13,6 +13,7 @@ const mocks = vi.hoisted(() => ({
canManage: false,
canManageSettings: false,
myPinnedIds: [] as string[],
+ recommendedIds: [] as string[],
confirmModal: vi.fn(),
confirmRemoveAgent: vi.fn(),
copyToClipboard: vi.fn(),
@@ -28,6 +29,7 @@ const mocks = vi.hoisted(() => ({
removeAgent: vi.fn(),
toggleAgentLabel: vi.fn(),
updateAgentGroup: vi.fn(),
+ updateRecommendedAgents: vi.fn(),
updateAgentMeta: vi.fn(),
},
navigate: vi.fn(),
@@ -129,6 +131,7 @@ vi.mock('@/store/home/selectors', () => ({
homeAgentListSelectors: {
agentGroups: () => [],
privateAgentGroups: () => [],
+ recommendedAgentIds: () => mocks.recommendedIds,
},
}));
@@ -150,6 +153,8 @@ vi.mock('@/store/user/selectors', () => ({
workspaceUserSettingsSelectors: {
sidebarPinnedItemIds: (state: UserStateMock) =>
state.workspaceUserPreference.sidebarPinnedItemIds,
+ // The member's sidebar was already set up.
+ sidebarSetupPreview: () => null,
},
}));
@@ -216,16 +221,17 @@ describe('useAgentDropdownMenu', () => {
mocks.canManage = false;
mocks.canManageSettings = false;
mocks.myPinnedIds = [];
+ mocks.recommendedIds = [];
mocks.transferMenuItems = null;
});
describe('workspace pins', () => {
- it('offers a personal pin but no team pin to a member', async () => {
+ it('offers a personal pin but no recommend entry to a member', async () => {
const { result } = renderPublicAgentMenu('creator-1');
const keys = getMenuKeys(result.current());
expect(keys).toContain('pin');
- expect(keys).not.toContain('pinForTeam');
+ expect(keys).not.toContain('recommend');
await getMenuItem(result.current(), 'pin').onClick({
domEvent: { stopPropagation: vi.fn() },
@@ -238,45 +244,70 @@ describe('useAgentDropdownMenu', () => {
expect(mocks.home.pinAgent).not.toHaveBeenCalled();
});
- it('lets an owner/admin pin a public agent for the team', async () => {
+ it('lets an owner/admin add a public agent to the recommended agents', async () => {
mocks.canManageSettings = true;
+ mocks.recommendedIds = ['other'];
const { result } = renderPublicAgentMenu('creator-1');
- expect(getMenuKeys(result.current())).toEqual(expect.arrayContaining(['pin', 'pinForTeam']));
+ expect(getMenuKeys(result.current())).toEqual(expect.arrayContaining(['pin', 'recommend']));
- await getMenuItem(result.current(), 'pinForTeam').onClick({
+ await getMenuItem(result.current(), 'recommend').onClick({
domEvent: { stopPropagation: vi.fn() },
});
- expect(mocks.home.pinAgent).toHaveBeenCalledWith('agent-1', true);
+ expect(mocks.home.updateRecommendedAgents).toHaveBeenCalledWith(['other', 'agent-1']);
+ expect(mocks.home.pinAgent).not.toHaveBeenCalled();
+ expect(mocks.toastSuccess).toHaveBeenCalledWith('recommendAgentSuccess');
});
- it('shows a team-pinned agent as fixed: no hide, no personal pin, admin can unpin', () => {
+ it('lets an owner/admin remove a recommended agent', async () => {
mocks.canManageSettings = true;
+ mocks.recommendedIds = ['agent-1', 'other'];
+
+ const { result } = renderPublicAgentMenu('creator-1');
+ const recommendItem = getMenuItem(result.current(), 'recommend') as unknown as {
+ label: string;
+ };
+ expect(recommendItem.label).toBe('unrecommendAgent');
+ await getMenuItem(result.current(), 'recommend').onClick({
+ domEvent: { stopPropagation: vi.fn() },
+ });
+ expect(mocks.home.updateRecommendedAgents).toHaveBeenCalledWith(['other']);
+ });
+
+ it('does not pin a legacy team pin for a member whose sidebar is set up', () => {
const { result } = renderPublicAgentMenu('creator-1', { pinned: true });
const keys = getMenuKeys(result.current());
+ const pinItem = getMenuItem(result.current(), 'pin') as unknown as { label: string };
- expect(keys).toContain('pinForTeam');
- expect(keys).not.toContain('pin');
- expect(keys).not.toContain('hideFromSidebar');
+ expect(keys).toEqual(expect.arrayContaining(['pin', 'hideFromSidebar']));
+ expect(pinItem.label).toBe('pin');
});
- it('gives a member no pin control over a team-pinned agent', () => {
+ it('lets a member unpin a team pin copied into their own list', async () => {
+ mocks.myPinnedIds = ['agent-1'];
const { result } = renderPublicAgentMenu('creator-1', { pinned: true });
- const keys = getMenuKeys(result.current());
+ const pinItem = getMenuItem(result.current(), 'pin') as unknown as { label: string };
+ expect(pinItem.label).toBe('pinOff');
- expect(keys).not.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: true, type: 'agent', visibility: 'public' },
+ false,
+ );
+ expect(mocks.home.pinAgent).not.toHaveBeenCalled();
});
- it('never offers a team pin on a private agent', () => {
+ it('never offers to recommend 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');
+ expect(keys).not.toContain('recommend');
});
it('reads a personal pin from the member preference', () => {
diff --git a/src/features/HomeSidebar/Body/Agent/List/AgentItem/useDropdownMenu.tsx b/src/features/HomeSidebar/Body/Agent/List/AgentItem/useDropdownMenu.tsx
index 5beb035cbc5..666e996a41e 100644
--- a/src/features/HomeSidebar/Body/Agent/List/AgentItem/useDropdownMenu.tsx
+++ b/src/features/HomeSidebar/Body/Agent/List/AgentItem/useDropdownMenu.tsx
@@ -183,7 +183,7 @@ export const useAgentDropdownMenu = ({
// 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({
+ const { menuItems: workspacePinItems } = useSidebarPinMenuItems({
id,
pinned,
type: 'agent',
@@ -206,9 +206,7 @@ export const useAgentDropdownMenu = ({
},
]
: []),
- // Team-pinned rows are the fixed section every member sees; hiding
- // them would do nothing there.
- ...(isShownInSidebar && !isTeamPinned
+ ...(isShownInSidebar
? [
{
icon: <Icon icon={EyeOffIcon} />,
@@ -508,7 +506,6 @@ export const useAgentDropdownMenu = ({
[
activeWorkspaceId,
workspacePinItems,
- isTeamPinned,
canCreate,
canConfigure,
canEdit,
diff --git a/src/features/HomeSidebar/Body/Agent/List/AgentListContent.tsx b/src/features/HomeSidebar/Body/Agent/List/AgentListContent.tsx
index 07c08071781..acb5a314fff 100644
--- a/src/features/HomeSidebar/Body/Agent/List/AgentListContent.tsx
+++ b/src/features/HomeSidebar/Body/Agent/List/AgentListContent.tsx
@@ -42,9 +42,9 @@ const AgentListContent = memo<AgentListContentProps>(({ hideInbox, onMoreClick }
});
const hasInboxAgent = useHomeStore(homeAgentListSelectors.hasInboxAgent);
const { customList, pinnedList, defaultList, inboxItem } = useAgentList();
- // Personal pins are the user's own, so they can always be reordered. A
- // workspace caller (compact switchers) gets the team pins here, whose order
- // only owners/admins may change from the sidebar's own section.
+ // Personal pins are the user's own, so they can always be reordered.
+ // Workspaces render `WorkspaceAgentListContent` instead, where each member
+ // arranges their own pinned list.
const isWorkspace = !!useActiveWorkspaceId();
const pinnedAgents = useHomeStore(homeAgentListSelectors.pinnedAgents);
const reorderPinnedAgents = useHomeStore((s) => s.reorderPinnedAgents);
diff --git a/src/features/HomeSidebar/Body/Agent/List/WorkspaceAgentListContent.tsx b/src/features/HomeSidebar/Body/Agent/List/WorkspaceAgentListContent.tsx
index c736f8826e5..cc881755c3c 100644
--- a/src/features/HomeSidebar/Body/Agent/List/WorkspaceAgentListContent.tsx
+++ b/src/features/HomeSidebar/Body/Agent/List/WorkspaceAgentListContent.tsx
@@ -1,15 +1,13 @@
'use client';
-import { cssVar, Flexbox, Icon, Text, Tooltip } from '@lobehub/ui';
-import { ChevronDown, ChevronUp, MoreHorizontal, PinIcon, UsersIcon } from 'lucide-react';
-import { type ReactNode } from 'react';
-import { memo, useCallback, useMemo, useState } from 'react';
+import { Flexbox } from '@lobehub/ui';
+import { MoreHorizontal } from 'lucide-react';
+import { memo, useMemo } 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 { usePermission } from '@/hooks/usePermission';
import { useGlobalStore } from '@/store/global';
import { systemStatusSelectors } from '@/store/global/selectors';
import { useHomeStore } from '@/store/home';
@@ -26,45 +24,13 @@ import SessionList from './List';
import SortableList from './SortableList';
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): Lobe AI → my pins → team pins (fixed,
- * set by owners/admins for everyone) → folders → the rest. Personal pins come
- * first so the agents a member chose stay at the top instead of being pushed
- * down by the (possibly long) team list. Private rows
- * carry a lock icon wherever they appear. Personal mode keeps rendering
+ * "Workspace" and "Private" accordions): Lobe AI → pinned → folders → the rest.
+ * Pinned is the member's own list, which the workspace's default pins only
+ * seed once (server side); the member moves or unpins any row in it, and
+ * dragging never changes another member's order. Private rows carry a lock
+ * icon wherever they appear. Personal mode keeps rendering
* `AgentListContent`.
*/
const WorkspaceAgentListContent = memo<{ hideInbox?: boolean }>(({ hideInbox }) => {
@@ -78,27 +44,19 @@ const WorkspaceAgentListContent = memo<{ hideInbox?: boolean }>(({ hideInbox })
isLogin: !!isLogin,
});
- const hasInboxAgent = useHomeStore(homeAgentListSelectors.hasInboxAgent);
const agentPageSize = useGlobalStore(systemStatusSelectors.agentPageSize);
const navigate = useWorkspaceAwareNavigate();
- const [teamExpanded, setTeamExpanded] = useState(false);
- // Team pins are shared by every member, so only owners/admins (the roles the
- // server lets write team pins) can reorder them; everyone orders their own.
- const { allowed: canManageTeamPins } = usePermission('manage_settings');
- const [reorderPinnedAgents, reorderMyPinned] = useHomeStore((s) => [
- s.reorderPinnedAgents,
- s.reorderMyPinned,
- ]);
+ const reorderMyPinned = useHomeStore((s) => s.reorderMyPinned);
+ const hasInboxAgent = useHomeStore(homeAgentListSelectors.hasInboxAgent);
const sectionsWithInbox = useWorkspaceAgentSections();
// Lobe AI (the inbox) leads the sidebar wherever its row sits — a pin, a
// folder or the rest — so it is taken out of the sections and rendered first.
const { inboxItem, resolved } = useMemo(() => {
const folders = withoutInboxInGroups(sectionsWithInbox.folders);
const { inbox, lists } = liftInboxRow({
- myPinned: sectionsWithInbox.myPinned,
+ pinned: sectionsWithInbox.pinned,
rest: sectionsWithInbox.rest,
- teamPinned: sectionsWithInbox.teamPinned,
});
return {
@@ -106,23 +64,6 @@ const WorkspaceAgentListContent = memo<{ hideInbox?: boolean }>(({ hideInbox })
resolved: { ...lists, folders: folders.groups },
};
}, [sectionsWithInbox]);
- const { teamPinned } = resolved;
- const teamOverflow = teamPinned.length > TEAM_PINNED_VISIBLE_LIMIT;
- const visibleTeamPinned =
- teamOverflow && !teamExpanded ? teamPinned.slice(0, TEAM_PINNED_VISIBLE_LIMIT) : teamPinned;
-
- // While the team section is folded only its visible rows can move; the
- // folded ones keep their order after them.
- const handleReorderTeamPinned = useCallback(
- (ids: string[]) => {
- const moved = new Set(ids);
- return reorderPinnedAgents([
- ...ids,
- ...teamPinned.map((item) => item.id).filter((id) => !moved.has(id)),
- ]);
- },
- [reorderPinnedAgents, teamPinned],
- );
const sections = useMemo(
() => ({
...resolved,
@@ -147,55 +88,15 @@ const WorkspaceAgentListContent = memo<{ hideInbox?: boolean }>(({ hideInbox })
</>
);
- const { folders, hasMore, myPinned, rest } = sections;
+ const { folders, hasMore, pinned, rest } = sections;
return (
<>
{showStandaloneInbox && <InboxItem />}
{inboxItem && <SessionList dataSource={[inboxItem]} />}
- {myPinned.length > 0 && (
- <Flexbox data-testid={'sidebar-my-pinned'} gap={1}>
- <SubHeader
- icon={PinIcon}
- testId={'sidebar-my-pinned-header'}
- title={t('navPanel.myPinned')}
- />
- <SortableList dataSource={myPinned} onReorder={reorderMyPinned} />
- </Flexbox>
- )}
- {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')}
- />
- {canManageTeamPins ? (
- <SortableList dataSource={visibleTeamPinned} onReorder={handleReorderTeamPinned} />
- ) : (
- <SessionList dataSource={visibleTeamPinned} />
- )}
- {teamOverflow && (
- // Subordinate to the team pins above, so it reads lighter and
- // smaller than an agent row instead of competing with them.
- <NavItem
- data-testid={'sidebar-team-pinned-toggle'}
- icon={teamExpanded ? ChevronUp : ChevronDown}
- iconSize={14}
- titleColor={cssVar.colorTextDescription}
- title={
- <span style={{ fontSize: 12 }}>
- {teamExpanded
- ? t('navPanel.showLessTeamPinned')
- : t('navPanel.showMoreTeamPinned', {
- count: teamPinned.length - TEAM_PINNED_VISIBLE_LIMIT,
- })}
- </span>
- }
- onClick={() => setTeamExpanded((expanded) => !expanded)}
- />
- )}
+ {pinned.length > 0 && (
+ <Flexbox data-testid={'sidebar-pinned'} gap={1}>
+ <SortableList dataSource={pinned} onReorder={reorderMyPinned} />
</Flexbox>
)}
{folders.length > 0 && <Group dataSource={folders} />}
diff --git a/src/features/HomeSidebar/Body/Agent/List/index.tsx b/src/features/HomeSidebar/Body/Agent/List/index.tsx
index 4ea3c3db7ba..aba2ef54e98 100644
--- a/src/features/HomeSidebar/Body/Agent/List/index.tsx
+++ b/src/features/HomeSidebar/Body/Agent/List/index.tsx
@@ -16,7 +16,7 @@ const AgentList = memo<{ onMoreClick?: () => void }>(({ onMoreClick }) => {
s.closeAllAgentsDrawer,
]);
// A workspace merges shared and private rows into one Agents section with
- // team / personal pin groups; personal mode keeps the original layout.
+ // the member's own pinned list; personal mode keeps the original layout.
const activeWorkspaceId = useActiveWorkspaceId();
return (
diff --git a/src/features/HomeSidebar/Body/Agent/List/useWorkspaceAgentSections.ts b/src/features/HomeSidebar/Body/Agent/List/useWorkspaceAgentSections.ts
index 7bfe44abf10..bac9261b349 100644
--- a/src/features/HomeSidebar/Body/Agent/List/useWorkspaceAgentSections.ts
+++ b/src/features/HomeSidebar/Body/Agent/List/useWorkspaceAgentSections.ts
@@ -17,7 +17,7 @@ import {
/**
* 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
+ * their explicit hides applied to every section. 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.
*/
@@ -29,6 +29,8 @@ export const useWorkspaceAgentSections = (): WorkspaceAgentSections => {
const ungrouped = useHomeStore(homeAgentListSelectors.ungroupedAgents, isEqual);
const privateUngrouped = useHomeStore(homeAgentListSelectors.privateUngroupedAgents, isEqual);
const myPinnedIds = useUserStore(workspaceUserSettingsSelectors.sidebarPinnedItemIds, isEqual);
+ const setupPreview = useUserStore(workspaceUserSettingsSelectors.sidebarSetupPreview);
+ const recommendedIds = useHomeStore(homeAgentListSelectors.recommendedAgentIds, isEqual);
const visibilityOverrides = useUserStore(
workspaceUserSettingsSelectors.sidebarAgentVisibilityOverrides,
isEqual,
@@ -47,20 +49,19 @@ export const useWorkspaceAgentSections = (): WorkspaceAgentSections => {
privateGroups,
privatePinned,
privateUngrouped,
+ recommendedIds,
+ setupPreview,
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),
+ pinned: keep(resolved.pinned),
rest: keep(resolved.rest),
- teamPinned: resolved.teamPinned,
};
}, [
currentUserId,
@@ -72,14 +73,14 @@ export const useWorkspaceAgentSections = (): WorkspaceAgentSections => {
privateGroups,
privatePinned,
privateUngrouped,
+ recommendedIds,
+ setupPreview,
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>;
}
@@ -95,15 +96,12 @@ export const useWorkspaceSidebarItemIds = (): WorkspaceSidebarItemIds | null =>
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.pinned);
add(sections.rest);
for (const folder of sections.folders) add(folder.items);
- return { fixed, listed: ids };
+ return { 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
index 9f8bbe506d4..7cb42621db5 100644
--- a/src/features/HomeSidebar/Body/Agent/List/workspaceAgentSections.test.ts
+++ b/src/features/HomeSidebar/Body/Agent/List/workspaceAgentSections.test.ts
@@ -86,7 +86,7 @@ describe('isListedInWorkspaceSidebar', () => {
});
describe('resolveWorkspaceAgentSections', () => {
- it('puts team pins, my pins, private folders and the rest in that order of sections', () => {
+ it('lists pinned rows, 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')])],
@@ -103,24 +103,22 @@ describe('resolveWorkspaceAgentSections', () => {
],
});
- 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']);
+ // One pinned list: preference order, then private column pins. A default
+ // pin the member's list does not hold is not pinned for them.
+ expect(ids(sections.pinned)).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', () => {
+ it('keeps a private row pinned through its own column by earlier clients', () => {
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']);
+ expect(ids(sections.pinned)).toEqual(['old-private-pin']);
});
it('moves public folders off the sidebar but keeps the member’s own and added rows', () => {
@@ -153,22 +151,11 @@ describe('resolveWorkspaceAgentSections', () => {
ungrouped: [item('c', 'public', '2026-01-01'), item('d', 'public', '2026-01-01', mine)],
});
- expect(ids(sections.myPinned)).toEqual(['a', 'c']);
+ expect(ids(sections.pinned)).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,
@@ -176,7 +163,7 @@ describe('resolveWorkspaceAgentSections', () => {
ungrouped: [item('kept', 'public', '2026-01-01')],
});
- expect(ids(sections.myPinned)).toEqual(['kept']);
+ expect(ids(sections.pinned)).toEqual(['kept']);
});
it('dedupes a private pin recorded both in the preference and on the column', () => {
@@ -187,7 +174,83 @@ describe('resolveWorkspaceAgentSections', () => {
privatePinned: [pinnedPrivate],
});
- expect(ids(sections.myPinned)).toEqual(['p']);
+ expect(ids(sections.pinned)).toEqual(['p']);
+ });
+
+ describe('team pins and recommended Agents', () => {
+ const team = [
+ item('t1', 'public', '2026-01-01', { pinned: true }),
+ item('t2', 'public', '2026-01-02', { pinned: true }),
+ ];
+ const ungrouped = [
+ item('m1', 'public', '2026-01-03', mine),
+ item('r1', 'public', '2026-01-04'),
+ ];
+
+ it('pins team pins only through the member’s own list, in the member’s order', () => {
+ const sections = resolveWorkspaceAgentSections({
+ ...base,
+ myPinnedIds: ['t2', 'm1', 't1'],
+ pinned: team,
+ ungrouped,
+ });
+
+ expect(ids(sections.pinned)).toEqual(['t2', 'm1', 't1']);
+ expect(ids(sections.rest)).toEqual([]);
+ });
+
+ it('shows the team pins after the member’s own while the server is about to copy them in', () => {
+ const sections = resolveWorkspaceAgentSections({
+ ...base,
+ myPinnedIds: ['m1', 't2'],
+ pinned: team,
+ setupPreview: 'teamPins',
+ ungrouped,
+ });
+
+ // Where the server appends them, so nothing moves when it lands.
+ expect(ids(sections.pinned)).toEqual(['m1', 't2', 't1']);
+ });
+
+ it('lists a new member’s recommended Agents, unpinned, before the server set them up', () => {
+ const sections = resolveWorkspaceAgentSections({
+ ...base,
+ pinned: team,
+ recommendedIds: ['r1', 't1'],
+ setupPreview: 'recommended',
+ ungrouped,
+ });
+
+ expect(sections.pinned).toEqual([]);
+ expect(ids(sections.rest)).toEqual(['r1', 'm1', 't1']);
+ });
+
+ it('ignores the recommended list once the member’s sidebar is set up', () => {
+ const sections = resolveWorkspaceAgentSections({
+ ...base,
+ pinned: team,
+ recommendedIds: ['r1', 't1'],
+ ungrouped,
+ // Set up earlier with r1 only; t1 was recommended later.
+ visibilityOverrides: { r1: true },
+ });
+
+ expect(ids(sections.rest)).toEqual(['r1', 'm1']);
+ });
+
+ it('lists a team pin the member unpinned in the rest while they keep it', () => {
+ const sections = resolveWorkspaceAgentSections({
+ ...base,
+ myPinnedIds: ['m1', 't2'],
+ pinned: team,
+ ungrouped,
+ // Unpinning records the row as added to the member's sidebar.
+ visibilityOverrides: { t1: true },
+ });
+
+ expect(ids(sections.pinned)).toEqual(['m1', 't2']);
+ expect(ids(sections.rest)).toEqual(['t1']);
+ });
});
});
diff --git a/src/features/HomeSidebar/Body/Agent/List/workspaceAgentSections.ts b/src/features/HomeSidebar/Body/Agent/List/workspaceAgentSections.ts
index 1e9b11323b0..8666c48413b 100644
--- a/src/features/HomeSidebar/Body/Agent/List/workspaceAgentSections.ts
+++ b/src/features/HomeSidebar/Body/Agent/List/workspaceAgentSections.ts
@@ -11,9 +11,13 @@ export interface WorkspaceSidebarMembership {
export interface WorkspaceAgentSectionsInput extends WorkspaceSidebarMembership {
/** Public folders. */
groups: SidebarGroup[];
- /** Ids the member pinned for themselves (agents, chat groups, folders), newest first. */
+ /** The member's pinned ids (agents, chat groups) in their own order. */
myPinnedIds: readonly string[];
- /** Public rows whose shared `pinned` column is set — the team pins. */
+ /**
+ * Public rows whose shared `pinned` column is set — legacy team pins. The
+ * server lists them in their own bucket, so they are only looked up here;
+ * the column does not pin them for this member.
+ */
pinned: SidebarAgentItem[];
/** The member's private folders. */
privateGroups: SidebarGroup[];
@@ -21,22 +25,28 @@ export interface WorkspaceAgentSectionsInput extends WorkspaceSidebarMembership
privatePinned: SidebarAgentItem[];
/** The member's private rows outside any folder. */
privateUngrouped: SidebarAgentItem[];
+ /** The workspace's recommended Agents / chat groups. */
+ recommendedIds?: readonly string[];
+ /**
+ * How the server will set this member's sidebar up, while it has not yet
+ * (see `workspaceUserSettingsSelectors.sidebarSetupPreview`). The sidebar
+ * already shows the result, so nothing jumps when it lands.
+ */
+ setupPreview?: 'recommended' | 'teamPins' | null;
/** Public rows outside any folder. */
ungrouped: SidebarAgentItem[];
}
export interface WorkspaceAgentSections {
- /** The member's private folders; my-pinned rows taken out. */
+ /** The member's private folders; pinned rows taken out. */
folders: SidebarGroup[];
- /** The member's own pinned rows, in their pin order. */
- myPinned: SidebarAgentItem[];
+ /** The member's pinned rows in their own order. */
+ pinned: 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;
@@ -79,16 +89,18 @@ export const isListedInWorkspaceSidebar = (
* 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
+ * 1. Pinned — the member's own list: ids in `myPinnedIds` that are still
+ * available, in that order (dangling ids are skipped), then the member's
+ * private rows pinned through their own column by earlier clients. Legacy
+ * team pins only reach it through `myPinnedIds` (copied once, server
+ * side); see `setupPreview` for the moment before.
+ * 2. 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, Lobe AI
- * first, then newest first.
+ * 3. The rest — rows outside the private folders (including rows inside a
+ * public folder or the team-pin bucket) that
+ * {@link isListedInWorkspaceSidebar} keeps, Lobe AI first, then newest
+ * first. A new member's recommended Agents land here (unpinned) once their
+ * sidebar is set up.
*
* Every row appears at most once.
*/
@@ -96,52 +108,60 @@ export const resolveWorkspaceAgentSections = ({
currentUserId,
groups,
myPinnedIds,
- pinned,
+ pinned: teamPinned,
privateGroups,
privatePinned,
privateUngrouped,
+ recommendedIds = [],
+ setupPreview = null,
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 [
+ ...teamPinned,
...privatePinned,
- ...groups.flatMap((group) => group.items),
+ ...publicFolderItems,
...privateGroups.flatMap((group) => group.items),
...ungrouped,
...privateUngrouped,
]) {
- if (!teamIds.has(item.id) && !candidates.has(item.id)) candidates.set(item.id, item);
+ if (!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);
+ const pinned: SidebarAgentItem[] = [];
+ const pinnedIds = new Set<string>();
+ const addPinned = (item: SidebarAgentItem | undefined) => {
+ if (!item || pinnedIds.has(item.id)) return;
+ pinnedIds.add(item.id);
+ pinned.push(item);
};
- for (const id of myPinnedIds) addMine(candidates.get(id));
+ for (const id of myPinnedIds) addPinned(candidates.get(id));
+ if (setupPreview === 'teamPins') for (const item of teamPinned) addPinned(item);
for (const item of [...privatePinned].sort((a, b) => updatedAtMs(b) - updatedAtMs(a))) {
- addMine(item);
+ addPinned(item);
}
- const notPinned = (item: SidebarAgentItem) => !myIds.has(item.id) && !teamIds.has(item.id);
+ const notPinned = (item: SidebarAgentItem) => !pinnedIds.has(item.id);
const folders = privateGroups.map((group) => ({
...group,
items: group.items.filter(notPinned),
}));
- const membership = { currentUserId, visibilityOverrides };
- const rest = [...ungrouped, ...privateUngrouped, ...publicFolderItems]
+ const membership = {
+ currentUserId,
+ visibilityOverrides:
+ setupPreview === 'recommended'
+ ? { ...Object.fromEntries(recommendedIds.map((id) => [id, true])), ...visibilityOverrides }
+ : visibilityOverrides,
+ };
+ // The server puts each row in exactly one bucket, so no dedupe is needed.
+ const rest = [...teamPinned, ...ungrouped, ...privateUngrouped, ...publicFolderItems]
.filter((item) => notPinned(item) && isListedInWorkspaceSidebar(item, membership))
.sort(byInboxThenRecency);
- return { folders, myPinned, rest, teamPinned };
+ return { folders, pinned, rest };
};
diff --git a/src/features/HomeSidebar/Body/Agent/useSidebarPinMenuItems.tsx b/src/features/HomeSidebar/Body/Agent/useSidebarPinMenuItems.tsx
index 6f051ab26a6..741b867f0e3 100644
--- a/src/features/HomeSidebar/Body/Agent/useSidebarPinMenuItems.tsx
+++ b/src/features/HomeSidebar/Body/Agent/useSidebarPinMenuItems.tsx
@@ -2,12 +2,13 @@
import type { SidebarVisibility } from '@lobechat/types';
import { type DropdownItem, Icon, toast } from '@lobehub/ui';
-import { Pin, PinOff, UsersIcon } from 'lucide-react';
+import { Pin, PinOff, Star, StarOff } from 'lucide-react';
import { useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { usePermission } from '@/hooks/usePermission';
import { useHomeStore } from '@/store/home';
+import { homeAgentListSelectors } from '@/store/home/selectors';
import { useSidebarPinState } from './useSidebarPinState';
@@ -23,15 +24,17 @@ const isForbidden = (error: unknown) =>
(error as { data?: { code?: string } } | undefined)?.data?.code === 'FORBIDDEN';
/**
- * Workspace pin entries for an Agent / chat group row menu:
+ * Workspace entries for an Agent / chat group row menu (sidebar and Agents
+ * page):
*
- * - "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.
+ * - "Pin" / "Unpin" — the member's own pin list, available to every role and
+ * on every row.
+ * - "Add to recommended agents" / "Remove from recommended agents" — the
+ * workspace's recommended list every member sees on the Agents page and new
+ * members start with in their sidebar (unpinned). It never changes a member
+ * already set up. 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.
*/
@@ -42,25 +45,20 @@ export const useSidebarPinMenuItems = ({
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) => [
+ const { isMyPinned, isPrivate, isWorkspace } = useSidebarPinState({ id, pinned, visibility });
+ const { allowed: canManageRecommended } = usePermission('manage_settings');
+ const [pinItemForMe, updateRecommendedAgents] = useHomeStore((s) => [
s.pinItemForMe,
- s.pinAgent,
- s.pinAgentGroup,
+ s.updateRecommendedAgents,
]);
+ const recommendedIds = useHomeStore(homeAgentListSelectors.recommendedAgentIds);
+ const isRecommended = recommendedIds.includes(id);
const menuItems = useMemo<DropdownItem[]>(() => {
if (!isWorkspace) return [];
- const items: DropdownItem[] = [];
-
- if (!isTeamPinned || isMyPinned) {
- items.push({
+ const items: DropdownItem[] = [
+ {
icon: <Icon icon={isMyPinned ? PinOff : Pin} />,
key: 'pin',
label: t(isMyPinned ? 'pinOff' : 'pin'),
@@ -72,21 +70,26 @@ export const useSidebarPinMenuItems = ({
toast.error(t('operationFailed', { ns: 'common' }));
}
},
- } as DropdownItem);
- }
+ } as DropdownItem,
+ ];
- if (canManageTeamPins && !isPrivate) {
+ if (canManageRecommended && !isPrivate) {
items.push({
- icon: <Icon icon={isTeamPinned ? PinOff : UsersIcon} />,
- key: 'pinForTeam',
- label: t(isTeamPinned ? 'unpinForTeam' : 'pinForTeam'),
+ icon: <Icon icon={isRecommended ? StarOff : Star} />,
+ key: 'recommend',
+ label: t(isRecommended ? 'unrecommendAgent' : 'recommendAgent'),
onClick: async () => {
try {
- await (type === 'group' ? pinAgentGroup : pinAgent)(id, !isTeamPinned);
+ await updateRecommendedAgents(
+ isRecommended
+ ? recommendedIds.filter((itemId) => itemId !== id)
+ : [...recommendedIds, id],
+ );
+ toast.success(t(isRecommended ? 'unrecommendAgentSuccess' : 'recommendAgentSuccess'));
} catch (error) {
- console.error('Failed to update team pin:', error);
+ console.error('Failed to update recommended agents:', error);
toast.error(
- t(isForbidden(error) ? 'pinForTeamForbidden' : 'operationFailed', {
+ t(isForbidden(error) ? 'recommendAgentForbidden' : 'operationFailed', {
ns: isForbidden(error) ? 'chat' : 'common',
}),
);
@@ -97,20 +100,20 @@ export const useSidebarPinMenuItems = ({
return items;
}, [
- canManageTeamPins,
+ canManageRecommended,
id,
isMyPinned,
isPrivate,
- isTeamPinned,
+ isRecommended,
isWorkspace,
- pinAgent,
- pinAgentGroup,
pinItemForMe,
pinned,
+ recommendedIds,
t,
type,
+ updateRecommendedAgents,
visibility,
]);
- return { isMyPinned, isTeamPinned, menuItems };
+ return { menuItems };
};
diff --git a/src/features/HomeSidebar/Body/Agent/useSidebarPinState.test.ts b/src/features/HomeSidebar/Body/Agent/useSidebarPinState.test.ts
index b38a226363f..4cb020b1e4e 100644
--- a/src/features/HomeSidebar/Body/Agent/useSidebarPinState.test.ts
+++ b/src/features/HomeSidebar/Body/Agent/useSidebarPinState.test.ts
@@ -3,36 +3,45 @@ 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', () => {
+ it('personal mode: the column is the user own pin', () => {
expect(
resolveSidebarPinState(
{ id: 'a', pinned: true, visibility: 'public' },
{ isWorkspace: false, myPinnedIds: [] },
),
- ).toEqual({ isMyPinned: true, isPrivate: false, isTeamPinned: false, isWorkspace: false });
+ ).toEqual({ isMyPinned: true, isPrivate: false, isWorkspace: false });
});
- it('workspace public row: the column is the team pin, the preference is mine', () => {
+ it('workspace public row: a legacy team pin pins nothing, the preference is mine', () => {
expect(
resolveSidebarPinState(
{ id: 'a', pinned: true, visibility: 'public' },
{ isWorkspace: true, myPinnedIds: [] },
),
- ).toMatchObject({ isMyPinned: false, isTeamPinned: true });
+ ).toMatchObject({ isMyPinned: false });
expect(
resolveSidebarPinState(
{ id: 'a', pinned: false, visibility: 'public' },
{ isWorkspace: true, myPinnedIds: ['a'] },
),
- ).toMatchObject({ isMyPinned: true, isTeamPinned: false });
+ ).toMatchObject({ isMyPinned: true });
});
- it('workspace private row: its column is the creator own pin, never a team pin', () => {
+ it('workspace private row: its column is the creator own pin', () => {
expect(
resolveSidebarPinState(
{ id: 'p', pinned: true, visibility: 'private' },
{ isWorkspace: true, myPinnedIds: [] },
),
- ).toEqual({ isMyPinned: true, isPrivate: true, isTeamPinned: false, isWorkspace: true });
+ ).toEqual({ isMyPinned: true, isPrivate: true, isWorkspace: true });
+ });
+
+ it('workspace public row: a team pin counts as mine while the server is about to copy it in', () => {
+ expect(
+ resolveSidebarPinState(
+ { id: 'a', pinned: true, visibility: 'public' },
+ { isWorkspace: true, myPinnedIds: [], previewTeamPins: true },
+ ),
+ ).toMatchObject({ isMyPinned: true });
});
});
diff --git a/src/features/HomeSidebar/Body/Agent/useSidebarPinState.ts b/src/features/HomeSidebar/Body/Agent/useSidebarPinState.ts
index 98b5ab31ac8..8711a014c27 100644
--- a/src/features/HomeSidebar/Body/Agent/useSidebarPinState.ts
+++ b/src/features/HomeSidebar/Body/Agent/useSidebarPinState.ts
@@ -14,9 +14,12 @@ interface SidebarPinStateInput {
}
export interface SidebarPinState {
+ /**
+ * Pinned in the member's own sidebar (`sidebarPinnedItemIds`, or a private
+ * row's own column). In personal mode, the row's column.
+ */
isMyPinned: boolean;
isPrivate: boolean;
- isTeamPinned: boolean;
isWorkspace: boolean;
}
@@ -24,22 +27,27 @@ export interface SidebarPinState {
* 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, public row: the column is a legacy team pin and pins nothing
+ * by itself; the member's own pins live in `sidebarPinnedItemIds`. While
+ * the server is about to copy the team pins in (`previewTeamPins`), a team
+ * pin already counts as the member's, as it will.
* - 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[] },
+ {
+ isWorkspace,
+ myPinnedIds,
+ previewTeamPins = false,
+ }: { isWorkspace: boolean; myPinnedIds: readonly string[]; previewTeamPins?: boolean },
): SidebarPinState => {
const isPrivate = isWorkspace && visibility === 'private';
- if (!isWorkspace) return { isMyPinned: !!pinned, isPrivate, isTeamPinned: false, isWorkspace };
+ if (!isWorkspace) return { isMyPinned: !!pinned, isPrivate, isWorkspace };
return {
- isMyPinned: myPinnedIds.includes(id) || (isPrivate && !!pinned),
+ isMyPinned: myPinnedIds.includes(id) || (!!pinned && (isPrivate || previewTeamPins)),
isPrivate,
- isTeamPinned: !isPrivate && !!pinned,
isWorkspace,
};
};
@@ -47,6 +55,9 @@ export const resolveSidebarPinState = (
export const useSidebarPinState = (input: SidebarPinStateInput): SidebarPinState => {
const isWorkspace = !!useActiveWorkspaceId();
const myPinnedIds = useUserStore(workspaceUserSettingsSelectors.sidebarPinnedItemIds);
+ const previewTeamPins = useUserStore(
+ (s) => workspaceUserSettingsSelectors.sidebarSetupPreview(s) === 'teamPins',
+ );
- return resolveSidebarPinState(input, { isWorkspace, myPinnedIds });
+ return resolveSidebarPinState(input, { isWorkspace, myPinnedIds, previewTeamPins });
};
diff --git a/src/services/home/index.ts b/src/services/home/index.ts
index 3e2679158c0..b737b9aaae3 100644
--- a/src/services/home/index.ts
+++ b/src/services/home/index.ts
@@ -41,6 +41,13 @@ export class HomeService {
await lambdaClient.home.updatePinnedOrder.mutate({ ids });
};
+ /**
+ * Replace the workspace's recommended Agents / chat groups (owner/admin only).
+ */
+ updateRecommendedAgents = async (ids: string[]): Promise<void> => {
+ await lambdaClient.home.updateRecommendedAgents.mutate({ ids });
+ };
+
/**
* Update an agent's session group
*/
diff --git a/src/store/global/initialState.ts b/src/store/global/initialState.ts
index 37f1e17afeb..1acc3f5cf7c 100644
--- a/src/store/global/initialState.ts
+++ b/src/store/global/initialState.ts
@@ -221,10 +221,22 @@ export interface SystemStatus {
*/
agentListExpandedGroupKeys?: string[];
/**
- * Whether the "in sidebar" overview section of the agent view-all page is
- * collapsed. Defaults to expanded so the section is discoverable.
+ * Whether the "Recommended agents" section of the agent view-all page is
+ * collapsed. Defaults to expanded: it is how members find what their
+ * workspace recommends.
+ */
+ agentListRecommendedSectionCollapsed?: boolean;
+ /**
+ * @deprecated Read and written by earlier builds only, whose default
+ * (expanded) was persisted for everyone; replaced by
+ * `agentListSidebarSectionExpanded` so the section starts collapsed.
*/
agentListSidebarSectionCollapsed?: boolean;
+ /**
+ * Whether the "in sidebar" overview section of the agent view-all page is
+ * expanded. Defaults to collapsed: the sidebar itself already shows it.
+ */
+ agentListSidebarSectionExpanded?: boolean;
/**
* View mode of the agent view-all page (badge-wall card grid vs table list); defaults to card
*/
@@ -655,7 +667,8 @@ export interface GlobalState {
export const INITIAL_STATUS = {
agentBuilderPanelWidth: 360,
agentListExpandedGroupKeys: [] as string[],
- agentListSidebarSectionCollapsed: false,
+ agentListRecommendedSectionCollapsed: false,
+ agentListSidebarSectionExpanded: false,
agentListViewMode: 'card' as const,
agentListViewOptions: {
orderBy: 'updatedAt' as const,
diff --git a/src/store/global/selectors/systemStatus.test.ts b/src/store/global/selectors/systemStatus.test.ts
index aac4d2fc8cb..e2b004f2ccb 100644
--- a/src/store/global/selectors/systemStatus.test.ts
+++ b/src/store/global/selectors/systemStatus.test.ts
@@ -21,6 +21,30 @@ import {
} from './systemStatus';
describe('systemStatusSelectors', () => {
+ describe('agent view-all sections', () => {
+ it('starts the "In sidebar" section collapsed, even over a persisted earlier default', () => {
+ expect(systemStatusSelectors.agentListSidebarSectionCollapsed(initialState)).toBe(true);
+ // Earlier builds persisted `agentListSidebarSectionCollapsed: false` for everyone.
+ const persisted: GlobalState = merge(initialState, {
+ status: { agentListSidebarSectionCollapsed: false },
+ });
+ expect(systemStatusSelectors.agentListSidebarSectionCollapsed(persisted)).toBe(true);
+
+ const expanded: GlobalState = merge(initialState, {
+ status: { agentListSidebarSectionExpanded: true },
+ });
+ expect(systemStatusSelectors.agentListSidebarSectionCollapsed(expanded)).toBe(false);
+ });
+
+ it('starts the "Recommended agents" section expanded and remembers a collapse', () => {
+ expect(systemStatusSelectors.agentListRecommendedSectionCollapsed(initialState)).toBe(false);
+ const collapsed: GlobalState = merge(initialState, {
+ status: { agentListRecommendedSectionCollapsed: true },
+ });
+ expect(systemStatusSelectors.agentListRecommendedSectionCollapsed(collapsed)).toBe(true);
+ });
+ });
+
describe('sessionGroupKeys', () => {
it('should return expandSessionGroupKeys from status', () => {
const s: GlobalState = merge(initialState, {
diff --git a/src/store/global/selectors/systemStatus.ts b/src/store/global/selectors/systemStatus.ts
index b0215a9b031..d8a199fdb2c 100644
--- a/src/store/global/selectors/systemStatus.ts
+++ b/src/store/global/selectors/systemStatus.ts
@@ -600,8 +600,10 @@ const agentDocumentSort = (s: GlobalState): AgentDocumentSort =>
s.status.agentDocumentSort ?? DEFAULT_AGENT_DOCUMENT_SORT;
const agentListViewOptions = (s: GlobalState) => s.status.agentListViewOptions;
const agentListExpandedGroupKeys = (s: GlobalState) => s.status.agentListExpandedGroupKeys ?? [];
+const agentListRecommendedSectionCollapsed = (s: GlobalState) =>
+ s.status.agentListRecommendedSectionCollapsed ?? false;
const agentListSidebarSectionCollapsed = (s: GlobalState) =>
- s.status.agentListSidebarSectionCollapsed ?? false;
+ !s.status.agentListSidebarSectionExpanded;
const imageTopicViewMode = (s: GlobalState) => s.status.imageTopicViewMode || 'grid';
const imageTopicPanelWidth = (s: GlobalState) => s.status.imageTopicPanelWidth;
const musicTopicViewMode = (s: GlobalState) => s.status.musicTopicViewMode || 'list';
@@ -656,6 +658,7 @@ export const systemStatusSelectors = {
projectListSortBy,
projectListViewMode,
agentListExpandedGroupKeys,
+ agentListRecommendedSectionCollapsed,
agentListSidebarSectionCollapsed,
agentListViewMode,
agentListViewOptions,
diff --git a/src/store/home/slices/agentList/action.test.ts b/src/store/home/slices/agentList/action.test.ts
index b9691c7556c..9a74425835c 100644
--- a/src/store/home/slices/agentList/action.test.ts
+++ b/src/store/home/slices/agentList/action.test.ts
@@ -155,6 +155,58 @@ describe('sidebar agent list replica', () => {
});
});
+describe('updateRecommendedAgents', () => {
+ it('shows the new list right away, drops unknown rows, and rolls back on failure', async () => {
+ vi.spyOn(homeService, 'getSidebarAgentList').mockResolvedValue(
+ response({ recommendedIds: ['a'], ungrouped: [agent('a'), agent('b')] }),
+ );
+ sync();
+ await waitFor(() => expect(useHomeStore.getState().recommendedAgentIds).toEqual(['a']));
+
+ let reject!: (error: Error) => void;
+ const save = vi
+ .spyOn(homeService, 'updateRecommendedAgents')
+ .mockImplementation(() => new Promise<void>((_, fail) => (reject = fail)));
+
+ // `gone` was deleted (or made private) since it was recommended.
+ const update = useHomeStore.getState().updateRecommendedAgents(['b', 'gone', 'a']);
+ expect(useHomeStore.getState().recommendedAgentIds).toEqual(['b', 'a']);
+ await waitFor(() => expect(save).toHaveBeenCalledWith(['b', 'a']));
+
+ reject(new Error('boom'));
+ await expect(update).rejects.toThrow('boom');
+ expect(useHomeStore.getState().recommendedAgentIds).toEqual(['a']);
+ });
+});
+
+describe('updateRecommendedAgents ordering', () => {
+ it('saves quick successive changes one after another, in order', async () => {
+ vi.spyOn(homeService, 'getSidebarAgentList').mockResolvedValue(
+ response({ recommendedIds: ['a', 'b'], ungrouped: [agent('a'), agent('b')] }),
+ );
+ sync();
+ await waitFor(() => expect(useHomeStore.getState().recommendedAgentIds).toEqual(['a', 'b']));
+
+ const pending: Array<() => void> = [];
+ const save = vi
+ .spyOn(homeService, 'updateRecommendedAgents')
+ .mockImplementation(() => new Promise<void>((resolve) => pending.push(resolve)));
+
+ const first = useHomeStore.getState().updateRecommendedAgents(['b', 'a']);
+ const second = useHomeStore.getState().updateRecommendedAgents(['a', 'b']);
+ await waitFor(() => expect(save).toHaveBeenCalledTimes(1));
+ // The second save waits for the first instead of racing it.
+ expect(save).toHaveBeenLastCalledWith(['b', 'a']);
+
+ pending[0]();
+ await waitFor(() => expect(save).toHaveBeenCalledTimes(2));
+ expect(save).toHaveBeenLastCalledWith(['a', 'b']);
+ pending[1]();
+ await act(() => Promise.all([first, second]));
+ expect(useHomeStore.getState().recommendedAgentIds).toEqual(['a', 'b']);
+ });
+});
+
describe('reorderPinnedAgents across a scope change', () => {
it.each([
['another workspace', (from: string) => from.replace(/:[^:]*$/, ':ws-2')],
diff --git a/src/store/home/slices/agentList/action.ts b/src/store/home/slices/agentList/action.ts
index 36a09a2c987..44df51eec43 100644
--- a/src/store/home/slices/agentList/action.ts
+++ b/src/store/home/slices/agentList/action.ts
@@ -106,13 +106,16 @@ class ScopeChangedError extends Error {}
export class AgentListActionImpl {
readonly #set: Setter;
+ readonly #get: () => HomeStore;
readonly #agentList;
readonly #agents;
#pinnedOrderQueue: Promise<unknown> = Promise.resolve();
+ #recommendedQueue: Promise<unknown> = Promise.resolve();
constructor(set: Setter, get: () => HomeStore, _api?: unknown) {
void _api;
this.#set = set;
+ this.#get = get;
this.#agentList = createReplicaSlice(agentListResource, {
actionPrefix: n('agentList'),
entity: sidebarAgentEntity,
@@ -188,6 +191,48 @@ export class AgentListActionImpl {
}
};
+ /**
+ * Replace the workspace's recommended Agents (owner/admin only): the Agents
+ * page updates now and rolls back if the save fails.
+ */
+ updateRecommendedAgents = async (ids: string[]): Promise<void> => {
+ // Only public rows can be recommended: drop ids of rows deleted or made
+ // private since, so they never count toward the list's cap.
+ const state = this.#get();
+ const available = new Set(
+ [
+ ...state.pinnedAgents,
+ ...state.ungroupedAgents,
+ ...state.agentGroups.flatMap((group) => group.items),
+ ].map((item) => item.id),
+ );
+ const next = ids.filter((id) => available.has(id));
+
+ // Each save replaces the whole list, so saves run one after another: two
+ // quick drags reach the server in the order they were made. A save still
+ // queued when the cache scope changes is dropped (see reorderPinnedAgents).
+ const scope = cacheScope.get();
+ try {
+ await this.#agentList.optimistic(
+ AGENT_LIST_KEY,
+ (data) => (data ? { ...data, recommendedIds: next } : data),
+ () => {
+ const operation = this.#recommendedQueue
+ .catch(() => undefined)
+ .then(async () => {
+ if (cacheScope.get() !== scope) throw new ScopeChangedError();
+ await homeService.updateRecommendedAgents(next);
+ });
+ this.#recommendedQueue = operation;
+ return operation;
+ },
+ );
+ } catch (error) {
+ if (error instanceof ScopeChangedError) return;
+ throw error;
+ }
+ };
+
/** Fetch orchestration only; read the list through `homeAgentListSelectors`. */
useFetchAgentList = (isLogin: boolean | undefined): ReplicaSyncResult =>
this.#agentList.useSync(LIST_PARAMS, { enabled: isLogin === true });
diff --git a/src/store/home/slices/agentList/initialState.ts b/src/store/home/slices/agentList/initialState.ts
index 5ffeb03e644..d0e7380931d 100644
--- a/src/store/home/slices/agentList/initialState.ts
+++ b/src/store/home/slices/agentList/initialState.ts
@@ -47,6 +47,12 @@ export interface AgentListState {
* the workspace. Always empty in personal mode.
*/
privateUngroupedAgents: SidebarAgentItem[];
+ /**
+ * Workspace-only: ids of the Agents / chat groups owners and admins
+ * recommend to every member, in their order. Absent in personal mode (and
+ * kept absent, so the list round-trips unchanged through the replica).
+ */
+ recommendedAgentIds?: string[];
/**
* Ungrouped agents and chat groups
*/
@@ -75,6 +81,7 @@ export const mapResponseToState = (
| 'privateAgentGroups'
| 'privatePinnedAgents'
| 'privateUngroupedAgents'
+ | 'recommendedAgentIds'
| 'ungroupedAgents'
> => ({
agentGroups: response.groups,
@@ -82,6 +89,7 @@ export const mapResponseToState = (
privateAgentGroups: response.privateGroups ?? [],
privatePinnedAgents: response.privatePinned ?? [],
privateUngroupedAgents: response.privateUngrouped ?? [],
+ recommendedAgentIds: response.recommendedIds,
ungroupedAgents: response.ungrouped,
});
@@ -92,5 +100,6 @@ export const mapStateToResponse = (state: AgentListState): SidebarAgentListRespo
privateGroups: state.privateAgentGroups,
privatePinned: state.privatePinnedAgents,
privateUngrouped: state.privateUngroupedAgents,
+ ...(state.recommendedAgentIds ? { recommendedIds: state.recommendedAgentIds } : {}),
ungrouped: state.ungroupedAgents,
});
diff --git a/src/store/home/slices/agentList/selectors.ts b/src/store/home/slices/agentList/selectors.ts
index e620af25d77..a5103b44b71 100644
--- a/src/store/home/slices/agentList/selectors.ts
+++ b/src/store/home/slices/agentList/selectors.ts
@@ -10,6 +10,13 @@ import { AGENT_LIST_KEY } from './projection';
*/
const pinnedAgents = (s: HomeStore): SidebarAgentItem[] => s.pinnedAgents;
+/**
+ * Ids of the Agents / chat groups recommended to every workspace member, in
+ * the owners'/admins' order. Empty in personal mode.
+ */
+const EMPTY_IDS: string[] = [];
+const recommendedAgentIds = (s: HomeStore): string[] => s.recommendedAgentIds ?? EMPTY_IDS;
+
/**
* Get all agent groups (folders)
*/
@@ -154,6 +161,7 @@ export const homeAgentListSelectors = {
privateUngroupedAgents,
privateUngroupedAgentsCount,
privateUngroupedAgentsLimited,
+ recommendedAgentIds,
sharedAgents,
ungroupedAgents,
ungroupedAgentsCount,
diff --git a/src/store/home/slices/sidebarUI/action.pinItemForMe.test.ts b/src/store/home/slices/sidebarUI/action.pinItemForMe.test.ts
index 14f09ab835e..5da8c94a3f9 100644
--- a/src/store/home/slices/sidebarUI/action.pinItemForMe.test.ts
+++ b/src/store/home/slices/sidebarUI/action.pinItemForMe.test.ts
@@ -12,13 +12,17 @@ vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({
}));
const updatePreference = vi.fn();
+const refreshPreference = vi.fn();
beforeEach(() => {
updatePreference.mockReset().mockResolvedValue(undefined);
+ refreshPreference.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);
+ useHomeStore.setState({ pinnedAgents: [] } as any);
useUserStore.setState({
+ refreshWorkspaceUserPreference: refreshPreference,
updateWorkspaceUserPreference: updatePreference,
workspaceUserPreference: { sidebarPinnedItemIds: ['older'] },
} as any);
@@ -36,20 +40,69 @@ describe('pinItemForMe', () => {
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.
+ // The shared column is the default pin for new members — a member's pin must not touch it.
expect(agentService.updateAgentPinned).not.toHaveBeenCalled();
});
- it('unpins a public agent from the member preference only', async () => {
+ it('unpins a public agent from the member preference only, keeping it listed', 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.
+ // A default pin seeded into the member's list moves down instead of
+ // leaving the sidebar, and the default itself is left alone.
+ expect(updatePreference).toHaveBeenCalledWith({
+ sidebarAgentVisibilityOverrides: { pub: true },
+ sidebarPinnedItemIds: ['older'],
+ });
expect(agentService.updateAgentPinned).not.toHaveBeenCalled();
});
+ it('waits for the server to set the sidebar up before a first pin', async () => {
+ useHomeStore.setState({ pinnedAgents: [{ id: 'team-1' }] } as any);
+ // The server answers with the team pins copied in after the member's own.
+ refreshPreference.mockImplementation(async () => {
+ useUserStore.setState({
+ workspaceUserPreference: {
+ sidebarInitialized: true,
+ sidebarPinnedItemIds: ['older', 'team-1'],
+ },
+ });
+ });
+
+ await pinForMe({ id: 'pub', pinned: false, type: 'agent', visibility: 'public' }, true);
+
+ expect(refreshPreference).toHaveBeenCalledTimes(1);
+ // Built on the server's answer; the client never sets the sidebar up itself.
+ expect(updatePreference).toHaveBeenCalledWith({
+ sidebarPinnedItemIds: ['pub', 'older', 'team-1'],
+ });
+ });
+
+ it('does not wait once the sidebar is set up', async () => {
+ useUserStore.setState({
+ workspaceUserPreference: { sidebarInitialized: true, sidebarPinnedItemIds: ['older'] },
+ });
+
+ await pinForMe({ id: 'pub', pinned: false, type: 'agent', visibility: 'public' }, true);
+
+ expect(refreshPreference).not.toHaveBeenCalled();
+ expect(updatePreference).toHaveBeenCalledWith({ sidebarPinnedItemIds: ['pub', 'older'] });
+ });
+
+ it('keeps an explicit sidebar choice when unpinning', async () => {
+ useUserStore.setState({
+ workspaceUserPreference: {
+ sidebarAgentVisibilityOverrides: { pub: false },
+ sidebarPinnedItemIds: ['pub'],
+ },
+ });
+
+ await pinForMe({ id: 'pub', pinned: false, type: 'agent', visibility: 'public' }, false);
+
+ expect(updatePreference).toHaveBeenCalledWith({ sidebarPinnedItemIds: [] });
+ });
+
it('keeps a private agent column in sync with its preference entry', async () => {
await pinForMe({ id: 'priv', pinned: false, type: 'agent', visibility: 'private' }, true);
diff --git a/src/store/home/slices/sidebarUI/action.reorderMyPinned.test.ts b/src/store/home/slices/sidebarUI/action.reorderMyPinned.test.ts
index 7f258c16a4e..ca316a2a13b 100644
--- a/src/store/home/slices/sidebarUI/action.reorderMyPinned.test.ts
+++ b/src/store/home/slices/sidebarUI/action.reorderMyPinned.test.ts
@@ -5,12 +5,19 @@ import { cacheScope } from '@/libs/replica';
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'),
+}));
+
let scope = 'user-a:ws-1';
const updatePreference = vi.fn();
+const refreshPreference = vi.fn();
const setPinned = (ids: string[]) =>
useUserStore.setState({
+ refreshWorkspaceUserPreference: refreshPreference,
updateWorkspaceUserPreference: updatePreference,
workspaceUserPreference: { sidebarPinnedItemIds: ids },
} as any);
@@ -21,6 +28,7 @@ beforeEach(() => {
scope = 'user-a:ws-1';
vi.spyOn(cacheScope, 'get').mockImplementation(() => scope);
updatePreference.mockReset().mockResolvedValue(undefined);
+ refreshPreference.mockReset().mockResolvedValue(undefined);
});
describe('reorderMyPinned', () => {
@@ -50,6 +58,33 @@ describe('reorderMyPinned', () => {
expect(updatePreference).toHaveBeenCalledWith({ sidebarPinnedItemIds: ['legacy', 'a'] });
});
+ it('keeps a pinned order longer than 200 rows, since it is seeded with every default pin', async () => {
+ const many = Array.from({ length: 250 }, (_, i) => `team-${i}`);
+ setPinned([]);
+
+ await reorder(many);
+
+ expect(updatePreference).toHaveBeenCalledWith({ sidebarPinnedItemIds: many });
+ });
+
+ it('never pins a team pin the sidebar only previewed as pinned', async () => {
+ useHomeStore.setState({ pinnedAgents: [{ id: 'team-1' }] } as any);
+ setPinned(['a', 'b']);
+ // The server answers that this (new) member gets no team pins.
+ refreshPreference.mockImplementation(async () => {
+ useUserStore.setState({
+ workspaceUserPreference: { sidebarInitialized: true, sidebarPinnedItemIds: ['a', 'b'] },
+ });
+ });
+
+ // The sidebar had guessed the team pin would follow the member's own.
+ await reorder(['b', 'team-1', 'a']);
+
+ expect(refreshPreference).toHaveBeenCalledTimes(1);
+ expect(updatePreference).toHaveBeenCalledWith({ sidebarPinnedItemIds: ['b', 'a'] });
+ useHomeStore.setState({ pinnedAgents: [] } as any);
+ });
+
it('skips the write when nothing moved', async () => {
setPinned(['a', 'b']);
diff --git a/src/store/home/slices/sidebarUI/action.ts b/src/store/home/slices/sidebarUI/action.ts
index 81ae306faeb..c1bc70119e4 100644
--- a/src/store/home/slices/sidebarUI/action.ts
+++ b/src/store/home/slices/sidebarUI/action.ts
@@ -1,3 +1,4 @@
+import type { WorkspaceUserPreference } from '@lobechat/types';
import { toast } from '@lobehub/ui';
import { t } from 'i18next';
@@ -11,13 +12,17 @@ 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 { workspaceUserSettingsSelectors } from '@/store/user/selectors';
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;
+/**
+ * Upper bound for one member's pin list (mirrors the server cap). It may hold
+ * every team pin, so this matches the team order cap (`MAX_PINNED_ORDER_ITEMS`).
+ */
+export const MAX_SIDEBAR_PINNED_ITEMS = 2000;
export interface PersonalPinTarget {
id: string;
@@ -27,6 +32,26 @@ export interface PersonalPinTarget {
visibility?: 'private' | 'public' | null;
}
+const isSameIds = (a: readonly string[], b: readonly string[]) =>
+ a.length === b.length && a.every((id, i) => id === b[i]);
+
+/**
+ * The caller's user store once the server has set their sidebar up. Pin
+ * writes replace the whole list, so one built from a cached preference the
+ * server has not answered yet could drop what the server is about to add —
+ * or, built from the sidebar's guess of the outcome
+ * (`workspaceUserSettingsSelectors.sidebarSetupPreview`), persist the wrong
+ * one. Such a write waits for that answer instead; the server sets the
+ * sidebar up in it.
+ */
+const getSettledUserStore = async () => {
+ const userStore = getUserStoreState();
+ if (workspaceUserSettingsSelectors.sidebarSetupPreview(userStore) === null) return userStore;
+
+ await userStore.refreshWorkspaceUserPreference();
+ return getUserStoreState();
+};
+
type Setter = StoreSetter<HomeStore>;
export const createSidebarUISlice = (set: Setter, get: () => HomeStore, _api?: unknown) =>
new SidebarUIActionImpl(set, get, _api);
@@ -36,6 +61,9 @@ export class SidebarUIActionImpl {
readonly #set: Setter;
#myPinnedQueue: Promise<unknown> = Promise.resolve();
+ /** The workspace's legacy team pins (public rows with the shared column), in team order. */
+ #teamPinnedIds = (): string[] => this.#get().pinnedAgents.map((item) => item.id);
+
constructor(set: Setter, get: () => HomeStore, _api?: unknown) {
void _api;
this.#set = set;
@@ -102,15 +130,21 @@ export class SidebarUIActionImpl {
/**
* 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.
+ * `sidebarPinnedItemIds` preference (a new pin goes first); the shared
+ * column on a public row is a legacy team pin and is left alone.
+ *
+ * - Unpinning keeps the row in the sidebar: a public row with no explicit
+ * choice yet (for example a team pin made by a teammate) is added to
+ * the member's list (`sidebarAgentVisibilityOverrides`), so it moves down
+ * instead of vanishing. Removing it stays a separate action.
+ * - 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 userStore = await getSettledUserStore();
+ const preference = userStore.workspaceUserPreference;
+ const current = preference.sidebarPinnedItemIds ?? [];
const isPrivate = item.visibility === 'private';
const writeColumn = (value: boolean) =>
item.type === 'group' ? this.pinAgentGroup(item.id, value) : this.pinAgent(item.id, value);
@@ -118,17 +152,22 @@ export class SidebarUIActionImpl {
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 });
- }
+ const patch: Partial<WorkspaceUserPreference> = {};
+ if (!isSameIds(nextIds, current)) patch.sidebarPinnedItemIds = nextIds;
+ if (
+ !pinned &&
+ !isPrivate &&
+ preference.sidebarAgentVisibilityOverrides?.[item.id] === undefined
+ )
+ patch.sidebarAgentVisibilityOverrides = { [item.id]: true };
+
+ if (Object.keys(patch).length > 0) await userStore.updateWorkspaceUserPreference(patch);
if (isPrivate && !!item.pinned !== pinned) await writeColumn(pinned);
};
/**
- * Reorder the member's own pins in the merged workspace Agents section.
+ * Reorder the member's pinned list in the merged workspace Agents section.
* `ids` is the new order of the rows the sidebar shows; ids in the stored
* list that are not shown right now (hidden or dangling) keep their place
* after them, so a reorder never unpins anything.
@@ -144,15 +183,19 @@ export class SidebarUIActionImpl {
.catch(() => undefined)
.then(async () => {
if (cacheScope.get() !== scope) return;
- const userStore = getUserStoreState();
+ const userStore = await getSettledUserStore();
+ if (cacheScope.get() !== scope) return;
const current = userStore.workspaceUserPreference.sidebarPinnedItemIds ?? [];
- const shown = new Set(ids);
- const nextIds = [...ids, ...current.filter((id) => !shown.has(id))].slice(
+ // A team pin is pinned only through the member's own list; one the
+ // sidebar merely previewed as pinned is not pinned by a drag.
+ const teamPinned = new Set(this.#teamPinnedIds());
+ const kept = ids.filter((id) => !teamPinned.has(id) || current.includes(id));
+ const shown = new Set(kept);
+ const nextIds = [...kept, ...current.filter((id) => !shown.has(id))].slice(
0,
MAX_SIDEBAR_PINNED_ITEMS,
);
- if (nextIds.length === current.length && nextIds.every((id, i) => id === current[i]))
- return;
+ if (isSameIds(nextIds, current)) return;
await userStore.updateWorkspaceUserPreference({ sidebarPinnedItemIds: nextIds });
});
diff --git a/src/store/user/slices/workspaceUserSettings/selectors.test.ts b/src/store/user/slices/workspaceUserSettings/selectors.test.ts
new file mode 100644
index 00000000000..8b917a55ba8
--- /dev/null
+++ b/src/store/user/slices/workspaceUserSettings/selectors.test.ts
@@ -0,0 +1,38 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import type { UserStore } from '@/store/user';
+
+import { workspaceUserSettingsSelectors } from './selectors';
+
+vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({
+ getActiveWorkspaceId: () => 'ws-1',
+}));
+
+const store = (preference: object, source?: 'server' | 'storage') =>
+ ({
+ workspaceUserPreference: preference,
+ workspaceUserPreferenceReplica: { entries: source ? { 'ws-1': { source } } : {} },
+ }) as unknown as UserStore;
+
+const { sidebarSetupPreview } = workspaceUserSettingsSelectors;
+
+describe('sidebarSetupPreview', () => {
+ it('previews the team pins for cached choices from an earlier visit', () => {
+ expect(sidebarSetupPreview(store({ sidebarPinnedItemIds: ['a'] }, 'storage'))).toBe('teamPins');
+ });
+
+ it('previews the recommended Agents for a member with nothing saved yet', () => {
+ expect(sidebarSetupPreview(store({}))).toBe('recommended');
+ });
+
+ it('previews nothing once the sidebar is set up', () => {
+ expect(sidebarSetupPreview(store({ sidebarInitialized: true }, 'storage'))).toBeNull();
+ });
+
+ it('previews nothing once the server answered without setting the sidebar up', () => {
+ // The server sets the sidebar up in that same answer whenever it can, so
+ // a guess from the preference's shape would only contradict it.
+ expect(sidebarSetupPreview(store({}, 'server'))).toBeNull();
+ expect(sidebarSetupPreview(store({ sidebarHiddenGroupIds: ['g'] }, 'server'))).toBeNull();
+ });
+});
diff --git a/src/store/user/slices/workspaceUserSettings/selectors.ts b/src/store/user/slices/workspaceUserSettings/selectors.ts
index 9d1a592f1e1..2761566de0a 100644
--- a/src/store/user/slices/workspaceUserSettings/selectors.ts
+++ b/src/store/user/slices/workspaceUserSettings/selectors.ts
@@ -1,5 +1,6 @@
import type { AgentDeviceOverride, AgentModelOverride } from '@lobechat/types';
+import { getActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
import { type UserStore } from '@/store/user';
/**
@@ -48,12 +49,40 @@ const isAgentHiddenFromSidebar =
!!s.workspaceUserPreference.sidebarHiddenAgentIds?.includes(agentId);
/**
- * Agents / chat groups the caller pinned for themselves in the active
- * workspace's merged Agents section, newest first.
+ * Agents / chat groups pinned in the caller's merged Agents section of the
+ * active workspace, in their own order (seeded from the workspace's default
+ * pins).
*/
const sidebarPinnedItemIds = (s: UserStore): string[] =>
s.workspaceUserPreference.sidebarPinnedItemIds ?? EMPTY_HIDDEN;
+/**
+ * How the server is about to set the caller's sidebar up from the workspace
+ * (`sidebarInitialized`), so the sidebar can show it before the first
+ * response arrives:
+ *
+ * - `teamPins` — saved choices from an earlier visit: a member who joined
+ * while team pins were shown, whose team pins will follow their own pins.
+ * - `recommended` — nothing saved: a new member, whose recommended Agents
+ * will be listed, unpinned.
+ * - `null` — already set up, or the server has answered: it sets the sidebar
+ * up in that same response whenever there is something to add, so an
+ * answer without the flag means there is nothing to preview.
+ *
+ * The server decides by join date; this guess only bridges the cached state
+ * shown before its answer.
+ */
+const sidebarSetupPreview = (s: UserStore): 'recommended' | 'teamPins' | null => {
+ const preference = s.workspaceUserPreference;
+ if (preference.sidebarInitialized) return null;
+
+ const workspaceId = getActiveWorkspaceId();
+ if (!workspaceId || s.workspaceUserPreferenceReplica.entries[workspaceId]?.source === 'server')
+ return null;
+
+ return Object.keys(preference).length > 0 ? 'teamPins' : 'recommended';
+};
+
/** Per-member sidebar sections layout for the active workspace. */
const sidebarLayout = (s: UserStore) => s.workspaceUserPreference.sidebar;
@@ -70,4 +99,5 @@ export const workspaceUserSettingsSelectors = {
sidebarHiddenGroupIds,
sidebarLayout,
sidebarPinnedItemIds,
+ sidebarSetupPreview,
};