From 5d8b0cdd0e3f6de496aa251c1fa71726313c3e80 Mon Sep 17 00:00:00 2001 From: Bob Lee Date: Thu, 5 Nov 2026 16:26:13 +0800 Subject: [PATCH 1/4] fix(web-ui): fix composer undo, sent large pastes, and bubble collapse - Own the composer undo history: WebKit coalesces a typing run, including IME commits, into one native undo step, so a single Cmd+Z cleared the whole draft. Steps now break at words, pauses, IME commits, edit-kind changes, and programmatic capsule inserts; capsules, contexts, and large pastes are restored on undo/redo. - Keep large paste bodies in user message metadata (`largePastes`) so the sent placeholder opens a read-only viewer, and copy, edit, rollback, and fill-to-input use the real text. Older builds ignore the key. - Expand same-length paste placeholders longest-first so `[... N] #2` is no longer corrupted by the `[... N]` prefix. - Stop collapsing an expanded user message on outside mousedown, which moved the copy/edit actions before the click landed. --- .../src/generated/chat-styles.css | 5 + .../src/flow_chat/components/ChatInput.tsx | 31 +- .../components/RichTextInput.test.tsx | 73 ++++ .../flow_chat/components/RichTextInput.tsx | 336 ++++++++++++++++-- .../modern/MessageReferenceCapsule.scss | 16 + .../components/modern/UserMessageItem.scss | 5 + .../modern/UserMessageItem.test.tsx | 50 +++ .../components/modern/UserMessageItem.tsx | 145 +++++--- .../modern/UserMessagePresentationContent.tsx | 52 ++- .../modern/userMessageLargePasteContext.ts | 9 + .../components/richTextInputHistory.test.ts | 87 +++++ .../components/richTextInputHistory.ts | 136 +++++++ .../flow_chat/hooks/useMessageSender.test.tsx | 3 + .../src/flow_chat/hooks/useMessageSender.ts | 8 +- .../utils/largePasteMetadata.test.ts | 37 ++ .../src/flow_chat/utils/largePasteMetadata.ts | 79 ++++ 16 files changed, 982 insertions(+), 90 deletions(-) create mode 100644 src/web-ui/src/flow_chat/components/modern/userMessageLargePasteContext.ts create mode 100644 src/web-ui/src/flow_chat/components/richTextInputHistory.test.ts create mode 100644 src/web-ui/src/flow_chat/components/richTextInputHistory.ts create mode 100644 src/web-ui/src/flow_chat/utils/largePasteMetadata.test.ts create mode 100644 src/web-ui/src/flow_chat/utils/largePasteMetadata.ts 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..2a893b209a 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; @@ -2369,15 +2373,9 @@ export const ChatInput: React.FC = ({ )); }, [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 +2420,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 +2446,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 +2473,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 +2493,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(() => { @@ -6677,6 +6681,7 @@ 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..89e36c37c4 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,64 @@ 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('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 +1031,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..cd4d02ec46 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,68 @@ 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])); +} + +/** 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 +162,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; @@ -132,6 +204,8 @@ export interface RichTextInputProps className?: string; contexts: ContextItem[]; 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 $ */ @@ -293,6 +367,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)); @@ -706,29 +776,56 @@ 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 +844,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 +890,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 +914,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 +1131,70 @@ 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 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; + } + }, [captureHistorySnapshot, getHistory]); + const handleInput = useCallback(() => { if (isComposingRef.current) return; @@ -1089,15 +1251,86 @@ export const RichTextInput = React.forwardRef visibleContextIds.has(context.id)); 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(); + 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); + } + 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') { + let text = segment.text; + for (const [from, to] of placeholderRenames) { + text = text.split(from).join(to); + } + 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, + 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 @@ -1347,7 +1580,39 @@ 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 { 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 +1831,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 +1863,13 @@ export const RichTextInput = React.forwardRef { @@ -1614,7 +1884,7 @@ export const RichTextInput = React.forwardRef { @@ -1662,6 +1932,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]); diff --git a/src/web-ui/src/flow_chat/components/modern/MessageReferenceCapsule.scss b/src/web-ui/src/flow_chat/components/modern/MessageReferenceCapsule.scss index 6cf4afb67e..3792390d49 100644 --- a/src/web-ui/src/flow_chat/components/modern/MessageReferenceCapsule.scss +++ b/src/web-ui/src/flow_chat/components/modern/MessageReferenceCapsule.scss @@ -29,6 +29,22 @@ color: var(--openbitfun-color-content-primary); } +// Large pastes open a viewer, so the capsule is a button. +.message-reference-capsule--large-paste { + border-color: transparent; + font-family: inherit; + cursor: pointer; + + &:hover { + color: var(--openbitfun-color-content-primary); + } + + &:focus-visible { + outline: 2px solid var(--openbitfun-color-focus-ring); + outline-offset: 1px; + } +} + .message-reference-capsule__label, .user-message-item__reference-label { // Make the label (rather than the leading icon) supply the inline-flex baseline. diff --git a/src/web-ui/src/flow_chat/components/modern/UserMessageItem.scss b/src/web-ui/src/flow_chat/components/modern/UserMessageItem.scss index 0c69dde4eb..8d8cfee34e 100644 --- a/src/web-ui/src/flow_chat/components/modern/UserMessageItem.scss +++ b/src/web-ui/src/flow_chat/components/modern/UserMessageItem.scss @@ -528,3 +528,8 @@ &::before { content: none; } > [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')} + + + + +