oficina / base Public

Ask composer: Shift and Option Return are a new line at the cursor

Tests: ComposerKeyTests drives the real composer in a window with key
events (Return, keypad Enter, Shift Return mid-text/end/over a
selection, Option Return, Return over marked text); five of them fail
against the old handler. TestAskComposerNewLines does the same in
Chromium for the web.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Summary

On a Mac the composer's TextField submits on any Return its field editor sees, so .onSubmit fired for Shift Return (the key handler let it through) and Option Return and an IME's Return sent too. The key handler now decides everything: Return (and keypad Enter) sends; Shift/Option Return inserts a newline through the field's own editor (at the cursor, replacing a selection, undoable); while an input method has marked text, Return is left to it. onSubmit stays only for the iPhone's Send key. The web composer also takes Option Enter as a new line and ignores Safari's keyCode 229 IME Enter.
claude agent, operated by paul@keymail.dev e700f1d4a04388c240ff7523b6ccc1b8641dc9cd parent 7b48b69
4 files changed, +289 −9
  • internal/browsertest/ask_test.go +51 −0
  • internal/look/static/ask.js +12 −2
  • native/apple/Sources/BaseKit/Ask/Composer.swift +90 −7
  • native/apple/Tests/BaseKitTests/ComposerTests.swift +136 −0

CI passed — run details

CI log
=== build ===
CGO_ENABLED=0 go build ./...
=== vet ===
go vet ./...
=== fmt-check ===
=== staticcheck ===
go run honnef.co/go/tools/cmd/staticcheck@v0.7.0 ./...
=== govulncheck ===
go run golang.org/x/vuln/cmd/govulncheck@v1.8.0 ./...
No vulnerabilities found.
=== gitleaks ===
9:41AM INF Unknown SCM platform. Use --platform to include links in findings. host=amadan.net
9:41AM INF 1 commits scanned.
9:41AM INF scanned ~2393411 bytes (2.39 MB) in 294ms
9:41AM INF no leaks found
=== budget ===
go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget size
budget size: 22 directories within budget
=== script-test ===
scripts/prepare-apps_test.sh
ok   releases lookup failure stops before ship
ok   app owned elsewhere stops the script
ok   apps listing failure stops before create
ok   ambiguous release dir is refused
ok   explicit version resolves the ambiguity
ok   releases match is exact, not substring
ok   shipped version is only promoted, existing app not created
ok   fresh account creates, ships, promotes to edge, enables
ok   failing promote stops the script
ok   ship is retried while uploads are rate limited
all passed
hack/fonts_test.sh
fonts_test: ok
=== test ===
go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -count=1 ./...

receipt: test step 8.361s against a 60s target (the gate's other steps are not in this figure)
receipt: 16 packages ran, 0 cached, 6 without tests, 0 failed
receipt: slow package 7.024s amadan.net/oficina/base/internal/webtest
receipt: slow package 1.254s amadan.net/oficina/base/internal/issuer
receipt: slow package 658ms amadan.net/oficina/base/internal/operations
receipt: slow package 362ms amadan.net/oficina/base/internal/consumer
receipt: slow package 245ms amadan.net/oficina/base/internal/e2e
receipt: slow test 1.52s amadan.net/oficina/base/internal/webtest TestHomeDoesNotWaitOnAStalledSnapshot
receipt: slow test 1.1s amadan.net/oficina/base/internal/webtest TestAskZoneIsToldOnce
receipt: slow test 860ms amadan.net/oficina/base/internal/issuer TestAuthorizeSignsForInstalledApp
receipt: slow test 530ms amadan.net/oficina/base/internal/operations TestOperationsRefusals
receipt: slow test 330ms amadan.net/oficina/base/internal/issuer TestAuthorizeRefusals
=== native ===
strings: copy review's strings.json is not here (git-ignored); its comparison skipped
strings: 119 in the catalog, 116 used
worktree-lib_test: ok
diff --git a/internal/browsertest/ask_test.go b/internal/browsertest/ask_test.go
index 88d44ae..a2d081e 100644
--- a/internal/browsertest/ask_test.go
+++ b/internal/browsertest/ask_test.go
@@ -550,6 +550,57 @@ func TestAskComposerSendAndStop(t *testing.T) {
}
}
+// The key events' modifier bits.
+const altKey, shiftKey = 1, 8
+
+// enter presses Enter as a keyboard does, with modifiers and the key code
+// an input method's Enter carries (229) or Enter's own (13).
+func enter(modifiers, keyCode int64) chromedp.Action[chromedp.Void] {
+ return chromedp.Func(func(ctx context.Context, target *chromedp.Target) error {
+ for _, typ := range []input.DispatchKeyEventType{input.DispatchKeyEventTypeKeyDown, input.DispatchKeyEventTypeKeyUp} {
+ k := input.DispatchKeyEventParams{Type: typ, Key: "Enter", Code: "Enter", Modifiers: modifiers,
+ WindowsVirtualKeyCode: keyCode, NativeVirtualKeyCode: keyCode}
+ if typ == input.DispatchKeyEventTypeKeyDown && keyCode != 229 { // the input method's own text
+ k.Text, k.UnmodifiedText = "\r", "\r"
+ }
+ if _, err := cdp.Call(ctx, target, input.DispatchKeyEvent, k); err != nil {
+ return err
+ }
+ }
+ return nil
+ })
+}
+
+// Paul's Base Mac bug, checked on the web: Enter sends; Shift Enter and
+// Option (Alt) Enter are a new line where the cursor is; an input
+// method's Enter (Safari's keyCode 229) finishes its word and sends
+// nothing.
+func TestAskComposerNewLines(t *testing.T) {
+ rig, f := askBase(t)
+ openPanel(t, rig)
+ value := func() string { return harness.Evaluate[string](rig, `document.querySelector("#ask-text").value`) }
+ at := func(n int) chromedp.Action[chromedp.Void] {
+ return chromedp.Evaluate[chromedp.Void](`(() => { const f = document.querySelector("#ask-text"); f.focus(); f.setSelectionRange(` + strconv.Itoa(n) + `, ` + strconv.Itoa(n) + `) })()`)
+ }
+ drive(t, rig, chromedp.SendKeys(chromedp.CSS(`#ask-text`), "Flour delivery"), at(5), enter(shiftKey, 13))
+ if got := value(); got != "Flour\n delivery" {
+ t.Errorf("Shift Enter mid-text: %q", got)
+ }
+ drive(t, rig, at(len("Flour\n delivery")), enter(altKey, 13))
+ if got := value(); got != "Flour\n delivery\n" {
+ t.Errorf("Option Enter at the end: %q", got)
+ }
+ drive(t, rig, enter(0, 229), chromedp.Sleep(300*time.Millisecond))
+ if n := len(f.Calls("/api/v1/assistant/messages")); n != 0 {
+ t.Fatalf("sent %d messages before a plain Enter", n)
+ }
+ drive(t, rig, enter(0, 13), chromedp.Sleep(300*time.Millisecond))
+ drive(t, rig, chromedp.Poll[chromedp.Void](`document.querySelector("#ask-text").value === ""`, chromedp.WithPollingTimeout(10*time.Second)))
+ if n := len(f.Calls("/api/v1/assistant/messages")); n != 1 {
+ t.Errorf("messages sent: %d, want 1", n)
+ }
+}
+
// holdDock wraps the page's fetch so its /ask/dock posts follow plan, one
// step per post: held for some milliseconds, then sent, or answered 500
// without reaching Base. window.__dock lists the bodies posted.
diff --git a/internal/look/static/ask.js b/internal/look/static/ask.js
index 12a2dae..4b2c735 100644
--- a/internal/look/static/ask.js
+++ b/internal/look/static/ask.js
@@ -1629,10 +1629,20 @@ function start(root) {
setTurn(sent.turn);
toBottom();
});
+ // Enter sends; Shift Enter is the field's own new line, and so is Option
+ // (Alt) Enter, as in the Mac app, though a browser leaves that one out.
+ // An input method's Enter finishes its word: Safari ends the composition
+ // before that keydown, so isComposing is already false there and only
+ // keyCode 229 tells.
field.addEventListener("keydown", (e) => {
- if (e.key === "Enter" && !e.shiftKey && !e.isComposing) {
- e.preventDefault();
+ if (e.key !== "Enter" || e.isComposing || e.keyCode === 229 || e.shiftKey) return;
+ e.preventDefault();
+ if (!e.altKey) {
composer.requestSubmit();
+ } else if (!document.execCommand("insertText", false, "\n")) {
+ // Where insertText isn't offered: at the cursor, without undo.
+ field.setRangeText("\n", field.selectionStart, field.selectionEnd, "end");
+ field.dispatchEvent(new Event("input", { bubbles: true }));
}
});
cancel.addEventListener("submit", (e) => {
diff --git a/native/apple/Sources/BaseKit/Ask/Composer.swift b/native/apple/Sources/BaseKit/Ask/Composer.swift
index 9d9a4d7..b5171c8 100644
--- a/native/apple/Sources/BaseKit/Ask/Composer.swift
+++ b/native/apple/Sources/BaseKit/Ask/Composer.swift
@@ -1,15 +1,22 @@
import SwiftUI
+#if os(macOS)
+import AppKit
+#elseif os(iOS)
+import UIKit
+#endif
/// The composer (chat.html `.composer`): one field that grows to a few
/// lines, with Send (an arrow) and, while a turn runs, Stop (a square) in
/// its end, round and filled like a primary button. Return sends; Shift
-/// Return is a new line. Focused, a thin luminous edge outside the field,
+/// Return and Option Return are a new line at the cursor; an input
+/// method's Return finishes its word and sends nothing. Focused, a thin luminous edge outside the field,
/// teal into violet, drifts round it (a turn every 6 s) over a soft glow;
/// with Reduce Motion it holds still.
public struct Composer: View {
@Bindable var model: AskModel
@FocusState.Binding var focused: Bool
@Environment(\.colorScheme) private var scheme
+ @State private var input = ComposerInput()
public init(model: AskModel, focused: FocusState<Bool>.Binding) {
self.model = model
@@ -30,14 +37,20 @@ public struct Composer: View {
.foregroundStyle(p[.frost])
.lineLimit(1...7)
.focused($focused)
- .onSubmit(send)
- // Return sends and Shift Return is a new line, as on the web.
- .onKeyPress(.return, phases: .down) { press in
- guard !press.modifiers.contains(.shift) else { return .ignored }
- send()
- return .handled
+ .background(ComposerAnchor(input: input).allowsHitTesting(false).accessibilityHidden(true))
+ // A hardware keyboard's Return (and a Mac keypad's Enter), as
+ // the web's keydown. On a Mac a field's own Return always
+ // submits, Shift or not, so the field never sees one of these.
+ .onKeyPress(keys: ComposerReturn.keys, phases: .down) { press in
+ switch ComposerReturn.action(press.modifiers, composing: input.composing) {
+ case .send: send(); return .handled
+ case .newline: return input.insertNewline() ? .handled : .ignored
+ case .pass: return .ignored
+ }
}
#if os(iOS)
+ // The iPhone's on-screen keyboard: its Send key.
+ .onSubmit(send)
.submitLabel(.send)
#endif
.padding(.vertical, 11).padding(.leading, 14).padding(.trailing, model.turn != nil || canSend ? 4 : 14)
@@ -65,6 +78,76 @@ public struct Composer: View {
}
}
+/// What Return does in the composer on a hardware keyboard: Return (with
+/// Command or Control too) sends; Shift or Option makes it a new line;
+/// while an input method is composing it is the input method's, to finish
+/// the word, as `!e.isComposing` in ask.js.
+enum ComposerReturn: Equatable {
+ case send, newline, pass
+
+ /// Return, and Enter on a Mac's keypad (ETX).
+ static let keys: Set<KeyEquivalent> = [.return, KeyEquivalent("\u{3}")]
+
+ static func action(_ modifiers: EventModifiers, composing: Bool) -> ComposerReturn {
+ if composing { return .pass }
+ if !modifiers.isDisjoint(with: [.shift, .option]) { return .newline }
+ return .send
+ }
+}
+
+/// The composer field's text view, which SwiftUI doesn't hand out: the
+/// first responder of the window the anchor is in, while the field has the
+/// keyboard (as it does whenever its key handler runs).
+@MainActor final class ComposerInput {
+ #if os(macOS)
+ weak var anchor: NSView?
+ /// A Mac field's editor.
+ var editor: NSTextView? { anchor?.window?.firstResponder as? NSTextView }
+ var composing: Bool { editor?.hasMarkedText() ?? false }
+ /// A new line in place of the selection, as Option Return in any Mac
+ /// field: one undoable edit, the cursor after it.
+ func insertNewline() -> Bool {
+ guard let editor else { return false }
+ editor.insertNewlineIgnoringFieldEditor(nil)
+ return true
+ }
+ #elseif os(iOS)
+ weak var anchor: UIView?
+ var editor: (UIView & UITextInput)? { anchor?.window.flatMap(Self.firstResponder) }
+ var composing: Bool { editor?.markedTextRange != nil }
+ func insertNewline() -> Bool {
+ guard let editor, let range = editor.selectedTextRange else { return false }
+ editor.replace(range, withText: "\n")
+ return true
+ }
+ private static func firstResponder(in view: UIView) -> (UIView & UITextInput)? {
+ if view.isFirstResponder, let input = view as? UIView & UITextInput { return input }
+ for sub in view.subviews { if let found = firstResponder(in: sub) { return found } }
+ return nil
+ }
+ #else
+ var composing: Bool { false }
+ func insertNewline() -> Bool { false }
+ #endif
+}
+
+/// An empty view behind the field, so the composer knows its window.
+#if os(macOS)
+struct ComposerAnchor: NSViewRepresentable {
+ let input: ComposerInput
+ func makeNSView(context: Context) -> NSView { let view = NSView(); input.anchor = view; return view }
+ func updateNSView(_ view: NSView, context: Context) { input.anchor = view }
+}
+#elseif os(iOS)
+struct ComposerAnchor: UIViewRepresentable {
+ let input: ComposerInput
+ func makeUIView(context: Context) -> UIView {
+ let view = UIView(); view.isUserInteractionEnabled = false; input.anchor = view; return view
+ }
+ func updateUIView(_ view: UIView, context: Context) { input.anchor = view }
+}
+#endif
+
/// Send and Stop: a 32 pt circle in a 44 pt target.
struct RoundAction: View {
enum Kind { case send, stop }
diff --git a/native/apple/Tests/BaseKitTests/ComposerTests.swift b/native/apple/Tests/BaseKitTests/ComposerTests.swift
new file mode 100644
index 0000000..7d902c1
--- /dev/null
+++ b/native/apple/Tests/BaseKitTests/ComposerTests.swift
@@ -0,0 +1,136 @@
+@testable import BaseKit
+import SwiftUI
+import XCTest
+
+/// Paul's bug in Base Mac 0.1.0: Shift Return sent the message. Return
+/// sends; Shift and Option Return are a new line at the cursor; an input
+/// method's Return is its own.
+final class ComposerReturnTests: XCTestCase {
+ func testWhatReturnDoes() {
+ XCTAssertEqual(ComposerReturn.action([], composing: false), .send)
+ XCTAssertEqual(ComposerReturn.action(.shift, composing: false), .newline)
+ XCTAssertEqual(ComposerReturn.action(.option, composing: false), .newline)
+ XCTAssertEqual(ComposerReturn.action([.shift, .option], composing: false), .newline)
+ XCTAssertEqual(ComposerReturn.action(.command, composing: false), .send)
+ for modifiers: EventModifiers in [[], .shift, .option, .command] {
+ XCTAssertEqual(ComposerReturn.action(modifiers, composing: true), .pass, "an input method's Return finishes its word")
+ }
+ XCTAssertTrue(ComposerReturn.keys.contains(.return))
+ }
+}
+
+#if os(macOS)
+import AppKit
+
+/// The real composer in a real window, driven by key events as the
+/// keyboard sends them.
+@MainActor final class ComposerKeyTests: XCTestCase {
+ private var window: NSWindow!
+ private var model: AskModel!
+ private var transport: GatedTransport!
+
+ override func setUp() {
+ _ = NSApplication.shared
+ transport = GatedTransport()
+ model = AskModel(client: BaseClient(transport: transport) {}, schedule: { _, _ in })
+ window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 420, height: 300), styleMask: [.titled], backing: .buffered, defer: false)
+ window.isReleasedWhenClosed = false
+ window.contentView = NSHostingView(rootView: FocusedComposer(model: model).frame(width: 420))
+ window.makeKeyAndOrderFront(nil)
+ for _ in 0..<40 where editor == nil { RunLoop.main.run(until: Date().addingTimeInterval(0.05)) }
+ XCTAssertNotNil(editor, "the composer never took the keyboard")
+ }
+
+ override func tearDown() { window.close() }
+
+ private var editor: NSTextView? { window.firstResponder as? NSTextView }
+
+ private func type(_ text: String, cursor: Int? = nil, selecting length: Int = 0) throws {
+ let editor = try XCTUnwrap(editor)
+ editor.insertText(text, replacementRange: NSRange(location: 0, length: (editor.string as NSString).length))
+ editor.setSelectedRange(NSRange(location: cursor ?? (text as NSString).length, length: length))
+ settle()
+ XCTAssertEqual(model.text, text)
+ }
+
+ private func press(_ modifiers: NSEvent.ModifierFlags = [], keyCode: UInt16 = 36, characters: String = "\r") throws {
+ let event = try XCTUnwrap(NSEvent.keyEvent(with: .keyDown, location: .zero, modifierFlags: modifiers, timestamp: 0,
+ windowNumber: window.windowNumber, context: nil, characters: characters,
+ charactersIgnoringModifiers: characters, isARepeat: false, keyCode: keyCode))
+ window.sendEvent(event)
+ settle()
+ }
+
+ private func settle() { RunLoop.main.run(until: Date().addingTimeInterval(0.15)) }
+ private var sent: Bool { !transport.calls.isEmpty }
+
+ func testReturnSends() throws {
+ try type("What's on tomorrow?")
+ try press()
+ XCTAssertTrue(sent, "Return sends")
+ }
+
+ func testKeypadEnterSends() throws {
+ try type("What's on tomorrow?")
+ try press(.numericPad, keyCode: 76, characters: "\u{3}")
+ XCTAssertTrue(sent, "the keypad's Enter sends")
+ }
+
+ func testShiftReturnIsANewLineAtTheEnd() throws {
+ try type("Three things")
+ try press(.shift)
+ XCTAssertFalse(sent, "Shift Return sent the message")
+ XCTAssertEqual(model.text, "Three things\n")
+ XCTAssertEqual(editor?.selectedRange(), NSRange(location: 13, length: 0))
+ }
+
+ func testShiftReturnIsANewLineAtTheCursor() throws {
+ try type("Flour delivery", cursor: 5)
+ try press(.shift)
+ XCTAssertFalse(sent)
+ XCTAssertEqual(model.text, "Flour\n delivery")
+ XCTAssertEqual(editor?.selectedRange(), NSRange(location: 6, length: 0), "the cursor follows the new line")
+ // And typing goes on from there.
+ editor?.insertText("x", replacementRange: editor!.selectedRange())
+ settle()
+ XCTAssertEqual(model.text, "Flour\nx delivery")
+ }
+
+ func testShiftReturnReplacesTheSelection() throws {
+ try type("Flour, then Ana", cursor: 5, selecting: 7)
+ try press(.shift)
+ XCTAssertFalse(sent)
+ XCTAssertEqual(model.text, "Flour\nAna")
+ }
+
+ func testOptionReturnIsANewLine() throws {
+ try type("Flour delivery", cursor: 5)
+ try press(.option)
+ XCTAssertFalse(sent, "Option Return sent the message")
+ XCTAssertEqual(model.text, "Flour\n delivery")
+ }
+
+ /// Return while an input method composes (marked text) finishes the
+ /// word; nothing is sent until the next Return.
+ func testReturnWhileComposingDoesNotSend() throws {
+ try type("Tomorrow ")
+ let editor = try XCTUnwrap(editor)
+ editor.setMarkedText("あした", selectedRange: NSRange(location: 3, length: 0), replacementRange: NSRange(location: NSNotFound, length: 0))
+ XCTAssertTrue(editor.hasMarkedText())
+ try press()
+ XCTAssertFalse(sent, "Return while composing sent the message")
+ XCTAssertFalse(editor.hasMarkedText(), "the composition is finished")
+ XCTAssertTrue(model.text.hasPrefix("Tomorrow あした"), model.text)
+ try press()
+ XCTAssertTrue(sent, "the next Return sends")
+ }
+}
+
+private struct FocusedComposer: View {
+ let model: AskModel
+ @FocusState private var focused: Bool
+ var body: some View {
+ Composer(model: model, focused: $focused).onAppear { focused = true }
+ }
+}
+#endif