The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 22, 04:30 UTC
fix(mobile): keep iOS composer empty after sending an autocorrected word (#30308)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: maria-rcks <maria@kuuro.net>
shivam committed
Nov 5, 2026 at 06:40 UTC
299f0db1e51a91dad6126b4e4927d5de63108b6f
11 files changed
+439
-36
apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift
+28
-3
@@ -24,6 +24,7 @@ private struct ComposerControlledDocumentPayload: Decodable {
24
let tokensJson: String
25
let mostRecentEventCount: Int
26
let isNativeEcho: Bool
27
+ let resetGeneration: Int
28
}
29
30
private struct ComposerThemePayload: Decodable {
@@ -444,6 +445,7 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro
445
private var isReadOnly = false
446
private var isApplyingControlledValue = false
447
private var nativeEventCount = 0
448
+ private var resetGeneration = 0
449
private var lastContentSize = CGSize.zero
450
private var iconImages: [String: UIImage] = [:]
451
private var pendingIconUris = Set<String>()
@@ -489,6 +491,7 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro
491
var payload: [String: Any] = context
492
payload["value"] = self.textView.serializedText()
493
payload["eventCount"] = self.nativeEventCount
494
+ payload["resetGeneration"] = self.resetGeneration
495
payload["selection"] = ["start": selection.start, "end": selection.end]
496
self.onComposerPasteContext(payload)
497
}
@@ -499,6 +502,7 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro
502
self.onComposerPasteText([
503
"value": self.textView.serializedText(),
504
"eventCount": self.nativeEventCount,
505
+ "resetGeneration": self.resetGeneration,
506
"text": text,
507
"selection": ["start": selection.start, "end": selection.end],
508
])
@@ -651,11 +655,21 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro
655
}
656
657
func setControlledDocumentJson(_ documentJson: String) {
654
- guard let document = decode(ComposerControlledDocumentPayload.self, from: documentJson),
655
- document.mostRecentEventCount >= nativeEventCount else {
658
+ guard let document = decode(ComposerControlledDocumentPayload.self, from: documentJson) else {
659
return
660
}
658
- if document.isNativeEcho && textView.serializedText() != document.value {
661
+ // A parent reset (a send clear) wins over native edits it could not see; JS drops their events
662
+ // by generation, so the revision restarts where the parent last acknowledged.
663
+ let isReset = document.resetGeneration > resetGeneration
664
+ guard isReset || document.mostRecentEventCount >= nativeEventCount else {
665
+ return
666
+ }
667
+ if isReset {
668
+ resetGeneration = document.resetGeneration
669
+ nativeEventCount = document.mostRecentEventCount
670
+ endComposition()
671
+ }
672
+ if document.isNativeEcho && !isReset && textView.serializedText() != document.value {
673
return
674
}
675
if tokensJson != document.tokensJson {
@@ -900,6 +914,15 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro
914
emitContentSizeIfNeeded()
915
}
916
917
+ private func endComposition() {
918
+ guard textView.markedTextRange != nil else {
919
+ return
920
+ }
921
+ isApplyingControlledValue = true
922
+ textView.unmarkText()
923
+ isApplyingControlledValue = false
924
+ }
925
+
926
private func makeAttributedDocument() -> NSAttributedString {
927
let result = NSMutableAttributedString()
928
let source = value as NSString
@@ -1113,6 +1136,7 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro
1136
"value": value,
1137
"selection": ["start": selection.start, "end": selection.end],
1138
"eventCount": nativeEventCount,
1139
+ "resetGeneration": resetGeneration,
1140
])
1141
updatePlaceholderVisibility()
1142
emitContentSizeIfNeeded()
@@ -1129,6 +1153,7 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro
1153
"value": currentValue,
1154
"selection": ["start": selection.start, "end": selection.end],
1155
"eventCount": nativeEventCount,
1156
+ "resetGeneration": resetGeneration,
1157
])
1158
}
1159
apps/mobile/modules/t3-composer-editor/tests/ios/main.swift
new
+110
@@ -0,0 +1,110 @@
1
+import UIKit
2
+
3
+func check(_ passed: Bool, _ message: String) {
4
+ if !passed {
5
+ FileHandle.standardError.write(Data((message + "\n").utf8))
6
+ exit(1)
7
+ }
8
+}
9
+
10
+extension T3ComposerEditorView {
11
+ var editor: UITextView { textView }
12
+ var text: String { textView.serializedText() }
13
+}
14
+
15
+func document(_ value: String, revision: Int, resetGeneration: Int = 0, isNativeEcho: Bool = false) -> String {
16
+ let payload: [String: Any] = [
17
+ "value": value,
18
+ "selection": NSNull(),
19
+ "tokensJson": "[]",
20
+ "mostRecentEventCount": revision,
21
+ "isNativeEcho": isNativeEcho,
22
+ "resetGeneration": resetGeneration,
23
+ ]
24
+ return String(data: try! JSONSerialization.data(withJSONObject: payload), encoding: .utf8)!
25
+}
26
+
27
+func replace(_ view: T3ComposerEditorView, _ target: String, with replacement: String) {
28
+ let editor = view.editor
29
+ let location = (editor.text as NSString).range(of: target).location
30
+ let start = editor.position(from: editor.beginningOfDocument, offset: location)!
31
+ let end = editor.position(from: start, offset: (target as NSString).length)!
32
+ editor.replace(editor.textRange(from: start, to: end)!, withText: replacement)
33
+}
34
+
35
+func makeEditor(_ value: String) -> T3ComposerEditorView {
36
+ let view = T3ComposerEditorView()
37
+ view.frame = CGRect(x: 0, y: 0, width: 320, height: 200)
38
+ view.setControlledDocumentJson(document(value, revision: 0))
39
+ check(view.text == value, "Initial controlled value was not applied")
40
+ return view
41
+}
42
+
43
+// A send clears the draft after an autocorrection the parent had not received yet.
44
+do {
45
+ let view = makeEditor("hello wrold")
46
+ replace(view, "wrold", with: "world")
47
+ let corrected = view.onComposerChange.payloads.last
48
+ check(corrected?["value"] as? String == "hello world", "Autocorrection did not emit a change")
49
+ check(corrected?["eventCount"] as? Int == 1, "Autocorrection did not advance the native revision")
50
+ view.setControlledDocumentJson(document("", revision: 0, resetGeneration: 1))
51
+ check(view.text == "", "Send clear lost to an autocorrection the parent had not seen: \(view.text)")
52
+ check(corrected?["resetGeneration"] as? Int == 0, "Pre-clear native event must carry the old reset generation")
53
+ view.editor.insertText("n")
54
+ let typed = view.onComposerChange.payloads.last
55
+ check(typed?["value"] as? String == "n", "Typing after the clear did not start from empty")
56
+ check(typed?["resetGeneration"] as? Int == 1, "Typing after the clear must carry the new reset generation")
57
+ check(typed?["eventCount"] as? Int == 1, "Typing after the clear must follow the parent's revision")
58
+}
59
+
60
+// An attachment-only send can reset an empty JS draft before a native keystroke is delivered.
61
+do {
62
+ let view = makeEditor("")
63
+ view.editor.insertText("x")
64
+ view.setControlledDocumentJson(document("", revision: 0, resetGeneration: 1, isNativeEcho: true))
65
+ check(view.text == "", "An echo-marked reset retained an undelivered keystroke: \(view.text)")
66
+ view.editor.insertText("n")
67
+ check(view.text == "n", "Typing after an echo-marked reset restored the previous keystroke")
68
+ view.setControlledDocumentJson(document("", revision: 1, resetGeneration: 1, isNativeEcho: true))
69
+ check(view.text == "n", "An ordinary mismatched echo overwrote newer native typing")
70
+}
71
+
72
+// Moving the editor to another draft can lower the parent's reset generation; that payload stays ordinary.
73
+do {
74
+ let view = makeEditor("draft a")
75
+ view.setControlledDocumentJson(document("", revision: 0, resetGeneration: 2))
76
+ view.setControlledDocumentJson(document("draft b", revision: 0, resetGeneration: 1))
77
+ check(view.text == "draft b", "A lower reset generation was rejected")
78
+ view.editor.insertText("!")
79
+ check(
80
+ view.onComposerChange.payloads.last?["resetGeneration"] as? Int == 2,
81
+ "A lower reset generation rewound the editor's"
82
+ )
83
+}
84
+
85
+// Without a reset, a payload behind the native revision still loses to newer typing.
86
+do {
87
+ let view = makeEditor("ab")
88
+ view.editor.selectedRange = NSRange(location: 2, length: 0)
89
+ view.editor.insertText("c")
90
+ view.setControlledDocumentJson(document("ab", revision: 0))
91
+ check(view.text == "abc", "A stale controlled value overwrote newer native typing")
92
+}
93
+
94
+// A send clear during an IME composition must not come back when the composition commits.
95
+do {
96
+ let view = makeEditor("hello ")
97
+ view.editor.selectedRange = NSRange(location: 6, length: 0)
98
+ view.editor.setMarkedText("wor", selectedRange: NSRange(location: 3, length: 0))
99
+ check(view.editor.markedTextRange != nil, "Harness could not start a composition")
100
+ let revision = view.onComposerChange.payloads.last?["eventCount"] as? Int ?? 0
101
+ view.setControlledDocumentJson(document("", revision: revision, resetGeneration: 1))
102
+ view.editor.unmarkText()
103
+ check(view.text == "", "Send clear lost to a committed composition: \(view.text)")
104
+ check(
105
+ !view.onComposerChange.payloads.contains { ($0["value"] as? String)?.contains("hello") == true && ($0["resetGeneration"] as? Int) == 1 },
106
+ "Committed composition republished the sent draft"
107
+ )
108
+}
109
+
110
+print("composer editor tests passed")
apps/mobile/modules/t3-composer-editor/tests/run-ios.sh
new
+37
@@ -0,0 +1,37 @@
1
+#!/bin/bash
2
+set -euo pipefail
3
+module_dir=$(cd "$(dirname "$0")/.." && pwd)
4
+sdk=$(xcrun --sdk macosx --show-sdk-path)
5
+compiler=$(xcrun --find swiftc)
6
+output=$(mktemp -d)
7
+trap 'rm -rf "$output"' EXIT
8
+# Compile the real editor view; only the Expo bridge and clipboard are stubbed.
9
+python3 - "$module_dir" "$output/main.swift" <<'PYTHON'
10
+import sys
11
+from pathlib import Path
12
+module = Path(sys.argv[1])
13
+source = (module / "ios/T3ComposerEditorView.swift").read_text()
14
+source = source.replace("import ExpoModulesCore\n", "")
15
+stubs = """
16
+public final class AppContext {}
17
+open class ExpoView: UIView {
18
+ public required init(appContext: AppContext? = nil) { super.init(frame: .zero) }
19
+ @available(*, unavailable)
20
+ public required init?(coder: NSCoder) { fatalError("init(coder:) is unused") }
21
+}
22
+final class EventDispatcher {
23
+ var payloads: [[String: Any]] = []
24
+ func callAsFunction(_ payload: [String: Any] = [:]) { payloads.append(payload) }
25
+}
26
+enum T3ComposerClipboard {
27
+ static func hasThreadLink(_ text: String) -> Bool { false }
28
+ static func read() -> [String: String] { [:] }
29
+ static func write(text: String, fragment: String) {}
30
+}
31
+"""
32
+Path(sys.argv[2]).write_text(source + "\n" + stubs + "\n" + (module / "tests/ios/main.swift").read_text())
33
+PYTHON
34
+"$compiler" -target "$(uname -m)-apple-ios16.1-macabi" -sdk "$sdk" \
35
+ -F "$sdk/System/iOSSupport/System/Library/Frameworks" \
36
+ "$output/main.swift" -o "$output/editor-tests"
37
+"$output/editor-tests"
apps/mobile/src/components/ComposerEditor.ios.test.tsx
new
+187
@@ -0,0 +1,187 @@
1
+import { RegistryContext } from "@effect/atom-react";
2
+import { act, useLayoutEffect, useRef, type ReactNode } from "react";
3
+import { createRoot } from "react-dom/client";
4
+import { expect, it, vi } from "vite-plus/test";
5
+
6
+interface NativeEvent {
7
+ readonly value: string;
8
+ readonly selection: { readonly start: number; readonly end: number };
9
+ readonly eventCount: number;
10
+ readonly resetGeneration: number;
11
+}
12
+
13
+interface NativeProps {
14
+ readonly controlledDocumentJson: string;
15
+ readonly onComposerChange: (event: { readonly nativeEvent: NativeEvent }) => void;
16
+}
17
+
18
+// Mirrors the iOS editor's revision and reset bookkeeping (T3ComposerEditorView.setControlledDocumentJson).
19
+const native = vi.hoisted(() => ({
20
+ text: "",
21
+ eventCount: 0,
22
+ resetGeneration: 0,
23
+ props: null as NativeProps | null,
24
+ deliver: null as ((event: NativeEvent) => void) | null,
25
+}));
26
+
27
+function NativeView(props: NativeProps) {
28
+ const propsRef = useRef(props);
29
+ useLayoutEffect(() => {
30
+ Object.assign(native, { text: "", eventCount: 0, resetGeneration: 0 });
31
+ }, []);
32
+ useLayoutEffect(() => {
33
+ propsRef.current = props;
34
+ native.props = props;
35
+ native.deliver = (event) => propsRef.current.onComposerChange({ nativeEvent: event });
36
+ });
37
+ const { controlledDocumentJson } = props;
38
+ useLayoutEffect(() => {
39
+ const document = JSON.parse(controlledDocumentJson) as {
40
+ value: string;
41
+ mostRecentEventCount: number;
42
+ resetGeneration?: number;
43
+ };
44
+ const resetGeneration = document.resetGeneration ?? 0;
45
+ const isReset = resetGeneration > native.resetGeneration;
46
+ if (!isReset && document.mostRecentEventCount < native.eventCount) return;
47
+ if (isReset) {
48
+ native.resetGeneration = resetGeneration;
49
+ native.eventCount = document.mostRecentEventCount;
50
+ }
51
+ native.text = document.value;
52
+ }, [controlledDocumentJson]);
53
+ return null;
54
+}
55
+
56
+function emit(value: string, resetGeneration = native.resetGeneration) {
57
+ native.eventCount += 1;
58
+ native.text = value;
59
+ native.props!.onComposerChange({
60
+ nativeEvent: {
61
+ value,
62
+ selection: { start: value.length, end: value.length },
63
+ eventCount: native.eventCount,
64
+ resetGeneration,
65
+ },
66
+ });
67
+}
68
+
69
+vi.mock("expo", () => ({ requireNativeView: () => NativeView }));
70
+// Vite resolves the platform-neutral module; the race lives in the iOS editor.
71
+vi.mock("../native/T3ComposerEditor", () => import("../native/T3ComposerEditor.ios"));
72
+vi.mock("react-native", () => ({ StyleSheet: { flatten: (style: unknown) => style } }));
73
+vi.mock("expo-file-system", () => ({
74
+ Directory: class {
75
+ create() {}
76
+ },
77
+ File: class {
78
+ exists = false;
79
+ write() {}
80
+ },
81
+ Paths: { document: { uri: "file:///documents" } },
82
+}));
83
+vi.mock("./ui/Dialog", () => ({ alert: vi.fn() }));
84
+vi.mock("./ui/AppText", () => ({ AppText: ({ children }: { children?: ReactNode }) => children }));
85
+vi.mock("./ComposerContextSheet", () => ({ ComposerContextSheet: () => null }));
86
+vi.mock("../features/threads/useOpenLinkedThread", () => ({ useOpenLinkedThread: () => vi.fn() }));
87
+vi.mock("../state/peerLinks", () => ({ useLinkedEnvironments: () => [] }));
88
+vi.mock("../state/preferences", async () => {
89
+ const { Atom } = await import("effect/reactivity");
90
+ return { mobilePreferencesAtom: Atom.make({ _tag: "Initial" }) };
91
+});
92
+vi.mock("../lib/composerContextClipboard", () => ({ importComposerContextClipboard: vi.fn() }));
93
+vi.mock("../lib/useUniwindTheme", () => ({ useUniwindTheme: () => ({}) }));
94
+vi.mock("../lib/nativeComposerTheme", () => ({ createNativeComposerTheme: () => ({}) }));
95
+vi.mock("../lib/contextChipIconSource", () => ({ contextChipIconUri: () => "" }));
96
+vi.mock("../features/settings/appearance/useScaledTextRole", () => ({
97
+ useScaledTextRole: () => ({ fontSize: 16, lineHeight: 22 }),
98
+}));
99
+vi.mock("../lib/uuid", () => ({ uuidv4: () => "uuid", randomHex: () => "0000" }));
100
+vi.mock("../state/assets", () => ({ assetEnvironment: {} }));
101
+vi.mock("../state/attachments", () => ({ attachmentEnvironment: {} }));
102
+vi.mock("../state/session", () => ({ environmentSession: {} }));
103
+vi.mock("@t3tools/client-runtime/state/runtime", () => ({
104
+ createEnvironmentRpcCommand: () => Symbol("rpc-command"),
105
+ settlePromise: vi.fn(),
106
+ squashAtomCommandFailure: vi.fn(),
107
+}));
108
+
109
+import { appAtomRegistry } from "../state/atom-registry";
110
+import {
111
+ clearComposerDraftContent,
112
+ getComposerDraftSnapshot,
113
+ setComposerDraftText,
114
+ useComposerDraft,
115
+} from "../state/use-composer-drafts";
116
+import { ComposerEditor } from "./ComposerEditor";
117
+
118
+const DRAFT_KEY = "environment:thread";
119
+
120
+function ThreadComposer({ draftKey = DRAFT_KEY }: { draftKey?: string }) {
121
+ const draft = useComposerDraft(draftKey);
122
+ return (
123
+ <ComposerEditor
124
+ draftKey={draftKey}
125
+ value={draft.text}
126
+ onChangeText={(text) => setComposerDraftText(draftKey, text)}
127
+ />
128
+ );
129
+}
130
+
131
+it("keeps a sent draft cleared when an autocorrection lands in the same batch as the send", async () => {
132
+ (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
133
+ Object.assign(native, { text: "", eventCount: 0, resetGeneration: 0, props: null });
134
+ const root = createRoot(document.createElement("div"));
135
+ await using _root = { [Symbol.asyncDispose]: async () => act(() => root.unmount()) };
136
+ await act(async () =>
137
+ root.render(
138
+ <RegistryContext.Provider value={appAtomRegistry}>
139
+ <ThreadComposer />
140
+ </RegistryContext.Provider>,
141
+ ),
142
+ );
143
+
144
+ await act(async () => emit("Hello wrold"));
145
+ expect(getComposerDraftSnapshot(DRAFT_KEY).text).toBe("Hello wrold");
146
+
147
+ // Send clears the draft; iOS commits the pending autocorrection as the keyboard dismisses.
148
+ await act(async () => {
149
+ clearComposerDraftContent(DRAFT_KEY);
150
+ emit("Hello world");
151
+ });
152
+ expect(getComposerDraftSnapshot(DRAFT_KEY).text).toBe("");
153
+ expect(native.text).toBe("");
154
+
155
+ await act(async () => emit("n"));
156
+ expect(getComposerDraftSnapshot(DRAFT_KEY).text).toBe("n");
157
+ expect(native.text).toBe("n");
158
+});
159
+
160
+it("keeps a pending event from the previous native editor out of the selected draft", async () => {
161
+ (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
162
+ const first = "switch-draft:first";
163
+ const second = "switch-draft:second";
164
+ setComposerDraftText(first, "Draft A");
165
+ setComposerDraftText(second, "Draft B");
166
+ const root = createRoot(document.createElement("div"));
167
+ await using _root = { [Symbol.asyncDispose]: async () => act(() => root.unmount()) };
168
+ const renderDraft = (draftKey: string) =>
169
+ root.render(
170
+ <RegistryContext.Provider value={appAtomRegistry}>
171
+ <ThreadComposer draftKey={draftKey} />
172
+ </RegistryContext.Provider>,
173
+ );
174
+ await act(async () => renderDraft(first));
175
+ const deliverPendingEvent = native.deliver!;
176
+ await act(async () => renderDraft(second));
177
+ await act(async () =>
178
+ deliverPendingEvent({
179
+ value: "Draft A corrected",
180
+ selection: { start: 17, end: 17 },
181
+ eventCount: 1,
182
+ resetGeneration: 0,
183
+ }),
184
+ );
185
+ expect(getComposerDraftSnapshot(second).text).toBe("Draft B");
186
+ expect(native.text).toBe("Draft B");
187
+});
apps/mobile/src/components/ComposerEditor.tsx
+4
-1
@@ -21,6 +21,7 @@ import {
21
setComposerDraftContext,
22
setComposerContextImporting,
23
useComposerDraft,
24
+ useComposerDraftResetGeneration,
25
} from "../state/use-composer-drafts";
26
import { importComposerContextClipboard } from "../lib/composerContextClipboard";
27
import { startComposerDraftOperation } from "../state/composerDraftOperations";
@@ -57,6 +58,7 @@ export function ComposerEditor({
58
...props
59
}: ComposerEditorProps) {
60
const draft = useComposerDraft(draftKey ?? null);
61
+ const readResetGeneration = useComposerDraftResetGeneration(draftKey ?? null);
62
const preferencesResult = useAtomValue(mobilePreferencesAtom);
63
const preferredEnterBehavior = AsyncResult.isSuccess(preferencesResult)
64
? preferencesResult.value.composerEnterBehavior
@@ -175,10 +177,11 @@ export function ComposerEditor({
177
<>
178
{/* Reset revision history with the recreated iOS view without aborting context imports. */}
179
<NativeComposerEditor
178
- key={hidden ? "hidden" : "visible"}
180
+ key={`${hidden ? "hidden" : "visible"}:${draftKey ?? "no-draft"}`}
181
{...props}
182
enterBehavior={props.enterBehavior ?? preferredEnterBehavior}
183
onChangeText={changeText}
184
+ readResetGeneration={readResetGeneration}
185
readOnly={props.readOnly || importing}
186
onSubmit={importing ? undefined : props.onSubmit}
187
clipboardFragment={clipboardFragment ?? undefined}
apps/mobile/src/native/T3ComposerEditor.ios.tsx
+32
-31
@@ -40,17 +40,20 @@ import type { ComposerEditorProps, ComposerEditorSelection } from "./T3ComposerE
40
41
const NATIVE_MODULE_NAME = "T3ComposerEditor";
42
const EMPTY_SKILLS: NonNullable<ComposerEditorProps["skills"]> = [];
43
+const NO_RESET = () => 0;
44
45
type NativeEditorEvent = NativeSyntheticEvent<{
46
readonly value: string;
47
readonly selection: ComposerEditorSelection;
48
readonly eventCount: number;
49
+ readonly resetGeneration: number;
50
}>;
51
52
type NativeSelectionEvent = NativeSyntheticEvent<{
53
readonly value: string;
54
readonly selection: ComposerEditorSelection;
55
readonly eventCount: number;
56
+ readonly resetGeneration: number;
57
}>;
58
59
type NativePasteImagesEvent = NativeSyntheticEvent<{
@@ -60,6 +63,7 @@ type NativePasteImagesEvent = NativeSyntheticEvent<{
63
type NativePasteTextEvent = NativeSyntheticEvent<{
64
readonly value: string;
65
readonly eventCount: number;
66
+ readonly resetGeneration: number;
67
readonly text: string;
68
readonly selection: ComposerEditorSelection;
69
}>;
@@ -138,12 +142,15 @@ export function ComposerEditor({
142
onSubmit,
143
onContentSizeChange,
144
contentInsetVertical = 0,
145
+ readResetGeneration = NO_RESET,
146
...props
147
}: ComposerEditorProps) {
148
const nativeRef = useRef<NativeComposerEditorRef>(null);
149
const mostRecentEventCountRef = useRef(0);
150
const [mostRecentEventCount, setMostRecentEventCount] = useState(0);
151
const [, forceNativeEventRender] = useState(0);
152
+ // Native stamps every event with the reset generation it had applied.
153
+ const nativeResetGenerationRef = useRef(0);
154
// Start history empty so restored drafts or recycled views receive a non-echo controlled payload.
155
const nativeEventSnapshotsRef = useRef<ComposerNativeEventSnapshot[]>([]);
156
// Tokens advance from the previous committed value; render-phase state keeps
@@ -215,12 +222,17 @@ export function ComposerEditor({
222
// the native revision and rejected by the editor instead of re-applying a
223
// stale caret or stale text mid-typing.
224
/* oxlint-disable react/refs -- Native controlled edits must reconcile against the last acknowledged native event before sending the next payload. */
218
- const controlledEventCount = resolveComposerControlledEventCount(
219
- props.value,
220
- selection ?? null,
221
- mostRecentEventCount,
222
- nativeEventSnapshotsRef.current,
223
- );
225
+ const resetGeneration = readResetGeneration();
226
+ // Native restarts its revision at a reset's stamp, so stamp it at the latest acknowledged event.
227
+ const controlledEventCount =
228
+ resetGeneration > nativeResetGenerationRef.current
229
+ ? mostRecentEventCount
230
+ : resolveComposerControlledEventCount(
231
+ props.value,
232
+ selection ?? null,
233
+ mostRecentEventCount,
234
+ nativeEventSnapshotsRef.current,
235
+ );
236
const acknowledgesLatestNativeEvent = isComposerNativeEcho(
237
props.value,
238
selection ?? null,
@@ -236,6 +248,7 @@ export function ComposerEditor({
248
tokensJson,
249
mostRecentEventCount: controlledEventCount,
250
isNativeEcho,
251
+ resetGeneration,
252
});
253
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- prunes native editor event snapshots once a committed payload acknowledges them
254
useEffect(() => {
@@ -264,23 +277,27 @@ export function ComposerEditor({
277
nativeEventSnapshotsRef,
278
]);
279
const acceptNativeEvent = useCallback(
267
- (eventCount: number, value: string, nextSelection: ComposerEditorSelection) => {
280
+ (event: NativeEditorEvent["nativeEvent"]) => {
281
+ // Read at delivery: a send can clear the draft in the same batch, before this view re-renders.
282
const acknowledgedEventCount = acknowledgeComposerNativeEvent(
283
mostRecentEventCountRef.current,
270
- eventCount,
284
+ event.eventCount,
285
+ readResetGeneration(),
286
+ event.resetGeneration,
287
);
288
if (acknowledgedEventCount === null) {
289
return false;
290
}
291
mostRecentEventCountRef.current = acknowledgedEventCount;
292
+ nativeResetGenerationRef.current = event.resetGeneration;
293
nativeEventSnapshotsRef.current.push({
294
eventCount: acknowledgedEventCount,
278
- value,
279
- selection: nextSelection,
295
+ value: event.value,
296
+ selection: event.selection,
297
});
298
return acknowledgedEventCount;
299
},
283
- [nativeEventSnapshotsRef],
300
+ [nativeEventSnapshotsRef, readResetGeneration],
301
);
302
const themeJson = JSON.stringify(createNativeComposerTheme(theme));
303
const resolvedTextStyle = StyleSheet.flatten(textStyle) ?? {};
@@ -318,11 +335,7 @@ export function ComposerEditor({
335
maxInputChars={PROVIDER_SEND_TURN_MAX_INPUT_CHARS}
336
style={style as StyleProp<ViewStyle>}
337
onComposerChange={(event) => {
321
- const acknowledgedEventCount = acceptNativeEvent(
322
- event.nativeEvent.eventCount,
323
- event.nativeEvent.value,
324
- event.nativeEvent.selection,
325
- );
338
+ const acknowledgedEventCount = acceptNativeEvent(event.nativeEvent);
339
if (acknowledgedEventCount === false) return;
340
onChangeText(event.nativeEvent.value);
341
onSelectionChange?.(event.nativeEvent.selection);
@@ -330,11 +343,7 @@ export function ComposerEditor({
343
forceNativeEventRender((sequence) => sequence + 1);
344
}}
345
onComposerSelectionChange={(event) => {
333
- const acknowledgedEventCount = acceptNativeEvent(
334
- event.nativeEvent.eventCount,
335
- event.nativeEvent.value,
336
- event.nativeEvent.selection,
337
- );
346
+ const acknowledgedEventCount = acceptNativeEvent(event.nativeEvent);
347
if (acknowledgedEventCount === false) return;
348
// Selection events may carry post-edit text; publish it with its revision or stale drafts can overwrite native text.
349
if (event.nativeEvent.value !== props.value) {
@@ -348,11 +357,7 @@ export function ComposerEditor({
357
onComposerContextPress={(event) => props.onContextPress?.(event.nativeEvent)}
358
onComposerPasteContext={(event) => {
359
const paste = event.nativeEvent;
351
- const acknowledgedEventCount = acceptNativeEvent(
352
- paste.eventCount,
353
- paste.value,
354
- paste.selection,
355
- );
360
+ const acknowledgedEventCount = acceptNativeEvent(paste);
361
if (acknowledgedEventCount === false) return;
362
onChangeText(paste.value);
363
onSelectionChange?.(paste.selection);
@@ -362,11 +367,7 @@ export function ComposerEditor({
367
}}
368
onComposerPasteText={(event) => {
369
const paste = event.nativeEvent;
365
- const acknowledgedEventCount = acceptNativeEvent(
366
- paste.eventCount,
367
- paste.value,
368
- paste.selection,
369
- );
370
+ const acknowledgedEventCount = acceptNativeEvent(paste);
371
if (acknowledgedEventCount === false) return;
372
// Sync before capturing async paste targets; props may lag the last native keystroke.
373
onChangeText(paste.value);
apps/mobile/src/native/T3ComposerEditor.tsx
+1
@@ -18,6 +18,7 @@ export function ComposerEditor({
18
contentInsetVertical = 0,
19
singleLineCentered: _singleLineCentered,
20
enterBehavior: _enterBehavior,
21
+ readResetGeneration: _readResetGeneration,
22
readOnly = false,
23
onContentSizeChange,
24
...props
apps/mobile/src/native/T3ComposerEditor.types.ts
+5
@@ -58,6 +58,11 @@ export interface ComposerEditorProps {
58
readonly style?: StyleProp<ViewStyle>;
59
readonly textStyle?: StyleProp<TextStyle>;
60
readonly onChangeText: (value: string) => void;
61
+ /**
62
+ * iOS: the owner's reset generation, raised synchronously when it replaces the text outright
63
+ * (send, discard). Native edits the editor made before applying that reset are dropped.
64
+ */
65
+ readonly readResetGeneration?: () => number;
66
readonly onSelectionChange?: (selection: ComposerEditorSelection) => void;
67
readonly onPasteImages?: (uris: ReadonlyArray<string>) => void;
68
readonly onContextPress?: (reference: {
apps/mobile/src/native/composerEditorRevision.ts
+8
-1
@@ -12,8 +12,15 @@ interface ComposerEditorSelection {
12
export function acknowledgeComposerNativeEvent(
13
mostRecentEventCount: number,
14
incomingEventCount: number,
15
+ resetGeneration = 0,
16
+ incomingResetGeneration = 0,
17
): number | null {
16
- if (!Number.isSafeInteger(incomingEventCount) || incomingEventCount < mostRecentEventCount) {
18
+ if (
19
+ !Number.isSafeInteger(incomingEventCount) ||
20
+ incomingEventCount < mostRecentEventCount ||
21
+ // Events from before the editor applied a parent reset describe text the parent replaced.
22
+ incomingResetGeneration < resetGeneration
23
+ ) {
24
return null;
25
}
26
return incomingEventCount;
apps/mobile/src/state/use-composer-drafts.ts
+26
@@ -104,6 +104,30 @@ const composerDraftSelectionAtom = Atom.family((_draftKey: string) =>
104
);
105
const NO_COMPOSER_DRAFT_SELECTION_ATOM = Atom.make<ComposerDraftSelection | null>(null);
106
107
+// Never persisted. One counter across drafts, so an editor moved between drafts never
108
+// sees a later reset numbered below one it already applied.
109
+let lastComposerDraftReset = 0;
110
+const composerDraftResetAtom = Atom.family((_draftKey: string) =>
111
+ Atom.make(0).pipe(Atom.withLabel("mobile:composer-draft-reset")),
112
+);
113
+const NO_COMPOSER_DRAFT_RESET_ATOM = Atom.make(0);
114
+
115
+function markComposerDraftReset(draftKey: string): void {
116
+ lastComposerDraftReset += 1;
117
+ appAtomRegistry.set(composerDraftResetAtom(draftKey), lastComposerDraftReset);
118
+}
119
+
120
+/**
121
+ * Raised when a draft's text is replaced outright (sent, discarded). Native editor events read it
122
+ * synchronously, so an edit the editor made before applying the reset cannot restore the text.
123
+ */
124
+export function useComposerDraftResetGeneration(draftKey: string | null): () => number {
125
+ const atom = draftKey === null ? NO_COMPOSER_DRAFT_RESET_ATOM : composerDraftResetAtom(draftKey);
126
+ // Subscribing re-renders the editor so it sends the reset even when the text did not change.
127
+ useAtomValue(atom);
128
+ return () => appAtomRegistry.get(atom);
129
+}
130
+
131
export function rememberComposerDraftSelection(
132
draftKey: string,
133
text: string,
@@ -1827,6 +1851,7 @@ export function clearComposerDraftContent(
1851
},
1852
): void {
1853
const previousAttachments = getComposerDraftSnapshot(draftKey).attachments;
1854
+ markComposerDraftReset(draftKey);
1855
updateComposerDrafts((current) => clearComposerDraftContentState(current, draftKey, options));
1856
if (!options?.deferAttachmentCleanup) {
1857
scheduleUnusedComposerAttachmentCleanup(previousAttachments);
@@ -1838,6 +1863,7 @@ export function clearComposerDraft(
1863
options?: { readonly deferAttachmentCleanup?: boolean },
1864
): void {
1865
abortComposerDraftOperations(draftKey);
1866
+ markComposerDraftReset(draftKey);
1867
const previousAttachments = getComposerDraftSnapshot(draftKey).attachments;
1868
updateComposerDrafts((current) => {
1869
if (!current[draftKey]) {
apps/mobile/vite.config.ts
+1
@@ -30,6 +30,7 @@ const reactTests = [
30
"src/features/threads/UsageLimitRecoveryCard.test.tsx",
31
"src/features/threads/NewTaskDraftRouteScreen.test.tsx",
32
"src/native/NativeHeaderToolbar.test.tsx",
33
+ "src/components/ComposerEditor.ios.test.tsx",
34
"src/native/V5StackHeader.ios.test.tsx",
35
"src/native/useRestingTopOffset.test.tsx",
36
"src/native/useRetryingImageSource.test.tsx",