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 numberDiff line numberDiff line change
Expand Up@@ -54,6 +54,7 @@ class T3ComposerEditorModule : Module() {
"onComposerSelectionChange",
"onComposerFocus",
"onComposerBlur",
"onComposerSubmit",
"onComposerPasteImages",
"onComposerContentSizeChange",
)
Expand Down
Original file line numberDiff line numberDiff 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 DownExpand 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 DownExpand 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 numberDiff line numberDiff 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 DownExpand 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 numberDiff line numberDiff line change
Expand Up@@ -23,6 +23,7 @@ import {
IconCircleCheck,
IconCircleXFilled,
IconCopy,
IconCornerDownLeft,
IconDeviceDesktop,
IconDots,
IconDotsCircleHorizontal,
Expand DownExpand 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 numberDiff line numberDiff 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 DownExpand 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 DownExpand 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 DownExpand 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 DownExpand 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 DownExpand 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,
});
});
});
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
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 numberDiff line numberDiff line change
Expand Up@@ -54,6 +54,7 @@ class T3ComposerEditorModule : Module() {
"onComposerSelectionChange",
"onComposerFocus",
"onComposerBlur",
"onComposerSubmit",
"onComposerPasteImages",
"onComposerContentSizeChange",
)
Expand Down
Original file line numberDiff line numberDiff 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 DownExpand 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 DownExpand 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 numberDiff line numberDiff 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 DownExpand 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 numberDiff line numberDiff line change
Expand Up@@ -23,6 +23,7 @@ import {
IconCircleCheck,
IconCircleXFilled,
IconCopy,
IconCornerDownLeft,
IconDeviceDesktop,
IconDots,
IconDotsCircleHorizontal,
Expand DownExpand 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 numberDiff line numberDiff 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 DownExpand 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 DownExpand 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 DownExpand 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 DownExpand 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 DownExpand 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,
});
});
});
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
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 numberDiff line numberDiff line change
Expand Up@@ -54,6 +54,7 @@ class T3ComposerEditorModule : Module() {
"onComposerSelectionChange",
"onComposerFocus",
"onComposerBlur",
"onComposerSubmit",
"onComposerPasteImages",
"onComposerContentSizeChange",
)
Expand Down
Original file line numberDiff line numberDiff 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 DownExpand 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 DownExpand 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 numberDiff line numberDiff 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 DownExpand 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 numberDiff line numberDiff line change
Expand Up@@ -23,6 +23,7 @@ import {
IconCircleCheck,
IconCircleXFilled,
IconCopy,
IconCornerDownLeft,
IconDeviceDesktop,
IconDots,
IconDotsCircleHorizontal,
Expand DownExpand 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 numberDiff line numberDiff 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 DownExpand 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 DownExpand 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 DownExpand 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 DownExpand 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 DownExpand 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,
});
});
});
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
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 numberDiff line numberDiff line change
Expand Up@@ -54,6 +54,7 @@ class T3ComposerEditorModule : Module() {
"onComposerSelectionChange",
"onComposerFocus",
"onComposerBlur",
"onComposerSubmit",
"onComposerPasteImages",
"onComposerContentSizeChange",
)
Expand Down
Original file line numberDiff line numberDiff 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 DownExpand 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 DownExpand 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 numberDiff line numberDiff 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 DownExpand 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 numberDiff line numberDiff line change
Expand Up@@ -23,6 +23,7 @@ import {
IconCircleCheck,
IconCircleXFilled,
IconCopy,
IconCornerDownLeft,
IconDeviceDesktop,
IconDots,
IconDotsCircleHorizontal,
Expand DownExpand 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 numberDiff line numberDiff 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 DownExpand 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 DownExpand 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 DownExpand 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 DownExpand 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 DownExpand 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,
});
});
});
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
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 numberDiff line numberDiff line change
Expand Up@@ -54,6 +54,7 @@ class T3ComposerEditorModule : Module() {
"onComposerSelectionChange",
"onComposerFocus",
"onComposerBlur",
"onComposerSubmit",
"onComposerPasteImages",
"onComposerContentSizeChange",
)
Expand Down
Original file line numberDiff line numberDiff 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 DownExpand 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 DownExpand 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 numberDiff line numberDiff 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 DownExpand 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 numberDiff line numberDiff line change
Expand Up@@ -23,6 +23,7 @@ import {
IconCircleCheck,
IconCircleXFilled,
IconCopy,
IconCornerDownLeft,
IconDeviceDesktop,
IconDots,
IconDotsCircleHorizontal,
Expand DownExpand 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 numberDiff line numberDiff 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 DownExpand 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 DownExpand 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 DownExpand 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 DownExpand 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 DownExpand 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,
});
});
});
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
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 numberDiff line numberDiff line change
Expand Up@@ -54,6 +54,7 @@ class T3ComposerEditorModule : Module() {
"onComposerSelectionChange",
"onComposerFocus",
"onComposerBlur",
"onComposerSubmit",
"onComposerPasteImages",
"onComposerContentSizeChange",
)
Expand Down
Original file line numberDiff line numberDiff 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 DownExpand 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 DownExpand 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 numberDiff line numberDiff 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 DownExpand 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 numberDiff line numberDiff line change
Expand Up@@ -23,6 +23,7 @@ import {
IconCircleCheck,
IconCircleXFilled,
IconCopy,
IconCornerDownLeft,
IconDeviceDesktop,
IconDots,
IconDotsCircleHorizontal,
Expand DownExpand 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 numberDiff line numberDiff 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 DownExpand 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 DownExpand 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 DownExpand 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 DownExpand 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 DownExpand 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,
});
});
});
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
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 numberDiff line numberDiff line change
Expand Up@@ -54,6 +54,7 @@ class T3ComposerEditorModule : Module() {
"onComposerSelectionChange",
"onComposerFocus",
"onComposerBlur",
"onComposerSubmit",
"onComposerPasteImages",
"onComposerContentSizeChange",
)
Expand Down
Original file line numberDiff line numberDiff 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 DownExpand 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 DownExpand 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 numberDiff line numberDiff 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 DownExpand 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 numberDiff line numberDiff line change
Expand Up@@ -23,6 +23,7 @@ import {
IconCircleCheck,
IconCircleXFilled,
IconCopy,
IconCornerDownLeft,
IconDeviceDesktop,
IconDots,
IconDotsCircleHorizontal,
Expand DownExpand 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 numberDiff line numberDiff 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 DownExpand 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 DownExpand 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 DownExpand 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 DownExpand 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 DownExpand 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,
});
});
});
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
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 numberDiff line numberDiff line change
Expand Up@@ -54,6 +54,7 @@ class T3ComposerEditorModule : Module() {
"onComposerSelectionChange",
"onComposerFocus",
"onComposerBlur",
"onComposerSubmit",
"onComposerPasteImages",
"onComposerContentSizeChange",
)
Expand Down
Original file line numberDiff line numberDiff 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 DownExpand 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 DownExpand 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 numberDiff line numberDiff 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 DownExpand 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 numberDiff line numberDiff line change
Expand Up@@ -23,6 +23,7 @@ import {
IconCircleCheck,
IconCircleXFilled,
IconCopy,
IconCornerDownLeft,
IconDeviceDesktop,
IconDots,
IconDotsCircleHorizontal,
Expand DownExpand 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 numberDiff line numberDiff 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 DownExpand 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 DownExpand 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 DownExpand 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 DownExpand 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 DownExpand 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,
});
});
});