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: creator-only visibility demotion & sidebar section reveal (#17107)

Rdmclin299ad8e2dadd5
diff --git a/.agents/skills/agent-testing/references/probe-mock-patterns.md b/.agents/skills/agent-testing/references/probe-mock-patterns.md
index 33924076a33..9c15ddbc71c 100644
--- a/.agents/skills/agent-testing/references/probe-mock-patterns.md
+++ b/.agents/skills/agent-testing/references/probe-mock-patterns.md
@@ -986,6 +986,19 @@ nodeintegration, plugins, disablewebsecurity, allowpopups, preload, …`). The h
- **Doesn't work**: `sessionStore.createSession({...})` β€” the desktop app doesn't use the classic session store (`sessions` is `[]`, `activeId` is `'inbox'`); agents are a server-backed model in `agentStore.agentMap` keyed by `agt_...`. The created session never becomes the active agent.
- **Works**: back up the active agent's full config (`model`, `provider`, `agencyConfig`, relevant `chatConfig`), reconfigure it in place (`updateAgentConfigById` + `updateAgentChatConfigById`), run the test, then restore every field and clear any injected key-vault entry. Also: `chat.sendMessage` requires `context: { agentId, topicId, isNew }` or it throws `Cannot destructure property 'agentId' of 'context'`. Reads right after an `updateAgent*` can be stale β€” re-read after \~1.5s to confirm persistence.
+### C7. DB-seeded task rows need a `task_`-prefixed id or `resolve()` silently misses them
+
+- **Situation**: seeding a `tasks` row directly in SQL for a router probe, with a
+ hand-written id like `tsk_foo`, then calling a task procedure β€” it 404s
+ ("Task not found") even though the row exists and the caller is a member.
+- **Doesn't work**: any id not starting with `task_`. `TaskModel.resolve()`
+ (`packages/database/src/models/task.ts:220-223`) only treats the input as a row
+ id when it starts with `task_`; everything else is upper-cased and looked up as
+ a workspace `identifier` (e.g. `T-1`), so `tsk_foo` becomes the identifier
+ lookup `TSK_FOO` β†’ null.
+- **Works**: use the idGenerator prefix (`task_<suffix>`) for seeded ids, or pass
+ the row's `identifier` (`T-<seq>`) to the procedure instead.
+
### F1. Seeding a shared topic by raw SQL: messages MUST carry `agent_id`, or the share page renders skeletons forever
- **Situation**: fixture-seeding a `/share/t/<id>` page (topics + messages + `topic_shares`
diff --git a/apps/server/src/routers/lambda/__tests__/agent.test.ts b/apps/server/src/routers/lambda/__tests__/agent.test.ts
index d6c52f7be80..7e32f86c2f0 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 { UserModel } from '@/database/models/user';
import { AgentService } from '@/server/services/agent';
import { EditLockService } from '@/server/services/editLock';
import { publishResourceEvent } from '@/server/services/resourceEvents';
+import { hasWorkspaceScopedPermission } from '@/server/services/workspacePermission';
import { KnowledgeType } from '@/types/knowledgeBase';
import { agentRouter } from '../agent';
@@ -50,6 +51,10 @@ vi.mock('@/server/services/agent', () => ({
AgentService: vi.fn(),
}));
+vi.mock('@/server/services/workspacePermission', () => ({
+ hasWorkspaceScopedPermission: vi.fn(),
+}));
+
describe('agentRouter', () => {
const userId = 'testUserId';
let mockCtx: any;
@@ -391,6 +396,54 @@ describe('agentRouter', () => {
expect(agentModelMock.setVisibility).toHaveBeenCalledWith('agent-1', 'private');
});
+ it('rejects demotion of another member agent even for a workspace owner (LOBE-11760)', async () => {
+ agentModelMock.getAgentVisibilityMeta.mockResolvedValue({
+ slug: null,
+ userId: 'other-member',
+ visibility: 'public',
+ });
+
+ const caller = agentRouter.createCaller(wsCtx());
+
+ await expect(
+ caller.setAgentVisibility({ id: 'agent-1', visibility: 'private' }),
+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });
+ // Creator-only: rejected before the owner-permission lookup even runs.
+ expect(hasWorkspaceScopedPermission).not.toHaveBeenCalled();
+ expect(agentModelMock.setVisibility).not.toHaveBeenCalled();
+ });
+
+ it('still allows a workspace owner to promote another member agent', async () => {
+ agentModelMock.getAgentVisibilityMeta.mockResolvedValue({
+ slug: null,
+ userId: 'other-member',
+ visibility: 'private',
+ });
+ vi.mocked(hasWorkspaceScopedPermission).mockResolvedValue(true);
+
+ const caller = agentRouter.createCaller(wsCtx());
+ const result = await caller.setAgentVisibility({ id: 'agent-1', visibility: 'public' });
+
+ expect(result).toEqual({ success: true });
+ expect(agentModelMock.setVisibility).toHaveBeenCalledWith('agent-1', 'public');
+ });
+
+ it('rejects promotion of another member agent for a plain member', async () => {
+ agentModelMock.getAgentVisibilityMeta.mockResolvedValue({
+ slug: null,
+ userId: 'other-member',
+ visibility: 'private',
+ });
+ vi.mocked(hasWorkspaceScopedPermission).mockResolvedValue(false);
+
+ const caller = agentRouter.createCaller(wsCtx());
+
+ await expect(
+ caller.setAgentVisibility({ id: 'agent-1', visibility: 'public' }),
+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });
+ expect(agentModelMock.setVisibility).not.toHaveBeenCalled();
+ });
+
it('does not run the public-task guard on promotion', async () => {
agentModelMock.getAgentVisibilityMeta.mockResolvedValue({
slug: null,
diff --git a/apps/server/src/routers/lambda/agent.ts b/apps/server/src/routers/lambda/agent.ts
index 5cf1ecd4e7d..90ebd0a7a08 100644
--- a/apps/server/src/routers/lambda/agent.ts
+++ b/apps/server/src/routers/lambda/agent.ts
@@ -107,7 +107,7 @@ export const agentRouter = router({
* Publish a private agent into the workspace. Only the creator of a
* still-private agent can run this; the underlying SQL enforces both rules.
* The inverse transition (public β†’ private) goes through
- * `setAgentVisibility`, which is gated to the creator or a workspace owner.
+ * `setAgentVisibility`, which is gated to the creator only (LOBE-11760).
*/
publishAgentToWorkspace: agentProcedure
.use(withScopedPermission('agent:update'))
@@ -120,9 +120,10 @@ export const agentRouter = router({
* Bidirectional visibility switch (LOBE-11551). Rules:
* - builtin agents (LobeAI etc., identified by slug) can never change
* visibility β€” the workspace copy must stay shared;
- * - only the agent's creator or a workspace owner may pull a published
- * agent back to private; other members get FORBIDDEN. The UI hides the
- * entry for them, this is the server-side backstop.
+ * - only the agent's creator may pull a published agent back to private
+ * (LOBE-11760): a workspace owner demoting another member's agent would
+ * effectively appropriate it, so everyone else gets FORBIDDEN. The UI
+ * hides the entry for them, this is the server-side backstop.
*/
setAgentVisibility: agentProcedure
.use(withScopedPermission('agent:update'))
@@ -141,6 +142,15 @@ export const agentRouter = router({
if (meta.visibility === input.visibility) return { success: true };
if (ctx.workspaceId && meta.userId !== ctx.userId) {
+ // Demoting to private stays creator-only even for owners: the agent
+ // would land in the creator's private list, not the actor's, so an
+ // owner-initiated demotion just appropriates another member's data.
+ if (input.visibility === 'private') {
+ throw new TRPCError({
+ code: 'FORBIDDEN',
+ message: 'Only the agent creator can make this agent private',
+ });
+ }
const canOverride = await hasWorkspaceScopedPermission({
action: 'AGENT_UPDATE',
db: ctx.serverDB,
diff --git a/apps/server/src/routers/lambda/device.ts b/apps/server/src/routers/lambda/device.ts
index 06ea3642c6d..0489f232f17 100644
--- a/apps/server/src/routers/lambda/device.ts
+++ b/apps/server/src/routers/lambda/device.ts
@@ -1094,10 +1094,11 @@ export const deviceRouter = router({
* Publish a private workspace device to the shared pool, or pull a public one
* back to private. Mirrors the agent/file `setVisibility` contract:
* - the enrolling member may toggle their own device both ways;
- * - a workspace owner may demote any *visible* (public) device β€” other
- * members' private devices are invisible to owners by design (the lookup
- * below already fails closed with NOT_FOUND), so publishing someone
- * else's private device is impossible.
+ * - nobody else may touch visibility (LOBE-11760): owners demoting another
+ * member's public device would appropriate it into that member's private
+ * list, and other members' private devices are invisible to everyone
+ * else by design (the lookup below already fails closed with NOT_FOUND),
+ * so the whole toggle is effectively enroller-only.
*/
setWorkspaceDeviceVisibility: wsWritableProcedure
.use(serverDatabase)
@@ -1114,12 +1115,10 @@ export const deviceRouter = router({
throw new TRPCError({ code: 'NOT_FOUND', message: 'Workspace device not found.' });
}
if (row.visibility === input.visibility) return { success: true };
- const role = (ctx as { workspaceRole?: WorkspaceRole }).workspaceRole;
- if (!canEditWorkspaceDevice(role, ctx.userId, row.userId)) {
+ if (row.userId !== ctx.userId) {
throw new TRPCError({
code: 'FORBIDDEN',
- message:
- 'Only the enrolling member or a workspace owner can change this device visibility.',
+ message: 'Only the enrolling member can change this device visibility.',
});
}
await model.setWorkspaceDeviceVisibility(input.deviceId, input.visibility);
diff --git a/apps/server/src/routers/lambda/task.ts b/apps/server/src/routers/lambda/task.ts
index 6f0ecd613cb..a6875bddfa4 100644
--- a/apps/server/src/routers/lambda/task.ts
+++ b/apps/server/src/routers/lambda/task.ts
@@ -1086,11 +1086,19 @@ export const taskRouter = router({
}
}
- // Owner can always change visibility on their own tasks. In workspace
- // mode, allow workspace owners to override (mirrors the transferTask
- // policy at line ~1166): only they can change visibility on tasks
- // created by other members.
+ // The creator can always change visibility on their own tasks. In
+ // workspace mode, workspace owners may still promote other members'
+ // tasks (mirrors the transferTask policy at line ~1166), but demoting
+ // to private stays creator-only (LOBE-11760): the task would land in
+ // the creator's private list, so an owner-initiated demotion just
+ // appropriates another member's data.
if (ctx.workspaceId && resolved.createdByUserId !== ctx.userId) {
+ if (input.visibility === 'private') {
+ throw new TRPCError({
+ code: 'FORBIDDEN',
+ message: 'Only the task creator can make this task private',
+ });
+ }
const canOverride = await hasWorkspaceScopedPermission({
action: 'AGENT_UPDATE',
db: ctx.serverDB,
diff --git a/packages/database/src/repositories/home/__tests__/workspaceHeteroVisibility.test.ts b/packages/database/src/repositories/home/__tests__/workspaceHeteroVisibility.test.ts
new file mode 100644
index 00000000000..08d1d3c7055
--- /dev/null
+++ b/packages/database/src/repositories/home/__tests__/workspaceHeteroVisibility.test.ts
@@ -0,0 +1,77 @@
+// Regression for LOBE-11758: a workspace heterogeneous agent flipped back to
+// `private` must stay visible to its creator (Private bucket) and invisible
+// to other members across the whole sidebar payload.
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../../core/getTestDB';
+import { AgentModel } from '../../../models/agent';
+import * as Schema from '../../../schemas';
+import { HomeRepository } from '../index';
+
+const clientDB = await getTestDB();
+
+const creator = 'u-creator';
+const member = 'u-member';
+const ws = 'ws-1';
+
+beforeEach(async () => {
+ await clientDB.delete(Schema.users);
+ await clientDB.delete(Schema.workspaces);
+ await clientDB.insert(Schema.users).values([{ id: creator }, { id: member }]);
+ await clientDB.insert(Schema.workspaces).values({
+ id: ws,
+ name: 'WS',
+ primaryOwnerId: creator,
+ slug: 'ws-1',
+ });
+});
+
+afterEach(async () => {
+ await clientDB.delete(Schema.users);
+ await clientDB.delete(Schema.workspaces);
+});
+
+describe('workspace hetero agent visibility flip (LOBE-11758)', () => {
+ it('hetero agent stays visible to creator after public -> private', async () => {
+ const agentModel = new AgentModel(clientDB, creator, ws);
+
+ // mirrors useCreateHeteroAgent -> lambda createAgent (public default)
+ const agent = await agentModel.create({
+ agencyConfig: { heterogeneousProvider: { command: 'claude', type: 'claude-code' } } as any,
+ provider: 'claude-code',
+ systemRole: '',
+ title: 'CC Agent',
+ });
+
+ // sanity: visible in workspace sidebar (public)
+ const before = await new HomeRepository(clientDB, creator, ws).getSidebarAgentList();
+ expect(before.ungrouped.map((a) => a.id)).toContain(agent.id);
+
+ // flip back to private (router path: getAgentVisibilityMeta -> setVisibility)
+ const updated = await agentModel.setVisibility(agent.id, 'private');
+ expect(updated).not.toBeNull();
+
+ // creator should still see it in the Private bucket
+ const after = await new HomeRepository(clientDB, creator, ws).getSidebarAgentList();
+ const everywhere = [
+ ...after.pinned,
+ ...after.ungrouped,
+ ...after.privateUngrouped,
+ ...after.groups.flatMap((g) => g.items),
+ ...after.privateGroups.flatMap((g) => g.items),
+ ];
+ expect(after.privateUngrouped.map((a) => a.id)).toContain(agent.id);
+ expect(everywhere.map((a) => a.id)).toContain(agent.id);
+
+ // member should NOT see it
+ const memberView = await new HomeRepository(clientDB, member, ws).getSidebarAgentList();
+ const memberAll = [
+ ...memberView.pinned,
+ ...memberView.ungrouped,
+ ...memberView.privateUngrouped,
+ ...memberView.groups.flatMap((g) => g.items),
+ ...memberView.privateGroups.flatMap((g) => g.items),
+ ];
+ expect(memberAll.map((a) => a.id)).not.toContain(agent.id);
+ });
+});
diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskDetailHeaderActions.test.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskDetailHeaderActions.test.tsx
index 30f4910716e..c9bc402a9ab 100644
--- a/src/features/AgentTasks/AgentTaskDetail/TaskDetailHeaderActions.test.tsx
+++ b/src/features/AgentTasks/AgentTaskDetail/TaskDetailHeaderActions.test.tsx
@@ -161,14 +161,14 @@ describe('TaskDetailHeaderActions', () => {
expect(mocks.dropdownItems.map((item) => item?.key)).toContain('makePrivate');
});
- it('shows "make private" on public tasks for a workspace owner (non-creator)', () => {
+ it('hides "make private" from a workspace owner who is not the creator (LOBE-11760)', () => {
mocks.isWorkspaceOwner = true;
mocks.taskState.taskDetailMap = {
'T-1': { createdByUserId: 'someone-else', visibility: 'public' },
};
render(<TaskDetailHeaderActions />);
- expect(mocks.dropdownItems.map((item) => item?.key)).toContain('makePrivate');
+ expect(mocks.dropdownItems.map((item) => item?.key)).not.toContain('makePrivate');
});
it('hides "make private" from non-creator members', () => {
diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskDetailHeaderActions.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskDetailHeaderActions.tsx
index 6c1b4eed70b..de2e057b60a 100644
--- a/src/features/AgentTasks/AgentTaskDetail/TaskDetailHeaderActions.tsx
+++ b/src/features/AgentTasks/AgentTaskDetail/TaskDetailHeaderActions.tsx
@@ -7,7 +7,6 @@ import { useTranslation } from 'react-i18next';
import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';
-import { useIsWorkspaceOwner } from '@/business/client/hooks/useIsWorkspaceOwner';
import { useTaskTransferMenuItem } from '@/business/client/hooks/useTaskTransferMenuItem';
import VisibilityConfirmContent from '@/features/VisibilityConfirmContent';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
@@ -34,7 +33,6 @@ const TaskDetailHeaderActions = memo(() => {
const visibility = useTaskStore(taskDetailSelectors.activeTaskVisibility);
const createdByUserId = useTaskStore(taskDetailSelectors.activeTaskCreatedByUserId);
const currentUserId = useUserStore(userProfileSelectors.userId);
- const isWorkspaceOwner = useIsWorkspaceOwner();
const deleteTask = useTaskStore((s) => s.deleteTask);
const updateTaskVisibility = useTaskStore((s) => s.updateTaskVisibility);
const transferItems = useTaskTransferMenuItem(taskId) as DropdownItem[] | null;
@@ -152,11 +150,12 @@ const TaskDetailHeaderActions = memo(() => {
}
: null;
- // Inverse transition (LOBE-11551): only the task creator or a workspace
- // owner can pull a published task back to private; other members don't see
- // the entry at all (the server enforces the same rule as a backstop).
- const canMakePrivate =
- isWorkspaceOwner || (!!currentUserId && createdByUserId === currentUserId);
+ // Inverse transition (LOBE-11551): only the task creator can pull a
+ // published task back to private (LOBE-11760 β€” an owner demoting another
+ // member's task would appropriate it into the creator's private list);
+ // everyone else doesn't see the entry at all (the server enforces the
+ // same rule as a backstop).
+ const canMakePrivate = !!currentUserId && createdByUserId === currentUserId;
const makePrivateItem: DropdownItem | null =
activeWorkspaceId && visibility === 'public' && canMakePrivate
? {
@@ -189,7 +188,6 @@ const TaskDetailHeaderActions = memo(() => {
visibility,
createdByUserId,
currentUserId,
- isWorkspaceOwner,
t,
message,
triggerDelete,
diff --git a/src/features/DeviceManager/DeviceItem.tsx b/src/features/DeviceManager/DeviceItem.tsx
index 6cf28e51fbb..175921a1419 100644
--- a/src/features/DeviceManager/DeviceItem.tsx
+++ b/src/features/DeviceManager/DeviceItem.tsx
@@ -29,6 +29,8 @@ import { useTranslation } from 'react-i18next';
import VisibilityConfirmContent from '@/features/VisibilityConfirmContent';
import { lambdaQuery } from '@/libs/trpc/client';
+import { useUserStore } from '@/store/user';
+import { userProfileSelectors } from '@/store/user/selectors';
import { refreshDeviceList } from './const';
import { getDeviceIcon } from './getDeviceIcon';
@@ -175,6 +177,7 @@ const DeviceItem = memo<DeviceItemProps>(
const { t } = useTranslation('setting');
const { t: tCommon } = useTranslation('common');
const canEdit = useCanEditDevice()(device);
+ const currentUserId = useUserStore(userProfileSelectors.userId);
// Workspace devices are self-or-owner-gated + workspace-scoped on the
// server; personal devices stay userId-scoped. Route by the device's own
@@ -233,9 +236,13 @@ const DeviceItem = memo<DeviceItemProps>(
});
// Only persisted workspace rows carry a visibility to toggle β€” ghosts
- // (unregistered) and personal devices don't.
+ // (unregistered) and personal devices don't. The toggle is enroller-only
+ // (LOBE-11760): an owner demoting another member's public device would
+ // move it into that member's private list, appropriating their data. The
+ // server rejects non-enroller writes as the backstop.
+ const isEnroller = !!currentUserId && device.enroller?.userId === currentUserId;
const visibilityItems =
- device.scope === 'workspace' && device.registered
+ device.scope === 'workspace' && device.registered && isEnroller
? device.visibility === 'private'
? [
{
diff --git a/src/routes/(main)/home/_layout/Body/Agent/List/AgentItem/useDropdownMenu.tsx b/src/routes/(main)/home/_layout/Body/Agent/List/AgentItem/useDropdownMenu.tsx
index 23726882868..f8a6a9472d0 100644
--- a/src/routes/(main)/home/_layout/Body/Agent/List/AgentItem/useDropdownMenu.tsx
+++ b/src/routes/(main)/home/_layout/Body/Agent/List/AgentItem/useDropdownMenu.tsx
@@ -23,7 +23,6 @@ import { useTranslation } from 'react-i18next';
import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
import { useAgentTransferMenuItem } from '@/business/client/hooks/useAgentTransferMenuItem';
-import { useIsWorkspaceOwner } from '@/business/client/hooks/useIsWorkspaceOwner';
import { openEditingPopover } from '@/features/EditingPopover/store';
import VisibilityConfirmContent from '@/features/VisibilityConfirmContent';
import { usePermission } from '@/hooks/usePermission';
@@ -34,6 +33,8 @@ import { homeAgentListSelectors } from '@/store/home/selectors';
import { useUserStore } from '@/store/user';
import { userProfileSelectors } from '@/store/user/selectors';
+import { useRevealSidebarSection } from '../../../../hooks';
+
const BUILTIN_SLUGS = new Set<string>(Object.values(BUILTIN_AGENT_SLUGS));
interface UseAgentDropdownMenuParams {
@@ -88,11 +89,11 @@ export const useAgentDropdownMenu = ({
// Visibility actions are only meaningful inside a workspace: in personal
// mode every row is implicitly owner-private. "Publish to Workspace"
// appears on private agents; the inverse "Make private" (LOBE-11551)
- // appears on published agents, but only for the creator or a workspace
- // owner, and never on builtin agents (LobeAI etc.). The server enforces
- // the same rules as a backstop.
+ // appears on published agents, but only for the creator (LOBE-11760 β€”
+ // owners demoting another member's agent would appropriate it), and never
+ // on builtin agents (LobeAI etc.). The server enforces the same rules as
+ // a backstop.
const activeWorkspaceId = useActiveWorkspaceId();
- const isWorkspaceOwner = useIsWorkspaceOwner();
const currentUserId = useUserStore(userProfileSelectors.userId);
const isPrivate = visibility === 'private';
const isBuiltin = !!slug && BUILTIN_SLUGS.has(slug);
@@ -101,7 +102,8 @@ export const useAgentDropdownMenu = ({
Boolean(activeWorkspaceId) &&
visibility === 'public' &&
!isBuiltin &&
- (isWorkspaceOwner || (!!currentUserId && userId === currentUserId));
+ !!currentUserId &&
+ userId === currentUserId;
// Viewer has no write permissions on agents β€” disable every mutating menu
// item (pin/rename/duplicate/move/delete) while keeping the menu visible
@@ -119,6 +121,12 @@ export const useAgentDropdownMenu = ({
const isDefault = group === SessionDefaultGroup.Default;
+ // Visibility flips move the item across accordions. Reveal the destination
+ // section afterwards β€” with a collapsed/hidden target (stale persisted
+ // `sidebarExpandedKeys` predate newer sections) the item would silently
+ // vanish from the sidebar (LOBE-11758).
+ const revealSidebarSection = useRevealSidebarSection();
+
return useMemo(
() => () =>
[
@@ -214,6 +222,7 @@ export const useAgentDropdownMenu = ({
try {
await agentService.publishAgentToWorkspace(id);
await refreshAgentList();
+ revealSidebarSection('agent');
message.success(
t('agent.publishToWorkspaceSuccess', {
defaultValue: 'Published to workspace',
@@ -254,6 +263,7 @@ export const useAgentDropdownMenu = ({
try {
await agentService.setAgentVisibility(id, 'private');
await refreshAgentList();
+ revealSidebarSection('private');
message.success(t('makePrivate.success', { ns: 'common' }));
} catch (error) {
console.error('Failed to make agent private:', error);
@@ -307,6 +317,7 @@ export const useAgentDropdownMenu = ({
showPublishAction,
showMakePrivateAction,
refreshAgentList,
+ revealSidebarSection,
t,
],
);
diff --git a/src/routes/(main)/home/_layout/hooks/index.ts b/src/routes/(main)/home/_layout/hooks/index.ts
index fe3bbfbfee7..90e6f638f3f 100644
--- a/src/routes/(main)/home/_layout/hooks/index.ts
+++ b/src/routes/(main)/home/_layout/hooks/index.ts
@@ -1,3 +1,4 @@
export { useCreateMenuItems } from './useCreateMenuItems';
export { useProjectMenuItems } from './useProjectMenuItems';
+export { useRevealSidebarSection } from './useRevealSidebarSection';
export { useSessionGroupMenuItems } from './useSessionGroupMenuItems';
diff --git a/src/routes/(main)/home/_layout/hooks/useRevealSidebarSection.test.ts b/src/routes/(main)/home/_layout/hooks/useRevealSidebarSection.test.ts
new file mode 100644
index 00000000000..493522fad6b
--- /dev/null
+++ b/src/routes/(main)/home/_layout/hooks/useRevealSidebarSection.test.ts
@@ -0,0 +1,39 @@
+import { describe, expect, it } from 'vitest';
+
+import { buildRevealSidebarSectionPatch } from './useRevealSidebarSection';
+
+describe('buildRevealSidebarSectionPatch (LOBE-11758)', () => {
+ it('expands a collapsed section', () => {
+ // Stale persisted keys from before the Private section shipped.
+ expect(buildRevealSidebarSectionPatch('private', ['recents', 'agent'], [])).toEqual({
+ sidebarExpandedKeys: ['recents', 'agent', 'private'],
+ });
+ });
+
+ it('un-hides a hidden section', () => {
+ expect(
+ buildRevealSidebarSectionPatch('private', ['recents', 'agent', 'private'], ['private']),
+ ).toEqual({
+ hiddenSidebarSections: [],
+ });
+ });
+
+ it('expands and un-hides in one patch', () => {
+ expect(buildRevealSidebarSectionPatch('private', ['agent'], ['recents', 'private'])).toEqual({
+ hiddenSidebarSections: ['recents'],
+ sidebarExpandedKeys: ['agent', 'private'],
+ });
+ });
+
+ it('returns null when the section is already visible', () => {
+ expect(
+ buildRevealSidebarSectionPatch('private', ['recents', 'agent', 'private'], ['recents']),
+ ).toBeNull();
+ });
+
+ it('handles the workspace (agent) section for the publish direction', () => {
+ expect(buildRevealSidebarSectionPatch('agent', ['recents', 'private'], [])).toEqual({
+ sidebarExpandedKeys: ['recents', 'private', 'agent'],
+ });
+ });
+});
diff --git a/src/routes/(main)/home/_layout/hooks/useRevealSidebarSection.ts b/src/routes/(main)/home/_layout/hooks/useRevealSidebarSection.ts
new file mode 100644
index 00000000000..6923f73f7de
--- /dev/null
+++ b/src/routes/(main)/home/_layout/hooks/useRevealSidebarSection.ts
@@ -0,0 +1,66 @@
+import { useCallback } from 'react';
+
+import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
+import { useGlobalStore } from '@/store/global';
+import { type SystemStatus } from '@/store/global/initialState';
+import { systemStatusSelectors } from '@/store/global/selectors';
+
+/**
+ * Section keys of the home sidebar accordions. Mirrors `GroupKey` in
+ * `../Body` β€” not imported from there to avoid a hooks ⇄ Body import cycle
+ * (Body renders sections that consume these hooks).
+ */
+export type RevealableSidebarSection = 'agent' | 'private';
+
+/**
+ * Compute the system-status patch that makes a sidebar section visible after
+ * an action moved content into it: expand the accordion and clear a
+ * user-applied section hide. Returns `null` when the section is already
+ * fully visible so callers can skip the store write.
+ *
+ * Why this exists (LOBE-11758): `sidebarExpandedKeys` is persisted, so
+ * accounts whose keys were saved before a section shipped (e.g. `private`,
+ * added with workspace private agents) never include the new key β€” the
+ * section stays collapsed forever. "Make private" then moves the agent into
+ * a collapsed (or hidden) Private section with zero visual feedback, which
+ * reads as the agent silently disappearing.
+ */
+export const buildRevealSidebarSectionPatch = (
+ section: RevealableSidebarSection,
+ expandedKeys: string[],
+ hiddenSections: string[],
+): Partial<SystemStatus> | null => {
+ const patch: Partial<SystemStatus> = {};
+
+ if (!expandedKeys.includes(section)) patch.sidebarExpandedKeys = [...expandedKeys, section];
+ if (hiddenSections.includes(section))
+ patch.hiddenSidebarSections = hiddenSections.filter((key) => key !== section);
+
+ return Object.keys(patch).length > 0 ? patch : null;
+};
+
+/**
+ * Returns a callback that reveals a home-sidebar section (expands the
+ * accordion and un-hides it) in the ACTIVE scope β€” `updateSystemStatus`
+ * routes the write into the workspace overlay when inside a workspace, so
+ * personal-mode preferences stay untouched.
+ *
+ * Call it after an action whose result lands in that section (e.g. "Make
+ * private" β†’ `private`, "Publish to Workspace" β†’ `agent`); a result the user
+ * cannot see is indistinguishable from data loss.
+ */
+export const useRevealSidebarSection = () => {
+ const activeWorkspaceId = useActiveWorkspaceId();
+
+ return useCallback(
+ (section: RevealableSidebarSection) => {
+ const state = useGlobalStore.getState();
+ const expandedKeys = systemStatusSelectors.sidebarExpandedKeys(activeWorkspaceId)(state);
+ const hiddenSections = systemStatusSelectors.hiddenSidebarSections(activeWorkspaceId)(state);
+
+ const patch = buildRevealSidebarSectionPatch(section, expandedKeys, hiddenSections);
+ if (patch) state.updateSystemStatus(patch);
+ },
+ [activeWorkspaceId],
+ );
+};