Skip to content
TypeScript

fix(mobile): keep iOS composer empty after sending an autocorrected word (#30308)

shivam299f0db1e51a
diff --git a/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift b/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift
index 188ab4a97b3..48eb6fdb2d9 100644
--- a/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift
+++ b/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift
@@ -24,6 +24,7 @@ private struct ComposerControlledDocumentPayload: Decodable {
let tokensJson: String
let mostRecentEventCount: Int
let isNativeEcho: Bool
+ let resetGeneration: Int
}
private struct ComposerThemePayload: Decodable {
@@ -444,6 +445,7 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro
private var isReadOnly = false
private var isApplyingControlledValue = false
private var nativeEventCount = 0
+ private var resetGeneration = 0
private var lastContentSize = CGSize.zero
private var iconImages: [String: UIImage] = [:]
private var pendingIconUris = Set<String>()
@@ -489,6 +491,7 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro
var payload: [String: Any] = context
payload["value"] = self.textView.serializedText()
payload["eventCount"] = self.nativeEventCount
+ payload["resetGeneration"] = self.resetGeneration
payload["selection"] = ["start": selection.start, "end": selection.end]
self.onComposerPasteContext(payload)
}
@@ -499,6 +502,7 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro
self.onComposerPasteText([
"value": self.textView.serializedText(),
"eventCount": self.nativeEventCount,
+ "resetGeneration": self.resetGeneration,
"text": text,
"selection": ["start": selection.start, "end": selection.end],
])
@@ -651,11 +655,21 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro
}
func setControlledDocumentJson(_ documentJson: String) {
- guard let document = decode(ComposerControlledDocumentPayload.self, from: documentJson),
- document.mostRecentEventCount >= nativeEventCount else {
+ guard let document = decode(ComposerControlledDocumentPayload.self, from: documentJson) else {
return
}
- if document.isNativeEcho && textView.serializedText() != document.value {
+ // A parent reset (a send clear) wins over native edits it could not see; JS drops their events
+ // by generation, so the revision restarts where the parent last acknowledged.
+ let isReset = document.resetGeneration > resetGeneration
+ guard isReset || document.mostRecentEventCount >= nativeEventCount else {
+ return
+ }
+ if isReset {
+ resetGeneration = document.resetGeneration
+ nativeEventCount = document.mostRecentEventCount
+ endComposition()
+ }
+ if document.isNativeEcho && !isReset && textView.serializedText() != document.value {
return
}
if tokensJson != document.tokensJson {
@@ -900,6 +914,15 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro
emitContentSizeIfNeeded()
}
+ private func endComposition() {
+ guard textView.markedTextRange != nil else {
+ return
+ }
+ isApplyingControlledValue = true
+ textView.unmarkText()
+ isApplyingControlledValue = false
+ }
+
private func makeAttributedDocument() -> NSAttributedString {
let result = NSMutableAttributedString()
let source = value as NSString
@@ -1113,6 +1136,7 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro
"value": value,
"selection": ["start": selection.start, "end": selection.end],
"eventCount": nativeEventCount,
+ "resetGeneration": resetGeneration,
])
updatePlaceholderVisibility()
emitContentSizeIfNeeded()
@@ -1129,6 +1153,7 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro
"value": currentValue,
"selection": ["start": selection.start, "end": selection.end],
"eventCount": nativeEventCount,
+ "resetGeneration": resetGeneration,
])
}
diff --git a/apps/mobile/modules/t3-composer-editor/tests/ios/main.swift b/apps/mobile/modules/t3-composer-editor/tests/ios/main.swift
new file mode 100644
index 00000000000..2266f1a451c
--- /dev/null
+++ b/apps/mobile/modules/t3-composer-editor/tests/ios/main.swift
@@ -0,0 +1,110 @@
+import UIKit
+
+func check(_ passed: Bool, _ message: String) {
+ if !passed {
+ FileHandle.standardError.write(Data((message + "\n").utf8))
+ exit(1)
+ }
+}
+
+extension T3ComposerEditorView {
+ var editor: UITextView { textView }
+ var text: String { textView.serializedText() }
+}
+
+func document(_ value: String, revision: Int, resetGeneration: Int = 0, isNativeEcho: Bool = false) -> String {
+ let payload: [String: Any] = [
+ "value": value,
+ "selection": NSNull(),
+ "tokensJson": "[]",
+ "mostRecentEventCount": revision,
+ "isNativeEcho": isNativeEcho,
+ "resetGeneration": resetGeneration,
+ ]
+ return String(data: try! JSONSerialization.data(withJSONObject: payload), encoding: .utf8)!
+}
+
+func replace(_ view: T3ComposerEditorView, _ target: String, with replacement: String) {
+ let editor = view.editor
+ let location = (editor.text as NSString).range(of: target).location
+ let start = editor.position(from: editor.beginningOfDocument, offset: location)!
+ let end = editor.position(from: start, offset: (target as NSString).length)!
+ editor.replace(editor.textRange(from: start, to: end)!, withText: replacement)
+}
+
+func makeEditor(_ value: String) -> T3ComposerEditorView {
+ let view = T3ComposerEditorView()
+ view.frame = CGRect(x: 0, y: 0, width: 320, height: 200)
+ view.setControlledDocumentJson(document(value, revision: 0))
+ check(view.text == value, "Initial controlled value was not applied")
+ return view
+}
+
+// A send clears the draft after an autocorrection the parent had not received yet.
+do {
+ let view = makeEditor("hello wrold")
+ replace(view, "wrold", with: "world")
+ let corrected = view.onComposerChange.payloads.last
+ check(corrected?["value"] as? String == "hello world", "Autocorrection did not emit a change")
+ check(corrected?["eventCount"] as? Int == 1, "Autocorrection did not advance the native revision")
+ view.setControlledDocumentJson(document("", revision: 0, resetGeneration: 1))
+ check(view.text == "", "Send clear lost to an autocorrection the parent had not seen: \(view.text)")
+ check(corrected?["resetGeneration"] as? Int == 0, "Pre-clear native event must carry the old reset generation")
+ view.editor.insertText("n")
+ let typed = view.onComposerChange.payloads.last
+ check(typed?["value"] as? String == "n", "Typing after the clear did not start from empty")
+ check(typed?["resetGeneration"] as? Int == 1, "Typing after the clear must carry the new reset generation")
+ check(typed?["eventCount"] as? Int == 1, "Typing after the clear must follow the parent's revision")
+}
+
+// An attachment-only send can reset an empty JS draft before a native keystroke is delivered.
+do {
+ let view = makeEditor("")
+ view.editor.insertText("x")
+ view.setControlledDocumentJson(document("", revision: 0, resetGeneration: 1, isNativeEcho: true))
+ check(view.text == "", "An echo-marked reset retained an undelivered keystroke: \(view.text)")
+ view.editor.insertText("n")
+ check(view.text == "n", "Typing after an echo-marked reset restored the previous keystroke")
+ view.setControlledDocumentJson(document("", revision: 1, resetGeneration: 1, isNativeEcho: true))
+ check(view.text == "n", "An ordinary mismatched echo overwrote newer native typing")
+}
+
+// Moving the editor to another draft can lower the parent's reset generation; that payload stays ordinary.
+do {
+ let view = makeEditor("draft a")
+ view.setControlledDocumentJson(document("", revision: 0, resetGeneration: 2))
+ view.setControlledDocumentJson(document("draft b", revision: 0, resetGeneration: 1))
+ check(view.text == "draft b", "A lower reset generation was rejected")
+ view.editor.insertText("!")
+ check(
+ view.onComposerChange.payloads.last?["resetGeneration"] as? Int == 2,
+ "A lower reset generation rewound the editor's"
+ )
+}
+
+// Without a reset, a payload behind the native revision still loses to newer typing.
+do {
+ let view = makeEditor("ab")
+ view.editor.selectedRange = NSRange(location: 2, length: 0)
+ view.editor.insertText("c")
+ view.setControlledDocumentJson(document("ab", revision: 0))
+ check(view.text == "abc", "A stale controlled value overwrote newer native typing")
+}
+
+// A send clear during an IME composition must not come back when the composition commits.
+do {
+ let view = makeEditor("hello ")
+ view.editor.selectedRange = NSRange(location: 6, length: 0)
+ view.editor.setMarkedText("wor", selectedRange: NSRange(location: 3, length: 0))
+ check(view.editor.markedTextRange != nil, "Harness could not start a composition")
+ let revision = view.onComposerChange.payloads.last?["eventCount"] as? Int ?? 0
+ view.setControlledDocumentJson(document("", revision: revision, resetGeneration: 1))
+ view.editor.unmarkText()
+ check(view.text == "", "Send clear lost to a committed composition: \(view.text)")
+ check(
+ !view.onComposerChange.payloads.contains { ($0["value"] as? String)?.contains("hello") == true && ($0["resetGeneration"] as? Int) == 1 },
+ "Committed composition republished the sent draft"
+ )
+}
+
+print("composer editor tests passed")
diff --git a/apps/mobile/modules/t3-composer-editor/tests/run-ios.sh b/apps/mobile/modules/t3-composer-editor/tests/run-ios.sh
new file mode 100755
index 00000000000..2350130889a
--- /dev/null
+++ b/apps/mobile/modules/t3-composer-editor/tests/run-ios.sh
@@ -0,0 +1,37 @@
+#!/bin/bash
+set -euo pipefail
+module_dir=$(cd "$(dirname "$0")/.." && pwd)
+sdk=$(xcrun --sdk macosx --show-sdk-path)
+compiler=$(xcrun --find swiftc)
+output=$(mktemp -d)
+trap 'rm -rf "$output"' EXIT
+# Compile the real editor view; only the Expo bridge and clipboard are stubbed.
+python3 - "$module_dir" "$output/main.swift" <<'PYTHON'
+import sys
+from pathlib import Path
+module = Path(sys.argv[1])
+source = (module / "ios/T3ComposerEditorView.swift").read_text()
+source = source.replace("import ExpoModulesCore\n", "")
+stubs = """
+public final class AppContext {}
+open class ExpoView: UIView {
+ public required init(appContext: AppContext? = nil) { super.init(frame: .zero) }
+ @available(*, unavailable)
+ public required init?(coder: NSCoder) { fatalError("init(coder:) is unused") }
+}
+final class EventDispatcher {
+ var payloads: [[String: Any]] = []
+ func callAsFunction(_ payload: [String: Any] = [:]) { payloads.append(payload) }
+}
+enum T3ComposerClipboard {
+ static func hasThreadLink(_ text: String) -> Bool { false }
+ static func read() -> [String: String] { [:] }
+ static func write(text: String, fragment: String) {}
+}
+"""
+Path(sys.argv[2]).write_text(source + "\n" + stubs + "\n" + (module / "tests/ios/main.swift").read_text())
+PYTHON
+"$compiler" -target "$(uname -m)-apple-ios16.1-macabi" -sdk "$sdk" \
+ -F "$sdk/System/iOSSupport/System/Library/Frameworks" \
+ "$output/main.swift" -o "$output/editor-tests"
+"$output/editor-tests"
diff --git a/apps/mobile/src/components/ComposerEditor.ios.test.tsx b/apps/mobile/src/components/ComposerEditor.ios.test.tsx
new file mode 100644
index 00000000000..d5e99928ac7
--- /dev/null
+++ b/apps/mobile/src/components/ComposerEditor.ios.test.tsx
@@ -0,0 +1,187 @@
+import { RegistryContext } from "@effect/atom-react";
+import { act, useLayoutEffect, useRef, type ReactNode } from "react";
+import { createRoot } from "react-dom/client";
+import { expect, it, vi } from "vite-plus/test";
+
+interface NativeEvent {
+ readonly value: string;
+ readonly selection: { readonly start: number; readonly end: number };
+ readonly eventCount: number;
+ readonly resetGeneration: number;
+}
+
+interface NativeProps {
+ readonly controlledDocumentJson: string;
+ readonly onComposerChange: (event: { readonly nativeEvent: NativeEvent }) => void;
+}
+
+// Mirrors the iOS editor's revision and reset bookkeeping (T3ComposerEditorView.setControlledDocumentJson).
+const native = vi.hoisted(() => ({
+ text: "",
+ eventCount: 0,
+ resetGeneration: 0,
+ props: null as NativeProps | null,
+ deliver: null as ((event: NativeEvent) => void) | null,
+}));
+
+function NativeView(props: NativeProps) {
+ const propsRef = useRef(props);
+ useLayoutEffect(() => {
+ Object.assign(native, { text: "", eventCount: 0, resetGeneration: 0 });
+ }, []);
+ useLayoutEffect(() => {
+ propsRef.current = props;
+ native.props = props;
+ native.deliver = (event) => propsRef.current.onComposerChange({ nativeEvent: event });
+ });
+ const { controlledDocumentJson } = props;
+ useLayoutEffect(() => {
+ const document = JSON.parse(controlledDocumentJson) as {
+ value: string;
+ mostRecentEventCount: number;
+ resetGeneration?: number;
+ };
+ const resetGeneration = document.resetGeneration ?? 0;
+ const isReset = resetGeneration > native.resetGeneration;
+ if (!isReset && document.mostRecentEventCount < native.eventCount) return;
+ if (isReset) {
+ native.resetGeneration = resetGeneration;
+ native.eventCount = document.mostRecentEventCount;
+ }
+ native.text = document.value;
+ }, [controlledDocumentJson]);
+ return null;
+}
+
+function emit(value: string, resetGeneration = native.resetGeneration) {
+ native.eventCount += 1;
+ native.text = value;
+ native.props!.onComposerChange({
+ nativeEvent: {
+ value,
+ selection: { start: value.length, end: value.length },
+ eventCount: native.eventCount,
+ resetGeneration,
+ },
+ });
+}
+
+vi.mock("expo", () => ({ requireNativeView: () => NativeView }));
+// Vite resolves the platform-neutral module; the race lives in the iOS editor.
+vi.mock("../native/T3ComposerEditor", () => import("../native/T3ComposerEditor.ios"));
+vi.mock("react-native", () => ({ StyleSheet: { flatten: (style: unknown) => style } }));
+vi.mock("expo-file-system", () => ({
+ Directory: class {
+ create() {}
+ },
+ File: class {
+ exists = false;
+ write() {}
+ },
+ Paths: { document: { uri: "file:///documents" } },
+}));
+vi.mock("./ui/Dialog", () => ({ alert: vi.fn() }));
+vi.mock("./ui/AppText", () => ({ AppText: ({ children }: { children?: ReactNode }) => children }));
+vi.mock("./ComposerContextSheet", () => ({ ComposerContextSheet: () => null }));
+vi.mock("../features/threads/useOpenLinkedThread", () => ({ useOpenLinkedThread: () => vi.fn() }));
+vi.mock("../state/peerLinks", () => ({ useLinkedEnvironments: () => [] }));
+vi.mock("../state/preferences", async () => {
+ const { Atom } = await import("effect/reactivity");
+ return { mobilePreferencesAtom: Atom.make({ _tag: "Initial" }) };
+});
+vi.mock("../lib/composerContextClipboard", () => ({ importComposerContextClipboard: vi.fn() }));
+vi.mock("../lib/useUniwindTheme", () => ({ useUniwindTheme: () => ({}) }));
+vi.mock("../lib/nativeComposerTheme", () => ({ createNativeComposerTheme: () => ({}) }));
+vi.mock("../lib/contextChipIconSource", () => ({ contextChipIconUri: () => "" }));
+vi.mock("../features/settings/appearance/useScaledTextRole", () => ({
+ useScaledTextRole: () => ({ fontSize: 16, lineHeight: 22 }),
+}));
+vi.mock("../lib/uuid", () => ({ uuidv4: () => "uuid", randomHex: () => "0000" }));
+vi.mock("../state/assets", () => ({ assetEnvironment: {} }));
+vi.mock("../state/attachments", () => ({ attachmentEnvironment: {} }));
+vi.mock("../state/session", () => ({ environmentSession: {} }));
+vi.mock("@t3tools/client-runtime/state/runtime", () => ({
+ createEnvironmentRpcCommand: () => Symbol("rpc-command"),
+ settlePromise: vi.fn(),
+ squashAtomCommandFailure: vi.fn(),
+}));
+
+import { appAtomRegistry } from "../state/atom-registry";
+import {
+ clearComposerDraftContent,
+ getComposerDraftSnapshot,
+ setComposerDraftText,
+ useComposerDraft,
+} from "../state/use-composer-drafts";
+import { ComposerEditor } from "./ComposerEditor";
+
+const DRAFT_KEY = "environment:thread";
+
+function ThreadComposer({ draftKey = DRAFT_KEY }: { draftKey?: string }) {
+ const draft = useComposerDraft(draftKey);
+ return (
+ <ComposerEditor
+ draftKey={draftKey}
+ value={draft.text}
+ onChangeText={(text) => setComposerDraftText(draftKey, text)}
+ />
+ );
+}
+
+it("keeps a sent draft cleared when an autocorrection lands in the same batch as the send", async () => {
+ (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+ Object.assign(native, { text: "", eventCount: 0, resetGeneration: 0, props: null });
+ const root = createRoot(document.createElement("div"));
+ await using _root = { [Symbol.asyncDispose]: async () => act(() => root.unmount()) };
+ await act(async () =>
+ root.render(
+ <RegistryContext.Provider value={appAtomRegistry}>
+ <ThreadComposer />
+ </RegistryContext.Provider>,
+ ),
+ );
+
+ await act(async () => emit("Hello wrold"));
+ expect(getComposerDraftSnapshot(DRAFT_KEY).text).toBe("Hello wrold");
+
+ // Send clears the draft; iOS commits the pending autocorrection as the keyboard dismisses.
+ await act(async () => {
+ clearComposerDraftContent(DRAFT_KEY);
+ emit("Hello world");
+ });
+ expect(getComposerDraftSnapshot(DRAFT_KEY).text).toBe("");
+ expect(native.text).toBe("");
+
+ await act(async () => emit("n"));
+ expect(getComposerDraftSnapshot(DRAFT_KEY).text).toBe("n");
+ expect(native.text).toBe("n");
+});
+
+it("keeps a pending event from the previous native editor out of the selected draft", async () => {
+ (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+ const first = "switch-draft:first";
+ const second = "switch-draft:second";
+ setComposerDraftText(first, "Draft A");
+ setComposerDraftText(second, "Draft B");
+ const root = createRoot(document.createElement("div"));
+ await using _root = { [Symbol.asyncDispose]: async () => act(() => root.unmount()) };
+ const renderDraft = (draftKey: string) =>
+ root.render(
+ <RegistryContext.Provider value={appAtomRegistry}>
+ <ThreadComposer draftKey={draftKey} />
+ </RegistryContext.Provider>,
+ );
+ await act(async () => renderDraft(first));
+ const deliverPendingEvent = native.deliver!;
+ await act(async () => renderDraft(second));
+ await act(async () =>
+ deliverPendingEvent({
+ value: "Draft A corrected",
+ selection: { start: 17, end: 17 },
+ eventCount: 1,
+ resetGeneration: 0,
+ }),
+ );
+ expect(getComposerDraftSnapshot(second).text).toBe("Draft B");
+ expect(native.text).toBe("Draft B");
+});
diff --git a/apps/mobile/src/components/ComposerEditor.tsx b/apps/mobile/src/components/ComposerEditor.tsx
index 59c0a74e452..9a146487625 100644
--- a/apps/mobile/src/components/ComposerEditor.tsx
+++ b/apps/mobile/src/components/ComposerEditor.tsx
@@ -21,6 +21,7 @@ import {
setComposerDraftContext,
setComposerContextImporting,
useComposerDraft,
+ useComposerDraftResetGeneration,
} from "../state/use-composer-drafts";
import { importComposerContextClipboard } from "../lib/composerContextClipboard";
import { startComposerDraftOperation } from "../state/composerDraftOperations";
@@ -57,6 +58,7 @@ export function ComposerEditor({
...props
}: ComposerEditorProps) {
const draft = useComposerDraft(draftKey ?? null);
+ const readResetGeneration = useComposerDraftResetGeneration(draftKey ?? null);
const preferencesResult = useAtomValue(mobilePreferencesAtom);
const preferredEnterBehavior = AsyncResult.isSuccess(preferencesResult)
? preferencesResult.value.composerEnterBehavior
@@ -175,10 +177,11 @@ export function ComposerEditor({
<>
{/* Reset revision history with the recreated iOS view without aborting context imports. */}
<NativeComposerEditor
- key={hidden ? "hidden" : "visible"}
+ key={`${hidden ? "hidden" : "visible"}:${draftKey ?? "no-draft"}`}
{...props}
enterBehavior={props.enterBehavior ?? preferredEnterBehavior}
onChangeText={changeText}
+ readResetGeneration={readResetGeneration}
readOnly={props.readOnly || importing}
onSubmit={importing ? undefined : props.onSubmit}
clipboardFragment={clipboardFragment ?? undefined}
diff --git a/apps/mobile/src/native/T3ComposerEditor.ios.tsx b/apps/mobile/src/native/T3ComposerEditor.ios.tsx
index c649b12292b..6b1ebc939bf 100644
--- a/apps/mobile/src/native/T3ComposerEditor.ios.tsx
+++ b/apps/mobile/src/native/T3ComposerEditor.ios.tsx
@@ -40,17 +40,20 @@ import type { ComposerEditorProps, ComposerEditorSelection } from "./T3ComposerE
const NATIVE_MODULE_NAME = "T3ComposerEditor";
const EMPTY_SKILLS: NonNullable<ComposerEditorProps["skills"]> = [];
+const NO_RESET = () => 0;
type NativeEditorEvent = NativeSyntheticEvent<{
readonly value: string;
readonly selection: ComposerEditorSelection;
readonly eventCount: number;
+ readonly resetGeneration: number;
}>;
type NativeSelectionEvent = NativeSyntheticEvent<{
readonly value: string;
readonly selection: ComposerEditorSelection;
readonly eventCount: number;
+ readonly resetGeneration: number;
}>;
type NativePasteImagesEvent = NativeSyntheticEvent<{
@@ -60,6 +63,7 @@ type NativePasteImagesEvent = NativeSyntheticEvent<{
type NativePasteTextEvent = NativeSyntheticEvent<{
readonly value: string;
readonly eventCount: number;
+ readonly resetGeneration: number;
readonly text: string;
readonly selection: ComposerEditorSelection;
}>;
@@ -138,12 +142,15 @@ export function ComposerEditor({
onSubmit,
onContentSizeChange,
contentInsetVertical = 0,
+ readResetGeneration = NO_RESET,
...props
}: ComposerEditorProps) {
const nativeRef = useRef<NativeComposerEditorRef>(null);
const mostRecentEventCountRef = useRef(0);
const [mostRecentEventCount, setMostRecentEventCount] = useState(0);
const [, forceNativeEventRender] = useState(0);
+ // Native stamps every event with the reset generation it had applied.
+ const nativeResetGenerationRef = useRef(0);
// Start history empty so restored drafts or recycled views receive a non-echo controlled payload.
const nativeEventSnapshotsRef = useRef<ComposerNativeEventSnapshot[]>([]);
// Tokens advance from the previous committed value; render-phase state keeps
@@ -215,12 +222,17 @@ export function ComposerEditor({
// the native revision and rejected by the editor instead of re-applying a
// stale caret or stale text mid-typing.
/* oxlint-disable react/refs -- Native controlled edits must reconcile against the last acknowledged native event before sending the next payload. */
- const controlledEventCount = resolveComposerControlledEventCount(
- props.value,
- selection ?? null,
- mostRecentEventCount,
- nativeEventSnapshotsRef.current,
- );
+ const resetGeneration = readResetGeneration();
+ // Native restarts its revision at a reset's stamp, so stamp it at the latest acknowledged event.
+ const controlledEventCount =
+ resetGeneration > nativeResetGenerationRef.current
+ ? mostRecentEventCount
+ : resolveComposerControlledEventCount(
+ props.value,
+ selection ?? null,
+ mostRecentEventCount,
+ nativeEventSnapshotsRef.current,
+ );
const acknowledgesLatestNativeEvent = isComposerNativeEcho(
props.value,
selection ?? null,
@@ -236,6 +248,7 @@ export function ComposerEditor({
tokensJson,
mostRecentEventCount: controlledEventCount,
isNativeEcho,
+ resetGeneration,
});
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- prunes native editor event snapshots once a committed payload acknowledges them
useEffect(() => {
@@ -264,23 +277,27 @@ export function ComposerEditor({
nativeEventSnapshotsRef,
]);
const acceptNativeEvent = useCallback(
- (eventCount: number, value: string, nextSelection: ComposerEditorSelection) => {
+ (event: NativeEditorEvent["nativeEvent"]) => {
+ // Read at delivery: a send can clear the draft in the same batch, before this view re-renders.
const acknowledgedEventCount = acknowledgeComposerNativeEvent(
mostRecentEventCountRef.current,
- eventCount,
+ event.eventCount,
+ readResetGeneration(),
+ event.resetGeneration,
);
if (acknowledgedEventCount === null) {
return false;
}
mostRecentEventCountRef.current = acknowledgedEventCount;
+ nativeResetGenerationRef.current = event.resetGeneration;
nativeEventSnapshotsRef.current.push({
eventCount: acknowledgedEventCount,
- value,
- selection: nextSelection,
+ value: event.value,
+ selection: event.selection,
});
return acknowledgedEventCount;
},
- [nativeEventSnapshotsRef],
+ [nativeEventSnapshotsRef, readResetGeneration],
);
const themeJson = JSON.stringify(createNativeComposerTheme(theme));
const resolvedTextStyle = StyleSheet.flatten(textStyle) ?? {};
@@ -318,11 +335,7 @@ export function ComposerEditor({
maxInputChars={PROVIDER_SEND_TURN_MAX_INPUT_CHARS}
style={style as StyleProp<ViewStyle>}
onComposerChange={(event) => {
- const acknowledgedEventCount = acceptNativeEvent(
- event.nativeEvent.eventCount,
- event.nativeEvent.value,
- event.nativeEvent.selection,
- );
+ const acknowledgedEventCount = acceptNativeEvent(event.nativeEvent);
if (acknowledgedEventCount === false) return;
onChangeText(event.nativeEvent.value);
onSelectionChange?.(event.nativeEvent.selection);
@@ -330,11 +343,7 @@ export function ComposerEditor({
forceNativeEventRender((sequence) => sequence + 1);
}}
onComposerSelectionChange={(event) => {
- const acknowledgedEventCount = acceptNativeEvent(
- event.nativeEvent.eventCount,
- event.nativeEvent.value,
- event.nativeEvent.selection,
- );
+ const acknowledgedEventCount = acceptNativeEvent(event.nativeEvent);
if (acknowledgedEventCount === false) return;
// Selection events may carry post-edit text; publish it with its revision or stale drafts can overwrite native text.
if (event.nativeEvent.value !== props.value) {
@@ -348,11 +357,7 @@ export function ComposerEditor({
onComposerContextPress={(event) => props.onContextPress?.(event.nativeEvent)}
onComposerPasteContext={(event) => {
const paste = event.nativeEvent;
- const acknowledgedEventCount = acceptNativeEvent(
- paste.eventCount,
- paste.value,
- paste.selection,
- );
+ const acknowledgedEventCount = acceptNativeEvent(paste);
if (acknowledgedEventCount === false) return;
onChangeText(paste.value);
onSelectionChange?.(paste.selection);
@@ -362,11 +367,7 @@ export function ComposerEditor({
}}
onComposerPasteText={(event) => {
const paste = event.nativeEvent;
- const acknowledgedEventCount = acceptNativeEvent(
- paste.eventCount,
- paste.value,
- paste.selection,
- );
+ const acknowledgedEventCount = acceptNativeEvent(paste);
if (acknowledgedEventCount === false) return;
// Sync before capturing async paste targets; props may lag the last native keystroke.
onChangeText(paste.value);
diff --git a/apps/mobile/src/native/T3ComposerEditor.tsx b/apps/mobile/src/native/T3ComposerEditor.tsx
index d621deb3c6a..6428c9beeb0 100644
--- a/apps/mobile/src/native/T3ComposerEditor.tsx
+++ b/apps/mobile/src/native/T3ComposerEditor.tsx
@@ -18,6 +18,7 @@ export function ComposerEditor({
contentInsetVertical = 0,
singleLineCentered: _singleLineCentered,
enterBehavior: _enterBehavior,
+ readResetGeneration: _readResetGeneration,
readOnly = false,
onContentSizeChange,
...props
diff --git a/apps/mobile/src/native/T3ComposerEditor.types.ts b/apps/mobile/src/native/T3ComposerEditor.types.ts
index f924ebc43ef..718ecb09ba5 100644
--- a/apps/mobile/src/native/T3ComposerEditor.types.ts
+++ b/apps/mobile/src/native/T3ComposerEditor.types.ts
@@ -58,6 +58,11 @@ export interface ComposerEditorProps {
readonly style?: StyleProp<ViewStyle>;
readonly textStyle?: StyleProp<TextStyle>;
readonly onChangeText: (value: string) => void;
+ /**
+ * iOS: the owner's reset generation, raised synchronously when it replaces the text outright
+ * (send, discard). Native edits the editor made before applying that reset are dropped.
+ */
+ readonly readResetGeneration?: () => number;
readonly onSelectionChange?: (selection: ComposerEditorSelection) => void;
readonly onPasteImages?: (uris: ReadonlyArray<string>) => void;
readonly onContextPress?: (reference: {
diff --git a/apps/mobile/src/native/composerEditorRevision.ts b/apps/mobile/src/native/composerEditorRevision.ts
index 1b075a81c74..dc037b66f3d 100644
--- a/apps/mobile/src/native/composerEditorRevision.ts
+++ b/apps/mobile/src/native/composerEditorRevision.ts
@@ -12,8 +12,15 @@ interface ComposerEditorSelection {
export function acknowledgeComposerNativeEvent(
mostRecentEventCount: number,
incomingEventCount: number,
+ resetGeneration = 0,
+ incomingResetGeneration = 0,
): number | null {
- if (!Number.isSafeInteger(incomingEventCount) || incomingEventCount < mostRecentEventCount) {
+ if (
+ !Number.isSafeInteger(incomingEventCount) ||
+ incomingEventCount < mostRecentEventCount ||
+ // Events from before the editor applied a parent reset describe text the parent replaced.
+ incomingResetGeneration < resetGeneration
+ ) {
return null;
}
return incomingEventCount;
diff --git a/apps/mobile/src/state/use-composer-drafts.ts b/apps/mobile/src/state/use-composer-drafts.ts
index 564becccf7d..2a19a7a4f7b 100644
--- a/apps/mobile/src/state/use-composer-drafts.ts
+++ b/apps/mobile/src/state/use-composer-drafts.ts
@@ -104,6 +104,30 @@ const composerDraftSelectionAtom = Atom.family((_draftKey: string) =>
);
const NO_COMPOSER_DRAFT_SELECTION_ATOM = Atom.make<ComposerDraftSelection | null>(null);
+// Never persisted. One counter across drafts, so an editor moved between drafts never
+// sees a later reset numbered below one it already applied.
+let lastComposerDraftReset = 0;
+const composerDraftResetAtom = Atom.family((_draftKey: string) =>
+ Atom.make(0).pipe(Atom.withLabel("mobile:composer-draft-reset")),
+);
+const NO_COMPOSER_DRAFT_RESET_ATOM = Atom.make(0);
+
+function markComposerDraftReset(draftKey: string): void {
+ lastComposerDraftReset += 1;
+ appAtomRegistry.set(composerDraftResetAtom(draftKey), lastComposerDraftReset);
+}
+
+/**
+ * Raised when a draft's text is replaced outright (sent, discarded). Native editor events read it
+ * synchronously, so an edit the editor made before applying the reset cannot restore the text.
+ */
+export function useComposerDraftResetGeneration(draftKey: string | null): () => number {
+ const atom = draftKey === null ? NO_COMPOSER_DRAFT_RESET_ATOM : composerDraftResetAtom(draftKey);
+ // Subscribing re-renders the editor so it sends the reset even when the text did not change.
+ useAtomValue(atom);
+ return () => appAtomRegistry.get(atom);
+}
+
export function rememberComposerDraftSelection(
draftKey: string,
text: string,
@@ -1827,6 +1851,7 @@ export function clearComposerDraftContent(
},
): void {
const previousAttachments = getComposerDraftSnapshot(draftKey).attachments;
+ markComposerDraftReset(draftKey);
updateComposerDrafts((current) => clearComposerDraftContentState(current, draftKey, options));
if (!options?.deferAttachmentCleanup) {
scheduleUnusedComposerAttachmentCleanup(previousAttachments);
@@ -1838,6 +1863,7 @@ export function clearComposerDraft(
options?: { readonly deferAttachmentCleanup?: boolean },
): void {
abortComposerDraftOperations(draftKey);
+ markComposerDraftReset(draftKey);
const previousAttachments = getComposerDraftSnapshot(draftKey).attachments;
updateComposerDrafts((current) => {
if (!current[draftKey]) {
diff --git a/apps/mobile/vite.config.ts b/apps/mobile/vite.config.ts
index 6f5c4558b5a..75400348bfb 100644
--- a/apps/mobile/vite.config.ts
+++ b/apps/mobile/vite.config.ts
@@ -30,6 +30,7 @@ const reactTests = [
"src/features/threads/UsageLimitRecoveryCard.test.tsx",
"src/features/threads/NewTaskDraftRouteScreen.test.tsx",
"src/native/NativeHeaderToolbar.test.tsx",
+ "src/components/ComposerEditor.ios.test.tsx",
"src/native/V5StackHeader.ios.test.tsx",
"src/native/useRestingTopOffset.test.tsx",
"src/native/useRetryingImageSource.test.tsx",