Skip to content

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

πŸ› fix(home): make workspace sidebar pins per-member and honor hidden agents in more drawer (#17559)

Rdmclin280c704106f47
diff --git a/apps/server/src/routers/lambda/__tests__/agent.test.ts b/apps/server/src/routers/lambda/__tests__/agent.test.ts
index 6ea240fe044..a2c8a40cd85 100644
--- a/apps/server/src/routers/lambda/__tests__/agent.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/agent.test.ts
@@ -12,6 +12,7 @@ import { ResourcePermissionModel } from '@/database/models/resourcePermission';
import { SessionModel } from '@/database/models/session';
import { TaskModel } from '@/database/models/task';
import { UserModel } from '@/database/models/user';
+import { WorkspaceUserSettingsModel } from '@/database/models/workspaceUserSettings';
import { AgentService } from '@/server/services/agent';
import { EditLockService } from '@/server/services/editLock';
import { publishResourceEvent } from '@/server/services/resourceEvents';
@@ -67,6 +68,10 @@ vi.mock('@/database/models/resourcePermission', () => ({
ResourcePermissionModel: vi.fn(),
}));
+vi.mock('@/database/models/workspaceUserSettings', () => ({
+ WorkspaceUserSettingsModel: vi.fn(),
+}));
+
vi.mock('@/server/services/agent', () => ({
AgentService: vi.fn(),
}));
@@ -97,6 +102,7 @@ describe('agentRouter', () => {
let knowledgeBaseModelMock: any;
let agentServiceMock: any;
let resourcePermissionModelMock: any;
+ let workspaceUserSettingsModelMock: any;
beforeEach(() => {
vi.clearAllMocks();
@@ -112,6 +118,11 @@ describe('agentRouter', () => {
setAccessLevel: vi.fn(),
};
vi.mocked(ResourcePermissionModel).mockImplementation(() => resourcePermissionModelMock);
+ workspaceUserSettingsModelMock = {
+ copySidebarGroupAssignment: vi.fn(),
+ setSidebarGroupAssignment: vi.fn(),
+ };
+ vi.mocked(WorkspaceUserSettingsModel).mockImplementation(() => workspaceUserSettingsModelMock);
agentModelMock = {
createAgentFiles: vi.fn(),
@@ -484,6 +495,12 @@ describe('agentRouter', () => {
'use',
userId,
);
+ // Folder placement is per-member in workspace mode β€” the duplicate must
+ // inherit the caller's own assignment for the source agent.
+ expect(workspaceUserSettingsModelMock.copySidebarGroupAssignment).toHaveBeenCalledWith(
+ 'public-agent',
+ 'copied-agent',
+ );
});
});
diff --git a/apps/server/src/routers/lambda/agent.ts b/apps/server/src/routers/lambda/agent.ts
index 763ad55538a..69682df5811 100644
--- a/apps/server/src/routers/lambda/agent.ts
+++ b/apps/server/src/routers/lambda/agent.ts
@@ -15,6 +15,7 @@ import { ResourcePermissionModel } from '@/database/models/resourcePermission';
import { SessionModel } from '@/database/models/session';
import { TaskModel } from '@/database/models/task';
import { UserModel } from '@/database/models/user';
+import { WorkspaceUserSettingsModel } from '@/database/models/workspaceUserSettings';
import { DEFAULT_RESOURCE_ACCESS_LEVELS, RESOURCE_ACCESS_LEVELS_BY_TYPE } from '@/database/schemas';
import { router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
@@ -149,6 +150,17 @@ export const agentRouter = router({
);
}
+ // Folder placement is per-member in workspace mode (the shared
+ // `sessionGroupId` column is ignored there), so a create-in-folder must
+ // also record the caller's own assignment for the new agent.
+ if (ctx.workspaceId && input.groupId) {
+ await new WorkspaceUserSettingsModel(
+ ctx.serverDB,
+ ctx.userId,
+ ctx.workspaceId,
+ ).setSidebarGroupAssignment(agent.id, input.groupId);
+ }
+
return { agentId: agent.id };
}),
@@ -479,6 +491,13 @@ export const agentRouter = router({
DEFAULT_RESOURCE_ACCESS_LEVELS.agent,
ctx.userId,
);
+ // Folder placement is per-member in workspace mode: keep the copy in
+ // the caller's folder when they had assigned the source agent there.
+ await new WorkspaceUserSettingsModel(
+ ctx.serverDB,
+ ctx.userId,
+ ctx.workspaceId,
+ ).copySidebarGroupAssignment(input.agentId, result.agentId);
}
return result;
}),
diff --git a/apps/server/src/routers/lambda/agentGroup.ts b/apps/server/src/routers/lambda/agentGroup.ts
index 6bc2a1d76a3..08296cbeea4 100644
--- a/apps/server/src/routers/lambda/agentGroup.ts
+++ b/apps/server/src/routers/lambda/agentGroup.ts
@@ -8,6 +8,7 @@ import { AgentModel } from '@/database/models/agent';
import { ChatGroupModel } from '@/database/models/chatGroup';
import { ResourcePermissionModel } from '@/database/models/resourcePermission';
import { UserModel } from '@/database/models/user';
+import { WorkspaceUserSettingsModel } from '@/database/models/workspaceUserSettings';
import { AgentGroupRepository } from '@/database/repositories/agentGroup';
import { DEFAULT_RESOURCE_ACCESS_LEVELS, RESOURCE_ACCESS_LEVELS_BY_TYPE } from '@/database/schemas';
import { type ChatGroupConfig } from '@/database/types/chatGroup';
@@ -287,6 +288,17 @@ export const agentGroupRouter = router({
]);
}
+ // Folder placement is per-member in workspace mode (the shared
+ // `chat_groups.groupId` column is ignored there), so a create-in-folder
+ // must also record the caller's own assignment for the new group.
+ if (ctx.workspaceId && input.groupId) {
+ await new WorkspaceUserSettingsModel(
+ ctx.serverDB,
+ ctx.userId,
+ ctx.workspaceId,
+ ).setSidebarGroupAssignment(group.id, input.groupId);
+ }
+
return { group, supervisorAgentId };
}),
@@ -382,6 +394,15 @@ export const agentGroupRouter = router({
]);
}
+ // Same per-member folder rule as `createGroup` above.
+ if (ctx.workspaceId && input.groupConfig.groupId) {
+ await new WorkspaceUserSettingsModel(
+ ctx.serverDB,
+ ctx.userId,
+ ctx.workspaceId,
+ ).setSidebarGroupAssignment(group.id, input.groupConfig.groupId);
+ }
+
return { agentIds: memberAgentIds, groupId: group.id, supervisorAgentId };
}),
@@ -462,6 +483,13 @@ export const agentGroupRouter = router({
ctx.userId,
),
]);
+ // Folder placement is per-member in workspace mode: keep the copy in
+ // the caller's folder when they had assigned the source group there.
+ await new WorkspaceUserSettingsModel(
+ ctx.serverDB,
+ ctx.userId,
+ ctx.workspaceId,
+ ).copySidebarGroupAssignment(input.groupId, result.groupId);
}
return result;
}),
diff --git a/packages/database/src/models/__tests__/workspaceUserSettings.test.ts b/packages/database/src/models/__tests__/workspaceUserSettings.test.ts
index 79d2dcf488c..32963207979 100644
--- a/packages/database/src/models/__tests__/workspaceUserSettings.test.ts
+++ b/packages/database/src/models/__tests__/workspaceUserSettings.test.ts
@@ -124,6 +124,47 @@ describe('WorkspaceUserSettingsModel', () => {
expect(preference.agentModeOverrides).toEqual({ agentX: true, agentY: false });
});
+ it('deep-merges sidebarPinnedOverrides so a single-item patch never drops other items', async () => {
+ const model = new WorkspaceUserSettingsModel(serverDB, userA, workspaceId);
+ await model.updatePreference({ sidebarPinnedOverrides: { agentX: true } });
+
+ // A stale/empty local copy patches ONLY groupY β€” agentX's pin (and an
+ // explicit unpin=false) must survive the write.
+ await model.updatePreference({ sidebarPinnedOverrides: { groupY: false } });
+
+ const preference = await model.getPreference();
+ expect(preference.sidebarPinnedOverrides).toEqual({ agentX: true, groupY: false });
+ });
+
+ it('setSidebarGroupAssignment records a create-in-folder placement without dropping siblings', async () => {
+ const model = new WorkspaceUserSettingsModel(serverDB, userA, workspaceId);
+ await model.updatePreference({ sidebarGroupAssignments: { agentX: 'folder-1' } });
+
+ // Server-side create-in-folder path (createAgent / createGroup lambdas).
+ await model.setSidebarGroupAssignment('agentNew', 'folder-2');
+
+ const preference = await model.getPreference();
+ expect(preference.sidebarGroupAssignments).toEqual({
+ agentNew: 'folder-2',
+ agentX: 'folder-1',
+ });
+ });
+
+ it('copySidebarGroupAssignment carries the source folder to a duplicate, no-op when unassigned', async () => {
+ const model = new WorkspaceUserSettingsModel(serverDB, userA, workspaceId);
+ await model.updatePreference({ sidebarGroupAssignments: { agentX: 'folder-1' } });
+
+ await model.copySidebarGroupAssignment('agentX', 'agentX-copy');
+ // Source never assigned β†’ no entry is written for the target.
+ await model.copySidebarGroupAssignment('agentY', 'agentY-copy');
+
+ const preference = await model.getPreference();
+ expect(preference.sidebarGroupAssignments).toEqual({
+ 'agentX': 'folder-1',
+ 'agentX-copy': 'folder-1',
+ });
+ });
+
it("isolates users' rows so one caller can never observe another's preference", async () => {
const modelA = new WorkspaceUserSettingsModel(serverDB, userA, workspaceId);
const modelB = new WorkspaceUserSettingsModel(serverDB, userB, workspaceId);
diff --git a/packages/database/src/models/workspaceUserSettings.ts b/packages/database/src/models/workspaceUserSettings.ts
index 1903326bb88..d918d428538 100644
--- a/packages/database/src/models/workspaceUserSettings.ts
+++ b/packages/database/src/models/workspaceUserSettings.ts
@@ -54,6 +54,29 @@ export class WorkspaceUserSettingsModel {
return row?.preference ?? {};
};
+ /**
+ * Record the caller's per-member folder assignment for a sidebar item.
+ * Creation flows call this when an item is created inside a folder in
+ * workspace mode: the shared `sessionGroupId` / `chat_groups.groupId`
+ * columns are ignored there, so without this entry a create-in-folder
+ * would land the new item in the ungrouped list.
+ */
+ setSidebarGroupAssignment = async (itemId: string, folderId: string | null) => {
+ await this.updatePreference({ sidebarGroupAssignments: { [itemId]: folderId } });
+ };
+
+ /**
+ * Copy the caller's folder assignment from a source item to its duplicate,
+ * so duplicating an item that sits in "my" folder keeps the copy there.
+ * No-op when the caller never assigned the source item.
+ */
+ copySidebarGroupAssignment = async (sourceItemId: string, targetItemId: string) => {
+ const preference = await this.getPreference();
+ const assignment = preference.sidebarGroupAssignments?.[sourceItemId];
+ if (assignment === undefined) return;
+ await this.updatePreference({ sidebarGroupAssignments: { [targetItemId]: assignment } });
+ };
+
/**
* 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 β†’
@@ -108,6 +131,14 @@ export class WorkspaceUserSettingsModel {
},
}
: {}),
+ ...(patch.sidebarPinnedOverrides
+ ? {
+ sidebarPinnedOverrides: {
+ ...current.sidebarPinnedOverrides,
+ ...patch.sidebarPinnedOverrides,
+ },
+ }
+ : {}),
};
const [row] = await this.db
.insert(workspaceUserSettings)
diff --git a/packages/database/src/repositories/home/__tests__/pinnedOverrides.test.ts b/packages/database/src/repositories/home/__tests__/pinnedOverrides.test.ts
new file mode 100644
index 00000000000..928f9bfdc28
--- /dev/null
+++ b/packages/database/src/repositories/home/__tests__/pinnedOverrides.test.ts
@@ -0,0 +1,106 @@
+// Regression: pinning is FULLY per-member in workspace mode. Only the
+// caller's `sidebarPinnedOverrides` entries pin items β€” the shared
+// `agents.pinned` / `chat_groups.pinned` columns are ignored entirely (no
+// fallback), so neither another member's legacy pin nor a transferred-in
+// agent's personal-mode pin can surface in anyone's sidebar.
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../../core/getTestDB';
+import { AgentModel } from '../../../models/agent';
+import { WorkspaceUserSettingsModel } from '../../../models/workspaceUserSettings';
+import * as Schema from '../../../schemas';
+import { HomeRepository } from '../index';
+
+const clientDB = await getTestDB();
+
+const memberA = 'u-member-a';
+const memberB = 'u-member-b';
+const ws = 'ws-pin-override';
+
+beforeEach(async () => {
+ await clientDB.delete(Schema.users);
+ await clientDB.delete(Schema.workspaces);
+ await clientDB.insert(Schema.users).values([{ id: memberA }, { id: memberB }]);
+ await clientDB.insert(Schema.workspaces).values({
+ id: ws,
+ name: 'WS',
+ primaryOwnerId: memberA,
+ slug: ws,
+ });
+});
+
+afterEach(async () => {
+ await clientDB.delete(Schema.users);
+ await clientDB.delete(Schema.workspaces);
+});
+
+describe('workspace per-member pins (no shared-column fallback)', () => {
+ it("member's pin floats the item into their own pinned bucket only", async () => {
+ const agentModel = new AgentModel(clientDB, memberA, ws);
+ const agent = await agentModel.create({
+ systemRole: '',
+ title: 'Shared Agent',
+ visibility: 'public',
+ } as any);
+
+ await new WorkspaceUserSettingsModel(clientDB, memberA, ws).updatePreference({
+ sidebarPinnedOverrides: { [agent.id]: true },
+ });
+
+ const forA = await new HomeRepository(clientDB, memberA, ws).getSidebarAgentList();
+ expect(forA.pinned.map((a) => a.id)).toContain(agent.id);
+
+ // Member B never pinned it β€” unpinned for them, regardless of A's action.
+ const forB = await new HomeRepository(clientDB, memberB, ws).getSidebarAgentList();
+ expect(forB.pinned.map((a) => a.id)).not.toContain(agent.id);
+ expect(forB.ungrouped.map((a) => a.id)).toContain(agent.id);
+ });
+
+ it('ignores the shared pinned column for every member (legacy / transferred-in pins)', async () => {
+ const agentModel = new AgentModel(clientDB, memberA, ws);
+ const agent = await agentModel.create({
+ systemRole: '',
+ title: 'Legacy Pinned Agent',
+ visibility: 'public',
+ } as any);
+ // Shared-column pin: pre-per-member legacy state, or a personal-mode pin
+ // carried along by transferAgents (ownership update keeps `pinned`).
+ await agentModel.update(agent.id, { pinned: true });
+
+ for (const member of [memberA, memberB]) {
+ const view = await new HomeRepository(clientDB, member, ws).getSidebarAgentList();
+ expect(view.pinned.map((a) => a.id)).not.toContain(agent.id);
+ expect(view.ungrouped.map((a) => a.id)).toContain(agent.id);
+ }
+ });
+
+ it("member's explicit unpin entry keeps the item unpinned for them", async () => {
+ const agentModel = new AgentModel(clientDB, memberA, ws);
+ const agent = await agentModel.create({
+ systemRole: '',
+ title: 'Toggled Agent',
+ visibility: 'public',
+ } as any);
+
+ const settings = new WorkspaceUserSettingsModel(clientDB, memberA, ws);
+ await settings.updatePreference({ sidebarPinnedOverrides: { [agent.id]: true } });
+ await settings.updatePreference({ sidebarPinnedOverrides: { [agent.id]: false } });
+
+ const forA = await new HomeRepository(clientDB, memberA, ws).getSidebarAgentList();
+ expect(forA.pinned.map((a) => a.id)).not.toContain(agent.id);
+ expect(forA.ungrouped.map((a) => a.id)).toContain(agent.id);
+ });
+
+ it('personal mode keeps reading the shared column', async () => {
+ const agentModel = new AgentModel(clientDB, memberA);
+ const agent = await agentModel.create({
+ systemRole: '',
+ title: 'Personal Agent',
+ visibility: 'private',
+ } as any);
+ await agentModel.update(agent.id, { pinned: true });
+
+ const result = await new HomeRepository(clientDB, memberA).getSidebarAgentList();
+ expect(result.pinned.map((a) => a.id)).toContain(agent.id);
+ });
+});
diff --git a/packages/database/src/repositories/home/__tests__/privatePinned.test.ts b/packages/database/src/repositories/home/__tests__/privatePinned.test.ts
index 1d01638964b..cbff2040b51 100644
--- a/packages/database/src/repositories/home/__tests__/privatePinned.test.ts
+++ b/packages/database/src/repositories/home/__tests__/privatePinned.test.ts
@@ -6,6 +6,7 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { getTestDB } from '../../../core/getTestDB';
import { AgentModel } from '../../../models/agent';
+import { WorkspaceUserSettingsModel } from '../../../models/workspaceUserSettings';
import * as Schema from '../../../schemas';
import { HomeRepository } from '../index';
@@ -40,7 +41,11 @@ describe('workspace private pinned bucket', () => {
title: 'Private Agent',
visibility: 'private',
} as any);
- await agentModel.update(agent.id, { pinned: true });
+ // Workspace pins live in the caller's per-member preference, not the
+ // shared `agents.pinned` column.
+ await new WorkspaceUserSettingsModel(clientDB, creator, ws).updatePreference({
+ sidebarPinnedOverrides: { [agent.id]: true },
+ });
const result = await new HomeRepository(clientDB, creator, ws).getSidebarAgentList();
@@ -57,7 +62,9 @@ describe('workspace private pinned bucket', () => {
title: 'Public Agent',
visibility: 'public',
} as any);
- await agentModel.update(agent.id, { pinned: true });
+ await new WorkspaceUserSettingsModel(clientDB, creator, ws).updatePreference({
+ sidebarPinnedOverrides: { [agent.id]: true },
+ });
const result = await new HomeRepository(clientDB, creator, ws).getSidebarAgentList();
diff --git a/packages/database/src/repositories/home/index.ts b/packages/database/src/repositories/home/index.ts
index d61080fdf12..1eeb1ff0339 100644
--- a/packages/database/src/repositories/home/index.ts
+++ b/packages/database/src/repositories/home/index.ts
@@ -157,21 +157,12 @@ export class HomeRepository {
)
.orderBy(sessionGroups.sort);
- // 3.5 Per-member folder assignments: workspace members organize shared
- // items into their own folders without touching the shared
- // `agents.sessionGroupId` column (one member's drag must not regroup
- // another member's sidebar). The shared column remains the fallback for
- // items the caller never reassigned.
- let assignmentOverrides: Record<string, string | null> = {};
- if (this.workspaceId) {
- const settings = await this.db.query.workspaceUserSettings.findFirst({
- where: and(
- eq(workspaceUserSettings.workspaceId, this.workspaceId),
- eq(workspaceUserSettings.userId, this.userId),
- ),
- });
- assignmentOverrides = settings?.preference?.sidebarGroupAssignments ?? {};
- }
+ // 3.5 Per-member folder assignments + pins: workspace members organize
+ // shared items without touching the shared `agents.sessionGroupId` /
+ // `pinned` columns (one member's drag or pin must not reshape another
+ // member's sidebar). These entries are the sole source in workspace mode
+ // β€” see processAgentList for the no-fallback rule.
+ const { assignmentOverrides, pinnedOverrides } = await this.getSidebarPreferenceOverrides();
// 4. Process and categorize
return this.processAgentList(
@@ -182,6 +173,7 @@ export class HomeRepository {
agentUnread,
groupUnread,
assignmentOverrides,
+ pinnedOverrides,
);
}
@@ -276,11 +268,19 @@ export class HomeRepository {
agentUnread: Map<string, number> = new Map(),
groupUnread: Map<string, number> = new Map(),
assignmentOverrides: Record<string, string | null> = {},
+ pinnedOverrides: Record<string, boolean> = {},
): SidebarAgentListResponse {
- // Per-member folder choice wins over the shared column; `null` means the
- // caller explicitly moved the item back to the default (ungrouped) list.
+ // Sidebar organization (folder + pin) is FULLY per-member in workspace
+ // mode: only the caller's own workspace_user_settings entries apply β€” the
+ // shared `sessionGroupId` / `pinned` columns are ignored entirely (no
+ // fallback), so nothing another member did (or a transferred-in agent's
+ // personal-mode state) can shape this caller's sidebar. Personal mode
+ // keeps reading the shared columns β€” single-user data, nothing to leak.
+ const perMember = Boolean(this.workspaceId);
const effectiveGroupId = (itemId: string, sharedGroupId: string | null): string | null =>
- itemId in assignmentOverrides ? assignmentOverrides[itemId] : sharedGroupId;
+ perMember ? (assignmentOverrides[itemId] ?? null) : sharedGroupId;
+ const effectivePinned = (itemId: string, sharedPinned: boolean): boolean =>
+ perMember ? (pinnedOverrides[itemId] ?? false) : sharedPinned;
// Convert to unified format
// For pinned status: agents.pinned takes priority, fallback to sessions.pinned for backward compatibility
// For groupId: agents.sessionGroupId takes priority, fallback to sessions.groupId for backward compatibility
@@ -305,7 +305,7 @@ export class HomeRepository {
heterogeneousType: a.agencyConfig?.heterogeneousProvider?.type ?? null,
id: a.id,
isPrivate: visibility === 'private',
- pinned: a.pinned ?? a.sessionPinned ?? false,
+ pinned: effectivePinned(a.id, a.pinned ?? a.sessionPinned ?? false),
sessionId: a.sessionId,
slug: a.slug,
title: meta.title,
@@ -328,7 +328,7 @@ export class HomeRepository {
groupId: effectiveGroupId(g.id, g.groupId),
id: g.id,
isPrivate: visibility === 'private',
- pinned: g.pinned ?? false,
+ pinned: effectivePinned(g.id, g.pinned ?? false),
sessionId: null,
title: g.title,
type: 'group' as const,
@@ -408,6 +408,31 @@ export class HomeRepository {
return { groups, pinned, privateGroups, privatePinned, privateUngrouped, ungrouped };
}
+ /**
+ * Per-member sidebar state from workspace_user_settings. Folder assignment
+ * and pinning are fully per-member in workspace mode β€” these entries are
+ * the only source of truth; the shared `sessionGroupId` / `pinned` columns
+ * are ignored (no fallback), so no other member's action leaks into the
+ * caller's sidebar.
+ */
+ private async getSidebarPreferenceOverrides(): Promise<{
+ assignmentOverrides: Record<string, string | null>;
+ pinnedOverrides: Record<string, boolean>;
+ }> {
+ if (!this.workspaceId) return { assignmentOverrides: {}, pinnedOverrides: {} };
+
+ const settings = await this.db.query.workspaceUserSettings.findFirst({
+ where: and(
+ eq(workspaceUserSettings.workspaceId, this.workspaceId),
+ eq(workspaceUserSettings.userId, this.userId),
+ ),
+ });
+ return {
+ assignmentOverrides: settings?.preference?.sidebarGroupAssignments ?? {},
+ pinnedOverrides: settings?.preference?.sidebarPinnedOverrides ?? {},
+ };
+ }
+
/**
* Search agents and chat groups by keyword
* Searches in title and description fields
@@ -418,7 +443,8 @@ export class HomeRepository {
const bm25Query = sanitizeBm25Query(keyword);
// Run agent and chat group searches in parallel
- const [agentResults, chatGroupResults] = await Promise.all([
+ const [{ pinnedOverrides }, agentResults, chatGroupResults] = await Promise.all([
+ this.getSidebarPreferenceOverrides(),
// 1. Search agents by title or description (BM25)
this.db
.select({
@@ -488,7 +514,9 @@ export class HomeRepository {
backgroundColor: a.backgroundColor,
description: a.description,
id: a.id,
- pinned: a.pinned ?? a.sessionPinned ?? false,
+ pinned: this.workspaceId
+ ? (pinnedOverrides[a.id] ?? false)
+ : (a.pinned ?? a.sessionPinned ?? false),
sessionId: a.sessionId,
title: meta.title,
type: 'agent' as const,
@@ -505,7 +533,7 @@ export class HomeRepository {
backgroundColor: g.backgroundColor,
description: g.description,
id: g.id,
- pinned: g.pinned ?? false,
+ pinned: this.workspaceId ? (pinnedOverrides[g.id] ?? false) : (g.pinned ?? false),
title: g.title,
type: 'group' as const,
updatedAt: g.updatedAt,
diff --git a/packages/types/src/user/preference.ts b/packages/types/src/user/preference.ts
index d21a4f185cb..d4bcdbc5ce5 100644
--- a/packages/types/src/user/preference.ts
+++ b/packages/types/src/user/preference.ts
@@ -74,8 +74,8 @@ export interface WorkspaceUserPreference {
* sessionGroupId). Folders are per-member in workspace mode, so moving a
* shared item into "my" folder must not rewrite the shared
* `agents.sessionGroupId` column (which would regroup every member's
- * sidebar). `null` = explicitly moved back to the default list. Items
- * absent here fall back to the shared column.
+ * sidebar). This map is the sole source in workspace mode β€” items absent
+ * here sit in the default (ungrouped) list; the shared column is ignored.
*/
sidebarGroupAssignments?: Record<string /* itemId */, string | null>;
/**
@@ -86,6 +86,15 @@ export interface WorkspaceUserPreference {
* untouched. Distinct from pinning: this is membership, not ordering.
*/
sidebarHiddenAgentIds?: string[];
+ /**
+ * Per-member pins for sidebar items (agentId/chatGroupId β†’ pinned).
+ * Pinning is fully per-member in workspace mode: this map is the sole
+ * source β€” the shared `agents.pinned` / `chat_groups.pinned` columns are
+ * ignored (a transferred-in agent's personal pin, or a pin made before
+ * this preference existed, must not surface for anyone). Items absent
+ * here are unpinned.
+ */
+ sidebarPinnedOverrides?: Record<string /* itemId */, boolean>;
}
export interface LobeUser {
diff --git a/src/features/AgentViewAll/AgentRow.tsx b/src/features/AgentViewAll/AgentRow.tsx
index 0d4ec457589..c47f8909c33 100644
--- a/src/features/AgentViewAll/AgentRow.tsx
+++ b/src/features/AgentViewAll/AgentRow.tsx
@@ -23,13 +23,30 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
description: css`
max-width: min(720px, 100%);
`,
- row: css`
+ // The link spans the name column (not the whole row) β€” a management list
+ // is for scanning and acting, and a full-row link turns clicks on the
+ // author / timestamp / action columns into a navigation. The name column
+ // stays a generous target, including the space right of a short title.
+ identity: css`
cursor: pointer;
+ display: flex;
+ flex: 1;
+ gap: 12px;
+ align-items: center;
+
+ min-width: 0;
+
+ color: inherit;
+
+ &:hover .agent-row-title {
+ text-decoration: underline;
+ }
+ `,
+ row: css`
padding-block: 8px;
padding-inline: 12px;
border-radius: ${cssVar.borderRadiusLG};
-
color: inherit;
&:hover {
@@ -77,8 +94,6 @@ const AgentRow = memo<AgentRowProps>(
const handleToggleSidebar = useCallback(
(e: MouseEvent) => {
- // Keep the toggle from following the row link.
- e.preventDefault();
e.stopPropagation();
onToggleSidebar?.(item);
},
@@ -86,16 +101,15 @@ const AgentRow = memo<AgentRowProps>(
);
return (
- <WorkspaceLink
- aria-label={title || undefined}
- className={styles.row}
- ref={setAnchor}
- to={type === 'group' ? GROUP_CHAT_URL(id) : AGENT_CHAT_URL(id, false)}
- >
- <Flexbox horizontal align={'center'} gap={12}>
+ <Flexbox horizontal align={'center'} className={styles.row} gap={12} ref={setAnchor}>
+ <WorkspaceLink
+ aria-label={title || undefined}
+ className={styles.identity}
+ to={type === 'group' ? GROUP_CHAT_URL(id) : AGENT_CHAT_URL(id, false)}
+ >
<AgentAvatar item={item} size={36} />
<Flexbox flex={1} gap={2} style={{ minWidth: 0 }}>
- <Text ellipsis weight={500}>
+ <Text ellipsis className={'agent-row-title'} weight={500}>
{title || t('agentViewAll.untitled')}
</Text>
{description && (
@@ -104,63 +118,56 @@ const AgentRow = memo<AgentRowProps>(
</Text>
)}
</Flexbox>
- {showAuthor && (
- <Flexbox
- horizontal
- align={'center'}
- flex={'none'}
- gap={6}
- style={{ width: AUTHOR_COL_WIDTH }}
- >
- {author ? (
- <>
- <Avatar avatar={author.avatar || DEFAULT_AVATAR} size={20} />
- <Text ellipsis fontSize={12} type={'secondary'}>
- {author.name}
- </Text>
- </>
- ) : (
- <Text fontSize={12} type={'secondary'}>
- –
- </Text>
- )}
- </Flexbox>
- )}
- <Text className={styles.updatedAt} fontSize={12} style={{ width: TIME_COL_WIDTH }}>
- {updatedAt ? formatUpdatedAt(updatedAt) : '–'}
- </Text>
+ </WorkspaceLink>
+ {showAuthor && (
<Flexbox
horizontal
align={'center'}
flex={'none'}
- gap={4}
- style={{ width: ACTION_COL_WIDTH }}
- onClick={(e) => {
- // Keep the actions from following the row link.
- e.preventDefault();
- e.stopPropagation();
- }}
+ gap={6}
+ style={{ width: AUTHOR_COL_WIDTH }}
>
- {onToggleSidebar && (
- <ActionIcon
- color={cssVar.colorTextSecondary}
- icon={sidebarHidden ? EyeOffIcon : EyeIcon}
- size={'small'}
- // Hidden agents read as faded, mirroring the customize-sidebar
- // modal's 0.5-opacity treatment of hidden rows.
- style={{ opacity: sidebarHidden ? 0.5 : undefined }}
- title={
- sidebarHidden
- ? t('agentViewAll.addToSidebar')
- : t('agentViewAll.removeFromSidebar')
- }
- onClick={handleToggleSidebar}
- />
+ {author ? (
+ <>
+ <Avatar avatar={author.avatar || DEFAULT_AVATAR} size={20} />
+ <Text ellipsis fontSize={12} type={'secondary'}>
+ {author.name}
+ </Text>
+ </>
+ ) : (
+ <Text fontSize={12} type={'secondary'}>
+ –
+ </Text>
)}
- <ItemActions anchor={anchor} item={item} />
</Flexbox>
+ )}
+ <Text className={styles.updatedAt} fontSize={12} style={{ width: TIME_COL_WIDTH }}>
+ {updatedAt ? formatUpdatedAt(updatedAt) : '–'}
+ </Text>
+ <Flexbox
+ horizontal
+ align={'center'}
+ flex={'none'}
+ gap={4}
+ style={{ width: ACTION_COL_WIDTH }}
+ >
+ {onToggleSidebar && (
+ <ActionIcon
+ color={cssVar.colorTextSecondary}
+ icon={sidebarHidden ? EyeOffIcon : EyeIcon}
+ size={'small'}
+ // Hidden agents read as faded, mirroring the customize-sidebar
+ // modal's 0.5-opacity treatment of hidden rows.
+ style={{ opacity: sidebarHidden ? 0.5 : undefined }}
+ title={
+ sidebarHidden ? t('agentViewAll.addToSidebar') : t('agentViewAll.removeFromSidebar')
+ }
+ onClick={handleToggleSidebar}
+ />
+ )}
+ <ItemActions anchor={anchor} item={item} />
</Flexbox>
- </WorkspaceLink>
+ </Flexbox>
);
},
);
diff --git a/src/routes/(main)/home/_layout/Body/Agent/AllAgentsDrawer/Content.tsx b/src/routes/(main)/home/_layout/Body/Agent/AllAgentsDrawer/Content.tsx
index cc22898f826..0526784f0c6 100644
--- a/src/routes/(main)/home/_layout/Body/Agent/AllAgentsDrawer/Content.tsx
+++ b/src/routes/(main)/home/_layout/Body/Agent/AllAgentsDrawer/Content.tsx
@@ -12,6 +12,7 @@ import { homeAgentListSelectors } from '@/store/home/selectors';
import GroupItem from '../List/AgentGroupItem';
import AgentItem from '../List/AgentItem';
+import { useKeepSidebarListed } from '../List/useAgentList';
interface ContentProps {
open: boolean;
@@ -35,8 +36,13 @@ const Content = memo<ContentProps>(({ searchKeyword }) => {
// Get all agents from homeStore (ungrouped agents for default view)
const allUngroupedAgents = useHomeStore(homeAgentListSelectors.ungroupedAgents, isEqual);
+ // The drawer is sidebar overflow, so it honors the caller's "removed from
+ // my sidebar" list like every sidebar section β€” items hidden there are
+ // findable on the /agents View All page instead.
+ const keep = useKeepSidebarListed();
+
// Filter and display - searchResults already returns SidebarAgentItem[]
- const displayItems = isSearching ? searchResults || [] : allUngroupedAgents;
+ const displayItems = keep(isSearching ? searchResults || [] : allUngroupedAgents);
const count = displayItems.length;
diff --git a/src/routes/(main)/home/_layout/Body/Agent/List/useAgentList.tsx b/src/routes/(main)/home/_layout/Body/Agent/List/useAgentList.tsx
index 616121c0781..17812e62dbd 100644
--- a/src/routes/(main)/home/_layout/Body/Agent/List/useAgentList.tsx
+++ b/src/routes/(main)/home/_layout/Body/Agent/List/useAgentList.tsx
@@ -14,9 +14,10 @@ import { workspaceUserSettingsSelectors } from '@/store/user/selectors';
/**
* Filter predicate over the caller's "removed from my sidebar" list β€”
* workspace mode reads the per-member `workspace_user_settings` bucket,
- * personal mode reads `users.preference`. Applied at sidebar render β€” not in
- * the home store β€” so "view all" surfaces (AllAgentsDrawer, the /agents page)
- * still list every item.
+ * personal mode reads `users.preference`. Applied at render on every
+ * sidebar-scoped surface (the section lists AND the "ζ›΄ε€š" AllAgentsDrawer,
+ * which is sidebar overflow) β€” not in the home store β€” so the /agents View
+ * All page remains the one surface that lists every item.
*/
export const useKeepSidebarListed = () => {
const activeWorkspaceId = useActiveWorkspaceId();
diff --git a/src/store/home/slices/sidebarUI/action.test.ts b/src/store/home/slices/sidebarUI/action.test.ts
index 1e85423b40d..924296eb34d 100644
--- a/src/store/home/slices/sidebarUI/action.test.ts
+++ b/src/store/home/slices/sidebarUI/action.test.ts
@@ -1,6 +1,7 @@
import { act, renderHook } from '@testing-library/react';
import { afterEach, describe, expect, it, vi } from 'vitest';
+import { getActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
import { INBOX_SESSION_ID } from '@/const/session';
import { agentService } from '@/services/agent';
import { chatGroupService } from '@/services/chatGroup';
@@ -11,6 +12,7 @@ import { getAgentStoreState } from '@/store/agent';
import { useHomeStore } from '@/store/home';
import type * as SessionStoreModule from '@/store/session';
import { getSessionStoreState } from '@/store/session';
+import { useUserStore } from '@/store/user';
// Mock dependencies
vi.mock('@/components/AntdStaticMethods', () => ({
@@ -22,6 +24,11 @@ vi.mock('@/components/AntdStaticMethods', () => ({
},
}));
+vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({
+ getActiveWorkspaceId: vi.fn(() => null),
+ useActiveWorkspaceId: vi.fn(() => null),
+}));
+
vi.mock('@/store/session', async (importOriginal) => {
const actual = await importOriginal<typeof SessionStoreModule>();
@@ -117,6 +124,53 @@ describe('createSidebarUISlice', () => {
});
});
+ describe('pin in workspace mode', () => {
+ // Regression: pinning used to write the shared `agents.pinned` /
+ // `chat_groups.pinned` columns in workspace mode, reordering every
+ // member's sidebar. It must go to the caller's per-member preference.
+ it('should write agent pin to per-member preference, not the shared column', async () => {
+ vi.mocked(getActiveWorkspaceId).mockReturnValue('ws-1');
+ const spyOnPreference = vi
+ .spyOn(useUserStore.getState(), 'updateWorkspaceUserPreference')
+ .mockResolvedValueOnce(undefined as any);
+ const spyOnShared = vi.spyOn(agentService, 'updateAgentPinned');
+ const spyOnRefresh = vi.spyOn(useHomeStore.getState(), 'refreshAgentList');
+
+ const { result } = renderHook(() => useHomeStore());
+
+ await act(async () => {
+ await result.current.pinAgent('agent-123', true);
+ });
+
+ expect(spyOnPreference).toHaveBeenCalledWith({
+ sidebarPinnedOverrides: { 'agent-123': true },
+ });
+ expect(spyOnShared).not.toHaveBeenCalled();
+ expect(spyOnRefresh).toHaveBeenCalled();
+ });
+
+ it('should write group pin to per-member preference, not the shared column', async () => {
+ vi.mocked(getActiveWorkspaceId).mockReturnValue('ws-1');
+ const spyOnPreference = vi
+ .spyOn(useUserStore.getState(), 'updateWorkspaceUserPreference')
+ .mockResolvedValueOnce(undefined as any);
+ const spyOnShared = vi.spyOn(chatGroupService, 'updateGroup');
+ const spyOnRefresh = vi.spyOn(useHomeStore.getState(), 'refreshAgentList');
+
+ const { result } = renderHook(() => useHomeStore());
+
+ await act(async () => {
+ await result.current.pinAgentGroup('group-123', false);
+ });
+
+ expect(spyOnPreference).toHaveBeenCalledWith({
+ sidebarPinnedOverrides: { 'group-123': false },
+ });
+ expect(spyOnShared).not.toHaveBeenCalled();
+ expect(spyOnRefresh).toHaveBeenCalled();
+ });
+ });
+
describe('removeAgent', () => {
it('should remove an agent and refresh agent list', async () => {
const mockAgentId = 'agent-123';
diff --git a/src/store/home/slices/sidebarUI/action.ts b/src/store/home/slices/sidebarUI/action.ts
index baba809ce2b..9111a39b996 100644
--- a/src/store/home/slices/sidebarUI/action.ts
+++ b/src/store/home/slices/sidebarUI/action.ts
@@ -82,15 +82,40 @@ export class SidebarUIActionImpl {
};
pinAgent = async (agentId: string, pinned: boolean): Promise<void> => {
- await agentService.updateAgentPinned(agentId, pinned);
+ await this.#persistPinned(agentId, pinned, () =>
+ agentService.updateAgentPinned(agentId, pinned),
+ );
await this.#get().refreshAgentList();
};
pinAgentGroup = async (groupId: string, pinned: boolean): Promise<void> => {
- await chatGroupService.updateGroup(groupId, { pinned });
+ await this.#persistPinned(groupId, pinned, () =>
+ chatGroupService.updateGroup(groupId, { pinned }),
+ );
await this.#get().refreshAgentList();
};
+ // Pinning is fully per-member in workspace mode: record it in the caller's
+ // workspace_user_settings instead of the shared `agents.pinned` /
+ // `chat_groups.pinned` columns, so one member's pin never reorders another
+ // member's sidebar. The shared columns are ignored entirely when reading
+ // workspace lists (no fallback).
+ #persistPinned = async (
+ itemId: string,
+ pinned: boolean,
+ persistShared: () => Promise<unknown>,
+ ): Promise<void> => {
+ const workspaceId = getActiveWorkspaceId();
+ if (workspaceId) {
+ const { getUserStoreState } = await import('@/store/user');
+ await getUserStoreState().updateWorkspaceUserPreference({
+ sidebarPinnedOverrides: { [itemId]: pinned },
+ });
+ } else {
+ await persistShared();
+ }
+ };
+
removeAgent = async (agentId: string): Promise<void> => {
await agentService.removeAgent(agentId);
await this.#get().refreshAgentList();
diff --git a/src/store/user/slices/workspaceUserSettings/action.ts b/src/store/user/slices/workspaceUserSettings/action.ts
index f51ae82c264..c58c01e03e0 100644
--- a/src/store/user/slices/workspaceUserSettings/action.ts
+++ b/src/store/user/slices/workspaceUserSettings/action.ts
@@ -114,6 +114,14 @@ export class WorkspaceUserSettingsActionImpl {
},
}
: {}),
+ ...(patch.sidebarPinnedOverrides
+ ? {
+ sidebarPinnedOverrides: {
+ ...previous.sidebarPinnedOverrides,
+ ...patch.sidebarPinnedOverrides,
+ },
+ }
+ : {}),
};
const workspaceId = getActiveWorkspaceId();
const swrKey = workspaceId ? [WORKSPACE_USER_SETTINGS_SWR_KEY, workspaceId] : null;