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: agent lost from sidebar after workspace transfer (#16853)

Rdmclin2bb7d5563980d
diff --git a/.agents/skills/agent-testing/references/probe-mock-patterns.md b/.agents/skills/agent-testing/references/probe-mock-patterns.md
index 765517fd207..648a05df729 100644
--- a/.agents/skills/agent-testing/references/probe-mock-patterns.md
+++ b/.agents/skills/agent-testing/references/probe-mock-patterns.md
@@ -509,3 +509,65 @@
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.
+
+---
+
+## F. Running the OSS web surface inside the CLOUD checkout (submodule)
+
+### F1. βœ… WORKS β€” vite dev EMFILE on a shared machine: serve a BUILT SPA behind a fake vite origin
+
+- **Situation**: `bun run dev` / `vite` in the lobehub submodule dies instantly with
+ `EMFILE: too many open files, watch` (node FSWatcher), even with `ulimit -n 245760`
+ and `CHOKIDAR_USEPOLLING=1` β€” happens when another worktree's dev server already
+ holds a huge watch set on the same machine.
+- **Works**: skip vite dev entirely. `bun run build:spa && bun run build:spa:copy`
+ (no watchers), then `PORT=<p> VITE_DEV_PORT=<q> init-dev-env.sh dev-next` (Next dev
+ alone starts fine), plus a tiny static server on `<q>` that returns
+ `dist/desktop/index.html` for `/` (Next's `fetchViteDevTemplate` fetches the HTML
+ template from the vite origin in dev). `build:spa:copy` puts assets under
+ `public/_spa` so Next serves the chunks itself.
+- **Gotcha**: with the built template, the inline importmap boot script does NOT
+ auto-import the entry β€” after every `open`, boot manually:
+ `agent-browser eval 'import("/_spa/assets/index-<hash>.js")'` (find the hash in
+ `public/_spa/assets`). Re-run after each rebuild (hash changes).
+
+### F2. Cloud pnpm overrides leak into the submodule app; shim the missing cloud aliases
+
+- **Situation**: in the cloud checkout, `@lobechat/business-*` resolves to CLOUD
+ packages; running the OSS Next app then fails with
+ `Module not found: Can't resolve '@/libs/redis-client'` (cloud-only module).
+- **Works**: create a minimal stub at `lobehub/src/libs/redis-client.ts`
+ (`isRedisClientEnabled=()=>false; getRedisClient=async()=>null`), marked
+ `[AGENT-TEST] REMOVE`; restart Next (Turbopack won't pick up the new file without
+ a restart). Revert after the run.
+- Also: better-auth needs a reachable `REDIS_URL`; ioredis failed against a leftover
+ redis on 6380 that redis-cli could reach β€” starting a fresh `redis:7-alpine` on
+ 6379 and passing `REDIS_URL=redis://127.0.0.1:6379` fixed `Failed to get session`.
+
+### F3. βœ… WORKS β€” drive workspace-scoped behavior in the OSS build (no cloud UI)
+
+- The workspace context is the `X-Workspace-Id` request header
+ (`packages/trpc/src/lambda/context.ts`); the OSS client never sets it and the
+ workspace UI hooks are empty business slots (`useActiveWorkspaceId` β†’ null).
+- **Works, three layers**:
+ 1. **API-level**: `fetch("/trpc/lambda/<proc>", {headers:{"X-Workspace-Id": ws}})`
+ from `agent-browser eval` (cookies included) hits the real router with real
+ RBAC checks.
+ 2. **RBAC**: workspace member needs rbac rows β€” seed `rbac_permissions`
+ (`agent:create:all` etc.), one `rbac_roles`, `rbac_role_permissions`, and a
+ workspace-scoped `rbac_user_roles` row; a 403 "No write access to target
+ workspace" proves the check is live.
+ 3. **UI-level**: patch the slot `src/business/client/hooks/useActiveWorkspaceId.ts`
+ to read `localStorage.AGENT_TEST_WS` (keep ALL original exports β€”
+ `getActiveWorkspaceId` too, or the build fails with MISSING\_EXPORT), rebuild the
+ SPA, and pre-patch `window.fetch` (BEFORE the manual entry import β€” the TRPC
+ client captures fetch at creation) to add the header. The sidebar then renders
+ the real Private/Workspace sections.
+- **Production SPA build exposes NO `window.__LOBE_STORES`** β€” store-action eval is
+ dev-build-only; use the TRPC fetch path instead.
+
+### F4. curl "502" on localhost with nothing listening = shell proxy env
+
+- With `http_proxy`/`HTTP_PROXY` set, `curl http://localhost:<port>` returns the
+ proxy's 502 instead of connection-refused, faking a "server up but broken" signal.
+ Always `curl --noproxy '*'` for local port probes.
diff --git a/packages/database/src/models/__tests__/agentTransfer.test.ts b/packages/database/src/models/__tests__/agentTransfer.test.ts
index 134413e0884..1c84b398952 100644
--- a/packages/database/src/models/__tests__/agentTransfer.test.ts
+++ b/packages/database/src/models/__tests__/agentTransfer.test.ts
@@ -12,6 +12,7 @@ import {
chatGroupsAgents,
documents,
messages,
+ sessionGroups,
sessions,
taskComments,
taskDependencies,
@@ -130,6 +131,32 @@ describe('AgentModel.transferAgent', () => {
expect(link.workspaceId).toBe(wsId1);
});
+ it('should clear stale session group references on transfer', async () => {
+ const model = new AgentModel(serverDB, userId);
+ const agent = await model.create({ title: 'Grouped Agent' });
+
+ // Personal-scope sidebar folder the agent and its session lived in
+ await serverDB.insert(sessionGroups).values({ id: 'sg-personal', name: 'Folder', userId });
+ await serverDB
+ .update(agents)
+ .set({ sessionGroupId: 'sg-personal' })
+ .where(eq(agents.id, agent.id));
+ await serverDB
+ .insert(sessions)
+ .values({ id: 'sess-grouped', userId, type: 'agent', groupId: 'sg-personal' });
+ await serverDB
+ .insert(agentsToSessions)
+ .values({ agentId: agent.id, sessionId: 'sess-grouped', userId });
+
+ await model.transferAgent(agent.id, wsId1, userId, 'private');
+
+ const updated = await serverDB.query.agents.findFirst({ where: eq(agents.id, agent.id) });
+ expect(updated?.sessionGroupId).toBeNull();
+
+ const [session] = await serverDB.select().from(sessions).where(eq(sessions.id, 'sess-grouped'));
+ expect(session.groupId).toBeNull();
+ });
+
it('should update topics and messages', async () => {
const model = new AgentModel(serverDB, userId);
const agent = await model.create({ title: 'Agent' });
diff --git a/packages/database/src/models/agent.ts b/packages/database/src/models/agent.ts
index 8895f4485b5..96c1174a3c6 100644
--- a/packages/database/src/models/agent.ts
+++ b/packages/database/src/models/agent.ts
@@ -1234,6 +1234,9 @@ export class AgentModel {
// 4. Update the agent record.
// Only apply visibility when moving into a workspace β€” visibility is
// a no-op in personal scope where every row is implicitly private.
+ // `sessionGroupId` is cleared because sidebar folders belong to the
+ // source scope (same rationale as dropping chatGroupsAgents below);
+ // a stale reference would orphan the agent out of the target sidebar.
const visibilityUpdate =
targetWorkspaceId && targetVisibility ? { visibility: targetVisibility } : {};
await trx
@@ -1242,6 +1245,7 @@ export class AgentModel {
...ownershipUpdate,
...visibilityUpdate,
agencyConfig: nextAgencyConfig,
+ sessionGroupId: null,
slug,
updatedAt: new Date(),
})
@@ -1256,7 +1260,12 @@ export class AgentModel {
const sessionIds = links.map((l) => l.sessionId);
if (sessionIds.length > 0) {
- await trx.update(sessions).set(ownershipUpdate).where(inArray(sessions.id, sessionIds));
+ // `groupId` is cleared for the same reason as the agent's
+ // `sessionGroupId`: folders stay in the source scope.
+ await trx
+ .update(sessions)
+ .set({ ...ownershipUpdate, groupId: null })
+ .where(inArray(sessions.id, sessionIds));
}
await trx
diff --git a/packages/database/src/repositories/home/index.test.ts b/packages/database/src/repositories/home/index.test.ts
index 4ebb696c043..6e93a1a97c9 100644
--- a/packages/database/src/repositories/home/index.test.ts
+++ b/packages/database/src/repositories/home/index.test.ts
@@ -8,6 +8,7 @@ import { chatGroups, chatGroupsAgents } from '../../schemas/chatGroup';
import { agentsToSessions } from '../../schemas/relations';
import { sessionGroups, sessions } from '../../schemas/session';
import { users } from '../../schemas/user';
+import { workspaces } from '../../schemas/workspace';
import type { LobeChatDatabase } from '../../type';
import { HomeRepository } from './index';
@@ -491,6 +492,35 @@ describe('HomeRepository', () => {
expect(result.groups[1].name).toBe('Group B');
expect(result.groups[2].name).toBe('Group C');
});
+
+ it('should fall back to ungrouped when groupId references a folder outside the scope', async () => {
+ const wsId = 'home-test-ws';
+ await serverDB
+ .insert(workspaces)
+ .values({ id: wsId, name: 'WS', slug: wsId, primaryOwnerId: userId });
+
+ // Personal-scope folder left behind by an agent transfer into the workspace
+ await serverDB
+ .insert(sessionGroups)
+ .values({ id: 'sg-personal-stale', name: 'Personal Folder', userId });
+ await serverDB.insert(agents).values({
+ sessionGroupId: 'sg-personal-stale',
+ title: 'Transferred Agent',
+ userId,
+ virtual: false,
+ visibility: 'private',
+ workspaceId: wsId,
+ });
+
+ const wsRepo = new HomeRepository(serverDB, userId, wsId);
+ const result = await wsRepo.getSidebarAgentList();
+
+ // The folder is not visible in the workspace scope, so the agent must
+ // surface in privateUngrouped instead of vanishing from the sidebar.
+ expect(result.privateGroups).toEqual([]);
+ expect(result.privateUngrouped).toHaveLength(1);
+ expect(result.privateUngrouped[0]).toMatchObject({ title: 'Transferred Agent' });
+ });
});
describe('getSidebarAgentList - user isolation', () => {
diff --git a/packages/database/src/repositories/home/index.ts b/packages/database/src/repositories/home/index.ts
index 5bd39610511..f8cd4881ddd 100644
--- a/packages/database/src/repositories/home/index.ts
+++ b/packages/database/src/repositories/home/index.ts
@@ -311,6 +311,16 @@ export class HomeRepository {
const groupedMap = new Map<string, SidebarAgentItem[]>();
const privateGroupedMap = new Map<string, SidebarAgentItem[]>();
+ // Group ids that will actually render, split by visibility bucket. An
+ // item whose groupId resolves to no visible folder (e.g. a folder from
+ // another scope left behind by a transfer, or a deleted folder) must fall
+ // back to the ungrouped list instead of being silently dropped.
+ const groupIds = new Set<string>();
+ const privateGroupIds = new Set<string>();
+ for (const g of groupItems) {
+ (g.visibility === 'private' ? privateGroupIds : groupIds).add(g.id);
+ }
+
for (const item of allItems) {
const { groupId, isPrivate, ...sidebarItem } = item;
const cleanedItem = cleanObject(sidebarItem) as SidebarAgentItem;
@@ -320,7 +330,8 @@ export class HomeRepository {
continue;
}
- if (groupId) {
+ const validGroupIds = isPrivate ? privateGroupIds : groupIds;
+ if (groupId && validGroupIds.has(groupId)) {
const bucket = isPrivate ? privateGroupedMap : groupedMap;
const existing = bucket.get(groupId) || [];
existing.push(cleanedItem);