mirror of
https://github.com/stablyai/orca.git
synced 2026-11-17 19:34:29 +00:00
fix(native-chat): make Shift+Enter start a new paragraph in the composer (#42607)
Shift+Enter inserted a hardBreak inside one paragraph, while paste, prompt recall and restored drafts already used one paragraph per line. ProseMirror handles triple-click, Mod-click and macOS Ctrl+A/Ctrl+E per paragraph, so on a message typed with Shift+Enter they all acted on the whole message. A small appendTransaction plugin now splits every hardBreak into a new paragraph in the same undo step, so Shift+Enter, rich-text drops and HTML pastes all produce paragraph lines. Saved drafts with hard breaks are split into paragraph lines when the editor adopts them. The placeholder and @agent spacing follow the per-paragraph shape. The NativeChatLineBoundaryKeys override from #42409 is no longer needed and is removed. Fixes #42606 Co-authored-by: Neil <neil@stably.ai>
This commit is contained in:
@@ -372,7 +372,7 @@ export function NativeChatComposerField({
|
||||
className={cn(
|
||||
'w-full bg-transparent px-2 py-1 text-sm outline-none',
|
||||
launch
|
||||
? 'min-h-7 max-h-[calc(6lh+0.5rem)] text-foreground placeholder:text-muted-foreground [&_p.is-editor-empty:first-child]:before:!h-auto [&_p.is-editor-empty:first-child]:before:w-full [&_p.is-editor-empty:first-child]:before:mr-[-100%]'
|
||||
? 'min-h-7 max-h-[calc(6lh+0.5rem)] text-foreground placeholder:text-muted-foreground [&_p.is-editor-empty:only-child]:before:!h-auto [&_p.is-editor-empty:only-child]:before:w-full [&_p.is-editor-empty:only-child]:before:mr-[-100%]'
|
||||
: 'min-h-12 max-h-[calc(8lh+0.5rem)] text-chat-foreground-strong placeholder:text-chat-foreground-faint pointer-coarse:min-h-14',
|
||||
'overflow-y-auto scrollbar-sleek',
|
||||
// Why: the editor is a contenteditable, which `:disabled` never matches.
|
||||
|
||||
+190
-21
@@ -3,10 +3,14 @@ import { readNativeChatDraftDocument } from '../../drafts/native-chat-draft-view
|
||||
import { createRef } from 'react'
|
||||
import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'
|
||||
import { afterEach, describe, expect, it, onTestFinished, vi } from 'vitest'
|
||||
import type { JSONContent } from '@tiptap/react'
|
||||
import type { Node as ProseMirrorNode } from '@tiptap/pm/model'
|
||||
import { AllSelection, NodeSelection, TextSelection, type Selection } from '@tiptap/pm/state'
|
||||
import { NativeChatPromptEditor } from './NativeChatPromptEditor'
|
||||
import type { NativeChatComposerInput } from './native-chat-composer-input'
|
||||
import { promptEditor } from './native-chat-prompt-editor.test-support'
|
||||
import { updateNativeChatComposerDraft } from '../../drafts/native-chat-composer-draft-store'
|
||||
import { serializeNativeChatAgentReferences } from '../pickers/native-chat-agent-reference-send'
|
||||
|
||||
afterEach(cleanup)
|
||||
|
||||
@@ -181,37 +185,202 @@ it('replaces the selection with literal pasted text as one undoable edit', async
|
||||
expect(input.value).toBe('hello world')
|
||||
})
|
||||
|
||||
it.each([
|
||||
['a', 4],
|
||||
['e', 7]
|
||||
])('moves Ctrl-%s on macOS to the edge of the hard-break line holding the caret', (key, offset) => {
|
||||
const pill: JSONContent = {
|
||||
type: 'nativeChatFileReference',
|
||||
attrs: { token: '@src/main.ts', path: '' }
|
||||
}
|
||||
|
||||
it.each<[string, (string | JSONContent)[][], (doc: ProseMirrorNode) => Selection, string, number]>([
|
||||
['at the caret', [['see please']], (doc) => TextSelection.create(doc, 5), 'see \n please', 5],
|
||||
[
|
||||
'in place of a selected pill',
|
||||
[['see ', pill, ' please']],
|
||||
(doc) => NodeSelection.create(doc, 5),
|
||||
'see \n please',
|
||||
5
|
||||
],
|
||||
['in place of everything', [['abc'], ['def']], (doc) => new AllSelection(doc), '\n', 1],
|
||||
[
|
||||
'in place of a whole selected line',
|
||||
[['abc'], ['def']],
|
||||
(doc) => NodeSelection.create(doc, 5),
|
||||
'abc\n\n',
|
||||
5
|
||||
]
|
||||
])('starts a new paragraph on Shift+Enter %s', (_name, lines, select, expected, caret) => {
|
||||
const { input, editor } = setup()
|
||||
act(() => {
|
||||
editor.commands.setContent({
|
||||
type: 'doc',
|
||||
content: lines.map((line) => ({
|
||||
type: 'paragraph',
|
||||
content: line.map((part) =>
|
||||
typeof part === 'string' ? { type: 'text', text: part } : part
|
||||
)
|
||||
}))
|
||||
})
|
||||
editor.view.dispatch(editor.state.tr.setSelection(select(editor.state.doc)))
|
||||
})
|
||||
act(() => {
|
||||
fireEvent.keyDown(editor.view.dom, { key: 'Enter', shiftKey: true })
|
||||
})
|
||||
expect(
|
||||
editor
|
||||
.getJSON()
|
||||
.content?.some((line) => line.content?.some((node) => node.type === 'hardBreak'))
|
||||
).toBe(false)
|
||||
expect([input.value, input.selectionStart]).toEqual([expected, caret])
|
||||
})
|
||||
|
||||
function mockMacPlatform(): void {
|
||||
const userAgent = vi.spyOn(navigator, 'userAgent', 'get').mockReturnValue('Macintosh')
|
||||
const platform = vi.spyOn(navigator, 'platform', 'get').mockReturnValue('MacIntel')
|
||||
onTestFinished(() => {
|
||||
userAgent.mockRestore()
|
||||
platform.mockRestore()
|
||||
})
|
||||
const { input, editor } = setup()
|
||||
}
|
||||
|
||||
function saveHardBreakDraft(scopeKey: string): string {
|
||||
const text = 'abc\ndef\nghi'
|
||||
updateNativeChatComposerDraft(
|
||||
scopeKey,
|
||||
{
|
||||
text,
|
||||
document: {
|
||||
type: 'doc',
|
||||
content: [
|
||||
{
|
||||
type: 'paragraph',
|
||||
content: [
|
||||
{ type: 'text', text: 'abc' },
|
||||
{ type: 'hardBreak' },
|
||||
{ type: 'text', text: 'def' },
|
||||
{ type: 'hardBreak' },
|
||||
{ type: 'text', text: 'ghi' }
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
'immediate'
|
||||
)
|
||||
return text
|
||||
}
|
||||
|
||||
it('splits a saved hard-break draft adopted through value into lines without an update', () => {
|
||||
const scopeKey = 'hard-break-draft-adopted'
|
||||
const inputRef = createRef<NativeChatComposerInput>()
|
||||
const onChange = vi.fn()
|
||||
const view = render(
|
||||
<NativeChatPromptEditor
|
||||
scopeKey={scopeKey}
|
||||
inputRef={inputRef}
|
||||
initialValue=""
|
||||
disabled={false}
|
||||
placeholder="Message"
|
||||
onChange={onChange}
|
||||
onSelect={vi.fn()}
|
||||
/>
|
||||
)
|
||||
const editor = promptEditor(within(view.container).getByRole('textbox'))
|
||||
const text = saveHardBreakDraft(scopeKey)
|
||||
act(() => {
|
||||
editor.commands.setContent({
|
||||
type: 'doc',
|
||||
content: [
|
||||
{
|
||||
type: 'paragraph',
|
||||
content: [
|
||||
{ type: 'text', text: 'abc' },
|
||||
{ type: 'hardBreak' },
|
||||
{ type: 'text', text: 'def' },
|
||||
{ type: 'hardBreak' },
|
||||
{ type: 'text', text: 'ghi' }
|
||||
]
|
||||
}
|
||||
]
|
||||
inputRef.current!.value = text
|
||||
})
|
||||
expect(editor.getJSON().content?.map((line) => line.content?.map((node) => node.type))).toEqual([
|
||||
['text'],
|
||||
['text'],
|
||||
['text']
|
||||
])
|
||||
expect([inputRef.current!.value, onChange.mock.calls.length]).toEqual([text, 0])
|
||||
})
|
||||
|
||||
it.each([
|
||||
['a', 4],
|
||||
['e', 7]
|
||||
])(
|
||||
'moves Ctrl-%s on macOS to the edge of the caret line in a saved hard-break draft',
|
||||
(key, offset) => {
|
||||
mockMacPlatform()
|
||||
const scopeKey = `hard-break-draft-${key}`
|
||||
const text = saveHardBreakDraft(scopeKey)
|
||||
const inputRef = createRef<NativeChatComposerInput>()
|
||||
const view = render(
|
||||
<NativeChatPromptEditor
|
||||
scopeKey={scopeKey}
|
||||
inputRef={inputRef}
|
||||
initialValue={text}
|
||||
disabled={false}
|
||||
placeholder="Message"
|
||||
onChange={vi.fn()}
|
||||
onSelect={vi.fn()}
|
||||
/>
|
||||
)
|
||||
const editor = promptEditor(within(view.container).getByRole('textbox'))
|
||||
const input = inputRef.current!
|
||||
input.setSelectionRange(6, 6)
|
||||
act(() => {
|
||||
fireEvent.keyDown(editor.view.dom, { key, ctrlKey: true })
|
||||
})
|
||||
expect([input.value, input.selectionStart, input.selectionEnd]).toEqual([text, offset, offset])
|
||||
}
|
||||
)
|
||||
|
||||
it.each([
|
||||
['a', 4],
|
||||
['e', 7]
|
||||
])('moves Ctrl-%s on macOS to the edge of the caret line after a rich-text drop', (key, offset) => {
|
||||
mockMacPlatform()
|
||||
const { input, editor } = setup()
|
||||
vi.spyOn(editor.view, 'posAtCoords').mockReturnValue({ pos: 1, inside: -1 })
|
||||
act(() => {
|
||||
fireEvent.drop(editor.view.dom, {
|
||||
dataTransfer: {
|
||||
types: ['text/html', 'text/plain'],
|
||||
getData: (format: string) =>
|
||||
format === 'text/html' ? '<p>abc<br>def<br>ghi</p>' : 'abc\ndef\nghi'
|
||||
}
|
||||
})
|
||||
})
|
||||
input.setSelectionRange(6, 6)
|
||||
expect(editor.getJSON().content?.map((line) => line.content?.map((node) => node.type))).toEqual([
|
||||
['text'],
|
||||
['text'],
|
||||
['text']
|
||||
])
|
||||
act(() => input.setSelectionRange(6, 6))
|
||||
act(() => {
|
||||
fireEvent.keyDown(editor.view.dom, { key, ctrlKey: true })
|
||||
})
|
||||
expect([input.selectionStart, input.selectionEnd]).toEqual([offset, offset])
|
||||
expect([input.value, input.selectionStart, input.selectionEnd]).toEqual([
|
||||
'abc\ndef\nghi',
|
||||
offset,
|
||||
offset
|
||||
])
|
||||
})
|
||||
|
||||
it('hides the placeholder on the first line of a blank multi-line draft', () => {
|
||||
const { input, editor } = setup()
|
||||
const root = editor.view.dom
|
||||
const placeholderLine = root.className.match(
|
||||
/\[&_([^\]]+)\]:before:content-\[attr\(data-placeholder\)\]/
|
||||
)?.[1]
|
||||
expect(placeholderLine).toBeDefined()
|
||||
const placeholderShown = () => root.querySelector(String(placeholderLine)) !== null
|
||||
expect(placeholderShown()).toBe(true)
|
||||
act(() => {
|
||||
fireEvent.keyDown(root, { key: 'Enter', shiftKey: true })
|
||||
})
|
||||
act(() => input.setSelectionRange(0, 0))
|
||||
expect([input.value, input.selectionStart]).toEqual(['\n', 0])
|
||||
expect(placeholderShown()).toBe(false)
|
||||
})
|
||||
|
||||
it('sends an agent mentioned at the end of a non-final line without a space before the newline', () => {
|
||||
const { input, editor } = setup('abc\ndef')
|
||||
act(() => input.setSelectionRange(3, 3))
|
||||
act(() => input.insertAgentReferences?.([{ label: 'Agent', address: 'term_agent', hostKey: '' }]))
|
||||
expect(serializeNativeChatAgentReferences(input.value, editor.getJSON())).toMatch(
|
||||
/^abc@Agent\ndef/
|
||||
)
|
||||
})
|
||||
|
||||
@@ -30,7 +30,7 @@ import {
|
||||
promptTextOffset,
|
||||
promptTextPosition
|
||||
} from './native-chat-prompt-document'
|
||||
import { promptTextContent } from './native-chat-prompt-document-text'
|
||||
import { promptParagraphLines, promptTextContent } from './native-chat-prompt-document-text'
|
||||
import type {
|
||||
NativeChatComposerInput,
|
||||
NativeChatPromptEditorProps
|
||||
@@ -38,7 +38,7 @@ import type {
|
||||
import { NativeChatImageRowProvider } from './NativeChatImageReferencePill'
|
||||
import { focusMountedNativeChatEditor, mountedEditorView } from './native-chat-mounted-editor-view'
|
||||
import { NativeChatUnkernedRunDecorations } from './native-chat-unkerned-run-decorations'
|
||||
import { NativeChatLineBoundaryKeys } from './native-chat-line-boundary-keys'
|
||||
import { NativeChatHardBreakParagraphs } from './native-chat-hard-break-paragraphs'
|
||||
|
||||
import { useNativeChatComposerMount } from '../focus/native-chat-composer-mount'
|
||||
|
||||
@@ -105,14 +105,16 @@ function NativePromptEditor({
|
||||
NativeChatFileReference,
|
||||
NativeChatImageReference,
|
||||
NativeChatUnkernedRunDecorations,
|
||||
NativeChatLineBoundaryKeys,
|
||||
NativeChatHardBreakParagraphs,
|
||||
// A disabled box still says why it is disabled, as the plain text box's placeholder does.
|
||||
Placeholder.configure({
|
||||
placeholder: () => placeholderRef.current,
|
||||
showOnlyWhenEditable: false
|
||||
})
|
||||
],
|
||||
content: adopted.current?.document || promptTextContent(initialValue),
|
||||
content: adopted.current?.document
|
||||
? promptParagraphLines(adopted.current.document)
|
||||
: promptTextContent(initialValue),
|
||||
editable: !disabled,
|
||||
editorProps: {
|
||||
attributes: {
|
||||
@@ -120,7 +122,7 @@ function NativePromptEditor({
|
||||
role: 'textbox',
|
||||
'aria-multiline': 'true',
|
||||
'aria-label': placeholder,
|
||||
class: `${className ?? ''} whitespace-pre-wrap break-words [&_p]:m-0 [&_p.is-editor-empty:first-child]:before:content-[attr(data-placeholder)] [&_p.is-editor-empty:first-child]:before:text-chat-foreground-faint [&_p.is-editor-empty:first-child]:before:float-left [&_p.is-editor-empty:first-child]:before:h-0 [&_p.is-editor-empty:first-child]:before:pointer-events-none`,
|
||||
class: `${className ?? ''} whitespace-pre-wrap break-words [&_p]:m-0 [&_p.is-editor-empty:only-child]:before:content-[attr(data-placeholder)] [&_p.is-editor-empty:only-child]:before:text-chat-foreground-faint [&_p.is-editor-empty:only-child]:before:float-left [&_p.is-editor-empty:only-child]:before:h-0 [&_p.is-editor-empty:only-child]:before:pointer-events-none`,
|
||||
...Object.fromEntries(Object.entries(events).filter(([key]) => key.startsWith('aria-')))
|
||||
},
|
||||
// Clipboard input is always literal text; only the picker and attachments create pills.
|
||||
|
||||
+5
-4
@@ -72,10 +72,11 @@ export function insertAgentReferences(
|
||||
if (references.length === 0) {
|
||||
return
|
||||
}
|
||||
const nextNode = editor.state.selection.$to.nodeAfter
|
||||
const hasRightSeparator = nextNode?.isText
|
||||
? /^\s/u.test(nextNode.text ?? '')
|
||||
: nextNode?.type.name === 'hardBreak'
|
||||
const { $to } = editor.state.selection
|
||||
const nextNode = $to.nodeAfter
|
||||
const endsNonFinalLine =
|
||||
!nextNode && $to.depth > 0 && $to.after(1) < editor.state.doc.content.size
|
||||
const hasRightSeparator = nextNode?.isText ? /^\s/u.test(nextNode.text ?? '') : endsNonFinalLine
|
||||
editor.view.dispatch(closeHistory(editor.state.tr))
|
||||
editor.commands.insertContent(
|
||||
references.flatMap((attrs, index) => [
|
||||
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
import { Extension } from '@tiptap/core'
|
||||
import { Plugin } from '@tiptap/pm/state'
|
||||
|
||||
// Why: a hard break keeps lines in one paragraph, which Tiptap's line keys and triple-click treat as one line; Shift+Enter, dropped <br> and adopted drafts get one paragraph per line like paste.
|
||||
export const NativeChatHardBreakParagraphs = Extension.create({
|
||||
name: 'nativeChatHardBreakParagraphs',
|
||||
addProseMirrorPlugins() {
|
||||
return [
|
||||
new Plugin({
|
||||
appendTransaction: (transactions, _oldState, state) => {
|
||||
if (!transactions.some((transaction) => transaction.docChanged)) {
|
||||
return null
|
||||
}
|
||||
const hardBreaks: number[] = []
|
||||
state.doc.descendants((node, pos) => {
|
||||
if (node.type.name === 'hardBreak') {
|
||||
hardBreaks.push(pos)
|
||||
}
|
||||
})
|
||||
if (hardBreaks.length === 0) {
|
||||
return null
|
||||
}
|
||||
const tr = state.tr
|
||||
for (const pos of hardBreaks.toReversed()) {
|
||||
tr.delete(pos, pos + 1).split(pos)
|
||||
}
|
||||
return tr
|
||||
}
|
||||
})
|
||||
]
|
||||
}
|
||||
})
|
||||
-45
@@ -1,45 +0,0 @@
|
||||
import { Extension, type Editor, type KeyboardShortcutCommand } from '@tiptap/core'
|
||||
import type { ResolvedPos } from '@tiptap/pm/model'
|
||||
import { isMacUserAgent } from '@/app-shell/platform/user-agent-platform'
|
||||
|
||||
function lineBoundary($pos: ResolvedPos, side: 'start' | 'end'): number {
|
||||
const blockStart = $pos.start()
|
||||
let boundary = side === 'start' ? blockStart : $pos.end()
|
||||
$pos.parent.forEach((child, offset) => {
|
||||
if (child.type.name !== 'hardBreak') {
|
||||
return
|
||||
}
|
||||
const at = blockStart + offset
|
||||
if (side === 'start' && at < $pos.pos) {
|
||||
boundary = at + child.nodeSize
|
||||
} else if (side === 'end' && at >= $pos.pos && at < boundary) {
|
||||
boundary = at
|
||||
}
|
||||
})
|
||||
return boundary
|
||||
}
|
||||
|
||||
function selectLineSide(editor: Editor, side: 'start' | 'end'): boolean {
|
||||
const { selection } = editor.state
|
||||
const $pos = side === 'start' ? selection.$from : selection.$to
|
||||
if (!$pos.parent.isTextblock) {
|
||||
return false
|
||||
}
|
||||
return editor.chain().setTextSelection(lineBoundary($pos, side)).scrollIntoView().run()
|
||||
}
|
||||
|
||||
// Why: Shift+Enter adds a hard break inside the paragraph, and Tiptap's macOS Ctrl-a/Ctrl-e jump to the whole paragraph's edge.
|
||||
export const NativeChatLineBoundaryKeys = Extension.create({
|
||||
name: 'nativeChatLineBoundaryKeys',
|
||||
priority: 1000,
|
||||
addKeyboardShortcuts(): Record<string, KeyboardShortcutCommand> {
|
||||
// Elsewhere Ctrl-a is select all.
|
||||
if (!isMacUserAgent()) {
|
||||
return {}
|
||||
}
|
||||
return {
|
||||
'Ctrl-a': ({ editor }) => selectLineSide(editor, 'start'),
|
||||
'Ctrl-e': ({ editor }) => selectLineSide(editor, 'end')
|
||||
}
|
||||
}
|
||||
})
|
||||
+18
@@ -51,6 +51,24 @@ export function promptTextContent(text: string): JSONContent {
|
||||
}
|
||||
}
|
||||
|
||||
/** Drafts saved before Shift+Enter split paragraphs hold hard breaks; initial editor content skips the hard-break plugin, which only sees transactions. */
|
||||
export function promptParagraphLines(document: JSONContent): JSONContent {
|
||||
return {
|
||||
...document,
|
||||
content: document.content?.flatMap((block) => {
|
||||
const lines: JSONContent[][] = [[]]
|
||||
for (const node of block.content ?? []) {
|
||||
if (node.type === 'hardBreak') {
|
||||
lines.push([])
|
||||
} else {
|
||||
lines.at(-1)?.push(node)
|
||||
}
|
||||
}
|
||||
return lines.length === 1 ? [block] : lines.map((content) => ({ ...block, content }))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
export function seedPromptSkillReferences(
|
||||
node: JSONContent,
|
||||
skills: readonly AgentJournalSkillRef[] = [],
|
||||
|
||||
Reference in New Issue
Block a user