The best way to control Claude Code, Codex and more from any computer or phone
fix(web): pasted images stay at their original insertion point (#35528)
Co-authored-by: brkgzlsy <berke.guzelsoy@fabrite.ch> Co-authored-by: Julius Marminge <julius0216@outlook.com>
Dragesia committed
Nov 14, 2026 at 21:10 UTC
ec01233fb653d935a8bea6784a694a4ac19bd55c
7 files changed
+313
-11
apps/mobile/src/state/use-composer-drafts.test.ts
+26
@@ -805,6 +805,32 @@ describe("mobile composer drafts", () => {
805
expect(getComposerDraftSnapshot(key).text).toBe("keep newly typed text pasted");
806
});
807
808
+ it("keeps a pending paste before text typed at its caret, and the caret after that text", async () => {
809
+ const key = "environment-1:typing-at-paste-point";
810
+ const image = {
811
+ id: "image",
812
+ type: "file" as const,
813
+ name: "picture.png",
814
+ mimeType: "text/plain",
815
+ sizeBytes: 4,
816
+ fileUri: "file:///picture.png",
817
+ };
818
+ setComposerDraftText(key, "Before ");
819
+ const insertion = captureComposerDraftInsertion(key, { start: 7, end: 7 });
820
+ const write = Promise.withResolvers<void>();
821
+ const pending = write.promise.then(() =>
822
+ appendComposerDraftAttachments(key, [image], { appendReference: true, insertion }),
823
+ );
824
+ setComposerDraftText(key, "Before yaz");
825
+ rememberComposerDraftSelection(key, "Before yaz", { start: 10, end: 10 });
826
+ write.resolve();
827
+ expect(await pending).toBe(0);
828
+ const link = "[picture.png](t3-context://v1/file/image)";
829
+ expect(getComposerDraftSnapshot(key).text).toBe(`Before ${link} yaz`);
830
+ const caret = `Before ${link} yaz`.length;
831
+ expect(captureComposerDraftInsertion(key)).toMatchObject({ start: caret, end: caret });
832
+ });
833
+
834
it.each(["attachment", "context", "imported context"])(
835
"releases a selected file when replaced by %s",
836
async (kind) => {
apps/mobile/src/state/use-composer-drafts.ts
+49
-10
@@ -195,14 +195,54 @@ export function captureComposerDraftInsertion(
195
};
196
}
197
198
+function mapCapturedRange(
199
+ captured: ComposerDraftInsertion,
200
+ text: string,
201
+): { start: number; end: number } | null {
202
+ if (captured.text === text) return captured;
203
+ // A replaced selection is not safe to delete after edits; only a caret follows them.
204
+ if (captured.start !== captured.end) return null;
205
+ const previous = captured.text;
206
+ const shared = Math.min(previous.length, text.length);
207
+ let prefix = 0;
208
+ while (prefix < shared && previous[prefix] === text[prefix]) prefix += 1;
209
+ let suffix = 0;
210
+ while (
211
+ suffix < shared - prefix &&
212
+ previous[previous.length - 1 - suffix] === text[text.length - 1 - suffix]
213
+ ) {
214
+ suffix += 1;
215
+ }
216
+ // Text typed at the caret lands after it, so the insertion stays before that text.
217
+ if (captured.start <= prefix) return captured;
218
+ if (captured.start < previous.length - suffix) return null;
219
+ const caret = captured.start + text.length - previous.length;
220
+ return { start: caret, end: caret };
221
+}
222
+
223
+/** Keep a caret after the insertion where it was, or the next keystroke lands before typed text. */
224
+function caretAfterInsertion(
225
+ draftKey: string,
226
+ previousText: string,
227
+ range: { start: number; end: number },
228
+ inserted: number,
229
+): { start: number; end: number } {
230
+ const caret = readComposerDraftSelection(draftKey, previousText);
231
+ if (caret && caret.start > range.end) {
232
+ const delta = range.start + inserted - range.end;
233
+ return { start: caret.start + delta, end: caret.end + delta };
234
+ }
235
+ return { start: range.start + inserted, end: range.start + inserted };
236
+}
237
+
238
function contextInsertionRange(
239
draftKey: string,
240
draft: ComposerDraft,
241
target?: ComposerDraftInsertion,
242
) {
243
const captured = target ?? appAtomRegistry.get(composerDraftSelectionAtom(draftKey));
204
- // Append after text edits during writes; caret-only moves preserve the captured insertion range.
205
- const selection = captured?.text === draft.text ? captured : null;
244
+ // Follow edits made during writes; append when an edit touched the captured range.
245
+ const selection = captured ? mapCapturedRange(captured, draft.text) : null;
246
const start = Math.max(0, Math.min(selection?.start ?? draft.text.length, draft.text.length));
247
return { start, end: Math.max(start, Math.min(selection?.end ?? start, draft.text.length)) };
248
}
@@ -373,10 +413,11 @@ function draftWithInsertedContext(
413
for (const record of content.context.records) records.set(record.contextId, record);
414
const context = referencedComposerContext(text, { version: 1, records: [...records.values()] });
415
if ((context?.records.length ?? 0) > COMPOSER_CONTEXT_MAX_RECORDS) return null;
376
- rememberComposerDraftSelection(draftKey, text, {
377
- start: start + insertion.length,
378
- end: start + insertion.length,
379
- });
416
+ rememberComposerDraftSelection(
417
+ draftKey,
418
+ text,
419
+ caretAfterInsertion(draftKey, draft.text, { start, end }, insertion.length),
420
+ );
421
return withReferencedContextFiles(draft, text, context);
422
}
423
@@ -1353,11 +1394,9 @@ export function insertComposerDraftText(
1394
const draft = getComposerDraftSnapshot(draftKey);
1395
const { start, end } = contextInsertionRange(draftKey, draft, target);
1396
const text = draft.text.slice(0, start) + value + draft.text.slice(end);
1397
+ const caret = caretAfterInsertion(draftKey, draft.text, { start, end }, value.length);
1398
setComposerDraftText(draftKey, text);
1357
- rememberComposerDraftSelection(draftKey, text, {
1358
- start: start + value.length,
1359
- end: start + value.length,
1360
- });
1399
+ rememberComposerDraftSelection(draftKey, text, caret);
1400
}
1401
1402
export function appendComposerDraftText(draftKey: string, value: string): void {
apps/web/src/components/ComposerPromptEditorTiptap.tsx
+7
@@ -138,6 +138,10 @@ import { resolveAssistantCitationCommentDismissal } from "./chat/assistantCitati
138
import { composerCodeBlockHighlight } from "./composerCodeBlockHighlight";
139
import { importPastedComposerText, readPastedPlainText } from "./composerInlineTokenPaste";
140
import { didComposerSelectionChangeVisibly } from "./composerSelection";
141
+import {
142
+ captureComposerAttachmentInsertion,
143
+ type ComposerAttachmentInsertion,
144
+} from "./composerAttachmentInsertion";
145
import type { ComposerDraftContextRecords } from "./composerContextPresentation";
146
147
export interface ComposerPromptEditorHandle {
@@ -145,6 +149,7 @@ export interface ComposerPromptEditorHandle {
149
focusAt: (cursor: number) => void;
150
focusAtEnd: () => void;
151
readSelectionRange: () => { start: number; end: number };
152
+ captureAttachmentInsertion: () => ComposerAttachmentInsertion | undefined;
153
requestCitationComment: (request: ComposerCitationCommentRequest) => void;
154
readSnapshot: () => {
155
value: string;
@@ -1741,6 +1746,8 @@ function ComposerPromptEditorTiptapInner(
1746
readSnapshot();
1747
return selectionRangeRef.current;
1748
},
1749
+ captureAttachmentInsertion: () =>
1750
+ editor ? captureComposerAttachmentInsertion(editor) : undefined,
1751
requestCitationComment: (request) => {
1752
citationRequestRef.current = request;
1753
if (!editor) return;
apps/web/src/components/chat/ChatComposer.tsx
+3
@@ -1,6 +1,7 @@
1
import { VoiceInputSetup } from "./VoiceInputSetup";
2
import { useComposerTypingGuard } from "./useComposerTypingGuard";
3
import { insertAttachmentReferencesForDraft } from "./composerAttachmentReferences";
4
+import type { ComposerAttachmentInsertion } from "../composerAttachmentInsertion";
5
import { DESKTOP_PASTE_AS_TEXT_EVENT } from "../../lib/desktopPasteAsText";
6
import { BackgroundThreadContext } from "./backgroundThread";
7
import {
@@ -2592,6 +2593,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
2593
const insertAttachmentReferences = (
2594
references: ReadonlyArray<ComposerContextReference>,
2595
selection?: { start: number; end: number },
2596
+ pendingInsertion?: ComposerAttachmentInsertion,
2597
): boolean => {
2598
if (references.length === 0) return false;
2599
// Question answers carry attachments beside the answer, never as chips. Falling back to
@@ -2602,6 +2604,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
2604
liveAttachmentTargetKey: attachmentTargetKeyRef.current,
2605
references,
2606
insertReferences: () => {
2607
+ if (pendingInsertion?.insert(references)) return true;
2608
if (selection) {
2609
const edit = inlineContextReferenceReplacement(promptRef.current, selection, references);
2610
return applyPromptReplacementStable(edit.start, edit.end, edit.text);
apps/web/src/components/chat/useComposerAttachmentIntake.ts
+11
-1
@@ -18,6 +18,7 @@ import {
18
composerFileNeedsReattach,
19
} from "../../composerDraftStore";
20
import { type ComposerPromptEditorHandle } from "../ComposerPromptEditorTiptap";
21
+import type { ComposerAttachmentInsertion } from "../composerAttachmentInsertion";
22
import { type PendingUserInput } from "../../session-logic";
23
import {
24
changeQuestionAttachmentPreparation,
@@ -84,6 +85,7 @@ export function useComposerAttachmentIntake(input: {
85
readonly insertAttachmentReferences: (
86
references: ReadonlyArray<ComposerContextReference>,
87
selection?: { start: number; end: number },
88
+ pendingInsertion?: ComposerAttachmentInsertion,
89
) => boolean;
90
}) {
91
const {
@@ -265,6 +267,9 @@ export function useComposerAttachmentIntake(input: {
267
const compressed: { id: string; file: File }[] = [];
268
// Keyed by image so a failure whose tile was removed (even mid-compression) is not reported.
269
const compressionErrors = new Map<string, string>();
270
+ const pendingInsertion = imageAttachmentsGetChips
271
+ ? composerEditorRef.current?.captureAttachmentInsertion()
272
+ : undefined;
273
for (const { id, file } of preparingImages) {
274
// Removed from the strip while an earlier image was compressing.
275
if (!isPreparingComposerImage(attachmentTargetKey, id)) continue;
@@ -287,6 +292,7 @@ export function useComposerAttachmentIntake(input: {
292
rememberComposerImageSource(file, result.file);
293
compressed.push({ id, file: result.file });
294
}
295
+ pendingInsertion?.dispose();
296
const questionDiscarded =
297
questionAttachmentTarget !== null &&
298
!useQuestionAttachmentPreparation.getState().counts[questionAttachmentTarget];
@@ -324,7 +330,11 @@ export function useComposerAttachmentIntake(input: {
330
}
331
if (storedImages.length > 0 && imageAttachmentsGetChips) {
332
insertedAny =
327
- insertAttachmentReferences(storedImages.map(imageContextReference)) || insertedAny;
333
+ insertAttachmentReferences(
334
+ storedImages.map(imageContextReference),
335
+ undefined,
336
+ pendingInsertion,
337
+ ) || insertedAny;
338
}
339
// Only failures are reported here. Success must not pass `null`: by
340
// now other work (a failed send, an overlapping paste) may have set a
apps/web/src/components/composerAttachmentInsertion.test.ts
new
+146
@@ -0,0 +1,146 @@
1
+import { Editor, Node, type Extensions, type JSONContent } from "@tiptap/core";
2
+import StarterKit from "@tiptap/starter-kit";
3
+import { TextSelection } from "@tiptap/pm/state";
4
+import { expect, it, vi } from "vite-plus/test";
5
+
6
+import { serializeEditorDoc } from "../composer-rich-text-doc";
7
+import { formatInlineContextReference } from "../lib/composerContextReferences";
8
+import { captureComposerAttachmentInsertion } from "./composerAttachmentInsertion";
9
+import { ComposerMarkdownSourceExtension } from "../composer-markdown-source";
10
+
11
+const image = { kind: "image", contextId: "image_pending", label: "picture.png" } as const;
12
+
13
+function createEditor(content: JSONContent, extensions: Extensions = []) {
14
+ const editor = new Editor({
15
+ extensions: [
16
+ StarterKit.configure({ trailingNode: false }),
17
+ Node.create({
18
+ name: "composer-context-reference",
19
+ group: "inline",
20
+ inline: true,
21
+ atom: true,
22
+ addAttributes: () => ({
23
+ kind: { default: "" },
24
+ contextId: { default: "" },
25
+ label: { default: "" },
26
+ source: { default: "" },
27
+ }),
28
+ }),
29
+ ...extensions,
30
+ ],
31
+ content,
32
+ });
33
+ editor.view.updateState(editor.state.reconfigure({ plugins: editor.extensionManager.plugins }));
34
+ return editor;
35
+}
36
+
37
+it.each([
38
+ { name: "continued typing", selected: "", insertedBefore: "" },
39
+ { name: "replaced selected text", selected: "selected", insertedBefore: "" },
40
+ { name: "an edit before the paste point", selected: "", insertedBefore: "prefix " },
41
+])("keeps the paste point and current caret after $name", ({ selected, insertedBefore }) => {
42
+ const editor = createEditor({
43
+ type: "doc",
44
+ content: [{ type: "paragraph", content: [{ type: "text", text: `Before ${selected}` }] }],
45
+ });
46
+ try {
47
+ // Headless Tiptap has no mounted view, so its lifecycle getter reports destroyed.
48
+ using _alive = vi.spyOn(editor, "isDestroyed", "get").mockReturnValue(false);
49
+ editor.view.dispatch(
50
+ editor.state.tr.setSelection(TextSelection.create(editor.state.doc, 8, 8 + selected.length)),
51
+ );
52
+ const insertion = captureComposerAttachmentInsertion(editor);
53
+ if (insertedBefore) editor.view.dispatch(editor.state.tr.insertText(insertedBefore, 1));
54
+ editor.view.dispatch(editor.state.tr.insertText("yaz"));
55
+ expect(insertion.insert([image])).toBe(true);
56
+ expect(serializeEditorDoc(editor.state.doc).value).toContain(
57
+ formatInlineContextReference(image),
58
+ );
59
+ insertion.dispose();
60
+ editor.view.dispatch(editor.state.tr.insertText("maya"));
61
+
62
+ expect(serializeEditorDoc(editor.state.doc).value).toBe(
63
+ `${insertedBefore}Before ${formatInlineContextReference(image)} yazmaya`,
64
+ );
65
+ } finally {
66
+ editor.destroy();
67
+ }
68
+});
69
+
70
+it("maps source-marker rewrites before the paste point when the caret enters styled text", () => {
71
+ const editor = createEditor(
72
+ {
73
+ type: "doc",
74
+ content: [
75
+ {
76
+ type: "paragraph",
77
+ content: [
78
+ { type: "text", text: "bold", marks: [{ type: "bold" }] },
79
+ { type: "text", text: " after" },
80
+ ],
81
+ },
82
+ ],
83
+ },
84
+ [ComposerMarkdownSourceExtension],
85
+ );
86
+ try {
87
+ using _alive = vi.spyOn(editor, "isDestroyed", "get").mockReturnValue(false);
88
+ editor.view.dispatch(editor.state.tr.setSelection(TextSelection.atEnd(editor.state.doc)));
89
+ const insertion = captureComposerAttachmentInsertion(editor);
90
+ editor.view.dispatch(editor.state.tr.setSelection(TextSelection.create(editor.state.doc, 3)));
91
+ expect(editor.state.doc.textContent).toContain("**bold**");
92
+ expect(insertion.insert([image])).toBe(true);
93
+ expect(serializeEditorDoc(editor.state.doc).value).toBe(
94
+ `**bold** after ${formatInlineContextReference(image)} `,
95
+ );
96
+ } finally {
97
+ editor.destroy();
98
+ }
99
+});
100
+
101
+it("gives up the paste point when the prompt is replaced wholesale", () => {
102
+ const editor = createEditor({
103
+ type: "doc",
104
+ content: [{ type: "paragraph", content: [{ type: "text", text: "Hello world" }] }],
105
+ });
106
+ try {
107
+ using _alive = vi.spyOn(editor, "isDestroyed", "get").mockReturnValue(false);
108
+ editor.view.dispatch(editor.state.tr.setSelection(TextSelection.create(editor.state.doc, 7)));
109
+ const insertion = captureComposerAttachmentInsertion(editor);
110
+ editor.commands.setContent(
111
+ {
112
+ type: "doc",
113
+ content: [
114
+ { type: "paragraph", content: [{ type: "text", text: "Hello world @src/a.ts" }] },
115
+ ],
116
+ },
117
+ { emitUpdate: false },
118
+ );
119
+ expect(insertion.insert([image])).toBe(false);
120
+ expect(serializeEditorDoc(editor.state.doc).value).toBe("Hello world @src/a.ts");
121
+ } finally {
122
+ editor.destroy();
123
+ }
124
+});
125
+
126
+it("keeps a pending image reference as text inside a code block", () => {
127
+ const editor = createEditor({
128
+ type: "doc",
129
+ content: [{ type: "codeBlock", content: [{ type: "text", text: "Before " }] }],
130
+ });
131
+ try {
132
+ using _alive = vi.spyOn(editor, "isDestroyed", "get").mockReturnValue(false);
133
+ editor.view.dispatch(editor.state.tr.setSelection(TextSelection.atEnd(editor.state.doc)));
134
+ const insertion = captureComposerAttachmentInsertion(editor);
135
+ editor.view.dispatch(editor.state.tr.insertText("yaz"));
136
+ expect(insertion.insert([image])).toBe(true);
137
+ editor.view.dispatch(editor.state.tr.insertText("maya"));
138
+ expect(editor.state.doc.childCount).toBe(1);
139
+ expect(editor.state.doc.firstChild?.type.name).toBe("codeBlock");
140
+ expect(editor.state.doc.firstChild?.textContent).toBe(
141
+ `Before ${formatInlineContextReference(image)} yazmaya`,
142
+ );
143
+ } finally {
144
+ editor.destroy();
145
+ }
146
+});
apps/web/src/components/composerAttachmentInsertion.ts
new
+71
@@ -0,0 +1,71 @@
1
+import type { Editor, EditorEvents } from "@tiptap/core";
2
+import {
3
+ flatToMarkdown,
4
+ flatToPm,
5
+ markdownToFlat,
6
+ pmToFlat,
7
+ serializeEditorDoc,
8
+} from "../composer-rich-text-doc";
9
+import {
10
+ type ComposerContextReference,
11
+ formatInlineContextReference,
12
+ inlineContextReferenceReplacement,
13
+} from "../lib/composerContextReferences";
14
+import { markAsClipboardEdit } from "../composer-undo-grouping";
15
+
16
+export function captureComposerAttachmentInsertion(editor: Editor) {
17
+ let { from, to } = editor.state.selection;
18
+ let lost = false;
19
+ const track = ({ transaction, appendedTransactions }: EditorEvents["transaction"]) => {
20
+ // Keep the attachment before text typed at the paste point while its image is preparing.
21
+ for (const tr of [transaction, ...appendedTransactions]) {
22
+ const start = tr.mapping.mapResult(from, -1);
23
+ const end = tr.mapping.mapResult(to, -1);
24
+ // A replacement spanning the paste point (such as a controlled setContent) leaves no
25
+ // position to keep, so the caller falls back to the current caret.
26
+ lost ||= start.deletedAcross || end.deletedAcross;
27
+ from = start.pos;
28
+ to = start.deletedAfter || end.deletedBefore ? from : end.pos;
29
+ }
30
+ };
31
+ editor.on("transaction", track);
32
+ const dispose = () => {
33
+ editor.off("transaction", track);
34
+ };
35
+ return {
36
+ insert: (references: ReadonlyArray<ComposerContextReference>): boolean => {
37
+ dispose();
38
+ if (lost || editor.isDestroyed || references.length === 0) return false;
39
+ const nodeType = editor.schema.nodes["composer-context-reference"];
40
+ if (!nodeType) return false;
41
+ const map = serializeEditorDoc(editor.state.doc);
42
+ const edit = inlineContextReferenceReplacement(
43
+ map.value,
44
+ {
45
+ start: flatToMarkdown(map, pmToFlat(map, from)),
46
+ end: flatToMarkdown(map, pmToFlat(map, to)),
47
+ },
48
+ references,
49
+ );
50
+ const acceptsReference =
51
+ editor.state.doc.resolve(from).parent.type.contentMatch.matchType(nodeType) !== null;
52
+ const content = acceptsReference
53
+ ? references.flatMap((reference) => [
54
+ nodeType.create({ ...reference, source: formatInlineContextReference(reference) }),
55
+ editor.schema.text(" "),
56
+ ])
57
+ : [editor.schema.text(edit.text)];
58
+ if (acceptsReference && edit.text.startsWith(" ")) content.unshift(editor.schema.text(" "));
59
+ const tr = editor.state.tr.replaceWith(
60
+ from,
61
+ flatToPm(map, markdownToFlat(map, edit.end)),
62
+ content,
63
+ );
64
+ editor.view.dispatch(markAsClipboardEdit(tr, "paste"));
65
+ return true;
66
+ },
67
+ dispose,
68
+ };
69
+}
70
+
71
+export type ComposerAttachmentInsertion = ReturnType<typeof captureComposerAttachmentInsertion>;