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: allow workspace topic references to read personal topics (#19697)

Arvin Xu4257b0094a95
diff --git a/apps/server/src/routers/lambda/topic.ts b/apps/server/src/routers/lambda/topic.ts
index 545431e7523..c6dfb33918e 100644
--- a/apps/server/src/routers/lambda/topic.ts
+++ b/apps/server/src/routers/lambda/topic.ts
@@ -36,6 +36,7 @@ import { router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
import { FileService } from '@/server/services/file';
import { createFtsSearchRepo } from '@/server/services/ftsSearch';
+import { TopicReferenceService } from '@/server/services/topicReference';
import { after } from '@/server/utils/scheduleAfterResponse';
import { type BatchTaskResult } from '@/types/service';
@@ -306,44 +307,13 @@ export const topicRouter = router({
getTopicContext: topicProcedure
.input(z.object({ topicId: z.string() }))
- .query(async ({ input, ctx }) => {
- const topic = await ctx.topicModel.findOwnTopicById(input.topicId);
-
- if (!topic) {
- return { content: `Topic not found: ${input.topicId}`, success: false };
- }
-
- const title = topic.title || 'Untitled';
-
- // Prefer historySummary if available
- if (topic.historySummary) {
- return {
- content: `# Topic: ${title}\n\n## Summary\n${topic.historySummary}`,
- success: true,
- };
- }
-
- // Fallback: fetch recent messages with correct agentId/groupId
- const messages = await ctx.messageModel.query({
- agentId: topic.agentId ?? undefined,
- groupId: topic.groupId ?? undefined,
- topicId: input.topicId,
- });
-
- const recentMessages = messages.slice(-30);
- const lines = [`# Topic: ${title}`, '', '## Recent Messages', ''];
-
- for (const msg of recentMessages) {
- const role =
- msg.role === 'user' ? 'User' : msg.role === 'assistant' ? 'Assistant' : msg.role;
- const content = (msg.content || '').trim();
- if (content) {
- lines.push(`**${role}**: ${content}`, '');
- }
- }
-
- return { content: lines.join('\n'), success: true };
- }),
+ .query(async ({ input, ctx }) =>
+ new TopicReferenceService(
+ ctx.serverDB,
+ ctx.userId,
+ ctx.workspaceId ?? undefined,
+ ).getTopicContext(input),
+ ),
batchCreateTopics: topicProcedure
.use(withScopedPermission('topic:create'))
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/topicReference.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/topicReference.test.ts
index a66e3a79e89..50c3b810e48 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/topicReference.test.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/topicReference.test.ts
@@ -78,7 +78,11 @@ describe('topicReferenceRuntime', () => {
workspaceId: 'workspace-1',
});
- mockTopicModelFindOwnTopicById.mockResolvedValue({ id: 'topic-1', title: 'Topic' });
+ mockTopicModelFindOwnTopicById.mockResolvedValue({
+ id: 'topic-1',
+ title: 'Topic',
+ workspaceId: 'workspace-1',
+ });
mockMessageModelQuery.mockResolvedValue([]);
await runtime.getTopicContext({ topicId: 'topic-1' });
@@ -109,6 +113,36 @@ describe('topicReferenceRuntime', () => {
expect(result).toEqual({ content: 'topicId is required', success: false });
});
+ it('reads personal messages after a workspace lookup misses', async () => {
+ const serverDB = {} as any;
+ runtime = topicReferenceRuntime.factory({
+ serverDB,
+ toolManifestMap: {},
+ userId: 'user-1',
+ workspaceId: 'workspace-1',
+ });
+ mockTopicModelFindOwnTopicById.mockResolvedValueOnce(null).mockResolvedValueOnce({
+ agentId: 'personal-agent',
+ id: 'personal-topic',
+ title: 'Personal notes',
+ workspaceId: null,
+ });
+ mockMessageModelQuery.mockResolvedValue([{ content: 'Pitch notes', role: 'user' }]);
+
+ const result = await runtime.getTopicContext({ topicId: 'personal-topic' });
+
+ expect(result.success).toBe(true);
+ expect(result.content).toContain('Pitch notes');
+ expect(TopicModel).toHaveBeenNthCalledWith(1, serverDB, 'user-1', 'workspace-1');
+ expect(TopicModel).toHaveBeenNthCalledWith(2, serverDB, 'user-1');
+ expect(MessageModel).toHaveBeenCalledWith(serverDB, 'user-1', undefined);
+ expect(mockMessageModelQuery).toHaveBeenCalledWith({
+ agentId: 'personal-agent',
+ groupId: undefined,
+ topicId: 'personal-topic',
+ });
+ });
+
it('should return error when topicId is undefined', async () => {
const result = await runtime.getTopicContext({ topicId: undefined });
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/topicReference.ts b/apps/server/src/services/toolExecution/serverRuntimes/topicReference.ts
index dbd0390d7ee..08bc4e61794 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/topicReference.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/topicReference.ts
@@ -1,89 +1,10 @@
import { TopicReferenceIdentifier } from '@lobechat/builtin-tool-topic-reference';
-import type { LobeChatDatabase } from '@lobechat/database';
import type { BuiltinServerRuntimeOutput } from '@lobechat/types';
-import { MessageModel } from '@/database/models/message';
-import { TopicModel } from '@/database/models/topic';
+import { TopicReferenceService } from '@/server/services/topicReference';
import type { ServerRuntimeRegistration } from './types';
-const MAX_MESSAGES = 30;
-
-interface GetTopicContextParams {
- topicId: string;
-}
-
-class TopicReferenceExecutionRuntime {
- private db: LobeChatDatabase;
- private userId: string;
- private workspaceId?: string;
-
- constructor(db: LobeChatDatabase, userId: string, workspaceId?: string) {
- this.db = db;
- this.userId = userId;
- this.workspaceId = workspaceId;
- }
-
- getTopicContext = async (params: GetTopicContextParams): Promise<BuiltinServerRuntimeOutput> => {
- const { topicId } = params;
-
- if (!topicId) {
- return { content: 'topicId is required', success: false };
- }
-
- try {
- const topicModel = new TopicModel(this.db, this.userId, this.workspaceId);
- // `findOwnTopicById`: this tool runs under the account owner's identity,
- // so a raw topic id must never resolve to an agent-share visitor topic
- // (those are stored under the creator's userId).
- const topic = await topicModel.findOwnTopicById(topicId);
-
- if (!topic) {
- return { content: `Topic not found: ${topicId}`, success: false };
- }
-
- // If topic has a summary, prefer it
- if (topic.historySummary) {
- const result = [
- `# Topic: ${topic.title || 'Untitled'}`,
- '',
- '## Summary',
- topic.historySummary,
- ].join('\n');
-
- return { content: result, success: true };
- }
-
- // Fallback: fetch recent messages
- // Must pass agentId/groupId from topic, otherwise query filters by isNull(sessionId/groupId)
- const messageModel = new MessageModel(this.db, this.userId, this.workspaceId);
- const messages = await messageModel.query({
- agentId: topic.agentId ?? undefined,
- groupId: topic.groupId ?? undefined,
- topicId,
- });
-
- const recentMessages = messages.slice(-MAX_MESSAGES);
-
- const lines = [`# Topic: ${topic.title || 'Untitled'}`, '', '## Recent Messages', ''];
-
- for (const msg of recentMessages) {
- const role =
- msg.role === 'user' ? 'User' : msg.role === 'assistant' ? 'Assistant' : msg.role;
- const content = (msg.content || '').trim();
- if (content) {
- lines.push(`**${role}**: ${content}`, '');
- }
- }
-
- return { content: lines.join('\n'), success: true };
- } catch (error) {
- const errorMessage = error instanceof Error ? error.message : String(error);
- return { content: `Failed to fetch topic context: ${errorMessage}`, error, success: false };
- }
- };
-}
-
export const topicReferenceRuntime: ServerRuntimeRegistration = {
factory: (context) => {
if (!context.serverDB) {
@@ -92,11 +13,25 @@ export const topicReferenceRuntime: ServerRuntimeRegistration = {
if (!context.userId) {
throw new Error('userId is required for TopicReference execution');
}
- return new TopicReferenceExecutionRuntime(
+ const service = new TopicReferenceService(
context.serverDB,
context.userId,
context.workspaceId,
);
+ return {
+ getTopicContext: async (params: { topicId: string }): Promise<BuiltinServerRuntimeOutput> => {
+ try {
+ return await service.getTopicContext(params);
+ } catch (error) {
+ const errorMessage = error instanceof Error ? error.message : String(error);
+ return {
+ content: `Failed to fetch topic context: ${errorMessage}`,
+ error,
+ success: false,
+ };
+ }
+ },
+ };
},
identifier: TopicReferenceIdentifier,
};
diff --git a/apps/server/src/services/topicReference/index.test.ts b/apps/server/src/services/topicReference/index.test.ts
new file mode 100644
index 00000000000..526260edb11
--- /dev/null
+++ b/apps/server/src/services/topicReference/index.test.ts
@@ -0,0 +1,127 @@
+import { agents, messages, topics, users, workspaces } from '@lobechat/database/schemas';
+import { getTestDB } from '@lobechat/database/test-utils';
+import { inArray } from 'drizzle-orm';
+import { afterAll, beforeAll, describe, expect, it } from 'vitest';
+
+import { TopicReferenceService } from './index';
+
+const db = await getTestDB();
+const userId = 'topic-reference-owner';
+const otherUserId = 'topic-reference-other';
+const workspaceId = 'topic-reference-workspace';
+const otherWorkspaceId = 'topic-reference-other-workspace';
+
+describe('TopicReferenceService scope resolution', () => {
+ beforeAll(async () => {
+ await db.insert(users).values([{ id: userId }, { id: otherUserId }]);
+ await db.insert(workspaces).values(
+ [workspaceId, otherWorkspaceId].map((id) => ({
+ id,
+ name: id,
+ primaryOwnerId: userId,
+ slug: id,
+ })),
+ );
+ await db.insert(agents).values({ id: 'reference-personal-agent', userId });
+ await db.insert(topics).values([
+ { id: 'reference-personal-summary', userId, historySummary: 'Personal summary' },
+ {
+ agentId: 'reference-personal-agent',
+ id: 'reference-personal-messages',
+ userId,
+ },
+ { id: 'reference-current', userId, workspaceId },
+ { id: 'reference-other-user', userId: otherUserId, historySummary: 'Foreign secret' },
+ {
+ id: 'reference-other-workspace',
+ userId,
+ workspaceId: otherWorkspaceId,
+ historySummary: 'Other workspace secret',
+ },
+ { id: 'reference-visitor', userId, senderId: 'visitor', historySummary: 'Visitor secret' },
+ {
+ id: 'reference-workspace-visitor',
+ userId,
+ workspaceId,
+ senderId: 'visitor',
+ historySummary: 'Workspace visitor secret',
+ },
+ ]);
+ await db.insert(messages).values([
+ {
+ agentId: 'reference-personal-agent',
+ content: 'Personal pitch notes',
+ id: 'reference-personal-message',
+ role: 'user',
+ topicId: 'reference-personal-messages',
+ userId,
+ },
+ {
+ content: 'Workspace notes',
+ id: 'reference-workspace-message',
+ role: 'user',
+ topicId: 'reference-current',
+ userId,
+ workspaceId,
+ },
+ ]);
+ });
+
+ afterAll(async () => {
+ await db.delete(users).where(inArray(users.id, [userId, otherUserId]));
+ });
+
+ const workspaceService = new TopicReferenceService(db, userId, workspaceId);
+ const personalService = new TopicReferenceService(db, userId);
+
+ it('reads the caller’s personal summary from a workspace', async () => {
+ const result = await workspaceService.getTopicContext({
+ topicId: 'reference-personal-summary',
+ });
+ expect(result.success).toBe(true);
+ expect(result.content).toContain('Personal summary');
+ });
+
+ it('reads personal messages using the target scope and agent', async () => {
+ const result = await workspaceService.getTopicContext({
+ topicId: 'reference-personal-messages',
+ });
+ expect(result.success).toBe(true);
+ expect(result.content).toContain('Personal pitch notes');
+ expect(result.content).not.toContain('Workspace notes');
+ });
+
+ it('continues to read current workspace messages', async () => {
+ const result = await workspaceService.getTopicContext({ topicId: 'reference-current' });
+ expect(result.success).toBe(true);
+ expect(result.content).toContain('Workspace notes');
+ });
+
+ it('continues to read personal topics in personal mode', async () => {
+ const result = await personalService.getTopicContext({
+ topicId: 'reference-personal-messages',
+ });
+ expect(result.success).toBe(true);
+ expect(result.content).toContain('Personal pitch notes');
+ });
+
+ it.each([
+ 'reference-other-user',
+ 'reference-other-workspace',
+ 'reference-visitor',
+ 'reference-workspace-visitor',
+ 'missing',
+ ])('does not expose inaccessible topic %s', async (topicId) => {
+ expect(await workspaceService.getTopicContext({ topicId })).toEqual({
+ content: `Topic not found: ${topicId}`,
+ success: false,
+ });
+ });
+
+ it('does not expand personal-mode reads into workspaces', async () => {
+ expect(await personalService.getTopicContext({ topicId: 'reference-current' })).toEqual({
+ content: 'Topic not found: reference-current',
+ success: false,
+ });
+ });
+});
diff --git a/apps/server/src/services/topicReference/index.ts b/apps/server/src/services/topicReference/index.ts
new file mode 100644
index 00000000000..55aa1ccc00c
--- /dev/null
+++ b/apps/server/src/services/topicReference/index.ts
@@ -0,0 +1,55 @@
+import type { LobeChatDatabase } from '@lobechat/database';
+
+import { MessageModel } from '@/database/models/message';
+import { TopicModel } from '@/database/models/topic';
+
+export class TopicReferenceService {
+ constructor(
+ private db: LobeChatDatabase,
+ private userId: string,
+ private workspaceId?: string,
+ ) {}
+
+ getTopicContext = async ({ topicId }: { topicId: string }) => {
+ if (!topicId) return { content: 'topicId is required', success: false };
+
+ let topic = await new TopicModel(this.db, this.userId, this.workspaceId).findOwnTopicById(
+ topicId,
+ );
+
+ if (!topic && this.workspaceId) {
+ topic = await new TopicModel(this.db, this.userId).findOwnTopicById(topicId);
+ }
+
+ if (!topic) return { content: `Topic not found: ${topicId}`, success: false };
+
+ const title = topic.title || 'Untitled';
+ if (topic.historySummary) {
+ return { content: `# Topic: ${title}\n\n## Summary\n${topic.historySummary}`, success: true };
+ }
+
+ const messages = await new MessageModel(
+ this.db,
+ this.userId,
+ topic.workspaceId ?? undefined,
+ ).query({
+ agentId: topic.agentId ?? undefined,
+ groupId: topic.groupId ?? undefined,
+ topicId,
+ });
+
+ const lines = [`# Topic: ${title}`, '', '## Recent Messages', ''];
+ for (const message of messages.slice(-30)) {
+ const role =
+ message.role === 'user'
+ ? 'User'
+ : message.role === 'assistant'
+ ? 'Assistant'
+ : message.role;
+ const content = (message.content || '').trim();
+ if (content) lines.push(`**${role}**: ${content}`, '');
+ }
+
+ return { content: lines.join('\n'), success: true };
+ };
+}
diff --git a/src/libs/swr/coldHydrationRace.test.tsx b/src/libs/swr/coldHydrationRace.test.tsx
index fcdc28a4309..42661d54e69 100644
--- a/src/libs/swr/coldHydrationRace.test.tsx
+++ b/src/libs/swr/coldHydrationRace.test.tsx
@@ -19,24 +19,25 @@
* the provider and `await`s `hydrateScope()` before mounting the React root (the
* `FIX (bootstrap-await)` case).
*/
-import { act, renderHook, waitFor } from '@testing-library/react';
+import { act, cleanup, renderHook, waitFor } from '@testing-library/react';
import type { PropsWithChildren } from 'react';
import { createElement } from 'react';
import useSWR, { type Cache, SWRConfig, unstable_serialize, useSWRConfig } from 'swr';
-import { afterEach, describe, expect, it } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
-import { localDataCache } from './localDataCache';
+import { buildLocalDataKey, localDataCache } from './localDataCache';
import { createCacheProvider, type ScopedSWRProvider } from './localStorageProvider';
-const SCOPE = 'race-user:personal';
+let scope: string;
+let scopeIndex = 0;
const KEY = ['MSGS', 'topic-cold'];
const CACHED = [{ id: 'm1', text: 'cached on disk' }];
const FRESH = [{ id: 'm1', text: 'from network' }];
-const makeProvider = () =>
+const makeProvider = (providerScope = scope) =>
createCacheProvider({
debounceMs: 5,
- getScope: () => SCOPE,
+ getScope: () => providerScope,
idbPatterns: ['MSGS'],
localPatterns: [],
});
@@ -52,19 +53,25 @@ const wrapper =
/** Seed IndexedDB with a persisted SWR state row, as a prior session would leave it. */
const seedDisk = async () => {
- const p = makeProvider();
- const r = renderHook(() => useSWR(KEY, () => Promise.resolve(CACHED)), { wrapper: wrapper(p) });
- await waitFor(() => expect(r.result.current.data).toEqual(CACHED));
- await waitFor(async () => {
- const rows = await localDataCache.entriesByScope(SCOPE);
- expect(rows.length).toBeGreaterThan(0);
- });
- r.unmount();
+ // Seed the completed prior session, without a second live provider whose
+ // debounced writes can race with the cold-boot provider under test.
+ const key = buildLocalDataKey(scope, unstable_serialize(KEY));
+ await localDataCache.set(key, { data: CACHED }, '1.0.0');
+ expect(await localDataCache.get(key)).toEqual({ data: CACHED });
};
describe('cold-open hydration race (SWR + tiered provider + IndexedDB)', () => {
+ beforeEach(() => {
+ scope = `race-user-${++scopeIndex}:personal`;
+ });
+
afterEach(async () => {
- await localDataCache.clearScope(SCOPE);
+ cleanup();
+ // Flush pending provider timers before clearing disk, so a late network
+ // result cannot recreate a row after teardown.
+ window.dispatchEvent(new Event('pagehide'));
+ await localDataCache.entriesByScope(scope);
+ await localDataCache.clearScope(scope);
});
it('control: hydration completes BEFORE mount → cached row is served locally', async () => {
@@ -79,6 +86,7 @@ describe('cold-open hydration race (SWR + tiered provider + IndexedDB)', () => {
const r = renderHook(() => useSWR(KEY, () => slow), { wrapper: wrapper(p) });
expect(r.result.current.data).toEqual(CACHED);
resolveNet(FRESH);
+ await waitFor(() => expect(r.result.current.data).toEqual(FRESH));
});
it('BUG: consumer mounts BEFORE hydration → never sees the cached row until the network resolves', async () => {