π€― 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix(cli): link a document to a topic without copying it (#20037)
Arvin Xu9131d842b9cb
diff --git a/apps/cli/src/commands/doc.test.ts b/apps/cli/src/commands/doc.test.tsindex 0988ba39305..25c847803dc 100644--- a/apps/cli/src/commands/doc.test.ts+++ b/apps/cli/src/commands/doc.test.ts@@ -21,6 +21,7 @@ const { mockTrpcClient } = vi.hoisted(() => ({updateDocument: { mutate: vi.fn() },},notebook: {+ associateDocument: { mutate: vi.fn() },createDocument: { mutate: vi.fn() },listDocuments: { query: vi.fn() },},@@ -567,48 +568,28 @@ describe('doc command', () => {// ββ link-topic ββββββββββββββββββββββββββββββββββββββββdescribe('link-topic', () => {- it('should link a document to a topic', async () => {+ it('attaches the existing document instead of creating a copy', async () => {+ vi.stubEnv('LOBEHUB_OPERATION_ID', 'op-current');+ vi.stubEnv('LOBEHUB_TOPIC_ID', 'topic_123');mockTrpcClient.document.getDocumentById.query.mockResolvedValue({content: 'doc content',- description: 'desc',id: 'doc1',title: 'My Doc',});- mockTrpcClient.notebook.createDocument.mutate.mockResolvedValue({ id: 'new-doc' });+ mockTrpcClient.notebook.associateDocument.mutate.mockResolvedValue({+ documentId: 'doc1',+ topicId: 'topic_123',+ });const program = createProgram();await program.parseAsync(['node', 'test', 'doc', 'link-topic', 'doc1', 'topic_123']);- expect(mockTrpcClient.notebook.createDocument.mutate).toHaveBeenCalledWith(- expect.objectContaining({- content: 'doc content',- title: 'My Doc',- topicId: 'topic_123',- }),- );- expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('Linked'));- });-- it('carries the dispatched operation only for its own topic', async () => {- vi.stubEnv('LOBEHUB_OPERATION_ID', 'op-current');- vi.stubEnv('LOBEHUB_TOPIC_ID', 'topic_123');- mockTrpcClient.document.getDocumentById.query.mockResolvedValue({ title: 'Report' });- mockTrpcClient.notebook.createDocument.mutate.mockResolvedValue({ id: 'linked' });- await createProgram().parseAsync(['node', 'test', 'doc', 'link-topic', 'doc1', 'topic_123']);- expect(mockTrpcClient.notebook.createDocument.mutate).toHaveBeenLastCalledWith(- expect.objectContaining({ operationId: 'op-current' }),- );- await createProgram().parseAsync([- 'node',- 'test',- 'doc',- 'link-topic',- 'doc1',- 'other-topic',- ]);- expect(mockTrpcClient.notebook.createDocument.mutate).toHaveBeenLastCalledWith(- expect.not.objectContaining({ operationId: expect.any(String) }),- );+ expect(mockTrpcClient.notebook.associateDocument.mutate).toHaveBeenCalledWith({+ documentId: 'doc1',+ topicId: 'topic_123',+ });+ expect(mockTrpcClient.notebook.createDocument.mutate).not.toHaveBeenCalled();+ expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('doc1'));});it('should error when document not found', async () => {@@ -617,6 +598,7 @@ describe('doc command', () => {const program = createProgram();await program.parseAsync(['node', 'test', 'doc', 'link-topic', 'bad-id', 'topic_123']);+ expect(mockTrpcClient.notebook.associateDocument.mutate).not.toHaveBeenCalled();expect(log.error).toHaveBeenCalledWith(expect.stringContaining('not found'));expect(exitSpy).toHaveBeenCalledWith(1);});diff --git a/apps/cli/src/commands/doc.ts b/apps/cli/src/commands/doc.tsindex fcde9083ecd..eeedd319c0b 100644--- a/apps/cli/src/commands/doc.ts+++ b/apps/cli/src/commands/doc.ts@@ -335,8 +335,8 @@ export function registerDocCommand(program: Command) {.action(async (docId: string, topicId: string) => {const client = await getTrpcClient();- // Create the document via notebook router which handles topic association- // First verify the document exists+ // Attach the existing document; creating a copy here used to leave two+ // documents (and two run deliverables) for a single link.const document = await client.document.getDocumentById.query({ id: docId });if (!document) {log.error(`Document not found: ${docId}`);@@ -344,19 +344,10 @@ export function registerDocCommand(program: Command) {return;}- // Use notebook.createDocument to create a linked copy, associating with the topic- const result = await client.notebook.createDocument.mutate({- content: document.content || '',- description: document.description || '',- ...(process.env.LOBEHUB_TOPIC_ID === topicId && process.env.LOBEHUB_OPERATION_ID- ? { operationId: process.env.LOBEHUB_OPERATION_ID }- : {}),- title: document.title || 'Untitled',- topicId,- });+ const result = await client.notebook.associateDocument.mutate({ documentId: docId, topicId });console.log(- `${pc.green('β')} Linked document ${pc.bold(result.id)} to topic ${pc.bold(topicId)}`,+ `${pc.green('β')} Linked document ${pc.bold(result.documentId)} to topic ${pc.bold(topicId)}`,);});diff --git a/apps/server/src/routers/lambda/notebook.test.ts b/apps/server/src/routers/lambda/notebook.test.tsindex 62a6aa01298..82858e0959d 100644--- a/apps/server/src/routers/lambda/notebook.test.ts+++ b/apps/server/src/routers/lambda/notebook.test.ts@@ -9,13 +9,15 @@ import { notebookRouter } from './notebook';const mocks = vi.hoisted(() => ({associate: vi.fn(),create: vi.fn(),+ findDocumentById: vi.fn(),findOwnOperationById: vi.fn(),+ findTopicById: vi.fn(),registerDocument: vi.fn(),}));vi.mock('@/database/core/db-adaptor', () => ({ getServerDB: vi.fn().mockResolvedValue({}) }));vi.mock('@/database/models/document', () => ({DocumentModel: vi.fn().mockImplementation(function () {- return { create: mocks.create };+ return { create: mocks.create, findById: mocks.findDocumentById };}),}));vi.mock('@/database/models/topicDocument', () => ({@@ -23,6 +25,11 @@ vi.mock('@/database/models/topicDocument', () => ({return { associate: mocks.associate };}),}));+vi.mock('@/database/models/topic', () => ({+ TopicModel: vi.fn().mockImplementation(function () {+ return { findById: mocks.findTopicById };+ }),+}));vi.mock('@/database/models/agentOperation', () => ({AgentOperationModel: vi.fn().mockImplementation(function () {return { findOwnOperationById: mocks.findOwnOperationById };@@ -103,3 +110,39 @@ describe('notebook document work provenance', () => {expect(mocks.create).not.toHaveBeenCalled();});});++describe('notebook.associateDocument', () => {+ beforeEach(() => {+ for (const mock of Object.values(mocks)) mock.mockReset();+ mocks.associate.mockImplementation(async (params) => params);+ });++ const caller = async () => createCaller(await createContextInner({ userId: 'user-1' }));++ it('links the existing document without creating a copy or a new Work', async () => {+ mocks.findDocumentById.mockResolvedValue({ id: 'doc-1' });+ mocks.findTopicById.mockResolvedValue({ id: 'topic-1' });++ const result = await (+ await caller()+ ).associateDocument({ documentId: 'doc-1', topicId: 'topic-1' });++ expect(result).toEqual({ documentId: 'doc-1', topicId: 'topic-1' });+ expect(mocks.associate).toHaveBeenCalledWith({ documentId: 'doc-1', topicId: 'topic-1' });+ expect(mocks.create).not.toHaveBeenCalled();+ expect(mocks.registerDocument).not.toHaveBeenCalled();+ });++ it.each([+ ['document', null, { id: 'topic-1' }],+ ['topic', { id: 'doc-1' }, null],+ ])('rejects an inaccessible %s', async (_, document, topic) => {+ mocks.findDocumentById.mockResolvedValue(document);+ mocks.findTopicById.mockResolvedValue(topic);++ await expect(+ (await caller()).associateDocument({ documentId: 'doc-1', topicId: 'topic-1' }),+ ).rejects.toThrow(/not found/);+ expect(mocks.associate).not.toHaveBeenCalled();+ });+});diff --git a/apps/server/src/routers/lambda/notebook.ts b/apps/server/src/routers/lambda/notebook.tsindex 9a6fb7c7a5f..f89ff1fdfa4 100644--- a/apps/server/src/routers/lambda/notebook.ts+++ b/apps/server/src/routers/lambda/notebook.ts@@ -7,6 +7,7 @@ import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAimport { AgentOperationModel } from '@/database/models/agentOperation';import { DocumentModel } from '@/database/models/document';import { ResourcePermissionModel } from '@/database/models/resourcePermission';+import { TopicModel } from '@/database/models/topic';import { TopicDocumentModel } from '@/database/models/topicDocument';import { WorkModel } from '@/database/models/work';import { router } from '@/libs/trpc/lambda';@@ -35,11 +36,34 @@ const notebookProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts)workspaceId: wsId,}),topicDocumentModel: new TopicDocumentModel(ctx.serverDB, ctx.userId, wsId),+ topicModel: new TopicModel(ctx.serverDB, ctx.userId, wsId),},});});export const notebookRouter = router({+ /**+ * Attach an existing document to a topic without copying it.+ *+ * `createDocument` always writes a new row, so linking through it duplicated+ * the document (and, inside an agent run, registered the copy as a second+ * produced Work). This only writes the `(documentId, topicId)` pair, which is+ * idempotent.+ */+ associateDocument: notebookProcedure+ .use(withScopedPermission('document:update'))+ .input(z.object({ documentId: z.string(), topicId: z.string() }))+ .mutation(async ({ ctx, input }) => {+ const [document, topic] = await Promise.all([+ ctx.documentModel.findById(input.documentId),+ ctx.topicModel.findById(input.topicId),+ ]);+ if (!document) throw new TRPCError({ code: 'NOT_FOUND', message: 'Document not found' });+ if (!topic) throw new TRPCError({ code: 'NOT_FOUND', message: 'Topic not found' });++ return ctx.topicDocumentModel.associate(input);+ }),+createDocument: notebookProcedure.use(withScopedPermission('document:create')).input(