Send chat messages with Enter and use Shift+Enter for newlines
This commit is contained in:
@@ -48,8 +48,9 @@ const String chatQueuedNotice =
|
||||
///
|
||||
/// The field owns only its [TextEditingController] and focus; the durable draft
|
||||
/// text lives in the composer controller, so a live transcript rebuild never
|
||||
/// replaces the operator's caret. Enter inserts a newline and Ctrl/Cmd+Enter
|
||||
/// sends the plain message. A leading `/` opens the recorded command palette
|
||||
/// replaces the operator's caret. Enter sends, Shift+Enter inserts a newline,
|
||||
/// and Ctrl/Cmd+Enter remains a send shortcut.
|
||||
/// A leading `/` opens the recorded command palette
|
||||
/// above the field: rows are filtered by name prefix, Up/Down move the
|
||||
/// highlight, Enter or a tap completes the highlighted command, Escape closes
|
||||
/// the palette. A slash draft is never handed to the prompt path: `/new`,
|
||||
@@ -224,8 +225,6 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
|
||||
KeyEventResult _onKey(FocusNode node, KeyEvent event) {
|
||||
final key = event.logicalKey;
|
||||
final commands = _paletteCommands();
|
||||
final word = chatCommandWord(widget.composer.draft);
|
||||
final slashDraft = word != null;
|
||||
if (key == LogicalKeyboardKey.escape) {
|
||||
if (commands.isEmpty && _commandNotice == null) {
|
||||
return KeyEventResult.ignored;
|
||||
@@ -253,35 +252,54 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
|
||||
}
|
||||
final keyboard = HardwareKeyboard.instance;
|
||||
final sendShortcut = keyboard.isControlPressed || keyboard.isMetaPressed;
|
||||
// A plain Enter accepts the highlighted command instead of sending it. With
|
||||
// no palette showing, a slash draft is still a command, never a prompt.
|
||||
if (!sendShortcut && !keyboard.isShiftPressed) {
|
||||
if (commands.isNotEmpty) {
|
||||
if (event is! KeyDownEvent) return KeyEventResult.handled;
|
||||
_completeCommand(commands[_selectedCommand % commands.length]);
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
if (slashDraft) {
|
||||
if (event is! KeyDownEvent) return KeyEventResult.handled;
|
||||
_runSlashDraft();
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
// Enter may be confirming an IME candidate rather than submitting a draft.
|
||||
if (_text.value.composing.isValid && !_text.value.composing.isCollapsed) {
|
||||
return KeyEventResult.ignored;
|
||||
}
|
||||
if (!sendShortcut && keyboard.isShiftPressed) {
|
||||
if (event is KeyDownEvent) {
|
||||
final selection = _text.selection;
|
||||
final start = selection.isValid ? selection.start : _text.text.length;
|
||||
final end = selection.isValid ? selection.end : start;
|
||||
_text.value = TextEditingValue(
|
||||
text: _text.text.replaceRange(start, end, '\n'),
|
||||
selection: TextSelection.collapsed(offset: start + 1),
|
||||
);
|
||||
_onDraftEdited(_text.text);
|
||||
}
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
if (!sendShortcut && keyboard.isAltPressed) {
|
||||
return KeyEventResult.ignored;
|
||||
}
|
||||
if (!sendShortcut) return KeyEventResult.ignored;
|
||||
// A held key must not post a second prompt.
|
||||
if (event is! KeyDownEvent) return KeyEventResult.handled;
|
||||
// Ctrl/Cmd+Enter is the same submit: a visible palette completes, and a
|
||||
// slash draft reports locally. Only plain text reaches the prompt path.
|
||||
_submitDraft();
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
|
||||
/// Hardware Enter, the keyboard's Send action and modifier shortcuts share
|
||||
/// the same command/prompt path. An active IME candidate is never submitted.
|
||||
void _submitDraft() {
|
||||
if (_text.value.composing.isValid && !_text.value.composing.isCollapsed) {
|
||||
return;
|
||||
}
|
||||
final keyboard = HardwareKeyboard.instance;
|
||||
if (!keyboard.isControlPressed &&
|
||||
!keyboard.isMetaPressed &&
|
||||
(keyboard.isShiftPressed || keyboard.isAltPressed)) {
|
||||
return;
|
||||
}
|
||||
final commands = _paletteCommands();
|
||||
if (commands.isNotEmpty) {
|
||||
_completeCommand(commands[_selectedCommand % commands.length]);
|
||||
return KeyEventResult.handled;
|
||||
return;
|
||||
}
|
||||
if (slashDraft) {
|
||||
if (chatCommandWord(widget.composer.draft) != null) {
|
||||
_runSlashDraft();
|
||||
return KeyEventResult.handled;
|
||||
return;
|
||||
}
|
||||
unawaited(_send());
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
|
||||
/// Routes a slash draft locally or through the existing Stop controller path.
|
||||
@@ -877,9 +895,13 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
minLines: lines,
|
||||
maxLines: empty ? lines : 6,
|
||||
// Keep the empty field multiline too: a single-line web editor
|
||||
// strips Shift+Enter's newline on the next text edit.
|
||||
maxLines: empty && lines > 1 ? lines : 6,
|
||||
keyboardType: TextInputType.multiline,
|
||||
textInputAction: TextInputAction.newline,
|
||||
textInputAction: TextInputAction.send,
|
||||
onEditingComplete: () {},
|
||||
onSubmitted: (_) => _submitDraft(),
|
||||
onChanged: _onDraftEdited,
|
||||
);
|
||||
},
|
||||
@@ -892,7 +914,9 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
|
||||
minLines: 1,
|
||||
maxLines: 6,
|
||||
keyboardType: TextInputType.multiline,
|
||||
textInputAction: TextInputAction.newline,
|
||||
textInputAction: TextInputAction.send,
|
||||
onEditingComplete: () {},
|
||||
onSubmitted: (_) => _submitDraft(),
|
||||
onChanged: _onDraftEdited,
|
||||
decoration: const InputDecoration(
|
||||
hintText: chatComposerPlaceholder,
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
# Enter sends chat messages
|
||||
|
||||
- Plain Enter and numpad Enter send; Shift+Enter inserts a newline at the caret
|
||||
or replaces only selected text. Ctrl/Cmd+Enter remain compatible shortcuts.
|
||||
- The native keyboard exposes Send and uses the same command/prompt path while
|
||||
retaining composer focus. Slash completion/execution remains local. Key repeat,
|
||||
blank drafts and duplicate submissions do not create extra prompts.
|
||||
- Enter during active IME composition does not submit an unfinished candidate.
|
||||
- Shift+Enter is handled explicitly: passing it through with a Send input action
|
||||
caused web submission. The empty Cupertino field also stays multiline, since
|
||||
a single-line web editor stripped a programmatically inserted newline on the
|
||||
next edit. Placeholder sizing/text-scale regression still passes.
|
||||
|
||||
## Checks and evidence
|
||||
|
||||
- Full `flutter test`: **1,915 passed**. `flutter analyze`: clean.
|
||||
- Release web build: `build/chat-enter-send-web` (isolated, not published).
|
||||
- Material and Cupertino real-browser probes used Shift+Enter, typed a second
|
||||
line, and submitted with plain Enter. Fixture wire evidence confirms exactly
|
||||
one prompt with the complete two-line text. Response dots/tool/text regressions
|
||||
also passed; screenshots inspected in
|
||||
`build/chat-enter-send-{material,cupertino}/`.
|
||||
- Widget tests cover both hosts, hardware Enter/numpad/Ctrl/Cmd, software Send,
|
||||
caret/selection behavior, IME confirmation, repeats and empty/duplicate sends.
|
||||
- No website/APK publication or device installation for this change. Mobile Send
|
||||
is covered by widget tests, not a new physical-device interaction.
|
||||
@@ -91,7 +91,7 @@ void main() {
|
||||
},
|
||||
);
|
||||
|
||||
testWidgets('Enter inserts a newline; Ctrl+Enter sends', (tester) async {
|
||||
testWidgets('Shift+Enter inserts a newline; Enter sends', (tester) async {
|
||||
await tester.pumpWidget(
|
||||
composerThread(gateway, newOperationId: nextOperation),
|
||||
);
|
||||
@@ -101,23 +101,15 @@ void main() {
|
||||
await tester.enterText(field, 'line one');
|
||||
await tester.pump();
|
||||
|
||||
// A hardware Enter is left to the IME and never submits; the engine then
|
||||
// inserts the newline as an editing value.
|
||||
// Shift+Enter inserts a newline without triggering the keyboard Send action.
|
||||
await tester.sendKeyDownEvent(LogicalKeyboardKey.shiftLeft);
|
||||
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
|
||||
await tester.sendKeyUpEvent(LogicalKeyboardKey.shiftLeft);
|
||||
await tester.pump();
|
||||
expect(gateway.promptBodies, isEmpty);
|
||||
tester.testTextInput.updateEditingValue(
|
||||
const TextEditingValue(
|
||||
text: 'line one\n',
|
||||
selection: TextSelection.collapsed(offset: 9),
|
||||
),
|
||||
);
|
||||
await tester.pump();
|
||||
expect(fieldText(tester), 'line one\n');
|
||||
|
||||
await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft);
|
||||
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
|
||||
await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(gateway.promptBodies.single['text'], 'line one');
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
import 'chat_composer_bar_fixtures.dart';
|
||||
|
||||
void main() {
|
||||
for (final cupertino in [false, true]) {
|
||||
for (final shortcut in ['enter', 'numpad', 'control', 'meta', 'software']) {
|
||||
testWidgets(
|
||||
'$shortcut sends on ${cupertino ? 'Cupertino' : 'Material'}',
|
||||
(tester) async {
|
||||
final gateway = ComposerBarGateway()..page = fixtureTurn();
|
||||
addTearDown(gateway.close);
|
||||
await tester.pumpWidget(
|
||||
composerThread(gateway, cupertino: cupertino),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
final field = find.byKey(const Key('chat-composer-field'));
|
||||
await tester.enterText(field, ' message ');
|
||||
await tester.pump();
|
||||
final modifier = switch (shortcut) {
|
||||
'control' => LogicalKeyboardKey.controlLeft,
|
||||
'meta' => LogicalKeyboardKey.metaLeft,
|
||||
_ => null,
|
||||
};
|
||||
if (modifier != null) await tester.sendKeyDownEvent(modifier);
|
||||
if (shortcut == 'software') {
|
||||
await tester.testTextInput.receiveAction(TextInputAction.send);
|
||||
} else {
|
||||
await tester.sendKeyEvent(
|
||||
shortcut == 'numpad'
|
||||
? LogicalKeyboardKey.numpadEnter
|
||||
: LogicalKeyboardKey.enter,
|
||||
);
|
||||
}
|
||||
if (modifier != null) await tester.sendKeyUpEvent(modifier);
|
||||
await tester.pumpAndSettle();
|
||||
expect(gateway.promptBodies.single['text'], 'message');
|
||||
expect(fieldText(tester), isEmpty);
|
||||
final editor = tester.widget<EditableText>(
|
||||
find.descendant(of: field, matching: find.byType(EditableText)),
|
||||
);
|
||||
expect(editor.focusNode.hasFocus, isTrue);
|
||||
expect(editor.textInputAction, TextInputAction.send);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
testWidgets('Shift+Enter replaces only selected text ($cupertino)', (
|
||||
tester,
|
||||
) async {
|
||||
final gateway = ComposerBarGateway()..page = fixtureTurn();
|
||||
addTearDown(gateway.close);
|
||||
await tester.pumpWidget(composerThread(gateway, cupertino: cupertino));
|
||||
await tester.pumpAndSettle();
|
||||
final field = find.byKey(const Key('chat-composer-field'));
|
||||
await tester.enterText(field, 'abcd');
|
||||
await tester.pump();
|
||||
final editor = tester.widget<EditableText>(
|
||||
find.descendant(of: field, matching: find.byType(EditableText)),
|
||||
);
|
||||
editor.controller.selection = const TextSelection(
|
||||
baseOffset: 1,
|
||||
extentOffset: 3,
|
||||
);
|
||||
await tester.sendKeyDownEvent(LogicalKeyboardKey.shiftLeft);
|
||||
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
|
||||
await tester.sendKeyUpEvent(LogicalKeyboardKey.shiftLeft);
|
||||
await tester.pump();
|
||||
expect(fieldText(tester), 'a\nd');
|
||||
expect(
|
||||
editor.controller.selection,
|
||||
const TextSelection.collapsed(offset: 2),
|
||||
);
|
||||
expect(gateway.promptBodies, isEmpty);
|
||||
});
|
||||
|
||||
testWidgets(
|
||||
'Enter confirms IME composition without submitting ($cupertino)',
|
||||
(tester) async {
|
||||
final gateway = ComposerBarGateway()..page = fixtureTurn();
|
||||
addTearDown(gateway.close);
|
||||
await tester.pumpWidget(composerThread(gateway, cupertino: cupertino));
|
||||
await tester.pumpAndSettle();
|
||||
await tester.showKeyboard(find.byKey(const Key('chat-composer-field')));
|
||||
tester.testTextInput.updateEditingValue(
|
||||
const TextEditingValue(
|
||||
text: '仮',
|
||||
selection: TextSelection.collapsed(offset: 1),
|
||||
composing: TextRange(start: 0, end: 1),
|
||||
),
|
||||
);
|
||||
await tester.pump();
|
||||
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
|
||||
await tester.pump();
|
||||
expect(gateway.promptBodies, isEmpty);
|
||||
tester.testTextInput.updateEditingValue(
|
||||
const TextEditingValue(
|
||||
text: '仮',
|
||||
selection: TextSelection.collapsed(offset: 1),
|
||||
),
|
||||
);
|
||||
await tester.pump();
|
||||
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
|
||||
await tester.pumpAndSettle();
|
||||
expect(gateway.promptBodies.single['text'], '仮');
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
testWidgets(
|
||||
'empty Enter, repeat and duplicate software submit send nothing extra',
|
||||
(tester) async {
|
||||
final gateway = ComposerBarGateway()..page = fixtureTurn();
|
||||
final reply = Completer<Map<String, dynamic>>();
|
||||
gateway.prompt = (_, _) => reply.future;
|
||||
addTearDown(gateway.close);
|
||||
await tester.pumpWidget(composerThread(gateway));
|
||||
await tester.pumpAndSettle();
|
||||
final field = find.byKey(const Key('chat-composer-field'));
|
||||
await tester.enterText(field, ' ');
|
||||
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
|
||||
await tester.pump();
|
||||
expect(gateway.promptBodies, isEmpty);
|
||||
await tester.enterText(field, 'one message');
|
||||
await tester.pump();
|
||||
await tester.sendKeyDownEvent(LogicalKeyboardKey.enter);
|
||||
await tester.pump();
|
||||
await tester.sendKeyRepeatEvent(LogicalKeyboardKey.enter);
|
||||
await tester.testTextInput.receiveAction(TextInputAction.send);
|
||||
await tester.sendKeyUpEvent(LogicalKeyboardKey.enter);
|
||||
await tester.pump();
|
||||
expect(gateway.promptBodies, hasLength(1));
|
||||
reply.complete({});
|
||||
await tester.pumpAndSettle();
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -9,12 +9,13 @@ import { launchChrome, waitForPort, waitForPage, connect, sleep } from './pipeli
|
||||
import { axNodes, enableSemantics, waitFor, capture, click, clickAt } from './pipelines_probe_cdp_input.mjs';
|
||||
|
||||
const platform = process.env.PROBE_PLATFORM ?? 'material';
|
||||
const enterSends = process.env.PROBE_ENTER === '1';
|
||||
const output = resolve(process.argv[3] ?? `build/chat-response-pending-${platform}`);
|
||||
await mkdir(output, { recursive: true });
|
||||
const fixture = await startFixture({ root: resolve(process.argv[2]), chatMessages: [] });
|
||||
const profile = await mkdtemp(join(tmpdir(), 'chat-response-pending-'));
|
||||
const chrome = launchChrome('/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', profile, 'about:blank');
|
||||
const log = { platform, checks: [], captures: [] };
|
||||
const log = { platform, enterSends, checks: [], captures: [] };
|
||||
let c;
|
||||
const names = async () => (await axNodes(c)).map(n => n.name?.value ?? '');
|
||||
const pending = async () => (await axNodes(c)).find(n => n.name?.value === 'Assistant is responding' && n.backendDOMNodeId);
|
||||
@@ -40,9 +41,30 @@ try {
|
||||
await clickAt(c, (x1 + x3) / 2, (y1 + y3) / 2);
|
||||
await c.send('Input.insertText', { text: 'Fixture prompt before any response tokens.' });
|
||||
await sleep(150);
|
||||
await click(c, 'Send');
|
||||
if (enterSends) {
|
||||
await c.send('Input.dispatchKeyEvent', { type: 'keyDown', key: 'Shift', code: 'ShiftLeft', windowsVirtualKeyCode: 16, modifiers: 8 });
|
||||
await c.send('Input.dispatchKeyEvent', { type: 'keyDown', key: 'Enter', code: 'Enter', windowsVirtualKeyCode: 13, modifiers: 8, text: '\r' });
|
||||
await c.send('Input.dispatchKeyEvent', { type: 'keyUp', key: 'Enter', code: 'Enter', windowsVirtualKeyCode: 13, modifiers: 8 });
|
||||
await c.send('Input.dispatchKeyEvent', { type: 'keyUp', key: 'Shift', code: 'ShiftLeft', windowsVirtualKeyCode: 16 });
|
||||
await sleep(150);
|
||||
const beforeSend = await (await fetch(fixture.url + '/fixture/state')).json();
|
||||
assert.equal(beforeSend.chatPrompts.length, 0, 'Shift+Enter does not submit');
|
||||
assert.equal(await pending(), undefined);
|
||||
await c.send('Input.insertText', { text: 'Second line.' });
|
||||
await c.send('Input.dispatchKeyEvent', { type: 'keyDown', key: 'Enter', code: 'Enter', windowsVirtualKeyCode: 13, text: '\r' });
|
||||
await c.send('Input.dispatchKeyEvent', { type: 'keyUp', key: 'Enter', code: 'Enter', windowsVirtualKeyCode: 13 });
|
||||
log.checks.push('real Shift+Enter inserts a newline; plain Enter submits');
|
||||
} else {
|
||||
await click(c, 'Send');
|
||||
}
|
||||
assert.ok(await waitFor(pending, 10000), 'assistant bubble before a server response frame');
|
||||
await sleep(500); // The accepted prompt still has no assistant frames.
|
||||
if (enterSends) {
|
||||
const state = await (await fetch(fixture.url + '/fixture/state')).json();
|
||||
assert.equal(state.chatPrompts.length, 1, 'Enter submits once');
|
||||
assert.equal(state.chatPrompts[0].text, 'Fixture prompt before any response tokens.\nSecond line.');
|
||||
log.checks.push('exact multiline prompt submitted once without Control or Command');
|
||||
}
|
||||
await capture(c, output, log, '01-before-first-frame');
|
||||
log.checks.push('normal assistant response bubble before any frames or tokens');
|
||||
|
||||
|
||||
Reference in New Issue
Block a user