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, 15:45 UTC
refactor(mobile): composer pastes and picks are cancelled by their draft, not by the composer (#25376)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Oct 26, 2026 at 02:51 UTC
6ffde5ba39ba6a718b658e2ef846e8f674c9ee6e
10 files changed
+231
-66
apps/mobile/src/components/ComposerEditor.tsx
+19
-18
@@ -3,7 +3,7 @@ import { ComposerContextId } from "@t3tools/contracts";
3
import { useAtomValue } from "@effect/atom-react";
4
import { AsyncResult } from "effect/reactivity";
5
import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
6
-import { useEffect, useRef, useState } from "react";
6
+import { useEffect, useState } from "react";
7
import type { EnvironmentId } from "@t3tools/contracts";
8
import { encodeComposerContextFragment } from "@t3tools/shared/composerContextClipboard";
9
import { collectComposerContextReferences } from "@t3tools/shared/composerContextReferences";
@@ -11,6 +11,7 @@ import { ComposerEditor as NativeComposerEditor } from "../native/T3ComposerEdit
11
import type { ComposerEditorProps as NativeComposerEditorProps } from "../native/T3ComposerEditor";
12
import {
13
appendComposerDraftAttachments,
14
+ composerContextImportsAtom,
15
createComposerDraftContextHistory,
16
getComposerDraftAfterSelection,
17
getComposerDraftSnapshot,
@@ -22,6 +23,8 @@ import {
23
useComposerDraft,
24
} from "../state/use-composer-drafts";
25
import { importComposerContextClipboard } from "../lib/composerContextClipboard";
26
+import { startComposerDraftOperation } from "../state/composerDraftOperations";
27
+import { appAtomRegistry } from "../state/atom-registry";
28
import { mobilePreferencesAtom } from "../state/preferences";
29
import { useOpenLinkedThread } from "../features/threads/useOpenLinkedThread";
30
import { ComposerContextSheet } from "./ComposerContextSheet";
@@ -73,33 +76,32 @@ export function ComposerEditor({
76
const [selected, setSelected] = useState<{ source: string; start: number; end: number } | null>(
77
null,
78
);
76
- const importRef = useRef<AbortController | null>(null);
77
- const [importing, setImporting] = useState(false);
78
- useEffect(
79
- () => () => {
80
- importRef.current?.abort();
81
- },
82
- // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Switching drafts aborts an import owned by the previous draft.
83
- [draftKey],
84
- );
79
+ const contextImports = useAtomValue(composerContextImportsAtom);
80
+ const importing = draftKey ? contextImports[draftKey] === true : false;
81
const pasteContext = async (
82
clipboard: Parameters<NonNullable<NativeComposerEditorProps["onPasteContext"]>>[0],
83
) => {
88
- if (!draftKey || importRef.current || props.readOnly || props.editable === false) return;
84
+ if (
85
+ !draftKey ||
86
+ appAtomRegistry.get(composerContextImportsAtom)[draftKey] ||
87
+ props.readOnly ||
88
+ props.editable === false
89
+ )
90
+ return;
91
const insertion = { text: clipboard.value, ...clipboard.selection };
90
- const controller = new AbortController();
91
- importRef.current = controller;
92
- setImporting(true);
92
+ const operation = startComposerDraftOperation(draftKey);
93
+ const { signal } = operation;
94
setComposerContextImporting(draftKey, true);
95
const settled = await settlePromise(async () => {
96
const retained = getComposerDraftAfterSelection(draftKey, insertion);
97
const result = await importComposerContextClipboard(
98
clipboard,
99
retained.attachments.length,
99
- controller.signal,
100
+ signal,
101
retained.context?.records.length ?? 0,
102
environmentId,
103
);
104
+ if (signal.aborted) return;
105
if (!result) {
106
insertComposerDraftText(draftKey, clipboard.text, insertion);
107
return;
@@ -126,10 +128,9 @@ export function ComposerEditor({
128
[...warnings, "Those references are marked unavailable."].join("\n\n"),
129
);
130
});
131
+ operation.finish();
132
setComposerContextImporting(draftKey, false);
130
- importRef.current = null;
131
- setImporting(false);
132
- if (AsyncResult.isFailure(settled) && !controller.signal.aborted) {
133
+ if (AsyncResult.isFailure(settled) && !signal.aborted) {
134
const error = squashAtomCommandFailure(settled);
135
Dialog.alert(
136
"Could not paste context",
apps/mobile/src/features/threads/NewTaskDraftScreen.tsx
+4
@@ -36,6 +36,7 @@ import {
36
37
import { ComposerEditor, type ComposerEditorHandle } from "../../components/ComposerEditor";
38
import { composerContextImportsAtom } from "../../state/use-composer-drafts";
39
+import { abortComposerDraftOperations } from "../../state/composerDraftOperations";
40
import { composerContextSendBlockReason } from "../../lib/composerContext";
41
import { ComposerInlineControl } from "../../components/ComposerToolbar";
42
@@ -934,6 +935,9 @@ export function NewTaskDraftScreen(props: {
935
submittedThreadParams(String(message.environmentId), String(message.threadId)),
936
),
937
);
938
+ // The composer has moved to the submitted thread; a pick still converting
939
+ // would otherwise resurrect this draft.
940
+ abortComposerDraftOperations(draftKey);
941
const draftSnapshot = getComposerDraftSnapshot(draftKey);
942
if (editingPendingTask) {
943
flow.finishEditingPendingTask();
apps/mobile/src/lib/composerContextClipboard.test.ts
+18
@@ -169,6 +169,24 @@ describe("mobile context clipboard imports", () => {
169
expect(mocks.dispose).toHaveBeenCalledOnce();
170
});
171
172
+ it("releases its files if cancelled after the last copy finishes", async () => {
173
+ const controller = new AbortController();
174
+ mocks.dispose.mockImplementationOnce(() => controller.abort());
175
+ const imageOnly = {
176
+ text: "",
177
+ fragment: encodeComposerContextFragment({
178
+ version: 1,
179
+ source: { environmentId: EnvironmentId.make("source") },
180
+ records: [image],
181
+ })!,
182
+ html: "",
183
+ };
184
+ await expect(importComposerContextClipboard(imageOnly, 0, controller.signal)).rejects.toThrow(
185
+ "cancelled",
186
+ );
187
+ expect(mocks.remove).toHaveBeenCalledWith("file:///owned.png");
188
+ });
189
+
190
it("can copy an image before its source upload completes", async () => {
191
mocks.local.mockReturnValue({
192
id: "source-file",
apps/mobile/src/lib/composerContextClipboard.ts
+2
@@ -106,6 +106,8 @@ export async function importComposerContextClipboard(
106
failures.push(record.name);
107
}
108
}
109
+ // The last copy can be cancelled after its own check; a cancelled import must not return files nobody will release.
110
+ checkAborted(signal);
111
return {
112
text: imported.text,
113
context: { version: 1 as const, records },
apps/mobile/src/state/composerDraftOperations.test.ts
new
+42
@@ -0,0 +1,42 @@
1
+import { describe, expect, it } from "vite-plus/test";
2
+
3
+import {
4
+ abortComposerDraftOperations,
5
+ startComposerDraftOperation,
6
+} from "./composerDraftOperations";
7
+
8
+describe("composer draft operations", () => {
9
+ it("aborts every running operation for the draft and leaves other drafts alone", () => {
10
+ const first = startComposerDraftOperation("thread-a");
11
+ const second = startComposerDraftOperation("thread-a");
12
+ const other = startComposerDraftOperation("thread-b");
13
+
14
+ abortComposerDraftOperations("thread-a");
15
+
16
+ expect(first.signal.aborted).toBe(true);
17
+ expect(second.signal.aborted).toBe(true);
18
+ expect(other.signal.aborted).toBe(false);
19
+ other.finish();
20
+ });
21
+
22
+ it("does not abort an operation that finished before the draft switched", () => {
23
+ const finished = startComposerDraftOperation("thread-c");
24
+ finished.finish();
25
+ const running = startComposerDraftOperation("thread-c");
26
+
27
+ abortComposerDraftOperations("thread-c");
28
+
29
+ expect(finished.signal.aborted).toBe(false);
30
+ expect(running.signal.aborted).toBe(true);
31
+ });
32
+
33
+ it("keeps tracking an operation started after an abort when an older one finishes", () => {
34
+ const before = startComposerDraftOperation("thread-d");
35
+ abortComposerDraftOperations("thread-d");
36
+ const after = startComposerDraftOperation("thread-d");
37
+ before.finish();
38
+ abortComposerDraftOperations("thread-d");
39
+
40
+ expect(after.signal.aborted).toBe(true);
41
+ });
42
+});
apps/mobile/src/state/composerDraftOperations.ts
new
+39
@@ -0,0 +1,39 @@
1
+const operationsByDraftKey = new Map<string, Set<AbortController>>();
2
+
3
+/**
4
+ * Async work that writes into one draft (a context import, a picker) starts
5
+ * here. Whoever discards that draft or moves the composer off it aborts the
6
+ * work, so a late result never lands in a draft the user has left.
7
+ */
8
+export function startComposerDraftOperation(draftKey: string): {
9
+ readonly signal: AbortSignal;
10
+ readonly finish: () => void;
11
+} {
12
+ const controller = new AbortController();
13
+ const operations = operationsByDraftKey.get(draftKey) ?? new Set();
14
+ operations.add(controller);
15
+ operationsByDraftKey.set(draftKey, operations);
16
+ return {
17
+ signal: controller.signal,
18
+ finish: () => {
19
+ operations.delete(controller);
20
+ if (operations.size === 0 && operationsByDraftKey.get(draftKey) === operations) {
21
+ operationsByDraftKey.delete(draftKey);
22
+ }
23
+ },
24
+ };
25
+}
26
+
27
+export function abortComposerDraftOperations(draftKey: string): void {
28
+ const operations = operationsByDraftKey.get(draftKey);
29
+ if (!operations) return;
30
+ operationsByDraftKey.delete(draftKey);
31
+ for (const controller of operations) controller.abort();
32
+}
33
+
34
+export function abortComposerDraftOperationsWhere(matches: (draftKey: string) => boolean): void {
35
+ // Deleting the current entry while iterating a Map is safe.
36
+ for (const draftKey of operationsByDraftKey.keys()) {
37
+ if (matches(draftKey)) abortComposerDraftOperations(draftKey);
38
+ }
39
+}
apps/mobile/src/state/queued-run-edit.ts
+3
@@ -10,6 +10,7 @@ import { useAtomValue } from "@effect/atom-react";
10
11
import { uploadedComposerContext } from "../lib/composerContext";
12
import { appAtomRegistry } from "./atom-registry";
13
+import { abortComposerDraftOperations } from "./composerDraftOperations";
14
import { queuedEditDraftKey } from "./queued-edit-draft-key";
15
import {
16
clearComposerDraft,
@@ -59,6 +60,8 @@ export function beginQueuedRunEdit(threadKey: string, edit: QueuedRunEdit): void
60
if (previous !== null && previous.runId !== edit.runId) {
61
clearComposerDraft(queuedEditDraftKey(threadKey, previous.runId));
62
}
63
+ // The composer moves off the thread draft, so a paste or pick still running for it is dropped.
64
+ abortComposerDraftOperations(threadKey);
65
const draftKey = queuedEditDraftKey(threadKey, edit.runId);
66
clearComposerDraft(draftKey);
67
setComposerDraftText(draftKey, edit.originalText);
apps/mobile/src/state/use-composer-attachment-actions.ts
+65
-48
@@ -1,5 +1,5 @@
1
import * as Dialog from "../components/ui/Dialog";
2
-import { useLayoutEffect, useRef } from "react";
2
+import { useRef } from "react";
3
import { PROVIDER_SEND_TURN_MAX_ATTACHMENTS, type ServerConfig } from "@t3tools/contracts";
4
import { clampFileAttachmentUploadBytes } from "@t3tools/client-runtime/state/attachments";
5
import { nextPastedTextFileName } from "@t3tools/client-runtime/text-paste";
@@ -19,28 +19,22 @@ import {
19
getComposerDraftSnapshot,
20
type ComposerDraftInsertion,
21
} from "./use-composer-drafts";
22
+import { startComposerDraftOperation } from "./composerDraftOperations";
23
24
export function useComposerAttachmentActions(props: {
25
readonly draftKey: string | null;
26
readonly serverConfig: ServerConfig | null | undefined;
27
readonly locked?: boolean;
28
}) {
28
- const currentKey = useRef(props.draftKey);
29
const reservedNames = useRef(new Map<string, Set<string>>());
30
- useLayoutEffect(() => {
31
- currentKey.current = props.draftKey;
32
- return () => {
33
- currentKey.current = null;
34
- };
35
- }, [props.draftKey]);
30
const capabilities = props.serverConfig?.environment.capabilities;
31
const append = async (
32
key: string,
33
+ signal: AbortSignal,
34
attachments: ReadonlyArray<DraftComposerAttachment>,
35
insertion: ComposerDraftInsertion,
36
) => {
42
- // A picker may finish after selecting another draft or sending this one.
43
- if (currentKey.current !== key) {
37
+ if (signal.aborted) {
38
await Promise.all(
39
attachments.flatMap((item) =>
40
item.fileUri ? [removePersistedComposerAttachmentFile(item.fileUri)] : [],
@@ -50,6 +44,11 @@ export function useComposerAttachmentActions(props: {
44
}
45
return appendComposerDraftAttachments(key, attachments, { appendReference: true, insertion });
46
};
47
+ // A picker may finish after its draft was discarded or the composer moved off it.
48
+ const withDraftOperation = async (key: string, work: (signal: AbortSignal) => Promise<void>) => {
49
+ const operation = startComposerDraftOperation(key);
50
+ await work(operation.signal).finally(operation.finish);
51
+ };
52
const report = (title: string, error: string | null | undefined, rejected: number) => {
53
const problems = [
54
...(error ? [error] : []),
@@ -63,17 +62,19 @@ export function useComposerAttachmentActions(props: {
62
const key = props.draftKey;
63
if (!key || props.locked) return;
64
const insertion = captureComposerDraftInsertion(key);
66
- const result = await pickComposerMedia({
67
- existingCount: countComposerDraftAttachmentsAfterSelection(key, insertion),
68
- maxVideoBytes: capabilities?.attachmentUploads
69
- ? capabilities.fileAttachments?.maxUploadBytes
70
- : undefined,
65
+ await withDraftOperation(key, async (signal) => {
66
+ const result = await pickComposerMedia({
67
+ existingCount: countComposerDraftAttachmentsAfterSelection(key, insertion),
68
+ maxVideoBytes: capabilities?.attachmentUploads
69
+ ? capabilities.fileAttachments?.maxUploadBytes
70
+ : undefined,
71
+ });
72
+ report(
73
+ "Could not attach photo or video",
74
+ result.error,
75
+ await append(key, signal, result.attachments, insertion),
76
+ );
77
});
72
- report(
73
- "Could not attach photo or video",
74
- result.error,
75
- await append(key, result.attachments, insertion),
76
- );
78
};
79
const onPickDraftFiles = async () => {
80
const key = props.draftKey;
@@ -84,25 +85,36 @@ export function useComposerAttachmentActions(props: {
85
return;
86
}
87
const insertion = captureComposerDraftInsertion(key);
87
- const result = await pickComposerFiles({
88
- existingCount: countComposerDraftAttachmentsAfterSelection(key, insertion),
89
- maxBytes,
88
+ await withDraftOperation(key, async (signal) => {
89
+ const result = await pickComposerFiles({
90
+ existingCount: countComposerDraftAttachmentsAfterSelection(key, insertion),
91
+ maxBytes,
92
+ });
93
+ report(
94
+ "Could not attach file",
95
+ result.error,
96
+ await append(key, signal, result.files, insertion),
97
+ );
98
});
91
- report("Could not attach file", result.error, await append(key, result.files, insertion));
99
};
100
const onNativePasteImages = async (uris: ReadonlyArray<string>) => {
101
const key = props.draftKey;
102
if (!key || props.locked || !uris.length) return;
103
const insertion = captureComposerDraftInsertion(key);
97
- try {
98
- const images = await convertPastedImagesToAttachments({
99
- uris,
100
- existingCount: countComposerDraftAttachmentsAfterSelection(key, insertion),
101
- });
102
- report("Could not paste images", null, await append(key, images, insertion));
103
- } catch (error) {
104
- Dialog.alert("Could not paste images", error instanceof Error ? error.message : "Try again.");
105
- }
104
+ await withDraftOperation(key, async (signal) => {
105
+ try {
106
+ const images = await convertPastedImagesToAttachments({
107
+ uris,
108
+ existingCount: countComposerDraftAttachmentsAfterSelection(key, insertion),
109
+ });
110
+ report("Could not paste images", null, await append(key, signal, images, insertion));
111
+ } catch (error) {
112
+ Dialog.alert(
113
+ "Could not paste images",
114
+ error instanceof Error ? error.message : "Try again.",
115
+ );
116
+ }
117
+ });
118
};
119
const onNativePasteText = async (paste: ComposerTextPaste) => {
120
const key = props.draftKey;
@@ -116,21 +128,26 @@ export function useComposerAttachmentActions(props: {
128
for (const attachment of getComposerDraftSnapshot(key).attachments) names.add(attachment.name);
129
const name = nextPastedTextFileName([...names]);
130
names.add(name);
119
- try {
120
- const attachment = await createPastedTextComposerAttachment({
121
- text: paste.text,
122
- name,
123
- maxBytes: clampFileAttachmentUploadBytes(maxBytes),
124
- });
125
- const rejected = await append(key, [attachment], { text: paste.value, ...paste.selection });
126
- if (rejected) await removePersistedComposerAttachmentFile(attachment.fileUri);
127
- report("Could not attach pasted text", null, rejected);
128
- } catch (error) {
129
- Dialog.alert(
130
- "Could not attach pasted text",
131
- error instanceof Error ? error.message : "Try again.",
132
- );
133
- }
131
+ await withDraftOperation(key, async (signal) => {
132
+ try {
133
+ const attachment = await createPastedTextComposerAttachment({
134
+ text: paste.text,
135
+ name,
136
+ maxBytes: clampFileAttachmentUploadBytes(maxBytes),
137
+ });
138
+ const rejected = await append(key, signal, [attachment], {
139
+ text: paste.value,
140
+ ...paste.selection,
141
+ });
142
+ if (rejected) await removePersistedComposerAttachmentFile(attachment.fileUri);
143
+ report("Could not attach pasted text", null, rejected);
144
+ } catch (error) {
145
+ Dialog.alert(
146
+ "Could not attach pasted text",
147
+ error instanceof Error ? error.message : "Try again.",
148
+ );
149
+ }
150
+ });
151
};
152
return { onPickDraftMedia, onPickDraftFiles, onNativePasteImages, onNativePasteText };
153
}
apps/mobile/src/state/use-composer-drafts.test.ts
+27
@@ -171,6 +171,7 @@ import {
171
formatComposerContextReference,
172
} from "@t3tools/shared/composerContextReferences";
173
import { appAtomRegistry } from "./atom-registry";
174
+import { startComposerDraftOperation } from "./composerDraftOperations";
175
import { threadOutboxManager } from "./thread-outbox";
176
import {
177
appendComposerDraftAttachments,
@@ -2276,6 +2277,32 @@ describe("mobile composer drafts", () => {
2277
});
2278
});
2279
2280
+ it("aborts operations running for drafts an environment removal drops", async () => {
2281
+ const environmentId = EnvironmentId.make("environment-removed");
2282
+ composerDraftFileMocks.setDocument({ schemaVersion: 1, drafts: {} });
2283
+ appAtomRegistry.set(composerDraftsAtom, {
2284
+ "new-task:removed-draft": {
2285
+ ...DRAFT,
2286
+ project: {
2287
+ environmentId,
2288
+ projectId: ProjectId.make("project-removed"),
2289
+ createdAt: "2026-09-05T00:00:00.000Z",
2290
+ },
2291
+ },
2292
+ "environment-kept:thread-kept": DRAFT,
2293
+ });
2294
+ const newTask = startComposerDraftOperation("new-task:removed-draft");
2295
+ const emptyThread = startComposerDraftOperation(`${environmentId}:thread-empty`);
2296
+ const kept = startComposerDraftOperation("environment-kept:thread-kept");
2297
+
2298
+ await clearComposerDraftsEnvironment(environmentId);
2299
+
2300
+ expect(newTask.signal.aborted).toBe(true);
2301
+ expect(emptyThread.signal.aborted).toBe(true);
2302
+ expect(kept.signal.aborted).toBe(false);
2303
+ kept.finish();
2304
+ });
2305
+
2306
it("lands a still-debounced draft write when flushed", async () => {
2307
const draftKey = "environment-1:thread-1";
2308
setComposerDraftText(draftKey, "typed right before the restart");
apps/mobile/src/state/use-composer-drafts.ts
+12
@@ -54,6 +54,10 @@ import {
54
import type { DraftComposerAttachment, FileBackedComposerAttachment } from "../lib/composerImages";
55
import { SerializedAsyncQueue } from "../lib/serialized-async-queue";
56
import { appAtomRegistry } from "./atom-registry";
57
+import {
58
+ abortComposerDraftOperations,
59
+ abortComposerDraftOperationsWhere,
60
+} from "./composerDraftOperations";
61
import {
62
isNewTaskDraftKey,
63
newTaskDraftKey,
@@ -1804,6 +1808,7 @@ export function clearComposerDraft(
1808
draftKey: string,
1809
options?: { readonly deferAttachmentCleanup?: boolean },
1810
): void {
1811
+ abortComposerDraftOperations(draftKey);
1812
const previousAttachments = getComposerDraftSnapshot(draftKey).attachments;
1813
updateComposerDrafts((current) => {
1814
if (!current[draftKey]) {
@@ -1913,6 +1918,13 @@ export async function clearComposerDraftsEnvironment(environmentId: EnvironmentI
1918
const removedAttachments = Object.entries(current)
1919
.filter(([draftKey]) => next[draftKey] === undefined)
1920
.flatMap(([, draft]) => draft.attachments);
1921
+ // Keys with no stored draft yet (an empty thread composer) can still have a pick running.
1922
+ const environmentPrefix = `${environmentId}:`;
1923
+ abortComposerDraftOperationsWhere(
1924
+ (draftKey) =>
1925
+ draftKey.startsWith(environmentPrefix) ||
1926
+ (current[draftKey] !== undefined && next[draftKey] === undefined),
1927
+ );
1928
1929
if (persistTimer !== null) {
1930
clearTimeout(persistTimer);