🤯 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
⏪ revert(page-agent): revert sandboxed bash tool (#20156, #20318) (#20321)
Innei6f595d1254bf
diff --git a/apps/server/src/modules/Mecha/ContextEngineering/__tests__/serverMessagesEngine.test.ts b/apps/server/src/modules/Mecha/ContextEngineering/__tests__/serverMessagesEngine.test.tsindex c13c20f11b4..44d92af5045 100644--- a/apps/server/src/modules/Mecha/ContextEngineering/__tests__/serverMessagesEngine.test.ts+++ b/apps/server/src/modules/Mecha/ContextEngineering/__tests__/serverMessagesEngine.test.ts@@ -693,6 +693,27 @@ describe('serverMessagesEngine', () => {expect(result).toBeDefined();});++ it('should inject Page Editor context when provided', async () => {+ const messages = createBasicMessages();++ const { messages: result } = await serverMessagesEngine({+ messages,+ model: 'gpt-4',+ pageContentContext: {+ markdown: '# Test Document\n\nPage content',+ metadata: {+ charCount: 30,+ lineCount: 3,+ title: 'Test Document',+ },+ xml: '<doc><h1 id="1">Test Document</h1><p id="2">Page content</p></doc>',+ },+ provider: 'openai',+ });++ expect(result).toBeDefined();+ });});describe('input template', () => {@@ -903,6 +924,11 @@ describe('serverMessagesEngine', () => {},messages,model: 'gpt-4',+ pageContentContext: {+ markdown: '# Doc',+ metadata: { charCount: 5, lineCount: 1, title: 'Doc' },+ xml: '<doc><h1 id="1">Doc</h1></doc>',+ },provider: 'openai',});diff --git a/apps/server/src/modules/Mecha/ContextEngineering/index.ts b/apps/server/src/modules/Mecha/ContextEngineering/index.tsindex 3d355f9dbe0..b57a37d53f7 100644--- a/apps/server/src/modules/Mecha/ContextEngineering/index.ts+++ b/apps/server/src/modules/Mecha/ContextEngineering/index.ts@@ -42,6 +42,7 @@ export const toContextSnapshot = ({modelDisplayName,modelKnowledgeCutoff,onboardingContext,+ pageContentContext,planTodo,projectInstructions,provider,@@ -94,6 +95,7 @@ export const toContextSnapshot = ({agentManagementContext,groupAgentBuilderContext,onboardingContext,+ pageContentContext,planTodo,topicReferences,workspaceContext,diff --git a/apps/server/src/modules/Mecha/ContextEngineering/types.ts b/apps/server/src/modules/Mecha/ContextEngineering/types.tsindex d7ff2cf01a0..4717c712a45 100644--- a/apps/server/src/modules/Mecha/ContextEngineering/types.ts+++ b/apps/server/src/modules/Mecha/ContextEngineering/types.ts@@ -20,7 +20,7 @@ import type {UserMemoryData,WorkspaceContext,} from '@lobechat/context-engine';-import type { AgentIdentityContext } from '@lobechat/prompts';+import type { AgentIdentityContext, PageContentContext } from '@lobechat/prompts';import type {ExpertiseContextSnapshot,RuntimeAdditionalContextFragment,@@ -166,6 +166,9 @@ export interface ServerMessagesEngineParams {/** Model knowledge cutoff date, e.g. `2024-06`. Omit when unknown. */modelKnowledgeCutoff?: string;+ /** Page content context (optional, for document editing) */+ pageContentContext?: PageContentContext;+/** Plan document TODO state used when conversation messages contain no TODO state */planTodo?: PlanTodoConfig;@@ -208,3 +211,4 @@ export {type TopicReferenceItem,type UserMemoryData,} from '@lobechat/context-engine';+export type { PageContentContext } from '@lobechat/prompts';diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/pageAgent.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/pageAgent.test.tsdeleted file mode 100644index 5debab431a7..00000000000--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/pageAgent.test.ts+++ /dev/null@@ -1,117 +0,0 @@-// @vitest-environment node-import { beforeEach, describe, expect, it, vi } from 'vitest';--import { pageAgentRuntime } from '../pageAgent';--const mocks = vi.hoisted(() => ({- findById: vi.fn(),- runWithDocumentLock: vi.fn(),- updateDocument: vi.fn(),-}));--vi.mock('@/database/models/document', () => ({- DocumentModel: class {- findById = mocks.findById;- },-}));-vi.mock('@/server/services/document', () => ({- DocumentService: class {- runWithDocumentLock = mocks.runWithDocumentLock;- updateDocument = mocks.updateDocument;- },-}));--const ctx = { documentId: 'doc_1', userId: 'u1' };--const createRuntime = () =>- pageAgentRuntime.factory({ serverDB: {} as any, toolManifestMap: {}, userId: 'u1' }) as {- bash: (args: { command: string }, context: typeof ctx) => Promise<any>;- initPage: (args: { markdown: string }, context: typeof ctx) => Promise<any>;- };--describe('pageAgentRuntime bash', () => {- beforeEach(() => {- vi.clearAllMocks();- mocks.findById.mockResolvedValue({ content: 'para one\n', editorData: null, title: 'Page' });- mocks.runWithDocumentLock.mockImplementation((_id, fn) => fn('owner_1'));- });-- it('holds the document lock but writes nothing for a read-only command', async () => {- const result = await createRuntime().bash({ command: 'cat /doc.xml' }, ctx);-- expect(result.success).toBe(true);- expect(result.content).toContain('para one');- expect(mocks.runWithDocumentLock).toHaveBeenCalledWith('doc_1', expect.any(Function));- expect(mocks.updateDocument).not.toHaveBeenCalled();- });-- it('persists an edit as an llm_call save under the lock owner', async () => {- const result = await createRuntime().bash(- { command: "sed -i 's/para one/para ONE/' /doc.xml" },- ctx,- );-- expect(result.state).toMatchObject({ changed: true, documentId: 'doc_1' });- expect(result.state).not.toHaveProperty('documentEditorData');- expect(mocks.updateDocument).toHaveBeenCalledWith(- 'doc_1',- expect.objectContaining({- content: expect.stringContaining('para ONE'),- lockOwnerId: 'owner_1',- saveSource: 'llm_call',- }),- );- });-- it('persists only the title when only /title changes', async () => {- await createRuntime().bash({ command: "echo 'Renamed' > /title" }, ctx);-- expect(mocks.updateDocument).toHaveBeenCalledWith(- 'doc_1',- expect.not.objectContaining({ editorData: expect.anything() }),- );- expect(mocks.updateDocument.mock.calls[0][1]).toMatchObject({ title: 'Renamed' });- });-- it('still answers a read-only command while another member holds the lock', async () => {- mocks.runWithDocumentLock.mockRejectedValue(- Object.assign(new Error('Document is being edited by another user'), { code: 'CONFLICT' }),- );-- const result = await createRuntime().bash({ command: 'cat /doc.xml' }, ctx);-- expect(result.success).toBe(true);- expect(result.content).toContain('para one');- expect(mocks.updateDocument).not.toHaveBeenCalled();- });-- it('reports a lock conflict for a write without saving it', async () => {- mocks.runWithDocumentLock.mockRejectedValue(- Object.assign(new Error('Document is being edited by another user'), { code: 'CONFLICT' }),- );-- const result = await createRuntime().bash(- { command: "sed -i 's/para one/para ONE/' /doc.xml" },- ctx,- );-- expect(result.success).toBe(false);- expect(result.error.type).toBe('PageAgentDocumentLocked');- expect(mocks.updateDocument).not.toHaveBeenCalled();- });-- it('replaces the page from Markdown with initPage and saves it as an llm_call', async () => {- const result = await createRuntime().initPage({ markdown: '# Fresh\n\nnew body' }, ctx);-- expect(result.success).toBe(true);- expect(result.state).toMatchObject({ changed: true, documentId: 'doc_1' });- expect(mocks.updateDocument).toHaveBeenCalledWith(- 'doc_1',- expect.objectContaining({- content: expect.stringContaining('new body'),- saveSource: 'llm_call',- title: 'Fresh',- }),- );- });-});diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/pageAgentBash.rich.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/pageAgentBash.rich.test.tsdeleted file mode 100644index 45b6cdd6b3c..00000000000--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/pageAgentBash.rich.test.ts+++ /dev/null@@ -1,77 +0,0 @@-// @vitest-environment node-import { runPageBash } from '@lobechat/builtin-tool-page-agent/bash';-import { EditorRuntime } from '@lobechat/editor-runtime';-import { createHeadlessEditor } from '@lobehub/editor/headless';-import { describe, expect, it } from 'vitest';--const setup = (markdown: string) => {- const headless = createHeadlessEditor();- headless.hydrateMarkdown(markdown, { keepId: true });- const runtime = new EditorRuntime();- runtime.setEditor(headless.kernel as unknown as Parameters<EditorRuntime['setEditor']>[0]);- runtime.setTitleHandlers(- () => {},- () => 'Page',- );-- return {- markdown: () => headless.export().markdown.trim(),- run: (command: string) => runPageBash(runtime, command),- xml: () => runtime.getPageContentContext('xml').xml ?? '',- };-};--describe('runPageBash on rich content', () => {- it('edits a table cell and keeps the table', async () => {- const page = setup('| Plan | Price |\n| --- | --- |\n| Basic | 10 |\n| Pro | 25 |\n');-- const { state } = await page.run("sed -i 's/>25</>30</' /doc.xml");-- expect(state.changed).toBe(true);- expect(page.markdown()).toContain('| Pro');- expect(page.markdown()).toContain('30');- expect(page.markdown()).not.toContain('25');- expect(page.markdown()).toContain('| Basic');- });-- it('edits a list item and keeps the list', async () => {- const page = setup('- first\n- second\n- third\n');-- const { state } = await page.run("sed -i 's/second/SECOND/' /doc.xml");-- expect(state.changed).toBe(true);- expect(page.markdown()).toBe('- first\n- SECOND\n- third');- });-- it('edits one line of a code block and keeps the rest verbatim', async () => {- const page = setup('```ts\nconst a = 1;\nif (a < 2) console.log("<ok>");\n```\n');- const before = page.markdown();-- const { state } = await page.run("sed -i 's/const a = 1;/const a = 3;/' /doc.xml");-- expect(state.changed).toBe(true);- expect(page.markdown()).toBe(before.replace('const a = 1;', 'const a = 3;'));- });-- it('edits a paragraph next to an image without touching the image', async () => {- const page = setup('\n\nCaption text\n');- const before = page.markdown();-- const { state } = await page.run("sed -i 's/Caption text/New caption/' /doc.xml");-- expect(state.changed).toBe(true);- expect(page.markdown()).toBe(before.replace('Caption text', 'New caption'));- });-- // The editor's LiteXML import re-wraps a math node's code ("$E=mc^2$" comes- // back as "$$E=mc^2$$"); plain modifyNodes does the same, so only the formula- // text is asserted here.- it('edits text around inline math and keeps the formula', async () => {- const page = setup('Energy is $E=mc^2$ here\n');-- const { state } = await page.run("sed -i 's/ here/ indeed/' /doc.xml");-- expect(state.changed).toBe(true);- expect(page.markdown()).toMatch(/^Energy is \$+E=mc\^2\$+ indeed$/);- });-});diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/pageAgentBash.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/pageAgentBash.test.tsdeleted file mode 100644index 712a0285ad9..00000000000--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/pageAgentBash.test.ts+++ /dev/null@@ -1,286 +0,0 @@-// @vitest-environment node-import { createHook } from 'node:async_hooks';--import { PageChangedDuringCommandError, runPageBash } from '@lobechat/builtin-tool-page-agent/bash';-import { EditorRuntime } from '@lobechat/editor-runtime';-import { createHeadlessEditor } from '@lobehub/editor/headless';-import { describe, expect, it } from 'vitest';--const setup = (markdown: string, initialTitle = 'Old Title') => {- const headless = createHeadlessEditor();- if (markdown) headless.hydrateMarkdown(markdown, { keepId: true });- let title = initialTitle;-- const runtime = new EditorRuntime();- runtime.setEditor(headless.kernel as unknown as Parameters<EditorRuntime['setEditor']>[0]);- runtime.setTitleHandlers(- (next) => {- title = next;- },- () => title,- );-- return {- getTitle: () => title,- setTitle: (next: string) => {- title = next;- },- runtime,- markdown: () => headless.export().markdown.trim(),- run: (command: string) => runPageBash(runtime, command),- };-};--describe('runPageBash', () => {- it.each(['title', 'page'])(- 'does not rename after %s changes while the body is saved',- async (change) => {- const page = setup('body');- page.runtime.setCurrentDocId('original');- page.runtime.setAfterMutateHandler(async () => {- // The real client hook waits for a network save before editTitle runs.- await new Promise((resolve) => setTimeout(resolve, 0));- if (change === 'title') page.setTitle('User title');- else page.runtime.setCurrentDocId('another-page');- });-- await expect(- page.run("sed -i 's/body/BODY/' /doc.xml; echo 'Agent title' > /title"),- ).rejects.toThrow(/body changes.*review.*title.*not/i);- expect(page.markdown()).toBe('BODY');- expect(page.getTitle()).toBe(change === 'title' ? 'User title' : 'Old Title');- },- );-- it('rechecks after an asynchronous pre-mutation hook', async () => {- const page = setup('body');- page.runtime.setBeforeMutateHandler(async () => {- await new Promise((resolve) => setTimeout(resolve, 0));- page.setTitle('User title');- });-- await expect(page.run("sed -i 's/body/BODY/' /doc.xml")).rejects.toBeInstanceOf(- PageChangedDuringCommandError,- );- expect(page.markdown()).toBe('body');- });- it('reads the page without changing it', async () => {- const page = setup('para one\n\npara two\n');-- const { content, state } = await page.run('cat /doc.xml');-- expect(content).toContain('para two');- expect(state.changed).toBe(false);- expect(state.exitCode).toBe(0);- });-- it('does not expose a markdown copy of the page', async () => {- const page = setup('para one\n');-- const { state } = await page.run('ls /doc.md');-- expect(state.exitCode).not.toBe(0);- });-- it('ignores a /doc.md written by the command', async () => {- const page = setup('para one\n');-- const { content, state } = await page.run("echo '# New' > /doc.md");-- expect(state.changed).toBe(false);- expect(page.markdown()).toBe('para one');- expect(content).toContain('/doc.md');- });-- it('lists top-level blocks in the outline', async () => {- const page = setup('# Heading\n\npara one\n');-- const { content } = await page.run('cat /.meta/outline');-- expect(content).toMatch(/^\w{4} h1 Heading$/m);- expect(content).toMatch(/^\w{4} p para one$/m);- });-- it('applies an in-place edit of /doc.xml', async () => {- const page = setup('para one\n\npara two\n');-- const { content, state } = await page.run("sed -i 's/para two/para TWO/' /doc.xml");-- expect(state.changed).toBe(true);- expect(page.markdown()).toBe('para one\n\npara TWO');- expect(content).toContain('1 modified');- });-- it('commits file changes even when the command exits non-zero', async () => {- const page = setup('para one\n');-- const { content, state } = await page.run("sed -i 's/one/ONE/' /doc.xml && false");-- expect(state.changed).toBe(true);- expect(state.exitCode).toBe(1);- expect(page.markdown()).toBe('para ONE');- expect(content).toContain('exit 1');- });-- it('renames the page when /title is written', async () => {- const page = setup('body\n');-- const { state } = await page.run("echo 'New Title' > /title");-- expect(state.changed).toBe(true);- expect(page.getTitle()).toBe('New Title');- });-- it('rejects an empty title', async () => {- const page = setup('body\n');-- const { content, state } = await page.run(': > /title');-- expect(state.changed).toBe(false);- expect(page.getTitle()).toBe('Old Title');- expect(content).toMatch(/title/i);- });-- it('rejects a malformed /doc.xml without touching the page', async () => {- const page = setup('para one\n');-- const { content, state } = await page.run("echo '<root><p>broken</root>' > /doc.xml");-- expect(state.changed).toBe(false);- expect(page.markdown()).toBe('para one');- expect(content).toMatch(/not written|nothing was written/i);- });-- it('stubs interpreters with exit 127', async () => {- const page = setup('para one\n');-- const { content, state } = await page.run('python3 -c "print(1)"');-- expect(state.exitCode).toBe(127);- expect(content).toContain('not available');- });-- it('warns about files written outside /tmp and ignores them', async () => {- const page = setup('para one\n');-- const { content, state } = await page.run('echo hi > /notes.txt; echo ok > /tmp/scratch');-- expect(state.changed).toBe(false);- expect(content).toContain('/notes.txt');- expect(content).not.toContain('/tmp/scratch');- });-- it('writes nothing when the command hits an execution limit', async () => {- const page = setup('para one\n');-- const { content, state } = await page.run(- "sed -i 's/one/ONE/' /doc.xml; while true; do :; done",- );-- expect(state.changed).toBe(false);- expect(page.markdown()).toBe('para one');- expect(content).toMatch(/nothing was written/i);- });-- it('rejects blocks appended after </root>', async () => {- const page = setup('para one\n');-- const { content, state } = await page.run("printf '<p>two</p>\\n' >> /doc.xml");-- expect(state.changed).toBe(false);- expect(content).toMatch(/nothing was written/i);- });-- it('points an edit of an empty page at the initPage tool', async () => {- const page = setup('');-- const { content, state } = await page.run("echo '<root><p>hello</p></root>' > /doc.xml");-- expect(state.changed).toBe(false);- expect(content).toContain('initPage');- });-- it('rejects a rewrite that grows the page far beyond its size', async () => {- const page = setup('para one\n');-- // Double through the hold space to keep this size-limit fixture fast under coverage.- const { content, state } = await page.run(- "echo 0123456789 > /tmp/a; for i in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18; do sed -i 'h; G; s/\\n//' /tmp/a; done; cp /tmp/a /doc.xml",- );-- expect(state).toEqual({ changed: false, exitCode: 0, success: false });- expect(page.markdown()).toBe('para one');- expect(content).toMatch(/too large/i);- });-- it('keeps command output out of the tool state', async () => {- const page = setup('para one\n');-- const { state } = await page.run('cat /doc.xml');-- expect(state).not.toHaveProperty('output');- });-- it('lets host async hooks read timers while a command executes', async () => {- const page = setup('para one\n');- const errors: unknown[] = [];- // Next.js installs an async hook that reads performance.now for every new- // promise; a throw from inside an async hook kills the whole process.- const hook = createHook({- init() {- try {- performance.now();- } catch (error) {- errors.push(error);- }- },- }).enable();-- const { state } = await page.run('cat /doc.xml');- hook.disable();-- expect(errors).toEqual([]);- expect(state.exitCode).toBe(0);- });-- it('decodes non-ASCII text written through a redirect as UTF-8', async () => {- const page = setup('café price $10 for alice\n');-- await page.run(- `awk '{gsub(/\\$10/, "\\xe2\\x82\\xac70"); gsub(/alice/, "张三"); print}' /doc.xml > /tmp/n && cp /tmp/n /doc.xml`,- );-- expect(page.markdown()).toBe('café price €70 for 张三');- });-- it('refuses to write when the page changed while the command ran', async () => {- const page = setup('para one\n\npara two\n');- const read = page.runtime.getPageContentContext.bind(page.runtime);- let reads = 0;- page.runtime.getPageContentContext = (format) => {- reads += 1;- const context = read(format);- return reads === 1 ? context : { ...context, xml: context.xml!.replace('para two', 'typed') };- };-- await expect(page.run("sed -i 's/para one/para ONE/' /doc.xml")).rejects.toBeInstanceOf(- PageChangedDuringCommandError,- );- expect(page.markdown()).toBe('para one\n\npara two');- });-- it('refuses to write when the editor went away while the command ran', async () => {- const page = setup('para one\n');- const read = page.runtime.getPageContentContext.bind(page.runtime);- let reads = 0;- page.runtime.getPageContentContext = (format) => {- reads += 1;- if (reads > 1) throw new Error('Editor not initialized.');- return read(format);- };-- await expect(page.run("sed -i 's/one/ONE/' /doc.xml")).rejects.toBeInstanceOf(- PageChangedDuringCommandError,- );- });-});diff --git a/apps/server/src/services/toolExecution/serverRuntimes/pageAgent.ts b/apps/server/src/services/toolExecution/serverRuntimes/pageAgent.tsindex 61390a00f18..e371f5958ac 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/pageAgent.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/pageAgent.ts@@ -1,11 +1,10 @@-import { PageAgentIdentifier, type PageAgentToolState } from '@lobechat/builtin-tool-page-agent';-import { runPageBash } from '@lobechat/builtin-tool-page-agent/bash';+import { PageAgentIdentifier } from '@lobechat/builtin-tool-page-agent';import {PageAgentExecutionRuntime,type PageAgentInvocationContext,type PageAgentRuntimeService,} from '@lobechat/builtin-tool-page-agent/executionRuntime';-import { EditorRuntime } from '@lobechat/editor-runtime';+import { EditorRuntime, formatModifyNodesResult } from '@lobechat/editor-runtime';import { createHeadlessEditor, type HeadlessEditor } from '@lobehub/editor/headless';import type { SerializedEditorState, SerializedLexicalNode } from 'lexical';@@ -60,12 +59,34 @@ interface InvariantViolation {kind: 'silent-no-op' | 'unexpected-mutation';}-const detectHandlerReportedChange = (state: PageAgentToolState): boolean => state.changed === true;+const detectHandlerReportedChange = (apiName: string, state: Record<string, unknown>): boolean => {+ switch (apiName) {+ case 'modifyNodes': {+ const successCount = state.successCount;+ return typeof successCount === 'number' && successCount > 0;+ }+ case 'replaceText': {+ const count = state.replacementCount;+ return typeof count === 'number' && count > 0;+ }+ case 'initPage': {+ const nodeCount = state.nodeCount;+ return typeof nodeCount === 'number' && nodeCount > 0;+ }+ default: {+ return false;+ }+ }+};const detectInvariantViolation = (apiName: string,flags: InvariantFlags,): InvariantViolation | undefined => {+ // editTitle is exempt: title lives outside editorData, so editorChanged is+ // expected to be false.+ if (apiName === 'editTitle') return undefined;+if (flags.handlerReportedChange && !flags.editorChanged && !flags.titleChanged) {return {apiName,@@ -147,9 +168,17 @@ const buildEnv = (snapshot: DocumentSnapshot, documentId: string): InvocationEnv};};+interface WithEditorOptions {+ exportEditorData?: boolean;+ /** Whether to enforce silent-failure invariant checks on this invocation. */+ invariantCheck?: boolean;+ /** Whether to persist any captured patch back to the document row. */+ persist?: boolean;+}+interface HandlerOutput {content: string;- state: PageAgentToolState;+ state: Record<string, unknown>;}const withEditor = async (@@ -157,30 +186,48 @@ const withEditor = async (apiName: string,ctx: PageAgentInvocationContext,handler: (env: InvocationEnv) => Promise<HandlerOutput>,+ options: WithEditorOptions = {},): Promise<HandlerOutput> => {const documentId = ctx.documentId;+ // The runtime shell already rejected missing documentId; this guard is for+ // type-narrowing only.if (!documentId) {throw new Error('documentId is required');}- const run = async (persist: boolean, lockOwnerId?: string): Promise<HandlerOutput> => {+ const exportEditorData = options.exportEditorData !== false;+ const persist = options.persist !== false;+ const invariantCheck = options.invariantCheck !== false;++ // Acquire the collaborative edit lock around the entire read-modify-write so+ // the agent reads, mutates and persists atomically: serialized against other+ // workspace members and rejected (CONFLICT) when someone else is actively+ // editing, instead of silently clobbering their work. Read-only invocations+ // (persist: false) never write, so they skip the lock.+ const run = async (lockOwnerId?: string): Promise<HandlerOutput> => {const snapshot = await loadSnapshot(documentModel, documentId);const env = buildEnv(snapshot, documentId);try {- const beforeHash = hashEditorData(env.headless.export().editorData);+ const beforeHash = exportEditorData+ ? hashEditorData(env.headless.export().editorData)+ : undefined;const handlerResult = await handler(env);- const exported = env.headless.export();+ const exported = exportEditorData ? env.headless.export() : undefined;+ const afterHash = exported ? hashEditorData(exported.editorData) : undefined;const titleChanged = env.getTitle() !== snapshot.title;- const editorChanged = beforeHash !== hashEditorData(exported.editorData);+ const editorChanged =+ exportEditorData && beforeHash !== undefined && beforeHash !== afterHash;- const invariantViolation = detectInvariantViolation(apiName, {- editorChanged,- handlerReportedChange: detectHandlerReportedChange(handlerResult.state),- titleChanged,- });+ const invariantViolation = invariantCheck+ ? detectInvariantViolation(apiName, {+ editorChanged,+ handlerReportedChange: detectHandlerReportedChange(apiName, handlerResult.state),+ titleChanged,+ })+ : undefined;if (invariantViolation) {console.warn(@@ -190,15 +237,26 @@ const withEditor = async ();}- if (persist && (editorChanged || titleChanged)) {+ const patch: {+ content?: string;+ editorData?: Record<string, unknown>;+ title?: string;+ } = {};+ if (exported) {+ patch.content = exported.markdown;+ patch.editorData = exported.editorData as unknown as Record<string, unknown>;+ }+ if (titleChanged) {+ patch.title = env.getTitle();+ }++ if (persist && Object.keys(patch).length > 0) {await documentService.updateDocument(documentId, {- ...(editorChanged && {- content: exported.markdown,- editorData: exported.editorData as unknown as Record<string, unknown>,- }),+ content: patch.content,+ editorData: patch.editorData,...(lockOwnerId ? { lockOwnerId } : {}),saveSource: 'llm_call',- ...(titleChanged && { title: env.getTitle() }),+ title: patch.title,});}@@ -206,6 +264,9 @@ const withEditor = async (content: handlerResult.content,state: {...handlerResult.state,+ documentContent: patch.content,+ documentEditorData: patch.editorData,+ documentTitle: env.getTitle(),...(invariantViolation ? { invariantViolation } : {}),},};@@ -214,19 +275,7 @@ const withEditor = async (}};- // Whether a command writes is only known after it runs, so it first runs- // under the collaborative edit lock. While another member holds the lock it- // reruns without saving: reads still answer, writes surface the CONFLICT.- try {- return await documentService.runWithDocumentLock(documentId, (lockOwnerId) =>- run(true, lockOwnerId),- );- } catch (error) {- if ((error as { code?: string }).code !== 'CONFLICT') throw error;- const unsaved = await run(false);- if (unsaved.state.changed) throw error;- return unsaved;- }+ return persist ? documentService.runWithDocumentLock(documentId, run) : run();};const buildService = (@@ -239,21 +288,109 @@ const buildService = (const serviceCtx: PageAgentServiceContext = { documentModel, documentService };return {- bash: (args, ctx) =>- withEditor(serviceCtx, 'bash', ctx, ({ runtime }) => runPageBash(runtime, args.command)),+ editTitle: (args, ctx) =>+ withEditor(+ serviceCtx,+ 'editTitle',+ ctx,+ async ({ runtime }) => {+ const result = await runtime.editTitle(args);+ return {+ content: `Title changed from "${result.previousTitle}" to "${result.newTitle}".`,+ state: { newTitle: result.newTitle, previousTitle: result.previousTitle },+ };+ },+ { exportEditorData: false },+ ),++ getPageContent: (args, ctx) =>+ withEditor(+ serviceCtx,+ 'getPageContent',+ ctx,+ async ({ runtime, getTitle }) => {+ const result = await runtime.getPageContent(args);+ return {+ content: result.markdown || result.xml || '',+ state: {+ markdown: result.markdown,+ metadata: {+ fileType: 'document',+ title: getTitle(),+ totalCharCount: result.charCount,+ totalLineCount: result.lineCount,+ },+ xml: result.xml,+ },+ };+ },+ { persist: false },+ ),+initPage: (args, ctx) =>withEditor(serviceCtx, 'initPage', ctx, async ({ runtime }) => {- const { extractedTitle, nodeCount } = await runtime.initPage(args);+ const result = await runtime.initPage(args);+ return {+ content: result.extractedTitle+ ? `Document initialized with ${result.nodeCount} nodes. Title "${result.extractedTitle}" extracted and set.`+ : `Document initialized with ${result.nodeCount} nodes.`,+ state: {+ extractedTitle: result.extractedTitle,+ nodeCount: result.nodeCount,+ rootId: 'root',+ },+ };+ }),++ modifyNodes: (args, ctx) =>+ withEditor(serviceCtx, 'modifyNodes', ctx, async ({ runtime }) => {+ const result = await runtime.modifyNodes(args);return {- content: extractedTitle- ? `Page replaced with ${nodeCount} blocks; title set to "${extractedTitle}".`- : `Page replaced with ${nodeCount} blocks.`,- state: { changed: true, nodeCount, rootId: 'root' },+ content: formatModifyNodesResult(result),+ state: {+ results: result.results,+ successCount: result.successCount,+ totalCount: result.totalCount,+ },+ };+ }),++ replaceText: (args, ctx) =>+ withEditor(serviceCtx, 'replaceText', ctx, async ({ runtime }) => {+ const result = await runtime.replaceText(args);+ const scope = args.nodeIds?.length+ ? `within ${args.nodeIds.length} specified node(s)`+ : 'across the document';+ const content =+ result.replacementCount > 0+ ? `Successfully replaced ${result.replacementCount} occurrence(s) of "${args.searchText}" with "${args.newText}" ${scope}. Modified ${result.modifiedNodeIds.length} node(s).`+ : `No occurrences of "${args.searchText}" found ${scope}.`;+ return {+ content,+ state: {+ modifiedNodeIds: result.modifiedNodeIds,+ replacementCount: result.replacementCount,+ },};}),};};+/**+ * Registers the page-agent builtin server runtime.+ *+ * Each tool invocation:+ * 1. loads the `documents` row,+ * 2. hydrates a `@lobehub/editor` HeadlessEditor from `editorData`/`content`,+ * 3. runs the requested page-agent API via the shared `EditorRuntime`,+ * 4. exports the new Lexical state and writes it back via+ * `DocumentService.updateDocument` (saveSource: 'llm_call' → also appends+ * a `documentHistories` snapshot).+ *+ * The renderer's `PageAgentExecutor.onAfterCall` consumes the returned+ * `result.state.document*` fields to apply the new editorData to the live+ * Lexical editor and reconcile the document store.+ */export const pageAgentRuntime: ServerRuntimeRegistration = {factory: (context) => {if (!context.userId || !context.serverDB) {diff --git a/locales/en-US/plugin.json b/locales/en-US/plugin.jsonindex f10d0bb22ec..602c957110f 100644--- a/locales/en-US/plugin.json+++ b/locales/en-US/plugin.json@@ -386,7 +386,6 @@"builtins.lobe-notebook.apiName.getDocument": "Get document","builtins.lobe-notebook.apiName.updateDocument": "Update document","builtins.lobe-notebook.title": "Notebook",- "builtins.lobe-page-agent.apiName.bash": "Work on page","builtins.lobe-page-agent.apiName.batchUpdate": "Batch update nodes","builtins.lobe-page-agent.apiName.compareSnapshots": "Compare snapshots","builtins.lobe-page-agent.apiName.convertToList": "Convert to list",diff --git a/locales/zh-CN/plugin.json b/locales/zh-CN/plugin.jsonindex c9a7029a769..1e42929b0ee 100644--- a/locales/zh-CN/plugin.json+++ b/locales/zh-CN/plugin.json@@ -386,7 +386,6 @@"builtins.lobe-notebook.apiName.getDocument": "获取文档","builtins.lobe-notebook.apiName.updateDocument": "更新文档","builtins.lobe-notebook.title": "笔记本",- "builtins.lobe-page-agent.apiName.bash": "处理页面","builtins.lobe-page-agent.apiName.batchUpdate": "批量更新节点","builtins.lobe-page-agent.apiName.compareSnapshots": "比较快照","builtins.lobe-page-agent.apiName.convertToList": "转换为列表",diff --git a/package.json b/package.jsonindex 7c5594e44fc..ea6735a6741 100644--- a/package.json+++ b/package.json@@ -401,7 +401,6 @@"js-sha256": "^0.11.1","jsondiffpatch": "^0.7.6","jsonl-parse-stringify": "^1.0.3",- "just-bash": "^3.4.2","keygrip": "^1.1.0","langfuse": "^3.38.20","langfuse-core": "^3.38.20",diff --git a/packages/builtin-tool-page-agent/package.json b/packages/builtin-tool-page-agent/package.jsonindex 1635faebe37..a95dd62855c 100644--- a/packages/builtin-tool-page-agent/package.json+++ b/packages/builtin-tool-page-agent/package.json@@ -4,16 +4,13 @@"private": true,"exports": {".": "./src/index.ts",- "./bash": "./src/bash/index.ts","./client": "./src/client/index.ts","./client/executor": "./src/client/executor/index.ts","./executionRuntime": "./src/ExecutionRuntime/index.ts"},"main": "./src/index.ts","dependencies": {- "@lobechat/editor-runtime": "workspace:*",- "@lobechat/shared-tool-ui": "workspace:*",- "just-bash": "^3.4.2"+ "@lobechat/editor-runtime": "workspace:*"},"devDependencies": {"@lobechat/types": "workspace:*"diff --git a/packages/builtin-tool-page-agent/src/ExecutionRuntime/index.test.ts b/packages/builtin-tool-page-agent/src/ExecutionRuntime/index.test.tsindex 6489f2ad2fa..32f4c5fb796 100644--- a/packages/builtin-tool-page-agent/src/ExecutionRuntime/index.test.ts+++ b/packages/builtin-tool-page-agent/src/ExecutionRuntime/index.test.ts@@ -8,78 +8,104 @@ const DOC_ID = 'doc_test_1';const ctxWithDoc: PageAgentInvocationContext = { documentId: DOC_ID, userId: 'u1' };const ctxNoDoc: PageAgentInvocationContext = { userId: 'u1' };-const state = (changed: boolean) => ({ changed, exitCode: 0, output: '', success: true });--const buildService = (bash?: PageAgentRuntimeService['bash']): PageAgentRuntimeService => ({- bash: vi.fn(bash ?? (async () => ({ content: 'ok', state: state(false) }))),- initPage: vi.fn(async () => ({- content: 'initialized',- state: { changed: true, nodeCount: 1, rootId: 'root' },- })),-});--describe('PageAgentExecutionRuntime', () => {- it('rejects a call without documentId and never reaches the service', async () => {- const service = buildService();- const runtime = new PageAgentExecutionRuntime(service);-- const result = await runtime.bash({ command: 'cat /doc.md' }, ctxNoDoc);-- expect(result.success).toBe(false);- expect((result.error as { type?: string }).type).toBe('PageAgentMissingDocumentId');- expect(service.bash).not.toHaveBeenCalled();- });-- it('forwards the command with context and envelopes the output with documentId', async () => {- const service = buildService(async () => ({ content: 'changed', state: state(true) }));- const runtime = new PageAgentExecutionRuntime(service);-- const result = await runtime.bash({ command: 'sed -i s/a/b/ /doc.xml' }, ctxWithDoc);-- expect(service.bash).toHaveBeenCalledWith({ command: 'sed -i s/a/b/ /doc.xml' }, ctxWithDoc);- expect(result.success).toBe(true);- expect(result.content).toBe('changed');- expect(result.state).toMatchObject({ changed: true, documentId: DOC_ID });+const buildService = (+ overrides: Partial<PageAgentRuntimeService> = {},+): PageAgentRuntimeService => {+ const ok = async (apiName: string) => ({+ content: `ok:${apiName}`,+ state: { ran: apiName },});+ return {+ editTitle: vi.fn(() => ok('editTitle')),+ getPageContent: vi.fn(() => ok('getPageContent')),+ initPage: vi.fn(() => ok('initPage')),+ modifyNodes: vi.fn(() => ok('modifyNodes')),+ replaceText: vi.fn(() => ok('replaceText')),+ ...overrides,+ };+};- it('wraps thrown service errors as PageAgentRuntimeError', async () => {- const runtime = new PageAgentExecutionRuntime(- buildService(async () => {- throw new Error('boom');- }),- );-- const result = await runtime.bash({ command: 'true' }, ctxWithDoc);-- expect(result.success).toBe(false);- expect(result.content).toBe('boom');- expect((result.error as { type?: string }).type).toBe('PageAgentRuntimeError');+describe('PageAgentExecutionRuntime', () => {+ describe('documentId guard', () => {+ it('rejects every API call when documentId is missing', async () => {+ const service = buildService();+ const runtime = new PageAgentExecutionRuntime(service);++ const results = await Promise.all([+ runtime.initPage({ markdown: '# Hi' }, ctxNoDoc),+ runtime.editTitle({ title: 'x' }, ctxNoDoc),+ runtime.getPageContent({}, ctxNoDoc),+ runtime.modifyNodes({ operations: [{ action: 'remove', id: 'a' }] }, ctxNoDoc),+ runtime.replaceText({ newText: 'a', searchText: 'b' }, ctxNoDoc),+ ]);++ for (const result of results) {+ expect(result.success).toBe(false);+ expect((result.error as { type?: string }).type).toBe('PageAgentMissingDocumentId');+ }++ // Service callbacks never invoked.+ expect(service.initPage).not.toHaveBeenCalled();+ expect(service.editTitle).not.toHaveBeenCalled();+ expect(service.getPageContent).not.toHaveBeenCalled();+ expect(service.modifyNodes).not.toHaveBeenCalled();+ expect(service.replaceText).not.toHaveBeenCalled();+ });});- it('explains a document lock conflict in words the model can act on', async () => {- const runtime = new PageAgentExecutionRuntime(- buildService(async () => {- throw Object.assign(new Error('Document is being edited by another user'), {- code: 'CONFLICT',- });- }),- );-- const result = await runtime.bash({ command: 'true' }, ctxWithDoc);-- expect(result.success).toBe(false);- expect((result.error as { type?: string }).type).toBe('PageAgentDocumentLocked');- expect(result.content).toMatch(/another member/);- expect(result.content).toMatch(/nothing was written/i);+ describe('forwarding', () => {+ it('forwards each API call to the service with args + context', async () => {+ const service = buildService();+ const runtime = new PageAgentExecutionRuntime(service);++ await runtime.modifyNodes({ operations: [{ action: 'remove', id: 'a' }] }, ctxWithDoc);++ expect(service.modifyNodes).toHaveBeenCalledWith(+ { operations: [{ action: 'remove', id: 'a' }] },+ ctxWithDoc,+ );+ });++ it('envelopes the service output with success + documentId', async () => {+ const service = buildService({+ modifyNodes: async () => ({+ content: 'changed',+ state: { successCount: 3 },+ }),+ });+ const runtime = new PageAgentExecutionRuntime(service);++ const result = await runtime.modifyNodes(+ { operations: [{ action: 'remove', id: 'a' }] },+ ctxWithDoc,+ );++ expect(result.success).toBe(true);+ expect(result.content).toBe('changed');+ expect(result.state).toMatchObject({+ documentId: DOC_ID,+ successCount: 3,+ });+ });});- it('forwards initPage to the service', async () => {- const service = buildService();- const runtime = new PageAgentExecutionRuntime(service);-- const result = await runtime.initPage({ markdown: '# Hi' }, ctxWithDoc);-- expect(service.initPage).toHaveBeenCalledWith({ markdown: '# Hi' }, ctxWithDoc);- expect(result).toMatchObject({ content: 'initialized', success: true });+ describe('error envelope', () => {+ it('wraps thrown service errors as PageAgentRuntimeError', async () => {+ const service = buildService({+ modifyNodes: async () => {+ throw new Error('boom');+ },+ });+ const runtime = new PageAgentExecutionRuntime(service);++ const result = await runtime.modifyNodes(+ { operations: [{ action: 'remove', id: 'a' }] },+ ctxWithDoc,+ );++ expect(result.success).toBe(false);+ expect(result.content).toBe('boom');+ expect((result.error as { type?: string }).type).toBe('PageAgentRuntimeError');+ });});});diff --git a/packages/builtin-tool-page-agent/src/ExecutionRuntime/index.ts b/packages/builtin-tool-page-agent/src/ExecutionRuntime/index.tsindex 61d5e201644..6b2555d6f61 100644--- a/packages/builtin-tool-page-agent/src/ExecutionRuntime/index.ts+++ b/packages/builtin-tool-page-agent/src/ExecutionRuntime/index.ts@@ -1,8 +1,19 @@-import type { InitDocumentArgs } from '@lobechat/editor-runtime';+import type {+ EditTitleArgs,+ GetPageContentArgs,+ InitDocumentArgs,+ ModifyNodesArgs,+ ReplaceTextArgs,+} from '@lobechat/editor-runtime';import type { BuiltinServerRuntimeOutput } from '@lobechat/types';-import type { BashArgs, PageAgentToolState } from '../types';-+/**+ * Context passed to every page-agent server invocation.+ *+ * Mirrors the subset of `BuiltinToolContext` the page-agent tools rely on.+ * Kept minimal so this package does not depend on `@lobechat/types`'+ * full context shape (which carries renderer-only fields).+ */export interface PageAgentInvocationContext {documentId?: string | null;operationId?: string;@@ -11,33 +22,75 @@ export interface PageAgentInvocationContext {userId?: string;}+/**+ * Shape every page-agent API callback must return. The runtime shell wraps+ * this into a `BuiltinServerRuntimeOutput` (filling `success: true`, adding+ * `documentId` to the state envelope, attaching error metadata on throw).+ */export interface PageAgentApiOutput {content: string;- state: PageAgentToolState;+ state?: Record<string, unknown>;}+/**+ * Service contract that host code (server runtime registration) implements.+ *+ * Implementations are expected to:+ * 1. Load the document row identified by `ctx.documentId`.+ * 2. Run the requested mutation against a `HeadlessEditor` + `EditorRuntime`+ * pair (page-agent tools always operate on a single document).+ * 3. Persist the new editorData/content/title back through `DocumentService`.+ * 4. Return both a human-readable `content` string and a `state` object+ * with at least `documentEditorData` / `documentContent` /+ * `documentTitle` so the renderer's `onAfterCall` hook can apply the+ * patch to the live Lexical editor without an extra DB roundtrip.+ *+ * Keeping the contract here (and the implementation at the registration site)+ * avoids dragging `@lobehub/editor` / `@lobechat/editor-runtime` into this+ * package's static import graph.+ */export interface PageAgentRuntimeService {- bash: (args: BashArgs, ctx: PageAgentInvocationContext) => Promise<PageAgentApiOutput>;+ editTitle: (args: EditTitleArgs, ctx: PageAgentInvocationContext) => Promise<PageAgentApiOutput>;+ getPageContent: (+ args: GetPageContentArgs,+ ctx: PageAgentInvocationContext,+ ) => Promise<PageAgentApiOutput>;initPage: (args: InitDocumentArgs,ctx: PageAgentInvocationContext,) => Promise<PageAgentApiOutput>;+ modifyNodes: (+ args: ModifyNodesArgs,+ ctx: PageAgentInvocationContext,+ ) => Promise<PageAgentApiOutput>;+ replaceText: (+ args: ReplaceTextArgs,+ ctx: PageAgentInvocationContext,+ ) => Promise<PageAgentApiOutput>;}const MISSING_DOCUMENT_ID ='PageAgent server runtime received a tool call without documentId in context. ' +'The conversation must be scoped to an open page editor.';-const DOCUMENT_LOCKED =- 'The page is being edited by another member right now, so nothing was written. ' +- 'Tell the user, or retry the same command later.';-const failure = (message: string, type: string, body?: unknown): BuiltinServerRuntimeOutput => ({content: message,error: { body, message, type } as unknown,success: false,});+/**+ * Server-side page-agent execution runtime.+ *+ * The runtime is a thin shell:+ * - validates `documentId` is present+ * - forwards to the host-supplied {@link PageAgentRuntimeService}+ * - normalizes success / failure into {@link BuiltinServerRuntimeOutput}+ *+ * All editor wiring (HeadlessEditor hydration, EditorRuntime invocation,+ * exports, persistence, silent-failure detection) lives in the consumer of+ * this class — see `src/server/services/toolExecution/serverRuntimes/pageAgent.ts`.+ */export class PageAgentExecutionRuntime {private service: PageAgentRuntimeService;@@ -45,12 +98,21 @@ export class PageAgentExecutionRuntime {this.service = service;}- bash = (args: BashArgs, ctx: PageAgentInvocationContext) =>- this.dispatch('bash', ctx, () => this.service.bash(args, ctx));-initPage = (args: InitDocumentArgs, ctx: PageAgentInvocationContext) =>this.dispatch('initPage', ctx, () => this.service.initPage(args, ctx));+ editTitle = (args: EditTitleArgs, ctx: PageAgentInvocationContext) =>+ this.dispatch('editTitle', ctx, () => this.service.editTitle(args, ctx));++ getPageContent = (args: GetPageContentArgs, ctx: PageAgentInvocationContext) =>+ this.dispatch('getPageContent', ctx, () => this.service.getPageContent(args, ctx));++ modifyNodes = (args: ModifyNodesArgs, ctx: PageAgentInvocationContext) =>+ this.dispatch('modifyNodes', ctx, () => this.service.modifyNodes(args, ctx));++ replaceText = (args: ReplaceTextArgs, ctx: PageAgentInvocationContext) =>+ this.dispatch('replaceText', ctx, () => this.service.replaceText(args, ctx));+private async dispatch(apiName: string,ctx: PageAgentInvocationContext,@@ -68,10 +130,7 @@ export class PageAgentExecutionRuntime {success: true,};} catch (error) {- const err = error as Error & { code?: string };- if (err.code === 'CONFLICT') {- return failure(DOCUMENT_LOCKED, 'PageAgentDocumentLocked', err);- }+ const err = error as Error;console.error(`[PageAgentExecutionRuntime] ${apiName} error`, err);return failure(err.message, 'PageAgentRuntimeError', err);}diff --git a/packages/builtin-tool-page-agent/src/bash/index.test.ts b/packages/builtin-tool-page-agent/src/bash/index.test.tsdeleted file mode 100644index f34d4f1d424..00000000000--- a/packages/builtin-tool-page-agent/src/bash/index.test.ts+++ /dev/null@@ -1,34 +0,0 @@-import { fileURLToPath } from 'node:url';--import { build } from 'esbuild';-import { describe, expect, it } from 'vitest';--describe('page bash bundle', () => {- it('does not pull optional language runtimes into the server bundle', async () => {- const optionalRuntimes = ['sql.js', 'typescript', 'quickjs-emscripten', 'run'];- const result = await build({- bundle: true,- entryPoints: [fileURLToPath(new URL('./index.ts', import.meta.url))],- external: [- '@lobechat/editor-runtime',- '@mongodb-js/zstd',- 'node-liblzma',- ...optionalRuntimes,- ],- format: 'esm',- metafile: true,- platform: 'node',- write: false,- });-- const imports = Object.values(result.metafile.outputs).flatMap((output) =>- output.imports.map((dependency) => dependency.path),- );- expect(imports.filter((dependency) => optionalRuntimes.includes(dependency))).toEqual([]);- expect(- Object.keys(result.metafile.inputs).filter((path) =>- /cpython|sqlite3-worker|js-exec-worker/.test(path),- ),- ).toEqual([]);- });-});diff --git a/packages/builtin-tool-page-agent/src/bash/index.ts b/packages/builtin-tool-page-agent/src/bash/index.tsdeleted file mode 100644index 538aa3dd105..00000000000--- a/packages/builtin-tool-page-agent/src/bash/index.ts+++ /dev/null@@ -1,269 +0,0 @@-import {- diffLiteXMLBlocks,- type EditorRuntime,- formatModifyNodesResult,- parseLiteXMLBlocks,-} from '@lobechat/editor-runtime';-import type { CommandName } from 'just-bash/browser';--import type { BashState } from '../types';--const DOC_XML = '/doc.xml';-const TITLE = '/title';-const OUTLINE = '/.meta/outline';--const ALLOWED_COMMANDS: CommandName[] = [- 'awk',- 'basename',- 'cat',- 'cp',- 'cut',- 'diff',- 'dirname',- 'echo',- 'egrep',- 'false',- 'fgrep',- 'find',- 'grep',- 'head',- 'help',- 'ls',- 'mkdir',- 'mv',- 'printf',- 'pwd',- 'rg',- 'rm',- 'sed',- 'sort',- 'tail',- 'tee',- 'touch',- 'tr',- 'tree',- 'true',- 'uniq',- 'wc',- 'which',-];--const STUB_COMMANDS = ['python3', 'python', 'pip', 'node', 'nodejs', 'perl', 'ruby', 'php'];--const AVAILABLE_HINT = `Available: ${ALLOWED_COMMANDS.join(' ')}`;--const MAX_OUTPUT_BYTES = 1024 * 1024;-// Stays well under the 30s edit-lock lease the server holds around a call.-const MAX_EXECUTION_MS = 10_000;--const buildOutline = (xml: string) => {- const blocks = parseLiteXMLBlocks(xml);- if (typeof blocks === 'string' || blocks.length === 0) return '';-- return `${blocks- .map(({ id, tag, text }) => `${id ?? '-'} ${tag} ${text.slice(0, 80)}`.trim())- .join('\n')}\n`;-};--const MIN_SIZE_LIMIT = 2 * 1024 * 1024;--const isTooLarge = (next: string, previous: string) =>- next.length > Math.max(4 * previous.length, MIN_SIZE_LIMIT);--const strictUtf8 = new TextDecoder('utf-8', { fatal: true });-const UTF8_BYTE_SEQUENCE =- /[\u00C2-\u00DF][\u0080-\u00BF]|[\u00E0-\u00EF][\u0080-\u00BF]{2}|[\u00F0-\u00F4][\u0080-\u00BF]{3}/g;--// just-bash stores bytes a command wrote through a redirect (awk "\xe2\x82\xac")-// as one char per byte, while literal text stays as real chars, so a read-back-// file can mix both. Only sequences that are valid UTF-8 are decoded; a lone-// Latin-1 char such as "é" is not one and stays as is.-// ponytail: page text that genuinely contains mojibake like "é" would be decoded too.-const decodeByteSequences = (text: string) =>- text.replaceAll(UTF8_BYTE_SEQUENCE, (bytes) => {- try {- return strictUtf8.decode(Uint8Array.from(bytes, (char) => char.charCodeAt(0)));- } catch {- return bytes;- }- });--const readIfExists = async (- fs: { exists: (path: string) => Promise<boolean>; readFile: (path: string) => Promise<string> },- path: string,-) => ((await fs.exists(path)) ? decodeByteSequences(await fs.readFile(path)) : undefined);--export class PageChangedDuringCommandError extends Error {- constructor(bodyChanged = false) {- super(- bodyChanged- ? 'The body changes were saved for review, but the page changed while saving, so the title was not changed. Tell the user what completed and read the page again before retrying.'- : 'The page changed while the command was running (it was edited or another page was opened), so nothing was written. Tell the user; if they still want the edit, read the page again before retrying.',- );- this.name = 'PageChangedDuringCommandError';- }-}--// The command works on a snapshot; a live editor can change under it while it-// runs, and applying ids from that snapshot would overwrite the user's typing-// or land on another page.-const assertPageUnchanged = (- runtime: EditorRuntime,- xml: string,- title: string,- documentId: string | undefined,- bodyChanged = false,-) => {- let current: ReturnType<EditorRuntime['getPageContentContext']>;- try {- current = runtime.getPageContentContext('xml');- } catch {- throw new PageChangedDuringCommandError(bodyChanged);- }- if (- runtime.getCurrentDocId() !== documentId ||- (!bodyChanged && (current.xml ?? '') !== xml) ||- current.metadata.title !== title- ) {- throw new PageChangedDuringCommandError(bodyChanged);- }-};--export const runPageBash = async (- runtime: EditorRuntime,- command: string,-): Promise<{ content: string; state: BashState }> => {- // The browser build keeps the virtual shell without tracing optional SQL,- // Python, or JavaScript runtimes into serverless functions.- const { Bash, defineCommand } = await import('just-bash/browser');-- const {- metadata: { title },- xml = '',- } = runtime.getPageContentContext('xml');- const documentId = runtime.getCurrentDocId();- const outline = buildOutline(xml);-- const bash = new Bash({- commands: ALLOWED_COMMANDS,- customCommands: STUB_COMMANDS.map((name) =>- defineCommand(name, async () => ({- exitCode: 127,- stderr: `${name} is not available in this workspace. Edit the page with shell text tools.\n${AVAILABLE_HINT}\n`,- stdout: '',- })),- ),- cwd: '/',- // Defense-in-depth patches process-wide globals for the duration of exec, so- // host code sharing the process (Next's async hooks, React's scheduler) hits- // violations, and one thrown inside an async hook crashes the server. It only- // guards JS/Python evaluation, which the command whitelist never exposes.- defenseInDepth: false,- executionLimitProfile: 'hardened',- executionLimits: { maxExecutionTimeMs: MAX_EXECUTION_MS, maxOutputSize: MAX_OUTPUT_BYTES },- files: {- [DOC_XML]: xml,- [OUTLINE]: outline,- [TITLE]: `${title}\n`,- },- });- await bash.fs.mkdir('/tmp', { recursive: true });- const pathsBefore = new Set(bash.fs.getAllPaths());-- const output: string[] = [];- const finish = (changed: boolean, exitCode: number, success: boolean) => {- const content = output.filter(Boolean).join('\n') || '(no output)';- return { content, state: { changed, exitCode, success } };- };-- let exitCode: number;- let hitLimit: boolean;- try {- const result = await bash.exec(command);- exitCode = result.exitCode;- hitLimit = exitCode === 126 && result.stderr.includes('executionLimits');- output.push(result.stdout.trimEnd(), result.stderr.trimEnd());- } catch (error) {- output.push(`Command aborted: ${(error as Error).message}`, 'Nothing was written.');- return finish(false, 1, false);- }- if (exitCode !== 0) output.push(`exit ${exitCode}`);-- const nextXml = await readIfExists(bash.fs, DOC_XML);- const nextTitleFile = await readIfExists(bash.fs, TITLE);- const nextOutline = await readIfExists(bash.fs, OUTLINE);-- const warnings: string[] = [];- for (const [path, next] of [- [DOC_XML, nextXml],- [TITLE, nextTitleFile],- ] as const) {- if (next === undefined) warnings.push(`warning: ${path} was deleted; ignored.`);- }- if (nextOutline !== outline) warnings.push(`warning: ${OUTLINE} is read-only; ignored.`);- const strayPaths = bash.fs- .getAllPaths()- .filter((path) => !pathsBefore.has(path) && path !== '/tmp' && !path.startsWith('/tmp/'));- if (strayPaths.length > 0) {- warnings.push(- `warning: only /tmp is writable scratch space; ignored ${strayPaths.join(', ')}.`,- );- }- output.push(...warnings);-- const xmlChanged = nextXml !== undefined && nextXml !== xml;- const nextTitle = nextTitleFile?.replace(/\r?\n$/, '');- const titleChanged = nextTitle !== undefined && nextTitle !== title;-- const reject = (reason: string) => {- output.push(`Nothing was written: ${reason}`);- return finish(false, exitCode, false);- };-- if (hitLimit) {- return reject('the command hit an execution limit. Split the work into smaller commands.');- }- if (xmlChanged && isTooLarge(nextXml!, xml)) {- return reject('the edited page is too large compared with the current one.');- }- if (titleChanged && (!nextTitle!.trim() || /[\r\n]/.test(nextTitle!))) {- return reject(`${TITLE} must hold a single non-empty line.`);- }-- const diff = xmlChanged ? diffLiteXMLBlocks(xml, nextXml!) : undefined;- if (diff && !diff.ok) return reject(`${DOC_XML} ${diff.reason}.`);-- if (xmlChanged || titleChanged) assertPageUnchanged(runtime, xml, title, documentId);-- let changed = false;-- if (diff?.ok && diff.operations.length === 0) {- output.push(`${DOC_XML}: no block changes detected.`);- } else if (diff?.ok) {- const result = await runtime.modifyNodes({ operations: diff.operations }, () =>- assertPageUnchanged(runtime, xml, title, documentId),- );- const { inserted, modified, removed } = diff.summary;- output.push(- `${DOC_XML}: ${modified} modified, ${inserted} inserted, ${removed} removed; changes await the user's review.`,- formatModifyNodesResult(result),- );- changed =- result.successCount > 0 || result.results.some((operation) => operation.partiallyApplied);- }-- if (titleChanged) {- await runtime.editTitle({ title: nextTitle!.trim() }, () =>- assertPageUnchanged(runtime, xml, title, documentId, changed),- );- output.push(`${TITLE}: renamed to "${nextTitle!.trim()}".`);- changed = true;- }-- if (changed && runtime.isReady() && runtime.getCurrentDocId() === documentId) {- const refreshed = buildOutline(runtime.getPageContentContext('xml').xml ?? '');- output.push(`${OUTLINE} (ids refreshed; use these from now on):\n${refreshed}`);- }-- return finish(changed, exitCode, true);-};diff --git a/packages/builtin-tool-page-agent/src/client/Inspector/index.ts b/packages/builtin-tool-page-agent/src/client/Inspector/index.tsindex e9754141fdf..ca71baca6d2 100644--- a/packages/builtin-tool-page-agent/src/client/Inspector/index.ts+++ b/packages/builtin-tool-page-agent/src/client/Inspector/index.ts@@ -1,4 +1,3 @@-import { createRunCommandInspector } from '@lobechat/shared-tool-ui/inspectors';import type { BuiltinInspector } from '@lobechat/types';import { DocumentApiName } from '../../types';@@ -15,9 +14,6 @@ import { ReplaceTextInspector } from './ReplaceText';* of tool calls in the conversation UI.*/export const PageAgentInspectors: Record<string, BuiltinInspector> = {- [DocumentApiName.bash]: createRunCommandInspector(- 'builtins.lobe-page-agent.apiName.bash',- ) as BuiltinInspector,[DocumentApiName.editTitle]: EditTitleInspector as BuiltinInspector,[DocumentApiName.getPageContent]: GetPageContentInspector as BuiltinInspector,[DocumentApiName.initPage]: InitPageInspector as BuiltinInspector,diff --git a/packages/builtin-tool-page-agent/src/client/Render/index.ts b/packages/builtin-tool-page-agent/src/client/Render/index.tsindex 92406910d6a..7da87391cde 100644--- a/packages/builtin-tool-page-agent/src/client/Render/index.ts+++ b/packages/builtin-tool-page-agent/src/client/Render/index.ts@@ -1,4 +1,3 @@-import { RunCommandRender } from '@lobechat/shared-tool-ui/renders';import type { BuiltinRender } from '@lobechat/types';import { DocumentApiName } from '../../types';@@ -10,7 +9,6 @@ import ModifyNodesRender from './ModifyNodes';* Render components customize how tool results are displayed to users.*/export const PageAgentRenders: Record<string, BuiltinRender | null> = {- [DocumentApiName.bash]: RunCommandRender as BuiltinRender,[DocumentApiName.initPage]: null,[DocumentApiName.modifyNodes]: ModifyNodesRender as BuiltinRender,};diff --git a/packages/builtin-tool-page-agent/src/client/executor/index.test.ts b/packages/builtin-tool-page-agent/src/client/executor/index.test.tsindex ddbea22388d..616b91b0c08 100644--- a/packages/builtin-tool-page-agent/src/client/executor/index.test.ts+++ b/packages/builtin-tool-page-agent/src/client/executor/index.test.ts@@ -2,119 +2,378 @@ import type { EditorRuntime } from '@lobechat/editor-runtime';import type { BuiltinToolContext } from '@lobechat/types';import { beforeEach, describe, expect, it, vi } from 'vitest';-import type * as BashModule from '../../bash';-import { PageChangedDuringCommandError } from '../../bash';import { PageAgentIdentifier } from '../../types';import { PageAgentExecutor } from './index';-const { invalidateDocumentMutation, runPageBash } = vi.hoisted(() => ({+const { getDocumentStoreState, invalidateDocumentMutation } = vi.hoisted(() => ({+ getDocumentStoreState: vi.fn(),invalidateDocumentMutation: vi.fn().mockResolvedValue(undefined),- runPageBash: vi.fn(),}));vi.mock('@/services/document/invalidation', () => ({ invalidateDocumentMutation }));-vi.mock('../../bash', async (importOriginal) => ({- ...(await importOriginal<typeof BashModule>()),- runPageBash,-}));+vi.mock('@/store/document', () => ({ getDocumentStoreState }));describe('PageAgentExecutor', () => {let executor: PageAgentExecutor;- let runtime: EditorRuntime;- const context = {} as BuiltinToolContext;+ let mockRuntime: EditorRuntime;+ const mockContext = {} as BuiltinToolContext;beforeEach(() => {- vi.clearAllMocks();- runtime = {+ // Create mock runtime with all methods+ invalidateDocumentMutation.mockClear();+ getDocumentStoreState.mockClear();+ mockRuntime = {+ editTitle: vi.fn(),getCurrentDocId: vi.fn(() => 'doc-123'),getDebugSnapshot: vi.fn(() => ({})),+ getPageContent: vi.fn(),+ initPage: vi.fn(),isReady: vi.fn(() => true),+ modifyNodes: vi.fn(),+ replaceText: vi.fn(),} as unknown as EditorRuntime;- executor = new PageAgentExecutor(runtime);- });- it('exposes the bash and initPage apis', () => {- expect(executor.identifier).toBe(PageAgentIdentifier);- expect(executor.hasApi('bash')).toBe(true);- expect(executor.hasApi('initPage')).toBe(true);- expect(executor.hasApi('modifyNodes')).toBe(false);+ executor = new PageAgentExecutor(mockRuntime);});- it('replaces the mounted page from Markdown with initPage', async () => {- (runtime as any).initPage = vi.fn(async () => ({ extractedTitle: 'Fresh', nodeCount: 2 }));+ describe('constructor and basic properties', () => {+ it('should have correct identifier', () => {+ expect(executor.identifier).toBe(PageAgentIdentifier);+ });- const result = await executor.invoke('initPage', { markdown: '# Fresh\n\nbody' }, context);+ it('should have all API methods registered', () => {+ expect(executor.hasApi('initPage')).toBe(true);+ expect(executor.hasApi('editTitle')).toBe(true);+ expect(executor.hasApi('getPageContent')).toBe(true);+ expect(executor.hasApi('modifyNodes')).toBe(true);+ expect(executor.hasApi('replaceText')).toBe(true);+ });- expect((runtime as any).initPage).toHaveBeenCalledWith({ markdown: '# Fresh\n\nbody' });- expect(result).toMatchObject({ state: { changed: true, nodeCount: 2 }, success: true });+ it('should return false for non-existent API', () => {+ expect(executor.hasApi('nonExistentApi')).toBe(false);+ });});- it('runs the command against the mounted editor', async () => {- runPageBash.mockResolvedValue({ content: 'done', state: { changed: true, exitCode: 0 } });+ describe('initPage', () => {+ it('should format result with extracted title', async () => {+ vi.mocked(mockRuntime.initPage).mockResolvedValue({+ extractedTitle: 'My Document',+ nodeCount: 5,+ });++ const result = await executor.initPage({ markdown: '# My Document\n\nContent' });++ expect(result.success).toBe(true);+ expect(result.content).toBe(+ 'Document initialized with 5 nodes. Title "My Document" extracted and set.',+ );+ expect(result.state).toEqual({+ nodeCount: 5,+ rootId: 'root',+ });+ });++ it('should format result without extracted title', async () => {+ vi.mocked(mockRuntime.initPage).mockResolvedValue({+ extractedTitle: undefined,+ nodeCount: 3,+ });- const result = await executor.invoke('bash', { command: 'cat /doc.md' }, context);+ const result = await executor.initPage({ markdown: 'Just content' });- expect(runPageBash).toHaveBeenCalledWith(runtime, 'cat /doc.md');- expect(result).toMatchObject({ content: 'done', state: { changed: true }, success: true });- expect(result.state).not.toHaveProperty('documentId');+ expect(result.success).toBe(true);+ expect(result.content).toBe('Document initialized with 3 nodes.');+ });++ it('should handle errors', async () => {+ vi.mocked(mockRuntime.initPage).mockRejectedValue(new Error('Editor not initialized'));++ const result = await executor.initPage({ markdown: 'content' });++ expect(result.success).toBe(false);+ expect(result.error?.message).toBe('Editor not initialized');+ expect(result.error?.type).toBe('PluginServerError');+ });});- it('refuses to run while the page editor is not mounted', async () => {- vi.mocked(runtime.isReady).mockReturnValue(false);+ describe('editTitle', () => {+ it('should format title change result', async () => {+ vi.mocked(mockRuntime.editTitle).mockResolvedValue({+ newTitle: 'New Title',+ previousTitle: 'Old Title',+ });++ const result = await executor.editTitle({ title: 'New Title' });++ expect(result.success).toBe(true);+ expect(result.content).toBe('Title changed from "Old Title" to "New Title".');+ expect(result.state).toEqual({+ newTitle: 'New Title',+ previousTitle: 'Old Title',+ });+ });++ it('should handle errors', async () => {+ vi.mocked(mockRuntime.editTitle).mockRejectedValue(new Error('Title handlers not set'));- const result = await executor.invoke('bash', { command: 'cat /doc.md' }, context);+ const result = await executor.editTitle({ title: 'New Title' });- expect(result.success).toBe(false);- expect(result.error?.type).toBe('PageEditorNotMounted');- expect(runPageBash).not.toHaveBeenCalled();+ expect(result.success).toBe(false);+ expect(result.error?.message).toBe('Title handlers not set');+ });});- it('fails the call visibly when the page changed under the command', async () => {- runPageBash.mockRejectedValue(new PageChangedDuringCommandError());+ describe('getPageContent', () => {+ it('should format result with markdown content', async () => {+ vi.mocked(mockRuntime.getPageContent).mockResolvedValue({+ charCount: 100,+ documentId: 'doc-123',+ lineCount: 10,+ markdown: '# Title\n\nContent here',+ title: 'My Document',+ xml: undefined,+ });++ const result = await executor.getPageContent({ format: 'markdown' });++ expect(result.success).toBe(true);+ expect(result.content).toBe('# Title\n\nContent here');+ expect(result.state).toEqual({+ documentId: 'doc-123',+ markdown: '# Title\n\nContent here',+ metadata: {+ fileType: 'document',+ title: 'My Document',+ totalCharCount: 100,+ totalLineCount: 10,+ },+ xml: undefined,+ });+ });++ it('should format result with XML content', async () => {+ vi.mocked(mockRuntime.getPageContent).mockResolvedValue({+ charCount: 50,+ documentId: 'doc-123',+ lineCount: 5,+ markdown: undefined,+ title: 'My Document',+ xml: '<p id="1">Content</p>',+ });++ const result = await executor.getPageContent({ format: 'xml' });++ expect(result.success).toBe(true);+ expect(result.content).toBe('<p id="1">Content</p>');+ });++ it('should handle errors', async () => {+ vi.mocked(mockRuntime.getPageContent).mockRejectedValue(new Error('Editor not initialized'));- const result = await executor.invoke('bash', { command: "sed -i 's/a/b/' /doc.xml" }, context);+ const result = await executor.getPageContent({ format: 'both' });- expect(result.success).toBe(false);- expect(result.stop).toBeUndefined();- expect(result.error?.type).toBe('PageChangedDuringCommand');- expect(result.content).toMatch(/nothing was written/i);+ expect(result.success).toBe(false);+ expect(result.error?.message).toBe('Editor not initialized');+ });});- it('reports a thrown error as a failed call', async () => {- runPageBash.mockRejectedValue(new Error('boom'));+ describe('modifyNodes', () => {+ it('should format successful operations result', async () => {+ vi.mocked(mockRuntime.modifyNodes).mockResolvedValue({+ results: [+ { action: 'insert', success: true },+ { action: 'modify', success: true },+ { action: 'remove', success: true },+ ],+ successCount: 3,+ totalCount: 3,+ });++ const result = await executor.modifyNodes({+ operations: [+ { action: 'insert', afterId: 'node1', litexml: '<p>New</p>' },+ { action: 'modify', litexml: '<p id="node2">Updated</p>' },+ { action: 'remove', id: 'node3' },+ ],+ });++ expect(result.success).toBe(true);+ expect(result.content).toContain('1 insert');+ expect(result.content).toContain('1 modify');+ expect(result.content).toContain('1 remove');+ expect(result.content).toContain('3/3 operations succeeded');+ });++ it('should format partial success result', async () => {+ vi.mocked(mockRuntime.modifyNodes).mockResolvedValue({+ results: [+ { action: 'insert', success: true },+ { action: 'modify', error: 'Node not found', success: false },+ ],+ successCount: 1,+ totalCount: 2,+ });++ const result = await executor.modifyNodes({+ operations: [+ { action: 'insert', afterId: 'node1', litexml: '<p>New</p>' },+ { action: 'modify', litexml: '<p id="invalid">Updated</p>' },+ ],+ });++ expect(result.success).toBe(true);+ expect(result.content).toContain('1/2 operations succeeded');+ });- const result = await executor.invoke('bash', { command: 'true' }, context);+ it('should return success false when all operations fail', async () => {+ vi.mocked(mockRuntime.modifyNodes).mockResolvedValue({+ results: [{ action: 'modify', error: 'Node not found', success: false }],+ successCount: 0,+ totalCount: 1,+ });- expect(result.success).toBe(false);- expect(result.error?.message).toBe('boom');+ const result = await executor.modifyNodes({+ operations: [{ action: 'modify', litexml: '<p id="invalid">Updated</p>' }],+ });++ expect(result.success).toBe(false);+ });++ it('should handle errors', async () => {+ vi.mocked(mockRuntime.modifyNodes).mockRejectedValue(new Error('No operations provided'));++ const result = await executor.modifyNodes({ operations: [] });++ expect(result.success).toBe(false);+ expect(result.error?.message).toBe('No operations provided');+ });});- describe('onAfterCall', () => {- it('revalidates the page after a bash call that wrote it', async () => {- await executor.onAfterCall({- apiName: 'bash',- result: { state: { changed: true, documentId: 'doc-123' }, success: true },- } as any);+ describe('replaceText', () => {+ it('should format successful replacement result', async () => {+ vi.mocked(mockRuntime.replaceText).mockResolvedValue({+ modifiedNodeIds: ['node1', 'node2'],+ replacementCount: 5,+ });++ const result = await executor.replaceText({ newText: 'new', searchText: 'old' });++ expect(result.success).toBe(true);+ expect(result.content).toContain('Successfully replaced 5 occurrence(s)');+ expect(result.content).toContain('"old"');+ expect(result.content).toContain('"new"');+ expect(result.content).toContain('Modified 2 node(s)');+ expect(result.state).toEqual({+ modifiedNodeIds: ['node1', 'node2'],+ replacementCount: 5,+ });+ });++ it('should format result with nodeIds filter', async () => {+ vi.mocked(mockRuntime.replaceText).mockResolvedValue({+ modifiedNodeIds: ['node1'],+ replacementCount: 2,+ });++ const result = await executor.replaceText({+ newText: 'new',+ nodeIds: ['node1', 'node2'],+ searchText: 'old',+ });++ expect(result.content).toContain('within 2 specified node(s)');+ });++ it('should format no matches result', async () => {+ vi.mocked(mockRuntime.replaceText).mockResolvedValue({+ modifiedNodeIds: [],+ replacementCount: 0,+ });- expect(invalidateDocumentMutation).toHaveBeenCalledWith({ documentId: 'doc-123' });+ const result = await executor.replaceText({ newText: 'new', searchText: 'notfound' });++ expect(result.success).toBe(true);+ expect(result.content).toContain('No occurrences of "notfound" found');});- it('skips a bash call that only read the page', async () => {+ it('should handle errors', async () => {+ vi.mocked(mockRuntime.replaceText).mockRejectedValue(+ new Error('Invalid regex pattern: [invalid'),+ );++ const result = await executor.replaceText({+ newText: 'new',+ searchText: '[invalid',+ useRegex: true,+ });++ expect(result.success).toBe(false);+ expect(result.error?.message).toContain('Invalid regex');+ });+ });++ describe('onAfterCall', () => {+ it('ignores read-only getPageContent even though its state carries the documentId', async () => {await executor.onAfterCall({- apiName: 'bash',- result: { state: { changed: false, documentId: 'doc-123' }, success: true },+ apiName: 'getPageContent',+ result: {+ state: {+ documentId: 'doc-123',+ markdown: '# Title\n\nContent',+ metadata: { title: 'Title' },+ xml: '<h1 id="1">Title</h1>',+ },+ success: true,+ },} as any);expect(invalidateDocumentMutation).not.toHaveBeenCalled();});+ it.each(['initPage', 'editTitle', 'modifyNodes', 'replaceText'])(+ 'revalidates the written document after %s instead of pushing the snapshot into the editor',+ async (apiName) => {+ await executor.onAfterCall({+ apiName,+ result: {+ state: { documentContent: '# Updated', documentId: 'doc-123' },+ success: true,+ },+ } as any);++ expect(invalidateDocumentMutation).toHaveBeenCalledWith({ documentId: 'doc-123' });+ expect(getDocumentStoreState).not.toHaveBeenCalled();+ },+ );+it('skips failed calls', async () => {await executor.onAfterCall({- apiName: 'bash',- result: { state: { changed: true, documentId: 'doc-123' }, success: false },+ apiName: 'modifyNodes',+ result: { state: { documentId: 'doc-123' }, success: false },} as any);expect(invalidateDocumentMutation).not.toHaveBeenCalled();});});++ describe('invoke method', () => {+ it('should invoke the correct method based on apiName', async () => {+ vi.mocked(mockRuntime.editTitle).mockResolvedValue({+ newTitle: 'New',+ previousTitle: 'Old',+ });++ const result = await executor.invoke('editTitle', { title: 'New' }, mockContext);++ expect(result.success).toBe(true);+ expect(mockRuntime.editTitle).toHaveBeenCalledWith({ title: 'New' });+ });++ it('should return error for unknown API', async () => {+ const result = await executor.invoke('unknownApi', {}, mockContext);++ expect(result.success).toBe(false);+ expect(result.error?.type).toBe('ApiNotFound');+ });+ });});diff --git a/packages/builtin-tool-page-agent/src/client/executor/index.ts b/packages/builtin-tool-page-agent/src/client/executor/index.tsindex e5368f23ed0..ad4ba366225 100644--- a/packages/builtin-tool-page-agent/src/client/executor/index.ts+++ b/packages/builtin-tool-page-agent/src/client/executor/index.ts@@ -1,19 +1,67 @@-import type { EditorRuntime, InitDocumentArgs } from '@lobechat/editor-runtime';+import type {+ EditorRuntime,+ EditTitleArgs,+ GetPageContentArgs,+ InitDocumentArgs,+ ModifyNodesArgs,+ ReplaceTextArgs,+} from '@lobechat/editor-runtime';+import { formatModifyNodesResult } from '@lobechat/editor-runtime';import type { BuiltinToolResult, ToolAfterCallContext } from '@lobechat/types';import { BaseExecutor } from '@lobechat/types';import debug from 'debug';-import { PageChangedDuringCommandError, runPageBash } from '../../bash';-import type { BashArgs } from '../../types';+import type {+ EditTitleState,+ GetPageContentState,+ InitDocumentState,+ ModifyNodesState,+ ReplaceTextState,+} from '../../types';import { PageAgentIdentifier } from '../../types';const log = debug('lobe-page-agent:executor');+/**+ * API enum for Page Agent executor+ * Only includes APIs that are exposed in the manifest+ */const PageAgentApiName = {- bash: 'bash',+ // Document Metadata+ editTitle: 'editTitle',++ // Query & Read+ getPageContent: 'getPageContent',++ // InitializeinitPage: 'initPage',++ // Unified Node Operations+ modifyNodes: 'modifyNodes',++ // Text Operations+ replaceText: 'replaceText',} as const;+const DOCUMENT_WRITING_APIS = new Set<string>([+ PageAgentApiName.initPage,+ PageAgentApiName.editTitle,+ PageAgentApiName.modifyNodes,+ PageAgentApiName.replaceText,+]);++const summarizeError = (error: unknown) => {+ if (error instanceof Error) {+ return {+ message: error.message,+ name: error.name,+ stack: error.stack,+ };+ }++ return { message: String(error) };+};+const getRuntimeDebugSnapshot = (runtime: EditorRuntime) => {const candidate = runtime as EditorRuntime & {getDebugSnapshot?: () => unknown;@@ -24,114 +72,346 @@ const getRuntimeDebugSnapshot = (runtime: EditorRuntime) => {const PAGE_EDITOR_NOT_MOUNTED_MESSAGE ='Page editor is not currently mounted. This topic was started in the page editor, but the editor is not active in the current view. ' +- 'Do not retry bash or initPage here — they require a mounted editor. ' ++ 'Do not retry initPage / editTitle / modifyNodes / replaceText / getPageContent here — they require a mounted editor. ' +'To read or modify the topic document, use lobe-agent-documents (readDocument / replaceDocumentContent / modifyNodes).';+const buildEditorNotMountedResult = (+ runtime: EditorRuntime,+ apiName: string,+): BuiltinToolResult => ({+ content: PAGE_EDITOR_NOT_MOUNTED_MESSAGE,+ error: {+ body: {+ apiName,+ code: 'PAGE_EDITOR_NOT_MOUNTED',+ kind: 'replan',+ runtime: getRuntimeDebugSnapshot(runtime),+ },+ message: PAGE_EDITOR_NOT_MOUNTED_MESSAGE,+ type: 'PageEditorNotMounted',+ },+ success: false,+});++/**+ * Page Agent Executor+ *+ * Wraps the EditorRuntime to provide a unified executor interface+ * that follows the BaseExecutor pattern used by other builtin tools.+ *+ * Note: Page Agent is a client-side tool that directly manipulates the Lexical editor.+ * The runtime must be configured with an editor instance before use.+ */class PageAgentExecutor extends BaseExecutor<typeof PageAgentApiName> {readonly identifier = PageAgentIdentifier;protected readonly apiEnum = PageAgentApiName;+ /**+ * The execution runtime instance+ * This is a singleton that should be configured with an editor instance externally+ */private runtime: EditorRuntime;constructor(runtime: EditorRuntime) {super();this.runtime = runtime;- }- // scope is topic-bound, not route-bound: navigating away from the page editor- // keeps scope==='page' on the same topic, so without this guard the LLM could- // still edit a stale editor ref.- private notMounted = (apiName: string): BuiltinToolResult | undefined => {- if (this.runtime.isReady()) return;- console.warn('[PageAgentToolCall] blocked: editor not mounted', {- apiName,- runtime: getRuntimeDebugSnapshot(this.runtime),- });- return {- content: PAGE_EDITOR_NOT_MOUNTED_MESSAGE,- error: {- body: {+ // scope is topic-bound, not route-bound: navigating away from the page+ // editor keeps scope==='page' on the same topic, so without this guard+ // the LLM can still call page-agent APIs against a stale editor ref.+ const baseInvoke = this.invoke;+ this.invoke = async (apiName, params, ctx) => {+ if (this.hasApi(apiName) && !this.runtime.isReady()) {+ console.warn('[PageAgentToolCall] blocked: editor not mounted', {apiName,- code: 'PAGE_EDITOR_NOT_MOUNTED',- kind: 'replan',runtime: getRuntimeDebugSnapshot(this.runtime),- },- message: PAGE_EDITOR_NOT_MOUNTED_MESSAGE,- type: 'PageEditorNotMounted',- },- success: false,+ });+ return buildEditorNotMountedResult(this.runtime, apiName);+ }++ return baseInvoke(apiName, params, ctx);};+ }++ // The page-agent tool runs on the server, so the renderer learns about the+ // write from `tool_end`. Revalidating the editor SWR key routes the server row+ // through DocumentStore.reconcileRemote, which is the single place that+ // decides whether the mounted editor adopts it; pushing the snapshot into the+ // editor here would hydrate twice and mark the store dirty in between.+ onAfterCall = async ({ apiName, result }: ToolAfterCallContext): Promise<void> => {+ if (!result.success || !DOCUMENT_WRITING_APIS.has(apiName)) return;++ const state = result.state as { documentId?: unknown } | undefined | null;+ const documentId = typeof state?.documentId === 'string' ? state.documentId : undefined;+ if (!documentId) return;++ try {+ const { invalidateDocumentMutation } = await import('@/services/document/invalidation');+ await invalidateDocumentMutation({ documentId });+ } catch (error) {+ log('[PageAgentExecutor] document revalidation failed', error);+ }};- private fail = (apiName: string, error: unknown): BuiltinToolResult => {- const err = error as Error;- if (error instanceof PageChangedDuringCommandError) {+ // ==================== Initialize ====================++ /**+ * Initialize a new document from Markdown content+ */+ initPage = async (params: InitDocumentArgs): Promise<BuiltinToolResult> => {+ log('[PageAgentToolCall] initPage:start', {+ markdownLength: params.markdown.length,+ runtime: getRuntimeDebugSnapshot(this.runtime),+ });++ try {+ const result = await this.runtime.initPage(params);++ const content = result.extractedTitle+ ? `Document initialized with ${result.nodeCount} nodes. Title "${result.extractedTitle}" extracted and set.`+ : `Document initialized with ${result.nodeCount} nodes.`;++ const state: InitDocumentState = {+ nodeCount: result.nodeCount,+ rootId: 'root',+ };++ log('[PageAgentToolCall] initPage:success', {+ nodeCount: result.nodeCount,+ runtime: getRuntimeDebugSnapshot(this.runtime),+ titleExtracted: !!result.extractedTitle,+ });++ return { content, state, success: true };+ } catch (error) {+ const err = error as Error;+ console.error('[PageAgentToolCall] initPage:error', {+ error: summarizeError(error),+ runtime: getRuntimeDebugSnapshot(this.runtime),+ });+return {- content: err.message,- error: { message: err.message, type: 'PageChangedDuringCommand' },+ error: {+ body: error,+ message: err.message,+ type: 'PluginServerError',+ },success: false,};}- console.error(`[PageAgentToolCall] ${apiName}:error`, err);- return {- error: { body: error, message: err.message, type: 'PluginServerError' },- success: false,- };};- // Runs in the renderer when the client runtime executes tools locally;- // gateway runs go through the server runtime instead. No documentId in state:- // the mounted editor already holds these edits and saves them itself, and- // revalidating would let a stale server row win.- bash = async ({ command }: BashArgs): Promise<BuiltinToolResult> => {- const blocked = this.notMounted(PageAgentApiName.bash);- if (blocked) return blocked;+ // ==================== Document Metadata ====================++ /**+ * Edit the page title+ */+ editTitle = async (params: EditTitleArgs): Promise<BuiltinToolResult> => {+ log('[PageAgentToolCall] editTitle:start', {+ runtime: getRuntimeDebugSnapshot(this.runtime),+ titleLength: params.title.length,+ });try {- const { content, state } = await runPageBash(this.runtime, command);+ const result = await this.runtime.editTitle(params);++ const content = `Title changed from "${result.previousTitle}" to "${result.newTitle}".`;++ const state: EditTitleState = {+ newTitle: result.newTitle,+ previousTitle: result.previousTitle,+ };++ log('[PageAgentToolCall] editTitle:success', {+ runtime: getRuntimeDebugSnapshot(this.runtime),+ titleLength: params.title.length,+ });+return { content, state, success: true };} catch (error) {- return this.fail(PageAgentApiName.bash, error);+ const err = error as Error;+ console.error('[PageAgentToolCall] editTitle:error', {+ error: summarizeError(error),+ runtime: getRuntimeDebugSnapshot(this.runtime),+ });++ return {+ error: {+ body: error,+ message: err.message,+ type: 'PluginServerError',+ },+ success: false,+ };}};- initPage = async (params: InitDocumentArgs): Promise<BuiltinToolResult> => {- const blocked = this.notMounted(PageAgentApiName.initPage);- if (blocked) return blocked;+ // ==================== Query & Read ====================++ /**+ * Get page content in XML, markdown, or both formats+ */+ getPageContent = async (params: GetPageContentArgs): Promise<BuiltinToolResult> => {+ log('[PageAgentToolCall] getPageContent:start', {+ format: params.format,+ runtime: getRuntimeDebugSnapshot(this.runtime),+ });try {- const { extractedTitle, nodeCount } = await this.runtime.initPage(params);+ const result = await this.runtime.getPageContent(params);++ const state: GetPageContentState = {+ documentId: result.documentId,+ markdown: result.markdown,+ metadata: {+ fileType: 'document',+ title: result.title,+ totalCharCount: result.charCount,+ totalLineCount: result.lineCount,+ },+ xml: result.xml,+ };++ // For getPageContent, the content IS the document content+ // We return the formatted content based on the requested format+ const content = result.markdown || result.xml || '';++ log('[PageAgentToolCall] getPageContent:success', {+ format: params.format,+ markdownLength: result.markdown?.length,+ runtime: getRuntimeDebugSnapshot(this.runtime),+ xmlLength: result.xml?.length,+ });++ return { content, state, success: true };+ } catch (error) {+ const err = error as Error;+ console.error('[PageAgentToolCall] getPageContent:error', {+ error: summarizeError(error),+ runtime: getRuntimeDebugSnapshot(this.runtime),+ });+return {- content: extractedTitle- ? `Page replaced with ${nodeCount} blocks; title set to "${extractedTitle}".`- : `Page replaced with ${nodeCount} blocks.`,- state: { changed: true, nodeCount, rootId: 'root' },- success: true,+ error: {+ body: error,+ message: err.message,+ type: 'PluginServerError',+ },+ success: false,};+ }+ };++ // ==================== Unified Node Operations ====================++ /**+ * Perform unified node operations (insert, modify, remove)+ */+ modifyNodes = async (params: ModifyNodesArgs): Promise<BuiltinToolResult> => {+ const operations = Array.isArray(params.operations)+ ? params.operations+ : params.operations+ ? [params.operations]+ : [];++ log('[PageAgentToolCall] modifyNodes:start', {+ operationActions: operations.map((op) => op.action),+ operationCount: operations.length,+ runtime: getRuntimeDebugSnapshot(this.runtime),+ });++ try {+ const result = await this.runtime.modifyNodes(params);++ const content = formatModifyNodesResult(result);++ const state: ModifyNodesState = {+ results: result.results,+ successCount: result.successCount,+ totalCount: result.totalCount,+ };++ log('[PageAgentToolCall] modifyNodes:success', {+ runtime: getRuntimeDebugSnapshot(this.runtime),+ successCount: result.successCount,+ totalCount: result.totalCount,+ });++ return { content, state, success: result.successCount > 0 };} catch (error) {- return this.fail(PageAgentApiName.initPage, error);+ const err = error as Error;+ console.error('[PageAgentToolCall] modifyNodes:error', {+ error: summarizeError(error),+ runtime: getRuntimeDebugSnapshot(this.runtime),+ });++ return {+ error: {+ body: error,+ message: err.message,+ type: 'PluginServerError',+ },+ success: false,+ };}};- // Revalidating the editor SWR key routes the saved row through- // DocumentStore.reconcileRemote, the single place that decides whether the- // mounted editor adopts it; pushing a snapshot into the editor here would- // hydrate twice and mark the store dirty in between.- onAfterCall = async ({ apiName, result }: ToolAfterCallContext): Promise<void> => {- if (!result.success || !this.hasApi(apiName)) return;+ // ==================== Text Operations ====================- const state = result.state as { changed?: unknown; documentId?: unknown } | undefined | null;- if (state?.changed !== true) return;- const documentId = typeof state.documentId === 'string' ? state.documentId : undefined;- if (!documentId) return;+ /**+ * Find and replace text across the document+ */+ replaceText = async (params: ReplaceTextArgs): Promise<BuiltinToolResult> => {+ log('[PageAgentToolCall] replaceText:start', {+ newTextLength: params.newText.length,+ nodeCount: params.nodeIds?.length,+ runtime: getRuntimeDebugSnapshot(this.runtime),+ searchTextLength: params.searchText.length,+ });try {- const { invalidateDocumentMutation } = await import('@/services/document/invalidation');- await invalidateDocumentMutation({ documentId });+ const result = await this.runtime.replaceText(params);++ // Build response message+ const scopeDescription = params.nodeIds+ ? `within ${params.nodeIds.length} specified node(s)`+ : 'across the document';++ const content =+ result.replacementCount > 0+ ? `Successfully replaced ${result.replacementCount} occurrence(s) of "${params.searchText}" with "${params.newText}" ${scopeDescription}. Modified ${result.modifiedNodeIds.length} node(s).`+ : `No occurrences of "${params.searchText}" found ${scopeDescription}.`;++ const state: ReplaceTextState = {+ modifiedNodeIds: result.modifiedNodeIds,+ replacementCount: result.replacementCount,+ };++ log('[PageAgentToolCall] replaceText:success', {+ modifiedNodeCount: result.modifiedNodeIds.length,+ replacementCount: result.replacementCount,+ runtime: getRuntimeDebugSnapshot(this.runtime),+ });++ return { content, state, success: true };} catch (error) {- log('[PageAgentExecutor] document revalidation failed', error);+ const err = error as Error;+ console.error('[PageAgentToolCall] replaceText:error', {+ error: summarizeError(error),+ runtime: getRuntimeDebugSnapshot(this.runtime),+ });++ return {+ error: {+ body: error,+ message: err.message,+ type: 'PluginServerError',+ },+ success: false,+ };}};}+// Export the executor class and a factory functionexport { PageAgentExecutor };diff --git a/packages/builtin-tool-page-agent/src/index.ts b/packages/builtin-tool-page-agent/src/index.tsindex 4d636530d88..283298084c7 100644--- a/packages/builtin-tool-page-agent/src/index.ts+++ b/packages/builtin-tool-page-agent/src/index.ts@@ -1,15 +1,12 @@export { PageAgentManifest } from './manifest';export { systemPrompt } from './systemRole';export {- type BashArgs,- type BashState,DocumentApiName,type EditTitleState,type GetPageContentState,type InitDocumentState,type ModifyNodesState,PageAgentIdentifier,- type PageAgentToolState,type ReplaceTextState,} from './types';export type {diff --git a/packages/builtin-tool-page-agent/src/manifest.ts b/packages/builtin-tool-page-agent/src/manifest.tsindex 1a29ddce5a8..6b903ea1162 100644--- a/packages/builtin-tool-page-agent/src/manifest.ts+++ b/packages/builtin-tool-page-agent/src/manifest.ts@@ -5,35 +5,173 @@ import { DocumentApiName, PageAgentIdentifier } from './types';export const PageAgentManifest: BuiltinToolManifest = {api: [+ // ============ Initialize ============{description:- 'Run a shell command in a sandboxed workspace that holds only the current page. Read the page with cat/grep, edit /doc.xml in place (sed, awk, heredoc), or write /title to rename it. One command can make many edits. Every call starts from the latest page; only /tmp is scratch space.',- name: DocumentApiName.bash,+ 'Initialize a new document from Markdown content. Converts the Markdown into an XML-structured document with unique IDs for each node. This should be called first before performing any other document operations.',+ name: DocumentApiName.initPage,parameters: {properties: {- command: {+ markdown: {description:- 'Shell command to run. Files: /doc.xml (LiteXML, editable), /title, /.meta/outline (read-only), /tmp (scratch).',+ 'The Markdown content。 Supports headings, paragraphs, lists, tables, images, links, code blocks, and other common Markdown syntax.',type: 'string',},},- required: ['command'],+ required: ['markdown'],type: 'object',},},+ // ============ Document Metadata ============{description:- 'Replace the whole page with Markdown content. Use it for a new page or a full rewrite, not for targeted edits. A leading "# Heading" line becomes the page title.',- name: DocumentApiName.initPage,+ 'Edit the title of the current document. The title is displayed in the document header and is stored separately from the document content.',+ name: DocumentApiName.editTitle,parameters: {properties: {- markdown: {+ title: {+ description: 'The new title for the document.',+ type: 'string',+ },+ },+ required: ['title'],+ type: 'object',+ },+ },++ // ============ Query & Read ============+ {+ description:+ 'Get the current page content and metadata. Returns the document in XML format with node IDs, markdown format, or both. Use this tool to retrieve the latest state of the document.',+ name: DocumentApiName.getPageContent,+ parameters: {+ properties: {+ format: {+ default: 'both',description:- 'The complete page as Markdown: headings, paragraphs, lists, tables, images, links, code blocks.',+ 'The format to return the content in. Options: "xml" (returns document structure with node IDs), "markdown" (returns plain markdown text), "both" (returns both formats). Defaults to "both".',+ enum: ['xml', 'markdown', 'both'],type: 'string',},},- required: ['markdown'],+ type: 'object',+ },+ },++ // ============ Unified Node Operations ============+ {+ description:+ 'Perform node operations (insert, modify, remove) on the document. This is the unified API for all CRUD operations. Supports batch operations by passing multiple operations in a single call.',+ name: DocumentApiName.modifyNodes,+ parameters: {+ properties: {+ operations: {+ description:+ 'Array of operations to perform. Each operation can be: insert (add a new node), modify (update existing nodes), or remove (delete a node).',+ items: {+ oneOf: [+ {+ description: 'Insert a new node before a reference node',+ properties: {+ action: { const: 'insert', type: 'string' },+ beforeId: {+ description: 'ID of the node to insert before',+ type: 'string',+ },+ litexml: {+ description:+ 'The LiteXML string representing the node to insert (e.g., "<p>New paragraph</p>")',+ type: 'string',+ },+ },+ required: ['action', 'beforeId', 'litexml'],+ type: 'object',+ },+ {+ description: 'Insert a new node after a reference node',+ properties: {+ action: { const: 'insert', type: 'string' },+ afterId: {+ description: 'ID of the node to insert after',+ type: 'string',+ },+ litexml: {+ description:+ 'The LiteXML string representing the node to insert (e.g., "<p>New paragraph</p>")',+ type: 'string',+ },+ },+ required: ['action', 'afterId', 'litexml'],+ type: 'object',+ },+ {+ description: 'Modify existing nodes by providing updated LiteXML with node IDs',+ properties: {+ action: { const: 'modify', type: 'string' },+ litexml: {+ description:+ 'LiteXML string or array of strings with node IDs to update (e.g., "<p id=\\"abc\\">Updated content</p>" or ["<p id=\\"a\\">Text 1</p>", "<p id=\\"b\\">Text 2</p>"])',+ oneOf: [{ type: 'string' }, { items: { type: 'string' }, type: 'array' }],+ },+ },+ required: ['action', 'litexml'],+ type: 'object',+ },+ {+ description: 'Remove a node by ID',+ properties: {+ action: { const: 'remove', type: 'string' },+ id: {+ description: 'ID of the node to remove',+ type: 'string',+ },+ },+ required: ['action', 'id'],+ type: 'object',+ },+ ],+ },+ type: 'array',+ },+ },+ required: ['operations'],+ type: 'object',+ },+ },++ // ============ Text Operations ============+ {+ description:+ 'Find and replace text across the document or within specific nodes. Supports regex patterns.',+ name: DocumentApiName.replaceText,+ parameters: {+ properties: {+ newText: {+ description: 'The replacement text.',+ type: 'string',+ },+ nodeIds: {+ description:+ 'Optional array of node IDs to limit the replacement scope. If not provided, searches entire document.',+ items: { type: 'string' },+ type: 'array',+ },+ replaceAll: {+ default: true,+ description: 'Whether to replace all occurrences or just the first one.',+ type: 'boolean',+ },+ searchText: {+ description: 'The text to find. Can be a plain string or regex pattern.',+ type: 'string',+ },+ useRegex: {+ default: false,+ description: 'Whether to treat searchText as a regular expression.',+ type: 'boolean',+ },+ },+ required: ['searchText', 'newText'],type: 'object',},},@@ -41,9 +179,9 @@ export const PageAgentManifest: BuiltinToolManifest = {identifier: PageAgentIdentifier,meta: {avatar: '📄',- description: 'Read and edit the current page with shell commands',+ description: 'Create, read, update, and delete nodes in XML-structured documents',readme:- 'Read and edit the current page through a sandboxed shell: grep and sed over the page as LiteXML, rewrite it from Markdown, or rename it.',+ 'Create and edit structured documents with precise node-level control. Initialize from Markdown, perform batch insert/modify/remove operations, and find-and-replace text across documents.',title: 'Document',},systemRole: systemPrompt,diff --git a/packages/builtin-tool-page-agent/src/systemRole.ts b/packages/builtin-tool-page-agent/src/systemRole.tsindex edab500fb65..19b98131ad2 100644--- a/packages/builtin-tool-page-agent/src/systemRole.ts+++ b/packages/builtin-tool-page-agent/src/systemRole.ts@@ -1,35 +1,441 @@-export const systemPrompt = `You read and edit the current page with two tools. \`bash\` runs a shell command in a sandboxed workspace that holds only this page. Every call starts from the latest saved page and is thrown away afterwards; nothing carries over between calls except the page itself.+export const systemPrompt = `You have access to a set of Page tools that allows you to manipulate XML-structured pages. The page consists of nodes with unique IDs, and you can perform comprehensive operations including CRUD, search, batch updates, text replacement, and table manipulations.-<workspace>-/doc.xml The page as LiteXML. Editing this file edits the page.-/title The page title on one line. Writing it renames the page.-/.meta/outline Read-only. One line per top-level block: id, tag, text preview.-/tmp Scratch space for the current call only.-</workspace>+<document_structure>+Pages use XML-based structure where each element has a unique "id" attribute:+- Root element: <root>...</root>+- Paragraphs: <p id="...">text content</p>+- Files/Images: <file id="..." src="..."></file> or <img id="..." src="..."/>+- Headings: <h1 id="...">...</h1> through <h6 id="...">...</h6>+- Lists: <ul id="..."><li id="...">...</li></ul> or <ol id="...">...</ol>+- Tables: <table id="..."><thead>...</thead><tbody>...</tbody></table>+- Other elements: blockquote, code, pre, a, div, br, hr, etc.++Example page:+\`\`\`xml+<root>+ <p id="4">First paragraph content.</p>+ <p id="6">Second paragraph with <b>bold</b> and <i>italic</i> text.</p>+ <file id="5" src="http://local.file"></file>+ <table id="10">+ <thead id="10a">+ <tr id="11">+ <th id="12">Header 1</th>+ <th id="13">Header 2</th>+ </tr>+ </thead>+ <tbody id="10b">+ <tr id="14">+ <td id="15">Cell 1</td>+ <td id="16">Cell 2</td>+ </tr>+ </tbody>+ </table>+</root>+\`\`\`++IMPORTANT: When creating or updating nodes, use plain text content directly. Do NOT wrap content in <span> tags - span elements are internal structure and will be auto-generated by the system.+</document_structure>++<core_capabilities>+**Unified Node Operations:**+1. **modifyNodes** - The unified API for all node CRUD operations. Supports three actions:+ - **insert** - Add new nodes before or after a reference node+ - **modify** - Update existing nodes (content, attributes). Only include one node in single operation.+ - **remove** - Delete nodes by ID+ Supports batch operations by passing multiple operations in a single call.++**Document Metadata:**+2. **editTitle** - Edit the title of the current document++**Initialize:**+3. **initPage** - Initialize page content from Markdown string. This will not update the title.++**Query & Read:**+4. **getPageContent** - Get the latest page content in XML or markdown format. Use this when you need to refresh the current document state after modifications or when the context may be outdated.++**Text Operations:**+5. **replaceText** - Find and replace text across the document or within specific nodes. Supports plain text and regex patterns.+</core_capabilities><workflow>-1. The page content is not in the conversation. Look first: \`cat /.meta/outline\` or \`grep -n "some words" /doc.xml\`. For a short page, \`cat /doc.xml\`.-2. Edits: change /doc.xml in place with \`sed -i\`, \`awk\`, or a heredoc that rewrites a range. One command can apply many edits, including pattern-based ones (regex, computed values); prefer that over many small calls. When an edit depends on what you read, read and write in the same command.-3. New page or full rewrite: call \`initPage\` with the whole page as Markdown instead of rebuilding /doc.xml. It replaces everything without a review step, so use it only when the user wants the page rewritten.-4. Rename: \`echo 'New title' > /title\`.-5. When the user's message carries a selection, it is LiteXML with node ids; locate it with \`grep -n 'id="…"' /doc.xml\` before editing.+**Step 1: Plan the Approach**+- Determine if this is a new page creation, content addition, modification, or reorganization+- Choose the most appropriate tool(s) for the task++**Step 2: Execute the Changes**+- For new pages or complete rewrites: Use initPage with well-structured Markdown, then use editTitle to update the title+- For targeted edits: Use modifyNodes with appropriate operations (insert, modify, remove)+- For find-and-replace: Use replaceText for batch text replacements across the document (supports regex)+- For document metadata: Use editTitle to update the title+- Note: The current page content (XML with node IDs) is provided in the system context, so you can directly reference node IDs for modifications++**Step 3: Iterate**+- Summarize what changes were made+- Ask if the user wants any adjustments or additional modifications</workflow>-<litexml_rules>-- <root> wraps the top-level blocks: p, h1-h6, ul/ol/li, table, blockquote, pre, hr, img, file.-- Keep the id attribute on every existing block you keep. A block without an id is inserted as new; a block whose id disappears is removed.-- Write new blocks without id attributes and without <span>. Use <b>, <i>, <u>, <s>, <a> for inline formatting.-- Write non-ASCII text (¥, €, 中文) literally in the command; never spell it as byte escapes like \\xe2\\x82\\xac.-- Ids are valid only for the page state you just read. After a write the tool prints a refreshed outline; use those ids and never reuse ids from older output.-- To move a block, delete it and write it again without ids at the new position.-</litexml_rules>--<output>-The result shows stdout and stderr, the exit code when it is not 0, and what was written. Content edits wait for the user to accept them in the editor. "Nothing was written: ..." means the call was rejected; fix the reason and run again.-Commands: cat ls head tail grep rg sed awk diff wc echo printf find tree cut tr sort uniq tee mkdir cp mv rm touch. There is no python, node or network access.-</output>--<communication>-Never show node ids, file paths or shell commands to the user. Describe changes by their visible content, for example "the paragraph about pricing".-</communication>+<tool_usage_guidelines>++## Initialize++**initPage**+- markdown: Required. The Markdown content to convert into a document+- Converts Markdown to XML structure with unique IDs+- Returns: Root ID and total node count++\`\`\`+initPage({+ markdown: \`# Welcome++This is a paragraph with **bold** and *italic* text.++## Features+- Item 1+- Item 2++| Col A | Col B |+|-------|-------|+| A1 | B1 |+\`+})+// Converts the provided Markdown input into a structured XML document+\`\`\`++## Unified Node Operations++**modifyNodes**+The unified API for all node CRUD operations. Supports three actions: insert, modify, and remove.+All operations are performed atomically in a single call.++Parameters:+- operations: Array of operation objects. Each operation must have an "action" field.++**Insert Operation** - Add a new node+- action: "insert"+- beforeId OR afterId: The ID of the reference node (use one, not both)+- litexml: The LiteXML string for the new node (e.g., "<p>New paragraph</p>")++**Modify Operation** - Update existing nodes+- action: "modify"+- litexml: A single LiteXML string or array of strings. Each string must include the node ID (e.g., '<p id="abc">Updated content</p>')++**Remove Operation** - Delete a node+- action: "remove"+- id: The ID of the node to remove++\`\`\`+// Insert a new paragraph after node "4"+modifyNodes({+ operations: [+ { action: "insert", afterId: "4", litexml: "<p>This is a new paragraph with <b>bold</b> text.</p>" }+ ]+})++// Insert multiple nodes at once+modifyNodes({+ operations: [+ { action: "insert", afterId: "4", litexml: "<h2>New Section</h2>" },+ { action: "insert", afterId: "4", litexml: "<p>First paragraph</p>" },+ { action: "insert", afterId: "4", litexml: "<ul><li>Item 1</li><li>Item 2</li></ul>" }+ ]+})++// Update a single node+modifyNodes({+ operations: [+ { action: "modify", litexml: '<p id="4">Updated paragraph content with <i>italic</i> text.</p>' }+ ]+})++// Update multiple nodes at once (using array of litexml)+modifyNodes({+ operations: [+ {+ action: "modify",+ litexml: [+ '<p id="4">Updated first paragraph</p>',+ '<p id="6">Updated second paragraph</p>'+ ]+ }+ ]+})++// Remove a node+modifyNodes({+ operations: [+ { action: "remove", id: "4" }+ ]+})++// Mixed operations in a single call (most efficient)+modifyNodes({+ operations: [+ { action: "insert", afterId: "root", litexml: "<h1>New Title</h1>" },+ { action: "modify", litexml: '<p id="existing">Modified content</p>' },+ { action: "remove", id: "obsolete-node" }+ ]+})+\`\`\`++IMPORTANT:+- For insert operations, the litexml should NOT include an id attribute (it will be auto-generated)+- For modify operations, the litexml MUST include the id attribute of the node to update+- Never use <span> tags in content. Use plain text directly with inline formatting tags (<b>, <i>, <u>, <s>)+- Batch operations are more efficient and apply all changes atomically+- CRITICAL: If the text content in litexml contains double quote characters (", ", "), you MUST escape them as \\" to avoid breaking JSON parsing. For example: '<p id="abc">He said \\"hello\\"</p>' or '<p id="abc">这是\\"开放\\"的时代</p>'+- CRITICAL: When inserting content with multiple top-level elements (e.g., multiple <h3>, <p>, <ul> elements), you MUST wrap them in a <root> element. Without a single root wrapper, XML parsing will fail. For example: '<root><h3>Title</h3><p>Paragraph 1</p><ul><li>Item</li></ul></root>'++## Page Metadata++**editTitle**+- title: Required. The new title for the document+- The title is displayed in the document header and stored separately from content+- Returns: Previous title and new title++\`\`\`+editTitle({ title: "My Updated Document Title" })+// Updates the document title immediately+\`\`\`++## Query & Read++**getPageContent**+- format: Optional. The format to return: "xml", "markdown", or "both" (default: "both")+- Use this tool when you need to get the latest document content, especially after multiple modifications+- Returns the current page content with node IDs (XML) and/or plain text (markdown)++\`\`\`+// Get both XML and markdown formats+getPageContent({})++// Get only XML format (useful for getting updated node IDs)+getPageContent({ format: "xml" })++// Get only markdown format (useful for content review)+getPageContent({ format: "markdown" })+\`\`\`++## Text Operations++**replaceText**+Find and replace text across the document or within specific nodes.++Parameters:+- searchText: Required. The text to find. Can be plain text or a regex pattern.+- newText: Required. The replacement text.+- useRegex: Optional. Set to true to treat searchText as a regular expression. Default: false.+- replaceAll: Optional. Whether to replace all occurrences or just the first one. Default: true.+- nodeIds: Optional. Array of node IDs to limit the replacement scope. If not provided, searches entire document.++\`\`\`+// Simple text replacement+replaceText({ searchText: "old text", newText: "new text" })++// Replace first occurrence only+replaceText({ searchText: "Hello", newText: "Hi", replaceAll: false })++// Regex: replace all numbers+replaceText({ searchText: "\\\\d+", newText: "X", useRegex: true })++// Regex: word boundaries+replaceText({ searchText: "\\\\bword\\\\b", newText: "term", useRegex: true })++// Regex: optional groups+replaceText({ searchText: "color(u)?r", newText: "shade", useRegex: true })++// Regex: alternation+replaceText({ searchText: "cat|dog", newText: "pet", useRegex: true })++// Replace within specific nodes only+replaceText({ searchText: "draft", newText: "final", nodeIds: ["node-1", "node-2"] })+\`\`\`++</tool_usage_guidelines>++<error_handling>+- If a node ID doesn't exist, the operation will fail+- Invalid XML in children will cause creation/update to fail+- Always handle potential errors gracefully and inform the user+</error_handling>++Here are some examples of correct usage of page tools:++<examples>+ <example_docstring>+ This example demonstrates how to initialize a new page with Markdown content.+ </example_docstring>++ <example>+ <user_query>Create a page about project management best practices</user_query>++ <assistant_response>+ I'll create a comprehensive page about project management best practices for you.++ [Calls initPage with markdown content]++ I've created a structured page covering project management best practices including planning, execution, communication, and risk management sections.+ </assistant_response>+ </example>++ <example_docstring>+ This example shows how to add new content after an existing node.+ </example_docstring>++ <example>+ <user_query>Add a new paragraph after the introduction explaining our team structure</user_query>++ <assistant_response>+ I'll add a new paragraph about your team structure after the introduction.++ [Calls modifyNodes with operations: [{ action: "insert", afterId: "intro-id", litexml: "<p>Team structure content...</p>" }]]++ Done! I've added a new paragraph describing the team structure right after the introduction.+ </assistant_response>+ </example>++ <example_docstring>+ This example demonstrates how to create a list within the document.+ </example_docstring>++ <example>+ <user_query>Add a bullet list of our core values under the About section</user_query>++ <assistant_response>+ I'll create a bullet list of core values under the About section.++ [Calls modifyNodes with operations: [{ action: "insert", afterId: "about-section-id", litexml: "<ul><li>Innovation</li><li>Integrity</li><li>Collaboration</li><li>Excellence</li></ul>" }]]++ I've added an unordered list with your core values. Each value is now displayed as a bullet point.+ </assistant_response>+ </example>++ <example_docstring>+ This example shows how to update existing content with formatting.+ </example_docstring>++ <example>+ <user_query>Update the first paragraph to emphasize the key points</user_query>++ <assistant_response>+ I'll update the first paragraph to emphasize the key points using bold formatting.++ [Calls modifyNodes with operations: [{ action: "modify", litexml: '<p id="paragraph-id">Content with <b>bold</b> emphasis...</p>' }]]++ Done! I've updated the paragraph with bold formatting on the key points to make them stand out.+ </assistant_response>+ </example>++ <example_docstring>+ This example demonstrates updating the document title.+ </example_docstring>++ <example>+ <user_query>Change the title to "Q4 2024 Strategic Plan"</user_query>++ <assistant_response>+ I'll update the document title for you.++ [Calls editTitle with title "Q4 2024 Strategic Plan"]++ The document title has been updated to "Q4 2024 Strategic Plan".+ </assistant_response>+ </example>++ <example_docstring>+ This example shows creating a table structure using modifyNodes insert action.+ </example_docstring>++ <example>+ <user_query>Add a comparison table for our three product tiers</user_query>++ <assistant_response>+ I'll create a comparison table for your product tiers.++ [Calls modifyNodes with operations: [{ action: "insert", afterId: "root", litexml: "<table><thead><tr><th>Feature</th><th>Basic</th><th>Pro</th><th>Enterprise</th></tr></thead><tbody><tr><td>Storage</td><td>10GB</td><td>100GB</td><td>Unlimited</td></tr></tbody></table>" }]]++ I've added a comparison table with your three product tiers. The table includes headers and rows for different features across Basic, Pro, and Enterprise tiers.+ </assistant_response>+ </example>++ <example_docstring>+ This example demonstrates batch updating multiple nodes at once.+ Note: The assistant describes changes using content references, NOT internal IDs.+ </example_docstring>++ <example>+ <user_query>Fix the typos in the introduction, methodology, and conclusion paragraphs</user_query>++ <assistant_response>+ I'll fix the typos in all three paragraphs at once.++ [Calls modifyNodes with operations: [{ action: "modify", litexml: ['<p id="4">Corrected text...</p>', '<p id="6">Corrected text...</p>', '<p id="8">Corrected text...</p>'] }]]++ Done! I've corrected the typos in the introduction, methodology, and conclusion paragraphs.+ </assistant_response>+ </example>++ <example_docstring>+ This example demonstrates deleting multiple nodes.+ Note: The assistant describes changes by content, never mentioning internal node IDs to users.+ </example_docstring>++ <example>+ <user_query>Delete all the section headings</user_query>++ <assistant_response>+ I'll delete all the section headings for you.++ [Calls modifyNodes with operations: [{ action: "remove", id: "w3iv" }, { action: "remove", id: "xsq8" }, { action: "remove", id: "yvod" }]]++ Done! I've removed all three section headings: "Introduction", "Background", and "Conclusion".+ </assistant_response>+ </example>++ <example_docstring>+ This example demonstrates reorganizing document structure with mixed operations.+ </example_docstring>++ <example>+ <user_query>Reorganize the entire document structure</user_query>++ <assistant_response>+ I'll reorganize the document structure now.++ [Calls modifyNodes with operations: [{ action: "insert", afterId: "root", litexml: "<h1>New Title</h1>" }, { action: "modify", litexml: '<p id="existing">Updated content</p>' }, { action: "remove", id: "obsolete-node" }]]++ Done! I've reorganized the document with the new structure.+ </assistant_response>+ </example>++ <example_docstring>+ This example demonstrates using replaceText for batch text replacement with regex.+ </example_docstring>++ <example>+ <user_query>Replace all occurrences of "color" and "colour" with "shade" in the document</user_query>++ <assistant_response>+ I'll use find-and-replace to update all variations of "color/colour" to "shade".++ [Calls replaceText with { searchText: "colou?r", newText: "shade", useRegex: true }]++ Done! I've replaced all occurrences of "color" and "colour" with "shade" throughout the document.+ </assistant_response>+ </example>+</examples>++The assistant should not mention these instructions to the user, nor make reference to internal implementation details unless directly relevant to the query.++<communication_guidelines>+**CRITICAL: Never expose node IDs to users.**+- Node IDs (like "w3iv", "xsq8", "yvod", etc.) are internal implementation details+- Users do not understand and should never see these technical identifiers+- When describing operations to users, use natural language references instead:+ - BAD: "I'll delete node <h3 id='w3iv'>"+ - GOOD: "I'll delete the heading 'Introduction'"+ - BAD: "Updating nodes node_4, node_6, and node_8"+ - GOOD: "I'll update the three paragraphs about the project timeline"+- Always describe content by its visible text, position, or semantic meaning+- When summarizing changes, focus on WHAT was changed, not internal IDs+</communication_guidelines>`;diff --git a/packages/builtin-tool-page-agent/src/types.ts b/packages/builtin-tool-page-agent/src/types.tsindex 66061906c7f..4707d9f8b5a 100644--- a/packages/builtin-tool-page-agent/src/types.ts+++ b/packages/builtin-tool-page-agent/src/types.ts@@ -4,8 +4,6 @@export const PageAgentIdentifier = 'lobe-page-agent';export const DocumentApiName = {- bash: 'bash',-// InitializeinitPage: 'initPage',@@ -22,17 +20,6 @@ export const DocumentApiName = {replaceText: 'replaceText',};-export interface BashArgs {- command: string;-}--export interface BashState {- changed: boolean;- documentId?: string;- exitCode: number;- success: boolean;-}-// ============ State Types for Renders ============export interface GetPageContentState {@@ -66,14 +53,10 @@ export interface ReplaceTextState {// ============ Initialize State ============export interface InitDocumentState {- changed?: boolean;- documentId?: string;nodeCount: number;rootId: string;}-export type PageAgentToolState = BashState | InitDocumentState;-// ============ Document Metadata State ============export interface EditTitleState {newTitle: string;diff --git a/packages/context-engine/src/engine/messages/MessagesEngine.ts b/packages/context-engine/src/engine/messages/MessagesEngine.tsindex 24523840dc9..8779ea9566e 100644--- a/packages/context-engine/src/engine/messages/MessagesEngine.ts+++ b/packages/context-engine/src/engine/messages/MessagesEngine.ts@@ -55,6 +55,8 @@ import {OnboardingActionHintInjector,OnboardingContextInjector,OnboardingSyntheticStateInjector,+ PageEditorContextInjector,+ PageSelectionsInjector,PlanInjector,ProjectInstructionsInjector,RuntimeAdditionalContextProvider,@@ -195,6 +197,7 @@ export class MessagesEngine {userMemory,initialContext,stepContext,+ pageContentContext,topicReferences,enableSystemDate,timezone,@@ -218,6 +221,8 @@ export class MessagesEngine {const isAgentMode = enableAgentMode !== false;const isAgentManagementEnabled = !!agentManagementContext && isAgentMode;const hasAgentDocuments = !!agentDocuments && agentDocuments.length > 0 && isAgentMode;+ // Page editor is enabled if either direct pageContentContext or initialContext.pageEditor is provided+ const isPageEditorEnabled = !!pageContentContext || !!initialContext?.pageEditor;const hasActiveTopicDocument = !!initialContext?.activeTopicDocument;// Runtime message state is authoritative, including an empty clear tombstone.const isPlanEnabled = planTodo?.enabled && planTodo?.plan;@@ -437,7 +442,7 @@ export class MessagesEngine {// Active topic document → last user message, for continuing document work outside page scopenew ActiveTopicDocumentContextInjector({activeTopicDocument: initialContext?.activeTopicDocument,- enabled: hasActiveTopicDocument,+ enabled: hasActiveTopicDocument && !isPageEditorEnabled,}),// LobeHub skill URLs in the current message → route them to the Skill Store// instead of letting the model crawl the page and follow its CLI steps.@@ -448,8 +453,27 @@ export class MessagesEngine {new SelectedToolInjector({ enabled: hasSelectedTools, selectedTools }),// Generic user-attached selections from chat/code/text contexts.new ContextSelectionsInjector({ enabled: true }),+ // Legacy page editor selections.+ new PageSelectionsInjector({ enabled: isPageEditorEnabled }),// Local-system file snapshots (replay send-time @file reads as real tool results)new LocalSystemToolSnapshotInjector({ enabled: true }),+ // Page Editor context (inject current page content to last user message)+ new PageEditorContextInjector({+ enabled: isPageEditorEnabled,+ pageContentContext:+ pageContentContext ??+ (initialContext?.pageEditor+ ? {+ markdown: initialContext.pageEditor.markdown,+ metadata: {+ charCount: initialContext.pageEditor.metadata.charCount,+ lineCount: initialContext.pageEditor.metadata.lineCount,+ title: initialContext.pageEditor.metadata.title,+ },+ xml: stepContext?.stepPageEditor?.xml || initialContext.pageEditor.xml,+ }+ : undefined),+ }),// Task Manager page context (inject current tasks list/detail to last user message)new TaskManagerContextInjector({contextPrompt: initialContext?.taskManager?.contextPrompt,diff --git a/packages/context-engine/src/engine/messages/__tests__/MessagesEngine.test.ts b/packages/context-engine/src/engine/messages/__tests__/MessagesEngine.test.tsindex 909d7b770c2..5c02ecf5de0 100644--- a/packages/context-engine/src/engine/messages/__tests__/MessagesEngine.test.ts+++ b/packages/context-engine/src/engine/messages/__tests__/MessagesEngine.test.ts@@ -828,6 +828,97 @@ describe('MessagesEngine', () => {});});+ describe('Page Editor context', () => {+ it('should inject page content to the last user message when pageContentContext is provided', async () => {+ const messages: UIChatMessage[] = [+ {+ content: 'First question',+ createdAt: Date.now(),+ id: 'msg-1',+ role: 'user',+ updatedAt: Date.now(),+ } as UIChatMessage,+ {+ content: 'Answer',+ createdAt: Date.now(),+ id: 'msg-2',+ role: 'assistant',+ updatedAt: Date.now(),+ } as UIChatMessage,+ {+ content: 'Second question about the page',+ createdAt: Date.now(),+ id: 'msg-3',+ role: 'user',+ updatedAt: Date.now(),+ } as UIChatMessage,+ ];++ const params = createBasicParams({+ messages,+ pageContentContext: {+ markdown: '# Document Title\n\nDocument content here.',+ metadata: {+ charCount: 40,+ lineCount: 3,+ title: 'Test Document',+ },+ },+ });+ const engine = new MessagesEngine(params);++ const result = await engine.process();++ expect(result.messages).toEqual([+ { content: 'First question', role: 'user' },+ { content: 'Answer', role: 'assistant' },+ {+ content: `Second question about the page++<!-- SYSTEM CONTEXT (NOT PART OF USER QUERY) -->+<context.instruction>following part contains context information injected by the system. Please follow these instructions:++1. Always prioritize handling user-visible content.+2. the context is only required when user's queries rely on it.+</context.instruction>+<current_page_context>+<current_page title="Test Document">+<markdown chars="40" lines="3">+# Document Title++Document content here.+</markdown>+</current_page>+</current_page_context>+<!-- END SYSTEM CONTEXT -->`,+ role: 'user',+ },+ ]);++ expect(result.metadata.pageEditorContextInjected).toBe(true);+ });++ it('should not inject page content when not enabled', async () => {+ const messages: UIChatMessage[] = [+ {+ content: 'Question',+ createdAt: Date.now(),+ id: 'msg-1',+ role: 'user',+ updatedAt: Date.now(),+ } as UIChatMessage,+ ];++ const params = createBasicParams({ messages });+ const engine = new MessagesEngine(params);++ const result = await engine.process();++ expect(result.messages).toEqual([{ content: 'Question', role: 'user' }]);+ expect(result.metadata.pageEditorContextInjected).toBeUndefined();+ });+ });+describe('Active Topic Document context', () => {it('should inject active topic document context to the last user message', async () => {const messages: UIChatMessage[] = [@@ -871,6 +962,42 @@ describe('MessagesEngine', () => {expect(userMessage?.content).toContain('Call readDocument with format="xml" only when');expect(result.metadata.activeTopicDocumentContextInjected).toBe(true);});++ it('should skip active topic document context when page editor context is enabled', async () => {+ const messages: UIChatMessage[] = [+ {+ content: 'Question',+ createdAt: Date.now(),+ id: 'msg-1',+ role: 'user',+ updatedAt: Date.now(),+ } as UIChatMessage,+ ];++ const params = createBasicParams({+ initialContext: {+ activeTopicDocument: {+ agentDocumentId: 'agd_123',+ documentId: 'docs_123',+ title: 'Topic Plan',+ },+ pageEditor: {+ markdown: '# Page',+ metadata: { title: 'Page' },+ xml: '<root />',+ },+ },+ messages,+ });+ const engine = new MessagesEngine(params);++ const result = await engine.process();+ const userMessage = result.messages.find((m) => m.role === 'user');++ expect(userMessage?.content).not.toContain('<active_topic_document>');+ expect(result.metadata.activeTopicDocumentContextInjected).toBeUndefined();+ expect(result.metadata.pageEditorContextInjected).toBe(true);+ });});describe('Disabled tool call filtering', () => {@@ -1069,6 +1196,252 @@ describe('MessagesEngine', () => {});describe('Page Selections', () => {+ it('should inject page selections to each user message that has them', async () => {+ const messages: UIChatMessage[] = [+ {+ content: 'First question with selection',+ createdAt: Date.now(),+ id: 'msg-1',+ metadata: {+ pageSelections: [+ {+ content: 'Selected paragraph 1',+ id: 'sel-1',+ pageId: 'page-1',+ xml: '<p>Selected paragraph 1</p>',+ },+ ],+ },+ role: 'user',+ updatedAt: Date.now(),+ } as UIChatMessage,+ {+ content: 'Answer to first',+ createdAt: Date.now(),+ id: 'msg-2',+ role: 'assistant',+ updatedAt: Date.now(),+ } as UIChatMessage,+ {+ content: 'Second question with different selection',+ createdAt: Date.now(),+ id: 'msg-3',+ metadata: {+ pageSelections: [+ {+ content: 'Selected paragraph 2',+ id: 'sel-2',+ pageId: 'page-1',+ xml: '<p>Selected paragraph 2</p>',+ },+ ],+ },+ role: 'user',+ updatedAt: Date.now(),+ } as UIChatMessage,+ ];++ const params = createBasicParams({+ messages,+ pageContentContext: {+ markdown: '# Doc',+ metadata: { title: 'Doc' },+ },+ });+ const engine = new MessagesEngine(params);++ const result = await engine.process();++ expect(result.messages).toEqual([+ {+ content: `First question with selection++<!-- SYSTEM CONTEXT (NOT PART OF USER QUERY) -->+<context.instruction>following part contains context information injected by the system. Please follow these instructions:++1. Always prioritize handling user-visible content.+2. the context is only required when user's queries rely on it.+</context.instruction>+<user_page_selections>+<user_selections count="1">+<selection >+<p>Selected paragraph 1</p>+</selection>+</user_selections>+</user_page_selections>+<!-- END SYSTEM CONTEXT -->`,+ role: 'user',+ },+ { content: 'Answer to first', role: 'assistant' },+ {+ content: `Second question with different selection++<!-- SYSTEM CONTEXT (NOT PART OF USER QUERY) -->+<context.instruction>following part contains context information injected by the system. Please follow these instructions:++1. Always prioritize handling user-visible content.+2. the context is only required when user's queries rely on it.+</context.instruction>+<user_page_selections>+<user_selections count="1">+<selection >+<p>Selected paragraph 2</p>+</selection>+</user_selections>+</user_page_selections>+<current_page_context>+<current_page title="Doc">+<markdown chars="5" lines="1">+# Doc+</markdown>+</current_page>+</current_page_context>+<!-- END SYSTEM CONTEXT -->`,+ role: 'user',+ },+ ]);+ });++ it('should skip user messages without pageSelections', async () => {+ const messages: UIChatMessage[] = [+ {+ content: 'No selection here',+ createdAt: Date.now(),+ id: 'msg-1',+ role: 'user',+ updatedAt: Date.now(),+ } as UIChatMessage,+ {+ content: 'Answer',+ createdAt: Date.now(),+ id: 'msg-2',+ role: 'assistant',+ updatedAt: Date.now(),+ } as UIChatMessage,+ {+ content: 'With selection',+ createdAt: Date.now(),+ id: 'msg-3',+ metadata: {+ pageSelections: [+ {+ content: 'Selected text',+ id: 'sel-1',+ pageId: 'page-1',+ xml: '<span>Selected text</span>',+ },+ ],+ },+ role: 'user',+ updatedAt: Date.now(),+ } as UIChatMessage,+ ];++ const params = createBasicParams({+ messages,+ pageContentContext: {+ markdown: '# Doc',+ metadata: { title: 'Doc' },+ },+ });+ const engine = new MessagesEngine(params);++ const result = await engine.process();++ expect(result.messages).toEqual([+ { content: 'No selection here', role: 'user' },+ { content: 'Answer', role: 'assistant' },+ {+ content: `With selection++<!-- SYSTEM CONTEXT (NOT PART OF USER QUERY) -->+<context.instruction>following part contains context information injected by the system. Please follow these instructions:++1. Always prioritize handling user-visible content.+2. the context is only required when user's queries rely on it.+</context.instruction>+<user_page_selections>+<user_selections count="1">+<selection >+<span>Selected text</span>+</selection>+</user_selections>+</user_page_selections>+<current_page_context>+<current_page title="Doc">+<markdown chars="5" lines="1">+# Doc+</markdown>+</current_page>+</current_page_context>+<!-- END SYSTEM CONTEXT -->`,+ role: 'user',+ },+ ]);+ });++ it('should have only one SYSTEM CONTEXT wrapper when both selections and page content are injected', async () => {+ const messages: UIChatMessage[] = [+ {+ content: 'Question about selection',+ createdAt: Date.now(),+ id: 'msg-1',+ metadata: {+ pageSelections: [+ {+ content: 'Selected text',+ id: 'sel-1',+ pageId: 'page-1',+ xml: '<p>Selected text</p>',+ },+ ],+ },+ role: 'user',+ updatedAt: Date.now(),+ } as UIChatMessage,+ ];++ const params = createBasicParams({+ messages,+ pageContentContext: {+ markdown: '# Full Document',+ metadata: { title: 'Full Doc' },+ },+ });+ const engine = new MessagesEngine(params);++ const result = await engine.process();++ expect(result.messages).toEqual([+ {+ content: `Question about selection++<!-- SYSTEM CONTEXT (NOT PART OF USER QUERY) -->+<context.instruction>following part contains context information injected by the system. Please follow these instructions:++1. Always prioritize handling user-visible content.+2. the context is only required when user's queries rely on it.+</context.instruction>+<user_page_selections>+<user_selections count="1">+<selection >+<p>Selected text</p>+</selection>+</user_selections>+</user_page_selections>+<current_page_context>+<current_page title="Full Doc">+<markdown chars="15" lines="1">+# Full Document+</markdown>+</current_page>+</current_page_context>+<!-- END SYSTEM CONTEXT -->`,+ role: 'user',+ },+ ]);+ });+it('should inject generic text selections when page editor is not enabled', async () => {const messages: UIChatMessage[] = [{@@ -1104,7 +1477,7 @@ describe('MessagesEngine', () => {);});- it('should inject legacy page selections as LiteXML with node ids', async () => {+ it('should not inject legacy page selections when page editor is not enabled', async () => {const messages: UIChatMessage[] = [{content: 'Question',@@ -1112,12 +1485,7 @@ describe('MessagesEngine', () => {id: 'msg-1',metadata: {pageSelections: [- {- content: 'Selected',- id: 'sel-1',- pageId: 'page-1',- xml: '<p id="ab12">Selected</p>',- },+ { content: 'Selected', id: 'sel-1', pageId: 'page-1', xml: '<p>Selected</p>' },],},role: 'user',@@ -1125,13 +1493,13 @@ describe('MessagesEngine', () => {} as UIChatMessage,];- const engine = new MessagesEngine(createBasicParams({ messages }));+ // No pageContentContext or initialContext.pageEditor means not enabled+ const params = createBasicParams({ messages });+ const engine = new MessagesEngine(params);const result = await engine.process();- expect(result.messages[0].content).toContain('source="page"');- expect(result.messages[0].content).toContain('<p id="ab12">Selected</p>');- expect(result.messages[0].content).not.toContain('<user_page_selections');+ expect(result.messages).toEqual([{ content: 'Question', role: 'user' }]);});it('should place additional contexts at the stable prefix and virtual tail', async () => {diff --git a/packages/context-engine/src/engine/messages/types.ts b/packages/context-engine/src/engine/messages/types.tsindex 5c34bb6bf32..3a059abd010 100644--- a/packages/context-engine/src/engine/messages/types.ts+++ b/packages/context-engine/src/engine/messages/types.ts@@ -1,5 +1,10 @@/* eslint-disable perfectionist/sort-interfaces */-import type { AgentIdentityContext, FileContent, KnowledgeBaseInfo } from '@lobechat/prompts';+import type {+ AgentIdentityContext,+ FileContent,+ KnowledgeBaseInfo,+ PageContentContext,+} from '@lobechat/prompts';import type {ExpertiseContextSnapshot,RuntimeAdditionalContextFragment,@@ -349,6 +354,11 @@ export interface MessagesEngineParams {* Contains static state like initial page content that doesn't change during execution*/initialContext?: RuntimeInitialContext;+ /**+ * Page content context for direct injection (server-side usage)+ * When provided, takes precedence over initialContext/stepContext+ */+ pageContentContext?: PageContentContext;/*** Step context computed at the beginning of each step (frontend runtime usage)* Contains dynamic state like latest XML that changes between stepsdiff --git a/packages/context-engine/src/providers/ContextSelectionsInjector.ts b/packages/context-engine/src/providers/ContextSelectionsInjector.tsindex 14f9bff3358..0b371384a25 100644--- a/packages/context-engine/src/providers/ContextSelectionsInjector.ts+++ b/packages/context-engine/src/providers/ContextSelectionsInjector.ts@@ -1,5 +1,5 @@import { formatContextSelections } from '@lobechat/prompts';-import type { ContextSelection, PageSelection } from '@lobechat/types';+import type { ContextSelection } from '@lobechat/types';import debug from 'debug';import { BaseEveryUserContentProvider } from '../base/BaseEveryUserContentProvider';@@ -7,22 +7,6 @@ import type { Message, ProcessorOptions } from '../types';const log = debug('context-engine:provider:ContextSelectionsInjector');-const fromLegacyPageSelections = (- selections: PageSelection[] | undefined,-): ContextSelection[] | undefined =>- selections?.map((selection) => ({- content: selection.content,- id: selection.id,- lineRange:- selection.startLine === undefined- ? undefined- : { endLine: selection.endLine ?? selection.startLine, startLine: selection.startLine },- pageId: selection.pageId,- source: 'page',- title: selection.title,- xml: selection.xml,- }));-export interface ContextSelectionsInjectorConfig {/** Whether generic contextSelections injection is enabled */enabled?: boolean;@@ -53,9 +37,7 @@ export class ContextSelectionsInjector extends BaseEveryUserContentProvider {return null;}- const contextSelections =- (message.metadata?.contextSelections as ContextSelection[] | undefined) ??- fromLegacyPageSelections(message.metadata?.pageSelections as PageSelection[] | undefined);+ const contextSelections = message.metadata?.contextSelections as ContextSelection[] | undefined;if (!contextSelections || contextSelections.length === 0) {return null;diff --git a/packages/context-engine/src/providers/PageEditorContextInjector.ts b/packages/context-engine/src/providers/PageEditorContextInjector.tsnew file mode 100644index 00000000000..d7925bfc1c6--- /dev/null+++ b/packages/context-engine/src/providers/PageEditorContextInjector.ts@@ -0,0 +1,94 @@+import type { PageContentContext } from '@lobechat/prompts';+import { formatPageContentContext } from '@lobechat/prompts';+import debug from 'debug';++import { BaseLastUserContentProvider } from '../base/BaseLastUserContentProvider';+import type { PipelineContext, ProcessorOptions } from '../types';++declare module '../types' {+ interface PipelineContextMetadataOverrides {+ pageEditorContextInjected?: boolean;+ }+}++const log = debug('context-engine:provider:PageEditorContextInjector');++export interface PageEditorContextInjectorConfig {+ /** Whether Page Editor/Agent is enabled */+ enabled?: boolean;+ /**+ * Page content context to inject+ * Contains markdown, xml, and metadata for the current page+ */+ pageContentContext?: PageContentContext;+}++/**+ * Page Editor Context Injector+ * Responsible for injecting current page context at the end of the last user message+ * This ensures the model receives the most up-to-date page/document state+ *+ * Note: Page selections (user-selected text regions) are handled separately by+ * PageSelectionsInjector, which injects selections into each user message that has them+ */+export class PageEditorContextInjector extends BaseLastUserContentProvider {+ readonly name = 'PageEditorContextInjector';++ constructor(+ private config: PageEditorContextInjectorConfig,+ options: ProcessorOptions = {},+ ) {+ super(options);+ }++ protected async doProcess(context: PipelineContext): Promise<PipelineContext> {+ log('doProcess called');+ log('config.enabled:', this.config.enabled);++ const clonedContext = this.cloneContext(context);++ // Check if we have page content to inject+ const hasPageContent = this.config.enabled && this.config.pageContentContext;++ if (!hasPageContent) {+ log('No pageContentContext, skipping injection');+ return this.markAsExecuted(clonedContext);+ }++ // Find the last user message index+ const lastUserIndex = this.findLastUserMessageIndex(clonedContext.messages);++ log('Last user message index:', lastUserIndex);++ if (lastUserIndex === -1) {+ log('No user messages found, skipping injection');+ return this.markAsExecuted(clonedContext);+ }++ // Format page content+ const formattedContent = formatPageContentContext(this.config.pageContentContext!);++ if (!formattedContent) {+ log('No content to inject after formatting');+ return this.markAsExecuted(clonedContext);+ }++ log('Page content formatted, length:', formattedContent.length);++ // Check if system context wrapper already exists+ // If yes, only insert context block; if no, use full wrapper+ const hasExistingWrapper = this.hasExistingSystemContext(clonedContext);+ const contentToAppend = hasExistingWrapper+ ? this.createContextBlock(formattedContent, 'current_page_context')+ : this.wrapWithSystemContext(formattedContent, 'current_page_context');++ this.appendToLastUserMessage(clonedContext, contentToAppend);++ // Update metadata+ clonedContext.metadata.pageEditorContextInjected = true;++ log('Page Editor context appended to last user message');++ return this.markAsExecuted(clonedContext);+ }+}diff --git a/packages/context-engine/src/providers/PageSelectionsInjector.ts b/packages/context-engine/src/providers/PageSelectionsInjector.tsnew file mode 100644index 00000000000..9357f35687a--- /dev/null+++ b/packages/context-engine/src/providers/PageSelectionsInjector.ts@@ -0,0 +1,64 @@+import { formatPageSelections } from '@lobechat/prompts';+import type { PageSelection } from '@lobechat/types';+import debug from 'debug';++import { BaseEveryUserContentProvider } from '../base/BaseEveryUserContentProvider';+import type { Message, ProcessorOptions } from '../types';++const log = debug('context-engine:provider:PageSelectionsInjector');++export interface PageSelectionsInjectorConfig {+ /** Whether Page Selections injection is enabled */+ enabled?: boolean;+}++/**+ * Page Selections Injector+ * Responsible for injecting page selections into each user message that has them+ * Unlike PageEditorContextInjector which only injects to the last user message,+ * this processor handles selections attached to any user message in the conversation+ *+ * This injector runs BEFORE PageEditorContextInjector so that:+ * - Each user message with selections gets a SYSTEM CONTEXT wrapper+ * - PageEditorContextInjector can then reuse the wrapper for the last user message+ */+export class PageSelectionsInjector extends BaseEveryUserContentProvider {+ readonly name = 'PageSelectionsInjector';++ constructor(+ private config: PageSelectionsInjectorConfig = {},+ options: ProcessorOptions = {},+ ) {+ super(options);+ }++ protected buildContentForMessage(+ message: Message,+ index: number,+ ): { content: string; contextType: string } | null {+ if (!this.config.enabled) {+ return null;+ }++ // Check if message has legacy pageSelections in metadata+ const pageSelections = message.metadata?.pageSelections as PageSelection[] | undefined;++ if (!pageSelections || pageSelections.length === 0) {+ return null;+ }++ // Format the selections+ const formattedSelections = formatPageSelections(pageSelections);++ if (!formattedSelections) {+ return null;+ }++ log(`Building content for message at index ${index} with ${pageSelections.length} selections`);++ return {+ content: formattedSelections,+ contextType: 'user_page_selections',+ };+ }+}diff --git a/packages/context-engine/src/providers/__tests__/ContextSelectionsInjector.test.ts b/packages/context-engine/src/providers/__tests__/ContextSelectionsInjector.test.tsindex 1eb1eadcd03..d21a26c4d1e 100644--- a/packages/context-engine/src/providers/__tests__/ContextSelectionsInjector.test.ts+++ b/packages/context-engine/src/providers/__tests__/ContextSelectionsInjector.test.ts@@ -84,93 +84,6 @@ describe('ContextSelectionsInjector', () => {});});- describe('page selections', () => {- it('distinguishes an exact phrase selection from the containing block', async () => {- const injector = new ContextSelectionsInjector({ enabled: true });- const result = await injector.process(- createContext([- {- content: 'Rewrite only the selection',- metadata: {- contextSelections: [- {- content: 'a<b\n and c>d',- id: 'sel-1',- pageId: 'page-1',- source: 'page',- xml: '<p id="ab12">Before a<b and c>d after</p>',- },- ],- },- role: 'user',- },- ]),- );-- expect(result.messages[0].content).toContain(- '<selected_text>a<b\n and c>d</selected_text>',- );- expect(result.messages[0].content).toContain('<containing_blocks>');- expect(result.messages[0].content).toContain(- '<p id="ab12">Before a<b and c>d after</p>',- );- });- it('injects a page selection as its LiteXML, node ids included', async () => {- const injector = new ContextSelectionsInjector({ enabled: true });-- const result = await injector.process(- createContext([- {- content: 'Rewrite this',- metadata: {- contextSelections: [- {- content: 'Pricing starts at $10',- id: 'sel-1',- pageId: 'page-1',- source: 'page',- xml: '<p id="ab12"><span id="cd34">Pricing starts at $10</span></p>',- },- ],- },- role: 'user',- },- ]),- );-- expect(result.messages[0].content).toContain(- '<p id="ab12"><span id="cd34">Pricing starts at $10</span></p>',- );- expect(result.messages[0].content).toContain('source="page"');- });-- it('falls back to legacy pageSelections on messages saved before contextSelections', async () => {- const injector = new ContextSelectionsInjector({ enabled: true });-- const result = await injector.process(- createContext([- {- content: 'Shorten this',- metadata: {- pageSelections: [- {- content: 'A long legacy paragraph',- id: 'sel-1',- pageId: 'page-1',- xml: '<p id="ab12">A long legacy paragraph</p>',- },- ],- },- role: 'user',- },- ]),- );-- expect(result.messages[0].content).toContain('<p id="ab12">A long legacy paragraph</p>');- expect(result.messages[0].content).toContain('source="page"');- });- });-describe('context sources', () => {it('should inject code context selections with source metadata', async () => {const injector = new ContextSelectionsInjector({ enabled: true });diff --git a/packages/context-engine/src/providers/__tests__/PageEditorContextInjector.test.ts b/packages/context-engine/src/providers/__tests__/PageEditorContextInjector.test.tsnew file mode 100644index 00000000000..490da720532--- /dev/null+++ b/packages/context-engine/src/providers/__tests__/PageEditorContextInjector.test.ts@@ -0,0 +1,247 @@+import type { PageContentContext } from '@lobechat/prompts';+import { describe, expect, it } from 'vitest';++import type { PipelineContext } from '../../types';+import { PageEditorContextInjector } from '../PageEditorContextInjector';++describe('PageEditorContextInjector', () => {+ const createContext = (messages: any[] = []): PipelineContext => ({+ initialState: {+ messages: [],+ model: 'test-model',+ provider: 'test-provider',+ },+ isAborted: false,+ messages,+ metadata: {+ maxTokens: 4000,+ model: 'test-model',+ },+ });++ // Minimal page content context for predictable output+ const createMinimalPageContentContext = (): PageContentContext => ({+ markdown: 'Doc content',+ metadata: {+ title: 'Test Document',+ },+ });++ describe('injection position', () => {+ it('should append context to the last user message', async () => {+ const injector = new PageEditorContextInjector({+ enabled: true,+ pageContentContext: createMinimalPageContentContext(),+ });++ const context = createContext([+ { content: 'First question', role: 'user' },+ { content: 'First answer', role: 'assistant' },+ { content: 'Second question', role: 'user' },+ ]);++ const result = await injector.process(context);++ expect(result.messages).toHaveLength(3);+ expect(result.messages[0].content).toBe('First question');+ expect(result.messages[1].content).toBe('First answer');+ // The last user message should have the context appended+ expect(result.messages[2].content).toContain('Second question');+ expect(result.messages[2].content).toContain('<current_page title="Test Document">');+ expect(result.messages[2].content).toContain('Doc content');+ });++ it('should append to the only user message when there is just one', async () => {+ const injector = new PageEditorContextInjector({+ enabled: true,+ pageContentContext: createMinimalPageContentContext(),+ });++ const context = createContext([{ content: 'Only question', role: 'user' }]);++ const result = await injector.process(context);++ expect(result.messages).toHaveLength(1);+ expect(result.messages[0].content).toContain('Only question');+ expect(result.messages[0].content).toContain('<current_page title="Test Document">');+ });++ it('should inject to last user message when last message is tool', async () => {+ const injector = new PageEditorContextInjector({+ enabled: true,+ pageContentContext: createMinimalPageContentContext(),+ });++ const context = createContext([+ { content: 'First question', role: 'user' },+ { content: 'First answer', role: 'assistant' },+ { content: 'User request to modify', role: 'user' },+ {+ content: 'I will modify the document',+ role: 'assistant',+ tool_calls: [{ id: 'call_1', function: { name: 'modifyNodes', arguments: '{}' } }],+ },+ { content: 'Successfully modified', role: 'tool', tool_call_id: 'call_1' },+ ]);++ const result = await injector.process(context);++ expect(result.messages).toHaveLength(5);+ // First user message should NOT have injection+ expect(result.messages[0].content).toBe('First question');+ // Last user message (index 2) should have the context appended+ expect(result.messages[2].content).toContain('User request to modify');+ expect(result.messages[2].content).toContain('<current_page title="Test Document">');+ // Tool message should remain unchanged+ expect(result.messages[4].content).toBe('Successfully modified');+ });+ });++ describe('injection format with markdown and xml', () => {+ it('should include markdown content in injection', async () => {+ const injector = new PageEditorContextInjector({+ enabled: true,+ pageContentContext: {+ markdown: '# Hello World\n\nThis is content.',+ metadata: {+ charCount: 30,+ lineCount: 3,+ title: 'Hello World',+ },+ },+ });++ const context = createContext([{ content: 'Question', role: 'user' }]);+ const result = await injector.process(context);++ expect(result.messages[0].content).toContain('<markdown chars="30" lines="3">');+ expect(result.messages[0].content).toContain('# Hello World');+ expect(result.messages[0].content).toContain('This is content.');+ });++ it('should include xml structure in injection', async () => {+ const injector = new PageEditorContextInjector({+ enabled: true,+ pageContentContext: {+ metadata: {+ title: 'Test Doc',+ },+ xml: '<root><p id="1">Hello</p></root>',+ },+ });++ const context = createContext([{ content: 'Question', role: 'user' }]);+ const result = await injector.process(context);++ expect(result.messages[0].content).toContain('<doc_xml_structure>');+ expect(result.messages[0].content).toContain('<root><p id="1">Hello</p></root>');+ expect(result.messages[0].content).toContain('</doc_xml_structure>');+ });++ it('should include both markdown and xml when provided', async () => {+ const injector = new PageEditorContextInjector({+ enabled: true,+ pageContentContext: {+ markdown: '# Title\n\nContent here.',+ metadata: {+ charCount: 20,+ lineCount: 3,+ title: 'Full Doc',+ },+ xml: '<root><h1 id="1">Title</h1><p id="2">Content here.</p></root>',+ },+ });++ const context = createContext([{ content: 'Q', role: 'user' }]);+ const result = await injector.process(context);++ expect(result.messages[0].content).toContain('<current_page title="Full Doc">');+ expect(result.messages[0].content).toContain('<markdown');+ expect(result.messages[0].content).toContain('# Title');+ expect(result.messages[0].content).toContain('<doc_xml_structure>');+ expect(result.messages[0].content).toContain('<root>');+ });+ });++ describe('skip conditions', () => {+ it('should skip injection when disabled', async () => {+ const injector = new PageEditorContextInjector({+ enabled: false,+ pageContentContext: createMinimalPageContentContext(),+ });++ const context = createContext([{ content: 'Question', role: 'user' }]);+ const result = await injector.process(context);++ expect(result.messages[0].content).toBe('Question');+ expect(result.metadata.pageEditorContextInjected).toBeUndefined();+ });++ it('should skip injection when pageContentContext is not provided', async () => {+ const injector = new PageEditorContextInjector({+ enabled: true,+ });++ const context = createContext([{ content: 'Question', role: 'user' }]);+ const result = await injector.process(context);++ expect(result.messages[0].content).toBe('Question');+ expect(result.metadata.pageEditorContextInjected).toBeUndefined();+ });++ it('should skip injection when no user messages exist', async () => {+ const injector = new PageEditorContextInjector({+ enabled: true,+ pageContentContext: createMinimalPageContentContext(),+ });++ const context = createContext([{ content: 'System message', role: 'system' }]);+ const result = await injector.process(context);++ expect(result.messages).toHaveLength(1);+ expect(result.messages[0].content).toBe('System message');+ });+ });++ describe('metadata', () => {+ it('should set pageEditorContextInjected metadata to true', async () => {+ const injector = new PageEditorContextInjector({+ enabled: true,+ pageContentContext: createMinimalPageContentContext(),+ });++ const context = createContext([{ content: 'Question', role: 'user' }]);+ const result = await injector.process(context);++ expect(result.metadata.pageEditorContextInjected).toBe(true);+ });+ });++ describe('multimodal messages', () => {+ it('should append to array content with text parts', async () => {+ const injector = new PageEditorContextInjector({+ enabled: true,+ pageContentContext: createMinimalPageContentContext(),+ });++ const context = createContext([+ {+ content: [+ { text: 'User question', type: 'text' },+ { image_url: { url: 'http://example.com/image.png' }, type: 'image_url' },+ ],+ role: 'user',+ },+ ]);++ const result = await injector.process(context);++ expect(result.messages[0].content[0].text).toContain('User question');+ expect(result.messages[0].content[0].text).toContain('<current_page title="Test Document">');+ expect(result.messages[0].content[1]).toEqual({+ image_url: { url: 'http://example.com/image.png' },+ type: 'image_url',+ });+ });+ });+});diff --git a/packages/context-engine/src/providers/__tests__/PageSelectionsInjector.test.ts b/packages/context-engine/src/providers/__tests__/PageSelectionsInjector.test.tsnew file mode 100644index 00000000000..f9f06a5321f--- /dev/null+++ b/packages/context-engine/src/providers/__tests__/PageSelectionsInjector.test.ts@@ -0,0 +1,333 @@+import { describe, expect, it } from 'vitest';++import type { PipelineContext } from '../../types';+import { PageSelectionsInjector } from '../PageSelectionsInjector';++describe('PageSelectionsInjector', () => {+ const createContext = (messages: any[] = []): PipelineContext => ({+ initialState: {+ messages: [],+ model: 'test-model',+ provider: 'test-provider',+ },+ isAborted: false,+ messages,+ metadata: {+ maxTokens: 4000,+ model: 'test-model',+ },+ });++ const createPageSelection = (id: string, xmlContent: string, pageId = 'page-1') => ({+ content: xmlContent, // preview content+ id,+ pageId,+ xml: xmlContent, // actual content used by formatPageSelections+ });++ describe('enabled/disabled', () => {+ it('should skip injection when disabled', async () => {+ const injector = new PageSelectionsInjector({ enabled: false });++ const context = createContext([+ {+ content: 'Question',+ metadata: {+ pageSelections: [createPageSelection('sel-1', 'Selected text')],+ },+ role: 'user',+ },+ ]);++ const result = await injector.process(context);++ expect(result.messages[0].content).toBe('Question');+ expect(result.metadata.PageSelectionsInjectorInjectedCount).toBeUndefined();+ });++ it('should inject when enabled', async () => {+ const injector = new PageSelectionsInjector({ enabled: true });++ const context = createContext([+ {+ content: 'Question',+ metadata: {+ pageSelections: [createPageSelection('sel-1', 'Selected text')],+ },+ role: 'user',+ },+ ]);++ const result = await injector.process(context);++ expect(result.messages[0].content).toContain('Question');+ expect(result.messages[0].content).toContain('<user_page_selections>');+ expect(result.messages[0].content).toContain('Selected text');+ });+ });++ describe('injection to every user message', () => {+ it('should inject selections to each user message that has them', async () => {+ const injector = new PageSelectionsInjector({ enabled: true });++ const context = createContext([+ {+ content: 'First question',+ metadata: {+ pageSelections: [createPageSelection('sel-1', 'First selection')],+ },+ role: 'user',+ },+ { content: 'First answer', role: 'assistant' },+ {+ content: 'Second question',+ metadata: {+ pageSelections: [createPageSelection('sel-2', 'Second selection')],+ },+ role: 'user',+ },+ { content: 'Second answer', role: 'assistant' },+ {+ content: 'Third question without selection',+ role: 'user',+ },+ ]);++ const result = await injector.process(context);++ // First user message should have first selection+ expect(result.messages[0].content).toContain('First question');+ expect(result.messages[0].content).toContain('First selection');+ expect(result.messages[0].content).toContain('<user_page_selections>');++ // Second user message should have second selection+ expect(result.messages[2].content).toContain('Second question');+ expect(result.messages[2].content).toContain('Second selection');+ expect(result.messages[2].content).toContain('<user_page_selections>');++ // Third user message should NOT have injection (no selections)+ expect(result.messages[4].content).toBe('Third question without selection');++ // Assistant messages should be unchanged+ expect(result.messages[1].content).toBe('First answer');+ expect(result.messages[3].content).toBe('Second answer');++ // Metadata should show 2 injections+ expect(result.metadata.PageSelectionsInjectorInjectedCount).toBe(2);+ });++ it('should skip user messages without pageSelections', async () => {+ const injector = new PageSelectionsInjector({ enabled: true });++ const context = createContext([+ { content: 'No selections here', role: 'user' },+ { content: 'Answer', role: 'assistant' },+ {+ content: 'With selections',+ metadata: {+ pageSelections: [createPageSelection('sel-1', 'Some text')],+ },+ role: 'user',+ },+ ]);++ const result = await injector.process(context);++ expect(result.messages[0].content).toBe('No selections here');+ expect(result.messages[2].content).toContain('With selections');+ expect(result.messages[2].content).toContain('Some text');+ });++ it('should skip user messages with empty pageSelections array', async () => {+ const injector = new PageSelectionsInjector({ enabled: true });++ const context = createContext([+ {+ content: 'Empty selections',+ metadata: { pageSelections: [] },+ role: 'user',+ },+ ]);++ const result = await injector.process(context);++ expect(result.messages[0].content).toBe('Empty selections');+ });+ });++ describe('SYSTEM CONTEXT wrapper', () => {+ it('should wrap selection content with SYSTEM CONTEXT markers', async () => {+ const injector = new PageSelectionsInjector({ enabled: true });++ const context = createContext([+ {+ content: 'Question',+ metadata: {+ pageSelections: [createPageSelection('sel-1', 'Selected text')],+ },+ role: 'user',+ },+ ]);++ const result = await injector.process(context);+ const content = result.messages[0].content as string;++ expect(content).toContain('<!-- SYSTEM CONTEXT (NOT PART OF USER QUERY) -->');+ expect(content).toContain('<context.instruction>');+ expect(content).toContain('<user_page_selections>');+ expect(content).toContain('</user_page_selections>');+ expect(content).toContain('<!-- END SYSTEM CONTEXT -->');+ });++ it('should have only one SYSTEM CONTEXT wrapper per message even with multiple selections', async () => {+ const injector = new PageSelectionsInjector({ enabled: true });++ const context = createContext([+ {+ content: 'Question',+ metadata: {+ pageSelections: [+ createPageSelection('sel-1', 'First selection'),+ createPageSelection('sel-2', 'Second selection'),+ ],+ },+ role: 'user',+ },+ ]);++ const result = await injector.process(context);+ const content = result.messages[0].content as string;++ const startCount = (content.match(/<!-- SYSTEM CONTEXT/g) || []).length;+ const endCount = (content.match(/<!-- END SYSTEM CONTEXT/g) || []).length;++ expect(startCount).toBe(1);+ expect(endCount).toBe(1);+ });++ it('should create separate SYSTEM CONTEXT wrappers for each user message', async () => {+ const injector = new PageSelectionsInjector({ enabled: true });++ const context = createContext([+ {+ content: 'First question',+ metadata: {+ pageSelections: [createPageSelection('sel-1', 'First selection')],+ },+ role: 'user',+ },+ { content: 'Answer', role: 'assistant' },+ {+ content: 'Second question',+ metadata: {+ pageSelections: [createPageSelection('sel-2', 'Second selection')],+ },+ role: 'user',+ },+ ]);++ const result = await injector.process(context);++ // Each user message should have its own SYSTEM CONTEXT wrapper+ const firstContent = result.messages[0].content as string;+ const secondContent = result.messages[2].content as string;++ expect(firstContent).toContain('<!-- SYSTEM CONTEXT');+ expect(firstContent).toContain('First selection');++ expect(secondContent).toContain('<!-- SYSTEM CONTEXT');+ expect(secondContent).toContain('Second selection');+ });+ });++ describe('multimodal messages', () => {+ it('should handle array content with text parts', async () => {+ const injector = new PageSelectionsInjector({ enabled: true });++ const context = createContext([+ {+ content: [+ { text: 'Question with image', type: 'text' },+ { image_url: { url: 'http://example.com/img.png' }, type: 'image_url' },+ ],+ metadata: {+ pageSelections: [createPageSelection('sel-1', 'Selected text')],+ },+ role: 'user',+ },+ ]);++ const result = await injector.process(context);++ expect(result.messages[0].content[0].text).toContain('Question with image');+ expect(result.messages[0].content[0].text).toContain('Selected text');+ expect(result.messages[0].content[0].text).toContain('<user_page_selections>');+ expect(result.messages[0].content[1]).toEqual({+ image_url: { url: 'http://example.com/img.png' },+ type: 'image_url',+ });+ });+ });++ describe('integration with PageEditorContextInjector', () => {+ it('should create wrapper that PageEditorContextInjector can reuse', async () => {+ const injector = new PageSelectionsInjector({ enabled: true });++ const context = createContext([+ {+ content: 'Question about the page',+ metadata: {+ pageSelections: [createPageSelection('sel-1', 'Selected paragraph')],+ },+ role: 'user',+ },+ ]);++ const result = await injector.process(context);+ const content = result.messages[0].content as string;++ // Verify the wrapper structure is correct for reuse+ expect(content).toContain('<!-- SYSTEM CONTEXT (NOT PART OF USER QUERY) -->');+ expect(content).toContain('<context.instruction>');+ expect(content).toContain('<!-- END SYSTEM CONTEXT -->');++ // Verify the content is in the right position (between instruction and end marker)+ const instructionIndex = content.indexOf('</context.instruction>');+ const selectionsIndex = content.indexOf('<user_page_selections>');+ const endIndex = content.indexOf('<!-- END SYSTEM CONTEXT -->');++ expect(instructionIndex).toBeLessThan(selectionsIndex);+ expect(selectionsIndex).toBeLessThan(endIndex);+ });+ });++ describe('metadata', () => {+ it('should set metadata when injections are made', async () => {+ const injector = new PageSelectionsInjector({ enabled: true });++ const context = createContext([+ {+ content: 'Question',+ metadata: {+ pageSelections: [createPageSelection('sel-1', 'Text')],+ },+ role: 'user',+ },+ ]);++ const result = await injector.process(context);++ expect(result.metadata.PageSelectionsInjectorInjectedCount).toBe(1);+ });++ it('should not set metadata when no injections are made', async () => {+ const injector = new PageSelectionsInjector({ enabled: true });++ const context = createContext([{ content: 'No selections', role: 'user' }]);++ const result = await injector.process(context);++ expect(result.metadata.PageSelectionsInjectorInjectedCount).toBeUndefined();+ });+ });+});diff --git a/packages/context-engine/src/providers/index.ts b/packages/context-engine/src/providers/index.tsindex 14bd99ed9e5..d2877e2c6c3 100644--- a/packages/context-engine/src/providers/index.ts+++ b/packages/context-engine/src/providers/index.ts@@ -32,6 +32,8 @@ export { ModelInfoProvider } from './ModelInfoProvider';export { OnboardingActionHintInjector } from './OnboardingActionHintInjector';export { OnboardingContextInjector } from './OnboardingContextInjector';export { OnboardingSyntheticStateInjector } from './OnboardingSyntheticStateInjector';+export { PageEditorContextInjector } from './PageEditorContextInjector';+export { PageSelectionsInjector } from './PageSelectionsInjector';export { PlanInjector } from './PlanInjector';export { ProjectInstructionsInjector } from './ProjectInstructionsInjector';export { RuntimeAdditionalContextProvider } from './RuntimeAdditionalContextProvider';@@ -120,6 +122,8 @@ export type {OnboardingContextInjectorConfig,OnboardingUserInfo,} from './OnboardingContextInjector';+export type { PageEditorContextInjectorConfig } from './PageEditorContextInjector';+export type { PageSelectionsInjectorConfig } from './PageSelectionsInjector';export type { Plan, PlanInjectorConfig } from './PlanInjector';export type {ProjectInstructionFile,diff --git a/packages/editor-runtime/package.json b/packages/editor-runtime/package.jsonindex 72d70912b14..c27d24b0604 100644--- a/packages/editor-runtime/package.json+++ b/packages/editor-runtime/package.json@@ -14,7 +14,6 @@},"peerDependencies": {"@lobehub/editor": "^4.17.1",- "debug": "*",- "lexical": "*"+ "debug": "*"}}diff --git a/packages/editor-runtime/src/EditorRuntime.ts b/packages/editor-runtime/src/EditorRuntime.tsindex 1dfd4115c61..2704241d16e 100644--- a/packages/editor-runtime/src/EditorRuntime.ts+++ b/packages/editor-runtime/src/EditorRuntime.ts@@ -1,14 +1,20 @@import type { PageContentContext } from '@lobechat/prompts';import type { IEditor } from '@lobehub/editor';-import { LITEXML_APPLY_COMMAND, LITEXML_MODIFY_COMMAND } from '@lobehub/editor/litexml-commands';+import {+ LITEXML_APPLY_COMMAND,+ LITEXML_INSERT_COMMAND,+ LITEXML_MODIFY_COMMAND,+ LITEXML_REMOVE_COMMAND,+} from '@lobehub/editor/litexml-commands';import debug from 'debug';-import { $setSelection, type LexicalEditor } from 'lexical';import {describeLiteXMLEditStep,findLiteXMLEditStepProblem,indexLiteXMLDocument,+ normalizeLiteXMLFragment,planLiteXMLEditSteps,+ touchesList,} from './liteXMLEditPlan';import type {EditTitleArgs,@@ -19,6 +25,7 @@ import type {InitPageRuntimeResult,ModifyNodesArgs,ModifyNodesRuntimeResult,+ ModifyOperation,ModifyOperationResult,ReplaceTextArgs,ReplaceTextRuntimeResult,@@ -32,7 +39,7 @@ const nextMicrotask = () => new Promise<void>((resolve) => queueMicrotask(resolvinterface InspectableEditor {dataTypeMap?: Map<string, unknown> | Record<string, unknown>;editor?: unknown;- getLexicalEditor?: () => LexicalEditor | null;+ getLexicalEditor?: () => unknown | null;plugins?: unknown[];pluginsInstances?: unknown[];}@@ -320,14 +327,13 @@ export class EditorRuntime {* Edit the page title* @returns Raw result with newTitle and previousTitle*/- async editTitle(args: EditTitleArgs, beforeApply?: () => void): Promise<EditTitleRuntimeResult> {+ async editTitle(args: EditTitleArgs): Promise<EditTitleRuntimeResult> {log('[EditorRuntime] editTitle:start', {snapshot: this.getDebugSnapshot(),titleLength: args.title.length,});await this.runBeforeMutate('editTitle');- beforeApply?.();const { setter, getter } = this.getTitleHandlers();const previousTitle = getter();@@ -407,10 +413,7 @@ export class EditorRuntime {* Supports insert, modify, and remove operations in a single call.* @returns Raw result with results, successCount and totalCount*/- async modifyNodes(- args: ModifyNodesArgs,- beforeApply?: () => void,- ): Promise<ModifyNodesRuntimeResult> {+ async modifyNodes(args: ModifyNodesArgs): Promise<ModifyNodesRuntimeResult> {const rawOperations = Array.isArray(args.operations)? args.operations: args.operations@@ -424,7 +427,6 @@ export class EditorRuntime {});await this.runBeforeMutate('modifyNodes');- beforeApply?.();const editor = this.getEditor();let { operations } = args;@@ -445,13 +447,6 @@ export class EditorRuntime {throw new Error('modifyNodes failed: LiteXML data source is not ready.');}- // A selection over a node makes the LiteXML diff commands reject edits to- // it ("did not change the page"), e.g. the paragraph a user selected for- // "Ask Lobe AI". The agent edits by node id, so drop the selection first.- (editor as InspectableEditor)- .getLexicalEditor?.()- ?.update(() => $setSelection(null), { discrete: true });-const results: ModifyOperationResult[] = operations.map((op) => ({action: op.action,success: false,@@ -495,7 +490,7 @@ export class EditorRuntime {throw new Error(`${describeLiteXMLEditStep(step, operations.length)}: ${problem}`);log('Dispatching LiteXML operation:', operation);- editor.dispatchCommand(LITEXML_MODIFY_COMMAND, [operation]);+ this.dispatchLiteXMLOperation(editor, operation, !touchesList(operation, document));await nextMicrotask();if (readLiteXML() === before) {@@ -533,6 +528,38 @@ export class EditorRuntime {return result;}+ /**+ * Edits that touch a list skip the pending review diff: @lobehub/editor's+ * list-item diffs serialize as empty items and lose list structure.+ */+ private dispatchLiteXMLOperation(editor: IEditor, operation: ModifyOperation, delay: boolean) {+ if (delay) {+ editor.dispatchCommand(LITEXML_MODIFY_COMMAND, [operation]);+ return;+ }++ switch (operation.action) {+ case 'insert': {+ const litexml = normalizeLiteXMLFragment(operation.litexml);+ editor.dispatchCommand(+ LITEXML_INSERT_COMMAND,+ 'beforeId' in operation+ ? { beforeId: operation.beforeId, delay: false, litexml }+ : { afterId: operation.afterId, delay: false, litexml },+ );+ return;+ }+ case 'modify': {+ editor.dispatchCommand(LITEXML_APPLY_COMMAND, { delay: false, litexml: operation.litexml });+ return;+ }+ case 'remove': {+ editor.dispatchCommand(LITEXML_REMOVE_COMMAND, { delay: false, id: operation.id });+ return;+ }+ }+ }+// ==================== Text Operations ====================/**diff --git a/packages/editor-runtime/src/__tests__/EditorRuntime.real.test.ts b/packages/editor-runtime/src/__tests__/EditorRuntime.real.test.tsindex afbb7e554ec..ca270071044 100644--- a/packages/editor-runtime/src/__tests__/EditorRuntime.real.test.ts+++ b/packages/editor-runtime/src/__tests__/EditorRuntime.real.test.ts@@ -11,7 +11,6 @@ import type { Mock } from 'vitest';import { beforeEach, describe, expect, it, vi } from 'vitest';import { EditorRuntime } from '../EditorRuntime';-import { parseLiteXMLBlocks } from '../liteXMLBlockDiff';import editAllFixture from './fixtures/edit-all.json';import removeFixture from './fixtures/remove.json';import removeThenAddFixture from './fixtures/remove-then-add.json';@@ -239,7 +238,7 @@ describe('EditorRuntime - Real Cases', () => {expect(xml.indexOf('P2')).toBeLessThan(xml.indexOf('P3'));});- it('preserves pending inserts when a later replacement of the enclosing list is rejected', async () => {+ it('does not report inserts erased by a later replacement of the enclosing list as applied', async () => {const anchor = idOf('li', 'a');const list = liteXML().match(/<ul id="\w+">[\s\S]*?<\/ul>/)![0];const result = await runtime.modifyNodes({@@ -250,14 +249,12 @@ describe('EditorRuntime - Real Cases', () => {],});- // Wrapping an existing pending edit in another diff is rejected. Keep- // both pending inserts instead of silently discarding the first one.- expect(result.results.map((r) => r.success)).toEqual([true, false, true]);- expect(result.results[1].error).toContain('did not change');- const markdown = editor.getDocument('markdown') as unknown as string;- expect(markdown).toContain('- A');- expect(markdown).toContain('- B');- expect(markdown).not.toContain('- b2');+ // Applied in caller order: the list replacement drops A and re-keys the+ // list, so the later insert is reported as failed instead of vanishing+ // behind a success.+ expect(result.results.map((r) => r.success)).toEqual([true, true, false]);+ expect(result.results[2].error).toContain('not found');+ expect(editor.getDocument('markdown') as unknown as string).toContain('- b2');});it('rejects a multi-fragment modify that replaces a list and an item inside it', async () => {@@ -397,14 +394,9 @@ describe('EditorRuntime - Real Cases', () => {expect(insertResult.results.every((r) => r.success)).toBe(true);expect(insertResult.results.every((r) => r.action === 'insert')).toBe(true);+ // Verify full outputconst xmlAfter = editor.getDocument('litexml') as unknown as string;- const blocks = parseLiteXMLBlocks(xmlAfter);- if (typeof blocks === 'string') throw new Error(blocks);- expect(blocks.map(({ tag }) => tag)).toEqual(['p', 'h2', 'ul', 'h2']);- expect(blocks[2].text).toBe(- '西湖风景区:杭州的灵魂,世界文化遗产 灵隐寺:杭州最著名的佛教寺庙 西溪国家湿地公园:中国第一个国家湿地公园 宋城:以宋代文化为主题的大型主题公园',- );- expect(JSON.stringify(editor.getDocument('json'))).toContain('"diffType":"add"');+ expect(xmlAfter).toMatchSnapshot('insert new');});});});diff --git a/packages/editor-runtime/src/__tests__/__snapshots__/EditorRuntime.real.test.ts.snap b/packages/editor-runtime/src/__tests__/__snapshots__/EditorRuntime.real.test.ts.snapindex 9c6a25e5310..e0e2c3711e3 100644--- a/packages/editor-runtime/src/__tests__/__snapshots__/EditorRuntime.real.test.ts.snap+++ b/packages/editor-runtime/src/__tests__/__snapshots__/EditorRuntime.real.test.ts.snap@@ -83,6 +83,35 @@ exports[`EditorRuntime - Real Cases > modifyNodes - batch remove paragraphs > sh</root>"`;+exports[`EditorRuntime - Real Cases > modifyNodes - remove then add > should remove 13 paragraphs then insert a list > insert new 1`] = `+"<?xml version="1.0" encoding="UTF-8"?>+<root>+ <p id="wihj">+ <span id="wo1u">杭州是中国著名的旅游城市,素有"人间天堂"的美誉。这里既有美丽的自然风光,又有深厚的历史文化底蕴。</span>+ </p>+ <h2 id="wtm5">+ <span id="wz6g">必游景点</span>+ </h2>+ <ul id="9nfi">+ <li id="9szt">+ <span id="9yk4">西湖风景区:杭州的灵魂,世界文化遗产</span>+ </li>+ <li id="a44f">+ <span id="a9oq">灵隐寺:杭州最著名的佛教寺庙</span>+ </li>+ <li id="af91">+ <span id="aktc">西溪国家湿地公园:中国第一个国家湿地公园</span>+ </li>+ <li id="aqdn">+ <span id="avxy">宋城:以宋代文化为主题的大型主题公园</span>+ </li>+ </ul>+ <h2 id="562n">+ <span id="5bmy">美食推荐</span>+ </h2>+</root>"+`;+exports[`EditorRuntime - Real Cases > modifyNodes - remove then add > should remove 13 paragraphs then insert a list > remove 13 paragraphs 1`] = `"<?xml version="1.0" encoding="UTF-8"?><root>diff --git a/packages/editor-runtime/src/__tests__/formatModifyNodesResult.test.ts b/packages/editor-runtime/src/__tests__/formatModifyNodesResult.test.tsindex d26d6fc0b20..241ae9aa462 100644--- a/packages/editor-runtime/src/__tests__/formatModifyNodesResult.test.ts+++ b/packages/editor-runtime/src/__tests__/formatModifyNodesResult.test.ts@@ -30,7 +30,7 @@ describe('formatModifyNodesResult', () => {expect(content).toMatchInlineSnapshot(`"Only 1/2 operations succeeded (1 modify, 1 insert requested). Failed operations were not applied:- Operation 1 (modify): node "zzzz" not found in the document- Re-read /doc.xml to get the current node ids before retrying the failed edits."+ Call getPageContent to get the current node ids before retrying the failed operations."`);});@@ -50,7 +50,5 @@ describe('formatModifyNodesResult', () => {expect(content).toContain('except those marked PARTIALLY APPLIED');expect(content).toContain('- Operation 1 (modify): PARTIALLY APPLIED');- expect(content).toContain('Re-read /doc.xml');- expect(content).not.toContain('getPageContent');});});diff --git a/packages/editor-runtime/src/__tests__/liteXMLBlockDiff.real.test.ts b/packages/editor-runtime/src/__tests__/liteXMLBlockDiff.real.test.tsdeleted file mode 100644index c6cf744de18..00000000000--- a/packages/editor-runtime/src/__tests__/liteXMLBlockDiff.real.test.ts+++ /dev/null@@ -1,322 +0,0 @@-import type { IEditor } from '@lobehub/editor';-import {- CommonPlugin,- Kernel,- ListPlugin,- LitexmlPlugin,- MarkdownPlugin,- moment,-} from '@lobehub/editor';-import { DiffAction, LITEXML_DIFFNODE_ALL_COMMAND } from '@lobehub/editor/litexml-commands';-import { $getRoot, type ElementNode, type TextNode } from 'lexical';-import { describe, expect, it } from 'vitest';--import { normalizeEditorDataDiffNodes } from '../../../../src/libs/editor/normalizeDiffNodes';-import { EditorRuntime } from '../EditorRuntime';-import { diffLiteXMLBlocks } from '../liteXMLBlockDiff';--const setup = async (markdown: string) => {- const editor = new Kernel() as unknown as IEditor;- editor.registerPlugins([CommonPlugin, MarkdownPlugin, ListPlugin, LitexmlPlugin]);- editor.initNodeEditor();- editor.setDocument('markdown', markdown);- await moment();-- const runtime = new EditorRuntime();- runtime.setEditor(editor);- runtime.setTitleHandlers(- () => {},- () => 'Title',- );-- const xml = () => editor.getDocument('litexml') as unknown as string;- const markdownOf = () => (editor.getDocument('markdown') as unknown as string).trim();-- const apply = async (edit: (xml: string) => string) => {- const original = xml();- const diff = diffLiteXMLBlocks(original, edit(original));- if (!diff.ok) throw new Error(diff.reason);- const result = await runtime.modifyNodes({ operations: diff.operations });- await moment();- return { diff, result };- };-- const selectBlock = (index: number) =>- (editor as any).getLexicalEditor().update(- () => {- const text = ($getRoot().getChildren()[index] as ElementNode).getFirstChild() as TextNode;- text.select(0, text.getTextContentSize());- },- { discrete: true },- );-- const resolve = async (action: DiffAction) => {- editor.dispatchCommand(LITEXML_DIFFNODE_ALL_COMMAND, { action });- await moment();- };-- return {- apply,- markdownOf,- selectBlock,- xml,- resolve,- runtime,- json: () => editor.getDocument('json'),- restore: async (json: Record<string, unknown>) => {- editor.setDocument('json', json);- await moment();- },- };-};--const topLevelIds = (xml: string) =>- [...xml.matchAll(/^ {2}<\w+ id="([^"]+)"/gm)].map((match) => match[1]);--describe('diffLiteXMLBlocks against a real editor', () => {- it.each(['before paragraph', '- first\n- second'])(- 'preserves accepted history while a modification is pending: %s',- async (markdown) => {- const page = await setup(markdown);- const before = page.json();- await page.apply((xml) => xml.replace(/before|second/, 'changed'));-- expect(- normalizeEditorDataDiffNodes(page.json() as unknown as Record<string, unknown>),- ).toEqual(before);- },- );-- it.each([DiffAction.Accept, DiffAction.Reject])(- 'keeps a list edit reviewable until action %s',- async (action) => {- const before = '- first\n- second\n- third';- const page = await setup(before);- const { result } = await page.apply((xml) => xml.replace('second', 'SECOND'));-- expect(result.successCount).toBe(result.totalCount);- expect(JSON.stringify(page.json())).toContain('"type":"diff"');- expect(page.markdownOf()).toBe(before.replace('second', 'SECOND'));- await page.resolve(action);- expect(JSON.stringify(page.json())).not.toContain('"type":"diff"');- expect(page.markdownOf()).toBe(- action === DiffAction.Accept ? before.replace('second', 'SECOND') : before,- );- },- );-- it.each([DiffAction.Accept, DiffAction.Reject])(- 'keeps inserted and removed lists reviewable until action %s',- async (action) => {- const page = await setup('intro\n\n- old item\n\ntail');- const before = page.markdownOf();- const { result } = await page.apply((xml) =>- xml- .replace(/<ul\b[^>]*>[\s\S]*?<\/ul>/, '')- .replace('</root>', '<ol><li>new item</li><li>next item</li></ol></root>'),- );-- expect(result.successCount).toBe(result.totalCount);- expect(JSON.stringify(page.json())).toContain('"diffType":"remove"');- expect(JSON.stringify(page.json())).toContain('"diffType":"add"');- await page.resolve(action);- expect(JSON.stringify(page.json())).not.toContain('"type":"diff"');- expect(page.markdownOf()).toBe(- action === DiffAction.Accept ? 'intro\n\ntail\n\n1. new item\n2. next item' : before,- );- },- );-- it.each([DiffAction.Accept, DiffAction.Reject])(- 'preserves nested list structure when resolving action %s',- async (action) => {- const page = await setup('- parent\n - nested\n- tail');- const before = page.markdownOf();- const { result } = await page.apply((xml) => xml.replace('nested', 'NESTED'));- expect(result.successCount).toBe(result.totalCount);- await page.resolve(action);- expect(page.markdownOf()).toBe(- action === DiffAction.Accept ? before.replace('nested', 'NESTED') : before,- );- },- );-- it.each(['beforeId', 'afterId'] as const)(- 'can reject a list item inserted using %s without an empty bullet',- async (anchor) => {- const page = await setup('- first\n- second');- const before = page.markdownOf();- const id = page.xml().match(/<li id="([^"]+)"/)![1];- const result = await page.runtime.modifyNodes({- operations: [- {- action: 'insert',- ...(anchor === 'beforeId' ? { beforeId: id } : { afterId: id }),- litexml: '<li>added</li>',- },- ],- });- expect(result.successCount).toBe(1);- expect(page.markdownOf()).toContain('- added');- const history = await setup('placeholder');- await history.restore(- normalizeEditorDataDiffNodes(page.json() as unknown as Record<string, unknown>),- );- expect(history.markdownOf()).toBe(before);- await page.resolve(DiffAction.Reject);- expect(page.markdownOf()).toBe(before);- },- );-- it.each([DiffAction.Accept, DiffAction.Reject])(- 'can review a directly targeted list item with action %s',- async (action) => {- const page = await setup('- first\n- second');- const before = page.markdownOf();- const id = page.xml().match(/<li id="([^"]+)"/)![1];- const result = await page.runtime.modifyNodes({- operations: [{ action: 'modify', litexml: `<li id="${id}">FIRST</li>` }],- });- expect(result.successCount).toBe(1);- expect(JSON.stringify(page.json())).toContain('"type":"diff"');- await page.resolve(action);- expect(page.markdownOf()).toBe(- action === DiffAction.Accept ? before.replace('first', 'FIRST') : before,- );- },- );-- it('restores the original list when a pending modification is deleted and rejected', async () => {- const page = await setup('intro\n\n- first\n- second\n\ntail');- const before = page.markdownOf();- await page.apply((xml) => xml.replace('second', 'SECOND'));- await page.apply((xml) => xml.replace(/<ul\b[^>]*>[\s\S]*?<\/ul>/, ''));- await page.resolve(DiffAction.Reject);-- expect(page.markdownOf()).toBe(before);- expect(page.json()).toMatchObject({- root: { children: [{ type: 'paragraph' }, { type: 'list' }, { type: 'paragraph' }] },- });- });- it('applies an in-place text edit as a single modify without whitespace artifacts', async () => {- const page = await setup('para one\n\npara two\n\npara three\n');- const [first, , third] = topLevelIds(page.xml());-- const { result } = await page.apply((xml) => xml.replace('para two', 'para TWO'));-- expect(result.successCount).toBe(result.totalCount);- expect(page.markdownOf()).toBe('para one\n\npara TWO\n\npara three');- expect(topLevelIds(page.xml())).toEqual(expect.arrayContaining([first, third]));- });-- it('appends new blocks at the end in order', async () => {- const page = await setup('para one\n\npara two\n');-- const { result } = await page.apply((xml) =>- xml.replace('</root>', '<h2>Next</h2><p>tail one</p><p>tail two</p></root>'),- );-- expect(result.successCount).toBe(result.totalCount);- expect(page.markdownOf()).toBe('para one\n\npara two\n\n## Next\n\ntail one\n\ntail two');- });-- it('inserts after a block that the same batch modifies', async () => {- const page = await setup('para one\n\npara two\n');-- const { result } = await page.apply((xml) =>- xml.replace(- /(<p id="[^"]+">\s*<span id="[^"]+">)para one(<\/span>\s*<\/p>)/,- '$1para ONE$2<p>between</p>',- ),- );-- expect(result.successCount).toBe(result.totalCount);- expect(page.markdownOf()).toBe('para ONE\n\nbetween\n\npara two');- });-- it('inserts after a block that the same batch removes', async () => {- const page = await setup('para one\n\npara two\n\npara three\n');-- const { result } = await page.apply((xml) =>- xml.replace(- /<p id="[^"]+">\s*<span id="[^"]+">para two<\/span>\s*<\/p>/,- '<p>replacement</p>',- ),- );-- expect(result.successCount).toBe(result.totalCount);- expect(page.markdownOf()).toBe('para one\n\nreplacement\n\npara three');- });-- it('moves a block', async () => {- const page = await setup('para one\n\npara two\n\npara three\n');-- const { result } = await page.apply((xml) => {- const blocks = [...xml.matchAll(/ {2}<p id="[^"]+">[\s\S]*?<\/p>/g)].map((match) => match[0]);- return `<root>${blocks[0]}${blocks[2]}${blocks[1]}</root>`;- });-- expect(result.successCount).toBe(result.totalCount);- expect(page.markdownOf()).toBe('para one\n\npara three\n\npara two');- });-- it('keeps the spaces between formatted runs when a paragraph is edited', async () => {- const page = await setup('**bold** *ital* tail\n');-- const { result } = await page.apply((xml) => xml.replace('tail', 'TAIL'));-- expect(result.successCount).toBe(result.totalCount);- expect(page.markdownOf()).toBe('**bold** *ital* TAIL');- });-- it('keeps the spaces between formatted runs in a newly written block', async () => {- const page = await setup('para one\n');-- const { result } = await page.apply((xml) =>- xml.replace('</root>', '<p>This is <b>bold</b> <i>ital</i> end</p></root>'),- );-- expect(result.successCount).toBe(result.totalCount);- expect(page.markdownOf()).toBe('para one\n\nThis is **bold** *ital* end');- });-- it('edits a page whose text contains unescaped angle brackets', async () => {- const page = await setup('use a<b and c>d\n\nplain\n');-- const { result } = await page.apply((xml) => xml.replace('plain', 'PLAIN'));-- expect(result.successCount).toBe(result.totalCount);- expect(page.markdownOf()).toContain('PLAIN');- });-- it('edits a paragraph that itself contains angle brackets and ampersands', async () => {- const page = await setup('AT&T says a<b and c>d tail\n');-- const { result } = await page.apply((xml) => xml.replace('tail', 'TAIL'));-- expect(result.successCount).toBe(result.totalCount);- expect(page.xml()).toContain('AT&T says a');- expect(page.xml()).toContain('<b and c>');- expect(page.xml()).toContain('d TAIL');- });-- it('edits a block that the user currently has selected', async () => {- const page = await setup('para one\n\npara two\n');- page.selectBlock(1);-- const { result } = await page.apply((xml) => xml.replace('para two', 'para TWO'));-- expect(result.successCount).toBe(result.totalCount);- expect(page.markdownOf()).toBe('para one\n\npara TWO');- });-- it('edits again while an earlier edit is still pending review', async () => {- const page = await setup('para one\n\npara two\n\npara three\n');- await page.apply((xml) => xml.replace('para one', 'para ONE'));-- const { result } = await page.apply((xml) => xml.replace('para three', 'para THREE'));-- expect(result.successCount).toBe(result.totalCount);- expect(page.markdownOf()).toBe('para ONE\n\npara two\n\npara THREE');- });-});diff --git a/packages/editor-runtime/src/__tests__/liteXMLBlockDiff.test.ts b/packages/editor-runtime/src/__tests__/liteXMLBlockDiff.test.tsdeleted file mode 100644index eb2a514e856..00000000000--- a/packages/editor-runtime/src/__tests__/liteXMLBlockDiff.test.ts+++ /dev/null@@ -1,218 +0,0 @@-import { describe, expect, it } from 'vitest';--import { diffLiteXMLBlocks } from '../liteXMLBlockDiff';--const doc = (...blocks: string[]) => `<root>${blocks.join('')}</root>`;--const ok = (original: string, edited: string) => {- const result = diffLiteXMLBlocks(original, edited);- if (!result.ok) throw new Error(`expected ok, got: ${result.reason}`);- return result;-};--const A = '<p id="a">A</p>';-const B = '<p id="b">B</p>';-const C = '<p id="c">C</p>';--describe('diffLiteXMLBlocks', () => {- it('returns no operations when only formatting whitespace differs', () => {- const pretty = `<?xml version="1.0" encoding="UTF-8"?>-<root>- <p id="a">- <span id="s1">A</span>- </p>- <hr id="h"/>-</root>`;- const compact = '<root><p id="a"><span id="s1">A</span></p><hr id="h"/></root>';-- const result = ok(pretty, compact);-- expect(result.operations).toEqual([]);- expect(result.summary).toEqual({ inserted: 0, modified: 0, removed: 0 });- });-- it('modifies a block whose content changed', () => {- const result = ok(doc(A, B, C), doc(A, '<p id="b">B2</p>', C));-- expect(result.operations).toEqual([{ action: 'modify', litexml: '<p id="b">B2</p>' }]);- expect(result.summary.modified).toBe(1);- });-- it('removes a block whose id disappeared', () => {- const result = ok(doc(A, B, C), doc(A, C));-- expect(result.operations).toEqual([{ action: 'remove', id: 'b' }]);- });-- it('inserts a new block after the preceding kept block', () => {- const result = ok(doc(A, B), doc(A, '<p>new</p>', B));-- expect(result.operations).toEqual([{ action: 'insert', afterId: 'a', litexml: '<p>new</p>' }]);- });-- it('merges consecutive new blocks into one root-wrapped insert', () => {- const result = ok(doc(A, B), doc(A, B, '<h2>T</h2>', '<p>x</p>'));-- expect(result.operations).toEqual([- { action: 'insert', afterId: 'b', litexml: '<root><h2>T</h2><p>x</p></root>' },- ]);- expect(result.summary.inserted).toBe(2);- });-- it('anchors leading new blocks before the first kept block', () => {- const result = ok(doc(A, B), doc('<p>lead</p>', A, B));-- expect(result.operations).toEqual([- { action: 'insert', beforeId: 'a', litexml: '<p>lead</p>' },- ]);- });-- it('anchors a full rewrite after the last original block, then removes the originals', () => {- const result = ok(doc(A), doc('<p>x</p>', '<p>y</p>'));-- expect(result.operations).toEqual([- { action: 'insert', afterId: 'a', litexml: '<root><p>x</p><p>y</p></root>' },- { action: 'remove', id: 'a' },- ]);- });-- it('orders operations insert, then modify, then remove, all on original ids', () => {- const result = ok(doc(A, B, C), doc('<p id="a">A2</p>', '<p>new</p>', C));-- expect(result.operations.map((operation) => operation.action)).toEqual([- 'insert',- 'modify',- 'remove',- ]);- expect(result.operations[0]).toEqual({ action: 'insert', afterId: 'a', litexml: '<p>new</p>' });- });-- it('turns a moved block into remove plus an id-free insert', () => {- const result = ok(- doc(A, B, '<p id="c"><span id="cs">C</span></p>'),- doc(A, '<p id="c"><span id="cs">C</span></p>', B),- );-- const inserts = result.operations.filter((operation) => operation.action === 'insert');- const removes = result.operations.filter((operation) => operation.action === 'remove');- expect(inserts).toHaveLength(1);- expect(removes).toHaveLength(1);- expect(JSON.stringify(inserts)).not.toContain('id=');- });-- it('treats a repeated id after its first use as a new block without ids', () => {- const result = ok(doc(A, B), doc(A, B, '<p id="b">B copy</p>'));-- expect(result.operations).toEqual([- { action: 'insert', afterId: 'b', litexml: '<p>B copy</p>' },- ]);- });-- it('treats an id missing from the original as new content', () => {- const result = ok(doc(A, B), doc(A, B, '<p id="zzzz"><span id="yyyy">stale</span></p>'));-- expect(result.operations).toEqual([- { action: 'insert', afterId: 'b', litexml: '<p><span>stale</span></p>' },- ]);- });-- it('keeps a whitespace-only span between formatted runs in the modify payload', () => {- const original = `<root>- <p id="p">- <span id="s1" bold="true">bold</span>- <span id="s2"> </span>- <span id="s3">tail</span>- </p>-</root>`;-- const result = ok(original, original.replace('tail', 'TAIL'));-- expect(result.operations).toEqual([- {- action: 'modify',- litexml:- '<p id="p"><span id="s1" bold="true">bold</span><span id="s2"><text> </text></span><span id="s3">TAIL</span></p>',- },- ]);- });-- it('keeps inline spaces between tags in newly written blocks', () => {- const result = ok(doc(A), doc(A, '<p>This is <b>bold</b> <i>ital</i> end</p>'));-- expect(result.operations).toEqual([- {- action: 'insert',- afterId: 'a',- litexml: '<p>This is <b>bold</b><text> </text><i>ital</i> end</p>',- },- ]);- });-- it('treats unescaped angle brackets inside text and code as text', () => {- const original = `<root>- <p id="p">- <span id="s1">use a</span>- <span id="s2"><b and c></span>- <codeInline id="ci">- <span id="s3"><div></span>- </codeInline>- </p>- <code id="c" lang="html"><p>hi</p>-<p>there</p></code>- <p id="q">- <span id="s4">plain</span>- </p>-</root>`;-- const result = ok(original, original.replace('plain', 'PLAIN').replace('there', 'THERE'));-- expect(result.operations).toEqual([- {- action: 'modify',- litexml: '<code id="c" lang="html"><p>hi</p>\n<p>THERE</p></code>',- },- { action: 'modify', litexml: '<p id="q"><span id="s4">PLAIN</span></p>' },- ]);- });-- it('strips ids from tags only, not from text that mentions id=', () => {- const result = ok(doc(A), doc(A, '<p id="zz"><span id="yy">say id="x"</span></p>'));-- expect(result.operations).toEqual([- { action: 'insert', afterId: 'a', litexml: '<p><span>say id="x"</span></p>' },- ]);- });-- it('rejects content written after </root>', () => {- const result = diffLiteXMLBlocks(doc(A, B), `${doc(A, B)}\n<p>three</p>\n`);-- expect(result.ok).toBe(false);- if (!result.ok) expect(result.reason).toMatch(/after <\/root>/);- });-- it('rejects edits to an empty page and points at the initPage tool', () => {- const result = diffLiteXMLBlocks('<root></root>', doc('<p>x</p>'));-- expect(result.ok).toBe(false);- if (!result.ok) expect(result.reason).toMatch(/initPage/);- });-- it('rejects unbalanced tags', () => {- const result = diffLiteXMLBlocks(doc(A, B), '<root><p id="a">A</root>');-- expect(result.ok).toBe(false);- });-- it('rejects a document without a root element', () => {- const result = diffLiteXMLBlocks(doc(A, B), `${A}${B}`);-- expect(result.ok).toBe(false);- });-- it('rejects an edit that strips most ids from a similar-length document', () => {- const result = diffLiteXMLBlocks(doc(A, B, C), doc('<p>A</p>', '<p>B</p>', '<p>C2</p>'));-- expect(result.ok).toBe(false);- if (!result.ok) expect(result.reason).toMatch(/id/);- });-});diff --git a/packages/editor-runtime/src/__tests__/selectionLiteXML.real.test.ts b/packages/editor-runtime/src/__tests__/selectionLiteXML.real.test.tsdeleted file mode 100644index 00ea8b51c48..00000000000--- a/packages/editor-runtime/src/__tests__/selectionLiteXML.real.test.ts+++ /dev/null@@ -1,70 +0,0 @@-import type { IEditor } from '@lobehub/editor';-import {- CommonPlugin,- Kernel,- ListPlugin,- LitexmlPlugin,- MarkdownPlugin,- moment,-} from '@lobehub/editor';-import { $getRoot, type ElementNode, type TextNode } from 'lexical';-import { describe, expect, it } from 'vitest';--import { parseLiteXMLBlocks } from '../liteXMLBlockDiff';-import { getSelectedBlocksLiteXML } from '../selectionLiteXML';--const setup = async (markdown: string) => {- const editor = new Kernel() as unknown as IEditor;- editor.registerPlugins([CommonPlugin, MarkdownPlugin, ListPlugin, LitexmlPlugin]);- editor.initNodeEditor();- editor.setDocument('markdown', markdown);- await moment();-- const lexical = (editor as any).getLexicalEditor();- const textOf = (index: number) =>- ($getRoot().getChildren()[index] as ElementNode).getFirstChild() as TextNode;- const blocks = () => {- const parsed = parseLiteXMLBlocks(editor.getDocument('litexml') as unknown as string);- if (typeof parsed === 'string') throw new Error(parsed);- return parsed;- };-- return { blocks, editor, lexical, textOf };-};--describe('getSelectedBlocksLiteXML', () => {- it('returns the whole block around a partial selection with the page ids', async () => {- const page = await setup('para one\n\npara two has more words\n');- page.lexical.update(() => page.textOf(1).select(5, 8), { discrete: true });-- const xml = getSelectedBlocksLiteXML(page.editor);-- const block = page.blocks()[1];- expect(xml).toContain(`id="${block.id}"`);- expect(xml?.replaceAll(/\s+/g, '')).toBe(`<root>${block.xml}</root>`.replaceAll(/\s+/g, ''));- });-- it('returns every block a selection spans, in order', async () => {- const page = await setup('para one\n\npara two\n\npara three\n');- page.lexical.update(- () => {- const selection = page.textOf(0).select(2, 2);- selection.focus.set(page.textOf(1).getKey(), 3, 'text');- },- { discrete: true },- );-- const xml = getSelectedBlocksLiteXML(page.editor) ?? '';-- const [first, second, third] = page.blocks();- expect(xml.indexOf(`id="${first.id}"`)).toBeGreaterThan(-1);- expect(xml.indexOf(`id="${second.id}"`)).toBeGreaterThan(xml.indexOf(`id="${first.id}"`));- expect(xml).not.toContain(`id="${third.id}"`);- });-- it('returns nothing without a selection', async () => {- const page = await setup('para one\n');-- expect(getSelectedBlocksLiteXML(page.editor)).toBeUndefined();- });-});diff --git a/packages/editor-runtime/src/formatModifyNodesResult.ts b/packages/editor-runtime/src/formatModifyNodesResult.tsindex 9b1d3be9f74..7a87f2d6cc0 100644--- a/packages/editor-runtime/src/formatModifyNodesResult.ts+++ b/packages/editor-runtime/src/formatModifyNodesResult.ts@@ -1,7 +1,7 @@import type { ModifyNodesRuntimeResult } from './types';/**- * Tool message for the page-agent edits applied from /doc.xml. Failed operations are listed+ * Tool message for a page-agent `modifyNodes` call. Failed operations are listed* with their reason so the model retries them instead of assuming they applied;* one that failed after part of it was written is flagged so a retry does not* duplicate the applied part.@@ -44,7 +44,7 @@ export const formatModifyNodesResult = ({}`,...failures,hasPartial- ? 'Re-read /doc.xml to get the current node ids and content before retrying; re-send only the parts of a partially applied edit that are still missing.'- : 'Re-read /doc.xml to get the current node ids before retrying the failed edits.',+ ? 'Call getPageContent to get the current node ids and content before retrying; re-send only the parts of a partially applied operation that are still missing.'+ : 'Call getPageContent to get the current node ids before retrying the failed operations.',].join('\n');};diff --git a/packages/editor-runtime/src/index.ts b/packages/editor-runtime/src/index.tsindex 06a1a139c4f..907542e5a15 100644--- a/packages/editor-runtime/src/index.ts+++ b/packages/editor-runtime/src/index.ts@@ -1,6 +1,4 @@export { EditorRuntime, type LiteXMLBatchOperation } from './EditorRuntime';export { formatModifyNodesResult } from './formatModifyNodesResult';-export * from './liteXMLBlockDiff';export * from './liteXMLEditPlan';-export * from './selectionLiteXML';export * from './types';diff --git a/packages/editor-runtime/src/liteXMLBlockDiff.ts b/packages/editor-runtime/src/liteXMLBlockDiff.tsdeleted file mode 100644index b90168d65a8..00000000000--- a/packages/editor-runtime/src/liteXMLBlockDiff.ts+++ /dev/null@@ -1,310 +0,0 @@-import type { ModifyOperation } from './types';--type Token =- | { kind: 'close'; raw: string; tag: string }- | { kind: 'open' | 'self'; raw: string; tag: string }- | { kind: 'text'; raw: string; verbatim: boolean };--export interface LiteXMLBlock {- id?: string;- tag: string;- text: string;- xml: string;-}--export interface LiteXMLBlockDiffSummary {- inserted: number;- modified: number;- removed: number;-}--export type LiteXMLBlockDiffResult =- | { ok: true; operations: ModifyOperation[]; summary: LiteXMLBlockDiffSummary }- | { ok: false; reason: string };--const TAG = /<(\/?)([a-z][\w-]*)(?:\s+[\w:-]+(?:="[^"]*")?)*\s*(\/?)>/iy;-const ID_ATTRIBUTE = /\bid="([^"]+)"/;-// The LiteXML exporter writes text inside these elements without escaping `<`.-const VERBATIM_TAGS = new Set(['code', 'span']);--const tokenize = (litexml: string): Token[] => {- const tokens: Token[] = [];- let text = '';- let i = 0;-- const flushText = () => {- if (text) tokens.push({ kind: 'text', raw: text, verbatim: false });- text = '';- };-- while (i < litexml.length) {- if (litexml[i] !== '<') {- text += litexml[i];- i += 1;- continue;- }- if (litexml.startsWith('<?', i) || litexml.startsWith('<!--', i)) {- const close = litexml.startsWith('<?', i) ? '?>' : '-->';- const end = litexml.indexOf(close, i);- i = end === -1 ? litexml.length : end + close.length;- continue;- }-- TAG.lastIndex = i;- const match = TAG.exec(litexml);- if (!match) {- text += '<';- i += 1;- continue;- }-- flushText();- const [raw, closing, tag, selfClosing] = match;- i += raw.length;- if (closing) {- tokens.push({ kind: 'close', raw, tag });- continue;- }- if (selfClosing) {- tokens.push({ kind: 'self', raw, tag });- continue;- }- tokens.push({ kind: 'open', raw, tag });-- if (VERBATIM_TAGS.has(tag)) {- const closeTag = `</${tag}>`;- const end = litexml.indexOf(closeTag, i);- if (end === -1) continue;- if (end > i) tokens.push({ kind: 'text', raw: litexml.slice(i, end), verbatim: true });- tokens.push({ kind: 'close', raw: closeTag, tag });- i = end + closeTag.length;- }- }- flushText();-- return tokens;-};--const isLayoutWhitespace = (token: Token) =>- token.kind === 'text' && !token.verbatim && /^\s*$/.test(token.raw) && token.raw.includes('\n');--const serialize = (tokens: Token[]) =>- tokens- .filter((token) => !isLayoutWhitespace(token))- .map((token) => token.raw)- .join('')- .trim();--const escapeText = (text: string) =>- text- .replaceAll(/&(?!#?\w+;)/g, '&')- .replaceAll('<', '<')- .replaceAll('>', '>');--// The editor imports LiteXML with DOMParser (so text must be escaped) and drops-// whitespace-only text nodes unless they sit in a <text> element.-const toPayload = (tokens: Token[], { stripIds = false } = {}) =>- tokens- .filter((token) => !isLayoutWhitespace(token))- .map((token) => {- if (token.kind === 'text') {- const text = escapeText(token.raw);- return /^\s+$/.test(token.raw) ? `<text>${text}</text>` : text;- }- return stripIds ? token.raw.replaceAll(/\s+id="[^"]*"/g, '') : token.raw;- })- .join('')- .trim();--const blockText = (tokens: Token[]) =>- tokens- .filter((token) => token.kind === 'text')- .map((token) => token.raw)- .join('')- .replaceAll(/\s+/g, ' ')- .trim();--interface ParsedBlock extends LiteXMLBlock {- tokens: Token[];-}--const parseBlocks = (litexml: string): ParsedBlock[] | string => {- const tokens = tokenize(litexml);- const rootIndex = tokens.findIndex(- (token) => token.kind !== 'text' && token.kind !== 'close' && token.tag === 'root',- );- if (rootIndex === -1) return 'missing <root> element';- if (tokens.slice(0, rootIndex).some((token) => token.raw.trim())) {- return 'content before <root>';- }- if (tokens[rootIndex].kind === 'self') {- return tokens.slice(rootIndex + 1).some((token) => token.raw.trim())- ? 'content after </root>'- : [];- }-- const blocks: ParsedBlock[] = [];- const stack: string[] = [];- let current: Token[] = [];-- for (let index = rootIndex + 1; index < tokens.length; index += 1) {- const token = tokens[index];-- if (stack.length === 0) {- if (token.kind === 'text') {- if (token.raw.trim()) return 'text outside a block under <root>';- continue;- }- if (token.kind === 'close') {- if (token.tag !== 'root') return `unexpected </${token.tag}> under <root>`;- if (tokens.slice(index + 1).some((rest) => rest.raw.trim())) {- return 'content after </root>; put new blocks inside <root>';- }- return blocks;- }- }-- current.push(token);- if (token.kind === 'open') stack.push(token.tag);- if (token.kind === 'close') {- const open = stack.pop();- if (open !== token.tag) return `</${token.tag}> does not close <${open}>`;- }-- if (stack.length === 0) {- const head = current[0] as Extract<Token, { tag: string }>;- blocks.push({- id: head.raw.match(ID_ATTRIBUTE)?.[1],- tag: head.tag,- text: blockText(current),- tokens: current,- xml: serialize(current),- });- current = [];- }- }-- return stack.length > 0 ? `<${stack.at(-1)}> is never closed` : 'missing </root>';-};--export const parseLiteXMLBlocks = (litexml: string): LiteXMLBlock[] | string => {- const blocks = parseBlocks(litexml);- return typeof blocks === 'string'- ? blocks- : blocks.map(({ id, tag, text, xml }) => ({ id, tag, text, xml }));-};--const longestCommonSubsequence = (a: string[], b: string[]): Set<string> => {- const common = new Set<string>();-- let start = 0;- while (start < a.length && start < b.length && a[start] === b[start]) {- common.add(a[start]);- start += 1;- }- let endA = a.length;- let endB = b.length;- while (endA > start && endB > start && a[endA - 1] === b[endB - 1]) {- common.add(a[endA - 1]);- endA -= 1;- endB -= 1;- }-- const midA = a.slice(start, endA);- const midB = b.slice(start, endB);- const lengths = Array.from({ length: midA.length + 1 }, () => new Int32Array(midB.length + 1));- for (let i = midA.length - 1; i >= 0; i -= 1) {- for (let j = midB.length - 1; j >= 0; j -= 1) {- lengths[i][j] =- midA[i] === midB[j]- ? lengths[i + 1][j + 1] + 1- : Math.max(lengths[i + 1][j], lengths[i][j + 1]);- }- }-- let i = 0;- let j = 0;- while (i < midA.length && j < midB.length) {- if (midA[i] === midB[j]) {- common.add(midA[i]);- i += 1;- j += 1;- } else if (lengths[i + 1][j] >= lengths[i][j + 1]) i += 1;- else j += 1;- }- return common;-};--export const diffLiteXMLBlocks = (original: string, edited: string): LiteXMLBlockDiffResult => {- const before = parseBlocks(original);- if (typeof before === 'string') return { ok: false, reason: `original document: ${before}` };- if (before.length === 0) {- return { ok: false, reason: 'the page is empty; call the initPage tool with Markdown instead' };- }- const after = parseBlocks(edited);- if (typeof after === 'string') return { ok: false, reason: after };-- const originalIds = before.flatMap((block) => (block.id ? [block.id] : []));- const originalById = new Map(before.map((block) => [block.id, block]));-- const editedIds = new Set(after.map((block) => block.id));- const surviving = originalIds.filter((id) => editedIds.has(id)).length;- const similarLength =- Math.abs(after.length - before.length) <= Math.max(2, Math.ceil(before.length * 0.2));- if (originalIds.length >= 2 && similarLength && surviving / originalIds.length < 0.5) {- return {- ok: false,- reason:- 'most block ids were dropped. Keep the id attributes from /doc.xml when editing existing blocks, or call the initPage tool to replace the whole page',- };- }-- const seen = new Set<string>();- const candidates = after.map((block) => {- if (!block.id || !originalById.has(block.id) || seen.has(block.id)) return undefined;- seen.add(block.id);- return block.id;- });- const kept = longestCommonSubsequence(- originalIds,- candidates.filter((id): id is string => !!id),- );-- const inserts: ModifyOperation[] = [];- const modifies: ModifyOperation[] = [];- let pending: string[] = [];- let lastKeptId: string | undefined;- let inserted = 0;-- const flush = (anchor: { afterId: string } | { beforeId: string }) => {- if (pending.length === 0) return;- inserted += pending.length;- const litexml = pending.length === 1 ? pending[0] : `<root>${pending.join('')}</root>`;- inserts.push({ action: 'insert', ...anchor, litexml });- pending = [];- };-- after.forEach((block, index) => {- const id = candidates[index];- if (!id || !kept.has(id)) {- pending.push(toPayload(block.tokens, { stripIds: true }));- return;- }- flush(lastKeptId ? { afterId: lastKeptId } : { beforeId: id });- lastKeptId = id;- if (block.xml !== originalById.get(id)!.xml) {- modifies.push({ action: 'modify', litexml: toPayload(block.tokens) });- }- });- flush({ afterId: lastKeptId ?? originalIds.at(-1)! });-- const removes: ModifyOperation[] = originalIds- .filter((id) => !kept.has(id))- .map((id) => ({ action: 'remove', id }));-- return {- ok: true,- operations: [...inserts, ...modifies, ...removes],- summary: { inserted, modified: modifies.length, removed: removes.length },- };-};diff --git a/packages/editor-runtime/src/selectionLiteXML.ts b/packages/editor-runtime/src/selectionLiteXML.tsdeleted file mode 100644index 74bbb87f501..00000000000--- a/packages/editor-runtime/src/selectionLiteXML.ts+++ /dev/null@@ -1,35 +0,0 @@-import type { IEditor } from '@lobehub/editor';-import { $getSelection, $isRangeSelection, type LexicalEditor, type LexicalNode } from 'lexical';--interface LiteXMLDataSource {- nodesToXML?: (node: LexicalNode, lines: string[], indent?: number) => void;-}--interface InspectableEditor {- dataTypeMap?: Map<string, unknown> | Record<string, unknown>;- getLexicalEditor?: () => LexicalEditor | null;-}--// getSelectionDocument('litexml') re-parses the selected nodes into a fresh-// state, so its ids never match the page's. Serializing the live top-level-// blocks with the page's own LiteXML writer keeps the ids the agent sees in-// /doc.xml.-export const getSelectedBlocksLiteXML = (editor: IEditor): string | undefined => {- const { dataTypeMap, getLexicalEditor } = editor as InspectableEditor;- const dataSource = (- dataTypeMap instanceof Map ? dataTypeMap.get('litexml') : dataTypeMap?.litexml- ) as LiteXMLDataSource | undefined;- const lexical = getLexicalEditor?.call(editor);- if (!lexical || !dataSource?.nodesToXML) return;-- return lexical.getEditorState().read(() => {- const selection = $getSelection();- if (!$isRangeSelection(selection) || selection.isCollapsed()) return;-- const blocks = new Set(selection.getNodes().map((node) => node.getTopLevelElement() ?? node));- const lines: string[] = [];- for (const block of blocks) dataSource.nodesToXML!.call(dataSource, block, lines, 1);-- return lines.length > 0 ? `<root>\n${lines.join('\n')}\n</root>` : undefined;- });-};diff --git a/packages/locales/src/default/plugin.ts b/packages/locales/src/default/plugin.tsindex b8b0a96d217..d5666adf5b5 100644--- a/packages/locales/src/default/plugin.ts+++ b/packages/locales/src/default/plugin.ts@@ -418,7 +418,6 @@ export default {'builtins.lobe-notebook.apiName.getDocument': 'Get document','builtins.lobe-notebook.apiName.updateDocument': 'Update document','builtins.lobe-notebook.title': 'Notebook',- 'builtins.lobe-page-agent.apiName.bash': 'Work on page','builtins.lobe-page-agent.apiName.batchUpdate': 'Batch update nodes','builtins.lobe-page-agent.apiName.compareSnapshots': 'Compare snapshots','builtins.lobe-page-agent.apiName.convertToList': 'Convert to list',diff --git a/packages/mecha/src/contextEngineering/buildMessagesEngineParams.ts b/packages/mecha/src/contextEngineering/buildMessagesEngineParams.tsindex db9547582da..f49c42057d9 100644--- a/packages/mecha/src/contextEngineering/buildMessagesEngineParams.ts+++ b/packages/mecha/src/contextEngineering/buildMessagesEngineParams.ts@@ -92,6 +92,7 @@ export const buildMessagesEngineParams = (snapshot: ContextSnapshot): MessagesEnagentManagementContext: step?.agentManagementContext,groupAgentBuilderContext: step?.groupAgentBuilderContext,onboardingContext: step?.onboardingContext,+ pageContentContext: step?.pageContentContext,planTodo: step?.planTodo,workspaceContext: step?.workspaceContext,}),diff --git a/packages/mecha/src/contextEngineering/types.ts b/packages/mecha/src/contextEngineering/types.tsindex 9811ef5d653..5dd51e28760 100644--- a/packages/mecha/src/contextEngineering/types.ts+++ b/packages/mecha/src/contextEngineering/types.ts@@ -20,7 +20,7 @@ import type {UserMemoryConfig,WorkspaceContext,} from '@lobechat/context-engine';-import type { AgentIdentityContext } from '@lobechat/prompts';+import type { AgentIdentityContext, PageContentContext } from '@lobechat/prompts';import type {ExpertiseContextSnapshot,RuntimeAdditionalContextFragment,@@ -132,6 +132,7 @@ export interface ContextStepSnapshot {agentManagementContext?: AgentManagementContext;groupAgentBuilderContext?: GroupAgentBuilderContext;onboardingContext?: OnboardingContext;+ pageContentContext?: PageContentContext;planTodo?: PlanTodoConfig;topicReferences?: TopicReferenceItem[];workspaceContext?: WorkspaceContext;diff --git a/packages/prompts/src/agents/contextSelectionContext.ts b/packages/prompts/src/agents/contextSelectionContext.tsindex c582d77c521..a5f1d7c0eca 100644--- a/packages/prompts/src/agents/contextSelectionContext.ts+++ b/packages/prompts/src/agents/contextSelectionContext.ts@@ -1,6 +1,6 @@import type { ContextSelection } from '@lobechat/types';-import { escapeXmlAttr, escapeXmlContent } from '../prompts/search/xmlEscape';+import { escapeXmlAttr } from '../prompts/search/xmlEscape';const formatLineRange = (selection: ContextSelection): string => {const range = selection.lineRange;@@ -27,14 +27,7 @@ const formatSelectionAttributes = (selection: ContextSelection): string => {};const getSelectionBody = (selection: ContextSelection): string => {- if (selection.source === 'page' && selection.xml) {- if (!selection.content || selection.content === selection.xml) return selection.xml;-- return `<selected_text>${escapeXmlContent(selection.content)}</selected_text>-<containing_blocks>-${selection.xml}-</containing_blocks>`;- }+ if (selection.source === 'page') return selection.xml || selection.content;return selection.content;};diff --git a/packages/types/src/stepContext.ts b/packages/types/src/stepContext.tsindex 03e1ff51be2..8ed8ca38430 100644--- a/packages/types/src/stepContext.ts+++ b/packages/types/src/stepContext.ts@@ -44,6 +44,18 @@ export interface StepActivatedSkill {name: string;}+/**+ * Page Editor context for each step+ * Contains the latest XML structure fetched at each step+ */+export interface StepPageEditorContext {+ /**+ * Current XML structure of the page+ * Fetched at the beginning of each step to get latest state+ */+ xml: string;+}+/*** Initial Page Editor context* Stored at operation initialization and remains constant@@ -168,6 +180,11 @@ export interface RuntimeStepContext {* so the queued messages can be sent as a new operation.*/hasQueuedMessages?: boolean;+ /**+ * Page Editor context for current step+ * Contains the latest XML structure fetched at each step+ */+ stepPageEditor?: StepPageEditorContext;/*** Current todo list state* Computed from the latest lobe-agent tool message in the conversation@@ -232,6 +249,11 @@ export interface RuntimeInitialContext {* supervisor and can delegate to the mentioned agents via callAgent.*/mentionedAgents?: RuntimeMentionedAgent[];+ /**+ * Initial Page Editor context+ * Contains markdown content and metadata captured at operation start+ */+ pageEditor?: InitialPageEditorContext;/*** Skills explicitly selected by the user for the current request* This is ephemeral runtime context and is not persisted to chat historydiff --git a/pnpm-workspace.yaml b/pnpm-workspace.yamlindex acd4575db65..fd0656b89bf 100644--- a/pnpm-workspace.yaml+++ b/pnpm-workspace.yaml@@ -48,7 +48,6 @@ childConcurrency: 1allowBuilds:'@google/genai': true'@lobehub/editor': true- '@mongodb-js/zstd': false'@sentry/cli': true'@vercel/speed-insights': truecore-js: false@@ -56,7 +55,6 @@ allowBuilds:es5-ext: falseesbuild: falseffmpeg-static: true- node-liblzma: falseprotobufjs: falsesharp: falseunrs-resolver: falsediff --git a/src/features/ChatInput/utils/contextSelections.test.ts b/src/features/ChatInput/utils/contextSelections.test.tsindex 9934723be54..98ee74ba5d2 100644--- a/src/features/ChatInput/utils/contextSelections.test.ts+++ b/src/features/ChatInput/utils/contextSelections.test.ts@@ -3,16 +3,6 @@ import { describe, expect, it } from 'vitest';import { buildMessageContextSelections } from './contextSelections';describe('buildMessageContextSelections', () => {- it('preserves exact selected text separately from its block XML and shortened preview', () => {- const content = ' a<b\n and c>d ';- const xml = '<p id="ab12">Before a<b and c>d after</p>';- const result = buildMessageContextSelections([- { content, xml, preview: 'a and c>d', id: 'sel-1', pageId: 'page-1', type: 'text' },- ]);-- expect(result.contextSelections[0]).toMatchObject({ content, xml });- expect(result.pageSelections[0]).toMatchObject({ content, xml });- });it('derives generic and legacy selections for page context', () => {const result = buildMessageContextSelections([{diff --git a/src/features/ChatInput/utils/contextSelections.ts b/src/features/ChatInput/utils/contextSelections.tsindex 91f0002c4bf..fea3c6ac62f 100644--- a/src/features/ChatInput/utils/contextSelections.ts+++ b/src/features/ChatInput/utils/contextSelections.ts@@ -9,7 +9,7 @@ const toPageSelection = (context: ChatContextContent): PageSelection | undefinedif (!context.pageId) return;return {- content: context.xml ? context.content : context.preview || context.content,+ content: context.preview || context.content,format: context.format,id: context.id,pageId: context.pageId,@@ -38,7 +38,7 @@ const toContextSelection = (context: ChatContextContent): ContextSelection => {if (context.pageId) {return {- content: context.xml ? context.content : context.preview || context.content,+ content: context.preview || context.content,format: context.format,id: context.id,lineRange: context.lineRange,diff --git a/src/features/Conversation/Messages/AssistantGroup/constants.ts b/src/features/Conversation/Messages/AssistantGroup/constants.tsindex 28d7ee5a2ab..a8d5fb4cf53 100644--- a/src/features/Conversation/Messages/AssistantGroup/constants.ts+++ b/src/features/Conversation/Messages/AssistantGroup/constants.ts@@ -161,7 +161,6 @@ export const TOOL_API_DISPLAY_NAMES: Record<string, string> = {updateAgent: 'workflow.toolDisplayName.updateAgent',// Page agent- bash: 'workflow.toolDisplayName.runCommand',editTitle: 'workflow.toolDisplayName.editTitle',getPageContent: 'workflow.toolDisplayName.getPageContent',initPage: 'workflow.toolDisplayName.initPage',diff --git a/src/features/Conversation/store/slices/data/reducer.ts b/src/features/Conversation/store/slices/data/reducer.tsindex 8c7721cd58e..ea696382c94 100644--- a/src/features/Conversation/store/slices/data/reducer.ts+++ b/src/features/Conversation/store/slices/data/reducer.ts@@ -183,7 +183,6 @@ export const messagesReducer = (return produce(state, (draft) => {draft[index].plugin = merge(draft[index].plugin, value);- if (value.error !== undefined) draft[index].pluginError = value.error;draft[index].updatedAt = Date.now();});}diff --git a/src/features/DevPanel/RenderGallery/fixtures/lobe-page-agent.ts b/src/features/DevPanel/RenderGallery/fixtures/lobe-page-agent.tsindex f5e780f1e7e..76d3b2310a7 100644--- a/src/features/DevPanel/RenderGallery/fixtures/lobe-page-agent.ts+++ b/src/features/DevPanel/RenderGallery/fixtures/lobe-page-agent.ts@@ -9,10 +9,6 @@ export default defineFixtures({title: 'Page Agent',},apiList: [- {- description: 'Run a shell command against the current page.',- name: 'bash',- },{description: 'Initialize a new document with markdown content.',name: 'initPage',@@ -35,15 +31,6 @@ export default defineFixtures({},],fixtures: {- bash: single({- args: { command: "sed -i 's/Draft/Final/' /doc.xml" },- content: "/doc.xml: 1 modified, 0 inserted, 0 removed; changes await the user's review.",- pluginState: {- changed: true,- exitCode: 0,- success: true,- },- }),initPage: single({args: {markdown:diff --git a/src/features/PageEditor/EditorCanvas/useAskCopilotItem.tsx b/src/features/PageEditor/EditorCanvas/useAskCopilotItem.tsxindex ac964e5baba..0e3801e6520 100644--- a/src/features/PageEditor/EditorCanvas/useAskCopilotItem.tsx+++ b/src/features/PageEditor/EditorCanvas/useAskCopilotItem.tsx@@ -1,7 +1,6 @@'use client';import { DEFAULT_INBOX_AVATAR } from '@lobechat/const';-import { getSelectedBlocksLiteXML } from '@lobechat/editor-runtime';import { nanoid } from '@lobechat/utils';import { type IEditor } from '@lobehub/editor';import { HIDE_TOOLBAR_COMMAND } from '@lobehub/editor';@@ -60,12 +59,9 @@ export const useAskCopilotItem = (paddingInline={12}variant="borderless"onClick={() => {- const xml =- getSelectedBlocksLiteXML(editor) ||- (editor.getSelectionDocument?.('litexml') as string) ||- '';+ const xml = (editor.getSelectionDocument?.('litexml') as string) || '';const plainText = (editor.getSelectionDocument?.('text') as string) || '';- const content = plainText || xml;+ const content = xml.trim() || plainText.trim();if (!content) return;@@ -87,7 +83,6 @@ export const useAskCopilotItem = (preview,title: 'Selection',type: 'text',- xml,},});diff --git a/src/libs/editor/normalizeDiffNodes.test.ts b/src/libs/editor/normalizeDiffNodes.test.tsindex 5a4356e271d..feaba65ed3f 100644--- a/src/libs/editor/normalizeDiffNodes.test.ts+++ b/src/libs/editor/normalizeDiffNodes.test.ts@@ -101,6 +101,10 @@ describe('normalizeEditorDataDiffNodes', () => {children: [{ text: 'removed item', type: 'text' }],type: 'listitem',},+ {+ children: [],+ type: 'listitem',+ },],type: 'list',},diff --git a/src/libs/editor/normalizeDiffNodes.ts b/src/libs/editor/normalizeDiffNodes.tsindex a51b2c70cae..bcc05d04241 100644--- a/src/libs/editor/normalizeDiffNodes.ts+++ b/src/libs/editor/normalizeDiffNodes.ts@@ -33,10 +33,6 @@ const normalizeChildren = (children: unknown[]): unknown[] =>const normalizeFirstChild = (node: SerializedDiffNodeLike): NormalizedNode => {const [origin] = getChildren(node);- if (isRecord(origin) && origin.type === 'diff-content') {- return normalizeChildren(getChildren(origin));- }-return origin === undefined ? REMOVED_NODE : normalizeNode(origin);};@@ -79,13 +75,6 @@ const normalizeNode = (value: unknown): NormalizedNode => {if (isDiffNode(value)) return normalizeDiffNodeOrigin(value);- if (- value.type === 'listitem' &&- getChildren(value).some((child) => isDiffNode(child) && child.diffType === 'listItemAdd')- ) {- return REMOVED_NODE;- }-const normalized: Record<string, unknown> = {};for (const [key, child] of Object.entries(value)) {diff --git a/src/libs/next/config/define-config.ts b/src/libs/next/config/define-config.tsindex d13c5164c9d..064e83d2bbe 100644--- a/src/libs/next/config/define-config.ts+++ b/src/libs/next/config/define-config.ts@@ -364,7 +364,6 @@ export function defineConfig(config: CustomNextConfig) {serverExternalPackages: config.serverExternalPackages ?? ['pdfkit','@lobehub/editor',- 'just-bash','discord.js','ffmpeg-static','pdfjs-dist',diff --git a/src/store/chat/slices/agentRun/actions/__tests__/streamingExecutor.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/streamingExecutor.test.tsindex 8771f389e7d..ed0198684fd 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/streamingExecutor.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/streamingExecutor.test.ts@@ -1168,7 +1168,11 @@ describe('StreamingExecutor actions', () => {// Mock internal_createAgentState to include initialContextconst mockInitialContext = {- selectedSkills: [{ identifier: 'user_memory', name: 'User Memory' }],+ pageEditor: {+ markdown: '# Test Document',+ xml: '<root><h1>Test</h1></root>',+ metadata: { title: 'Test Doc', charCount: 15, lineCount: 1 },+ },};const originalCreateAgentState = result.current.internal_createAgentState;@@ -1245,7 +1249,11 @@ describe('StreamingExecutor actions', () => {});const mockInitialContext = {- selectedTools: [{ identifier: 'lobe-notebook', name: 'Notebook' }],+ pageEditor: {+ markdown: '# Preserved Context',+ xml: '<doc>preserved</doc>',+ metadata: { title: 'Preserved', charCount: 20, lineCount: 1 },+ },};const originalCreateAgentState = result.current.internal_createAgentState;@@ -1279,7 +1287,7 @@ describe('StreamingExecutor actions', () => {streamSpy.mockRestore();});- it('should not put the page document into initialContext in page scope', () => {+ it('should merge provided initialContext with runtime page editor context', () => {act(() => {useChatStore.setState({ executeClientAgent: realExecAgentRuntime });});@@ -1307,7 +1315,11 @@ describe('StreamingExecutor actions', () => {}),} as any);vi.spyOn(pageAgentRuntime, 'isReady').mockReturnValue(true);- const pageContextSpy = vi.spyOn(pageAgentRuntime, 'getPageContentContext');+ vi.spyOn(pageAgentRuntime, 'getPageContentContext').mockReturnValue({+ markdown: '# Test Document',+ xml: '<root><h1>Test</h1></root>',+ metadata: { title: 'Test Doc', charCount: 15, lineCount: 1 },+ });const { operationId } = result.current.startOperation({context: {agentId: TEST_IDS.SESSION_ID,@@ -1333,10 +1345,14 @@ describe('StreamingExecutor actions', () => {});expect(context.initialContext).toEqual({+ pageEditor: {+ markdown: '# Test Document',+ xml: '<root><h1>Test</h1></root>',+ metadata: { title: 'Test Doc', charCount: 15, lineCount: 1 },+ },selectedSkills: [{ identifier: 'user_memory', name: 'User Memory' }],selectedTools: [{ identifier: 'lobe-notebook', name: 'Notebook' }],});- expect(pageContextSpy).not.toHaveBeenCalled();});it('should resolve desktop client tool manifests for the local execution environment', () => {@@ -1383,6 +1399,55 @@ describe('StreamingExecutor actions', () => {expect(localSystem?.systemRole).toContain('Image files are uploaded as visual tool results');});+ it('should not inject page editor context outside page scope', () => {+ act(() => {+ useChatStore.setState({ executeClientAgent: realExecAgentRuntime });+ });++ const { result } = renderHook(() => useChatStore());+ const userMessage = {+ id: TEST_IDS.USER_MESSAGE_ID,+ role: 'user',+ content: TEST_CONTENT.USER_MESSAGE,+ sessionId: TEST_IDS.SESSION_ID,+ topicId: TEST_IDS.TOPIC_ID,+ } as UIChatMessage;++ vi.spyOn(agentConfigResolver, 'resolveAgentConfig').mockReturnValue({+ agentConfig: createMockAgentConfig(),+ chatConfig: createMockChatConfig(),+ isBuiltinAgent: false,+ plugins: ['lobe-page-agent'],+ });+ vi.spyOn(toolEngineering, 'createAgentToolsEngine').mockReturnValue({+ generateToolsDetailed: vi.fn().mockReturnValue({+ enabledManifests: [],+ enabledToolIds: ['lobe-page-agent'],+ tools: [],+ }),+ } as any);+ const pageContextSpy = vi.spyOn(pageAgentRuntime, 'getPageContentContext');+ const { operationId } = result.current.startOperation({+ context: {+ agentId: TEST_IDS.SESSION_ID,+ scope: 'main',+ topicId: TEST_IDS.TOPIC_ID,+ },+ type: 'execAgentRuntime',+ });++ const { context } = result.current.internal_createAgentState({+ messages: [userMessage],+ parentMessageId: userMessage.id,+ agentId: TEST_IDS.SESSION_ID,+ topicId: TEST_IDS.TOPIC_ID,+ operationId,+ });++ expect(context.initialContext?.pageEditor).toBeUndefined();+ expect(pageContextSpy).not.toHaveBeenCalled();+ });+it('should merge selectedTools into generated tools when provided', () => {act(() => {useChatStore.setState({ executeClientAgent: realExecAgentRuntime });diff --git a/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts b/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.tsindex f2a447691d0..d92e42f25e7 100644--- a/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts+++ b/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts@@ -386,8 +386,36 @@ export class StreamingExecutorActionImpl {},};+ // Build initialContext for page editor if lobe-page-agent is enabledlet runtimeInitialContext: RuntimeInitialContext | undefined;+ if (scope === 'page' && enabledToolIds.includes(PageAgentIdentifier)) {+ try {+ // Get page content context from page agent runtime+ const pageContentContext = pageAgentRuntime.getPageContentContext('both');++ runtimeInitialContext = {+ pageEditor: {+ markdown: pageContentContext.markdown || '',+ xml: pageContentContext.xml || '',+ metadata: {+ title: pageContentContext.metadata.title,+ charCount: pageContentContext.metadata.charCount,+ lineCount: pageContentContext.metadata.lineCount,+ },+ },+ };+ log(+ '[internal_createAgentState] Page Agent detected, injected initialContext.pageEditor with title: %s',+ pageContentContext.metadata.title,+ );+ } catch (error) {+ // Page agent runtime may not be initialized (e.g., editor not set)+ // This is expected in some scenarios, so we just log and continue+ log('[internal_createAgentState] Failed to get page content context: %o', error);+ }+ }+const viewedTask = operation?.context.viewedTask;if (viewedTask) {try {@@ -761,6 +789,19 @@ export class StreamingExecutorActionImpl {todos,});+ // If page agent is enabled, get the latest XML for stepPageEditor+ if (scope === 'page' && nextContext.initialContext?.pageEditor) {+ try {+ const pageContentContext = pageAgentRuntime.getPageContentContext('xml');+ stepContext.stepPageEditor = {+ xml: pageContentContext.xml || '',+ };+ } catch (error) {+ // Page agent runtime may not be available, ignore errors+ log('[executeClientAgent] Failed to get page XML for step: %o', error);+ }+ }+// Inject stepContext into the runtime context for this stepnextContext = { ...nextContext, stepContext };diff --git a/src/store/chat/slices/message/reducer.test.ts b/src/store/chat/slices/message/reducer.test.tsindex 080d08b85c5..36223ed5cca 100644--- a/src/store/chat/slices/message/reducer.test.ts+++ b/src/store/chat/slices/message/reducer.test.ts@@ -1,9 +1,6 @@-import { parse } from '@lobechat/conversation-flow';import { type ChatToolPayload, type UIChatMessage } from '@lobechat/types';import i18n from 'i18next';-import { messagesReducer as conversationMessagesReducer } from '@/features/Conversation/store/slices/data/reducer';-import { type MessageDispatch } from './reducer';import { messagesReducer } from './reducer';@@ -283,49 +280,6 @@ describe('messagesReducer', () => {});describe('updateMessagePlugin', () => {- it.each([- ['chat', messagesReducer],- ['conversation', conversationMessagesReducer],- ] as const)('shows and clears tool failures before a server refresh in %s', (_, reduce) => {- const state: UIChatMessage[] = [- initialState[0],- { ...initialState[1], parentId: 'message1' },- {- content: 'Body saved for review; title not changed.',- createdAt: 1629264000001,- id: 'tool-result',- parentId: 'message2',- role: 'tool',- tool_call_id: 'abc',- updatedAt: 1629264000001,- },- ];- const error = { message: 'Page changed while saving', type: 'PageChangedDuringCommand' };- const resultError = (messages: UIChatMessage[]) =>- parse(messages).flatList.find((row) => row.role === 'assistantGroup')?.children?.[0]- .tools?.[0].result?.error;- const failed = reduce(state, {- id: 'tool-result',- type: 'updateMessagePlugin',- value: { error },- });- expect(resultError(failed)).toEqual(error);-- const unchanged = reduce(failed, {- id: 'tool-result',- type: 'updateMessagePlugin',- value: { arguments: '{}' },- });- expect(resultError(unchanged)).toEqual(error);-- const recovered = reduce(unchanged, {- id: 'tool-result',- type: 'updateMessagePlugin',- value: { error: null },- });- expect(resultError(recovered)).toBeUndefined();- });-it('should update the plugin of a tool message', () => {const toolMessage: UIChatMessage = {id: 'toolMessage',diff --git a/src/store/chat/slices/message/reducer.ts b/src/store/chat/slices/message/reducer.tsindex f9026a8ea8d..b49f0ec356b 100644--- a/src/store/chat/slices/message/reducer.ts+++ b/src/store/chat/slices/message/reducer.ts@@ -194,7 +194,6 @@ export const messagesReducer = (if (!message || message.role !== 'tool') return;message.plugin = merge(message.plugin, value);- if (value.error !== undefined) message.pluginError = value.error;message.updatedAt = Date.now();});}