🤯 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(agent-documents): accept documentId and a missing title instead of failing opaquely (#20078)
Arvin Xu5be3ef77b503
diff --git a/apps/server/src/services/agentDocuments/index.test.ts b/apps/server/src/services/agentDocuments/index.test.tsindex 7cc5c7f10ab..9a2fbf63d16 100644--- a/apps/server/src/services/agentDocuments/index.test.ts+++ b/apps/server/src/services/agentDocuments/index.test.ts@@ -304,6 +304,29 @@ describe('AgentDocumentsService', () => {);});+ it('names the document from its H1 when the tool call omits the title', async () => {+ // Seen in production after #19969: a model sent only `content`, and+ // `title.trim()` threw "Cannot read properties of undefined (reading 'trim')".+ vi.mocked(extractMarkdownH1Title).mockReturnValueOnce({+ content: 'body',+ title: 'Research Notes V2',+ });+ mockModel.findByParentAndFilename.mockResolvedValue(undefined);+ mockModel.create.mockResolvedValue({ id: 'new-doc', filename: 'Research Notes V2' });++ const service = new AgentDocumentsService(db, userId);+ await service.createDocument(+ 'agent-1',+ undefined as unknown as string,+ '# Research Notes V2\n\nbody',+ );++ expect(mockModel.create).toHaveBeenCalledWith('agent-1', 'Research Notes V2', 'body', {+ editorData: { root: { children: [] } },+ title: 'Research Notes V2',+ });+ });+it('strips an H1 that duplicates the explicit title', async () => {vi.mocked(extractMarkdownH1Title).mockReturnValueOnce({content: 'body',diff --git a/apps/server/src/services/agentDocuments/index.ts b/apps/server/src/services/agentDocuments/index.tsindex b2a2e53e853..e127bc4ff00 100644--- a/apps/server/src/services/agentDocuments/index.ts+++ b/apps/server/src/services/agentDocuments/index.ts@@ -649,7 +649,9 @@ export class AgentDocumentsService {// The caller's explicit title wins; a leading H1 only names untitled documents.// The H1 is stripped from the body only when it duplicates the chosen title.const { title: extractedTitle, content: strippedContent } = extractMarkdownH1Title(content);- const finalTitle = title.trim() || extractedTitle || title;+ // Tool callers do not always send `title` even though the schema asks for it.+ const requestedTitle = typeof title === 'string' ? title.trim() : '';+ const finalTitle = requestedTitle || extractedTitle || '';const finalContent = extractedTitle === finalTitle ? strippedContent : content;const metadata = options.hintIsSkill? {diff --git a/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.test.ts b/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.test.tsindex 52373afba59..bc9487c72ca 100644--- a/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.test.ts+++ b/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.test.ts@@ -102,6 +102,139 @@ describe('AgentDocumentsExecutionRuntime', () => {});});+ describe('tool arguments the model gets wrong', () => {+ it('reads by the `documentId` alias when `id` is missing', async () => {+ // Production: readDocument({ documentId: "905d1809-…" }) returned+ // "Document not found: undefined" for documents that existed.+ const readDocument = vi.fn().mockResolvedValue({+ content: 'Working notes',+ documentId: 'docs_test_read',+ id: '905d1809-b765-48bc-890e-84e82d9986e7',+ title: 'Notes',+ });+ const runtime = createRuntime({ readDocument });++ const result = await runtime.readDocument(+ { documentId: '905d1809-b765-48bc-890e-84e82d9986e7', format: 'markdown' } as any,+ { agentId: 'agent-1' },+ );++ expect(readDocument).toHaveBeenCalledWith({+ agentId: 'agent-1',+ format: 'markdown',+ id: '905d1809-b765-48bc-890e-84e82d9986e7',+ });+ expect(result.success).toBe(true);+ expect(result.content).toContain('Working notes');+ });++ it('mutates by the binding id when given a backing `docs_` id', async () => {+ const readDocument = vi.fn().mockResolvedValue({+ documentId: 'docs_test_write',+ id: '6740f044-b58b-47eb-bdc0-21ade6c85eb2',+ title: 'Design Directives',+ });+ const replaceDocumentContent = vi.fn().mockResolvedValue({ title: 'Design Directives' });+ const runtime = createRuntime({ readDocument, replaceDocumentContent });++ const result = await runtime.replaceDocumentContent(+ { content: 'new body', documentId: 'docs_test_write' } as any,+ { agentId: 'agent-1' },+ );++ expect(replaceDocumentContent).toHaveBeenCalledWith(+ expect.objectContaining({ id: '6740f044-b58b-47eb-bdc0-21ade6c85eb2' }),+ );+ expect(result.success).toBe(true);+ });++ it('copies and updates load rules by the binding id when given a backing `docs_` id', async () => {+ const readDocument = vi.fn().mockResolvedValue({+ documentId: 'docs_test_write',+ id: '6740f044-b58b-47eb-bdc0-21ade6c85eb2',+ title: 'Design Directives',+ });+ const copyDocument = vi.fn().mockResolvedValue({+ documentId: 'docs_copy',+ id: 'copy-binding',+ title: 'Design Directives (copy)',+ });+ const updateLoadRule = vi.fn().mockResolvedValue({+ documentId: 'docs_test_write',+ title: 'Design Directives',+ });+ const runtime = createRuntime({ copyDocument, readDocument, updateLoadRule });++ await runtime.copyDocument({ documentId: 'docs_test_write' } as any, {+ agentId: 'agent-1',+ });+ await runtime.updateLoadRule(+ { documentId: 'docs_test_write', rule: { rule: 'always' } } as any,+ { agentId: 'agent-1' },+ );++ expect(copyDocument).toHaveBeenCalledWith(+ expect.objectContaining({ id: '6740f044-b58b-47eb-bdc0-21ade6c85eb2' }),+ );+ expect(updateLoadRule).toHaveBeenCalledWith(+ expect.objectContaining({ id: '6740f044-b58b-47eb-bdc0-21ade6c85eb2' }),+ );+ });++ it('does not pre-read when copy already has a binding id', async () => {+ const readDocument = vi.fn();+ const copyDocument = vi.fn().mockResolvedValue({ documentId: 'docs_c', id: 'c', title: 'C' });+ const runtime = createRuntime({ copyDocument, readDocument });++ await runtime.copyDocument({ id: '6740f044-b58b-47eb-bdc0-21ade6c85eb2' } as any, {+ agentId: 'agent-1',+ });++ expect(readDocument).not.toHaveBeenCalled();+ });++ it('explains the missing `id` instead of reporting "Document not found: undefined"', async () => {+ const readDocument = vi.fn();+ const runtime = createRuntime({ readDocument });++ const result = await runtime.readDocument({ format: 'xml' } as any, { agentId: 'agent-1' });++ expect(readDocument).not.toHaveBeenCalled();+ expect(result.success).toBe(false);+ expect(result.content).not.toContain('undefined');+ expect(result.content).toContain('readDocument requires `id`');+ });++ it('rejects createDocument without content instead of crashing', async () => {+ const createDocument = vi.fn();+ const runtime = createRuntime({ createDocument });++ const result = await runtime.createDocument({} as any, { agentId: 'agent-1' });++ expect(createDocument).not.toHaveBeenCalled();+ expect(result.success).toBe(false);+ expect(result.content).toContain('createDocument requires `content`');+ });++ it('passes an empty title through when the model omits it', async () => {+ const createDocument = vi.fn().mockResolvedValue({+ documentId: 'docs_new',+ id: 'agent-doc-new',+ title: 'Research Notes V2',+ });+ const runtime = createRuntime({ createDocument });++ const result = await runtime.createDocument(+ { content: '# Research Notes V2\n\nbody' } as any,+ { agentId: 'agent-1' },+ );++ expect(createDocument).toHaveBeenCalledWith(expect.objectContaining({ title: '' }));+ expect(result.success).toBe(true);+ expect(result.content).toContain('Research Notes V2');+ });+ });+it('surfaces the identity block and pre-reads documentId when removing a document', async () => {const readDocument = vi.fn().mockResolvedValue({documentId: 'backing-doc-1',diff --git a/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.ts b/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.tsindex cfe109ced78..bfed59b7346 100644--- a/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.ts+++ b/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.ts@@ -182,6 +182,30 @@ export interface AgentDocumentsRuntimeOptions {onDocumentsMutated?: (params: { documentId?: string }) => MaybePromise<void>;}+/**+ * Models regularly echo the `documentId` field from listDocuments/createDocument+ * back instead of `id`, or drop the id entirely. Accept `documentId` as an alias+ * (reads resolve either identifier) and fail with an actionable message when+ * neither is present, instead of looking up and reporting `undefined`.+ */+const UUID_PATTERN = /^[\da-f]{8}(?:-[\da-f]{4}){3}-[\da-f]{12}$/i;++const resolveTargetId = <T extends { id: string }>(+ args: T,+ apiName: string,+): { args: T } | { error: BuiltinServerRuntimeOutput } => {+ const { documentId: alias, ...rest } = args as T & { documentId?: unknown };+ const id = typeof args.id === 'string' && args.id.trim() ? args.id : alias;+ if (typeof id === 'string' && id.trim()) return { args: { ...rest, id } as T };++ return {+ error: {+ content: `${apiName} requires \`id\`: pass the \`id\` field returned by listDocuments or createDocument (e.g. "3f2c…-uuid").`,+ success: false,+ },+ };+};+export class AgentDocumentsExecutionRuntime {constructor(private service: AgentDocumentsRuntimeService,@@ -199,6 +223,17 @@ export class AgentDocumentsExecutionRuntime {return Promise.resolve(this.options.onDocumentsMutated?.(params));}+ /**+ * Mutations without a pre-read (copy, load rule) key off the binding id, so a+ * backing `docs_` id received through the `documentId` alias is resolved first.+ */+ private async resolveBindingId(agentId: string, id: string): Promise<string | undefined> {+ if (UUID_PATTERN.test(id)) return id;++ const existing = await this.service.readDocument({ agentId, id });+ return existing?.id;+ }+private resolveAgentId(context?: AgentDocumentOperationContext) {if (!context?.agentId) return;return context.agentId;@@ -393,6 +428,16 @@ export class AgentDocumentsExecutionRuntime {};}+ if (typeof args.content !== 'string') {+ return {+ content:+ 'createDocument requires `content` (the document body as markdown or plain text) and a `title`. Nothing was created.',+ success: false,+ };+ }+ // An omitted title falls back to the body's leading H1, then a default name.+ if (typeof args.title !== 'string') args = { ...args, title: '' };+const scope = args.scope ?? 'agent';const topicId = this.resolveTopicId(context);if (scope === 'currentTopic' && !topicId) {@@ -433,9 +478,13 @@ export class AgentDocumentsExecutionRuntime {}async readDocument(- args: ReadDocumentArgs,+ rawArgs: ReadDocumentArgs,context?: AgentDocumentOperationContext,): Promise<BuiltinServerRuntimeOutput> {+ const target = resolveTargetId(rawArgs, 'readDocument');+ if ('error' in target) return target.error;+ const args = target.args;+const agentId = this.resolveAgentId(context);if (!agentId) {return {@@ -456,9 +505,13 @@ export class AgentDocumentsExecutionRuntime {}async replaceDocumentContent(- args: ReplaceDocumentContentArgs,+ rawArgs: ReplaceDocumentContentArgs,context?: AgentDocumentOperationContext,): Promise<BuiltinServerRuntimeOutput> {+ const target = resolveTargetId(rawArgs, 'replaceDocumentContent');+ if ('error' in target) return target.error;+ let args = target.args;+const agentId = this.resolveAgentId(context);if (!agentId) {return {@@ -469,6 +522,8 @@ export class AgentDocumentsExecutionRuntime {const existing = await this.service.readDocument({ agentId, id: args.id });if (!existing) return { content: `Document not found: ${args.id}`, success: false };+ // A backing `docs_` id resolves on read; mutations key off the binding id.+ args = { ...args, id: existing.id || args.id };if (this.isCurrentPageDocument(existing, context)) {return this.buildCurrentPageDocumentWriteBlockedResult('replaceDocumentContent');@@ -501,9 +556,13 @@ export class AgentDocumentsExecutionRuntime {}async modifyNodes(- args: ModifyDocumentNodesArgs,+ rawArgs: ModifyDocumentNodesArgs,context?: AgentDocumentOperationContext,): Promise<BuiltinServerRuntimeOutput> {+ const target = resolveTargetId(rawArgs, 'modifyNodes');+ if ('error' in target) return target.error;+ let args = target.args;+const agentId = this.resolveAgentId(context);if (!agentId) {return {@@ -514,6 +573,8 @@ export class AgentDocumentsExecutionRuntime {const existing = await this.service.readDocument({ agentId, id: args.id });if (!existing) return { content: `Document not found: ${args.id}`, success: false };+ // A backing `docs_` id resolves on read; mutations key off the binding id.+ args = { ...args, id: existing.id || args.id };if (this.isCurrentPageDocument(existing, context)) {return this.buildCurrentPageDocumentWriteBlockedResult('modifyNodes');@@ -563,9 +624,13 @@ export class AgentDocumentsExecutionRuntime {}async removeDocument(- args: RemoveDocumentArgs,+ rawArgs: RemoveDocumentArgs,context?: AgentDocumentOperationContext,): Promise<BuiltinServerRuntimeOutput> {+ const target = resolveTargetId(rawArgs, 'removeDocument');+ if ('error' in target) return target.error;+ let args = target.args;+const agentId = this.resolveAgentId(context);if (!agentId) {return {@@ -580,6 +645,8 @@ export class AgentDocumentsExecutionRuntime {// impl previously ran this lookup imperatively for the delete registration).const existing = await this.service.readDocument({ agentId, id: args.id });if (!existing) return { content: `Document not found: ${args.id}`, success: false };+ // A backing `docs_` id resolves on read; mutations key off the binding id.+ args = { ...args, id: existing.id || args.id };const deleted = await this.service.removeDocument({...args,@@ -602,9 +669,13 @@ export class AgentDocumentsExecutionRuntime {}async renameDocument(- args: RenameDocumentArgs,+ rawArgs: RenameDocumentArgs,context?: AgentDocumentOperationContext,): Promise<BuiltinServerRuntimeOutput> {+ const target = resolveTargetId(rawArgs, 'renameDocument');+ if ('error' in target) return target.error;+ let args = target.args;+const agentId = this.resolveAgentId(context);if (!agentId) {return {@@ -615,6 +686,8 @@ export class AgentDocumentsExecutionRuntime {const existing = await this.service.readDocument({ agentId, id: args.id });if (!existing) return { content: `Document not found: ${args.id}`, success: false };+ // A backing `docs_` id resolves on read; mutations key off the binding id.+ args = { ...args, id: existing.id || args.id };if (this.isCurrentPageDocument(existing, context)) {return this.buildCurrentPageDocumentWriteBlockedResult('renameDocument');@@ -644,9 +717,12 @@ export class AgentDocumentsExecutionRuntime {}async copyDocument(- args: CopyDocumentArgs,+ rawArgs: CopyDocumentArgs,context?: AgentDocumentOperationContext,): Promise<BuiltinServerRuntimeOutput> {+ const target = resolveTargetId(rawArgs, 'copyDocument');+ if ('error' in target) return target.error;+const agentId = this.resolveAgentId(context);if (!agentId) {return {@@ -655,6 +731,10 @@ export class AgentDocumentsExecutionRuntime {};}+ const bindingId = await this.resolveBindingId(agentId, target.args.id);+ if (!bindingId) return { content: `Document not found: ${target.args.id}`, success: false };+ const args = { ...target.args, id: bindingId };+const copied = await this.service.copyDocument({...args,...this.buildToolTriggerInput(context),@@ -683,9 +763,12 @@ export class AgentDocumentsExecutionRuntime {}async updateLoadRule(- args: UpdateLoadRuleArgs,+ rawArgs: UpdateLoadRuleArgs,context?: AgentDocumentOperationContext,): Promise<BuiltinServerRuntimeOutput> {+ const target = resolveTargetId(rawArgs, 'updateLoadRule');+ if ('error' in target) return target.error;+const agentId = this.resolveAgentId(context);if (!agentId) {return {@@ -694,6 +777,10 @@ export class AgentDocumentsExecutionRuntime {};}+ const bindingId = await this.resolveBindingId(agentId, target.args.id);+ if (!bindingId) return { content: `Document not found: ${target.args.id}`, success: false };+ const args = { ...target.args, id: bindingId };+const updated = await this.service.updateLoadRule({ ...args, agentId });if (!updated) return { content: `Document not found: ${args.id}`, success: false };