oficina / base Public

Merge branch 'fix/composer-shift-enter' into main

claude agent, operated by paul@keymail.dev 6b40d3899a51fb06c35a753ee529806dd53e8cd3 parent 7b48b69parent d811be9
4 files changed, +365 −9
  • internal/browsertest/ask_test.go +51 −0
  • internal/look/static/ask.js +12 −2
  • native/apple/Sources/BaseKit/Ask/Composer.swift +125 −7
  • native/apple/Tests/BaseKitTests/ComposerTests.swift +177 −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 ===
12:25PM INF Unknown SCM platform. Use --platform to include links in findings. host=amadan.net
12:25PM INF 1 commits scanned.
12:25PM INF scanned ~2396736 bytes (2.40 MB) in 291ms
12:25PM 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.112s 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 6.814s amadan.net/oficina/base/internal/webtest
receipt: slow package 1.028s amadan.net/oficina/base/internal/issuer
receipt: slow package 643ms amadan.net/oficina/base/internal/operations
receipt: slow package 266ms amadan.net/oficina/base/internal/consumer
receipt: slow package 175ms amadan.net/oficina/base/internal/web
receipt: slow test 1.51s amadan.net/oficina/base/internal/webtest TestHomeDoesNotWaitOnAStalledSnapshot
receipt: slow test 1.1s amadan.net/oficina/base/internal/webtest TestAskZoneIsToldOnce
receipt: slow test 690ms amadan.net/oficina/base/internal/issuer TestAuthorizeSignsForInstalledApp
receipt: slow test 520ms amadan.net/oficina/base/internal/operations TestOperationsRefusals
receipt: slow test 300ms 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..fc647b2 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,21 @@ 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, model: model).allowsHitTesting(false).accessibilityHidden(true))
+ .onChange(of: focused, initial: true) { _, now in input.focused = now }
+ // 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 +79,110 @@ 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 {
+ /// Whether the field has the keyboard (its FocusState).
+ var focused = false
+ weak var model: AskModel?
+ #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 }
+ private var observers: [NSObjectProtocol] = []
+
+ /// Starts watching the field, once its anchor is in a view (never in
+ /// an init: SwiftUI makes a ComposerInput on every pass of a parent's
+ /// body and keeps only the first).
+ func start() {
+ guard observers.isEmpty else { return }
+ for name in [Notification.Name.NSUndoManagerDidUndoChange, .NSUndoManagerDidRedoChange] {
+ observers.append(NotificationCenter.default.addObserver(forName: name, object: nil, queue: nil) { [weak self] note in
+ // Undo and Redo post on the main thread.
+ nonisolated(unsafe) let manager = note.object as AnyObject?
+ MainActor.assumeIsolated { self?.undone(by: manager) }
+ })
+ }
+ }
+
+ isolated deinit { observers.forEach(NotificationCenter.default.removeObserver) }
+
+ /// Undo and Redo in a Mac field change the field but never tell it,
+ /// so its binding kept the text taken back, and Send sent that. Told
+ /// here as a typed change is, the field updates the model itself
+ /// (setting the model would push the text back into the field and
+ /// lose Redo).
+ func undone(by manager: AnyObject?) {
+ guard focused, let editor, let manager, manager === editor.undoManager, model?.text != editor.string else { return }
+ editor.didChangeText()
+ }
+ /// 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
+ let model: AskModel
+ func makeNSView(context: Context) -> NSView {
+ let view = NSView(); input.anchor = view; input.model = model; input.start(); return view
+ }
+ func updateNSView(_ view: NSView, context: Context) { input.anchor = view; input.model = model }
+}
+#elseif os(iOS)
+struct ComposerAnchor: UIViewRepresentable {
+ let input: ComposerInput
+ let model: AskModel
+ func makeUIView(context: Context) -> UIView {
+ let view = UIView(); view.isUserInteractionEnabled = false; input.anchor = view; input.model = model; return view
+ }
+ func updateUIView(_ view: UIView, context: Context) { input.anchor = view; input.model = model }
+}
+#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..220d46e
--- /dev/null
+++ b/native/apple/Tests/BaseKitTests/ComposerTests.swift
@@ -0,0 +1,177 @@
+@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")
+ }
+}
+
+extension ComposerKeyTests {
+ private var sentText: String? {
+ transport.bodies("/ask/messages").last.flatMap { $0 }.flatMap { URLComponents(string: "?" + String(decoding: $0, as: UTF8.self))?.queryItems?.first { $0.name == "text" }?.value }
+ }
+
+ /// Fable's S1: Undo in a Mac field told the field and not the model, so
+ /// Return sent the text that had been taken back.
+ func testReturnSendsWhatUndoLeft() throws {
+ try type("Flour")
+ let editor = try XCTUnwrap(editor)
+ editor.breakUndoCoalescing()
+ editor.insertText(" delivery", replacementRange: editor.selectedRange())
+ settle()
+ XCTAssertEqual(model.text, "Flour delivery")
+ editor.undoManager?.undo()
+ settle()
+ XCTAssertEqual(editor.string, "Flour")
+ XCTAssertEqual(model.text, "Flour", "Undo reaches the model")
+ editor.undoManager?.redo()
+ settle()
+ XCTAssertEqual(model.text, "Flour delivery", "and so does Redo")
+ editor.undoManager?.undo()
+ settle()
+ try press()
+ XCTAssertEqual(sentText, "Flour", "Return sends what the field shows")
+ }
+
+ func testUndoingANewLineReachesTheModel() throws {
+ try type("Flour delivery", cursor: 5)
+ try press(.shift)
+ XCTAssertEqual(model.text, "Flour\n delivery")
+ editor?.undoManager?.undo()
+ settle()
+ XCTAssertEqual(model.text, "Flour delivery")
+ editor?.undoManager?.redo()
+ settle()
+ XCTAssertEqual(model.text, "Flour\n delivery")
+ XCTAssertFalse(sent)
+ }
+}
+
+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