Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat: add send-time snapshot to active topic document context (#16583)

Innei93c8bfb1ee60
diff --git a/packages/context-engine/src/engine/messages/__tests__/MessagesEngine.test.ts b/packages/context-engine/src/engine/messages/__tests__/MessagesEngine.test.ts
index 59b04641a9a..281d99c9956 100644
--- a/packages/context-engine/src/engine/messages/__tests__/MessagesEngine.test.ts
+++ b/packages/context-engine/src/engine/messages/__tests__/MessagesEngine.test.ts
@@ -628,6 +628,11 @@ Document content here.
activeTopicDocument: {
agentDocumentId: 'agd_123',
documentId: 'docs_123',
+ snapshot: {
+ markdown: '# Topic Plan\n\nDraft body',
+ metadata: { charCount: 24, lineCount: 3, title: 'Topic Plan' },
+ xml: '<doc><heading id="h1">Topic Plan</heading></doc>',
+ },
title: 'Topic Plan',
},
},
@@ -641,8 +646,12 @@ Document content here.
expect(userMessage?.content).toContain('<active_topic_document>');
expect(userMessage?.content).toContain('document_id="docs_123"');
expect(userMessage?.content).toContain('agent_document_id="agd_123"');
+ expect(userMessage?.content).toContain('<current_document_snapshot>');
+ expect(userMessage?.content).toContain('<markdown chars="24" lines="3">');
+ expect(userMessage?.content).toContain('<doc_xml_structure>');
expect(userMessage?.content).toContain('scope="currentTopic"');
expect(userMessage?.content).toContain('Do not use PageAgent editor tools');
+ expect(userMessage?.content).toContain('Call readDocument with format="xml" only when');
expect(result.metadata.activeTopicDocumentContextInjected).toBe(true);
});
diff --git a/packages/context-engine/src/providers/ActiveTopicDocumentContextInjector.ts b/packages/context-engine/src/providers/ActiveTopicDocumentContextInjector.ts
index a4e90b8c487..bd3c5574213 100644
--- a/packages/context-engine/src/providers/ActiveTopicDocumentContextInjector.ts
+++ b/packages/context-engine/src/providers/ActiveTopicDocumentContextInjector.ts
@@ -1,4 +1,4 @@
-import { escapeXmlAttr } from '@lobechat/prompts';
+import { escapeXmlAttr, formatPageContentContext } from '@lobechat/prompts';
import type { RuntimeActiveTopicDocumentContext } from '@lobechat/types';
import debug from 'debug';
@@ -29,11 +29,20 @@ const formatActiveTopicDocumentContext = (document: RuntimeActiveTopicDocumentCo
.filter(Boolean)
.join(' ');
+ const snapshot = document.snapshot
+ ? `<current_document_snapshot>
+${formatPageContentContext(document.snapshot)}
+</current_document_snapshot>`
+ : '';
+
return `<document ${attrs} />
+${snapshot}
<guidance>
The current conversation is not inside the page editor. Do not use PageAgent editor tools.
When the user asks to continue editing this topic document, use lobe-agent-documents tools instead.
-Prefer readDocument with format="xml" and modifyNodes with agent_document_id when it is present.
+Use the injected current document snapshot when it is sufficient for the requested change.
+Call readDocument with format="xml" only when the injected snapshot is missing, stale, or insufficient.
+Prefer modifyNodes with agent_document_id when it is present.
If agent_document_id is missing, call listDocuments with scope="currentTopic" and match document_id.
</guidance>`;
};
diff --git a/packages/types/src/stepContext.ts b/packages/types/src/stepContext.ts
index e436fab3b1b..88171e8da89 100644
--- a/packages/types/src/stepContext.ts
+++ b/packages/types/src/stepContext.ts
@@ -88,6 +88,13 @@ export interface RuntimeActiveTopicDocumentContext {
* Underlying documents.id used by topic page routes.
*/
documentId: string;
+ /**
+ * Optional send-time document snapshot.
+ *
+ * This lets non-page surfaces, such as an agent-document floating panel,
+ * provide the current document body without enabling PageAgent editor tools.
+ */
+ snapshot?: InitialPageEditorContext;
/**
* Human-readable title for model disambiguation.
*/
diff --git a/src/features/FloatingChatPanel/InputRow.tsx b/src/features/FloatingChatPanel/InputRow.tsx
index 0f8f35a9db6..1c42b614f74 100644
--- a/src/features/FloatingChatPanel/InputRow.tsx
+++ b/src/features/FloatingChatPanel/InputRow.tsx
@@ -26,29 +26,42 @@ const InputRowViewTransitionStyle = createGlobalStyle`
}
`;
-const supportsViewTransition =
- typeof document !== 'undefined' &&
- typeof (document as Document & { startViewTransition?: unknown }).startViewTransition ===
- 'function';
+interface ViewTransitionLike {
+ finished: Promise<void>;
+}
-const startViewTransition = (callback: () => void) => {
- (document as Document & { startViewTransition: (cb: () => void) => unknown }).startViewTransition(
- callback,
- );
+type DocumentWithVT = Document & {
+ startViewTransition?: (cb: () => void) => ViewTransitionLike;
};
+const supportsViewTransition =
+ typeof document !== 'undefined' &&
+ typeof (document as DocumentWithVT).startViewTransition === 'function';
+
// View Transition snapshots the DOM before and after this callback. The DOM mutation
// must commit synchronously inside it, otherwise the "after" snapshot is identical
// to the "before" one and nothing animates.
+//
+// Setting `view-transition-name: none` on <html> for the duration of the transition
+// suppresses the default root snapshot, so only the named `floating-chat-panel-input`
+// element participates. Elements outside the panel keep their native CSS animations
+// instead of being frozen under the root crossfade.
const commitWithViewTransition = (commit: () => void) => {
if (!supportsViewTransition) {
commit();
return;
}
- startViewTransition(() => {
+ const root = document.documentElement;
+ const previousViewTransitionName = root.style.viewTransitionName;
+ root.style.viewTransitionName = 'none';
+ const transition = (document as DocumentWithVT).startViewTransition!(() => {
// eslint-disable-next-line @eslint-react/dom/no-flush-sync
flushSync(commit);
});
+ const restore = () => {
+ root.style.viewTransitionName = previousViewTransitionName;
+ };
+ transition.finished.then(restore, restore);
};
const EMPTY_ACTIONS: never[] = [];
diff --git a/src/features/FloatingChatPanel/index.test.tsx b/src/features/FloatingChatPanel/index.test.tsx
index 4992b391ab8..0a1cb26f9d1 100644
--- a/src/features/FloatingChatPanel/index.test.tsx
+++ b/src/features/FloatingChatPanel/index.test.tsx
@@ -242,11 +242,11 @@ describe('FloatingChatPanel', () => {
it('starts collapsed and ships a seamless dismissible sheet with two snap points', () => {
const { getByTestId } = render(<FloatingChatPanel agentId="a" topicId="t" />);
const sheet = getByTestId('floating-panel-shell');
- expect(sheet.dataset.snapPoints).toBe(JSON.stringify([420, 800]));
+ expect(sheet.dataset.snapPoints).toBe(JSON.stringify([320, 800]));
expect(sheet.dataset.variant).toBe('elevated');
expect(sheet.dataset.dismissible).toBe('true');
expect(sheet.dataset.open).toBe('false');
- expect(sheet.dataset.activeSnap).toBe('420');
+ expect(sheet.dataset.activeSnap).toBe('320');
expect(getByTestId('floating-chat-panel').dataset.collapsed).toBe('true');
});
@@ -268,7 +268,7 @@ describe('FloatingChatPanel', () => {
const sheet = getByTestId('floating-panel-shell');
expect(sheet.dataset.open).toBe('true');
- expect(sheet.dataset.activeSnap).toBe('420');
+ expect(sheet.dataset.activeSnap).toBe('320');
expect(getByTestId('floating-chat-panel').dataset.collapsed).toBe('false');
const input = getByTestId('chat-input');
expect(input.dataset.allowExpand).toBe('false');
@@ -290,7 +290,7 @@ describe('FloatingChatPanel', () => {
expect(getByTestId('floating-panel-shell').dataset.open).toBe('false');
expect(getByTestId('floating-chat-panel').dataset.collapsed).toBe('true');
- expect(getByTestId('floating-panel-shell').dataset.activeSnap).toBe('420');
+ expect(getByTestId('floating-panel-shell').dataset.activeSnap).toBe('320');
});
it('expands when the header collapse button is clicked from expanded state', async () => {
@@ -311,7 +311,7 @@ describe('FloatingChatPanel', () => {
fireEvent.click(getByTestId('floating-chat-panel-expand-button'));
expect(getByTestId('floating-chat-panel').dataset.collapsed).toBe('false');
- expect(getByTestId('floating-panel-shell').dataset.activeSnap).toBe('420');
+ expect(getByTestId('floating-panel-shell').dataset.activeSnap).toBe('320');
});
it('reflects user-driven snap changes through onSnapPointChange', async () => {
@@ -320,7 +320,7 @@ describe('FloatingChatPanel', () => {
await act(async () => {
await mergedHooksCaptured.current?.onBeforeSendMessage?.();
});
- expect(getByTestId('floating-panel-shell').dataset.activeSnap).toBe('420');
+ expect(getByTestId('floating-panel-shell').dataset.activeSnap).toBe('320');
act(() => {
sheetHandlers.current.onSnapPointChange?.(800);
diff --git a/src/features/FloatingChatPanel/index.tsx b/src/features/FloatingChatPanel/index.tsx
index 48d8c486600..12a22cc2e7f 100644
--- a/src/features/FloatingChatPanel/index.tsx
+++ b/src/features/FloatingChatPanel/index.tsx
@@ -28,7 +28,7 @@ import ChatBody from './ChatBody';
import { useSingleInstanceGuard } from './guard';
import InputRow from './InputRow';
-const SNAP_POINTS = [420, 800] as const;
+const SNAP_POINTS = [320, 800] as const;
const MID_SNAP_POINT = SNAP_POINTS[0];
const MAX_SNAP_POINT = SNAP_POINTS.at(-1)!;
diff --git a/src/store/chat/utils/activeTopicDocumentContext.test.ts b/src/store/chat/utils/activeTopicDocumentContext.test.ts
index 4338fab717b..f12417fed95 100644
--- a/src/store/chat/utils/activeTopicDocumentContext.test.ts
+++ b/src/store/chat/utils/activeTopicDocumentContext.test.ts
@@ -10,12 +10,14 @@ import {
vi.mock('@/services/agentDocument', () => ({
agentDocumentService: {
listDocuments: vi.fn(),
+ readDocument: vi.fn(),
},
}));
describe('activeTopicDocumentContext', () => {
beforeEach(() => {
vi.clearAllMocks();
+ vi.mocked(agentDocumentService.readDocument).mockResolvedValue(undefined);
});
it('resolves active topic document context from current topic documents', async () => {
@@ -63,6 +65,43 @@ describe('activeTopicDocumentContext', () => {
});
});
+ it('hydrates a send-time snapshot when the caller supplies agentDocumentId', async () => {
+ vi.mocked(agentDocumentService.readDocument).mockResolvedValue({
+ content: '# Plan\n\nCurrent body',
+ contentCharCount: 20,
+ litexml: '<doc><heading id="h1">Plan</heading></doc>',
+ title: 'Plan',
+ } as any);
+
+ const context = await resolveActiveTopicDocumentInitialContext({
+ agentDocumentId: 'agd_caller',
+ agentId: 'agt_1',
+ documentId: 'docs_1',
+ scope: 'main',
+ topicId: 'tpc_1',
+ });
+
+ expect(agentDocumentService.readDocument).toHaveBeenCalledWith({
+ agentId: 'agt_1',
+ format: 'both',
+ id: 'agd_caller',
+ });
+ expect(context?.initialContext?.activeTopicDocument).toEqual({
+ agentDocumentId: 'agd_caller',
+ documentId: 'docs_1',
+ snapshot: {
+ markdown: '# Plan\n\nCurrent body',
+ metadata: {
+ charCount: 20,
+ lineCount: 3,
+ title: 'Plan',
+ },
+ xml: '<doc><heading id="h1">Plan</heading></doc>',
+ },
+ title: 'Plan',
+ });
+ });
+
it('resolves with caller-supplied agentDocumentId even without an active topic', async () => {
const context = await resolveActiveTopicDocumentInitialContext({
agentDocumentId: 'agd_caller',
diff --git a/src/store/chat/utils/activeTopicDocumentContext.ts b/src/store/chat/utils/activeTopicDocumentContext.ts
index bab643037e6..9c1c26ef3a6 100644
--- a/src/store/chat/utils/activeTopicDocumentContext.ts
+++ b/src/store/chat/utils/activeTopicDocumentContext.ts
@@ -1,8 +1,19 @@
import type { AgentRuntimeContext } from '@lobechat/agent-runtime';
-import type { ConversationContext, RuntimeActiveTopicDocumentContext } from '@lobechat/types';
+import type {
+ ConversationContext,
+ InitialPageEditorContext,
+ RuntimeActiveTopicDocumentContext,
+} from '@lobechat/types';
import { agentDocumentService } from '@/services/agentDocument';
+interface AgentDocumentSnapshotPayload {
+ content?: string | null;
+ contentCharCount?: number | null;
+ litexml?: string | null;
+ title?: string | null;
+}
+
export const mergeAgentRuntimeInitialContexts = (
...contexts: Array<AgentRuntimeContext | undefined>
): AgentRuntimeContext | undefined => {
@@ -34,6 +45,38 @@ export const mergeAgentRuntimeInitialContexts = (
);
};
+const resolveActiveTopicDocumentSnapshot = async (
+ agentId: string,
+ agentDocumentId?: string,
+): Promise<InitialPageEditorContext | undefined> => {
+ if (!agentDocumentId) return;
+
+ try {
+ const document = await agentDocumentService.readDocument({
+ agentId,
+ format: 'both',
+ id: agentDocumentId,
+ });
+ if (!document) return;
+
+ const snapshot = document as AgentDocumentSnapshotPayload;
+ const markdown = snapshot.content ?? '';
+ const xml = snapshot.litexml ?? '';
+
+ return {
+ markdown,
+ metadata: {
+ charCount: snapshot.contentCharCount ?? markdown.length,
+ lineCount: markdown.length > 0 ? markdown.split('\n').length : 0,
+ title: snapshot.title || 'Untitled',
+ },
+ xml,
+ };
+ } catch (error) {
+ console.error('[activeTopicDocumentContext] Failed to read topic document snapshot:', error);
+ }
+};
+
const resolveActiveTopicDocument = async (
context: ConversationContext,
): Promise<RuntimeActiveTopicDocumentContext | undefined> => {
@@ -45,9 +88,16 @@ const resolveActiveTopicDocument = async (
// the lookup is scoped to currentTopic and would miss docs opened outside
// the active topic (skills, web docs).
if (context.agentDocumentId) {
+ const snapshot = await resolveActiveTopicDocumentSnapshot(
+ context.agentId,
+ context.agentDocumentId,
+ );
+
return {
agentDocumentId: context.agentDocumentId,
documentId: context.documentId,
+ snapshot,
+ ...(snapshot?.metadata.title ? { title: snapshot.metadata.title } : {}),
};
}
@@ -66,6 +116,7 @@ const resolveActiveTopicDocument = async (
return {
agentDocumentId: matchedDocument?.id,
documentId: context.documentId,
+ snapshot: await resolveActiveTopicDocumentSnapshot(context.agentId, matchedDocument?.id),
title: matchedDocument?.title,
};
} catch (error) {