@devries-cameron20 / t3code Mirror · read-only / commits / 7ef841dcf7
Fork 0

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, 03:15 UTC

fix(mobile): sending on iOS no longer leaves an autocorrected draft behind (#26452)

Co-authored-by: SAPHID <saphid@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: maria-rcks <maria@kuuro.net> Co-authored-by: Julius Marminge <julius0216@outlook.com>

Alex Southwell committed Nov 6, 2026 at 01:34 UTC 7ef841dcf7c9f48b950b6d2b02e48b44e2be3265
10 files changed +157 -24
apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorModule.swift
+3
@@ -132,6 +132,9 @@ public class T3ComposerEditorModule: Module {
132 AsyncFunction("setSelection") { (view: T3ComposerEditorView, start: Int, end: Int) in
133 view.setSelection(start: start, end: end)
134 }
135 + AsyncFunction("readState") { (view: T3ComposerEditorView) -> [String: Any] in
136 + view.readState()
137 + }
138 }
139 }
140 }
apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift
+17
@@ -447,6 +447,8 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro
447 private var isReadOnly = false
448 private var isApplyingControlledValue = false
449 private var nativeEventCount = 0
450 + // Count of the latest intercepted paste, so a flush can tell whether JS has received it.
451 + private var lastPasteEventCount = 0
452 private var hasControlledDocument = false
453 private var resetGeneration = 0
454 private var lastContentSize = CGSize.zero
@@ -499,6 +501,7 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro
501 guard let self else { return }
502 let selection = self.sourceSelection()
503 self.nativeEventCount += 1
504 + self.lastPasteEventCount = self.nativeEventCount
505 var payload: [String: Any] = context
506 payload["value"] = self.textView.serializedText()
507 payload["eventCount"] = self.nativeEventCount
@@ -510,6 +513,7 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro
513 guard let self else { return }
514 let selection = self.sourceSelection()
515 self.nativeEventCount += 1
516 + self.lastPasteEventCount = self.nativeEventCount
517 self.onComposerPasteText([
518 "value": self.textView.serializedText(),
519 "eventCount": self.nativeEventCount,
@@ -677,6 +681,8 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro
681 }
682 if isReset {
683 resetGeneration = document.resetGeneration
684 + // JS drops a paste from before the reset by generation, so the flush must not wait for it.
685 + lastPasteEventCount = 0
686 endComposition()
687 }
688 // iOS destroys this view under display: none and mounts a fresh one while JS keeps its
@@ -807,6 +813,17 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro
813 textView.resignFirstResponder()
814 }
815
816 + func readState() -> [String: Any] {
817 + let selection = sourceSelection()
818 + return [
819 + "value": value,
820 + "selection": ["start": selection.start, "end": selection.end],
821 + "eventCount": nativeEventCount,
822 + "resetGeneration": resetGeneration,
823 + "pasteEventCount": lastPasteEventCount,
824 + ]
825 + }
826 +
827 func setSelection(start: Int, end: Int) {
828 let previousSelection = sourceSelection()
829 requestedSelection = ComposerSelectionPayload(start: start, end: end)
apps/mobile/src/components/ComposerEditor.ios.test.tsx
+91 -4
@@ -1,5 +1,13 @@
1 import { RegistryContext } from "@effect/atom-react";
2 -import { act, useLayoutEffect, useRef, type ReactNode } from "react";
2 +import {
3 + act,
4 + createRef,
5 + useImperativeHandle,
6 + useLayoutEffect,
7 + useRef,
8 + type ReactNode,
9 + type Ref,
10 +} from "react";
11 import { createRoot } from "react-dom/client";
12 import { expect, it, vi } from "vite-plus/test";
13
@@ -11,6 +19,7 @@ interface NativeEvent {
19 }
20
21 interface NativeProps {
22 + readonly ref?: Ref<unknown>;
23 readonly controlledDocumentJson: string;
24 readonly onComposerChange: (event: { readonly nativeEvent: NativeEvent }) => void;
25 }
@@ -20,17 +29,27 @@ const native = vi.hoisted(() => ({
29 text: "",
30 eventCount: 0,
31 resetGeneration: 0,
32 + pasteEventCount: 0,
33 mounts: 0,
34 props: null as NativeProps | null,
35 deliver: null as ((event: NativeEvent) => void) | null,
36 }));
37
28 -function NativeView(props: NativeProps) {
38 +function NativeView({ ref, ...props }: NativeProps) {
39 const propsRef = useRef(props);
40 useLayoutEffect(() => {
31 - Object.assign(native, { text: "", eventCount: 0, resetGeneration: 0 });
41 + Object.assign(native, { text: "", eventCount: 0, resetGeneration: 0, pasteEventCount: 0 });
42 native.mounts += 1;
43 }, []);
44 + useImperativeHandle(ref, () => ({
45 + readState: async () => ({
46 + value: native.text,
47 + selection: { start: native.text.length, end: native.text.length },
48 + eventCount: native.eventCount,
49 + resetGeneration: native.resetGeneration,
50 + pasteEventCount: native.pasteEventCount,
51 + }),
52 + }));
53 useLayoutEffect(() => {
54 propsRef.current = props;
55 native.props = props;
@@ -55,6 +74,18 @@ function NativeView(props: NativeProps) {
74 return null;
75 }
76
77 +// A native edit whose event has not reached JS yet.
78 +function pend(value: string): NativeEvent {
79 + native.eventCount += 1;
80 + native.text = value;
81 + return {
82 + value,
83 + selection: { start: value.length, end: value.length },
84 + eventCount: native.eventCount,
85 + resetGeneration: native.resetGeneration,
86 + };
87 +}
88 +
89 function emit(value: string, resetGeneration = native.resetGeneration) {
90 native.eventCount += 1;
91 native.text = value;
@@ -116,13 +147,21 @@ import {
147 useComposerDraft,
148 } from "../state/use-composer-drafts";
149 import { ComposerEditor } from "./ComposerEditor";
150 +import type { ComposerEditorHandle } from "../native/T3ComposerEditor.types";
151
152 const DRAFT_KEY = "environment:thread";
153
122 -function ThreadComposer({ draftKey = DRAFT_KEY }: { draftKey?: string }) {
154 +function ThreadComposer({
155 + draftKey = DRAFT_KEY,
156 + editorRef,
157 +}: {
158 + draftKey?: string;
159 + editorRef?: Ref<ComposerEditorHandle>;
160 +}) {
161 const draft = useComposerDraft(draftKey);
162 return (
163 <ComposerEditor
164 + ref={editorRef}
165 draftKey={draftKey}
166 value={draft.text}
167 onChangeText={(text) => setComposerDraftText(draftKey, text)}
@@ -190,3 +229,51 @@ it("keeps a pending event from the previous native editor out of the selected dr
229 expect(getComposerDraftSnapshot(second).text).toBe("Draft B");
230 expect(native.text).toBe("Draft B");
231 });
232 +
233 +async function renderFlushableComposer() {
234 + (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
235 + const editor = createRef<ComposerEditorHandle>();
236 + const root = createRoot(document.createElement("div"));
237 + await act(async () =>
238 + root.render(
239 + <RegistryContext.Provider value={appAtomRegistry}>
240 + <ThreadComposer editorRef={editor} />
241 + </RegistryContext.Provider>,
242 + ),
243 + );
244 + return {
245 + editor,
246 + [Symbol.asyncDispose]: async () => act(() => root.unmount()),
247 + };
248 +}
249 +
250 +it("sends the autocorrection the Send tap accepted, and its late event cannot refill the draft", async () => {
251 + await using screen = await renderFlushableComposer();
252 + await act(async () => emit("Hello wrold"));
253 + const lateCorrection = pend("Hello world");
254 +
255 + await act(async () => screen.editor.current!.flushPendingInput());
256 + expect(getComposerDraftSnapshot(DRAFT_KEY).text).toBe("Hello world");
257 +
258 + await act(async () => {
259 + clearComposerDraftContent(DRAFT_KEY);
260 + native.deliver!(lateCorrection);
261 + });
262 + expect(getComposerDraftSnapshot(DRAFT_KEY).text).toBe("");
263 +});
264 +
265 +it("does not flush past a paste whose event has not reached JS", async () => {
266 + await using screen = await renderFlushableComposer();
267 + await act(async () => emit("Before"));
268 + const paste = pend("Before pasted");
269 + native.pasteEventCount = paste.eventCount;
270 + const caretMove = pend("Before pasted");
271 +
272 + await act(async () => screen.editor.current!.flushPendingInput());
273 + expect(getComposerDraftSnapshot(DRAFT_KEY).text).toBe("Before");
274 +
275 + await act(async () => native.deliver!(paste));
276 + expect(getComposerDraftSnapshot(DRAFT_KEY).text).toBe("Before pasted");
277 + await act(async () => native.deliver!(caretMove));
278 + expect(getComposerDraftSnapshot(DRAFT_KEY).text).toBe("Before pasted");
279 +});
apps/mobile/src/features/threads/ThreadComposer.tsx
+1
@@ -683,6 +683,7 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps
683 const threadKey = scopedThreadKey(props.environmentId, props.selectedThread.id);
684 if (inFlightThreadIdsRef.current.has(threadKey)) return;
685 inFlightThreadIdsRef.current.add(threadKey);
686 + await inputRef.current?.flushPendingInput();
687 const draftAtSend = getComposerDraftSnapshot(composerDraftKey);
688 const stillSendable = () => {
689 const draft = getComposerDraftSnapshot(composerDraftKey);
apps/mobile/src/native/T3ComposerEditor.ios.tsx
+33 -19
@@ -72,6 +72,13 @@ interface NativeComposerEditorRef {
72 focus: () => Promise<void>;
73 blur: () => Promise<void>;
74 setSelection: (start: number, end: number) => Promise<void>;
75 + readState: () => Promise<{
76 + readonly value: string;
77 + readonly selection: ComposerEditorSelection;
78 + readonly eventCount: number;
79 + readonly resetGeneration: number;
80 + readonly pasteEventCount: number;
81 + }>;
82 }
83
84 interface NativeComposerEditorProps extends ViewProps {
@@ -170,17 +177,6 @@ export function ComposerEditor({
177 const theme = useUniwindTheme();
178 const fontFamily = FONT_FAMILIES.regular;
179
173 - useImperativeHandle(
174 - ref,
175 - () => ({
176 - focus: () => settleViewCommand(nativeRef.current?.focus()),
177 - blur: () => settleViewCommand(nativeRef.current?.blur()),
178 - setSelection: (nextSelection) =>
179 - settleViewCommand(nativeRef.current?.setSelection(nextSelection.start, nextSelection.end)),
180 - }),
181 - [],
182 - );
183 -
180 const skillLabels = useMemo(() => composerSkillLabels(skills), [skills]);
181 const chipTextColor = createNativeComposerTheme(theme).text;
182 const tokensJson = useMemo(() => {
@@ -299,6 +295,31 @@ export function ComposerEditor({
295 },
296 [nativeEventSnapshotsRef, readResetGeneration],
297 );
298 + const applyNativeChange = (event: NativeEditorEvent["nativeEvent"]) => {
299 + const acknowledgedEventCount = acceptNativeEvent(event);
300 + if (acknowledgedEventCount === false) return;
301 + onChangeText(event.value);
302 + onSelectionChange?.(event.selection);
303 + setMostRecentEventCount(acknowledgedEventCount);
304 + forceNativeEventRender((sequence) => sequence + 1);
305 + };
306 + useImperativeHandle(ref, () => ({
307 + focus: () => settleViewCommand(nativeRef.current?.focus()),
308 + blur: () => settleViewCommand(nativeRef.current?.blur()),
309 + setSelection: (nextSelection) =>
310 + settleViewCommand(nativeRef.current?.setSelection(nextSelection.start, nextSelection.end)),
311 + // Tapping outside the editor makes iOS accept a pending autocorrection, and that edit's
312 + // event can reach JS after the tap's handler has already read the draft.
313 + flushPendingInput: async () => {
314 + const state = await Promise.resolve()
315 + .then(() => nativeRef.current?.readState())
316 + .catch(() => undefined);
317 + // Acknowledging past a paste JS has not received yet would get the paste rejected.
318 + if (state && state.pasteEventCount <= mostRecentEventCountRef.current) {
319 + applyNativeChange(state);
320 + }
321 + },
322 + }));
323 const themeJson = JSON.stringify(createNativeComposerTheme(theme));
324 const resolvedTextStyle = StyleSheet.flatten(textStyle) ?? {};
325 return (
@@ -334,14 +355,7 @@ export function ComposerEditor({
355 textPasteThresholdBytes={onPasteText ? PASTED_TEXT_ATTACHMENT_THRESHOLD_BYTES : 0}
356 maxInputChars={PROVIDER_SEND_TURN_MAX_INPUT_CHARS}
357 style={style as StyleProp<ViewStyle>}
337 - onComposerChange={(event) => {
338 - const acknowledgedEventCount = acceptNativeEvent(event.nativeEvent);
339 - if (acknowledgedEventCount === false) return;
340 - onChangeText(event.nativeEvent.value);
341 - onSelectionChange?.(event.nativeEvent.selection);
342 - setMostRecentEventCount(acknowledgedEventCount);
343 - forceNativeEventRender((sequence) => sequence + 1);
344 - }}
358 + onComposerChange={(event) => applyNativeChange(event.nativeEvent)}
359 onComposerSelectionChange={(event) => {
360 const acknowledgedEventCount = acceptNativeEvent(event.nativeEvent);
361 if (acknowledgedEventCount === false) return;
apps/mobile/src/native/T3ComposerEditor.native.tsx
+1
@@ -167,6 +167,7 @@ export function ComposerEditor({
167 blur: () => settleViewCommand(nativeRef.current?.blur()),
168 setSelection: (nextSelection) =>
169 settleViewCommand(nativeRef.current?.setSelection(nextSelection.start, nextSelection.end)),
170 + flushPendingInput: async () => {},
171 }),
172 [],
173 );
apps/mobile/src/native/T3ComposerEditor.tsx
+1
@@ -35,6 +35,7 @@ export function ComposerEditor({
35 blur: () => inputRef.current?.blur(),
36 setSelection: (nextSelection) =>
37 inputRef.current?.setSelection(nextSelection.start, nextSelection.end),
38 + flushPendingInput: async () => {},
39 }),
40 [],
41 );
apps/mobile/src/native/T3ComposerEditor.types.ts
+2
@@ -22,6 +22,8 @@ export interface ComposerEditorHandle {
22 focus: () => void;
23 blur: () => void;
24 setSelection: (selection: ComposerEditorSelection) => void;
25 + /** iOS: resolves once a native edit still in flight has reached `onChangeText`. */
26 + flushPendingInput: () => Promise<void>;
27 }
28
29 export interface ComposerEditorProps {
apps/mobile/src/native/composerEditorRevision.test.ts
+7
@@ -164,3 +164,10 @@ describe("typing immediately before an intercepted paste", () => {
164 expect(acknowledgeComposerNativeEvent(2, 1)).toBeNull();
165 });
166 });
167 +
168 +describe("acknowledgeComposerNativeEvent", () => {
169 + it("drops a native edit a send already read, so it cannot refill the cleared draft", () => {
170 + expect(acknowledgeComposerNativeEvent(76, 77)).toBe(77);
171 + expect(acknowledgeComposerNativeEvent(77, 77)).toBeNull();
172 + });
173 +});
apps/mobile/src/native/composerEditorRevision.ts
+1 -1
@@ -17,7 +17,7 @@ export function acknowledgeComposerNativeEvent(
17 ): number | null {
18 if (
19 !Number.isSafeInteger(incomingEventCount) ||
20 - incomingEventCount < mostRecentEventCount ||
20 + incomingEventCount <= mostRecentEventCount ||
21 // Events from before the editor applied a parent reset describe text the parent replaced.
22 incomingResetGeneration < resetGeneration
23 ) {