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 21, 07:15 UTC
fix(web): Enter during image compression sends once it finishes (#37547)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Julius Marminge <julius0216@outlook.com>
Muzammil Hussain committed
Nov 19, 2026 at 01:26 UTC
ad77fd88e2cf3be58c5e4c93b41d6dc705f648c3
21 files changed
+491
-49
apps/mobile/src/features/threads/ThreadComposer.tsx
+17
-9
@@ -48,6 +48,7 @@ import {
48
composerContextImportsAtom,
49
countComposerDraftAttachmentsAfterSelection,
50
useComposerDraft,
51
+ useComposerDraftResetGeneration,
52
} from "../../state/use-composer-drafts";
53
import type { ComposerDocumentAttachment } from "../../lib/composerContext";
54
import { useProject, useVisibleThreadShells } from "../../state/entities";
@@ -102,6 +103,7 @@ import {
103
resolveComposerSendPresentation,
104
type ComposerSendPresentation,
105
} from "./composerSendPresentation";
106
+import { useSubmitAfterNativeImages } from "./useSubmitAfterNativeImages";
107
import { ComposerCommandPopover } from "./ComposerCommandPopover";
108
import { ComposerPopoverAnchor } from "./ComposerPopoverAnchor";
109
import { ComposerQueuedEditAttachments } from "./ComposerQueuedEdit";
@@ -174,7 +176,7 @@ export interface ThreadComposerProps {
176
readonly onChangeDraftMessage: (value: string) => void;
177
readonly onPickDraftMedia: () => Promise<void>;
178
readonly onPickDraftFiles: () => Promise<void>;
177
- readonly onNativePasteImages: (uris: ReadonlyArray<string>) => Promise<void>;
179
+ readonly onNativePasteImages: (uris: ReadonlyArray<string>) => Promise<boolean>;
180
readonly onNativePasteText: (paste: ComposerTextPaste) => Promise<void>;
181
readonly onRemoveDraftImage: (imageId: string) => void;
182
readonly onStopThread: () => void;
@@ -294,6 +296,7 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps
296
const [previewVideo, setPreviewVideo] = useState<VideoPreviewSource | null>(null);
297
const composerOwnerKey = scopedThreadKey(props.environmentId, props.selectedThread.id);
298
const composerDraftKey = props.draftKey ?? composerOwnerKey;
299
+ const readResetGeneration = useComposerDraftResetGeneration(composerDraftKey);
300
const {
301
text: draftMessage,
302
attachments: draftAttachments,
@@ -543,13 +546,10 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps
546
onEditorFocusChange?.(false);
547
};
548
const handleSend = async (followUp?: ActiveTurnComposerAction) => {
546
- if (
547
- isSubmissionLocked ||
548
- sendBlockedReason !== null ||
549
- pendingPastedTextAttachmentCountRef.current > 0 ||
550
- pendingNativeImagePasteCountRef.current > 0
551
- )
552
- return;
549
+ if (isSubmissionLocked || sendBlockedReason !== null) return;
550
+ // Sending now would leave a still-converting pasted image out of the turn, so wait for it.
551
+ if (nativeImageSubmit.deferSend(followUp)) return;
552
+ if (pendingPastedTextAttachmentCountRef.current > 0) return;
553
if (usageLimitsOffered && isUsageLimitsCommand(draftMessage) && draftAttachments.length === 0) {
554
if (openUsageLimits()) onChangeDraftMessage("");
555
return;
@@ -586,6 +586,14 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps
586
});
587
};
588
589
+ const nativeImageSubmit = useSubmitAfterNativeImages({
590
+ draftKey: composerDraftKey,
591
+ readResetGeneration,
592
+ blocked: isSubmissionLocked || sendBlockedReason !== null,
593
+ onPasteImages: props.onNativePasteImages,
594
+ onSubmit: (followUp) => void handleSend(followUp),
595
+ });
596
+
597
const lockedProviderInstanceId = props.canSwitchProvider
598
? undefined
599
: currentModelSelection.instanceId;
@@ -871,7 +879,7 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps
879
onPasteImages={(uris) => {
880
if (isSubmissionLocked) return;
881
pendingNativeImagePasteCountRef.current += 1;
874
- void props.onNativePasteImages(uris).finally(() => {
882
+ void nativeImageSubmit.pasteImages(uris).finally(() => {
883
pendingNativeImagePasteCountRef.current -= 1;
884
});
885
}}
apps/mobile/src/features/threads/ThreadDetailScreen.tsx
+1
-1
@@ -287,7 +287,7 @@ export interface ThreadDetailScreenProps {
287
readonly onChangeDraftMessage: (value: string) => void;
288
readonly onPickDraftMedia: () => Promise<void>;
289
readonly onPickDraftFiles: () => Promise<void>;
290
- readonly onNativePasteImages: (uris: ReadonlyArray<string>) => Promise<void>;
290
+ readonly onNativePasteImages: (uris: ReadonlyArray<string>) => Promise<boolean>;
291
readonly onNativePasteText: (paste: ComposerTextPaste) => Promise<void>;
292
readonly onRemoveDraftImage: (imageId: string) => void;
293
readonly onStopThread: () => void;
apps/mobile/src/features/threads/useSubmitAfterNativeImages.test.tsx
new
+114
@@ -0,0 +1,114 @@
1
+import { act, useLayoutEffect } from "react";
2
+import { createRoot } from "react-dom/client";
3
+import { expect, it, vi } from "vite-plus/test";
4
+import { useSubmitAfterNativeImages } from "./useSubmitAfterNativeImages";
5
+
6
+function setup() {
7
+ const root = createRoot(document.createElement("div"));
8
+ let queue: ReturnType<typeof useSubmitAfterNativeImages>;
9
+ let generation = 0;
10
+ let blocked = false;
11
+ const onSubmit = vi.fn();
12
+ const preparations: Array<(success: boolean) => void> = [];
13
+ const onPasteImages = () => new Promise<boolean>((resolve) => preparations.push(resolve));
14
+ function Probe() {
15
+ const current = useSubmitAfterNativeImages({
16
+ draftKey: "draft",
17
+ readResetGeneration: () => generation,
18
+ blocked,
19
+ onPasteImages,
20
+ onSubmit: (action) => {
21
+ if (!blocked) onSubmit(action);
22
+ },
23
+ });
24
+ useLayoutEffect(() => {
25
+ queue = current;
26
+ });
27
+ return null;
28
+ }
29
+ const render = () => act(() => root.render(<Probe />));
30
+ render();
31
+ return {
32
+ get queue() {
33
+ return queue!;
34
+ },
35
+ onSubmit,
36
+ setBlocked(value: boolean) {
37
+ blocked = value;
38
+ render();
39
+ },
40
+ reset() {
41
+ generation += 1;
42
+ render();
43
+ },
44
+ async finish(success: boolean) {
45
+ await act(async () => {
46
+ preparations.shift()!(success);
47
+ });
48
+ },
49
+ [Symbol.dispose]() {
50
+ act(() => root.unmount());
51
+ },
52
+ };
53
+}
54
+
55
+it("does not send when conversion finishes without adding an image", async () => {
56
+ using state = setup();
57
+ const paste = state.queue.pasteImages(["image"]);
58
+ expect(state.queue.deferSend()).toBe(true);
59
+ await state.finish(false);
60
+ await paste;
61
+ expect(state.onSubmit).not.toHaveBeenCalled();
62
+
63
+ const first = state.queue.pasteImages(["failed"]);
64
+ const second = state.queue.pasteImages(["successful"]);
65
+ state.queue.deferSend();
66
+ await state.finish(false);
67
+ await state.finish(true);
68
+ await Promise.all([first, second]);
69
+ expect(state.onSubmit).not.toHaveBeenCalled();
70
+
71
+ const retry = state.queue.pasteImages(["retry"]);
72
+ state.queue.deferSend();
73
+ await state.finish(true);
74
+ await retry;
75
+ expect(state.onSubmit).toHaveBeenCalledOnce();
76
+});
77
+
78
+it("does not send a replacement draft after the original draft was discarded", async () => {
79
+ using state = setup();
80
+ const paste = state.queue.pasteImages(["image"]);
81
+ state.queue.deferSend();
82
+ state.reset();
83
+ await state.finish(true);
84
+ await paste;
85
+ expect(state.onSubmit).not.toHaveBeenCalled();
86
+
87
+ const next = state.queue.pasteImages(["next"]);
88
+ state.queue.deferSend();
89
+ state.setBlocked(true);
90
+ await state.finish(true);
91
+ await next;
92
+ state.reset();
93
+ state.setBlocked(false);
94
+ expect(state.onSubmit).not.toHaveBeenCalled();
95
+});
96
+
97
+it("waits for other attachment preparation and sends once after all images join the draft", async () => {
98
+ using state = setup();
99
+ const first = state.queue.pasteImages(["first"]);
100
+ const second = state.queue.pasteImages(["second"]);
101
+ state.queue.deferSend("queue");
102
+ state.queue.deferSend("steer");
103
+ await state.finish(true);
104
+ expect(state.onSubmit).not.toHaveBeenCalled();
105
+ state.setBlocked(true);
106
+ await state.finish(true);
107
+ await Promise.all([first, second]);
108
+ expect(state.onSubmit).not.toHaveBeenCalled();
109
+ state.setBlocked(false);
110
+ expect(state.onSubmit).toHaveBeenCalledExactlyOnceWith("steer");
111
+ state.setBlocked(true);
112
+ state.setBlocked(false);
113
+ expect(state.onSubmit).toHaveBeenCalledOnce();
114
+});
apps/mobile/src/features/threads/useSubmitAfterNativeImages.ts
new
+60
@@ -0,0 +1,60 @@
1
+import { useEffect, useEffectEvent, useRef, useState } from "react";
2
+import type { ActiveTurnComposerAction } from "@t3tools/client-runtime/state/composer-dispatch";
3
+
4
+export function useSubmitAfterNativeImages(props: {
5
+ readonly draftKey: string;
6
+ readonly readResetGeneration: () => number;
7
+ readonly blocked: boolean;
8
+ readonly onPasteImages: (uris: ReadonlyArray<string>) => Promise<boolean>;
9
+ readonly onSubmit: (followUp?: ActiveTurnComposerAction) => void;
10
+}) {
11
+ type HeldSend = {
12
+ readonly draftKey: string;
13
+ readonly generation: number;
14
+ readonly followUp?: ActiveTurnComposerAction;
15
+ };
16
+ const pendingCount = useRef(0);
17
+ const failed = useRef(false);
18
+ const heldSend = useRef<HeldSend | null>(null);
19
+ const [releasedSend, setReleasedSend] = useState<HeldSend | null>(null);
20
+ const consumedSend = useRef<HeldSend | null>(null);
21
+ const sendReleased = useEffectEvent((held: HeldSend) => {
22
+ if (held.draftKey === props.draftKey && held.generation === props.readResetGeneration()) {
23
+ props.onSubmit(held.followUp);
24
+ }
25
+ });
26
+ // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- submits from the render where the native images joined the draft
27
+ useEffect(() => {
28
+ if (!releasedSend || props.blocked || consumedSend.current === releasedSend) return;
29
+ consumedSend.current = releasedSend;
30
+ sendReleased(releasedSend);
31
+ }, [releasedSend, props.blocked]);
32
+ return {
33
+ deferSend: (followUp?: ActiveTurnComposerAction) => {
34
+ if (pendingCount.current === 0) return false;
35
+ heldSend.current = {
36
+ draftKey: props.draftKey,
37
+ generation: props.readResetGeneration(),
38
+ followUp,
39
+ };
40
+ return true;
41
+ },
42
+ pasteImages: (uris: ReadonlyArray<string>) => {
43
+ if (pendingCount.current === 0) failed.current = false;
44
+ pendingCount.current += 1;
45
+ const finish = (success: boolean) => {
46
+ if (!success) failed.current = true;
47
+ pendingCount.current -= 1;
48
+ if (pendingCount.current === 0) {
49
+ const held = heldSend.current;
50
+ heldSend.current = null;
51
+ if (held && !failed.current) setReleasedSend(held);
52
+ }
53
+ };
54
+ return props.onPasteImages(uris).then(finish, (error: unknown) => {
55
+ finish(false);
56
+ throw error;
57
+ });
58
+ },
59
+ };
60
+}
apps/mobile/src/state/use-composer-attachment-actions.ts
+11
-9
@@ -48,9 +48,9 @@ export function useComposerAttachmentActions(props: {
48
return appendComposerDraftAttachments(key, attachments, { appendReference: true, insertion });
49
};
50
// A picker may finish after its draft was discarded or the composer moved off it.
51
- const withDraftOperation = async (key: string, work: (signal: AbortSignal) => Promise<void>) => {
51
+ const withDraftOperation = async <T>(key: string, work: (signal: AbortSignal) => Promise<T>) => {
52
const operation = startComposerDraftOperation(key);
53
- await work(operation.signal).finally(operation.finish);
53
+ return work(operation.signal).finally(operation.finish);
54
};
55
const report = (title: string, error: string | null | undefined, rejected: number) => {
56
const problems = [
@@ -109,21 +109,23 @@ export function useComposerAttachmentActions(props: {
109
};
110
const onNativePasteImages = async (uris: ReadonlyArray<string>) => {
111
const key = props.draftKey;
112
- if (!key || props.locked || !uris.length) return;
112
+ if (!key || props.locked || !uris.length) return false;
113
const insertion = captureComposerDraftInsertion(key);
114
- await withDraftOperation(key, async (signal) => {
114
+ return withDraftOperation(key, async (signal) => {
115
try {
116
const result = await convertPastedImagesToAttachments({ uris });
117
- report(
118
- m(msg("Could not paste images")),
119
- result.error,
120
- await append(key, signal, result.attachments, insertion),
121
- );
117
+ const rejected = await append(key, signal, result.attachments, insertion);
118
+ report(m(msg("Could not paste images")), result.error, rejected);
119
+ if (signal.aborted) return false;
120
+ if (result.error) return false;
121
+ if (rejected > 0) return false;
122
+ return result.attachments.length > 0;
123
} catch (error) {
124
Dialog.alert(
125
m(msg("Could not paste images")),
126
errorDisplayMessage(error, m) ?? m(msg("Try again.")),
127
);
128
+ return false;
129
}
130
});
131
};
apps/mobile/vite.config.ts
+1
@@ -4,6 +4,7 @@ import { defineConfig, normalizePath } from "vite-plus";
4
import "vite-plus/test/config";
5
6
const reactTests = [
7
+ "src/features/threads/useSubmitAfterNativeImages.test.tsx",
8
"src/features/threads/git/GitBranchesSheet.test.tsx",
9
"src/features/threads/new-task-flow-provider.test.tsx",
10
"src/features/layout/workspace/workspace-tabs-state.test.ts",
apps/web/src/components/chat/ChatComposer.tsx
+10
-9
@@ -287,6 +287,7 @@ import { useComposerAttachmentIntake } from "./useComposerAttachmentIntake";
287
import {
288
countPreparingComposerImages,
289
usePreparingComposerImages,
290
+ useSubmitAfterPreparingImages,
291
} from "./preparingComposerImages";
292
import { ComposerControlsBar } from "./ComposerControlsBar";
293
import { composerCommandKeyHandler } from "./composerCommandKey";
@@ -1918,6 +1919,10 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
1919
attachmentBlockReason,
1920
environmentUnavailable: environmentUnavailable !== null,
1921
});
1922
+ const submitAfterPreparingImages = useSubmitAfterPreparingImages(
1923
+ attachmentTargetKey,
1924
+ submissionBlocked,
1925
+ );
1926
// The pending Submit button follows the answer's own blockers, matching submitComposer.
1927
const primaryActionSendDisabledReason =
1928
(activePendingProgress ? attachmentBlockReason : sendDisabledReason) ??
@@ -2196,16 +2201,12 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
2201
event?.preventDefault();
2202
return false;
2203
}
2199
- // A send while a pasted image is still compressing would strand that image:
2200
- // the turn snapshot wouldn't include it, and it would surface in the *next*
2201
- // draft instead.
2202
- if (activeThreadId && countPreparingComposerImages(attachmentTargetKey) > 0) {
2204
+ // Sending now would leave a still-compressing image out of the turn, so wait for it.
2205
+ if (
2206
+ activeThreadId &&
2207
+ submitAfterPreparingImages(() => submitComposerRef.current(dispatchMode, submissionIntent))
2208
+ ) {
2209
event?.preventDefault();
2204
- toastManager.add({
2205
- type: "info",
2206
- title: gt("Still compressing a pasted image."),
2207
- description: gt("Send again once its thumbnail appears."),
2208
- });
2210
return false;
2211
}
2212
if (pendingDraftWork.has(attachmentTargetKey)) {
apps/web/src/components/chat/preparingComposerImages.browser.test.tsx
new
+175
@@ -0,0 +1,175 @@
1
+import { useEffect } from "react";
2
+import { expect, it, vi } from "vite-plus/test";
3
+import { createStore, type StoreApi, useStore } from "zustand";
4
+
5
+import { act, render } from "../../../test/render";
6
+import {
7
+ addPreparingComposerImages,
8
+ cancelPreparingComposerImages,
9
+ removePreparingComposerImages,
10
+ useSubmitAfterPreparingImages,
11
+} from "./preparingComposerImages";
12
+
13
+type QueueSubmit = ReturnType<typeof useSubmitAfterPreparingImages>;
14
+
15
+type DraftImagesStore = StoreApi<{ readonly ids: ReadonlyArray<string> }>;
16
+
17
+function createDraftImagesStore(): DraftImagesStore {
18
+ return createStore(() => ({ ids: [] }));
19
+}
20
+
21
+// Mirrors ChatComposer: the send reads draft images that a later effect syncs from the store.
22
+function Probe(props: {
23
+ targetKey: string;
24
+ draftImagesStore: DraftImagesStore;
25
+ onReady: (queue: QueueSubmit) => void;
26
+ onCommit?: (images: ReadonlyArray<string>) => void;
27
+ blocked?: boolean;
28
+}) {
29
+ const queue = useSubmitAfterPreparingImages(props.targetKey, props.blocked);
30
+ const draftImages = useStore(props.draftImagesStore, (state) => state.ids);
31
+ const { onCommit } = props;
32
+ useEffect(() => {
33
+ onCommit?.(draftImages);
34
+ }, [onCommit, draftImages]);
35
+ props.onReady(queue);
36
+ return null;
37
+}
38
+
39
+function preparingImage(id: string) {
40
+ return { id, name: `${id}.png`, file: new File(["png"], `${id}.png`), hidden: false };
41
+}
42
+
43
+it("sends after pasted images finish compressing, with the compressed image in the draft", async () => {
44
+ const target = "submit-after-preparing";
45
+ using _store = { [Symbol.dispose]: () => cancelPreparingComposerImages(target) };
46
+ const draftImagesStore = createDraftImagesStore();
47
+ let queueSubmit: QueueSubmit | undefined;
48
+ let committedImages: ReadonlyArray<string> = [];
49
+ const onCommit = (images: ReadonlyArray<string>) => {
50
+ committedImages = images;
51
+ };
52
+ const onReady = (queue: QueueSubmit) => {
53
+ queueSubmit = queue;
54
+ };
55
+ await using screen = await render(
56
+ <Probe
57
+ targetKey={target}
58
+ draftImagesStore={draftImagesStore}
59
+ onCommit={onCommit}
60
+ onReady={onReady}
61
+ />,
62
+ // A bare hook probe; nothing here navigates.
63
+ { router: false },
64
+ );
65
+ const submit = vi.fn(() => committedImages);
66
+
67
+ expect(queueSubmit?.(submit)).toBe(false);
68
+
69
+ addPreparingComposerImages(target, [preparingImage("first"), preparingImage("second")]);
70
+ expect(queueSubmit?.(submit)).toBe(true);
71
+
72
+ await act(() => removePreparingComposerImages(target, new Set(["first"])));
73
+ expect(submit).not.toHaveBeenCalled();
74
+
75
+ // Intake drops the placeholder and adds the compressed image in the same tick.
76
+ await act(() => {
77
+ removePreparingComposerImages(target, new Set(["second"]));
78
+ draftImagesStore.setState({ ids: ["second"] });
79
+ });
80
+ expect(submit).toHaveBeenCalledOnce();
81
+ expect(submit.mock.results[0]?.value).toEqual(["second"]);
82
+
83
+ submit.mockClear();
84
+ await act(() => addPreparingComposerImages(target, [preparingImage("uploading")]));
85
+ expect(queueSubmit?.(submit)).toBe(true);
86
+ await screen.rerender(
87
+ <Probe
88
+ targetKey={target}
89
+ draftImagesStore={draftImagesStore}
90
+ onCommit={onCommit}
91
+ onReady={onReady}
92
+ blocked
93
+ />,
94
+ );
95
+ await act(() => removePreparingComposerImages(target, new Set(["uploading"])));
96
+ expect(submit).not.toHaveBeenCalled();
97
+ await screen.rerender(
98
+ <Probe
99
+ targetKey={target}
100
+ draftImagesStore={draftImagesStore}
101
+ onCommit={onCommit}
102
+ onReady={onReady}
103
+ />,
104
+ );
105
+ expect(submit).toHaveBeenCalledOnce();
106
+ expect(submit.mock.results[0]?.value).toEqual(["second"]);
107
+});
108
+
109
+it("drops a waiting send when the composer moves to another draft or discards it", async () => {
110
+ const target = "submit-after-preparing-old";
111
+ const otherTarget = "submit-after-preparing-new";
112
+ using _store = {
113
+ [Symbol.dispose]: () => {
114
+ cancelPreparingComposerImages(target);
115
+ cancelPreparingComposerImages(otherTarget);
116
+ },
117
+ };
118
+ const draftImagesStore = createDraftImagesStore();
119
+ let queueSubmit: QueueSubmit | undefined;
120
+ const onReady = (queue: QueueSubmit) => {
121
+ queueSubmit = queue;
122
+ };
123
+ await using screen = await render(
124
+ <Probe targetKey={target} draftImagesStore={draftImagesStore} onReady={onReady} />,
125
+ {
126
+ // A bare hook probe; nothing here navigates.
127
+ router: false,
128
+ },
129
+ );
130
+ const submit = vi.fn();
131
+ addPreparingComposerImages(target, [preparingImage("pasted")]);
132
+ expect(queueSubmit?.(submit)).toBe(true);
133
+
134
+ // The other draft is still compressing too, so the switch alone must drop the send.
135
+ addPreparingComposerImages(otherTarget, [preparingImage("other")]);
136
+ await screen.rerender(
137
+ <Probe targetKey={otherTarget} draftImagesStore={draftImagesStore} onReady={onReady} />,
138
+ );
139
+ await act(() => removePreparingComposerImages(target, new Set(["pasted"])));
140
+ await screen.rerender(
141
+ <Probe targetKey={target} draftImagesStore={draftImagesStore} onReady={onReady} />,
142
+ );
143
+ expect(submit).not.toHaveBeenCalled();
144
+
145
+ // Discarding the draft cancels its compression, which must not release the held send.
146
+ await act(() => addPreparingComposerImages(target, [preparingImage("discarded")]));
147
+ expect(queueSubmit?.(submit)).toBe(true);
148
+ await act(() => cancelPreparingComposerImages(target));
149
+ expect(submit).not.toHaveBeenCalled();
150
+});
151
+
152
+it("keeps the draft unsent when image preparation fails", async () => {
153
+ const target = "submit-after-failed-preparation";
154
+ using _store = { [Symbol.dispose]: () => cancelPreparingComposerImages(target) };
155
+ const draftImagesStore = createDraftImagesStore();
156
+ let queueSubmit: QueueSubmit | undefined;
157
+ await using _screen = await render(
158
+ <Probe
159
+ targetKey={target}
160
+ draftImagesStore={draftImagesStore}
161
+ onReady={(queue) => {
162
+ queueSubmit = queue;
163
+ }}
164
+ />,
165
+ // A bare hook probe; nothing here navigates.
166
+ { router: false },
167
+ );
168
+ const submit = vi.fn();
169
+ await act(() => addPreparingComposerImages(target, [preparingImage("failed")]));
170
+ expect(queueSubmit?.(submit)).toBe(true);
171
+ await act(() =>
172
+ removePreparingComposerImages(target, new Set(["failed"]), { cancelSubmission: true }),
173
+ );
174
+ expect(submit).not.toHaveBeenCalled();
175
+});
apps/web/src/components/chat/preparingComposerImages.ts
+51
@@ -1,5 +1,8 @@
1
+import { useEffect, useRef } from "react";
2
import { create } from "zustand";
3
4
+import { useStableCallback } from "../../hooks/useStableCallback";
5
+
6
export interface PreparingComposerImage {
7
readonly id: string;
8
readonly name: string;
@@ -60,6 +63,7 @@ export function isPreparingComposerImage(targetKey: string, imageId: string): bo
63
export function removePreparingComposerImages(
64
targetKey: string,
65
imageIds: ReadonlySet<string>,
66
+ options?: { readonly cancelSubmission?: boolean },
67
): ReadonlySet<string> {
68
const current =
69
usePreparingComposerImageStore.getState().byTargetKey[targetKey] ?? NO_PREPARING_IMAGES;
@@ -67,6 +71,7 @@ export function removePreparingComposerImages(
71
current.filter((image) => imageIds.has(image.id)).map((image) => image.id),
72
);
73
if (removed.size === 0) return removed;
74
+ if (options?.cancelSubmission) invalidatePendingSubmit(targetKey);
75
usePreparingComposerImageStore.setState((state) => {
76
const remaining = (state.byTargetKey[targetKey] ?? NO_PREPARING_IMAGES).filter(
77
(image) => !removed.has(image.id),
@@ -82,8 +87,16 @@ export function removePreparingComposerImages(
87
return removed;
88
}
89
90
+// Bumped on cancel so a send held for the cancelled images is dropped rather than released.
91
+const cancelGenerations = new Map<string, number>();
92
+
93
+function invalidatePendingSubmit(targetKey: string) {
94
+ cancelGenerations.set(targetKey, (cancelGenerations.get(targetKey) ?? 0) + 1);
95
+}
96
+
97
/** Drops every image still preparing for the target, so its compression result is discarded. */
98
export function cancelPreparingComposerImages(targetKey: string): void {
99
+ invalidatePendingSubmit(targetKey);
100
if (!usePreparingComposerImageStore.getState().byTargetKey[targetKey]) return;
101
usePreparingComposerImageStore.setState((state) => {
102
const byTargetKey = { ...state.byTargetKey };
@@ -91,3 +104,41 @@ export function cancelPreparingComposerImages(targetKey: string): void {
104
return { byTargetKey };
105
});
106
}
107
+
108
+/**
109
+ * Holds a send made while the target still has images compressing, and runs it once they finish,
110
+ * so the turn includes them. Returns false when nothing is compressing and the caller should send.
111
+ */
112
+export function useSubmitAfterPreparingImages(targetKey: string, blocked = false) {
113
+ const preparing = usePreparingComposerImages(targetKey);
114
+ const pendingRef = useRef<{
115
+ readonly targetKey: string;
116
+ readonly cancelGeneration: number;
117
+ readonly submit: () => void;
118
+ } | null>(null);
119
+ // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- sends only after the render where the compressed images joined the draft
120
+ useEffect(() => {
121
+ const pending = pendingRef.current;
122
+ if (!pending) return;
123
+ if (
124
+ pending.targetKey !== targetKey ||
125
+ pending.cancelGeneration !== (cancelGenerations.get(targetKey) ?? 0)
126
+ ) {
127
+ pendingRef.current = null;
128
+ return;
129
+ }
130
+ if (preparing.length > 0 || blocked) return;
131
+ pendingRef.current = null;
132
+ // After the composer's later effects have synced its draft refs to this render.
133
+ queueMicrotask(pending.submit);
134
+ }, [preparing, targetKey, blocked]);
135
+ return useStableCallback((submit: () => void) => {
136
+ if (countPreparingComposerImages(targetKey) === 0) return false;
137
+ pendingRef.current = {
138
+ targetKey,
139
+ cancelGeneration: cancelGenerations.get(targetKey) ?? 0,
140
+ submit,
141
+ };
142
+ return true;
143
+ });
144
+}
apps/web/src/components/chat/useComposerAttachmentIntake.ts
+6
-1
@@ -322,6 +322,7 @@ export function useComposerAttachmentIntake(input: {
322
const stillPreparingIds = removePreparingComposerImages(
323
attachmentTargetKey,
324
new Set(preparingImages.map((image) => image.id)),
325
+ { cancelSubmission: compressionErrors.size > 0 || questionDiscarded },
326
);
327
if (questionAttachmentTarget)
328
changeQuestionAttachmentPreparation(questionAttachmentTarget, -stillPreparingIds.size);
@@ -372,7 +373,11 @@ export function useComposerAttachmentIntake(input: {
373
};
374
375
const removeComposerImage = (imageId: string) => {
375
- if (removePreparingComposerImages(attachmentTargetKey, new Set([imageId])).size > 0) {
376
+ if (
377
+ removePreparingComposerImages(attachmentTargetKey, new Set([imageId]), {
378
+ cancelSubmission: true,
379
+ }).size > 0
380
+ ) {
381
// Its compression finishes in the background and is dropped.
382
if (questionAttachmentTarget)
383
changeQuestionAttachmentPreparation(questionAttachmentTarget, -1);
apps/web/src/i18n/translations/de.json
+1
-2
@@ -3156,8 +3156,6 @@
3156
"164d3295a763dbad": "Der Snapshot ist nicht mehr verfügbar.",
3157
"f77ce9bc81a68882": "Der Snapshot ist noch nicht bereit zum Kopieren.",
3158
"68a4461e56df0896": "Spracheingabe wird vorbereitet",
3159
- "cfc4f3582964bf84": "Ein eingefügtes Bild wird noch komprimiert.",
3160
- "aedaf7f4faba8bd3": "Sende erneut, sobald die Miniatur erscheint.",
3159
"4bc6e68c58cbb173": "Angehängter Kontext wird noch in diese Nachricht übernommen.",
3160
"62bf4adef45b9830": "Sende erneut, sobald der Chip aufgelöst ist.",
3161
"d0e9c30191edf07e": "Antwort auf {titles}",
@@ -4642,6 +4640,7 @@
4640
"98c76143d9aae871": "Ablage-Eintrag kommt möglicherweise zurück",
4641
"a7101927759103ad": "Der Browserspeicher hat das Löschen abgelehnt, daher könnte dieser Prompt nach dem Neuladen wieder erscheinen.",
4642
"fb34cb404c4930dc": "Lege erneut ab, sobald der Chip aufgelöst ist.",
4643
+ "cfc4f3582964bf84": "Ein eingefügtes Bild wird noch komprimiert.",
4644
"70b12bc1e1a26abb": "Lege erneut ab, sobald die Komprimierung abgeschlossen ist.",
4645
"f6b1ef37f7587664": "Hänge abgelegte Dateien erneut an oder entferne sie, bevor du ablegst",
4646
"120167bbfb6d5939": "Warte auf die Datei-Uploads, bevor du diesen Prompt ablegst",
apps/web/src/i18n/translations/en.json
+1
-2
@@ -3155,8 +3155,6 @@
3155
"164d3295a763dbad": "Snapshot is no longer available.",
3156
"f77ce9bc81a68882": "The snapshot is not ready to copy.",
3157
"68a4461e56df0896": "Preparing voice input",
3158
- "cfc4f3582964bf84": "Still compressing a pasted image.",
3159
- "aedaf7f4faba8bd3": "Send again once its thumbnail appears.",
3158
"4bc6e68c58cbb173": "Still bringing attached context into this message.",
3159
"62bf4adef45b9830": "Send again once its chip resolves.",
3160
"d0e9c30191edf07e": "Replying to {titles}",
@@ -4641,6 +4639,7 @@
4639
"98c76143d9aae871": "Stash entry may come back",
4640
"a7101927759103ad": "Browser storage rejected the delete, so this prompt could reappear after a reload.",
4641
"fb34cb404c4930dc": "Stash again once its chip resolves.",
4642
+ "cfc4f3582964bf84": "Still compressing a pasted image.",
4643
"70b12bc1e1a26abb": "Stash again once it finishes compressing.",
4644
"f6b1ef37f7587664": "Attach dropped files again or remove them before stashing",
4645
"120167bbfb6d5939": "Wait for file uploads before stashing this prompt",
apps/web/src/i18n/translations/es.json
+1
-2
@@ -3155,8 +3155,6 @@
3155
"164d3295a763dbad": "La instantánea ya no está disponible.",
3156
"f77ce9bc81a68882": "La instantánea no está lista para copiarla.",
3157
"68a4461e56df0896": "Preparando la entrada de voz",
3158
- "cfc4f3582964bf84": "Aún se está comprimiendo una imagen pegada.",
3159
- "aedaf7f4faba8bd3": "Vuelve a enviar cuando aparezca su miniatura.",
3158
"4bc6e68c58cbb173": "Aún se está incorporando el contexto adjunto a este mensaje.",
3159
"62bf4adef45b9830": "Vuelve a enviar cuando se resuelva su chip.",
3160
"d0e9c30191edf07e": "Respondiendo a {titles}",
@@ -4639,6 +4637,7 @@
4637
"98c76143d9aae871": "Puede que la entrada del stash vuelva",
4638
"a7101927759103ad": "El almacenamiento del navegador rechazó la eliminación, así que este prompt podría volver a aparecer tras recargar.",
4639
"fb34cb404c4930dc": "Vuelve a guardarlo en el stash cuando se resuelva su chip.",
4640
+ "cfc4f3582964bf84": "Aún se está comprimiendo una imagen pegada.",
4641
"70b12bc1e1a26abb": "Vuelve a guardarlo en el stash cuando termine de comprimirse.",
4642
"f6b1ef37f7587664": "Vuelve a adjuntar los archivos soltados o quítalos antes de guardarlo en el stash",
4643
"120167bbfb6d5939": "Espera a que se suban los archivos antes de guardar este prompt en el stash",
apps/web/src/i18n/translations/fr.json
+1
-2
@@ -3155,8 +3155,6 @@
3155
"164d3295a763dbad": "L’instantané n’est plus disponible.",
3156
"f77ce9bc81a68882": "L’instantané n’est pas prêt à être copié.",
3157
"68a4461e56df0896": "Préparation de la saisie vocale",
3158
- "cfc4f3582964bf84": "Compression d’une image collée en cours.",
3159
- "aedaf7f4faba8bd3": "Renvoyez quand sa miniature apparaît.",
3158
"4bc6e68c58cbb173": "Ajout du contexte joint à ce message en cours.",
3159
"62bf4adef45b9830": "Renvoyez quand sa puce est résolue.",
3160
"d0e9c30191edf07e": "Réponse à {titles}",
@@ -4640,6 +4638,7 @@
4638
"98c76143d9aae871": "L’entrée de la réserve peut revenir",
4639
"a7101927759103ad": "Le stockage du navigateur a refusé la suppression ; ce prompt pourrait donc réapparaître après un rechargement.",
4640
"fb34cb404c4930dc": "Mettez de côté à nouveau quand sa puce est résolue.",
4641
+ "cfc4f3582964bf84": "Compression d’une image collée en cours.",
4642
"70b12bc1e1a26abb": "Mettez de côté à nouveau une fois la compression terminée.",
4643
"f6b1ef37f7587664": "Joignez à nouveau les fichiers retirés ou supprimez-les avant de mettre de côté",
4644
"120167bbfb6d5939": "Attendez la fin de l’envoi des fichiers avant de mettre ce prompt de côté",
apps/web/src/i18n/translations/ja.json
+1
-2
@@ -3153,8 +3153,6 @@
3153
"164d3295a763dbad": "スナップショットは利用できなくなりました。",
3154
"f77ce9bc81a68882": "スナップショットはまだコピーできる状態ではありません。",
3155
"68a4461e56df0896": "音声入力を準備しています",
3156
- "cfc4f3582964bf84": "貼り付けた画像をまだ圧縮しています。",
3157
- "aedaf7f4faba8bd3": "サムネイルが表示されたら、もう一度送信してください。",
3156
"4bc6e68c58cbb173": "添付したコンテキストをまだこのメッセージに取り込んでいます。",
3157
"62bf4adef45b9830": "チップが確定したら、もう一度送信してください。",
3158
"d0e9c30191edf07e": "{titles} に返信中",
@@ -4629,6 +4627,7 @@
4627
"98c76143d9aae871": "退避した項目が戻る可能性があります",
4628
"a7101927759103ad": "ブラウザーのストレージが削除を拒否したため、再読み込み後にこのプロンプトが再表示される可能性があります。",
4629
"fb34cb404c4930dc": "チップが確定したら、もう一度退避してください。",
4630
+ "cfc4f3582964bf84": "貼り付けた画像をまだ圧縮しています。",
4631
"70b12bc1e1a26abb": "圧縮が終わったら、もう一度退避してください。",
4632
"f6b1ef37f7587664": "退避する前に、ドロップしたファイルをもう一度添付するか削除してください",
4633
"120167bbfb6d5939": "このプロンプトを退避する前に、ファイルのアップロードが終わるまでお待ちください",
apps/web/src/i18n/translations/ko.json
+1
-2
@@ -3154,8 +3154,6 @@
3154
"164d3295a763dbad": "스냅샷을 더 이상 사용할 수 없습니다.",
3155
"f77ce9bc81a68882": "스냅샷을 복사할 준비가 되지 않았습니다.",
3156
"68a4461e56df0896": "음성 입력 준비 중",
3157
- "cfc4f3582964bf84": "붙여 넣은 이미지를 아직 압축하는 중입니다.",
3158
- "aedaf7f4faba8bd3": "썸네일이 표시되면 다시 보내세요.",
3157
"4bc6e68c58cbb173": "첨부한 컨텍스트를 아직 이 메시지로 가져오는 중입니다.",
3158
"62bf4adef45b9830": "칩이 확인되면 다시 보내세요.",
3159
"d0e9c30191edf07e": "{titles}에 답장하는 중",
@@ -4626,6 +4624,7 @@
4624
"98c76143d9aae871": "임시 저장함 항목이 다시 나타날 수 있습니다",
4625
"a7101927759103ad": "브라우저 저장소가 삭제를 거부해서 새로 고친 후 이 프롬프트가 다시 나타날 수 있습니다.",
4626
"fb34cb404c4930dc": "칩이 확인되면 다시 임시 저장하세요.",
4627
+ "cfc4f3582964bf84": "붙여 넣은 이미지를 아직 압축하는 중입니다.",
4628
"70b12bc1e1a26abb": "압축이 끝나면 다시 임시 저장하세요.",
4629
"f6b1ef37f7587664": "임시 저장하기 전에 끌어다 놓은 파일을 다시 첨부하거나 제거하세요",
4630
"120167bbfb6d5939": "이 프롬프트를 임시 저장하기 전에 파일 업로드를 기다리세요",
apps/web/src/i18n/translations/pt-BR.json
+1
-2
@@ -3155,8 +3155,6 @@
3155
"164d3295a763dbad": "O snapshot não está mais disponível.",
3156
"f77ce9bc81a68882": "O snapshot não está pronto para copiar.",
3157
"68a4461e56df0896": "Preparando a entrada de voz",
3158
- "cfc4f3582964bf84": "Ainda comprimindo uma imagem colada.",
3159
- "aedaf7f4faba8bd3": "Envie novamente quando a miniatura aparecer.",
3158
"4bc6e68c58cbb173": "Ainda trazendo o contexto anexado para esta mensagem.",
3159
"62bf4adef45b9830": "Envie novamente quando o chip carregar.",
3160
"d0e9c30191edf07e": "Respondendo a {titles}",
@@ -4639,6 +4637,7 @@
4637
"98c76143d9aae871": "O item guardado pode voltar",
4638
"a7101927759103ad": "O armazenamento do navegador rejeitou a exclusão, então este prompt pode reaparecer após recarregar.",
4639
"fb34cb404c4930dc": "Guarde novamente quando o chip carregar.",
4640
+ "cfc4f3582964bf84": "Ainda comprimindo uma imagem colada.",
4641
"70b12bc1e1a26abb": "Guarde novamente quando a compressão terminar.",
4642
"f6b1ef37f7587664": "Anexe novamente os arquivos soltos ou remova-os antes de guardar",
4643
"120167bbfb6d5939": "Aguarde o upload dos arquivos antes de guardar este prompt",
apps/web/src/i18n/translations/ru.json
+1
-2
@@ -3155,8 +3155,6 @@
3155
"164d3295a763dbad": "Снимок больше недоступен.",
3156
"f77ce9bc81a68882": "Снимок ещё не готов к копированию.",
3157
"68a4461e56df0896": "Подготовка голосового ввода",
3158
- "cfc4f3582964bf84": "Вставленное изображение ещё сжимается.",
3159
- "aedaf7f4faba8bd3": "Отправьте снова, когда появится миниатюра.",
3158
"4bc6e68c58cbb173": "Прикреплённый контекст ещё добавляется в сообщение.",
3159
"62bf4adef45b9830": "Отправьте снова, когда чип загрузится.",
3160
"d0e9c30191edf07e": "Ответ на {titles}",
@@ -4639,6 +4637,7 @@
4637
"98c76143d9aae871": "Запись тайника может вернуться",
4638
"a7101927759103ad": "Хранилище браузера отклонило удаление, поэтому промпт может снова появиться после перезагрузки.",
4639
"fb34cb404c4930dc": "Спрячьте снова, когда чип загрузится.",
4640
+ "cfc4f3582964bf84": "Вставленное изображение ещё сжимается.",
4641
"70b12bc1e1a26abb": "Спрячьте снова, когда сжатие завершится.",
4642
"f6b1ef37f7587664": "Прикрепите отброшенные файлы снова или удалите их перед откладыванием",
4643
"120167bbfb6d5939": "Дождитесь загрузки файлов, прежде чем откладывать этот промпт",
apps/web/src/i18n/translations/sv.json
+1
-2
@@ -3155,8 +3155,6 @@
3155
"164d3295a763dbad": "Ögonblicksbilden är inte längre tillgänglig.",
3156
"f77ce9bc81a68882": "Ögonblicksbilden är inte redo att kopieras.",
3157
"68a4461e56df0896": "Förbereder röstinmatning",
3158
- "cfc4f3582964bf84": "Komprimerar fortfarande en inklistrad bild.",
3159
- "aedaf7f4faba8bd3": "Skicka igen när miniatyrbilden visas.",
3158
"4bc6e68c58cbb173": "Hämtar fortfarande bifogad kontext till det här meddelandet.",
3159
"62bf4adef45b9830": "Skicka igen när dess etikett har lästs in.",
3160
"d0e9c30191edf07e": "Svarar på {titles}",
@@ -4640,6 +4638,7 @@
4638
"98c76143d9aae871": "Den undanlagda prompten kan komma tillbaka",
4639
"a7101927759103ad": "Webbläsarens lagring avvisade raderingen, så prompten kan dyka upp igen efter en omladdning.",
4640
"fb34cb404c4930dc": "Lägg undan igen när dess etikett har lästs in.",
4641
+ "cfc4f3582964bf84": "Komprimerar fortfarande en inklistrad bild.",
4642
"70b12bc1e1a26abb": "Lägg undan igen när komprimeringen är klar.",
4643
"f6b1ef37f7587664": "Bifoga släppta filer igen eller ta bort dem innan du lägger undan",
4644
"120167bbfb6d5939": "Vänta på filuppladdningarna innan du lägger undan den här prompten",
apps/web/src/i18n/translations/zh.json
+1
-2
@@ -3159,8 +3159,6 @@
3159
"164d3295a763dbad": "快照已不可用。",
3160
"f77ce9bc81a68882": "快照尚未准备好复制。",
3161
"68a4461e56df0896": "正在准备语音输入",
3162
- "cfc4f3582964bf84": "粘贴的图片仍在压缩。",
3163
- "aedaf7f4faba8bd3": "缩略图出现后请再次发送。",
3162
"4bc6e68c58cbb173": "仍在把附加的上下文放入这条消息。",
3163
"62bf4adef45b9830": "标签加载完成后请再次发送。",
3164
"d0e9c30191edf07e": "回复 {titles}",
@@ -4646,6 +4644,7 @@
4644
"98c76143d9aae871": "暂存条目可能会再次出现",
4645
"a7101927759103ad": "浏览器存储拒绝了删除操作,所以刷新后这条提示词可能再次出现。",
4646
"fb34cb404c4930dc": "标签加载完成后请再次暂存。",
4647
+ "cfc4f3582964bf84": "粘贴的图片仍在压缩。",
4648
"70b12bc1e1a26abb": "请在压缩完成后重新暂存。",
4649
"f6b1ef37f7587664": "暂存前请重新添加丢失的文件,或将其移除",
4650
"120167bbfb6d5939": "请等文件上传完成后再暂存这条提示词",
scripts/scenarios/enter-during-image-compression-sends-after.e2e.ts
new
+35
@@ -0,0 +1,35 @@
1
+import { expect } from "e2e";
2
+
3
+import {
4
+ finishImageCompression,
5
+ holdImageCompression,
6
+ pasteWideScreenshot,
7
+} from "./image-compression-hold.ts";
8
+import { test, WEB } from "./t3.ts";
9
+
10
+test(
11
+ "Enter while a pasted image compresses sends the message with the image once it finishes",
12
+ WEB,
13
+ async ({ t3, app, browser, screen }) => {
14
+ await holdImageCompression(browser);
15
+ const project = await t3.project("demo");
16
+ const thread = await t3.thread({ project, title: "Screenshot work", messages: ["first"] });
17
+ await t3.open(thread);
18
+ await expect(screen.getByText("first fixture turn complete", { exact: false })).toBeVisible();
19
+
20
+ const composer = screen.getByRole("textbox");
21
+ await composer.fill("What is in this screenshot?");
22
+ await pasteWideScreenshot(browser);
23
+ await browser.keyboard.press("Enter");
24
+ await app.screenshot("enter-while-compressing");
25
+
26
+ await finishImageCompression(browser);
27
+ await app.screenshot("after-compression");
28
+ const sentWithImage = browser
29
+ .locator('[data-message-role="user"]:has([aria-label="Preview screenshot.png"])')
30
+ .filter({ hasText: "What is in this screenshot?" });
31
+ await expect(sentWithImage).toBeVisible();
32
+ await expect(composer).not.toContainText("What is in this screenshot?");
33
+ await expect(composer).not.toContainText("screenshot.png");
34
+ },
35
+);