diff --git a/apps/mobile/src/features/threads/ThreadComposer.tsx b/apps/mobile/src/features/threads/ThreadComposer.tsx index 76bb79d608682..5d84787aca9a5 100644 --- a/apps/mobile/src/features/threads/ThreadComposer.tsx +++ b/apps/mobile/src/features/threads/ThreadComposer.tsx @@ -48,6 +48,7 @@ import { composerContextImportsAtom, countComposerDraftAttachmentsAfterSelection, useComposerDraft, + useComposerDraftResetGeneration, } from "../../state/use-composer-drafts"; import type { ComposerDocumentAttachment } from "../../lib/composerContext"; import { useProject, useVisibleThreadShells } from "../../state/entities"; @@ -101,6 +102,7 @@ import { resolveComposerSendPresentation, type ComposerSendPresentation, } from "./composerSendPresentation"; +import { useSubmitAfterNativeImages } from "./useSubmitAfterNativeImages"; import { ComposerCommandPopover } from "./ComposerCommandPopover"; import { ComposerPopoverAnchor } from "./ComposerPopoverAnchor"; import { ComposerQueuedEditAttachments } from "./ComposerQueuedEdit"; @@ -173,7 +175,7 @@ export interface ThreadComposerProps { readonly onChangeDraftMessage: (value: string) => void; readonly onPickDraftMedia: () => Promise; readonly onPickDraftFiles: () => Promise; - readonly onNativePasteImages: (uris: ReadonlyArray) => Promise; + readonly onNativePasteImages: (uris: ReadonlyArray) => Promise; readonly onNativePasteText: (paste: ComposerTextPaste) => Promise; readonly onRemoveDraftImage: (imageId: string) => void; readonly onStopThread: () => void; @@ -293,6 +295,7 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps const [previewVideo, setPreviewVideo] = useState(null); const composerOwnerKey = scopedThreadKey(props.environmentId, props.selectedThread.id); const composerDraftKey = props.draftKey ?? composerOwnerKey; + const readResetGeneration = useComposerDraftResetGeneration(composerDraftKey); const { text: draftMessage, attachments: draftAttachments, @@ -539,13 +542,10 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps onEditorFocusChange?.(false); }; const handleSend = async (followUp?: ActiveTurnComposerAction) => { - if ( - isSubmissionLocked || - sendBlockedReason !== null || - pendingPastedTextAttachmentCountRef.current > 0 || - pendingNativeImagePasteCountRef.current > 0 - ) - return; + if (isSubmissionLocked || sendBlockedReason !== null) return; + // Sending now would leave a still-converting pasted image out of the turn, so wait for it. + if (nativeImageSubmit.deferSend(followUp)) return; + if (pendingPastedTextAttachmentCountRef.current > 0) return; if (usageLimitsOffered && isUsageLimitsCommand(draftMessage) && draftAttachments.length === 0) { if (openUsageLimits()) onChangeDraftMessage(""); return; @@ -582,6 +582,14 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps }); }; + const nativeImageSubmit = useSubmitAfterNativeImages({ + draftKey: composerDraftKey, + readResetGeneration, + blocked: isSubmissionLocked || sendBlockedReason !== null, + onPasteImages: props.onNativePasteImages, + onSubmit: (followUp) => void handleSend(followUp), + }); + const lockedProviderInstanceId = props.canSwitchProvider ? undefined : currentModelSelection.instanceId; @@ -867,7 +875,7 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps onPasteImages={(uris) => { if (isSubmissionLocked) return; pendingNativeImagePasteCountRef.current += 1; - void props.onNativePasteImages(uris).finally(() => { + void nativeImageSubmit.pasteImages(uris).finally(() => { pendingNativeImagePasteCountRef.current -= 1; }); }} diff --git a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx index d8f06b101a54a..4e11f618d0095 100644 --- a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx +++ b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx @@ -287,7 +287,7 @@ export interface ThreadDetailScreenProps { readonly onChangeDraftMessage: (value: string) => void; readonly onPickDraftMedia: () => Promise; readonly onPickDraftFiles: () => Promise; - readonly onNativePasteImages: (uris: ReadonlyArray) => Promise; + readonly onNativePasteImages: (uris: ReadonlyArray) => Promise; readonly onNativePasteText: (paste: ComposerTextPaste) => Promise; readonly onRemoveDraftImage: (imageId: string) => void; readonly onStopThread: () => void; diff --git a/apps/mobile/src/features/threads/useSubmitAfterNativeImages.test.tsx b/apps/mobile/src/features/threads/useSubmitAfterNativeImages.test.tsx new file mode 100644 index 0000000000000..8451a7c49319d --- /dev/null +++ b/apps/mobile/src/features/threads/useSubmitAfterNativeImages.test.tsx @@ -0,0 +1,114 @@ +import { act, useLayoutEffect } from "react"; +import { createRoot } from "react-dom/client"; +import { expect, it, vi } from "vite-plus/test"; +import { useSubmitAfterNativeImages } from "./useSubmitAfterNativeImages"; + +function setup() { + const root = createRoot(document.createElement("div")); + let queue: ReturnType; + let generation = 0; + let blocked = false; + const onSubmit = vi.fn(); + const preparations: Array<(success: boolean) => void> = []; + const onPasteImages = () => new Promise((resolve) => preparations.push(resolve)); + function Probe() { + const current = useSubmitAfterNativeImages({ + draftKey: "draft", + readResetGeneration: () => generation, + blocked, + onPasteImages, + onSubmit: (action) => { + if (!blocked) onSubmit(action); + }, + }); + useLayoutEffect(() => { + queue = current; + }); + return null; + } + const render = () => act(() => root.render()); + render(); + return { + get queue() { + return queue!; + }, + onSubmit, + setBlocked(value: boolean) { + blocked = value; + render(); + }, + reset() { + generation += 1; + render(); + }, + async finish(success: boolean) { + await act(async () => { + preparations.shift()!(success); + }); + }, + [Symbol.dispose]() { + act(() => root.unmount()); + }, + }; +} + +it("does not send when conversion finishes without adding an image", async () => { + using state = setup(); + const paste = state.queue.pasteImages(["image"]); + expect(state.queue.deferSend()).toBe(true); + await state.finish(false); + await paste; + expect(state.onSubmit).not.toHaveBeenCalled(); + + const first = state.queue.pasteImages(["failed"]); + const second = state.queue.pasteImages(["successful"]); + state.queue.deferSend(); + await state.finish(false); + await state.finish(true); + await Promise.all([first, second]); + expect(state.onSubmit).not.toHaveBeenCalled(); + + const retry = state.queue.pasteImages(["retry"]); + state.queue.deferSend(); + await state.finish(true); + await retry; + expect(state.onSubmit).toHaveBeenCalledOnce(); +}); + +it("does not send a replacement draft after the original draft was discarded", async () => { + using state = setup(); + const paste = state.queue.pasteImages(["image"]); + state.queue.deferSend(); + state.reset(); + await state.finish(true); + await paste; + expect(state.onSubmit).not.toHaveBeenCalled(); + + const next = state.queue.pasteImages(["next"]); + state.queue.deferSend(); + state.setBlocked(true); + await state.finish(true); + await next; + state.reset(); + state.setBlocked(false); + expect(state.onSubmit).not.toHaveBeenCalled(); +}); + +it("waits for other attachment preparation and sends once after all images join the draft", async () => { + using state = setup(); + const first = state.queue.pasteImages(["first"]); + const second = state.queue.pasteImages(["second"]); + state.queue.deferSend("queue"); + state.queue.deferSend("steer"); + await state.finish(true); + expect(state.onSubmit).not.toHaveBeenCalled(); + state.setBlocked(true); + await state.finish(true); + await Promise.all([first, second]); + expect(state.onSubmit).not.toHaveBeenCalled(); + state.setBlocked(false); + expect(state.onSubmit).toHaveBeenCalledExactlyOnceWith("steer"); + state.setBlocked(true); + state.setBlocked(false); + expect(state.onSubmit).toHaveBeenCalledOnce(); +}); diff --git a/apps/mobile/src/features/threads/useSubmitAfterNativeImages.ts b/apps/mobile/src/features/threads/useSubmitAfterNativeImages.ts new file mode 100644 index 0000000000000..8b8209562719f --- /dev/null +++ b/apps/mobile/src/features/threads/useSubmitAfterNativeImages.ts @@ -0,0 +1,60 @@ +import { useEffect, useEffectEvent, useRef, useState } from "react"; +import type { ActiveTurnComposerAction } from "@t3tools/client-runtime/state/composer-dispatch"; + +export function useSubmitAfterNativeImages(props: { + readonly draftKey: string; + readonly readResetGeneration: () => number; + readonly blocked: boolean; + readonly onPasteImages: (uris: ReadonlyArray) => Promise; + readonly onSubmit: (followUp?: ActiveTurnComposerAction) => void; +}) { + type HeldSend = { + readonly draftKey: string; + readonly generation: number; + readonly followUp?: ActiveTurnComposerAction; + }; + const pendingCount = useRef(0); + const failed = useRef(false); + const heldSend = useRef(null); + const [releasedSend, setReleasedSend] = useState(null); + const consumedSend = useRef(null); + const sendReleased = useEffectEvent((held: HeldSend) => { + if (held.draftKey === props.draftKey && held.generation === props.readResetGeneration()) { + props.onSubmit(held.followUp); + } + }); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- submits from the render where the native images joined the draft + useEffect(() => { + if (!releasedSend || props.blocked || consumedSend.current === releasedSend) return; + consumedSend.current = releasedSend; + sendReleased(releasedSend); + }, [releasedSend, props.blocked]); + return { + deferSend: (followUp?: ActiveTurnComposerAction) => { + if (pendingCount.current === 0) return false; + heldSend.current = { + draftKey: props.draftKey, + generation: props.readResetGeneration(), + followUp, + }; + return true; + }, + pasteImages: (uris: ReadonlyArray) => { + if (pendingCount.current === 0) failed.current = false; + pendingCount.current += 1; + const finish = (success: boolean) => { + if (!success) failed.current = true; + pendingCount.current -= 1; + if (pendingCount.current === 0) { + const held = heldSend.current; + heldSend.current = null; + if (held && !failed.current) setReleasedSend(held); + } + }; + return props.onPasteImages(uris).then(finish, (error: unknown) => { + finish(false); + throw error; + }); + }, + }; +} diff --git a/apps/mobile/src/state/use-composer-attachment-actions.ts b/apps/mobile/src/state/use-composer-attachment-actions.ts index 147a6668fd44a..3e9c3439d4164 100644 --- a/apps/mobile/src/state/use-composer-attachment-actions.ts +++ b/apps/mobile/src/state/use-composer-attachment-actions.ts @@ -48,9 +48,9 @@ export function useComposerAttachmentActions(props: { return appendComposerDraftAttachments(key, attachments, { appendReference: true, insertion }); }; // A picker may finish after its draft was discarded or the composer moved off it. - const withDraftOperation = async (key: string, work: (signal: AbortSignal) => Promise) => { + const withDraftOperation = async (key: string, work: (signal: AbortSignal) => Promise) => { const operation = startComposerDraftOperation(key); - await work(operation.signal).finally(operation.finish); + return work(operation.signal).finally(operation.finish); }; const report = (title: string, error: string | null | undefined, rejected: number) => { const problems = [ @@ -109,21 +109,23 @@ export function useComposerAttachmentActions(props: { }; const onNativePasteImages = async (uris: ReadonlyArray) => { const key = props.draftKey; - if (!key || props.locked || !uris.length) return; + if (!key || props.locked || !uris.length) return false; const insertion = captureComposerDraftInsertion(key); - await withDraftOperation(key, async (signal) => { + return withDraftOperation(key, async (signal) => { try { const result = await convertPastedImagesToAttachments({ uris }); - report( - m(msg("Could not paste images")), - result.error, - await append(key, signal, result.attachments, insertion), - ); + const rejected = await append(key, signal, result.attachments, insertion); + report(m(msg("Could not paste images")), result.error, rejected); + if (signal.aborted) return false; + if (result.error) return false; + if (rejected > 0) return false; + return result.attachments.length > 0; } catch (error) { Dialog.alert( m(msg("Could not paste images")), errorDisplayMessage(error, m) ?? m(msg("Try again.")), ); + return false; } }); }; diff --git a/apps/mobile/vite.config.ts b/apps/mobile/vite.config.ts index c25e9aad604b8..01c7dcbd3386a 100644 --- a/apps/mobile/vite.config.ts +++ b/apps/mobile/vite.config.ts @@ -4,6 +4,7 @@ import { defineConfig, normalizePath } from "vite-plus"; import "vite-plus/test/config"; const reactTests = [ + "src/features/threads/useSubmitAfterNativeImages.test.tsx", "src/features/threads/git/GitBranchesSheet.test.tsx", "src/features/threads/new-task-flow-provider.test.tsx", "src/features/layout/workspace/workspace-tabs-state.test.ts", diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index 3c2919c7606d2..634fe4a6975af 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -287,6 +287,7 @@ import { useComposerAttachmentIntake } from "./useComposerAttachmentIntake"; import { countPreparingComposerImages, usePreparingComposerImages, + useSubmitAfterPreparingImages, } from "./preparingComposerImages"; import { ComposerControlsBar } from "./ComposerControlsBar"; import { composerCommandKeyHandler } from "./composerCommandKey"; @@ -1918,6 +1919,10 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) attachmentBlockReason, environmentUnavailable: environmentUnavailable !== null, }); + const submitAfterPreparingImages = useSubmitAfterPreparingImages( + attachmentTargetKey, + submissionBlocked, + ); // The pending Submit button follows the answer's own blockers, matching submitComposer. const primaryActionSendDisabledReason = (activePendingProgress ? attachmentBlockReason : sendDisabledReason) ?? @@ -2196,16 +2201,12 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) event?.preventDefault(); return false; } - // A send while a pasted image is still compressing would strand that image: - // the turn snapshot wouldn't include it, and it would surface in the *next* - // draft instead. - if (activeThreadId && countPreparingComposerImages(attachmentTargetKey) > 0) { + // Sending now would leave a still-compressing image out of the turn, so wait for it. + if ( + activeThreadId && + submitAfterPreparingImages(() => submitComposerRef.current(dispatchMode, submissionIntent)) + ) { event?.preventDefault(); - toastManager.add({ - type: "info", - title: gt("Still compressing a pasted image."), - description: gt("Send again once its thumbnail appears."), - }); return false; } if (pendingDraftWork.has(attachmentTargetKey)) { diff --git a/apps/web/src/components/chat/preparingComposerImages.browser.test.tsx b/apps/web/src/components/chat/preparingComposerImages.browser.test.tsx new file mode 100644 index 0000000000000..38a1bab533825 --- /dev/null +++ b/apps/web/src/components/chat/preparingComposerImages.browser.test.tsx @@ -0,0 +1,175 @@ +import { useEffect } from "react"; +import { expect, it, vi } from "vite-plus/test"; +import { createStore, type StoreApi, useStore } from "zustand"; + +import { act, render } from "../../../test/render"; +import { + addPreparingComposerImages, + cancelPreparingComposerImages, + removePreparingComposerImages, + useSubmitAfterPreparingImages, +} from "./preparingComposerImages"; + +type QueueSubmit = ReturnType; + +type DraftImagesStore = StoreApi<{ readonly ids: ReadonlyArray }>; + +function createDraftImagesStore(): DraftImagesStore { + return createStore(() => ({ ids: [] })); +} + +// Mirrors ChatComposer: the send reads draft images that a later effect syncs from the store. +function Probe(props: { + targetKey: string; + draftImagesStore: DraftImagesStore; + onReady: (queue: QueueSubmit) => void; + onCommit?: (images: ReadonlyArray) => void; + blocked?: boolean; +}) { + const queue = useSubmitAfterPreparingImages(props.targetKey, props.blocked); + const draftImages = useStore(props.draftImagesStore, (state) => state.ids); + const { onCommit } = props; + useEffect(() => { + onCommit?.(draftImages); + }, [onCommit, draftImages]); + props.onReady(queue); + return null; +} + +function preparingImage(id: string) { + return { id, name: `${id}.png`, file: new File(["png"], `${id}.png`), hidden: false }; +} + +it("sends after pasted images finish compressing, with the compressed image in the draft", async () => { + const target = "submit-after-preparing"; + using _store = { [Symbol.dispose]: () => cancelPreparingComposerImages(target) }; + const draftImagesStore = createDraftImagesStore(); + let queueSubmit: QueueSubmit | undefined; + let committedImages: ReadonlyArray = []; + const onCommit = (images: ReadonlyArray) => { + committedImages = images; + }; + const onReady = (queue: QueueSubmit) => { + queueSubmit = queue; + }; + await using screen = await render( + , + // A bare hook probe; nothing here navigates. + { router: false }, + ); + const submit = vi.fn(() => committedImages); + + expect(queueSubmit?.(submit)).toBe(false); + + addPreparingComposerImages(target, [preparingImage("first"), preparingImage("second")]); + expect(queueSubmit?.(submit)).toBe(true); + + await act(() => removePreparingComposerImages(target, new Set(["first"]))); + expect(submit).not.toHaveBeenCalled(); + + // Intake drops the placeholder and adds the compressed image in the same tick. + await act(() => { + removePreparingComposerImages(target, new Set(["second"])); + draftImagesStore.setState({ ids: ["second"] }); + }); + expect(submit).toHaveBeenCalledOnce(); + expect(submit.mock.results[0]?.value).toEqual(["second"]); + + submit.mockClear(); + await act(() => addPreparingComposerImages(target, [preparingImage("uploading")])); + expect(queueSubmit?.(submit)).toBe(true); + await screen.rerender( + , + ); + await act(() => removePreparingComposerImages(target, new Set(["uploading"]))); + expect(submit).not.toHaveBeenCalled(); + await screen.rerender( + , + ); + expect(submit).toHaveBeenCalledOnce(); + expect(submit.mock.results[0]?.value).toEqual(["second"]); +}); + +it("drops a waiting send when the composer moves to another draft or discards it", async () => { + const target = "submit-after-preparing-old"; + const otherTarget = "submit-after-preparing-new"; + using _store = { + [Symbol.dispose]: () => { + cancelPreparingComposerImages(target); + cancelPreparingComposerImages(otherTarget); + }, + }; + const draftImagesStore = createDraftImagesStore(); + let queueSubmit: QueueSubmit | undefined; + const onReady = (queue: QueueSubmit) => { + queueSubmit = queue; + }; + await using screen = await render( + , + { + // A bare hook probe; nothing here navigates. + router: false, + }, + ); + const submit = vi.fn(); + addPreparingComposerImages(target, [preparingImage("pasted")]); + expect(queueSubmit?.(submit)).toBe(true); + + // The other draft is still compressing too, so the switch alone must drop the send. + addPreparingComposerImages(otherTarget, [preparingImage("other")]); + await screen.rerender( + , + ); + await act(() => removePreparingComposerImages(target, new Set(["pasted"]))); + await screen.rerender( + , + ); + expect(submit).not.toHaveBeenCalled(); + + // Discarding the draft cancels its compression, which must not release the held send. + await act(() => addPreparingComposerImages(target, [preparingImage("discarded")])); + expect(queueSubmit?.(submit)).toBe(true); + await act(() => cancelPreparingComposerImages(target)); + expect(submit).not.toHaveBeenCalled(); +}); + +it("keeps the draft unsent when image preparation fails", async () => { + const target = "submit-after-failed-preparation"; + using _store = { [Symbol.dispose]: () => cancelPreparingComposerImages(target) }; + const draftImagesStore = createDraftImagesStore(); + let queueSubmit: QueueSubmit | undefined; + await using _screen = await render( + { + queueSubmit = queue; + }} + />, + // A bare hook probe; nothing here navigates. + { router: false }, + ); + const submit = vi.fn(); + await act(() => addPreparingComposerImages(target, [preparingImage("failed")])); + expect(queueSubmit?.(submit)).toBe(true); + await act(() => + removePreparingComposerImages(target, new Set(["failed"]), { cancelSubmission: true }), + ); + expect(submit).not.toHaveBeenCalled(); +}); diff --git a/apps/web/src/components/chat/preparingComposerImages.ts b/apps/web/src/components/chat/preparingComposerImages.ts index 0e571510f764b..754c1b4e4696a 100644 --- a/apps/web/src/components/chat/preparingComposerImages.ts +++ b/apps/web/src/components/chat/preparingComposerImages.ts @@ -1,5 +1,8 @@ +import { useEffect, useRef } from "react"; import { create } from "zustand"; +import { useStableCallback } from "../../hooks/useStableCallback"; + export interface PreparingComposerImage { readonly id: string; readonly name: string; @@ -60,6 +63,7 @@ export function isPreparingComposerImage(targetKey: string, imageId: string): bo export function removePreparingComposerImages( targetKey: string, imageIds: ReadonlySet, + options?: { readonly cancelSubmission?: boolean }, ): ReadonlySet { const current = usePreparingComposerImageStore.getState().byTargetKey[targetKey] ?? NO_PREPARING_IMAGES; @@ -67,6 +71,7 @@ export function removePreparingComposerImages( current.filter((image) => imageIds.has(image.id)).map((image) => image.id), ); if (removed.size === 0) return removed; + if (options?.cancelSubmission) invalidatePendingSubmit(targetKey); usePreparingComposerImageStore.setState((state) => { const remaining = (state.byTargetKey[targetKey] ?? NO_PREPARING_IMAGES).filter( (image) => !removed.has(image.id), @@ -82,8 +87,16 @@ export function removePreparingComposerImages( return removed; } +// Bumped on cancel so a send held for the cancelled images is dropped rather than released. +const cancelGenerations = new Map(); + +function invalidatePendingSubmit(targetKey: string) { + cancelGenerations.set(targetKey, (cancelGenerations.get(targetKey) ?? 0) + 1); +} + /** Drops every image still preparing for the target, so its compression result is discarded. */ export function cancelPreparingComposerImages(targetKey: string): void { + invalidatePendingSubmit(targetKey); if (!usePreparingComposerImageStore.getState().byTargetKey[targetKey]) return; usePreparingComposerImageStore.setState((state) => { const byTargetKey = { ...state.byTargetKey }; @@ -91,3 +104,41 @@ export function cancelPreparingComposerImages(targetKey: string): void { return { byTargetKey }; }); } + +/** + * Holds a send made while the target still has images compressing, and runs it once they finish, + * so the turn includes them. Returns false when nothing is compressing and the caller should send. + */ +export function useSubmitAfterPreparingImages(targetKey: string, blocked = false) { + const preparing = usePreparingComposerImages(targetKey); + const pendingRef = useRef<{ + readonly targetKey: string; + readonly cancelGeneration: number; + readonly submit: () => void; + } | null>(null); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- sends only after the render where the compressed images joined the draft + useEffect(() => { + const pending = pendingRef.current; + if (!pending) return; + if ( + pending.targetKey !== targetKey || + pending.cancelGeneration !== (cancelGenerations.get(targetKey) ?? 0) + ) { + pendingRef.current = null; + return; + } + if (preparing.length > 0 || blocked) return; + pendingRef.current = null; + // After the composer's later effects have synced its draft refs to this render. + queueMicrotask(pending.submit); + }, [preparing, targetKey, blocked]); + return useStableCallback((submit: () => void) => { + if (countPreparingComposerImages(targetKey) === 0) return false; + pendingRef.current = { + targetKey, + cancelGeneration: cancelGenerations.get(targetKey) ?? 0, + submit, + }; + return true; + }); +} diff --git a/apps/web/src/components/chat/useComposerAttachmentIntake.ts b/apps/web/src/components/chat/useComposerAttachmentIntake.ts index d6f981bc9440a..f0e429415d0bd 100644 --- a/apps/web/src/components/chat/useComposerAttachmentIntake.ts +++ b/apps/web/src/components/chat/useComposerAttachmentIntake.ts @@ -322,6 +322,7 @@ export function useComposerAttachmentIntake(input: { const stillPreparingIds = removePreparingComposerImages( attachmentTargetKey, new Set(preparingImages.map((image) => image.id)), + { cancelSubmission: compressionErrors.size > 0 || questionDiscarded }, ); if (questionAttachmentTarget) changeQuestionAttachmentPreparation(questionAttachmentTarget, -stillPreparingIds.size); @@ -372,7 +373,11 @@ export function useComposerAttachmentIntake(input: { }; const removeComposerImage = (imageId: string) => { - if (removePreparingComposerImages(attachmentTargetKey, new Set([imageId])).size > 0) { + if ( + removePreparingComposerImages(attachmentTargetKey, new Set([imageId]), { + cancelSubmission: true, + }).size > 0 + ) { // Its compression finishes in the background and is dropped. if (questionAttachmentTarget) changeQuestionAttachmentPreparation(questionAttachmentTarget, -1); diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 648fd58859dbe..7969ce24bc748 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -3156,8 +3156,6 @@ "164d3295a763dbad": "Der Snapshot ist nicht mehr verfügbar.", "f77ce9bc81a68882": "Der Snapshot ist noch nicht bereit zum Kopieren.", "68a4461e56df0896": "Spracheingabe wird vorbereitet", - "cfc4f3582964bf84": "Ein eingefügtes Bild wird noch komprimiert.", - "aedaf7f4faba8bd3": "Sende erneut, sobald die Miniatur erscheint.", "4bc6e68c58cbb173": "Angehängter Kontext wird noch in diese Nachricht übernommen.", "62bf4adef45b9830": "Sende erneut, sobald der Chip aufgelöst ist.", "d0e9c30191edf07e": "Antwort auf {titles}", @@ -4642,6 +4640,7 @@ "98c76143d9aae871": "Ablage-Eintrag kommt möglicherweise zurück", "a7101927759103ad": "Der Browserspeicher hat das Löschen abgelehnt, daher könnte dieser Prompt nach dem Neuladen wieder erscheinen.", "fb34cb404c4930dc": "Lege erneut ab, sobald der Chip aufgelöst ist.", + "cfc4f3582964bf84": "Ein eingefügtes Bild wird noch komprimiert.", "70b12bc1e1a26abb": "Lege erneut ab, sobald die Komprimierung abgeschlossen ist.", "f6b1ef37f7587664": "Hänge abgelegte Dateien erneut an oder entferne sie, bevor du ablegst", "120167bbfb6d5939": "Warte auf die Datei-Uploads, bevor du diesen Prompt ablegst", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index 599944358b5bb..cb30b352e7095 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -3155,8 +3155,6 @@ "164d3295a763dbad": "Snapshot is no longer available.", "f77ce9bc81a68882": "The snapshot is not ready to copy.", "68a4461e56df0896": "Preparing voice input", - "cfc4f3582964bf84": "Still compressing a pasted image.", - "aedaf7f4faba8bd3": "Send again once its thumbnail appears.", "4bc6e68c58cbb173": "Still bringing attached context into this message.", "62bf4adef45b9830": "Send again once its chip resolves.", "d0e9c30191edf07e": "Replying to {titles}", @@ -4641,6 +4639,7 @@ "98c76143d9aae871": "Stash entry may come back", "a7101927759103ad": "Browser storage rejected the delete, so this prompt could reappear after a reload.", "fb34cb404c4930dc": "Stash again once its chip resolves.", + "cfc4f3582964bf84": "Still compressing a pasted image.", "70b12bc1e1a26abb": "Stash again once it finishes compressing.", "f6b1ef37f7587664": "Attach dropped files again or remove them before stashing", "120167bbfb6d5939": "Wait for file uploads before stashing this prompt", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index 956f4e17a9617..aba7481449778 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -3155,8 +3155,6 @@ "164d3295a763dbad": "La instantánea ya no está disponible.", "f77ce9bc81a68882": "La instantánea no está lista para copiarla.", "68a4461e56df0896": "Preparando la entrada de voz", - "cfc4f3582964bf84": "Aún se está comprimiendo una imagen pegada.", - "aedaf7f4faba8bd3": "Vuelve a enviar cuando aparezca su miniatura.", "4bc6e68c58cbb173": "Aún se está incorporando el contexto adjunto a este mensaje.", "62bf4adef45b9830": "Vuelve a enviar cuando se resuelva su chip.", "d0e9c30191edf07e": "Respondiendo a {titles}", @@ -4639,6 +4637,7 @@ "98c76143d9aae871": "Puede que la entrada del stash vuelva", "a7101927759103ad": "El almacenamiento del navegador rechazó la eliminación, así que este prompt podría volver a aparecer tras recargar.", "fb34cb404c4930dc": "Vuelve a guardarlo en el stash cuando se resuelva su chip.", + "cfc4f3582964bf84": "Aún se está comprimiendo una imagen pegada.", "70b12bc1e1a26abb": "Vuelve a guardarlo en el stash cuando termine de comprimirse.", "f6b1ef37f7587664": "Vuelve a adjuntar los archivos soltados o quítalos antes de guardarlo en el stash", "120167bbfb6d5939": "Espera a que se suban los archivos antes de guardar este prompt en el stash", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index 1c982cc6d6f58..df6190f7eb702 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -3155,8 +3155,6 @@ "164d3295a763dbad": "L’instantané n’est plus disponible.", "f77ce9bc81a68882": "L’instantané n’est pas prêt à être copié.", "68a4461e56df0896": "Préparation de la saisie vocale", - "cfc4f3582964bf84": "Compression d’une image collée en cours.", - "aedaf7f4faba8bd3": "Renvoyez quand sa miniature apparaît.", "4bc6e68c58cbb173": "Ajout du contexte joint à ce message en cours.", "62bf4adef45b9830": "Renvoyez quand sa puce est résolue.", "d0e9c30191edf07e": "Réponse à {titles}", @@ -4640,6 +4638,7 @@ "98c76143d9aae871": "L’entrée de la réserve peut revenir", "a7101927759103ad": "Le stockage du navigateur a refusé la suppression ; ce prompt pourrait donc réapparaître après un rechargement.", "fb34cb404c4930dc": "Mettez de côté à nouveau quand sa puce est résolue.", + "cfc4f3582964bf84": "Compression d’une image collée en cours.", "70b12bc1e1a26abb": "Mettez de côté à nouveau une fois la compression terminée.", "f6b1ef37f7587664": "Joignez à nouveau les fichiers retirés ou supprimez-les avant de mettre de côté", "120167bbfb6d5939": "Attendez la fin de l’envoi des fichiers avant de mettre ce prompt de côté", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index 879531a396d2a..dc962e7a01c1e 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -3153,8 +3153,6 @@ "164d3295a763dbad": "スナップショットは利用できなくなりました。", "f77ce9bc81a68882": "スナップショットはまだコピーできる状態ではありません。", "68a4461e56df0896": "音声入力を準備しています", - "cfc4f3582964bf84": "貼り付けた画像をまだ圧縮しています。", - "aedaf7f4faba8bd3": "サムネイルが表示されたら、もう一度送信してください。", "4bc6e68c58cbb173": "添付したコンテキストをまだこのメッセージに取り込んでいます。", "62bf4adef45b9830": "チップが確定したら、もう一度送信してください。", "d0e9c30191edf07e": "{titles} に返信中", @@ -4629,6 +4627,7 @@ "98c76143d9aae871": "退避した項目が戻る可能性があります", "a7101927759103ad": "ブラウザーのストレージが削除を拒否したため、再読み込み後にこのプロンプトが再表示される可能性があります。", "fb34cb404c4930dc": "チップが確定したら、もう一度退避してください。", + "cfc4f3582964bf84": "貼り付けた画像をまだ圧縮しています。", "70b12bc1e1a26abb": "圧縮が終わったら、もう一度退避してください。", "f6b1ef37f7587664": "退避する前に、ドロップしたファイルをもう一度添付するか削除してください", "120167bbfb6d5939": "このプロンプトを退避する前に、ファイルのアップロードが終わるまでお待ちください", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index fae8ce2ec6fc4..ff5281e80cb8a 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -3154,8 +3154,6 @@ "164d3295a763dbad": "스냅샷을 더 이상 사용할 수 없습니다.", "f77ce9bc81a68882": "스냅샷을 복사할 준비가 되지 않았습니다.", "68a4461e56df0896": "음성 입력 준비 중", - "cfc4f3582964bf84": "붙여 넣은 이미지를 아직 압축하는 중입니다.", - "aedaf7f4faba8bd3": "썸네일이 표시되면 다시 보내세요.", "4bc6e68c58cbb173": "첨부한 컨텍스트를 아직 이 메시지로 가져오는 중입니다.", "62bf4adef45b9830": "칩이 확인되면 다시 보내세요.", "d0e9c30191edf07e": "{titles}에 답장하는 중", @@ -4626,6 +4624,7 @@ "98c76143d9aae871": "임시 저장함 항목이 다시 나타날 수 있습니다", "a7101927759103ad": "브라우저 저장소가 삭제를 거부해서 새로 고친 후 이 프롬프트가 다시 나타날 수 있습니다.", "fb34cb404c4930dc": "칩이 확인되면 다시 임시 저장하세요.", + "cfc4f3582964bf84": "붙여 넣은 이미지를 아직 압축하는 중입니다.", "70b12bc1e1a26abb": "압축이 끝나면 다시 임시 저장하세요.", "f6b1ef37f7587664": "임시 저장하기 전에 끌어다 놓은 파일을 다시 첨부하거나 제거하세요", "120167bbfb6d5939": "이 프롬프트를 임시 저장하기 전에 파일 업로드를 기다리세요", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index 7010bef288b16..0a80119685c2d 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -3155,8 +3155,6 @@ "164d3295a763dbad": "O snapshot não está mais disponível.", "f77ce9bc81a68882": "O snapshot não está pronto para copiar.", "68a4461e56df0896": "Preparando a entrada de voz", - "cfc4f3582964bf84": "Ainda comprimindo uma imagem colada.", - "aedaf7f4faba8bd3": "Envie novamente quando a miniatura aparecer.", "4bc6e68c58cbb173": "Ainda trazendo o contexto anexado para esta mensagem.", "62bf4adef45b9830": "Envie novamente quando o chip carregar.", "d0e9c30191edf07e": "Respondendo a {titles}", @@ -4639,6 +4637,7 @@ "98c76143d9aae871": "O item guardado pode voltar", "a7101927759103ad": "O armazenamento do navegador rejeitou a exclusão, então este prompt pode reaparecer após recarregar.", "fb34cb404c4930dc": "Guarde novamente quando o chip carregar.", + "cfc4f3582964bf84": "Ainda comprimindo uma imagem colada.", "70b12bc1e1a26abb": "Guarde novamente quando a compressão terminar.", "f6b1ef37f7587664": "Anexe novamente os arquivos soltos ou remova-os antes de guardar", "120167bbfb6d5939": "Aguarde o upload dos arquivos antes de guardar este prompt", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 0766d953dd02d..f83ae70839ad0 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -3155,8 +3155,6 @@ "164d3295a763dbad": "Снимок больше недоступен.", "f77ce9bc81a68882": "Снимок ещё не готов к копированию.", "68a4461e56df0896": "Подготовка голосового ввода", - "cfc4f3582964bf84": "Вставленное изображение ещё сжимается.", - "aedaf7f4faba8bd3": "Отправьте снова, когда появится миниатюра.", "4bc6e68c58cbb173": "Прикреплённый контекст ещё добавляется в сообщение.", "62bf4adef45b9830": "Отправьте снова, когда чип загрузится.", "d0e9c30191edf07e": "Ответ на {titles}", @@ -4639,6 +4637,7 @@ "98c76143d9aae871": "Запись тайника может вернуться", "a7101927759103ad": "Хранилище браузера отклонило удаление, поэтому промпт может снова появиться после перезагрузки.", "fb34cb404c4930dc": "Спрячьте снова, когда чип загрузится.", + "cfc4f3582964bf84": "Вставленное изображение ещё сжимается.", "70b12bc1e1a26abb": "Спрячьте снова, когда сжатие завершится.", "f6b1ef37f7587664": "Прикрепите отброшенные файлы снова или удалите их перед откладыванием", "120167bbfb6d5939": "Дождитесь загрузки файлов, прежде чем откладывать этот промпт", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index 5e6d1607edf31..16e6feff436b6 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -3155,8 +3155,6 @@ "164d3295a763dbad": "Ögonblicksbilden är inte längre tillgänglig.", "f77ce9bc81a68882": "Ögonblicksbilden är inte redo att kopieras.", "68a4461e56df0896": "Förbereder röstinmatning", - "cfc4f3582964bf84": "Komprimerar fortfarande en inklistrad bild.", - "aedaf7f4faba8bd3": "Skicka igen när miniatyrbilden visas.", "4bc6e68c58cbb173": "Hämtar fortfarande bifogad kontext till det här meddelandet.", "62bf4adef45b9830": "Skicka igen när dess etikett har lästs in.", "d0e9c30191edf07e": "Svarar på {titles}", @@ -4640,6 +4638,7 @@ "98c76143d9aae871": "Den undanlagda prompten kan komma tillbaka", "a7101927759103ad": "Webbläsarens lagring avvisade raderingen, så prompten kan dyka upp igen efter en omladdning.", "fb34cb404c4930dc": "Lägg undan igen när dess etikett har lästs in.", + "cfc4f3582964bf84": "Komprimerar fortfarande en inklistrad bild.", "70b12bc1e1a26abb": "Lägg undan igen när komprimeringen är klar.", "f6b1ef37f7587664": "Bifoga släppta filer igen eller ta bort dem innan du lägger undan", "120167bbfb6d5939": "Vänta på filuppladdningarna innan du lägger undan den här prompten", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index c86b9e6c55e41..3ab089125f8ae 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -3159,8 +3159,6 @@ "164d3295a763dbad": "快照已不可用。", "f77ce9bc81a68882": "快照尚未准备好复制。", "68a4461e56df0896": "正在准备语音输入", - "cfc4f3582964bf84": "粘贴的图片仍在压缩。", - "aedaf7f4faba8bd3": "缩略图出现后请再次发送。", "4bc6e68c58cbb173": "仍在把附加的上下文放入这条消息。", "62bf4adef45b9830": "标签加载完成后请再次发送。", "d0e9c30191edf07e": "回复 {titles}", @@ -4646,6 +4644,7 @@ "98c76143d9aae871": "暂存条目可能会再次出现", "a7101927759103ad": "浏览器存储拒绝了删除操作,所以刷新后这条提示词可能再次出现。", "fb34cb404c4930dc": "标签加载完成后请再次暂存。", + "cfc4f3582964bf84": "粘贴的图片仍在压缩。", "70b12bc1e1a26abb": "请在压缩完成后重新暂存。", "f6b1ef37f7587664": "暂存前请重新添加丢失的文件,或将其移除", "120167bbfb6d5939": "请等文件上传完成后再暂存这条提示词", diff --git a/scripts/scenarios/enter-during-image-compression-sends-after.e2e.ts b/scripts/scenarios/enter-during-image-compression-sends-after.e2e.ts new file mode 100644 index 0000000000000..415e4288dedf4 --- /dev/null +++ b/scripts/scenarios/enter-during-image-compression-sends-after.e2e.ts @@ -0,0 +1,35 @@ +import { expect } from "e2e"; + +import { + finishImageCompression, + holdImageCompression, + pasteWideScreenshot, +} from "./image-compression-hold.ts"; +import { test, WEB } from "./t3.ts"; + +test( + "Enter while a pasted image compresses sends the message with the image once it finishes", + WEB, + async ({ t3, app, browser, screen }) => { + await holdImageCompression(browser); + const project = await t3.project("demo"); + const thread = await t3.thread({ project, title: "Screenshot work", messages: ["first"] }); + await t3.open(thread); + await expect(screen.getByText("first fixture turn complete", { exact: false })).toBeVisible(); + + const composer = screen.getByRole("textbox"); + await composer.fill("What is in this screenshot?"); + await pasteWideScreenshot(browser); + await browser.keyboard.press("Enter"); + await app.screenshot("enter-while-compressing"); + + await finishImageCompression(browser); + await app.screenshot("after-compression"); + const sentWithImage = browser + .locator('[data-message-role="user"]:has([aria-label="Preview screenshot.png"])') + .filter({ hasText: "What is in this screenshot?" }); + await expect(sentWithImage).toBeVisible(); + await expect(composer).not.toContainText("What is in this screenshot?"); + await expect(composer).not.toContainText("screenshot.png"); + }, +);