diff --git a/src/apps/miniapp-shell/src/generated/chat-styles.css b/src/apps/miniapp-shell/src/generated/chat-styles.css index 15008dcf06..8b7990e25a 100644 --- a/src/apps/miniapp-shell/src/generated/chat-styles.css +++ b/src/apps/miniapp-shell/src/generated/chat-styles.css @@ -2616,6 +2616,11 @@ .user-message-item__lightbox-close[data-openbitfun-component=icon-button] > [data-openbitfun-part=icon] { display: contents; } + +.user-message-item__large-paste-text { + min-height: 280px; + font-family: var(--openbitfun-type-code-md-font-family); +} /* Model round item styles (BEM). */ .model-round-item:is([data-flow-item-stack], .explore-region__content, .flow-group-content-segment):not([data-agent-card-grid]) > :is(.flow-text-block, .flow-thinking-item, .flowchat-flow-item, .subagent-projection-text--truncated):not([hidden]):not([data-thinking-attachment=side]) { diff --git a/src/web-ui/src/flow_chat/components/ChatInput.tsx b/src/web-ui/src/flow_chat/components/ChatInput.tsx index feb50346c5..a2add38c86 100644 --- a/src/web-ui/src/flow_chat/components/ChatInput.tsx +++ b/src/web-ui/src/flow_chat/components/ChatInput.tsx @@ -3,6 +3,7 @@ import { ChatInputAttachments } from './ChatInputAttachments'; import { useExcerptComposerActions } from '../selection/useExcerptComposerActions'; import { isConversationExcerpt, formatConversationExcerpt } from '@/shared/utils/conversationExcerpt'; import { withConversationExcerpts } from '../utils/composerPresentation'; +import { expandLargePastes, pickReferencedLargePastes } from '../utils/largePasteMetadata'; /** * Standalone chat input component * Separated from bottom bar, supports session-level state awareness @@ -632,6 +633,9 @@ export const ChatInput: React.FC = ({ const removeContext = useContextStore(state => state.removeContext); const clearContexts = useContextStore(state => state.clearContexts); const replaceContexts = useContextStore(state => state.replaceContexts); + const restoreContexts = useCallback((items: ContextItem[]) => { + items.forEach(addContext); + }, [addContext]); const contextsRef = useRef(contexts); contextsRef.current = contexts; @@ -2364,20 +2368,12 @@ export const ChatInput: React.FC = ({ return; } - replacePendingLargePastes(Object.fromEntries( - entries.filter(([placeholder]) => text.includes(placeholder)) - )); + replacePendingLargePastes(pickReferencedLargePastes(pendingLargePastesRef.current, text) ?? {}); }, [replacePendingLargePastes]); - const expandPendingLargePastes = useCallback((text: string) => { - let expanded = text; - for (const [placeholder, actual] of Object.entries(pendingLargePastesRef.current)) { - if (expanded.includes(placeholder)) { - expanded = expanded.split(placeholder).join(actual); - } - } - return expanded; - }, []); + const expandPendingLargePastes = useCallback((text: string) => ( + expandLargePastes(text, pendingLargePastesRef.current) + ), []); const expandComposerSpecialTokens = useCallback((text: string) => { return expandAdditionalModePromptReferenceTokens( @@ -2422,6 +2418,7 @@ export const ChatInput: React.FC = ({ /** Complete composer context replacement, including image attachments. */ contexts?: ContextItem[]; composerPresentation?: ComposerPresentation; + largePastes?: Record; onlyIfEmpty?: boolean; mode?: 'replace' | 'append'; separator?: string; @@ -2447,10 +2444,13 @@ export const ChatInput: React.FC = ({ if (composerPresentation && data.mode !== 'append') { const restoredValue = composerPresentationToEditorText(composerPresentation); replaceContexts(data.contexts ?? composerPresentationContexts(composerPresentation)); - clearPendingLargePastes(); + const restoredLargePastes = pickReferencedLargePastes(data.largePastes, restoredValue) ?? {}; + replacePendingLargePastes(restoredLargePastes); dispatchInput({ type: 'SET_VALUE', payload: restoredValue }); inputValueRef.current = restoredValue; - richTextInputRef.current?.restoreComposerPresentation?.(composerPresentation); + richTextInputRef.current?.restoreComposerPresentation?.(composerPresentation, { + largePastes: restoredLargePastes, + }); richTextInputRef.current?.focus(); return; } @@ -2471,7 +2471,9 @@ export const ChatInput: React.FC = ({ : content; if (data.mode !== 'append') { - clearPendingLargePastes(); + // A restored message keeps its pasted bodies so the placeholders + // render as capsules again instead of becoming literal text. + replacePendingLargePastes(pickReferencedLargePastes(data.largePastes, nextValue) ?? {}); if (data.contexts) { replaceContexts(data.contexts); } @@ -2489,7 +2491,7 @@ export const ChatInput: React.FC = ({ return () => { globalEventBus.off('fill-chat-input', handleFillChatInput); }; - }, [addContext, clearPendingLargePastes, conversationScope, dispatchInput, replaceContexts]); + }, [addContext, conversationScope, dispatchInput, replaceContexts, replacePendingLargePastes]); // Expose current input value for external queries (e.g. deep review fill-back confirmation) React.useEffect(() => { @@ -6662,11 +6664,13 @@ export const ChatInput: React.FC = ({ ))} = ({ disabled={!targetCanCompose || caps.transferInFlight || isInterruptedTurnRecoveryInFlight} contexts={contexts} onRemoveContext={removeContext} + onRestoreContexts={restoreContexts} onContextTriggerStateChange={setContextTriggerState} onInlineTriggerStateChange={setInlineTriggerState} data-testid="chat-input-textarea" diff --git a/src/web-ui/src/flow_chat/components/RichTextInput.test.tsx b/src/web-ui/src/flow_chat/components/RichTextInput.test.tsx index 6ab65d7b29..c6fd6e329f 100644 --- a/src/web-ui/src/flow_chat/components/RichTextInput.test.tsx +++ b/src/web-ui/src/flow_chat/components/RichTextInput.test.tsx @@ -203,6 +203,215 @@ describeWithJsdom('RichTextInput external sync', () => { } }); + it('undoes an IME commit without also undoing the typing before it', async () => { + const onChange = vi.fn(); + const Controlled = () => { + const [value, setValue] = useState(''); + return ( + { onChange(next, contexts); setValue(next); }} + contexts={emptyContexts} + onRemoveContext={() => {}} + /> + ); + }; + await act(async () => root.render()); + const editor = container.querySelector('.rich-text-input') as HTMLDivElement; + + for (const text of ['1', '12', '123', '1234', '12345']) { + await act(async () => { + editor.dispatchEvent(new window.InputEvent('beforeinput', { + bubbles: true, cancelable: true, inputType: 'insertText', data: text.slice(-1), + })); + editor.textContent = text; + setCaret(editor, text.length); + editor.dispatchEvent(new window.InputEvent('input', { bubbles: true, inputType: 'insertText' })); + }); + } + await act(async () => { + Simulate.compositionStart(editor); + editor.textContent = '12345ni'; + editor.dispatchEvent(new window.InputEvent('input', { bubbles: true, inputType: 'insertCompositionText' })); + editor.textContent = '12345你好'; + setCaret(editor, 7); + Simulate.compositionEnd(editor); + }); + expect(onChange).toHaveBeenLastCalledWith('12345你好', []); + + const pressUndo = async (shiftKey = false) => { + const event = new window.KeyboardEvent('keydown', { + key: 'z', metaKey: true, shiftKey, bubbles: true, cancelable: true, + }); + await act(async () => { editor.dispatchEvent(event); }); + expect(event.defaultPrevented).toBe(true); + }; + + await pressUndo(); + expect(editor.textContent).toBe('12345'); + expect(onChange).toHaveBeenLastCalledWith('12345', []); + expect(window.getSelection()?.anchorOffset).toBe(5); + + await pressUndo(); + expect(editor.textContent).toBe(''); + + await pressUndo(true); + expect(editor.textContent).toBe('12345'); + await pressUndo(true); + expect(editor.textContent).toBe('12345你好'); + }); + + it.each([false, true])('keeps paste bodies through undo/redo and same-length edits (exact restore: %s)', async (exactRestore) => { + const placeholder = '[Pasted Content 1001 chars]'; + const original = 'a'.repeat(1001); + const edited = 'b'.repeat(1001); + let currentPastes: Record = {}; + const Controlled = () => { + const [value, setValue] = useState(''); + const [pastes, setPastes] = useState>({}); + currentPastes = pastes; + return { + setValue(next); + setPastes(previous => Object.fromEntries(Object.entries(previous).filter(([key]) => next.includes(key)))); + }} + pendingLargePastes={pastes} + onRestoreLargePastes={exactRestore ? setPastes : undefined} + onLargePaste={(text) => { setPastes(previous => ({ ...previous, [placeholder]: text })); return placeholder; }} + onUpdateLargePaste={(key, text) => { setPastes(previous => ({ ...previous, [key]: text })); return key; }} + contexts={emptyContexts} + onRemoveContext={() => {}} + />; + }; + await act(async () => root.render()); + const editor = container.querySelector('.rich-text-input') as HTMLDivElement; + setCaret(editor, 0); + await act(async () => paste(editor, { text: original })); + const undo = async (redo = false) => { + await act(async () => { editor.dispatchEvent(new window.KeyboardEvent('keydown', { + key: 'z', metaKey: true, shiftKey: redo, bubbles: true, cancelable: true, + })); }); + }; + for (let cycle = 0; cycle < 2; cycle++) { + await undo(); + expect(editor.querySelector('[data-large-paste-placeholder]')).toBeNull(); + await undo(true); + expect(editor.querySelector('[data-large-paste-placeholder]')).not.toBeNull(); + expect(currentPastes[placeholder]).toBe(original); + } + await act(async () => { (editor.querySelector('[data-large-paste-placeholder]') as HTMLElement).click(); }); + const textarea = document.body.querySelector('.rich-text-large-paste-dialog__textarea textarea') as HTMLTextAreaElement; + expect(textarea.value).toBe(original); + await act(async () => Simulate.change(textarea, { target: { value: edited } } as never)); + const buttons = textarea.closest('[role="dialog"]')!.querySelectorAll('button'); + await act(async () => { (buttons[buttons.length - 1] as HTMLButtonElement).click(); }); + expect(currentPastes[placeholder]).toBe(edited); + await undo(); + expect(currentPastes[placeholder]).toBe(original); + await undo(true); + expect(currentPastes[placeholder]).toBe(edited); + }); + + it('restores a newly inserted context through undo and redo before another edit', async () => { + const context: ContextItem = { id: 'undo-file', type: 'file', fileName: 'file.ts', filePath: '/workspace/file.ts', timestamp: 1 }; + const inputRef = createRef(); + let add: () => void = () => {}; + let currentContexts: ContextItem[] = []; + const Controlled = () => { + const [value, setValue] = useState(''); + const [contexts, setContexts] = useState([]); + currentContexts = contexts; + add = () => { + setContexts([context]); + inputRef.current?.insertTag?.(context); + }; + return { + setValue(next); + const visibleIds = new Set(visible.map(item => item.id)); + const removedIds = new Set(contexts.filter(item => !visibleIds.has(item.id)).map(item => item.id)); + setContexts(previous => previous.filter(item => !removedIds.has(item.id))); + }} + onRemoveContext={id => setContexts(previous => previous.filter(item => item.id !== id))} + onRestoreContexts={items => setContexts(previous => [...previous, ...items])} + />; + }; + await act(async () => root.render()); + await act(async () => add()); + const editor = inputRef.current!; + expect(editor.querySelector('[data-context-id="undo-file"]')).not.toBeNull(); + for (let cycle = 0; cycle < 2; cycle++) { + await act(async () => { editor.dispatchEvent(new window.KeyboardEvent('keydown', { + key: 'z', metaKey: true, bubbles: true, cancelable: true, + })); }); + expect(currentContexts).toEqual([]); + await act(async () => { editor.dispatchEvent(new window.KeyboardEvent('keydown', { + key: 'z', metaKey: true, shiftKey: true, bubbles: true, cancelable: true, + })); }); + expect(editor.querySelector('[data-context-id="undo-file"]')).not.toBeNull(); + expect(currentContexts).toEqual([context]); + } + }); + + it('forgets undo and redo when the session or device activation changes with identical draft text', async () => { + const renderScope = async (historyScope: string, value: string) => { + await act(async () => root.render( {}} + contexts={emptyContexts} onRemoveContext={() => {}} + />)); + }; + await renderScope('local:session-a:1', ''); + const editor = container.querySelector('.rich-text-input') as HTMLDivElement; + editor.textContent = 'private'; + await act(async () => { editor.dispatchEvent(new window.InputEvent('input', { bubbles: true })); }); + await renderScope('local:session-b:1', 'private'); + await act(async () => { editor.dispatchEvent(new window.InputEvent('beforeinput', { + inputType: 'historyUndo', bubbles: true, cancelable: true, + })); }); + expect(editor.textContent).toBe('private'); + editor.textContent = 'private draft'; + await act(async () => { editor.dispatchEvent(new window.InputEvent('input', { bubbles: true })); }); + await act(async () => { editor.dispatchEvent(new window.InputEvent('beforeinput', { + inputType: 'historyUndo', bubbles: true, cancelable: true, + })); }); + expect(editor.textContent).toBe('private'); + await renderScope('peer:session-b:2', 'private'); + await act(async () => { editor.dispatchEvent(new window.InputEvent('beforeinput', { + inputType: 'historyRedo', bubbles: true, cancelable: true, + })); }); + expect(editor.textContent).toBe('private'); + }); + + it('starts a new undo step after moving the caret within a typing run', async () => { + const Controlled = () => { + const [value, setValue] = useState(''); + return {}} />; + }; + await act(async () => root.render()); + const editor = container.querySelector('.rich-text-input') as HTMLDivElement; + const insert = async (text: string, caret: number) => { + await act(async () => { + editor.dispatchEvent(new window.InputEvent('beforeinput', { + bubbles: true, cancelable: true, inputType: 'insertText', data: 'x', + })); + editor.textContent = text; + setCaret(editor, caret); + editor.dispatchEvent(new window.InputEvent('input', { bubbles: true, inputType: 'insertText' })); + }); + }; + await insert('abc', 3); + setCaret(editor, 0); + await insert('xabc', 1); + await act(async () => { editor.dispatchEvent(new window.KeyboardEvent('keydown', { + key: 'z', metaKey: true, bubbles: true, cancelable: true, + })); }); + expect(editor.textContent).toBe('abc'); + }); + it('removes leaked key characters from composer output while preserving joined emoji and IME text', async () => { const onChange = vi.fn(); await act(async () => root.render( {}} />)); @@ -973,6 +1182,21 @@ describeWithJsdom('RichTextInput external sync', () => { expect(inputRef.current!.textContent).toBe('Compare Docs× with Docs× please.'); }); + it('restores large paste capsules from a sent message presentation', async () => { + const placeholder = '[Pasted content 12 chars]'; + const inputRef = createRef(); + await act(async () => root.render( {}} contexts={emptyContexts} onRemoveContext={() => {}} />)); + await act(async () => { + inputRef.current!.restoreComposerPresentation!( + { version: 1, segments: [{ kind: 'text', text: `Review ${placeholder} now` }] }, + { largePastes: { [placeholder]: 'pasted body' } }, + ); + }); + const capsule = inputRef.current!.querySelector('[data-large-paste-placeholder]'); + expect(capsule?.dataset.largePastePlaceholder).toBe(placeholder); + expect(composerPresentationToEditorText(inputRef.current!.getComposerPresentation!()!)).toBe(`Review ${placeholder} now`); + }); + it.each(['remove-button', 'Backspace'])('removes an MCP capsule atomically with %s', async method => { const onChange = vi.fn(); const reference = createMcpPromptReference({ serverName: 'Docs', serverId: 'docs' }); diff --git a/src/web-ui/src/flow_chat/components/RichTextInput.tsx b/src/web-ui/src/flow_chat/components/RichTextInput.tsx index e85f3b1870..34d83b9fc6 100644 --- a/src/web-ui/src/flow_chat/components/RichTextInput.tsx +++ b/src/web-ui/src/flow_chat/components/RichTextInput.tsx @@ -10,6 +10,13 @@ import { MessageCircle, Plug } from 'lucide-react'; import { useTranslation } from 'react-i18next'; import type { ContextItem } from '../../shared/types/context'; import { getRichTextExternalSyncAction } from './richTextInputSync'; +import { splitLargePasteText } from '../utils/largePasteMetadata'; +import { + classifyRichTextHistoryInput, + RichTextUndoHistory, + shouldStartRichTextHistoryGroup, + type RichTextHistoryEdit, +} from './richTextInputHistory'; import { getWidgetPromptReferenceMatches, parseWidgetPromptReferenceToken, @@ -52,6 +59,70 @@ const MCP_REFERENCE_BADGE_ICON = renderToStaticMarkup( const EMPTY_PENDING_LARGE_PASTES: Record = Object.freeze({}); const LARGE_PASTE_CARET_ANCHOR = '\u200B'; +interface ComposerHistorySnapshot { + segments: ComposerPresentationSegment[]; + /** Large paste bodies referenced by the segments, keyed by placeholder. */ + largePastes: Record; + /** Caret position measured in composer text (capsules count as their tag). */ + caret: number; +} + +const EMPTY_HISTORY_SNAPSHOT: ComposerHistorySnapshot = { segments: [], largePastes: {}, caret: 0 }; + +function getComposerSegmentsLength(segments: readonly ComposerPresentationSegment[]): number { + return segments.reduce((length, segment) => length + ( + segment.kind === 'text' ? segment.text.length + : segment.kind === 'context' ? segment.tag.length + : segment.token.length + ), 0); +} + +function composerSegmentKey(segment: ComposerPresentationSegment): string { + if (segment.kind === 'text') return `t:${segment.text}`; + if (segment.kind === 'context') return `c:${segment.context.id}:${segment.tag}`; + return `i:${segment.token}`; +} + +function isSameComposerHistorySnapshot(a: ComposerHistorySnapshot, b: ComposerHistorySnapshot): boolean { + return a.segments.length === b.segments.length + && a.segments.every((segment, index) => composerSegmentKey(segment) === composerSegmentKey(b.segments[index])) + && Object.keys(a.largePastes).length === Object.keys(b.largePastes).length + && Object.entries(a.largePastes).every(([placeholder, body]) => b.largePastes[placeholder] === body); +} + +/** Places the caret in a flat editor rendered from history segments. */ +function setComposerCaretOffset(editor: HTMLElement, offset: number): void { + const selection = window.getSelection(); + if (!selection) return; + let remaining = Math.max(offset, 0); + const children = Array.from(editor.childNodes); + for (let index = 0; index < children.length; index += 1) { + const node = children[index]; + if (node.nodeType === Node.TEXT_NODE) { + const length = node.textContent?.length ?? 0; + if (remaining <= length) { + selection.collapse(node, remaining); + return; + } + remaining -= length; + continue; + } + if (remaining === 0) { + selection.collapse(editor, index); + return; + } + const length = node instanceof HTMLElement + ? (node.dataset.tagFormat ?? node.textContent ?? '').length + : 0; + if (remaining <= length) { + selection.collapse(editor, index + 1); + return; + } + remaining -= length; + } + selection.collapse(editor, children.length); +} + function getEditorBoundaryOffset(editor: HTMLElement, container: Node, offset: number): number | null { if (container === editor) { return offset >= 0 && offset <= editor.childNodes.length ? offset : null; @@ -93,7 +164,10 @@ export interface InlineTriggerState { export type RichTextInputElement = HTMLDivElement & { getComposerPresentation?: () => ComposerPresentation | null; - restoreComposerPresentation?: (presentation: ComposerPresentation) => void; + restoreComposerPresentation?: ( + presentation: ComposerPresentation, + options?: { largePastes?: Readonly> }, + ) => void; insertTag?: (context: ContextItem) => void; insertContextTagReplacingTrigger?: (context: ContextItem) => void; replaceActiveContextTrigger?: (replacementText: string) => void; @@ -121,6 +195,8 @@ export interface RichTextInputProps pendingLargePastes?: Record; skillReferenceNames?: Readonly>; onUpdateLargePaste?: (placeholder: string, text: string) => string; + /** Restore the exact placeholder identities and bodies owned by an undo step. */ + onRestoreLargePastes?: (pastes: Record) => void; onRemoveLargePaste?: (placeholder: string) => void; onKeyDown?: (e: React.KeyboardEvent) => void; onCompositionStart?: () => void; @@ -131,7 +207,11 @@ export interface RichTextInputProps disabled?: boolean; className?: string; contexts: ContextItem[]; + /** Session and device activation identity; equal draft text must not share history. */ + historyScope?: string; onRemoveContext: (id: string) => void; + /** Re-adds contexts whose capsules come back through undo or redo. */ + onRestoreContexts?: (contexts: ContextItem[]) => void; /** Callback when the @ context-picker trigger changes. */ onContextTriggerStateChange?: (state: ContextTriggerState) => void; /** Callback when inline trigger state changes for / or $ */ @@ -282,6 +362,7 @@ export const RichTextInput = React.forwardRef void) | null>(null); + // Capsule insertion can precede the parent's batched context prop update. + // Keep the payload on the live element until serialization can read it. + const tagContextsRef = useRef(new WeakMap()); const closeContextPicker = useCallback(() => { if (!contextTriggerStateRef.current.isActive) { @@ -352,6 +438,7 @@ export const RichTextInput = React.forwardRef { const tag = document.createElement('span'); + tagContextsRef.current.set(tag, context); tag.className = 'rich-text-tag-pill'; tag.dataset.openbitfunComponent = 'rich-text-input'; tag.dataset.openbitfunPart = 'contextTag'; @@ -616,12 +703,7 @@ export const RichTextInput = React.forwardRef { - const editor = internalRef.current; - if (!editor) { - return null; - } - + const collectComposerSegments = useCallback((root: Node): ComposerPresentationSegment[] => { const contextsById = new Map(contexts.map(context => [context.id, context])); const segments: ComposerPresentationSegment[] = []; const appendText = (text: string) => appendComposerTextSegment(segments, sanitizeText(text)); @@ -649,7 +731,7 @@ export const RichTextInput = React.forwardRef { + const editor = internalRef.current; + if (!editor) { + return null; + } return { version: COMPOSER_PRESENTATION_VERSION, - segments, + segments: collectComposerSegments(editor), }; - }, [contexts, internalRef]); + }, [collectComposerSegments, internalRef]); - const restoreComposerPresentation = useCallback((presentation: ComposerPresentation) => { + const restoreComposerPresentation = useCallback(( + presentation: ComposerPresentation, + options?: { largePastes?: Readonly> }, + ) => { const editor = internalRef.current; if (!editor || presentation.version !== COMPOSER_PRESENTATION_VERSION) { return; } + // The parent sets the matching pending pastes in the same update; expose + // them now so the capsules open before that prop arrives. + const largePastes = options?.largePastes; + if (largePastes) { + largePasteValuesRef.current = { ...largePasteValuesRef.current, ...largePastes }; + } const fragment = document.createDocumentFragment(); + const appendTextWithMcpReferences = (text: string) => { + let cursor = 0; + for (const match of getMcpPromptReferenceMatches(text)) { + fragment.appendChild(document.createTextNode(text.slice(cursor, match.start))); + fragment.appendChild(createMcpReferenceElement(match.token) ?? document.createTextNode(match.token)); + cursor = match.end; + } + fragment.appendChild(document.createTextNode(text.slice(cursor))); + }; + for (const segment of presentation.segments) { if (segment.kind === 'text') { - let cursor = 0; - for (const match of getMcpPromptReferenceMatches(segment.text)) { - fragment.appendChild(document.createTextNode(segment.text.slice(cursor, match.start))); - fragment.appendChild(createMcpReferenceElement(match.token) ?? document.createTextNode(match.token)); - cursor = match.end; + for (const part of splitLargePasteText(segment.text, largePastes)) { + if (part.kind === 'paste') { + fragment.appendChild(createLargePasteElement(part.placeholder)); + } else { + appendTextWithMcpReferences(part.text); + } } - fragment.appendChild(document.createTextNode(segment.text.slice(cursor))); } else if (segment.kind === 'context') { if (segment.context.type !== 'conversation-excerpt') { fragment.appendChild(createTagElement(segment.context)); @@ -747,11 +856,14 @@ export const RichTextInput = React.forwardRef { + const buildInlineTokenFragment = useCallback(( + text: string, + largePastePlaceholders: readonly string[], + ): DocumentFragment => { const fragment = document.createDocumentFragment(); - const largePasteMatches = Object.keys(pendingLargePastes).flatMap((placeholder) => { + const largePasteMatches = largePastePlaceholders.flatMap((placeholder) => { const matches: Array<{ start: number; end: number; @@ -790,11 +902,6 @@ export const RichTextInput = React.forwardRef a.start - b.start || b.end - a.end); - if (matches.length === 0) { - editor.textContent = text; - return; - } - let cursor = 0; for (const match of matches) { if (match.start < cursor) continue; @@ -819,16 +926,19 @@ export const RichTextInput = React.forwardRef { + editor.replaceChildren(buildInlineTokenFragment(text, Object.keys(pendingLargePastes))); + }, [buildInlineTokenFragment, pendingLargePastes]); + /** Map textContent offsets to a DOM Range to replace only the @ span. */ const getRangeByTextOffsets = useCallback((root: Node, start: number, end: number): Range | null => { let current = 0; @@ -1033,6 +1143,75 @@ export const RichTextInput = React.forwardRef { + const editor = internalRef.current; + if (!editor) return null; + const segments = collectComposerSegments(editor); + const largePastes: Record = {}; + for (const element of editor.querySelectorAll('[data-large-paste-placeholder]')) { + const placeholder = element.dataset.largePastePlaceholder; + const text = placeholder ? largePasteValuesRef.current[placeholder] : undefined; + if (placeholder && text !== undefined) largePastes[placeholder] = text; + } + + let caret = getComposerSegmentsLength(segments); + const selection = window.getSelection(); + const range = selection?.rangeCount ? selection.getRangeAt(0) : null; + if (range && editor.contains(range.endContainer)) { + const prefix = document.createRange(); + prefix.selectNodeContents(editor); + prefix.setEnd(range.endContainer, range.endOffset); + const holder = document.createElement('div'); + holder.appendChild(prefix.cloneContents()); + caret = Math.min(caret, getComposerSegmentsLength(collectComposerSegments(holder))); + } + return { segments, largePastes, caret }; + }, [collectComposerSegments, internalRef]); + + // Read through a ref so history resets never re-run the external value sync. + const captureHistorySnapshotRef = useRef(captureHistorySnapshot); + captureHistorySnapshotRef.current = captureHistorySnapshot; + const historyRef = useRef | null>(null); + const pendingHistoryEditRef = useRef(null); + const lastHistoryEditRef = useRef(null); + const lastHistorySelectionRef = useRef<{ node: Node | null; offset: number } | null>(null); + const applyingHistoryRef = useRef(false); + + const getHistory = useCallback(() => { + if (!historyRef.current) { + historyRef.current = new RichTextUndoHistory( + EMPTY_HISTORY_SNAPSHOT, + isSameComposerHistorySnapshot, + ); + } + return historyRef.current; + }, []); + + /** Make the current DOM the history baseline, e.g. after an external value sync. */ + const resetHistory = useCallback(() => { + getHistory().reset(captureHistorySnapshotRef.current() ?? EMPTY_HISTORY_SNAPSHOT); + pendingHistoryEditRef.current = null; + lastHistoryEditRef.current = null; + }, [getHistory]); + + const recordHistory = useCallback(() => { + if (applyingHistoryRef.current) return; + const snapshot = captureHistorySnapshot(); + if (!snapshot) return; + // No `beforeinput` means a programmatic change (capsule insert, paste + // handler, picker), which always gets its own undo step. + const edit = pendingHistoryEditRef.current; + pendingHistoryEditRef.current = null; + const startGroup = shouldStartRichTextHistoryGroup(lastHistoryEditRef.current, edit); + if (getHistory().record(snapshot, startGroup)) { + lastHistoryEditRef.current = edit; + } + const selection = window.getSelection(); + lastHistorySelectionRef.current = selection + ? { node: selection.focusNode, offset: selection.focusOffset } + : null; + }, [captureHistorySnapshot, getHistory]); + const handleInput = useCallback(() => { if (isComposingRef.current) return; @@ -1086,18 +1265,103 @@ export const RichTextInput = React.forwardRef element.dataset.contextId) .filter((id): id is string => !!id) ); - const visibleContexts = contexts.filter(context => visibleContextIds.has(context.id)); + const visibleContextsById = new Map(contexts + .filter(context => visibleContextIds.has(context.id)) + .map(context => [context.id, context])); + for (const element of internalRef.current?.querySelectorAll('[data-context-id]') ?? []) { + const context = tagContextsRef.current.get(element); + if (context && !visibleContextsById.has(context.id)) visibleContextsById.set(context.id, context); + } + const visibleContexts = Array.from(visibleContextsById.values()); onChange(textContent, visibleContexts); + recordHistory(); // Ensure detection runs after DOM updates requestAnimationFrame(() => { detectActiveTrigger(); }); - }, [contexts, detectActiveTrigger, extractTextContent, getCursorOffset, internalRef, onChange, setCursorOffset]); + }, [contexts, detectActiveTrigger, extractTextContent, getCursorOffset, internalRef, onChange, recordHistory, setCursorOffset]); triggerSyncRef.current = handleInput; + const applyHistorySnapshot = useCallback((snapshot: ComposerHistorySnapshot) => { + const editor = internalRef.current; + if (!editor) return; + + // Large pastes and contexts removed after the snapshot are restored with + // the text that references them; a renamed placeholder is rewritten. + const placeholderRenames = new Map(); + if (onRestoreLargePastes) { + onRestoreLargePastes({ ...snapshot.largePastes }); + } else { + for (const [placeholder, text] of Object.entries(snapshot.largePastes)) { + if (largePasteValuesRef.current[placeholder] === text) continue; + const nextPlaceholder = onUpdateLargePaste?.(placeholder, text) ?? placeholder; + if (nextPlaceholder !== placeholder) placeholderRenames.set(placeholder, nextPlaceholder); + } + } + largePasteValuesRef.current = Object.fromEntries(Object.entries(snapshot.largePastes).map( + ([placeholder, text]) => [placeholderRenames.get(placeholder) ?? placeholder, text], + )); + const currentContextIds = new Set(contexts.map(context => context.id)); + const missingContexts = snapshot.segments.flatMap(segment => ( + segment.kind === 'context' && !currentContextIds.has(segment.context.id) ? [segment.context] : [] + )); + if (missingContexts.length > 0) { + onRestoreContexts?.(missingContexts); + } + + const placeholders = Object.keys(snapshot.largePastes).map( + placeholder => placeholderRenames.get(placeholder) ?? placeholder, + ); + const fragment = document.createDocumentFragment(); + for (const segment of snapshot.segments) { + if (segment.kind === 'text') { + const text = splitLargePasteText(segment.text, snapshot.largePastes) + .map(part => part.kind === 'text' ? part.text : placeholderRenames.get(part.placeholder) ?? part.placeholder) + .join(''); + fragment.appendChild(buildInlineTokenFragment(text, placeholders)); + } else if (segment.kind === 'context') { + fragment.appendChild(createTagElement(segment.context)); + } else { + fragment.appendChild(createInlineTokenElement(segment.token) ?? document.createTextNode(segment.token)); + } + } + + applyingHistoryRef.current = true; + try { + editor.replaceChildren(fragment); + editor.focus(); + setComposerCaretOffset(editor, snapshot.caret); + handleInput(); + } finally { + applyingHistoryRef.current = false; + } + pendingHistoryEditRef.current = null; + lastHistoryEditRef.current = null; + }, [ + buildInlineTokenFragment, + contexts, + createInlineTokenElement, + createTagElement, + handleInput, + internalRef, + onRestoreContexts, + onRestoreLargePastes, + onUpdateLargePaste, + ]); + + const undoHistory = useCallback(() => { + const snapshot = getHistory().undo(); + if (snapshot) applyHistorySnapshot(snapshot); + }, [applyHistorySnapshot, getHistory]); + + const redoHistory = useCallback(() => { + const snapshot = getHistory().redo(); + if (snapshot) applyHistorySnapshot(snapshot); + }, [applyHistorySnapshot, getHistory]); + /** * Inserts pasted text at the caret, rebuilding capsule elements for the * inline tokens it carries. Returns false when the text has no token, so the @@ -1199,6 +1463,8 @@ export const RichTextInput = React.forwardRef { + const editor = internalRef.current; + if (!editor) return; + const handleBeforeInput = (event: InputEvent) => { + if (event.inputType === 'historyUndo' || event.inputType === 'historyRedo') { + // Native undo cannot see programmatic capsule edits; use the owned history. + event.preventDefault(); + if (event.inputType === 'historyUndo') undoHistory(); + else redoHistory(); + return; + } + if (isComposingRef.current) return; + const selection = window.getSelection(); + const previousSelection = lastHistorySelectionRef.current; + if (selection && ( + !selection.isCollapsed + || selection.focusNode !== previousSelection?.node + || selection.focusOffset !== previousSelection?.offset + )) { + // Typing at a different location (or replacing a selection) is a new edit. + lastHistoryEditRef.current = null; + } + const { kind, data } = classifyRichTextHistoryInput(event.inputType, event.data); + pendingHistoryEditRef.current = { kind, data, at: Date.now() }; + }; + editor.addEventListener('beforeinput', handleBeforeInput); + return () => editor.removeEventListener('beforeinput', handleBeforeInput); + }, [internalRef, redoHistory, undoHistory]); // Insert tag at cursor const insertTagAtCursor = useCallback((context: ContextItem) => { @@ -1566,9 +1874,12 @@ export const RichTextInput = React.forwardRef { + restoreComposerPresentation(presentation, options); + resetHistory(); + }; } - }, [appendInlineTokenAtEnd, buildComposerPresentation, closeContextPicker, closeInlineTrigger, insertContextTagReplacingTrigger, insertTagAtCursor, openContextPicker, replaceActiveContextTrigger, replaceActiveInlineTrigger, restoreComposerPresentation, internalRef]); + }, [appendInlineTokenAtEnd, buildComposerPresentation, closeContextPicker, closeInlineTrigger, insertContextTagReplacingTrigger, insertTagAtCursor, openContextPicker, replaceActiveContextTrigger, replaceActiveInlineTrigger, resetHistory, restoreComposerPresentation, internalRef]); // Initialize and sync value changes from external sources. // This editor is effectively controlled by comparing the parent's value @@ -1595,11 +1906,13 @@ export const RichTextInput = React.forwardRef { @@ -1614,7 +1927,7 @@ export const RichTextInput = React.forwardRef { @@ -1644,6 +1957,10 @@ export const RichTextInput = React.forwardRef { + resetHistory(); + }, [historyScope, resetHistory]); + const handleFocus = useCallback(() => { setIsFocused(true); onFocus?.(); @@ -1662,6 +1979,8 @@ export const RichTextInput = React.forwardRef { isComposingRef.current = true; + // Each IME commit is its own undo step. + pendingHistoryEditRef.current = { kind: 'composition', data: null, at: Date.now() }; onCompositionStart?.(); }, [onCompositionStart]); @@ -1698,6 +2017,7 @@ export const RichTextInput = React.forwardRef [data-openbitfun-part='icon'] { display: contents; } } + +.user-message-item__large-paste-text { + min-height: 280px; + font-family: var(--openbitfun-type-code-md-font-family); +} diff --git a/src/web-ui/src/flow_chat/components/modern/UserMessageItem.test.tsx b/src/web-ui/src/flow_chat/components/modern/UserMessageItem.test.tsx index b8ecc95668..ebe493a61c 100644 --- a/src/web-ui/src/flow_chat/components/modern/UserMessageItem.test.tsx +++ b/src/web-ui/src/flow_chat/components/modern/UserMessageItem.test.tsx @@ -310,6 +310,56 @@ describe('UserMessageItem steering tag', () => { expect(navigator.clipboard.writeText).toHaveBeenCalledWith(text); }); + it('stays expanded when the pointer moves outside the bubble to its actions', () => { + const text = 'Line one\nLine two\nLine three\nLine four'; + act(() => root.render( + + + , + )); + + const content = container.querySelector('[data-testid="chat-user-message-content"]')!; + act(() => content.click()); + expect(content.title).toBe('message.clickToCollapse'); + + const copyButton = container.querySelector('.user-message-item__copy-btn')!; + act(() => { + copyButton.dispatchEvent(new dom.window.MouseEvent('mousedown', { bubbles: true })); + document.body.dispatchEvent(new dom.window.MouseEvent('mousedown', { bubbles: true })); + }); + expect(content.title).toBe('message.clickToCollapse'); + + act(() => content.click()); + expect(content.title).toBe('message.clickToExpand'); + }); + + it('shows, opens, and copies stored large paste content instead of only its placeholder', async () => { + const placeholder = '[Pasted content 12 chars]'; + act(() => root.render( + + + , + )); + + const capsule = container.querySelector('.message-reference-capsule--large-paste')!; + expect(capsule.textContent).toBe(placeholder); + act(() => capsule.click()); + const viewer = document.querySelector('.user-message-item__large-paste-text textarea, textarea.user-message-item__large-paste-text'); + expect(viewer?.value).toBe('pasted body'); + expect(viewer?.readOnly).toBe(true); + + await act(async () => container.querySelector('.user-message-item__copy-btn')!.click()); + expect(navigator.clipboard.writeText).toHaveBeenCalledWith('Review pasted body please'); + }); + it('uses the shared image dialog without changing image or background click behavior', () => { act(() => root.render( diff --git a/src/web-ui/src/flow_chat/components/modern/UserMessageItem.tsx b/src/web-ui/src/flow_chat/components/modern/UserMessageItem.tsx index ffb286faa7..db1e80af3e 100644 --- a/src/web-ui/src/flow_chat/components/modern/UserMessageItem.tsx +++ b/src/web-ui/src/flow_chat/components/modern/UserMessageItem.tsx @@ -27,7 +27,7 @@ import { globalEventBus } from '@/infrastructure/event-bus'; import { shouldIgnoreCardToggleClick } from '@/shared/utils/textSelection'; import { observeElementResize } from '@/shared/utils/sharedResizeObserver'; import { formatContextForPrompt } from '@/shared/utils/contextPrompt'; -import { Button, Dialog, DialogClose, Tooltip, Icon, IconButton, MenuItem, MenuPopover, type MenuEntry, type MenuItemProps } from '@openbitfun/ui'; +import { Button, Dialog, DialogBody, DialogClose, DialogFooter, DialogHeader, DialogHeading, DialogTitle, Textarea, Tooltip, Icon, IconButton, MenuItem, MenuPopover, type MenuEntry, type MenuItemProps } from '@openbitfun/ui'; import { confirmDanger } from '@/infrastructure/confirm-dialog'; import { ToolProcessingDots } from '@openbitfun/ui/flow-chat'; import { UserMessageEditComposer } from './UserMessageEditComposer'; @@ -60,6 +60,8 @@ import { restoreImageContextsFromPayload } from '../../utils/imageContextRestora import { writeComposerClipboardPayload } from '../../utils/composerClipboard'; import { buildImagePayload } from '../../utils/imagePayload'; import { UserMessagePresentationContent } from './UserMessagePresentationContent'; +import { UserMessageLargePasteContext } from './userMessageLargePasteContext'; +import { expandLargePastes, readLargePastesMetadata } from '../../utils/largePasteMetadata'; import { splitUserMessagePreview } from './userMessagePreview'; import { UserMessageImage } from './UserMessageImage'; import { useSubmittedMessageMotion } from './useSubmittedMessageMotion'; @@ -178,6 +180,38 @@ export const UserMessageItem = React.memo( const presentation = parseComposerPresentation(message?.metadata?.composerPresentation); return hasComposerPresentationReferences(presentation) ? presentation : null; }, [message?.metadata?.composerPresentation]); + const largePastes = useMemo( + () => readLargePastesMetadata(message?.metadata), + [message?.metadata], + ); + // Edit works on the real text: the edit composer has no paste store, and an + // unchanged edit must still compare equal to the original. + const editableContent = useMemo( + () => expandLargePastes(messageContent, largePastes), + [largePastes, messageContent], + ); + const editablePresentation = useMemo(() => ( + composerPresentation && largePastes + ? { + ...composerPresentation, + segments: composerPresentation.segments.map(segment => ( + segment.kind === 'text' + ? { ...segment, text: expandLargePastes(segment.text, largePastes) } + : segment + )), + } + : composerPresentation + ), [composerPresentation, largePastes]); + const [openLargePaste, setOpenLargePaste] = useState(null); + const [largePasteCopied, setLargePasteCopied] = useState(false); + const largePasteContextValue = useMemo(() => (largePastes ? { + largePastes, + openLargePaste: (placeholder: string) => { + setLargePasteCopied(false); + setOpenLargePaste(placeholder); + }, + } : null), [largePastes]); + const openLargePasteText = openLargePaste ? largePastes?.[openLargePaste] ?? null : null; const messageImages = useMemo(() => message?.images ?? [], [message?.images]); const restoredComposerContexts = useMemo(() => [ ...(composerPresentation ? composerPresentationContexts(composerPresentation) : []), @@ -329,15 +363,15 @@ export const UserMessageItem = React.memo( return cleaned; }, [isThreadGoalContinuationCheck, messageContent, messageImages]); - const copyText = composerPresentation + const copyText = expandLargePastes(composerPresentation ? composerPresentationToAccessibleText(composerPresentation) - : messageContent; + : messageContent, largePastes); // The readable value stays in text/plain while the canonical token text // rides along in the HTML flavor, so pasting a copied message back into the // composer rebuilds its capsules instead of leaving their source text. - const copyTokens = composerPresentation + const copyTokens = expandLargePastes(composerPresentation ? composerPresentationToClipboardText(composerPresentation) - : messageContent; + : messageContent, largePastes); const messagePreview = useMemo(() => splitUserMessagePreview(composerPresentation ?? { version: 1, @@ -384,6 +418,16 @@ export const UserMessageItem = React.memo( } }, [copyText, copyTokens]); + const handleCopyLargePaste = useCallback(async () => { + if (openLargePasteText === null) return; + try { + await navigator.clipboard.writeText(openLargePasteText); + setLargePasteCopied(true); + } catch (error) { + log.error('Failed to copy pasted content', error); + } + }, [openLargePasteText]); + const handleRollback = useCallback(async () => { if (!canRollback || !resolvedSessionId) return; @@ -422,6 +466,7 @@ export const UserMessageItem = React.memo( content: composerContent, contexts: restoredComposerContexts, ...(composerPresentation ? { composerPresentation } : {}), + ...(largePastes ? { largePastes } : {}), }); } @@ -430,12 +475,12 @@ export const UserMessageItem = React.memo( log.error('Rollback failed', error); notificationService.error(`${t('message.rollbackFailed')}: ${error instanceof Error ? error.message : String(error)}`); } - }, [actionTurnIndex, canRollback, composerPresentation, resolvedSessionId, restoredComposerContexts, t, turnId, messageContent]); + }, [actionTurnIndex, canRollback, composerPresentation, largePastes, resolvedSessionId, restoredComposerContexts, t, turnId, messageContent]); const handleBeginEdit = useCallback(() => { if (!canEdit) return; - beginEdit(turnId, messageContent); - }, [beginEdit, canEdit, messageContent, turnId]); + beginEdit(turnId, editableContent); + }, [beginEdit, canEdit, editableContent, turnId]); const actionMenuItems: MenuEntry[] = [ ...(canShowEditAction ? [{ @@ -457,11 +502,11 @@ export const UserMessageItem = React.memo( const handleSubmitEdit = useCallback(async (submittedPresentation?: ComposerPresentation) => { if (!resolvedSessionId || actionTurnIndex < 0 || isEditSubmitting) return; - const editedPresentation = submittedPresentation ?? composerPresentation; + const editedPresentation = submittedPresentation ?? editablePresentation; const editedContent = editedPresentation ? composerPresentationToEditorText(editedPresentation) : editDraft.trim(); - if (!editedContent || editedContent === messageContent.trim()) { + if (!editedContent || editedContent === editableContent.trim()) { cancelEdit(); return; } @@ -488,7 +533,7 @@ export const UserMessageItem = React.memo( await editAndRerunUserMessage({ sessionId: resolvedSessionId, turnId, - originalContent: messageContent, + originalContent: editableContent, editedContent, agentType: currentSession?.mode, rerun: async (content, agentType, sessionMutationLeaseId) => { @@ -532,11 +577,11 @@ export const UserMessageItem = React.memo( }, [ cancelEdit, actionTurnIndex, - composerPresentation, currentSession?.mode, editDraft, + editableContent, + editablePresentation, isEditSubmitting, - messageContent, restoredImageContexts, resolvedSessionId, setEditSubmitting, @@ -564,11 +609,12 @@ export const UserMessageItem = React.memo( content: messageContent, contexts: restoredComposerContexts, ...(composerPresentation ? { composerPresentation } : {}), + ...(largePastes ? { largePastes } : {}), }); if (submissionPhase === 'failed' && resolvedSessionId) { finishSubmittedMessagePreview(getActiveSurfaceScope(), resolvedSessionId, turnId); } - }, [composerPresentation, messageContent, restoredComposerContexts, submissionPhase, resolvedSessionId, turnId]); + }, [composerPresentation, largePastes, messageContent, restoredComposerContexts, submissionPhase, resolvedSessionId, turnId]); const handleOpenUsageReport = useCallback((report: SessionUsageReport, initialTab?: SessionUsagePanelTab) => { void import('../../services/openSessionUsageReport').then(({ openSessionUsagePanel }) => { @@ -584,22 +630,6 @@ export const UserMessageItem = React.memo( }); }, [currentSession?.sessionId, currentSession?.workspacePath, messageContent, resolvedSessionId, t]); - // Collapse when clicking outside. - useEffect(() => { - if (!expanded) return; - - const handleClickOutside = (e: MouseEvent) => { - if (containerRef.current && !containerRef.current.contains(e.target as Node)) { - setExpanded(false); - } - }; - - document.addEventListener('mousedown', handleClickOutside); - return () => { - document.removeEventListener('mousedown', handleClickOutside); - }; - }, [expanded]); - // Avoid zero-size errors by rendering a placeholder instead of null. if (!message) { return
; @@ -642,16 +672,20 @@ export const UserMessageItem = React.memo(
) : null; - const messageTextContent = messagePreview.overflow ? ( - <> - - - - - - - - ) : ; + const messageTextContent = ( + + {messagePreview.overflow ? ( + <> + + + + + + + + ) : } + + ); return (
@@ -680,7 +714,7 @@ export const UserMessageItem = React.memo( onChange={setEditDraft} onSubmit={handleSubmitEdit} onCancel={cancelEdit} - presentation={composerPresentation} + presentation={editablePresentation} workspacePath={currentSession?.workspacePath} workspaceId={currentSession?.workspaceId} remoteConnectionId={ @@ -779,6 +813,35 @@ export const UserMessageItem = React.memo( Preview e.stopPropagation()} /> )} + {openLargePasteText !== null && ( + { if (!open) setOpenLargePaste(null); }} + > + + + {t('input.largePasteDialogTitle')} + + + + +