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: optimize workspace (#16859)

Rdmclin2cde5a8025f06
diff --git a/.agents/skills/agent-testing/SKILL.md b/.agents/skills/agent-testing/SKILL.md
index ace19e10e1f..f7b5477fa1b 100644
--- a/.agents/skills/agent-testing/SKILL.md
+++ b/.agents/skills/agent-testing/SKILL.md
@@ -47,6 +47,12 @@ this run:
(Wrong approach / Why / What it breaks / Correct approach).
- You hit any probe/mock that is blocked, bypassed, or needs a workaround → new
item in `probe-mock-patterns.md` (Situation / Doesn't work / Works).
+- **Confidentiality — this skill ships in the open-source repository.** Keep
+ appended entries product-generic: never include details that only exist in a
+ private/commercial superproject (its packages, routes, DB schemas, env vars,
+ service names, or business logic). Record those learnings in the
+ superproject's own skills/notes instead, and genericize anything worth
+ keeping here.
## Step -1 — Plan approval for non-trivial tests
diff --git a/.agents/skills/agent-testing/references/common-mistakes.md b/.agents/skills/agent-testing/references/common-mistakes.md
index 45f621ff0ca..428c188b40a 100644
--- a/.agents/skills/agent-testing/references/common-mistakes.md
+++ b/.agents/skills/agent-testing/references/common-mistakes.md
@@ -299,3 +299,28 @@ selected context never reached the assistant.
last mile: add or run an integration-level assertion against the transformed
messages/request body (e.g. `MessagesEngine` output or transport payload), and
only treat the UI chip/store as supporting evidence.
+
+---
+
+## Case 13 — GIF evidence ending on an expected-failure frame reads as "the page failed to load"
+
+**Wrong approach**: for a loading-skeleton case, attaching a GIF that records the
+full timeline — skeleton (the asserted state) followed by the error page that the
+test data inevitably produces (fake ids / dummy provider keys mean the route can
+only end in its error state). The GIF loops and rests on its final frames, so the
+viewer opens the report and sees the error card, not the skeleton.
+
+**Why it's wrong**: same trap as Case 5 (unlabeled before-shot) in time-based
+form — the LAST frame of a GIF is its de-facto headline. An expected-failure
+terminal state without explanation reads as the case failing (" 这里怎么加载失败
+了 "), even when the asserted behavior (the skeleton) passed.
+
+**What it breaks**: the user reads a passed case as a load failure and a round is
+burned re-explaining the evidence.
+
+**Correct approach**: trim evidence to the asserted state — end the GIF on the
+skeleton/loading phase (cut the frames after the terminal state appears), or
+attach the static shot of the asserted state as the primary evidence. If the
+expected-failure terminal state is worth showing, say so explicitly in the
+case's `observation` ("ends in the error page because the test session id is
+fake — expected, not the assertion") so the viewer is told before they see it.
diff --git a/.agents/skills/agent-testing/references/probe-mock-patterns.md b/.agents/skills/agent-testing/references/probe-mock-patterns.md
index 80beaff5a37..765517fd207 100644
--- a/.agents/skills/agent-testing/references/probe-mock-patterns.md
+++ b/.agents/skills/agent-testing/references/probe-mock-patterns.md
@@ -467,3 +467,45 @@
available.
- **Works**: use the numeric `electron-dev.sh start <id>` pool path, or keep
manual IPC ids very short, e.g. `LOBE_IPC_ID=lhmsel2`.
+
+### E5. ✅ WORKS — no-Docker fallback stack for the isolated no-.env env
+
+- **Situation**: `init-dev-env.sh setup-db` needs Docker (paradedb + redis images), but
+ Docker Desktop's VM can wedge indefinitely (`no route to host` to 192.168.65.x, empty
+ vm/console.log). Verified working substitute:
+ - **Postgres**: local brew Postgres 17 (pgvector available). The only paradedb-specific
+ migrations are `0090_enable_pg_search` / `0093_add_bm25_indexes_with_icu` — no-op them
+ in the worktree (`SELECT 1;`), everything else applies clean.
+ - **Redis is a hard dependency of Better Auth sign-in** — with a dead REDIS\_URL the seed
+ login 500s (`[Better Auth]: Error: Connection is closed`). `brew install redis`,
+ `redis-server --port 6380 --daemonize yes`.
+ - **S3**: `s3rver` (npm) on 29000 with a CORS config for the bucket. Its presigned-URL
+ validation only accepts key id `S3RVER` (secret `S3RVER`) — `allowMismatchedSignatures`
+ does NOT rescue an unknown access key id (403 on the browser preflight). Set the dev
+ server's `S3_ACCESS_KEY_ID/S3_SECRET_ACCESS_KEY=S3RVER`, `S3_ENABLE_PATH_STYLE=1`,
+ `S3_PUBLIC_DOMAIN=http://127.0.0.1:29000/<bucket>`.
+
+### E6. code-inspector-plugin breaks Turbopack compile of Next-served authed pages
+
+- **Situation**: the first AUTHENTICATED render of a Next-served (non-SPA) page whose client
+ graph pulls the chat store dies in `next dev` (Turbopack) with Build Error `Resource path
+"worker/browser/createWorker.ts" needs to be on project filesystem` (chain: layout →
+ GlobalProvider/Query → trpc client → image/chat store → python-interpreter worker).
+ Unauthenticated curl 302s BEFORE the client graph compiles, so it false-passes; a fresh
+ no-lockfile `pnpm install` can resolve a broken plugin version.
+- **Works**: `E2E=1` (or `TEST=1`) — `defineConfig`'s `isTest` skips `codeInspectorPlugin`,
+ the only thing it gates. Webpack mode (`next dev --webpack`) is NOT a viable fallback
+ (react version mismatch when two next versions are hoisted; `zlib-sync` unresolved for
+ discord.js).
+
+### D12. agent-browser daemon serializes commands — `open` queues behind a record-gif loop
+
+- **Situation**: `record-gif.sh` (a screenshot loop) running while you issue
+ `agent-browser open <url>` — the daemon socket serializes, the open lands late/out of
+ order, and your "during navigation" screenshot actually shows the PREVIOUS page (which can
+ look identical to the expected end state — false read).
+- **Works**: during any recording loop, navigate with
+ `agent-browser eval 'location.href="<url>"'` (fire-and-forget) instead of `open`. To hold
+ a streaming loading state on screen, inject a server-side `await sleep(8000)` before the
+ slow lookup in the page (\[AGENT-TEST], revert) — TTFB stays \~0.3s so loading.tsx renders
+ while the route hangs, giving a wide static-capture window.
diff --git a/apps/server/src/routers/lambda/__tests__/agent.test.ts b/apps/server/src/routers/lambda/__tests__/agent.test.ts
index fa615f6ec49..d6c52f7be80 100644
--- a/apps/server/src/routers/lambda/__tests__/agent.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/agent.test.ts
@@ -7,6 +7,7 @@ import { AgentModel } from '@/database/models/agent';
import { FileModel } from '@/database/models/file';
import { KnowledgeBaseModel } from '@/database/models/knowledgeBase';
import { SessionModel } from '@/database/models/session';
+import { TaskModel } from '@/database/models/task';
import { UserModel } from '@/database/models/user';
import { AgentService } from '@/server/services/agent';
import { EditLockService } from '@/server/services/editLock';
@@ -33,6 +34,10 @@ vi.mock('@/database/models/session', () => ({
SessionModel: vi.fn(),
}));
+vi.mock('@/database/models/task', () => ({
+ TaskModel: vi.fn(),
+}));
+
vi.mock('@/database/models/file', () => ({
FileModel: vi.fn(),
}));
@@ -49,6 +54,7 @@ describe('agentRouter', () => {
const userId = 'testUserId';
let mockCtx: any;
let agentModelMock: any;
+ let taskModelMock: any;
let sessionModelMock: any;
let fileModelMock: any;
let knowledgeBaseModelMock: any;
@@ -71,6 +77,11 @@ describe('agentRouter', () => {
};
vi.mocked(AgentModel).mockImplementation(() => agentModelMock);
+ taskModelMock = {
+ countTasksBlockingAgentDemotion: vi.fn().mockResolvedValue(0),
+ };
+ vi.mocked(TaskModel).mockImplementation(() => taskModelMock);
+
sessionModelMock = {
findByIdOrSlug: vi.fn(),
};
@@ -345,6 +356,56 @@ describe('agentRouter', () => {
});
});
+ describe('setAgentVisibility', () => {
+ const wsCtx = () => ({ ...mockCtx, workspaceId: 'ws-1' });
+
+ beforeEach(() => {
+ agentModelMock.getAgentVisibilityMeta = vi.fn().mockResolvedValue({
+ slug: null,
+ userId,
+ visibility: 'public',
+ });
+ agentModelMock.setVisibility = vi.fn().mockResolvedValue({ id: 'agent-1' });
+ });
+
+ it('rejects demotion while workspace tasks still depend on the agent', async () => {
+ taskModelMock.countTasksBlockingAgentDemotion.mockResolvedValue(2);
+
+ const caller = agentRouter.createCaller(wsCtx());
+
+ await expect(
+ caller.setAgentVisibility({ id: 'agent-1', visibility: 'private' }),
+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });
+ // Compared against the agent owner (meta.userId), not just the caller.
+ expect(taskModelMock.countTasksBlockingAgentDemotion).toHaveBeenCalledWith('agent-1', userId);
+ expect(agentModelMock.setVisibility).not.toHaveBeenCalled();
+ });
+
+ it('allows demotion when no task depends on the agent', async () => {
+ taskModelMock.countTasksBlockingAgentDemotion.mockResolvedValue(0);
+
+ const caller = agentRouter.createCaller(wsCtx());
+ const result = await caller.setAgentVisibility({ id: 'agent-1', visibility: 'private' });
+
+ expect(result).toEqual({ success: true });
+ expect(agentModelMock.setVisibility).toHaveBeenCalledWith('agent-1', 'private');
+ });
+
+ it('does not run the public-task guard on promotion', async () => {
+ agentModelMock.getAgentVisibilityMeta.mockResolvedValue({
+ slug: null,
+ userId,
+ visibility: 'private',
+ });
+
+ const caller = agentRouter.createCaller(wsCtx());
+ await caller.setAgentVisibility({ id: 'agent-1', visibility: 'public' });
+
+ expect(taskModelMock.countTasksBlockingAgentDemotion).not.toHaveBeenCalled();
+ expect(agentModelMock.setVisibility).toHaveBeenCalledWith('agent-1', 'public');
+ });
+ });
+
describe('edit lock', () => {
const wsCtx = () => ({ ...mockCtx, workspaceId: 'ws-1' });
diff --git a/apps/server/src/routers/lambda/agent.ts b/apps/server/src/routers/lambda/agent.ts
index 5ffc8c0efa8..ceb79cd3d88 100644
--- a/apps/server/src/routers/lambda/agent.ts
+++ b/apps/server/src/routers/lambda/agent.ts
@@ -1,3 +1,4 @@
+import { BUILTIN_AGENT_SLUGS } from '@lobechat/builtin-agents';
import { DEFAULT_AGENT_CONFIG, INBOX_SESSION_ID } from '@lobechat/const';
import { CreateAgentSchema, type KnowledgeItem } from '@lobechat/types';
import { KnowledgeType } from '@lobechat/types';
@@ -11,6 +12,7 @@ import { ChatGroupModel } from '@/database/models/chatGroup';
import { FileModel } from '@/database/models/file';
import { KnowledgeBaseModel } from '@/database/models/knowledgeBase';
import { SessionModel } from '@/database/models/session';
+import { TaskModel } from '@/database/models/task';
import { UserModel } from '@/database/models/user';
import { router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
@@ -97,10 +99,10 @@ export const agentRouter = router({
}),
/**
- * Publish a private agent into the workspace. **One-way** — once an agent
- * is shared, workspace members may already depend on it, so it can't slip
- * back to `private`. Only the creator of a still-private agent can run
- * this; the underlying SQL enforces both rules.
+ * 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.
*/
publishAgentToWorkspace: agentProcedure
.use(withScopedPermission('agent:update'))
@@ -109,6 +111,74 @@ export const agentRouter = router({
return ctx.agentModel.publishToWorkspace(input.id);
}),
+ /**
+ * 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.
+ */
+ setAgentVisibility: agentProcedure
+ .use(withScopedPermission('agent:update'))
+ .input(z.object({ id: z.string(), visibility: z.enum(['private', 'public']) }))
+ .mutation(async ({ input, ctx }) => {
+ const meta = await ctx.agentModel.getAgentVisibilityMeta(input.id);
+ if (!meta) throw new TRPCError({ code: 'NOT_FOUND', message: 'Agent not found' });
+
+ if (meta.slug && Object.values(BUILTIN_AGENT_SLUGS).includes(meta.slug as any)) {
+ throw new TRPCError({
+ code: 'FORBIDDEN',
+ message: 'Builtin agents cannot change visibility',
+ });
+ }
+
+ if (meta.visibility === input.visibility) return { success: true };
+
+ if (ctx.workspaceId && meta.userId !== ctx.userId) {
+ const canOverride = await hasWorkspaceScopedPermission({
+ action: 'AGENT_UPDATE',
+ db: ctx.serverDB,
+ scopes: ['ALL'],
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
+ });
+ if (!canOverride) {
+ throw new TRPCError({
+ code: 'FORBIDDEN',
+ message: 'Only the agent creator or workspace owner can change visibility',
+ });
+ }
+ }
+
+ // Demoting an agent must not strand tasks that depend on it: public
+ // tasks would violate the `assertAgentVisibilityCompat` invariant
+ // (members keep seeing the task but can no longer see or run the
+ // assignee), and other members' tasks — private ones included — would
+ // fail future runs/updates because their creators can no longer
+ // resolve the agent. Reject early — reassign or demote those tasks
+ // first.
+ if (input.visibility === 'private' && ctx.workspaceId) {
+ const taskModel = new TaskModel(ctx.serverDB, ctx.userId, ctx.workspaceId);
+ const blockingTasks = await taskModel.countTasksBlockingAgentDemotion(
+ input.id,
+ meta.userId,
+ );
+ if (blockingTasks > 0) {
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message:
+ 'Cannot make this agent private while workspace tasks still depend on it. Reassign those tasks or make them private first.',
+ });
+ }
+ }
+
+ const updated = await ctx.agentModel.setVisibility(input.id, input.visibility);
+ if (!updated) throw new TRPCError({ code: 'NOT_FOUND', message: 'Agent not found' });
+
+ return { success: true };
+ }),
+
createAgentFiles: agentProcedure
.use(withScopedPermission('agent:update'))
.input(
diff --git a/apps/server/src/routers/lambda/task.ts b/apps/server/src/routers/lambda/task.ts
index 9f5ffff6eff..4fb38151868 100644
--- a/apps/server/src/routers/lambda/task.ts
+++ b/apps/server/src/routers/lambda/task.ts
@@ -1071,22 +1071,6 @@ export const taskRouter = router({
try {
const resolved = await resolveOrThrow(ctx.taskModel, input.id);
- // Visibility is a one-way commitment: once a task is published to the
- // workspace, retracting it back to private would yank a resource other
- // members may already be running, referencing, or commenting on. The
- // product surface enforces this via a "Publish to Workspace" action
- // that has no inverse — any caller asking for public→private here is
- // either a stale UI path or a direct API client and should be rejected.
- // Placed before the edit-lock check because the invariant is schema-
- // level, not concurrency-level: there is no legitimate "wait for the
- // lock and try again" outcome.
- if (resolved.visibility === 'public' && input.visibility === 'private') {
- throw new TRPCError({
- code: 'BAD_REQUEST',
- message: 'Task visibility cannot be reverted from public to private',
- });
- }
-
// Mirror the edit-lock contract from `update`: reject visibility flips
// while another workspace member is actively editing this task. Without
// this check a collaborator could silently retitle a private task to
@@ -1122,6 +1106,25 @@ export const taskRouter = router({
}
}
+ // Demoting a mixed-creator subtree would fracture it: each descendant
+ // stays owned by its creator, so the root creator loses other
+ // members' subtasks while those members keep orphaned children whose
+ // parent is hidden. Reject early — the subtree must be single-creator
+ // to go private.
+ if (input.visibility === 'private') {
+ const hasOtherCreators = await ctx.taskModel.subtreeHasOtherCreators(
+ resolved.id,
+ resolved.createdByUserId,
+ );
+ if (hasOtherCreators) {
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message:
+ 'Cannot make this task private while it has subtasks created by other members. Reassign or remove those subtasks first.',
+ });
+ }
+ }
+
// Promoting a task to public while a private agent is its assignee
// breaks the visibility invariant. Reject early — the user should
// reassign first, then promote.
diff --git a/apps/server/src/services/document/__tests__/index.test.ts b/apps/server/src/services/document/__tests__/index.test.ts
index bd0d20cd8df..9bfcdf77f63 100644
--- a/apps/server/src/services/document/__tests__/index.test.ts
+++ b/apps/server/src/services/document/__tests__/index.test.ts
@@ -908,6 +908,22 @@ describe('DocumentService', () => {
expect(mockDocumentModel.update).not.toHaveBeenCalled();
});
+ it('skips the lock guard for private-visibility workspace documents', async () => {
+ // Private rows are creator-only; a leftover lease from a publish →
+ // unpublish flip must not turn every autosave into a CONFLICT loop.
+ const wsService = new DocumentService(mockDb, userId, 'ws-1');
+ mockDocumentModel.update.mockResolvedValue({ id: 'doc-1' });
+ mockDocumentModel.findById.mockResolvedValue(
+ createCurrentDocument({ visibility: 'private', workspaceId: 'ws-1' }),
+ );
+ const guardSpy = vi.spyOn(EditLockService.prototype, 'canWrite').mockResolvedValue(false);
+
+ await wsService.updateDocument('doc-1', { content: 'x', lockOwnerId: 'stale-owner' });
+
+ expect(guardSpy).not.toHaveBeenCalled();
+ expect(mockDocumentModel.update).toHaveBeenCalled();
+ });
+
it('should allow a workspace save when no other member holds the lock', async () => {
const wsService = new DocumentService(mockDb, userId, 'ws-1');
mockDocumentModel.update.mockResolvedValue({ id: 'doc-1' });
@@ -970,6 +986,31 @@ describe('DocumentService', () => {
});
describe('runWithDocumentLock', () => {
+ beforeEach(() => {
+ // Workspace-shared doc by default; the lock only applies to these.
+ mockDocumentModel.findById.mockResolvedValue({
+ id: 'doc-1',
+ visibility: 'public',
+ workspaceId: 'ws-1',
+ });
+ });
+
+ it('runs the callback without touching the lock for private-visibility documents', async () => {
+ const wsService = new DocumentService(mockDb, userId, 'ws-1');
+ mockDocumentModel.findById.mockResolvedValue({
+ id: 'doc-1',
+ visibility: 'private',
+ workspaceId: 'ws-1',
+ });
+ const acquireSpy = vi.spyOn(EditLockService.prototype, 'acquire');
+ const fn = vi.fn().mockResolvedValue('ok');
+
+ const result = await wsService.runWithDocumentLock('doc-1', fn);
+
+ expect(result).toBe('ok');
+ expect(acquireSpy).not.toHaveBeenCalled();
+ });
+
it('runs the callback without touching the lock for personal documents', async () => {
const acquireSpy = vi.spyOn(EditLockService.prototype, 'acquire');
const releaseSpy = vi.spyOn(EditLockService.prototype, 'release');
@@ -1120,6 +1161,59 @@ describe('DocumentService', () => {
});
describe('document edit lock', () => {
+ beforeEach(() => {
+ // Workspace-shared doc by default; the lock only applies to these.
+ mockDocumentModel.findById.mockResolvedValue({
+ id: 'doc-1',
+ visibility: 'public',
+ workspaceId: 'ws-1',
+ });
+ });
+
+ it('acquireDocumentLock reports unlocked for private-visibility documents', async () => {
+ const wsService = new DocumentService(mockDb, userId, 'ws-1');
+ mockDocumentModel.findById.mockResolvedValue({
+ id: 'doc-1',
+ visibility: 'private',
+ workspaceId: 'ws-1',
+ });
+ const acquireSpy = vi.spyOn(EditLockService.prototype, 'acquire');
+
+ const result = await wsService.acquireDocumentLock('doc-1');
+
+ expect(result).toEqual({
+ expiresAt: null,
+ holderId: null,
+ lockedByOther: false,
+ ownerId: null,
+ });
+ expect(acquireSpy).not.toHaveBeenCalled();
+ });
+
+ it('getDocumentLock reads as unlocked for private-visibility documents', async () => {
+ const wsService = new DocumentService(mockDb, userId, 'ws-1');
+ mockDocumentModel.findById.mockResolvedValue({
+ id: 'doc-1',
+ visibility: 'private',
+ workspaceId: 'ws-1',
+ });
+ // Even a leftover lease from before an unpublish must not surface.
+ vi.spyOn(EditLockService.prototype, 'getActiveLock').mockResolvedValue({
+ expiresAt: new Date(),
+ ownerId: 'stale-owner',
+ userId: 'other-user',
+ });
+
+ const result = await wsService.getDocumentLock('doc-1');
+
+ expect(result).toEqual({
+ expiresAt: null,
+ holderId: null,
+ lockedByOther: false,
+ ownerId: null,
+ });
+ });
+
it('reports unlocked for personal documents without touching the lock service', async () => {
const acquireSpy = vi.spyOn(EditLockService.prototype, 'acquire');
@@ -1311,7 +1405,12 @@ describe('DocumentService', () => {
it('rejects a workspace history snapshot when another member holds the lock', async () => {
const wsService = new DocumentService(mockDb, userId, 'ws-1');
- mockDocumentModel.findById.mockResolvedValue({ id: 'doc-1', editorData: { blocks: [] } });
+ mockDocumentModel.findById.mockResolvedValue({
+ editorData: { blocks: [] },
+ id: 'doc-1',
+ visibility: 'public',
+ workspaceId: 'ws-1',
+ });
vi.spyOn(EditLockService.prototype, 'canWrite').mockResolvedValue(false);
await expect(
@@ -1322,7 +1421,12 @@ describe('DocumentService', () => {
it('allows a workspace history snapshot when no other member holds the lock', async () => {
const wsService = new DocumentService(mockDb, userId, 'ws-1');
- mockDocumentModel.findById.mockResolvedValue({ id: 'doc-1', editorData: { blocks: [] } });
+ mockDocumentModel.findById.mockResolvedValue({
+ editorData: { blocks: [] },
+ id: 'doc-1',
+ visibility: 'public',
+ workspaceId: 'ws-1',
+ });
vi.spyOn(EditLockService.prototype, 'canWrite').mockResolvedValue(true);
await wsService.saveDocumentHistory('doc-1', { blocks: [] }, 'llm_call');
@@ -1330,9 +1434,30 @@ describe('DocumentService', () => {
expect(mockDocumentHistoryService.createHistory).toHaveBeenCalled();
});
+ it('does not check the lock for private-visibility workspace documents', async () => {
+ const wsService = new DocumentService(mockDb, userId, 'ws-1');
+ mockDocumentModel.findById.mockResolvedValue({
+ editorData: { blocks: [] },
+ id: 'doc-1',
+ visibility: 'private',
+ workspaceId: 'ws-1',
+ });
+ const guardSpy = vi.spyOn(EditLockService.prototype, 'canWrite');
+
+ await wsService.saveDocumentHistory('doc-1', { blocks: [] }, 'llm_call');
+
+ expect(guardSpy).not.toHaveBeenCalled();
+ expect(mockDocumentHistoryService.createHistory).toHaveBeenCalled();
+ });
+
it('forwards the lock owner so the holder can snapshot its own page', async () => {
const wsService = new DocumentService(mockDb, userId, 'ws-1');
- mockDocumentModel.findById.mockResolvedValue({ id: 'doc-1', editorData: { blocks: [] } });
+ mockDocumentModel.findById.mockResolvedValue({
+ editorData: { blocks: [] },
+ id: 'doc-1',
+ visibility: 'public',
+ workspaceId: 'ws-1',
+ });
const guardSpy = vi.spyOn(EditLockService.prototype, 'canWrite').mockResolvedValue(true);
await wsService.saveDocumentHistory('doc-1', { blocks: [] }, 'llm_call', 'page-owner-1');
diff --git a/apps/server/src/services/document/index.ts b/apps/server/src/services/document/index.ts
index bb3ab6a3ea7..679fbf7bcfe 100644
--- a/apps/server/src/services/document/index.ts
+++ b/apps/server/src/services/document/index.ts
@@ -92,6 +92,21 @@ export class DocumentService {
return this.documentHistoryServiceInstance;
}
+ /**
+ * Whether a document participates in collaborative edit locking. Only
+ * workspace documents other members can actually open need the lock:
+ * a `visibility: 'private'` row is creator-only (buildWorkspaceWhere hides it
+ * from everyone else), so locking it can only ever conflict the creator with
+ * themselves — e.g. a stale lease left behind by a publish → unpublish flip
+ * turning every autosave into a CONFLICT loop. NULL visibility is treated as
+ * public, mirroring buildWorkspaceWhere.
+ */
+ private isCollaborativeDocument(
+ doc: Pick<DocumentItem, 'visibility' | 'workspaceId'> | null | undefined,
+ ): boolean {
+ return Boolean(this.workspaceId && doc?.workspaceId && doc.visibility !== 'private');
+ }
+
private async deleteFileRecordAndStorage(fileId: string) {
const file = await this.fileModel.delete(fileId);
if (!file?.url || file.url.startsWith('internal://')) return;
@@ -285,6 +300,13 @@ export class DocumentService {
if (!this.workspaceId)
return { expiresAt: null, holderId: null, lockedByOther: false, ownerId: null };
+ // Creator-only (private-visibility) documents never take a lease — see
+ // isCollaborativeDocument. Refusing here keeps a stale client from minting
+ // a lock the write guards would then trip over.
+ const doc = await this.documentModel.findById(id);
+ if (!this.isCollaborativeDocument(doc))
+ return { expiresAt: null, holderId: null, lockedByOther: false, ownerId: null };
+
const prevHolder = await this.editLockService.getActiveLock('document', id);
const result = await this.editLockService.acquire('document', id, ownerId);
@@ -319,6 +341,12 @@ export class DocumentService {
async getDocumentLock(id: string, ownerId?: string): Promise<DocumentLockResult> {
if (!this.workspaceId)
return { expiresAt: null, holderId: null, lockedByOther: false, ownerId: null };
+ // Private-visibility documents always read as unlocked (no lease can be
+ // taken on them), so a viewer of a just-unpublished page is never stranded
+ // read-only behind a leftover lease.
+ const doc = await this.documentModel.findById(id);
+ if (!this.isCollaborativeDocument(doc))
+ return { expiresAt: null, holderId: null, lockedByOther: false, ownerId: null };
const holder = await this.editLockService.getActiveLock('document', id);
const lockedByOther = holder
? holder.ownerId
@@ -377,6 +405,14 @@ export class DocumentService {
return fn();
}
+ // Creator-only (private-visibility) documents have no collaborators to
+ // serialize against — run without a lease, same as personal mode.
+ const targetDoc = await this.documentModel.findById(id);
+ if (!this.isCollaborativeDocument(targetDoc)) {
+ log('runWithDocumentLock skip: non-collaborative doc (id=%s userId=%s)', id, this.userId);
+ return fn();
+ }
+
// If this user's live editor already holds the lease, ride along on the
// same ownerId so the acquire below is a pure heartbeat. Stealing the lock
// with a fresh `server:UUID` would silently rewrite the lease's ownerId,
@@ -459,7 +495,7 @@ export class DocumentService {
// can't pollute the version timeline. The lock holder forwards its
// `lockOwnerId` so it can still snapshot its own page (e.g. the pre-mutation
// snapshot a Copilot edit takes) without being blocked by its own lease.
- if (this.workspaceId) {
+ if (this.isCollaborativeDocument(currentDocument)) {
const canWrite = await this.editLockService.canWrite('document', documentId, lockOwnerId);
if (!canWrite) {
throw new TRPCError({
@@ -610,7 +646,7 @@ export class DocumentService {
const contentChanged =
historyAppended ||
(params.content !== undefined && params.content !== currentDocument.content);
- if (this.workspaceId && contentChanged) {
+ if (contentChanged && this.isCollaborativeDocument(currentDocument)) {
const canWrite = await this.editLockService.canWrite('document', id, params.lockOwnerId);
if (!canWrite) {
throw new TRPCError({
diff --git a/apps/server/src/services/task/index.ts b/apps/server/src/services/task/index.ts
index 6c7baad816f..1e090a62470 100644
--- a/apps/server/src/services/task/index.ts
+++ b/apps/server/src/services/task/index.ts
@@ -787,6 +787,7 @@ export class TaskService {
checkpoint: this.taskModel.getCheckpointConfig(task),
config: taskConfig,
createdAt: task.createdAt ? new Date(task.createdAt).toISOString() : undefined,
+ createdByUserId: task.createdByUserId,
dependencies: dependencies.map((d) => {
const info = depIdToInfo.get(d.dependsOnId);
return {
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index 32431e74187..834e47780d5 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -3,7 +3,6 @@
"active": "Active",
"addAgentFromMarket": "Add from Market",
"agent.publishToWorkspace": "Publish to Workspace",
- "agent.publishToWorkspaceConfirm": "Other workspace members will be able to use this agent. You will not be able to make it private again.",
"agent.publishToWorkspaceSuccess": "Published to workspace",
"agentBuilder.installPlugin.authRequired": "Cloud MCP requires sign-in to continue",
"agentBuilder.installPlugin.cancel": "Cancel",
@@ -829,7 +828,6 @@
"taskDetail.priority.normal": "Normal",
"taskDetail.priority.urgent": "Urgent",
"taskDetail.properties": "Properties",
- "taskDetail.publishToWorkspace.confirmContent": "Once published, this task becomes visible to all workspace members and cannot be reverted to private.",
"taskDetail.publishToWorkspace.confirmHint": "Past runs remain private. Only runs created after publishing will be visible to workspace members.",
"taskDetail.publishToWorkspace.confirmOk": "Publish",
"taskDetail.publishToWorkspace.confirmTitle": "Publish task to workspace?",
diff --git a/locales/en-US/setting.json b/locales/en-US/setting.json
index 8c0205b40e1..ad199e8c75b 100644
--- a/locales/en-US/setting.json
+++ b/locales/en-US/setting.json
@@ -1906,7 +1906,7 @@
"workspace.create.submit": "Create workspace",
"workspace.create.title": "Create a new workspace",
"workspace.description.title": "Description",
- "workspace.general.avatar.description": "This is your workspace's avatar.",
+ "workspace.general.avatar.description": "This is your workspace's avatar. Click on the avatar to upload a custom one from your files.",
"workspace.general.avatar.hint": "An avatar is optional but strongly recommended.",
"workspace.general.avatar.title": "Workspace Avatar",
"workspace.general.avatar.tooLarge": "Avatar file must be smaller than 5MB.",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 8a02ffe8e61..a224f4e231f 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -3,7 +3,6 @@
"active": "活跃",
"addAgentFromMarket": "从市场添加助理",
"agent.publishToWorkspace": "发布到工作区",
- "agent.publishToWorkspaceConfirm": "工作区的其他成员将可以使用该助理,发布后无法再设为私人。",
"agent.publishToWorkspaceSuccess": "已发布到工作区",
"agentBuilder.installPlugin.authRequired": "云端 MCP 需要登录后才能继续",
"agentBuilder.installPlugin.cancel": "取消",
@@ -829,7 +828,6 @@
"taskDetail.priority.normal": "普通",
"taskDetail.priority.urgent": "紧急",
"taskDetail.properties": "属性",
- "taskDetail.publishToWorkspace.confirmContent": "发布后所有工作区成员(包括您)都可以看到此任务,且无法转回私人。",
"taskDetail.publishToWorkspace.confirmHint": "历史运行仍保持私密,只有发布后新产生的运行对工作区成员可见。",
"taskDetail.publishToWorkspace.confirmOk": "发布",
"taskDetail.publishToWorkspace.confirmTitle": "将任务发布到工作区?",
diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.json
index b2b223f031e..ab95cfe468e 100644
--- a/locales/zh-CN/setting.json
+++ b/locales/zh-CN/setting.json
@@ -1906,7 +1906,7 @@
"workspace.create.submit": "创建工作区",
"workspace.create.title": "创建新工作区",
"workspace.description.title": "描述",
- "workspace.general.avatar.description": "这是您的工作区头像。",
+ "workspace.general.avatar.description": "这是您的工作区头像。点击头像即可从本地文件上传自定义头像。",
"workspace.general.avatar.hint": "头像是可选的,但强烈推荐。",
"workspace.general.avatar.title": "工作区头像",
"workspace.general.avatar.tooLarge": "头像文件必须小于 5MB。",
diff --git a/packages/database/src/models/__tests__/agent.privateVisibility.workspace.test.ts b/packages/database/src/models/__tests__/agent.privateVisibility.workspace.test.ts
index 80277487618..1df651a1ac1 100644
--- a/packages/database/src/models/__tests__/agent.privateVisibility.workspace.test.ts
+++ b/packages/database/src/models/__tests__/agent.privateVisibility.workspace.test.ts
@@ -1,8 +1,9 @@
// @vitest-environment node
+import { eq } from 'drizzle-orm';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { getTestDB } from '../../core/getTestDB';
-import { agents, users, workspaces } from '../../schemas';
+import { agents, sessionGroups, users, workspaces } from '../../schemas';
import type { LobeChatDatabase } from '../../type';
import { AgentModel } from '../agent';
@@ -137,6 +138,61 @@ describe('AgentModel — private/public cross-user isolation', () => {
});
});
+ describe('setVisibility group rehoming', () => {
+ // A sidebar folder cannot mix visibilities — an agent crossing scopes
+ // while keyed to a group of the old scope would be emitted nowhere by
+ // HomeRepository.processAgentList and vanish from the sidebar.
+ const insertGroup = async (id: string, visibility: 'private' | 'public') => {
+ await serverDB.insert(sessionGroups).values({
+ id,
+ name: id,
+ userId: userA,
+ visibility,
+ workspaceId,
+ });
+ };
+
+ it('clears sessionGroupId when demotion leaves a public group', async () => {
+ await insertGroup('pub-group', 'public');
+ await insertAgent({ id: 'a-grouped', userId: userA, visibility: 'public', workspaceId });
+ await serverDB
+ .update(agents)
+ .set({ sessionGroupId: 'pub-group' })
+ .where(eq(agents.id, 'a-grouped'));
+
+ const callerA = new AgentModel(serverDB, userA, workspaceId);
+ const updated = await callerA.setVisibility('a-grouped', 'private');
+
+ expect(updated?.visibility).toBe('private');
+ expect(updated?.sessionGroupId).toBeNull();
+ });
+
+ it('keeps sessionGroupId when the group already matches the new visibility', async () => {
+ await insertGroup('priv-group', 'private');
+ await insertAgent({ id: 'a-priv-grouped', userId: userA, visibility: 'public', workspaceId });
+ await serverDB
+ .update(agents)
+ .set({ sessionGroupId: 'priv-group' })
+ .where(eq(agents.id, 'a-priv-grouped'));
+
+ const callerA = new AgentModel(serverDB, userA, workspaceId);
+ const updated = await callerA.setVisibility('a-priv-grouped', 'private');
+
+ expect(updated?.visibility).toBe('private');
+ expect(updated?.sessionGroupId).toBe('priv-group');
+ });
+
+ it('keeps ungrouped agents ungrouped on demotion', async () => {
+ await insertAgent({ id: 'a-ungrouped', userId: userA, visibility: 'public', workspaceId });
+
+ const callerA = new AgentModel(serverDB, userA, workspaceId);
+ const updated = await callerA.setVisibility('a-ungrouped', 'private');
+
+ expect(updated?.visibility).toBe('private');
+ expect(updated?.sessionGroupId).toBeNull();
+ });
+ });
+
describe('personal mode', () => {
it("never returns another user's personal-mode agent", async () => {
// workspaceId omitted → personal row
diff --git a/packages/database/src/models/__tests__/task.test.ts b/packages/database/src/models/__tests__/task.test.ts
index 18bba72157c..1ee6c2f569f 100644
--- a/packages/database/src/models/__tests__/task.test.ts
+++ b/packages/database/src/models/__tests__/task.test.ts
@@ -2091,6 +2091,131 @@ describe('TaskModel', () => {
expect(historical.visibility).toBe('private');
});
+ it('should cascade public→private demotion into task_comments and task_topics', async () => {
+ // Inverse of the two non-cascade tests above: comment/topic visibility
+ // is a write-time mirror of the task used as a JOIN-free authorization
+ // proxy. When the task is pulled back to private, public-era rows must
+ // follow — otherwise members who saved a comment/topic id while the
+ // task was public could keep reading/operating those historical rows.
+ const alice = new TaskModel(serverDB, userId, wsId);
+ const bob = new TaskModel(serverDB, userId2, wsId);
+
+ const task = await alice.create({
+ instruction: 'will be demoted',
+ visibility: 'public',
+ });
+ await alice.addComment({
+ authorUserId: userId,
+ content: 'public-era comment',
+ taskId: task.id,
+ userId,
+ });
+
+ const publicTopicId = await createTopic('public-era-run-topic-id');
+ await serverDB.insert(taskTopics).values({
+ seq: 1,
+ status: 'completed',
+ taskId: task.id,
+ topicId: publicTopicId,
+ userId,
+ visibility: 'public',
+ workspaceId: wsId,
+ });
+
+ // Sanity: Bob sees the public-era comment while the task is public.
+ expect(await bob.getComments(task.id)).toHaveLength(1);
+
+ await alice.updateVisibility(task.id, 'private');
+
+ // Task and both child rows are private now — gone from Bob's scope.
+ expect(await bob.findById(task.id)).toBeNull();
+ expect(await bob.getComments(task.id)).toHaveLength(0);
+ const [demotedTopic] = await serverDB
+ .select({ visibility: taskTopics.visibility })
+ .from(taskTopics)
+ .where(eq(taskTopics.taskId, task.id));
+ expect(demotedTopic.visibility).toBe('private');
+
+ // Alice (creator) keeps access to her own rows.
+ expect(await alice.getComments(task.id)).toHaveLength(1);
+ });
+
+ it('should count tasks blocking agent demotion (public + other creators, even private)', async () => {
+ // Backs the agent demotion guard. Blocking: public tasks by any member,
+ // and other members' tasks of ANY visibility (their creators lose the
+ // assignee after demotion). Non-blocking: the agent owner's own private
+ // tasks and tasks assigned elsewhere.
+ const alice = new TaskModel(serverDB, userId, wsId);
+ const bob = new TaskModel(serverDB, userId2, wsId);
+ const agentId = 'count-assignee-agent';
+ await serverDB
+ .insert(agents)
+ .values({ id: agentId, userId, visibility: 'public', workspaceId: wsId })
+ .onConflictDoNothing();
+
+ expect(await alice.countTasksBlockingAgentDemotion(agentId, userId)).toBe(0);
+
+ // Owner's own private task — does NOT block (owner keeps the agent).
+ await alice.create({
+ assigneeAgentId: agentId,
+ instruction: 'Alice private',
+ visibility: 'private',
+ });
+ expect(await alice.countTasksBlockingAgentDemotion(agentId, userId)).toBe(0);
+
+ // Public tasks block regardless of creator.
+ await alice.create({
+ assigneeAgentId: agentId,
+ instruction: 'Alice public',
+ visibility: 'public',
+ });
+ // Bob's PRIVATE task blocks too — invisible to Alice, but Bob would
+ // lose the assignee.
+ await bob.create({
+ assigneeAgentId: agentId,
+ instruction: 'Bob private',
+ visibility: 'private',
+ });
+ // Unrelated public task does not count.
+ await alice.create({ instruction: 'Unassigned public', visibility: 'public' });
+
+ expect(await alice.countTasksBlockingAgentDemotion(agentId, userId)).toBe(2);
+
+ // Personal mode: guard is inert.
+ const personal = new TaskModel(serverDB, userId);
+ expect(await personal.countTasksBlockingAgentDemotion(agentId, userId)).toBe(0);
+ });
+
+ it('should detect other creators in the subtree (visibility-blind)', async () => {
+ const alice = new TaskModel(serverDB, userId, wsId);
+ const bob = new TaskModel(serverDB, userId2, wsId);
+
+ const root = await alice.create({ instruction: 'Root', visibility: 'public' });
+ const aliceChild = await alice.create({
+ instruction: 'Alice child',
+ parentTaskId: root.id,
+ visibility: 'public',
+ });
+
+ // Single-creator subtree → demotion is allowed.
+ expect(await alice.subtreeHasOtherCreators(root.id, userId)).toBe(false);
+
+ // Bob's PRIVATE grandchild — invisible to Alice, but demoting the root
+ // would orphan it, so it must still be detected.
+ await bob.create({
+ instruction: 'Bob grandchild',
+ parentTaskId: aliceChild.id,
+ visibility: 'private',
+ });
+ expect(await alice.subtreeHasOtherCreators(root.id, userId)).toBe(true);
+
+ // The root's own creator mismatch is not the subtree's problem: a
+ // workspace owner demoting Bob's task compares against Bob (the root
+ // creator), not the caller.
+ const bobRoot = await bob.create({ instruction: 'Bob root', visibility: 'public' });
+ expect(await alice.subtreeHasOtherCreators(bobRoot.id, userId2)).toBe(false);
+ });
+
it('should narrow list() to private tasks when visibility filter is set', async () => {
const alice = new TaskModel(serverDB, userId, wsId);
await alice.create({ instruction: 'Pub', visibility: 'public' });
diff --git a/packages/database/src/models/agent.ts b/packages/database/src/models/agent.ts
index efcaa5a2f71..8895f4485b5 100644
--- a/packages/database/src/models/agent.ts
+++ b/packages/database/src/models/agent.ts
@@ -23,6 +23,7 @@ import {
files,
knowledgeBases,
messages,
+ sessionGroups,
sessions,
taskComments,
taskDependencies,
@@ -793,14 +794,14 @@ export class AgentModel {
};
/**
- * Publish a private agent into the workspace. **One-way only** — once an
- * agent has been shared with the workspace, other members may already be
- * using it, so we never let it slip back to `private`. Likewise the
- * `user_id = ?` + `visibility = 'private'` guards lock the operation to
- * the creator's own still-private agent.
+ * Publish a private agent into the workspace. The `user_id = ?` +
+ * `visibility = 'private'` guards lock the operation to the creator's own
+ * still-private agent. The inverse transition (public → private) goes
+ * through {@link setVisibility}, which the router gates to the creator or
+ * a workspace owner (LOBE-11551).
*
* Use the existing `update` to change other fields; visibility is the only
- * one with this asymmetric rule.
+ * one with these authorization rules.
*/
publishToWorkspace = async (agentId: string) => {
return this.db
@@ -816,6 +817,66 @@ export class AgentModel {
);
};
+ /**
+ * Lightweight lookup used to authorize visibility changes: the agent's
+ * creator, slug and current visibility, scoped by the ownership predicate
+ * (other members' private agents resolve to `null`).
+ */
+ getAgentVisibilityMeta = async (
+ id: string,
+ ): Promise<{ slug: string | null; userId: string; visibility: 'private' | 'public' } | null> => {
+ const rows = await this.db
+ .select({ slug: agents.slug, userId: agents.userId, visibility: agents.visibility })
+ .from(agents)
+ .where(and(eq(agents.id, id), this.ownership()))
+ .limit(1);
+ const row = rows[0];
+ if (!row) return null;
+ return {
+ slug: row.slug,
+ userId: row.userId,
+ visibility: (row.visibility as 'private' | 'public' | null) ?? 'public',
+ };
+ };
+
+ /**
+ * Bidirectional visibility switch (LOBE-11551). Authorization (creator OR
+ * workspace owner, builtin agents excluded) is the router's responsibility —
+ * this method only applies the ownership-scoped write.
+ *
+ * Uses UPDATE … RETURNING instead of a follow-up SELECT: when a workspace
+ * owner demotes another member's agent to private, the post-update row no
+ * longer matches the visibility-aware ownership predicate, so a read-back
+ * would return 0 rows even though the write succeeded (same pattern as
+ * TaskModel.updateVisibility).
+ */
+ setVisibility = async (agentId: string, visibility: 'private' | 'public') => {
+ // A sidebar folder cannot mix visibilities (HomeRepository.processAgentList
+ // buckets grouped items by item visibility under same-visibility groups),
+ // so an agent crossing scopes while keyed to a group of the OLD scope
+ // would be emitted nowhere and vanish from the sidebar. Rehome it to the
+ // ungrouped section of its new scope when the group no longer matches.
+ const [current] = await this.db
+ .select({ groupVisibility: sessionGroups.visibility })
+ .from(agents)
+ .leftJoin(sessionGroups, eq(agents.sessionGroupId, sessionGroups.id))
+ .where(and(eq(agents.id, agentId), this.ownership()))
+ .limit(1);
+ const groupVisibility = current?.groupVisibility as 'private' | 'public' | null | undefined;
+ const clearGroup = groupVisibility != null && groupVisibility !== visibility;
+
+ const [updated] = await this.db
+ .update(agents)
+ .set({
+ updatedAt: new Date(),
+ visibility,
+ ...(clearGroup ? { sessionGroupId: null } : {}),
+ })
+ .where(and(eq(agents.id, agentId), this.ownership()))
+ .returning();
+ return updated ?? null;
+ };
+
touchUpdatedAt = async (agentId: string) => {
return this.update(agentId, {});
};
diff --git a/packages/database/src/models/task.ts b/packages/database/src/models/task.ts
index 9e53c9e1007..338df58d8c4 100644
--- a/packages/database/src/models/task.ts
+++ b/packages/database/src/models/task.ts
@@ -17,6 +17,7 @@ import {
isNull,
ne,
notInArray,
+ or,
type SQL,
sql,
} from 'drizzle-orm';
@@ -26,7 +27,7 @@ import { merge } from '@/utils/merge';
import { documents } from '../schemas/file';
import type { NewTaskComment, TaskCommentItem } from '../schemas/task';
-import { taskComments, taskDependencies, taskDocuments, tasks } from '../schemas/task';
+import { taskComments, taskDependencies, taskDocuments, tasks, taskTopics } from '../schemas/task';
import type { LobeChatDatabase } from '../type';
import { buildWorkspaceWhere } from '../utils/workspace';
@@ -255,20 +256,24 @@ export class TaskModel {
}
/**
- * Promote a task and its full subtree to a new visibility. The only legal
- * transition is `private → public` — there is no `public → private` path
- * (one-way commitment; enforced by the router-level guard).
+ * Move a task and its full subtree to a new visibility (both directions —
+ * LOBE-11551 added the `public → private` demotion; the router gates who
+ * may call it).
*
- * Cascades inside a single transaction across structural rows only:
+ * Cascades inside a single transaction:
* - the root task and every descendant in `tasks`;
* - `task_dependencies` and `task_documents` whose `task_id` is in the set.
*
- * `task_topics` and `task_comments` are deliberately **not** cascaded.
- * They are event-shaped historical rows whose visibility was fixed at write
- * time; promoting the task to public must not retroactively expose runs and
- * discussions that happened while the task was private.
- * Topics / comments created after promotion inherit the task's then-current
- * visibility through their own create paths.
+ * `task_topics` and `task_comments` are direction-sensitive. Their
+ * `visibility` column is a write-time mirror of the parent task used as a
+ * JOIN-free authorization proxy, so:
+ * - `private → public` deliberately does **not** cascade them: promoting
+ * the task must not retroactively expose runs and discussions that
+ * happened while it was private. Rows created after promotion inherit
+ * the task's then-current visibility through their own create paths.
+ * - `public → private` **does** cascade them: leaving public-era rows
+ * public would let workspace members keep reading/operating historical
+ * topics and comments of a task they can no longer see.
*
* Returns `null` if the root task is not visible to the current caller
* (either missing or owned by another workspace member). Callers should
@@ -315,10 +320,81 @@ export class TaskModel {
.set({ visibility })
.where(and(inArray(taskDocuments.taskId, taskIds), this.docsOwnership()));
+ // Demotion-only cascade for the event-shaped child rows (see docstring):
+ // their visibility mirrors the task, so pulling the task back to private
+ // must also pull public-era topics/comments out of workspace scope.
+ if (visibility === 'private') {
+ await tx
+ .update(taskTopics)
+ .set({ visibility })
+ .where(and(inArray(taskTopics.taskId, taskIds), this.topicsOwnership()));
+
+ await tx
+ .update(taskComments)
+ .set({ visibility })
+ .where(and(inArray(taskComments.taskId, taskIds), this.commentsOwnership()));
+ }
+
return updated ?? null;
});
}
+ /**
+ * Count workspace tasks that would break if the given agent were demoted to
+ * private:
+ * - public tasks assigned to it — a public task must never reference a
+ * private agent (`assertAgentVisibilityCompat`);
+ * - tasks created by anyone other than the agent's owner (any visibility)
+ * — after demotion those creators can no longer resolve the assignee,
+ * so their runs and assignee updates fail.
+ * Deliberately workspace-wide and visibility-blind (NOT `ownership()`):
+ * other members' private tasks are invisible to the caller but still lose
+ * their assignee. Backs the router-level agent demotion guard.
+ */
+ async countTasksBlockingAgentDemotion(
+ assigneeAgentId: string,
+ agentOwnerUserId: string,
+ ): Promise<number> {
+ if (!this.workspaceId) return 0;
+ const [row] = await this.db
+ .select({ count: sql<number>`count(*)` })
+ .from(tasks)
+ .where(
+ and(
+ eq(tasks.workspaceId, this.workspaceId),
+ eq(tasks.assigneeAgentId, assigneeAgentId),
+ or(eq(tasks.visibility, 'public'), ne(tasks.createdByUserId, agentOwnerUserId)),
+ ),
+ );
+ return Number(row?.count ?? 0);
+ }
+
+ /**
+ * Whether the subtree rooted at `rootTaskId` (root excluded) contains tasks
+ * created by someone other than `creatorUserId`. Deliberately workspace-wide
+ * and visibility-blind: other members' private subtasks are invisible to the
+ * caller but would still be fractured by a public→private demotion (each row
+ * stays owned by its creator, so the root creator loses those descendants
+ * while their creators keep orphaned children whose parent is hidden).
+ * Backs the router-level task demotion guard.
+ */
+ async subtreeHasOtherCreators(rootTaskId: string, creatorUserId: string): Promise<boolean> {
+ if (!this.workspaceId) return false;
+ const result = await this.db.execute(sql`
+ WITH RECURSIVE task_tree AS (
+ SELECT id, created_by_user_id FROM tasks
+ WHERE id = ${rootTaskId} AND workspace_id = ${this.workspaceId}
+ UNION ALL
+ SELECT t.id, t.created_by_user_id FROM tasks t
+ JOIN task_tree tt ON t.parent_task_id = tt.id
+ )
+ SELECT 1 AS hit FROM task_tree
+ WHERE id <> ${rootTaskId} AND created_by_user_id <> ${creatorUserId}
+ LIMIT 1
+ `);
+ return result.rows.length > 0;
+ }
+
async deleteAll(): Promise<number> {
const result = await this.db.delete(tasks).where(this.ownership()).returning();
@@ -791,6 +867,15 @@ export class TaskModel {
workspaceId: taskDependencies.workspaceId,
});
+ /** Only used by the demotion cascade in {@link updateVisibility} — regular
+ * taskTopics reads/writes live in `TaskTopicModel`. */
+ private topicsOwnership = () =>
+ this.childOwnership({
+ userId: taskTopics.userId,
+ visibility: taskTopics.visibility,
+ workspaceId: taskTopics.workspaceId,
+ });
+
async addDependency(taskId: string, dependsOnId: string, type: string = 'blocks'): Promise<void> {
const visibility = await this.getTaskVisibility(taskId);
await this.db
diff --git a/packages/database/src/repositories/home/index.ts b/packages/database/src/repositories/home/index.ts
index 402509570c2..5bd39610511 100644
--- a/packages/database/src/repositories/home/index.ts
+++ b/packages/database/src/repositories/home/index.ts
@@ -271,10 +271,12 @@ export class HomeRepository {
isPrivate: a.visibility === 'private',
pinned: a.pinned ?? a.sessionPinned ?? false,
sessionId: a.sessionId,
+ slug: a.slug,
title: meta.title,
type: 'agent' as const,
unreadCount: agentUnread.get(a.id) ?? 0,
updatedAt: a.updatedAt,
+ userId: a.agentUserId,
visibility: a.visibility,
};
}),
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index fa81140c9f6..87222ce2913 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -527,8 +527,6 @@ export default {
'newPlatformAgent': 'Connect Agent',
'newGroupChat': 'Create Group',
'agent.publishToWorkspace': 'Publish to Workspace',
- 'agent.publishToWorkspaceConfirm':
- 'Other workspace members will be able to use this agent. You will not be able to make it private again.',
'agent.publishToWorkspaceSuccess': 'Published to workspace',
'resources.publishToWorkspace.menu': 'Publish to Workspace',
'resources.publishToWorkspace.confirm':
@@ -1020,8 +1018,6 @@ export default {
'taskDetail.updateFailed': 'Failed to update task',
'taskDetail.publishToWorkspace.menuLabel': 'Publish to Workspace',
'taskDetail.publishToWorkspace.confirmTitle': 'Publish task to workspace?',
- 'taskDetail.publishToWorkspace.confirmContent':
- 'Once published, this task becomes visible to all workspace members and cannot be reverted to private.',
'taskDetail.publishToWorkspace.confirmHint':
'Past runs remain private. Only runs created after publishing will be visible to workspace members.',
'taskDetail.publishToWorkspace.confirmOk': 'Publish',
diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.ts
index 69a05bd377b..75f08a5828e 100644
--- a/packages/locales/src/default/setting.ts
+++ b/packages/locales/src/default/setting.ts
@@ -1968,7 +1968,8 @@ When I am ___, I need ___
'workspace.auditLog.upgrade.title': 'Unlock audit logs before issues become incidents',
'workspace.create.title': 'Create a new workspace',
'workspace.description.title': 'Description',
- 'workspace.general.avatar.description': "This is your workspace's avatar.",
+ 'workspace.general.avatar.description':
+ "This is your workspace's avatar. Click on the avatar to upload a custom one from your files.",
'workspace.general.avatar.hint': 'An avatar is optional but strongly recommended.',
'workspace.general.avatar.title': 'Workspace Avatar',
'workspace.general.avatar.tooLarge': 'Avatar file must be smaller than 5MB.',
diff --git a/packages/types/src/home.ts b/packages/types/src/home.ts
index 1b3042e7f25..03b6eb93d9d 100644
--- a/packages/types/src/home.ts
+++ b/packages/types/src/home.ts
@@ -49,6 +49,12 @@ export interface SidebarAgentItem {
id: string;
pinned: boolean;
sessionId?: string | null;
+ /**
+ * Agent slug. Builtin agents (LobeAI / agent-builder / …) are identified by
+ * slug, letting the sidebar hide creator-only actions on official agents.
+ * Absent for chat groups.
+ */
+ slug?: string | null;
title: string | null;
type: SidebarItemType;
/**
@@ -59,6 +65,11 @@ export interface SidebarAgentItem {
*/
unreadCount?: number;
updatedAt: Date;
+ /**
+ * Creator of the item. Lets the client gate creator-only actions (e.g.
+ * pulling a published agent back to private). Absent for chat groups.
+ */
+ userId?: string | null;
/**
* `private` items are only visible to their creator within a workspace.
* Absent / `public` for items that are visible to every workspace member or
diff --git a/packages/types/src/task/index.ts b/packages/types/src/task/index.ts
index bc38a0ac2cd..5ac0d387689 100644
--- a/packages/types/src/task/index.ts
+++ b/packages/types/src/task/index.ts
@@ -375,6 +375,8 @@ export interface TaskDetailData {
checkpoint?: CheckpointConfig;
config?: Record<string, unknown>;
createdAt?: string;
+ /** Creator of the task; used by the UI to gate creator-only actions (e.g. make private). */
+ createdByUserId?: string | null;
dependencies?: Array<{ dependsOn: string; type: string }>;
description?: string | null;
/** Rich-editor JSON state for the instruction; preserves details markdown drops (image size, etc.). */
diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskDetailHeaderActions.test.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskDetailHeaderActions.test.tsx
index c215500130d..30f4910716e 100644
--- a/src/features/AgentTasks/AgentTaskDetail/TaskDetailHeaderActions.test.tsx
+++ b/src/features/AgentTasks/AgentTaskDetail/TaskDetailHeaderActions.test.tsx
@@ -16,16 +16,17 @@ interface MenuItem {
const mocks = vi.hoisted(() => ({
activeWorkspaceId: 'ws-1' as string | undefined,
confirmModal: vi.fn(),
+ currentUserId: 'user-1' as string | undefined,
deleteTask: vi.fn(),
dropdownItems: [] as MenuItem[],
+ isWorkspaceOwner: false,
messageSuccess: vi.fn(),
navigate: vi.fn(),
taskState: {
activeTaskId: 'T-1' as string | undefined,
- taskDetailMap: { 'T-1': { visibility: 'private' as 'private' | 'public' } } as Record<
- string,
- { visibility?: 'private' | 'public' }
- >,
+ taskDetailMap: {
+ 'T-1': { visibility: 'private' as 'private' | 'public' },
+ } as Record<string, { createdByUserId?: string | null; visibility?: 'private' | 'public' }>,
},
transferItems: [
{ key: 'transfer-task', label: 'Transfer to...' },
@@ -70,6 +71,24 @@ vi.mock('@/business/client/hooks/useActiveWorkspaceSlug', () => ({
useActiveWorkspaceSlug: () => 'ws-slug',
}));
+vi.mock('@/business/client/hooks/useIsWorkspaceOwner', () => ({
+ useIsWorkspaceOwner: () => mocks.isWorkspaceOwner,
+}));
+
+vi.mock('@/features/VisibilityConfirmContent', () => ({
+ default: () => <div />,
+}));
+
+vi.mock('@/store/user', () => ({
+ useUserStore: (selector: (state: Record<string, unknown>) => unknown) => selector({}),
+}));
+
+vi.mock('@/store/user/selectors', () => ({
+ userProfileSelectors: {
+ userId: () => mocks.currentUserId,
+ },
+}));
+
vi.mock('@/business/client/hooks/useTaskTransferMenuItem', () => ({
useTaskTransferMenuItem: vi.fn(() => mocks.transferItems),
}));
@@ -102,6 +121,8 @@ describe('TaskDetailHeaderActions', () => {
mocks.taskState.activeTaskId = 'T-1';
mocks.taskState.taskDetailMap = { 'T-1': { visibility: 'private' } };
mocks.activeWorkspaceId = 'ws-1';
+ mocks.currentUserId = 'user-1';
+ mocks.isWorkspaceOwner = false;
});
it('includes task transfer and copy actions in the detail menu', () => {
@@ -131,6 +152,65 @@ describe('TaskDetailHeaderActions', () => {
expect(mocks.dropdownItems.map((item) => item?.key)).not.toContain('publishToWorkspace');
});
+ it('shows "make private" on public tasks for the creator', () => {
+ mocks.taskState.taskDetailMap = {
+ 'T-1': { createdByUserId: 'user-1', visibility: 'public' },
+ };
+ render(<TaskDetailHeaderActions />);
+
+ expect(mocks.dropdownItems.map((item) => item?.key)).toContain('makePrivate');
+ });
+
+ it('shows "make private" on public tasks for a workspace owner (non-creator)', () => {
+ mocks.isWorkspaceOwner = true;
+ mocks.taskState.taskDetailMap = {
+ 'T-1': { createdByUserId: 'someone-else', visibility: 'public' },
+ };
+ render(<TaskDetailHeaderActions />);
+
+ expect(mocks.dropdownItems.map((item) => item?.key)).toContain('makePrivate');
+ });
+
+ it('hides "make private" from non-creator members', () => {
+ mocks.taskState.taskDetailMap = {
+ 'T-1': { createdByUserId: 'someone-else', visibility: 'public' },
+ };
+ render(<TaskDetailHeaderActions />);
+
+ expect(mocks.dropdownItems.map((item) => item?.key)).not.toContain('makePrivate');
+ });
+
+ it('hides "make private" on private tasks', () => {
+ mocks.taskState.taskDetailMap = {
+ 'T-1': { createdByUserId: 'user-1', visibility: 'private' },
+ };
+ render(<TaskDetailHeaderActions />);
+
+ expect(mocks.dropdownItems.map((item) => item?.key)).not.toContain('makePrivate');
+ });
+
+ it('make-private action opens a destructive confirmation and updates visibility', () => {
+ mocks.taskState.taskDetailMap = {
+ 'T-1': { createdByUserId: 'user-1', visibility: 'public' },
+ };
+ render(<TaskDetailHeaderActions />);
+ const item = mocks.dropdownItems.find((i) => i?.key === 'makePrivate') as
+ { onClick?: () => void } | undefined;
+ item?.onClick?.();
+
+ expect(mocks.confirmModal).toHaveBeenCalledTimes(1);
+ const opts = mocks.confirmModal.mock.calls[0][0] as {
+ okButtonProps?: { danger?: boolean };
+ onOk: () => Promise<void>;
+ title: string;
+ };
+ expect(opts.title).toBe('makePrivate.confirm.title');
+ expect(opts.okButtonProps?.danger).toBe(true);
+ return opts.onOk().then(() => {
+ expect(mocks.updateTaskVisibility).toHaveBeenCalledWith('T-1', 'private');
+ });
+ });
+
it('publish action opens a one-way confirmation modal', () => {
render(<TaskDetailHeaderActions />);
const publishItem = mocks.dropdownItems.find((i) => i?.key === 'publishToWorkspace') as
diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskDetailHeaderActions.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskDetailHeaderActions.tsx
index 52b37b4d3df..6c1b4eed70b 100644
--- a/src/features/AgentTasks/AgentTaskDetail/TaskDetailHeaderActions.tsx
+++ b/src/features/AgentTasks/AgentTaskDetail/TaskDetailHeaderActions.tsx
@@ -1,19 +1,23 @@
import { ActionIcon, copyToClipboard, type DropdownItem, DropdownMenu, Icon } from '@lobehub/ui';
import { confirmModal } from '@lobehub/ui/base-ui';
import { App } from 'antd';
-import { CopyIcon, LinkIcon, MoreHorizontal, Trash, UsersIcon } from 'lucide-react';
+import { CopyIcon, EyeOffIcon, LinkIcon, MoreHorizontal, Trash, UsersIcon } from 'lucide-react';
import { memo, useCallback, useMemo } from 'react';
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';
import { buildWorkspaceAwarePath } from '@/features/Workspace/workspaceAwarePath';
import { useAppOrigin } from '@/hooks/useAppOrigin';
import { usePermission } from '@/hooks/usePermission';
import { useTaskStore } from '@/store/task';
import { taskDetailSelectors } from '@/store/task/selectors';
+import { useUserStore } from '@/store/user';
+import { userProfileSelectors } from '@/store/user/selectors';
import { taskDetailPath } from '../shared/taskDetailPath';
@@ -28,6 +32,9 @@ const TaskDetailHeaderActions = memo(() => {
const taskId = useTaskStore(taskDetailSelectors.activeTaskId);
const taskAgentId = useTaskStore(taskDetailSelectors.activeTaskAgentId);
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;
@@ -54,7 +61,7 @@ const TaskDetailHeaderActions = memo(() => {
cancelText: t('cancel', { ns: 'common' }),
content: (
<>
- <div>{t('taskDetail.publishToWorkspace.confirmContent')}</div>
+ <VisibilityConfirmContent variant="publish" />
<div style={{ marginTop: 8, opacity: 0.7 }}>
{t('taskDetail.publishToWorkspace.confirmHint')}
</div>
@@ -73,6 +80,27 @@ const TaskDetailHeaderActions = memo(() => {
});
}, [canEditTask, taskId, t, updateTaskVisibility]);
+ const triggerMakePrivate = useCallback(() => {
+ if (!canEditTask) return;
+ if (!taskId) return;
+ confirmModal({
+ cancelText: t('cancel', { ns: 'common' }),
+ content: <VisibilityConfirmContent variant="makePrivate" />,
+ okButtonProps: { danger: true },
+ okText: t('makePrivate.confirm.ok', { ns: 'common' }),
+ onOk: async () => {
+ try {
+ await updateTaskVisibility(taskId, 'private');
+ message.success(t('makePrivate.success', { ns: 'common' }));
+ } catch {
+ // store action already surfaced a targeted toast; swallow so the
+ // confirm modal doesn't bubble a second error to base-ui.
+ }
+ },
+ title: t('makePrivate.confirm.title', { ns: 'common' }),
+ });
+ }, [canEditTask, taskId, t, message, updateTaskVisibility]);
+
const menuItems = useMemo<DropdownItem[]>(() => {
if (!taskId) return [];
@@ -111,10 +139,8 @@ const TaskDetailHeaderActions = memo(() => {
},
];
- // Publish-to-workspace is the one-way visibility transition. Only surface
- // it on private tasks inside a workspace; public tasks have no inverse
- // action (intentional — visibility is a one-way commitment) and personal
- // mode has no workspace to publish to.
+ // Publish-to-workspace only surfaces on private tasks inside a workspace;
+ // personal mode has no workspace to publish to.
const publishItem: DropdownItem | null =
activeWorkspaceId && visibility === 'private'
? {
@@ -126,11 +152,29 @@ 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);
+ const makePrivateItem: DropdownItem | null =
+ activeWorkspaceId && visibility === 'public' && canMakePrivate
+ ? {
+ disabled: !canEditTask,
+ icon: <Icon icon={EyeOffIcon} />,
+ key: 'makePrivate',
+ label: t('makePrivate', { ns: 'common' }),
+ onClick: triggerMakePrivate,
+ }
+ : null;
+
+ const visibilityItem = publishItem ?? makePrivateItem;
+
const transferGroup =
transferItems && transferItems.length > 0
- ? [...transferItems, ...(publishItem ? [publishItem] : [])]
- : publishItem
- ? [publishItem]
+ ? [...transferItems, ...(visibilityItem ? [visibilityItem] : [])]
+ : visibilityItem
+ ? [visibilityItem]
: [];
if (transferGroup.length === 0) return baseItems;
@@ -143,10 +187,14 @@ const TaskDetailHeaderActions = memo(() => {
activeWorkspaceSlug,
activeWorkspaceId,
visibility,
+ createdByUserId,
+ currentUserId,
+ isWorkspaceOwner,
t,
message,
triggerDelete,
triggerPublish,
+ triggerMakePrivate,
canEditTask,
transferItems,
]);
diff --git a/src/features/EditorCanvas/DocumentIdMode.tsx b/src/features/EditorCanvas/DocumentIdMode.tsx
index 8a4ba36689d..b72d28e4f49 100644
--- a/src/features/EditorCanvas/DocumentIdMode.tsx
+++ b/src/features/EditorCanvas/DocumentIdMode.tsx
@@ -104,8 +104,12 @@ const DocumentIdMode = memo<DocumentIdModeProps>(
await performSave(documentId, undefined, { saveSource: 'system' });
const latestDocument = useDocumentStore.getState().documents[documentId];
+ // A lock CONFLICT is not a network failure — surface the real reason
+ // instead of the generic "check your connection" toast.
+ if (latestDocument?.saveBlockedByLock)
+ throw new Error(t('pageEditor.editMode.lockedBySomeone'));
return latestDocument ? !latestDocument.isDirty : true;
- }, [documentId, handleContentChangeStore, performSave, shouldGuardUnsavedChanges]);
+ }, [documentId, handleContentChangeStore, performSave, shouldGuardUnsavedChanges, t]);
const unsavedGuardNode = (
<UnsavedChangesGuard
diff --git a/src/features/PageEditor/StoreUpdater.tsx b/src/features/PageEditor/StoreUpdater.tsx
index 936a264c97d..c2869508da6 100644
--- a/src/features/PageEditor/StoreUpdater.tsx
+++ b/src/features/PageEditor/StoreUpdater.tsx
@@ -49,10 +49,13 @@ const StoreUpdater = memo<StoreUpdaterProps>(
const initMeta = usePageEditorStore((s) => s.initMeta);
const pageAgentEditor = editor as unknown as PageAgentEditor | undefined;
// Workspace pages are view-first; resolve once here so the lock + gating read
- // a single source of truth.
- const isWorkspacePage = usePageStore((s) =>
- Boolean(pageSelectors.getDocumentById(pageId)(s)?.workspaceId),
- );
+ // a single source of truth. Private-visibility pages are creator-only —
+ // no other member can open them — so they stay outside the lock lifecycle
+ // (mirrors DocumentService.isCollaborativeDocument on the server).
+ const isWorkspacePage = usePageStore((s) => {
+ const doc = pageSelectors.getDocumentById(pageId)(s);
+ return Boolean(doc?.workspaceId) && doc?.visibility !== 'private';
+ });
// Drive the collaborative edit lock for workspace pages
useDocumentLock();
diff --git a/src/routes/(main)/home/_layout/Body/Agent/List/AgentItem/index.tsx b/src/routes/(main)/home/_layout/Body/Agent/List/AgentItem/index.tsx
index 447269e82ac..fa249d1fc00 100644
--- a/src/routes/(main)/home/_layout/Body/Agent/List/AgentItem/index.tsx
+++ b/src/routes/(main)/home/_layout/Body/Agent/List/AgentItem/index.tsx
@@ -79,7 +79,7 @@ interface AgentItemProps {
}
const AgentItem = memo<AgentItemProps>(({ item, style, className, onNavigate }) => {
- const { id, avatar, backgroundColor, title, pinned, heterogeneousType, visibility } = item;
+ const { id, avatar, backgroundColor, title, pinned, slug, userId, visibility } = item;
// Unread count is server-computed (topics.status === 'unread') and carried on
// the sidebar list item, so it stays accurate across agents whose topics
// aren't loaded into the chat store on this client.
@@ -182,7 +182,9 @@ const AgentItem = memo<AgentItemProps>(({ item, style, className, onNavigate })
id,
openCreateGroupModal: handleOpenCreateGroupModal,
pinned: pinned ?? false,
+ slug,
title: displayTitle,
+ userId,
visibility,
});
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 14fb670079c..23726882868 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
@@ -1,3 +1,4 @@
+import { BUILTIN_AGENT_SLUGS } from '@lobechat/builtin-agents';
import { SessionDefaultGroup, type SidebarVisibility } from '@lobechat/types';
import { type MenuProps } from '@lobehub/ui';
import { Icon } from '@lobehub/ui';
@@ -6,6 +7,7 @@ import { App } from 'antd';
import isEqual from 'fast-deep-equal';
import {
Check,
+ EyeOffIcon,
FolderInputIcon,
GlobeIcon,
LucideCopy,
@@ -21,12 +23,18 @@ 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';
import { agentService } from '@/services/agent';
import { useGlobalStore } from '@/store/global';
import { useHomeStore } from '@/store/home';
import { homeAgentListSelectors } from '@/store/home/selectors';
+import { useUserStore } from '@/store/user';
+import { userProfileSelectors } from '@/store/user/selectors';
+
+const BUILTIN_SLUGS = new Set<string>(Object.values(BUILTIN_AGENT_SLUGS));
interface UseAgentDropdownMenuParams {
anchor: HTMLElement | null;
@@ -36,7 +44,9 @@ interface UseAgentDropdownMenuParams {
id: string;
openCreateGroupModal: () => void;
pinned: boolean;
+ slug?: string | null;
title: string;
+ userId?: string | null;
visibility?: SidebarVisibility;
}
@@ -48,7 +58,9 @@ export const useAgentDropdownMenu = ({
id,
openCreateGroupModal,
pinned,
+ slug,
title,
+ userId,
visibility,
}: UseAgentDropdownMenuParams): (() => MenuProps['items']) => {
const { t } = useTranslation(['chat', 'common']);
@@ -73,15 +85,23 @@ export const useAgentDropdownMenu = ({
s.removeAgent,
]);
- // "Publish to Workspace" is a one-way action and only meaningful inside a
- // workspace: in personal mode every row is implicitly owner-private. Once
- // an agent is `public`, other members may already use it, so we never let
- // it slip back to `private`. The menu item only appears for private
- // agents in workspace mode; the server is the source of truth for whether
- // the viewer is the creator and rejects requests from anyone else.
+ // 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.
const activeWorkspaceId = useActiveWorkspaceId();
+ const isWorkspaceOwner = useIsWorkspaceOwner();
+ const currentUserId = useUserStore(userProfileSelectors.userId);
const isPrivate = visibility === 'private';
+ const isBuiltin = !!slug && BUILTIN_SLUGS.has(slug);
const showPublishAction = Boolean(activeWorkspaceId) && isPrivate;
+ const showMakePrivateAction =
+ Boolean(activeWorkspaceId) &&
+ visibility === 'public' &&
+ !isBuiltin &&
+ (isWorkspaceOwner || (!!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
@@ -184,16 +204,9 @@ export const useAgentDropdownMenu = ({
onClick: async ({ domEvent }: any) => {
domEvent?.stopPropagation();
if (!canEdit) return;
- // Soft confirm because the action is irreversible: once
- // teammates start using a published agent, the change
- // can't be rolled back from the UI.
confirmModal({
cancelText: t('cancel', { ns: 'common' }),
- content: t('agent.publishToWorkspaceConfirm', {
- defaultValue:
- 'Other workspace members will be able to use this agent. ' +
- 'You will not be able to make it private again.',
- }),
+ content: <VisibilityConfirmContent variant="publish" />,
okText: t('agent.publishToWorkspace', {
defaultValue: 'Publish to Workspace',
}),
@@ -222,6 +235,38 @@ export const useAgentDropdownMenu = ({
{ type: 'divider' as const },
]
: []),
+ ...(showMakePrivateAction
+ ? [
+ {
+ disabled: !canEdit,
+ icon: <Icon icon={EyeOffIcon} />,
+ key: 'makePrivate',
+ label: t('makePrivate', { ns: 'common' }),
+ onClick: async ({ domEvent }: any) => {
+ domEvent?.stopPropagation();
+ if (!canEdit) return;
+ confirmModal({
+ cancelText: t('cancel', { ns: 'common' }),
+ content: <VisibilityConfirmContent variant="makePrivate" />,
+ okButtonProps: { danger: true },
+ okText: t('makePrivate.confirm.ok', { ns: 'common' }),
+ onOk: async () => {
+ try {
+ await agentService.setAgentVisibility(id, 'private');
+ await refreshAgentList();
+ message.success(t('makePrivate.success', { ns: 'common' }));
+ } catch (error) {
+ console.error('Failed to make agent private:', error);
+ message.error(t('makePrivate.error', { ns: 'common' }));
+ }
+ },
+ title: t('makePrivate.confirm.title', { ns: 'common' }),
+ });
+ },
+ },
+ { type: 'divider' as const },
+ ]
+ : []),
{
danger: true,
disabled: !canEdit,
@@ -260,6 +305,7 @@ export const useAgentDropdownMenu = ({
message,
transferMenuItems,
showPublishAction,
+ showMakePrivateAction,
refreshAgentList,
t,
],
diff --git a/src/services/agent.ts b/src/services/agent.ts
index 3dcc79f1a83..8bf63767b4e 100644
--- a/src/services/agent.ts
+++ b/src/services/agent.ts
@@ -124,16 +124,24 @@ class AgentService {
};
/**
- * Publish a private agent to the workspace. One-way action — `private`
- * agents cannot be re-privatized once shared, because other workspace
- * members may already be using them. Caller should refresh the sidebar
- * list afterwards so the agent moves from the Private bucket to the
- * shared list.
+ * Publish a private agent to the workspace. Caller should refresh the
+ * sidebar list afterwards so the agent moves from the Private bucket to
+ * the shared list. The inverse (public → private) goes through
+ * {@link setAgentVisibility}.
*/
publishAgentToWorkspace = async (id: string): Promise<void> => {
await lambdaClient.agent.publishAgentToWorkspace.mutate({ id });
};
+ /**
+ * Bidirectional visibility switch (LOBE-11551). The server only allows the
+ * agent's creator or a workspace owner to pull a published agent back to
+ * private, and rejects builtin agents (LobeAI etc.) outright.
+ */
+ setAgentVisibility = async (id: string, visibility: 'private' | 'public'): Promise<void> => {
+ await lambdaClient.agent.setAgentVisibility.mutate({ id, visibility });
+ };
+
/**
* Create a virtual agent without session.
* Used for Group Agent Builder to create virtual agents for groups.
diff --git a/src/store/task/selectors/detailSelectors.ts b/src/store/task/selectors/detailSelectors.ts
index 37be275aac2..d5e68bafe20 100644
--- a/src/store/task/selectors/detailSelectors.ts
+++ b/src/store/task/selectors/detailSelectors.ts
@@ -23,6 +23,8 @@ const activeTaskPriority = (s: TaskStoreState) => activeTaskDetail(s)?.priority
const activeTaskVisibility = (s: TaskStoreState): 'private' | 'public' =>
activeTaskDetail(s)?.visibility ?? 'public';
+const activeTaskCreatedByUserId = (s: TaskStoreState) => activeTaskDetail(s)?.createdByUserId;
+
const activeTaskInstruction = (s: TaskStoreState) => activeTaskDetail(s)?.instruction;
const activeTaskEditorData = (s: TaskStoreState) => activeTaskDetail(s)?.editorData;
@@ -109,6 +111,7 @@ export const taskDetailSelectors = {
activeTaskAgentId,
activeTaskAutomationMode,
activeTaskCheckpoint,
+ activeTaskCreatedByUserId,
activeTaskModel,
activeTaskDependencies,
activeTaskDescription,