🤯 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
✨ feat(chat): add message text selection actions (#16842)
Arvin Xu046c245ad91e
diff --git a/.agents/skills/agent-testing/references/common-mistakes.md b/.agents/skills/agent-testing/references/common-mistakes.mdindex ab401f07789..45f621ff0ca 100644--- a/.agents/skills/agent-testing/references/common-mistakes.md+++ b/.agents/skills/agent-testing/references/common-mistakes.md@@ -255,3 +255,47 @@ verify run. Either drive the real app UI with agent-browser/Electron/Web and atta screenshot, or explicitly mark the UI screenshot case blocked with the measuredenvironment blocker. Do not present a UI-touching report as complete with only CLIevidence.++## Case 11 — Skipping the agent-testing entry point for a UI E2E check++**Wrong approach**: after implementing a user-facing Markdown/chat interaction,+running generic local checks and an ad-hoc browser probe without first reading and+following the repo's `agent-testing` skill. The user had to ask why the test plan+did not use the dedicated skill.++**Why it's wrong**: `agent-testing` encodes LobeHub-specific surface choice, auth,+isolated Electron dev instances, screenshot evidence rules, reporting, and known+tooling traps. Bypassing it makes the validation weaker even when individual unit+tests pass.++**What it breaks**: the run can stop at DOM/text heuristics, use the wrong app+surface, miss required screenshot/report evidence, or fail to publish a verify+report that the user can inspect.++**Correct approach**: for any local end-to-end or manual verification task,+especially UI-facing changes, start with `agent-testing`: read this file and+`probe-mock-patterns.md`, resolve the test env, choose the correct surface, run+the app-specific probes, capture visually confirmed evidence, publish the verify+report, and tear down processes started by the run.++## Case 12 — Verifying the selection chip but not the final model payload++**Wrong approach**: after adding a chat text-selection action, marking the feature+verified because the floating toolbar appeared, the selected-text chip rendered,+and the UI store contained a `contextSelections` entry — without checking the+final message payload that the model receives.++**Why it's wrong**: UI metadata can be saved and displayed while a later+context-engine/runtime gate drops it before request construction. In this case,+the user bubble showed the selected text, but the Anthropic request only carried+the raw user question because generic `contextSelections` were gated behind page+editor context injection.++**What it breaks**: ships a feature that looks successful in the chat UI but has+no effect on model behavior; the user must inspect DevTools to discover the+selected context never reached the assistant.++**Correct approach**: for any feature that claims to "inject" context, verify the+last mile: add or run an integration-level assertion against the transformed+messages/request body (e.g. `MessagesEngine` output or transport payload), and+only treat the UI chip/store as supporting evidence.diff --git a/.agents/skills/agent-testing/references/probe-mock-patterns.md b/.agents/skills/agent-testing/references/probe-mock-patterns.mdindex fdaccc87c07..80beaff5a37 100644--- a/.agents/skills/agent-testing/references/probe-mock-patterns.md+++ b/.agents/skills/agent-testing/references/probe-mock-patterns.md@@ -455,3 +455,15 @@- Byte-size is a reliable auto-flag for near-uniform frames (blank/loading), but twodifferent near-uniform states (dark loading-screen vs blank) can both be small — alwaysRead the frame to tell them apart (Case 1 rule).++### E4. ✅ WORKS — keep Electron pool `LOBE_IPC_ID` short++- **Situation**: manually starting an isolated Electron dev instance with a+ descriptive `LOBE_IPC_ID` such as `lobehub-desktop-dev-manual-selection-2`.+ The main process builds a Unix socket path under `$TMPDIR`, and macOS rejects+ overlong socket paths.+- **Doesn't work**: long IPC ids can crash Electron at bootstrap with+ `listen EINVAL ... <id>-electron-ipc.sock`, before any renderer/CDP evidence is+ available.+- **Works**: use the numeric `electron-dev.sh start <id>` pool path, or keep+ manual IPC ids very short, e.g. `LOBE_IPC_ID=lhmsel2`.diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex d339e989ea2..32431e74187 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -1002,6 +1002,9 @@"taskSchedule.weekdays.thu": "Thu","taskSchedule.weekdays.tue": "Tue","taskSchedule.weekdays.wed": "Wed",+ "textSelection.addToConversation": "Add to conversation",+ "textSelection.added": "Added to conversation context",+ "textSelection.title": "Message selection","thread.closeSubagentThread": "Hide Detail","thread.divider": "Subtopic","thread.openSubagentThread": "View Detail",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex 792d2121b3d..8a02ffe8e61 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -1002,6 +1002,9 @@"taskSchedule.weekdays.thu": "四","taskSchedule.weekdays.tue": "二","taskSchedule.weekdays.wed": "三",+ "textSelection.addToConversation": "添加到对话",+ "textSelection.added": "已添加到对话上下文",+ "textSelection.title": "消息选区","thread.closeSubagentThread": "隐藏详情","thread.divider": "子话题","thread.openSubagentThread": "查看详情",diff --git a/packages/context-engine/src/engine/messages/MessagesEngine.ts b/packages/context-engine/src/engine/messages/MessagesEngine.tsindex c551ef390ca..6d76f92cb33 100644--- a/packages/context-engine/src/engine/messages/MessagesEngine.ts+++ b/packages/context-engine/src/engine/messages/MessagesEngine.ts@@ -34,6 +34,7 @@ import {AgentDocumentSystemReplaceInjector,AgentManagementContextInjector,BotPlatformContextInjector,+ ContextSelectionsInjector,DiscordContextProvider,EvalContextSystemInjector,ForceFinishSummaryInjector,@@ -212,8 +213,7 @@ export class MessagesEngine {const currentUserMessage = [...messages].reverse().find((m) => m.role === 'user' && typeof m.content === 'string')?.content as- | string- | undefined;+ string | undefined;// Shared config for all agent document injectorsconst agentDocConfig = {@@ -349,7 +349,9 @@ export class MessagesEngine {new SelectedSkillInjector({ enabled: hasSelectedSkills, selectedSkills }),// Selected tools (ephemeral user-selected @tool for this request)new SelectedToolInjector({ enabled: hasSelectedTools, selectedTools }),- // Page selections (inject user-selected text into each user message)+ // 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 }),diff --git a/packages/context-engine/src/engine/messages/__tests__/MessagesEngine.test.ts b/packages/context-engine/src/engine/messages/__tests__/MessagesEngine.test.tsindex d14435b38f8..524bfc6486f 100644--- a/packages/context-engine/src/engine/messages/__tests__/MessagesEngine.test.ts+++ b/packages/context-engine/src/engine/messages/__tests__/MessagesEngine.test.ts@@ -1081,7 +1081,42 @@ Document content here.]);});- it('should not inject selections when page editor is not enabled', async () => {+ it('should inject generic text selections when page editor is not enabled', async () => {+ const messages: UIChatMessage[] = [+ {+ content: '我是说,这是啥?',+ createdAt: Date.now(),+ id: 'msg-1',+ metadata: {+ contextSelections: [+ {+ content: '脚踢自学习',+ id: 'text-selection-1',+ source: 'text',+ title: '脚踢自学习',+ },+ ],+ },+ role: 'user',+ updatedAt: Date.now(),+ } as UIChatMessage,+ ];++ const params = createBasicParams({ messages });+ const engine = new MessagesEngine(params);++ const result = await engine.process();++ expect(result.messages[0].content).toContain('我是说,这是啥?');+ expect(result.messages[0].content).toContain('<user_context_selections count="1">');+ expect(result.messages[0].content).toContain('source="text"');+ expect(result.messages[0].content).toContain('脚踢自学习');+ expect(result.messages[0].content).toContain(+ '<!-- SYSTEM CONTEXT (NOT PART OF USER QUERY) -->',+ );+ });++ it('should not inject legacy page selections when page editor is not enabled', async () => {const messages: UIChatMessage[] = [{content: 'Question',diff --git a/packages/context-engine/src/providers/ContextSelectionsInjector.ts b/packages/context-engine/src/providers/ContextSelectionsInjector.tsnew file mode 100644index 00000000000..0b371384a25--- /dev/null+++ b/packages/context-engine/src/providers/ContextSelectionsInjector.ts@@ -0,0 +1,59 @@+import { formatContextSelections } from '@lobechat/prompts';+import type { ContextSelection } from '@lobechat/types';+import debug from 'debug';++import { BaseEveryUserContentProvider } from '../base/BaseEveryUserContentProvider';+import type { Message, ProcessorOptions } from '../types';++const log = debug('context-engine:provider:ContextSelectionsInjector');++export interface ContextSelectionsInjectorConfig {+ /** Whether generic contextSelections injection is enabled */+ enabled?: boolean;+}++/**+ * Injects generic user-attached context selections into each user message that owns them.+ *+ * These selections are not page-editor selections: they can come from chat text,+ * code snippets, page selections normalized into the generic format, or other+ * future context sources.+ */+export class ContextSelectionsInjector extends BaseEveryUserContentProvider {+ readonly name = 'ContextSelectionsInjector';++ constructor(+ private config: ContextSelectionsInjectorConfig = {},+ options: ProcessorOptions = {},+ ) {+ super(options);+ }++ protected buildContentForMessage(+ message: Message,+ index: number,+ ): { content: string; contextType: string } | null {+ if (!this.config.enabled) {+ return null;+ }++ const contextSelections = message.metadata?.contextSelections as ContextSelection[] | undefined;++ if (!contextSelections || contextSelections.length === 0) {+ return null;+ }++ const formattedSelections = formatContextSelections(contextSelections);++ if (!formattedSelections) return null;++ log(+ `Building generic context selections for message at index ${index} with ${contextSelections.length} selections`,+ );++ return {+ content: formattedSelections,+ contextType: 'user_context_selections',+ };+ }+}diff --git a/packages/context-engine/src/providers/PageSelectionsInjector.ts b/packages/context-engine/src/providers/PageSelectionsInjector.tsindex 9b2c34e470d..9357f35687a 100644--- a/packages/context-engine/src/providers/PageSelectionsInjector.ts+++ b/packages/context-engine/src/providers/PageSelectionsInjector.ts@@ -1,5 +1,5 @@-import { formatContextSelections, formatPageSelections } from '@lobechat/prompts';-import type { ContextSelection, PageSelection } from '@lobechat/types';+import { formatPageSelections } from '@lobechat/prompts';+import type { PageSelection } from '@lobechat/types';import debug from 'debug';import { BaseEveryUserContentProvider } from '../base/BaseEveryUserContentProvider';@@ -36,28 +36,10 @@ export class PageSelectionsInjector extends BaseEveryUserContentProvider {message: Message,index: number,): { content: string; contextType: string } | null {- // Skip if not enabledif (!this.config.enabled) {return null;}- const contextSelections = message.metadata?.contextSelections as ContextSelection[] | undefined;-- if (contextSelections && contextSelections.length > 0) {- const formattedSelections = formatContextSelections(contextSelections);-- if (!formattedSelections) return null;-- log(- `Building generic context selections for message at index ${index} with ${contextSelections.length} selections`,- );-- return {- content: formattedSelections,- contextType: 'user_context_selections',- };- }-// Check if message has legacy pageSelections in metadataconst pageSelections = message.metadata?.pageSelections as PageSelection[] | undefined;diff --git a/packages/context-engine/src/providers/__tests__/ContextSelectionsInjector.test.ts b/packages/context-engine/src/providers/__tests__/ContextSelectionsInjector.test.tsnew file mode 100644index 00000000000..d21a26c4d1e--- /dev/null+++ b/packages/context-engine/src/providers/__tests__/ContextSelectionsInjector.test.ts@@ -0,0 +1,118 @@+import { describe, expect, it } from 'vitest';++import type { PipelineContext } from '../../types';+import { ContextSelectionsInjector } from '../ContextSelectionsInjector';++describe('ContextSelectionsInjector', () => {+ const createContext = (messages: any[] = []): PipelineContext => ({+ initialState: {+ messages: [],+ model: 'test-model',+ provider: 'test-provider',+ },+ isAborted: false,+ messages,+ metadata: {+ maxTokens: 4000,+ model: 'test-model',+ },+ });++ describe('enabled/disabled', () => {+ it('should skip injection when disabled', async () => {+ const injector = new ContextSelectionsInjector({ enabled: false });++ const context = createContext([+ {+ content: 'Question',+ metadata: {+ contextSelections: [+ {+ content: 'Selected text',+ id: 'text-1',+ source: 'text',+ },+ ],+ },+ role: 'user',+ },+ ]);++ const result = await injector.process(context);++ expect(result.messages[0].content).toBe('Question');+ expect(result.metadata.ContextSelectionsInjectorInjectedCount).toBeUndefined();+ });++ it('should inject text context selections independently from legacy page selections', async () => {+ const injector = new ContextSelectionsInjector({ enabled: true });++ const context = createContext([+ {+ content: 'What does this mean?',+ metadata: {+ contextSelections: [+ {+ content: '脚踢自学习',+ id: 'text-1',+ source: 'text',+ title: '脚踢自学习',+ },+ ],+ pageSelections: [+ {+ content: 'Legacy page selection',+ id: 'page-1',+ pageId: 'page-1',+ xml: '<p>Legacy page selection</p>',+ },+ ],+ },+ role: 'user',+ },+ ]);++ const result = await injector.process(context);++ expect(result.messages[0].content).toContain('What does this mean?');+ expect(result.messages[0].content).toContain('<user_context_selections>');+ expect(result.messages[0].content).toContain('source="text"');+ expect(result.messages[0].content).toContain('脚踢自学习');+ expect(result.messages[0].content).not.toContain('<user_page_selections>');+ expect(result.messages[0].content).not.toContain('Legacy page selection');+ expect(result.metadata.ContextSelectionsInjectorInjectedCount).toBe(1);+ });+ });++ describe('context sources', () => {+ it('should inject code context selections with source metadata', async () => {+ const injector = new ContextSelectionsInjector({ enabled: true });++ const context = createContext([+ {+ content: 'Review this code',+ metadata: {+ contextSelections: [+ {+ content: 'const value = 1;',+ filePath: 'src/example.ts',+ id: 'code-1',+ lineRange: { endLine: 12, startLine: 12 },+ source: 'code',+ },+ ],+ },+ role: 'user',+ },+ ]);++ const result = await injector.process(context);++ expect(result.messages[0].content).toContain('Review this code');+ expect(result.messages[0].content).toContain('<user_context_selections>');+ expect(result.messages[0].content).toContain('filePath="src/example.ts"');+ expect(result.messages[0].content).toContain('lines="12-12"');+ expect(result.messages[0].content).toContain('const value = 1;');+ });+ });+});diff --git a/packages/context-engine/src/providers/__tests__/PageSelectionsInjector.test.ts b/packages/context-engine/src/providers/__tests__/PageSelectionsInjector.test.tsindex 07c2a556fa2..f9f06a5321f 100644--- a/packages/context-engine/src/providers/__tests__/PageSelectionsInjector.test.ts+++ b/packages/context-engine/src/providers/__tests__/PageSelectionsInjector.test.ts@@ -64,36 +64,6 @@ describe('PageSelectionsInjector', () => {expect(result.messages[0].content).toContain('<user_page_selections>');expect(result.messages[0].content).toContain('Selected text');});-- it('should inject generic context selections when present', async () => {- const injector = new PageSelectionsInjector({ enabled: true });-- const context = createContext([- {- content: 'Review this code',- metadata: {- contextSelections: [- {- content: 'const value = 1;',- filePath: 'src/example.ts',- id: 'code-1',- lineRange: { endLine: 12, startLine: 12 },- source: 'code',- },- ],- },- role: 'user',- },- ]);-- const result = await injector.process(context);-- expect(result.messages[0].content).toContain('Review this code');- expect(result.messages[0].content).toContain('<user_context_selections>');- expect(result.messages[0].content).toContain('filePath="src/example.ts"');- expect(result.messages[0].content).toContain('lines="12-12"');- expect(result.messages[0].content).toContain('const value = 1;');- });});describe('injection to every user message', () => {diff --git a/packages/context-engine/src/providers/index.ts b/packages/context-engine/src/providers/index.tsindex 2aedcb0b537..49bc14d4a36 100644--- a/packages/context-engine/src/providers/index.ts+++ b/packages/context-engine/src/providers/index.ts@@ -11,6 +11,7 @@ export {} from './AgentDocumentInjector';export { AgentManagementContextInjector } from './AgentManagementContextInjector';export { BotPlatformContextInjector } from './BotPlatformContextInjector';+export { ContextSelectionsInjector } from './ContextSelectionsInjector';export { DiscordContextProvider } from './DiscordContextProvider';export { EvalContextSystemInjector } from './EvalContextSystemInjector';export { ForceFinishSummaryInjector } from './ForceFinishSummaryInjector';@@ -75,6 +76,7 @@ export type {BotPlatformContext,BotPlatformContextInjectorConfig,} from './BotPlatformContextInjector';+export type { ContextSelectionsInjectorConfig } from './ContextSelectionsInjector';export type { DiscordContext, DiscordContextProviderConfig } from './DiscordContextProvider';export type { EvalContext, EvalContextSystemInjectorConfig } from './EvalContextSystemInjector';export type { ForceFinishSummaryInjectorConfig } from './ForceFinishSummaryInjector';diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex fcf7c431b37..fa81140c9f6 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -624,6 +624,9 @@ export default {'pageCopilot.welcome': `**Clearer, sharper writing**\n\nDraft, rewrite, or polish—tell me your intent and I'll refine the rest.`,'pageSelection.lines': 'Lines {{start}}-{{end}}','pageSelection.reference': 'Selected Text',+ 'textSelection.added': 'Added to conversation context',+ 'textSelection.addToConversation': 'Add to conversation',+ 'textSelection.title': 'Message selection','pin': 'Pin','pinOff': 'Unpin','rag.referenceChunks': 'Reference Source',diff --git a/src/features/Conversation/Messages/components/TextSelectionActionLayer/helpers.test.ts b/src/features/Conversation/Messages/components/TextSelectionActionLayer/helpers.test.tsnew file mode 100644index 00000000000..c21aca6c657--- /dev/null+++ b/src/features/Conversation/Messages/components/TextSelectionActionLayer/helpers.test.ts@@ -0,0 +1,74 @@+import { describe, expect, it } from 'vitest';++import {+ createTextSelectionContext,+ getRangeFirstLineRect,+ getSelectionPreview,+ getSelectionToolbarPosition,+ isSameTextSelectionContext,+} from './helpers';++describe('TextSelectionActionLayer helpers', () => {+ it('builds a text context selection from selected rendered text', () => {+ const context = createTextSelectionContext({+ id: 'selection-1',+ selectedText: ' selected\ntext ',+ title: 'Message selection',+ });++ expect(context).toEqual({+ content: 'selected\ntext',+ format: 'text',+ id: 'selection-1',+ preview: 'selected text',+ source: 'text',+ title: 'Message selection',+ type: 'text',+ });+ });++ it('dedupes only plain text selections with the same content', () => {+ const textContext = createTextSelectionContext({+ id: 'selection-1',+ selectedText: 'selected text',+ title: 'Message selection',+ });++ expect(isSameTextSelectionContext(textContext, ' selected text ')).toBe(true);+ expect(+ isSameTextSelectionContext({ ...textContext, filePath: 'src/a.ts' }, 'selected text'),+ ).toBe(false);+ expect(isSameTextSelectionContext({ ...textContext, pageId: 'page-1' }, 'selected text')).toBe(+ false,+ );+ });++ it('clips long previews without changing the selected content', () => {+ const selectedText = 'a'.repeat(90);++ expect(getSelectionPreview(selectedText)).toBe(`${'a'.repeat(80)}...`);+ });++ it('keeps toolbar position inside viewport margins', () => {+ const rect = DOMRect.fromRect({ height: 18, width: 30, x: -20, y: 4 });++ expect(getSelectionToolbarPosition(rect, 320)).toEqual({+ left: 12,+ top: 12,+ });+ });++ it('uses the first visual line of a multi-line selection for toolbar anchoring', () => {+ const firstLineStart = DOMRect.fromRect({ height: 18, width: 40, x: 120, y: 20 });+ const secondLine = DOMRect.fromRect({ height: 18, width: 280, x: 40, y: 44 });+ const firstLineEnd = DOMRect.fromRect({ height: 17, width: 60, x: 170, y: 21 });+ const range = {+ getBoundingClientRect: () => secondLine,+ getClientRects: () => [firstLineStart, secondLine, firstLineEnd],+ } as unknown as Range;++ expect(getRangeFirstLineRect(range)).toEqual(+ DOMRect.fromRect({ height: 18, width: 110, x: 120, y: 20 }),+ );+ });+});diff --git a/src/features/Conversation/Messages/components/TextSelectionActionLayer/helpers.ts b/src/features/Conversation/Messages/components/TextSelectionActionLayer/helpers.tsnew file mode 100644index 00000000000..0d8bfbd6e9f--- /dev/null+++ b/src/features/Conversation/Messages/components/TextSelectionActionLayer/helpers.ts@@ -0,0 +1,88 @@+import type { ChatContextContent } from '@lobechat/types';++export interface SelectionToolbarPosition {+ left: number;+ top: number;+}++export interface TextSelectionContextParams {+ id: string;+ selectedText: string;+ title: string;+}++const TOOLBAR_OFFSET = 12;+const VIEWPORT_MARGIN = 12;+const LINE_TOP_TOLERANCE = 3;++export const getSelectionPreview = (selectedText: string): string | undefined => {+ const preview = selectedText.replaceAll(/\s+/g, ' ').trim();+ if (!preview) return;++ return preview.length > 80 ? `${preview.slice(0, 80)}...` : preview;+};++export const createTextSelectionContext = ({+ id,+ selectedText,+ title,+}: TextSelectionContextParams): ChatContextContent => ({+ content: selectedText.trim(),+ format: 'text',+ id,+ preview: getSelectionPreview(selectedText),+ source: 'text',+ title,+ type: 'text',+});++export const isSameTextSelectionContext = (+ item: ChatContextContent,+ selectedText: string,+): boolean =>+ item.source === 'text' &&+ !item.filePath &&+ !item.pageId &&+ item.content.trim() === selectedText.trim();++export const getSelectionToolbarPosition = (+ rect: DOMRect,+ viewportWidth: number,+): SelectionToolbarPosition => {+ const center = rect.left + rect.width / 2;++ return {+ left: Math.min(Math.max(center, VIEWPORT_MARGIN), viewportWidth - VIEWPORT_MARGIN),+ top: Math.max(rect.top - TOOLBAR_OFFSET, VIEWPORT_MARGIN),+ };+};++const mergeRects = (rects: DOMRect[]): DOMRect => {+ const left = Math.min(...rects.map((rect) => rect.left));+ const right = Math.max(...rects.map((rect) => rect.right));+ const top = Math.min(...rects.map((rect) => rect.top));+ const bottom = Math.max(...rects.map((rect) => rect.bottom));++ return DOMRect.fromRect({+ height: bottom - top,+ width: right - left,+ x: left,+ y: top,+ });+};++export const getRangeFirstLineRect = (range: Range): DOMRect | undefined => {+ const rects = [...range.getClientRects()].filter((rect) => rect.width > 0 && rect.height > 0);++ if (rects.length === 0) {+ const rect = range.getBoundingClientRect();+ return rect.width > 0 || rect.height > 0 ? rect : undefined;+ }++ const firstTop = Math.min(...rects.map((rect) => rect.top));+ const firstLineRects = rects.filter(+ (rect) => Math.abs(rect.top - firstTop) <= LINE_TOP_TOLERANCE,+ );++ return mergeRects(firstLineRects);+};diff --git a/src/features/Conversation/Messages/components/TextSelectionActionLayer/index.tsx b/src/features/Conversation/Messages/components/TextSelectionActionLayer/index.tsxnew file mode 100644index 00000000000..90625f9d996--- /dev/null+++ b/src/features/Conversation/Messages/components/TextSelectionActionLayer/index.tsx@@ -0,0 +1,217 @@+'use client';++import { nanoid } from '@lobechat/utils';+import { Flexbox } from '@lobehub/ui';+import { Button, toast } from '@lobehub/ui/base-ui';+import { createStaticStyles } from 'antd-style';+import { MessageCirclePlusIcon } from 'lucide-react';+import type { CSSProperties, PointerEvent, ReactNode } from 'react';+import { memo, useCallback, useEffect, useRef, useState } from 'react';+import { createPortal } from 'react-dom';+import { useTranslation } from 'react-i18next';++import { useChatStore } from '@/store/chat';+import { useFileStore } from '@/store/file';++import {+ createTextSelectionContext,+ getRangeFirstLineRect,+ getSelectionToolbarPosition,+ isSameTextSelectionContext,+} from './helpers';++interface ActiveSelection {+ position: {+ left: number;+ top: number;+ };+ text: string;+}++interface TextSelectionActionLayerProps {+ children: ReactNode;+ disabled?: boolean;+}++const styles = createStaticStyles(({ css }) => ({+ root: css`+ display: contents;+ `,+ toolbar: css`+ position: fixed;+ z-index: 10000;+ transform: translate(-50%, -100%);++ padding: 4px;+ border: 1px solid light-dark(rgb(229 231 235), rgb(64 64 64));+ border-radius: 999px;++ background: light-dark(#fff, #1f1f1f);+ box-shadow:+ 0 8px 24px rgb(0 0 0 / 12%),+ 0 2px 8px rgb(0 0 0 / 8%);+ `,+}));++const focusChatInputSoon = () => {+ window.setTimeout(() => {+ // The Conversation ChatInput syncs the active editor here. In a portal+ // thread, the newly mounted input becomes the latest registered editor.+ useChatStore.getState().mainInputEditor?.focus();+ }, 160);+};++const TextSelectionActionLayer = memo<TextSelectionActionLayerProps>(({ children, disabled }) => {+ const { t } = useTranslation('chat');+ const rootRef = useRef<HTMLDivElement | null>(null);+ const toolbarRef = useRef<HTMLDivElement | null>(null);+ const [activeSelection, setActiveSelection] = useState<ActiveSelection | null>(null);++ const addChatContextSelection = useFileStore((s) => s.addChatContextSelection);++ const hideToolbar = useCallback(() => {+ setActiveSelection(null);+ }, []);++ const clearNativeSelection = useCallback(() => {+ window.getSelection()?.removeAllRanges();+ hideToolbar();+ }, [hideToolbar]);++ const updateSelection = useCallback(() => {+ if (disabled) {+ hideToolbar();+ return;+ }++ const root = rootRef.current;+ const selection = window.getSelection();+ if (!root || !selection || selection.rangeCount === 0 || selection.isCollapsed) {+ hideToolbar();+ return;+ }++ const anchorNode = selection.anchorNode;+ const focusNode = selection.focusNode;+ if (!anchorNode || !focusNode || !root.contains(anchorNode) || !root.contains(focusNode)) {+ hideToolbar();+ return;+ }++ const text = selection.toString().trim();+ if (!text) {+ hideToolbar();+ return;+ }++ const rect = getRangeFirstLineRect(selection.getRangeAt(0));+ if (!rect) {+ hideToolbar();+ return;+ }++ setActiveSelection({+ position: getSelectionToolbarPosition(rect, window.innerWidth),+ text,+ });+ }, [disabled, hideToolbar]);++ const scheduleSelectionUpdate = useCallback(() => {+ window.setTimeout(updateSelection, 0);+ }, [updateSelection]);++ useEffect(() => {+ if (!activeSelection) return;++ const handlePointerDown = (event: globalThis.PointerEvent) => {+ const target = event.target;+ if (!(target instanceof Node)) return;+ if (toolbarRef.current?.contains(target) || rootRef.current?.contains(target)) return;++ hideToolbar();+ };++ window.addEventListener('pointerdown', handlePointerDown, true);+ window.addEventListener('resize', hideToolbar);+ window.addEventListener('scroll', hideToolbar, true);++ return () => {+ window.removeEventListener('pointerdown', handlePointerDown, true);+ window.removeEventListener('resize', hideToolbar);+ window.removeEventListener('scroll', hideToolbar, true);+ };+ }, [activeSelection, hideToolbar]);++ const addSelectionToConversation = useCallback(() => {+ const text = activeSelection?.text;+ if (!text) return;++ const currentSelections = useFileStore.getState().chatContextSelections;+ const existing = currentSelections.find((item) => isSameTextSelectionContext(item, text));+ const context =+ existing ??+ createTextSelectionContext({+ id: `selection-${nanoid(6)}`,+ selectedText: text,+ title: t('textSelection.title'),+ });++ addChatContextSelection(context);+ toast.success(t('textSelection.added'));+ }, [activeSelection?.text, addChatContextSelection, t]);++ const handleAddToConversation = useCallback(() => {+ addSelectionToConversation();+ clearNativeSelection();+ focusChatInputSoon();+ }, [addSelectionToConversation, clearNativeSelection]);++ const handleToolbarPointerDown = useCallback((event: PointerEvent<HTMLDivElement>) => {+ event.preventDefault();+ event.stopPropagation();+ }, []);++ const toolbarStyle = activeSelection+ ? ({+ left: activeSelection.position.left,+ top: activeSelection.position.top,+ } satisfies CSSProperties)+ : undefined;++ return (+ <div+ className={styles.root}+ ref={rootRef}+ onKeyUp={scheduleSelectionUpdate}+ onPointerUp={scheduleSelectionUpdate}+ >+ {children}+ {activeSelection &&+ createPortal(+ <Flexbox+ horizontal+ align={'center'}+ className={styles.toolbar}+ gap={2}+ ref={toolbarRef}+ style={toolbarStyle}+ onPointerDown={handleToolbarPointerDown}+ >+ <Button+ icon={<MessageCirclePlusIcon size={14} />}+ size={'small'}+ type={'text'}+ onClick={handleAddToConversation}+ >+ {t('textSelection.addToConversation')}+ </Button>+ </Flexbox>,+ document.body,+ )}+ </div>+ );+});++TextSelectionActionLayer.displayName = 'TextSelectionActionLayer';++export default TextSelectionActionLayer;diff --git a/src/features/Conversation/Messages/index.tsx b/src/features/Conversation/Messages/index.tsxindex 6e104a218a9..14ace9f786c 100644--- a/src/features/Conversation/Messages/index.tsx+++ b/src/features/Conversation/Messages/index.tsx@@ -18,6 +18,7 @@ import AgentCouncilMessage from './AgentCouncil';import AssistantMessage from './Assistant';import AssistantGroupMessage from './AssistantGroup';import type { WorkflowExpandLevelDefault } from './AssistantGroup/components/WorkflowCollapse';+import TextSelectionActionLayer from './components/TextSelectionActionLayer';import CompressedGroupMessage from './CompressedGroup';import GroupTasksMessage from './GroupTasks';import TaskMessage from './Task';@@ -90,6 +91,8 @@ const MessageItem = memo<MessageItemProps>(// render the same anchored footer (e.g. AgentSignalReceiptList) a second time.const shouldInjectFooter =role === 'assistant' || role === 'assistantGroup' || role === 'supervisor';+ const supportsTextSelectionActions =+ role === 'user' || role === 'assistant' || role === 'assistantGroup';const onContextMenu = useCallback(async (event: MouseEvent<HTMLDivElement>) => {@@ -213,6 +216,18 @@ const MessageItem = memo<MessageItemProps>(if (!role) return;+ const content = (+ <SafeBoundary variant="alert">+ <Suspense fallback={<BubblesLoading />}>{renderContent()}</Suspense>+ </SafeBoundary>+ );++ const selectableContent = supportsTextSelectionActions ? (+ <TextSelectionActionLayer>{content}</TextSelectionActionLayer>+ ) : (+ content+ );+return (<>{enableHistoryDivider && <History />}@@ -222,9 +237,7 @@ const MessageItem = memo<MessageItemProps>(onContextMenu={onContextMenu}><MessageSelectionWrapper id={id} role={role}>- <SafeBoundary variant="alert">- <Suspense fallback={<BubblesLoading />}>{renderContent()}</Suspense>- </SafeBoundary>+ {selectableContent}</MessageSelectionWrapper>{!shouldInjectFooter && footerRender}{endRender}