Skip to content

Commit 7b8713b

Browse files
refactor(mobile): composer pastes and picks are cancelled by their draft, not by the composer
Mobile's composer guarded late async results (a context paste import, a photo/file pick, a pasted-image conversion) with component state: the attachment actions hook mirrored the draft key into a ref from a useLayoutEffect, and ComposerEditor aborted its import from an effect cleanup keyed on draftKey while keeping a local `importing` flag next to the per-draft importing atom it also wrote. Async work that writes into a draft now registers with composerDraftOperations under that draft's key. Whoever discards the draft or moves the composer off it aborts the work: clearComposerDraft, clearComposerDraftsEnvironment (including empty thread drafts with no stored entry), beginQueuedRunEdit for the thread draft, and the new-task submit. ComposerEditor reads `importing` from composerContextImportsAtom. Effects: use-composer-attachment-actions 1 -> 0 (useLayoutEffect key mirror), ComposerEditor 1 -> 0 (abort-on-key-change cleanup; one useState mirror of the atom removed). No effects added. Behavior change: unmounting the composer or switching it to another draft no longer cancels a paste/pick; the result lands in the draft it started for. It is dropped only when that draft is cleared, its environment is removed, a queued-run edit takes over the thread composer, or a new task is submitted. Clearing a thread draft (send) now also drops a pick still running for it, where before the result landed in the emptied draft. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 2763bbe commit 7b8713b

8 files changed

Lines changed: 211 additions & 66 deletions

‎apps/mobile/src/components/ComposerEditor.tsx‎

Lines changed: 19 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -3,14 +3,15 @@ import { ComposerContextId } from "@t3tools/contracts";
33
import { useAtomValue } from "@effect/atom-react";
44
import { AsyncResult } from "effect/reactivity";
55
import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
6-
import { useEffect, useRef, useState } from "react";
6+
import { useEffect, useState } from "react";
77
import type { EnvironmentId } from "@t3tools/contracts";
88
import { encodeComposerContextFragment } from "@t3tools/shared/composerContextClipboard";
99
import { collectComposerContextReferences } from "@t3tools/shared/composerContextReferences";
1010
import { ComposerEditor as NativeComposerEditor } from "../native/T3ComposerEditor";
1111
import type { ComposerEditorProps as NativeComposerEditorProps } from "../native/T3ComposerEditor";
1212
import {
1313
appendComposerDraftAttachments,
14+
composerContextImportsAtom,
1415
createComposerDraftContextHistory,
1516
getComposerDraftAfterSelection,
1617
getComposerDraftSnapshot,
@@ -22,6 +23,8 @@ import {
2223
useComposerDraft,
2324
} from "../state/use-composer-drafts";
2425
import { importComposerContextClipboard } from "../lib/composerContextClipboard";
26+
import { startComposerDraftOperation } from "../state/composerDraftOperations";
27+
import { appAtomRegistry } from "../state/atom-registry";
2528
import { mobilePreferencesAtom } from "../state/preferences";
2629
import { useOpenLinkedThread } from "../features/threads/useOpenLinkedThread";
2730
import { ComposerContextSheet } from "./ComposerContextSheet";
@@ -73,33 +76,32 @@ export function ComposerEditor({
7376
const [selected, setSelected] = useState<{ source: string; start: number; end: number } | null>(
7477
null,
7578
);
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;
8581
const pasteContext = async (
8682
clipboard: Parameters<NonNullable<NativeComposerEditorProps["onPasteContext"]>>[0],
8783
) => {
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;
8991
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;
9394
setComposerContextImporting(draftKey, true);
9495
const settled = await settlePromise(async () => {
9596
const retained = getComposerDraftAfterSelection(draftKey, insertion);
9697
const result = await importComposerContextClipboard(
9798
clipboard,
9899
retained.attachments.length,
99-
controller.signal,
100+
signal,
100101
retained.context?.records.length ?? 0,
101102
environmentId,
102103
);
104+
if (signal.aborted) return;
103105
if (!result) {
104106
insertComposerDraftText(draftKey, clipboard.text, insertion);
105107
return;
@@ -126,10 +128,9 @@ export function ComposerEditor({
126128
[...warnings, "Those references are marked unavailable."].join("\n\n"),
127129
);
128130
});
131+
operation.finish();
129132
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) {
133134
const error = squashAtomCommandFailure(settled);
134135
Dialog.alert(
135136
"Could not paste context",

‎apps/mobile/src/features/threads/NewTaskDraftScreen.tsx‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@ import {
3636

3737
import { ComposerEditor, type ComposerEditorHandle } from "../../components/ComposerEditor";
3838
import { composerContextImportsAtom } from "../../state/use-composer-drafts";
39+
import { abortComposerDraftOperations } from "../../state/composerDraftOperations";
3940
import { composerContextSendBlockReason } from "../../lib/composerContext";
4041
import { ComposerInlineControl } from "../../components/ComposerToolbar";
4142

@@ -934,6 +935,9 @@ export function NewTaskDraftScreen(props: {
934935
submittedThreadParams(String(message.environmentId), String(message.threadId)),
935936
),
936937
);
938+
// The composer has moved to the submitted thread; a pick still converting
939+
// would otherwise resurrect this draft.
940+
abortComposerDraftOperations(draftKey);
937941
const draftSnapshot = getComposerDraftSnapshot(draftKey);
938942
if (editingPendingTask) {
939943
flow.finishEditingPendingTask();
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -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+
});
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -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‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import { useAtomValue } from "@effect/atom-react";
1010

1111
import { uploadedComposerContext } from "../lib/composerContext";
1212
import { appAtomRegistry } from "./atom-registry";
13+
import { abortComposerDraftOperations } from "./composerDraftOperations";
1314
import { queuedEditDraftKey } from "./queued-edit-draft-key";
1415
import {
1516
clearComposerDraft,
@@ -59,6 +60,8 @@ export function beginQueuedRunEdit(threadKey: string, edit: QueuedRunEdit): void
5960
if (previous !== null && previous.runId !== edit.runId) {
6061
clearComposerDraft(queuedEditDraftKey(threadKey, previous.runId));
6162
}
63+
// The composer moves off the thread draft, so a paste or pick still running for it is dropped.
64+
abortComposerDraftOperations(threadKey);
6265
const draftKey = queuedEditDraftKey(threadKey, edit.runId);
6366
clearComposerDraft(draftKey);
6467
setComposerDraftText(draftKey, edit.originalText);
Lines changed: 65 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import * as Dialog from "../components/ui/Dialog";
2-
import { useLayoutEffect, useRef } from "react";
2+
import { useRef } from "react";
33
import { PROVIDER_SEND_TURN_MAX_ATTACHMENTS, type ServerConfig } from "@t3tools/contracts";
44
import { clampFileAttachmentUploadBytes } from "@t3tools/client-runtime/state/attachments";
55
import { nextPastedTextFileName } from "@t3tools/client-runtime/text-paste";
@@ -19,28 +19,22 @@ import {
1919
getComposerDraftSnapshot,
2020
type ComposerDraftInsertion,
2121
} from "./use-composer-drafts";
22+
import { startComposerDraftOperation } from "./composerDraftOperations";
2223

2324
export function useComposerAttachmentActions(props: {
2425
readonly draftKey: string | null;
2526
readonly serverConfig: ServerConfig | null | undefined;
2627
readonly locked?: boolean;
2728
}) {
28-
const currentKey = useRef(props.draftKey);
2929
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]);
3630
const capabilities = props.serverConfig?.environment.capabilities;
3731
const append = async (
3832
key: string,
33+
signal: AbortSignal,
3934
attachments: ReadonlyArray<DraftComposerAttachment>,
4035
insertion: ComposerDraftInsertion,
4136
) => {
42-
// A picker may finish after selecting another draft or sending this one.
43-
if (currentKey.current !== key) {
37+
if (signal.aborted) {
4438
await Promise.all(
4539
attachments.flatMap((item) =>
4640
item.fileUri ? [removePersistedComposerAttachmentFile(item.fileUri)] : [],
@@ -50,6 +44,11 @@ export function useComposerAttachmentActions(props: {
5044
}
5145
return appendComposerDraftAttachments(key, attachments, { appendReference: true, insertion });
5246
};
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+
};
5352
const report = (title: string, error: string | null | undefined, rejected: number) => {
5453
const problems = [
5554
...(error ? [error] : []),
@@ -63,17 +62,19 @@ export function useComposerAttachmentActions(props: {
6362
const key = props.draftKey;
6463
if (!key || props.locked) return;
6564
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+
);
7177
});
72-
report(
73-
"Could not attach photo or video",
74-
result.error,
75-
await append(key, result.attachments, insertion),
76-
);
7778
};
7879
const onPickDraftFiles = async () => {
7980
const key = props.draftKey;
@@ -84,25 +85,36 @@ export function useComposerAttachmentActions(props: {
8485
return;
8586
}
8687
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+
);
9098
});
91-
report("Could not attach file", result.error, await append(key, result.files, insertion));
9299
};
93100
const onNativePasteImages = async (uris: ReadonlyArray<string>) => {
94101
const key = props.draftKey;
95102
if (!key || props.locked || !uris.length) return;
96103
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+
});
106118
};
107119
const onNativePasteText = async (paste: ComposerTextPaste) => {
108120
const key = props.draftKey;
@@ -116,21 +128,26 @@ export function useComposerAttachmentActions(props: {
116128
for (const attachment of getComposerDraftSnapshot(key).attachments) names.add(attachment.name);
117129
const name = nextPastedTextFileName([...names]);
118130
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+
});
134151
};
135152
return { onPickDraftMedia, onPickDraftFiles, onNativePasteImages, onNativePasteText };
136153
}

0 commit comments

Comments
 (0)