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
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ class T3ComposerEditorModule : Module() {
"onComposerSelectionChange",
"onComposerFocus",
"onComposerBlur",
"onComposerSubmit",
"onComposerPasteImages",
"onComposerContentSizeChange",
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,11 @@ import android.text.Spanned
import android.text.TextWatcher
import android.text.style.ReplacementSpan
import android.view.Gravity
import android.view.KeyEvent
import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputConnection
import android.view.inputmethod.InputConnectionWrapper
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import expo.modules.kotlin.AppContext
Expand All @@ -31,6 +35,7 @@ class T3ComposerEditorView(context: Context, appContext: AppContext) : ExpoView(
private val onComposerSelectionChange by EventDispatcher()
private val onComposerFocus by EventDispatcher()
private val onComposerBlur by EventDispatcher()
private val onComposerSubmit by EventDispatcher()
private val onComposerPasteImages by EventDispatcher()
private val onComposerContentSizeChange by EventDispatcher()
private var applyingNativeValue = false
Expand Down Expand Up @@ -65,6 +70,11 @@ class T3ComposerEditorView(context: Context, appContext: AppContext) : ExpoView(
editor.pasteImagesListener = { uris ->
onComposerPasteImages(mapOf("uris" to uris))
}
// A bare Enter (no Shift) submits — mirrors iOS and desktop Enter=submit.
// Empty payload matches the iOS `onComposerSubmit([:])` contract.
editor.submitListener = {
onComposerSubmit(emptyMap<String, Any>())
}
editor.setOnFocusChangeListener { _, hasFocus ->
if (hasFocus) {
onComposerFocus(emptyMap<String, Any>())
Expand Down Expand Up @@ -450,6 +460,47 @@ private fun parseTokens(value: String): List<ComposerToken> = try {
private class SelectionAwareEditText(context: Context) : EditText(context) {
var selectionListener: ((Int, Int) -> Unit)? = null
var pasteImagesListener: ((List<String>) -> Unit)? = null
var submitListener: (() -> Unit)? = null

private fun isPlainEnter(keyCode: Int, event: KeyEvent?): Boolean {
val isEnter = keyCode == KeyEvent.KEYCODE_ENTER || keyCode == KeyEvent.KEYCODE_NUMPAD_ENTER
// Shift+Enter still inserts a newline; only an unmodified Enter submits.
return isEnter && event?.isShiftPressed != true
}

// Hardware keyboards (and soft keyboards that route Enter as a key event)
// land here. Fire submit on the down edge and consume both edges so the
// multi-line field never inserts the newline.
override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
if (isPlainEnter(keyCode, event)) {
submitListener?.invoke()
return true
}
return super.onKeyDown(keyCode, event)
}

override fun onKeyUp(keyCode: Int, event: KeyEvent?): Boolean {
if (isPlainEnter(keyCode, event)) {
return true
}
return super.onKeyUp(keyCode, event)
}

// Soft keyboards that commit the newline as text (rather than a key event)
// land here; an exact "\n" commit means a bare Return, so submit instead.
// A multi-line paste ("a\nb") is unaffected because it is not exactly "\n".
override fun onCreateInputConnection(outAttrs: EditorInfo): InputConnection? {
val base = super.onCreateInputConnection(outAttrs) ?: return null
return object : InputConnectionWrapper(base, false) {
override fun commitText(text: CharSequence?, newCursorPosition: Int): Boolean {
if (text?.toString() == "\n") {
submitListener?.invoke()
return true
}
return super.commitText(text, newCursorPosition)
}
}
}

override fun onSelectionChanged(selStart: Int, selEnd: Int) {
super.onSelectionChanged(selStart, selEnd)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,11 @@ private final class ComposerTextView: UITextView {
var onAttributedMutation: (() -> Void)?
var onSubmit: (() -> Void)?

// Set only while a Shift+Return hardware key command is programmatically
// inserting a line break, so the delegate lets that "\n" through instead of
// treating it as a submit. Reset synchronously after the insert.
private(set) var isInsertingHardLineBreak = false

override var keyCommands: [UIKeyCommand]? {
var commands = super.keyCommands ?? []
let submit = UIKeyCommand(
Expand All @@ -75,13 +80,30 @@ private final class ComposerTextView: UITextView {
submit.discoverabilityTitle = "Send Message"
submit.wantsPriorityOverSystemBehavior = true
commands.append(submit)
// Shift+Return inserts a newline on a hardware keyboard (mirrors Android and
// desktop Shift+Enter), since a bare Return now submits. Soft keyboards use
// the composer's line-break button instead.
let newline = UIKeyCommand(
input: "\r",
modifierFlags: .shift,
action: #selector(insertHardLineBreak(_:))
)
newline.discoverabilityTitle = "Insert Line Break"
newline.wantsPriorityOverSystemBehavior = true
commands.append(newline)
return commands
}

@objc private func submitMessage(_ sender: UIKeyCommand) {
onSubmit?()
}

@objc private func insertHardLineBreak(_ sender: UIKeyCommand) {
isInsertingHardLineBreak = true
insertText("\n")
isInsertingHardLineBreak = false
}

override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
if action == #selector(paste(_:)) {
let pasteboard = UIPasteboard.general
Expand Down Expand Up @@ -496,6 +518,17 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate {
shouldChangeTextIn range: NSRange,
replacementText text: String
) -> Bool {
// A bare Return (soft keyboard or hardware) submits — matching desktop
// Enter=submit and the composer's queue-when-busy / send-when-idle outbox.
// Only an exact single "\n" is intercepted, so a multi-line paste like
// "a\nb" still inserts normally. The newline button inserts "\n" through
// the controlled value (setText), never this typing path. Hardware
// Command-Return keeps flowing through the UIKeyCommand above, and a
// Shift+Return line break is let through via isInsertingHardLineBreak.
if text == "\n", (textView as? ComposerTextView)?.isInsertingHardLineBreak != true {
onComposerSubmit([:])
return false
}
restoreBaseTypingAttributes()
return true
}
Expand Down
2 changes: 2 additions & 0 deletions apps/mobile/src/components/AppSymbol.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import {
IconCircleCheck,
IconCircleXFilled,
IconCopy,
IconCornerDownLeft,
IconDeviceDesktop,
IconDots,
IconDotsCircleHorizontal,
Expand Down Expand Up @@ -122,6 +123,7 @@ const ANDROID_ICON_BY_SF_SYMBOL: Partial<Record<SFSymbol, Icon>> = {
play: IconPlayerPlay,
plus: IconPlus,
"qrcode.viewfinder": IconQrcode,
return: IconCornerDownLeft,
"point.3.connected.trianglepath.dotted": IconNetwork,
"point.topleft.down.curvedto.point.bottomright.up": IconGitMerge,
safari: IconExternalLink,
Expand Down
30 changes: 26 additions & 4 deletions apps/mobile/src/features/threads/ThreadComposer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ import {
} from "../../lib/providerOptions";
import { useComposerPathSearch } from "../../state/use-composer-path-search";
import { ComposerCommandPopover, type ComposerCommandItem } from "./ComposerCommandPopover";
import { resolveComposerSendLabel } from "./composerSendLabel";

/**
* Height of the collapsed composer (pill + vertical padding, excluding safe-area inset).
Expand Down Expand Up @@ -309,10 +310,11 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
props.selectedThread.session?.status === "running" ||
props.selectedThread.session?.status === "starting";

const sendLabel =
props.connectionState !== "connected" || props.activeThreadBusy || props.queueCount > 0
? "Queue"
: "Send";
const sendLabel = resolveComposerSendLabel({
connectionState: props.connectionState,
activeThreadBusy: props.activeThreadBusy,
queueCount: props.queueCount,
});
const currentModelSelection = props.selectedThread.modelSelection;
const currentRuntimeMode = props.selectedThread.runtimeMode;
const currentInteractionMode = props.selectedThread.interactionMode ?? "default";
Expand Down Expand Up @@ -536,6 +538,20 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
props.selectedThread.id,
props.selectedThread.title,
]);
// Return now submits (queues-when-busy / sends-when-idle), matching desktop
// Enter=submit. The newline button is the cross-platform multiline escape
// hatch: it inserts "\n" at the caret through the same insert-at-selection
// mechanism used for @file / skill tokens (replaceTextRange + selection).
const handleInsertNewline = useCallback(() => {
const result = replaceTextRange(
draftMessage,
composerSelection.start,
composerSelection.end,
"\n",
);
setComposerSelection({ start: result.cursor, end: result.cursor });
onChangeDraftMessage(result.text);
}, [composerSelection.start, composerSelection.end, draftMessage, onChangeDraftMessage]);
const handleCommandSelect = useCallback(
(item: ComposerCommandItem) => {
if (!composerTrigger) return;
Expand Down Expand Up @@ -865,6 +881,12 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
onPress={() => void props.onPickDraftImages()}
showChevron={false}
/>
<ComposerToolbarButton
accessibilityLabel="Insert line break"
icon="return"
onPress={handleInsertNewline}
showChevron={false}
/>
<ControlPillMenu
actions={modelMenuActions}
onPressAction={({ nativeEvent }) => handleModelMenuAction(nativeEvent.event)}
Expand Down
45 changes: 45 additions & 0 deletions apps/mobile/src/features/threads/composerSendLabel.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import { describe, expect, it } from "@effect/vitest";

import { resolveComposerSendLabel } from "./composerSendLabel";

describe("resolveComposerSendLabel", () => {
it("labels Send when connected, idle, and the outbox is empty", () => {
expect(
resolveComposerSendLabel({
connectionState: "connected",
activeThreadBusy: false,
queueCount: 0,
}),
).toBe("Send");
});

it("labels Queue while the active thread is busy", () => {
expect(
resolveComposerSendLabel({
connectionState: "connected",
activeThreadBusy: true,
queueCount: 0,
}),
).toBe("Queue");
});

it("labels Queue when messages are already queued to send later", () => {
expect(
resolveComposerSendLabel({
connectionState: "connected",
activeThreadBusy: false,
queueCount: 2,
}),
).toBe("Queue");
});

it("labels Queue while the environment is not connected", () => {
expect(
resolveComposerSendLabel({
connectionState: "reconnecting",
activeThreadBusy: false,
queueCount: 0,
}),
).toBe("Queue");
});
});
22 changes: 22 additions & 0 deletions apps/mobile/src/features/threads/composerSendLabel.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import type { RemoteClientConnectionState } from "../../lib/connection";

/**
* The composer's send affordance doubles as a queue affordance: every "send"
* enqueues to the thread outbox, which sends-when-idle and holds-when-busy.
* The button label mirrors that decision so the user knows whether pressing it
* (or hitting Return) will dispatch now or queue for later.
*
* Returns "Queue" when the message cannot be delivered immediately — the
* environment is not connected, the active thread is still working, or the
* outbox already holds messages — and "Send" only when it will go out now.
*/
export function resolveComposerSendLabel(input: {
readonly connectionState: RemoteClientConnectionState;
readonly activeThreadBusy: boolean;
readonly queueCount: number;
}): "Send" | "Queue" {
if (input.connectionState !== "connected" || input.activeThreadBusy || input.queueCount > 0) {
return "Queue";
}
return "Send";
}
3 changes: 3 additions & 0 deletions apps/mobile/src/native/T3ComposerEditor.native.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ interface NativeComposerEditorProps extends ViewProps {
readonly onComposerPasteImages?: (event: NativePasteImagesEvent) => void;
readonly onComposerFocus?: () => void;
readonly onComposerBlur?: () => void;
readonly onComposerSubmit?: () => void;
}

const NativeView = requireNativeView<NativeComposerEditorProps>(NATIVE_MODULE_NAME);
Expand All @@ -95,6 +96,7 @@ export function ComposerEditor({
onPasteImages,
onFocus,
onBlur,
onSubmit,
contentInsetVertical = 0,
...props
}: ComposerEditorProps) {
Expand Down Expand Up @@ -275,6 +277,7 @@ export function ComposerEditor({
onComposerPasteImages={(event) => onPasteImages?.(event.nativeEvent.uris)}
onComposerFocus={onFocus}
onComposerBlur={onBlur}
onComposerSubmit={onSubmit}
/>
);
}
Expand Down
6 changes: 5 additions & 1 deletion apps/mobile/src/native/T3ComposerEditor.types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,10 @@ export interface ComposerEditorProps {
readonly onPasteImages?: (uris: ReadonlyArray<string>) => void;
readonly onFocus?: () => void;
readonly onBlur?: () => void;
/** Invoked by the native editor when Command-Return is pressed on a hardware keyboard. */
/**
* Invoked by the native editor when the composer should submit: any Return
* key with no modifier (soft keyboard or hardware), plus hardware
* Command-Return. Shift-Return still inserts a newline instead of submitting.
*/
readonly onSubmit?: () => void;
}
32 changes: 31 additions & 1 deletion packages/shared/src/composerTrigger.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import { describe, expect, it } from "vite-plus/test";

import { serializeComposerFileLink, serializeComposerMentionPath } from "./composerTrigger.ts";
import {
replaceTextRange,
serializeComposerFileLink,
serializeComposerMentionPath,
} from "./composerTrigger.ts";

describe("serializeComposerMentionPath", () => {
it("keeps simple mention paths unquoted", () => {
Expand Down Expand Up @@ -41,3 +45,29 @@ describe("serializeComposerFileLink", () => {
);
});
});

// The mobile composer's newline button inserts "\n" at the caret through this
// same insert-at-selection helper it uses for @file / skill tokens. These cover
// the newline cases specifically so the button's behaviour stays pinned.
describe("replaceTextRange newline insertion", () => {
it("inserts a newline at a collapsed caret in the middle of the text", () => {
expect(replaceTextRange("abcd", 2, 2, "\n")).toEqual({
text: "ab\ncd",
cursor: 3,
});
});

it("inserts a newline at the end of the text", () => {
expect(replaceTextRange("abc", 3, 3, "\n")).toEqual({
text: "abc\n",
cursor: 4,
});
});

it("replaces a selection range with a newline", () => {
expect(replaceTextRange("abcdef", 1, 4, "\n")).toEqual({
text: "a\nef",
cursor: 2,
});
});
});