Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions src/apps/miniapp-shell/src/generated/chat-styles.css
Original file line number Diff line number Diff line change
Expand Up @@ -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]) {
Expand Down
37 changes: 21 additions & 16 deletions src/web-ui/src/flow_chat/components/ChatInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -632,6 +633,9 @@ export const ChatInput: React.FC<ChatInputProps> = ({
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;
Expand Down Expand Up @@ -2364,20 +2368,12 @@ export const ChatInput: React.FC<ChatInputProps> = ({
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(
Expand Down Expand Up @@ -2422,6 +2418,7 @@ export const ChatInput: React.FC<ChatInputProps> = ({
/** Complete composer context replacement, including image attachments. */
contexts?: ContextItem[];
composerPresentation?: ComposerPresentation;
largePastes?: Record<string, string>;
onlyIfEmpty?: boolean;
mode?: 'replace' | 'append';
separator?: string;
Expand All @@ -2447,10 +2444,13 @@ export const ChatInput: React.FC<ChatInputProps> = ({
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;
}
Expand All @@ -2471,7 +2471,9 @@ export const ChatInput: React.FC<ChatInputProps> = ({
: 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);
}
Expand All @@ -2489,7 +2491,7 @@ export const ChatInput: React.FC<ChatInputProps> = ({
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(() => {
Expand Down Expand Up @@ -6662,11 +6664,13 @@ export const ChatInput: React.FC<ChatInputProps> = ({
))}
<RichTextInput
ref={richTextInputRef}
historyScope={`${deviceSurfaceScope.epoch}:${deviceSurfaceScope.key(effectiveTargetSessionId)}`}
value={inputState.value}
onChange={handleInputChange}
onLargePaste={createLargePastePlaceholder}
onPasteFiles={handleClipboardFiles}
pendingLargePastes={pendingLargePastes}
onRestoreLargePastes={replacePendingLargePastes}
skillReferenceNames={skillReferenceNames}
onUpdateLargePaste={updateLargePaste}
onRemoveLargePaste={removeLargePaste}
Expand All @@ -6677,6 +6681,7 @@ export const ChatInput: React.FC<ChatInputProps> = ({
disabled={!targetCanCompose || caps.transferInFlight || isInterruptedTurnRecoveryInFlight}
contexts={contexts}
onRemoveContext={removeContext}
onRestoreContexts={restoreContexts}
onContextTriggerStateChange={setContextTriggerState}
onInlineTriggerStateChange={setInlineTriggerState}
data-testid="chat-input-textarea"
Expand Down
224 changes: 224 additions & 0 deletions src/web-ui/src/flow_chat/components/RichTextInput.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
<RichTextInput
value={value}
onChange={(next, contexts) => { onChange(next, contexts); setValue(next); }}
contexts={emptyContexts}
onRemoveContext={() => {}}
/>
);
};
await act(async () => root.render(<Controlled />));
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<string, string> = {};
const Controlled = () => {
const [value, setValue] = useState('');
const [pastes, setPastes] = useState<Record<string, string>>({});
currentPastes = pastes;
return <RichTextInput
value={value}
onChange={(next) => {
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(<Controlled />));
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<RichTextInputElement>();
let add: () => void = () => {};
let currentContexts: ContextItem[] = [];
const Controlled = () => {
const [value, setValue] = useState('');
const [contexts, setContexts] = useState<ContextItem[]>([]);
currentContexts = contexts;
add = () => {
setContexts([context]);
inputRef.current?.insertTag?.(context);
};
return <RichTextInput
ref={inputRef}
value={value}
contexts={contexts}
onChange={(next, visible) => {
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(<Controlled />));
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(<RichTextInput
value={value} historyScope={historyScope} onChange={() => {}}
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 <RichTextInput value={value} onChange={setValue} contexts={emptyContexts} onRemoveContext={() => {}} />;
};
await act(async () => root.render(<Controlled />));
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(<RichTextInput value="" onChange={onChange} contexts={emptyContexts} onRemoveContext={() => {}} />));
Expand Down Expand Up @@ -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<RichTextInputElement>();
await act(async () => root.render(<RichTextInput ref={inputRef} value="" onChange={() => {}} 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<HTMLElement>('[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' });
Expand Down
Loading
Loading