Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-8672 fix(views): lock avatar crop through encoding and upload handoff (BOYF-524) (#10018)

沙雕的小鱼儿 boyfeiyu8a6cb87c5fd9
diff --git a/packages/views/common/avatar-crop-dialog.test.tsx b/packages/views/common/avatar-crop-dialog.test.tsx
new file mode 100644
index 0000000000..1c2040a2a8
--- /dev/null
+++ b/packages/views/common/avatar-crop-dialog.test.tsx
@@ -0,0 +1,152 @@
+// @vitest-environment jsdom
+
+import { useEffect } from "react";
+import { act, cleanup, fireEvent, screen, waitFor } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { renderWithI18n } from "../test/i18n";
+import { AvatarCropDialog } from "./avatar-crop-dialog";
+
+const encode = vi.hoisted(() => vi.fn());
+vi.mock("./avatar-crop", async (importOriginal) => ({
+ ...await importOriginal<typeof import("./avatar-crop")>(),
+ getCroppedAvatarBlob: encode,
+ pickOutputType: () => ({ type: "image/webp", quality: 0.9 }),
+}));
+// jsdom has no image layout; the browser regression exercises the real cropper.
+vi.mock("react-easy-crop", () => ({
+ default: function LoadedCropper({ onCropComplete }: {
+ onCropComplete: (area: object, pixels: object) => void;
+ }) {
+ useEffect(() => {
+ onCropComplete({}, { x: 10, y: 20, width: 100, height: 100 });
+ // A loaded image reports its initial crop once.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
+ return null;
+ },
+}));
+
+function deferred<T>() {
+ let resolve!: (value: T) => void;
+ let reject!: (reason: Error) => void;
+ const promise = new Promise<T>((yes, no) => { resolve = yes; reject = no; });
+ return { promise, resolve, reject };
+}
+
+beforeEach(() => {
+ vi.stubGlobal("URL", class extends URL {
+ static createObjectURL = vi.fn(() => "blob:synthetic-avatar");
+ static revokeObjectURL = vi.fn();
+ });
+});
+afterEach(() => {
+ cleanup();
+ vi.unstubAllGlobals();
+ vi.resetAllMocks();
+});
+
+async function mount() {
+ const pending = deferred<Blob>();
+ encode.mockReturnValue(pending.promise);
+ const props = {
+ file: new File(["synthetic"], "avatar.png", { type: "image/png" }),
+ open: true,
+ busy: false,
+ onOpenChange: vi.fn(),
+ onCropped: vi.fn(),
+ };
+ const view = renderWithI18n(<AvatarCropDialog {...props} />);
+ const apply = await screen.findByRole("button", { name: "Save" });
+ await waitFor(() => expect(apply).toBeEnabled());
+ return { ...view, props, pending, apply };
+}
+
+describe("AvatarCropDialog encoding", () => {
+ it("locks controls and dismissal from Apply until the upload handoff", async () => {
+ const { apply, pending, props } = await mount();
+ fireEvent.click(apply);
+
+ for (const name of ["Save", "Cancel", "Reset", "Rotate", "Zoom in", "Zoom out"]) {
+ expect(screen.getByRole("button", { name })).toBeDisabled();
+ }
+ expect(screen.queryByRole("button", { name: "Close" })).not.toBeInTheDocument();
+ expect(screen.getByRole("slider")).toBeDisabled();
+ expect(apply).toHaveAttribute("aria-busy", "true");
+ expect(screen.queryByText("Uploading…")).not.toBeInTheDocument();
+ fireEvent.click(screen.getByRole("button", { name: "Cancel" }));
+ fireEvent.keyDown(screen.getByRole("dialog"), { key: "Escape" });
+ const overlay = document.querySelector('[data-slot="dialog-overlay"]')!;
+ fireEvent.mouseDown(overlay);
+ fireEvent.mouseUp(overlay);
+ fireEvent.click(overlay);
+ expect(props.onOpenChange).not.toHaveBeenCalled();
+ expect(props.onCropped).not.toHaveBeenCalled();
+
+ await act(async () => pending.resolve(new Blob(["cropped"], { type: "image/webp" })));
+ expect(props.onCropped).toHaveBeenCalledTimes(1);
+ const file = props.onCropped.mock.calls[0]![0] as File;
+ expect([file.name, file.type, file.size]).toEqual(["avatar.webp", "image/webp", 7]);
+ expect(apply).toBeEnabled();
+ });
+
+ it("accepts only one encode for two clicks in the same event batch", async () => {
+ const { apply, pending, props } = await mount();
+ const cancel = screen.getByRole("button", { name: "Cancel" });
+ const close = screen.getByRole("button", { name: "Close" });
+ act(() => {
+ apply.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ apply.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ cancel.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ close.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ });
+ expect(encode).toHaveBeenCalledTimes(1);
+ expect(props.onOpenChange).not.toHaveBeenCalled();
+ await act(async () => pending.resolve(new Blob(["cropped"])));
+ expect(props.onCropped).toHaveBeenCalledTimes(1);
+ });
+
+ it("releases the encoding lock on failure and keeps close available", async () => {
+ const { apply, pending, props } = await mount();
+ fireEvent.click(apply);
+ await act(async () => pending.reject(new Error("synthetic encoding failure")));
+ expect(screen.getByText("Couldn't load image")).toBeInTheDocument();
+ expect(props.onCropped).not.toHaveBeenCalled();
+ const cancel = screen.getByRole("button", { name: "Cancel" });
+ expect(cancel).toBeEnabled();
+ expect(screen.getByRole("button", { name: "Close" })).toBeEnabled();
+ expect(apply).not.toHaveAttribute("aria-busy", "true");
+ fireEvent.click(cancel);
+ expect(props.onOpenChange).toHaveBeenCalledWith(false);
+ });
+
+ it("preserves the parent's busy lock after encoding settles", async () => {
+ const { apply, pending, props, rerender } = await mount();
+ fireEvent.click(apply);
+ rerender(<AvatarCropDialog {...props} busy />);
+ await act(async () => pending.resolve(new Blob(["cropped"])));
+ expect(screen.getByRole("button", { name: /Uploading/ })).toBeDisabled();
+ expect(screen.getByRole("button", { name: "Cancel" })).toBeDisabled();
+ fireEvent.keyDown(screen.getByRole("dialog"), { key: "Escape" });
+ expect(props.onOpenChange).not.toHaveBeenCalled();
+ rerender(<AvatarCropDialog {...props} />);
+ expect(screen.getByRole("button", { name: "Save" })).toBeEnabled();
+ });
+
+ it("allows cancellation before Apply without starting an encode", async () => {
+ const { props } = await mount();
+ fireEvent.click(screen.getByRole("button", { name: "Cancel" }));
+ expect(props.onOpenChange).toHaveBeenCalledWith(false);
+ expect(encode).not.toHaveBeenCalled();
+ });
+
+ it("keeps the selected rotation and crop in the encoder request", async () => {
+ const { apply, pending } = await mount();
+ fireEvent.click(screen.getByRole("button", { name: "Rotate" }));
+ fireEvent.click(apply);
+ expect(encode).toHaveBeenCalledWith(
+ "blob:synthetic-avatar", { x: 10, y: 20, width: 100, height: 100 }, 90,
+ { output: 512, type: "image/webp", quality: 0.9, background: undefined },
+ );
+ await act(async () => pending.resolve(new Blob(["cropped"])));
+ });
+});
diff --git a/packages/views/common/avatar-crop-dialog.tsx b/packages/views/common/avatar-crop-dialog.tsx
index 091ab3128f..de70251178 100644
--- a/packages/views/common/avatar-crop-dialog.tsx
+++ b/packages/views/common/avatar-crop-dialog.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useEffect, useState } from "react";
+import { useEffect, useRef, useState } from "react";
import Cropper, { type Area, type Point } from "react-easy-crop";
import { Loader2, Minus, Plus, RotateCw } from "@multica/ui/icons";
import { Button } from "@multica/ui/components/ui/button";
@@ -62,6 +62,9 @@ export function AvatarCropDialog({
null,
);
const [loadError, setLoadError] = useState(false);
+ const [encoding, setEncoding] = useState(false);
+ const encodingRef = useRef(false);
+ const pending = busy || encoding;
// One object URL per picked file, alive for the dialog's lifetime; reset the
// transform so a new pick starts centered and unrotated.
@@ -90,9 +93,15 @@ export function AvatarCropDialog({
};
const handleConfirm = async () => {
- if (!objectUrl || !croppedAreaPixels || !file) return;
- const { type, quality } = pickOutputType();
+ if (
+ busy || encodingRef.current || loadError ||
+ !objectUrl || !croppedAreaPixels || !file
+ ) return;
+ // Guard re-entry before React has rendered the disabled controls.
+ encodingRef.current = true;
+ setEncoding(true);
try {
+ const { type, quality } = pickOutputType();
const blob = await getCroppedAvatarBlob(objectUrl, croppedAreaPixels, rotation, {
output: AVATAR_OUTPUT_SIZE,
type,
@@ -104,21 +113,25 @@ export function AvatarCropDialog({
onCropped(blobToAvatarFile(blob, file.name, type));
} catch {
setLoadError(true);
+ } finally {
+ encodingRef.current = false;
+ setEncoding(false);
}
};
- const disabled = busy || !objectUrl || loadError || !croppedAreaPixels;
+ const handleOpenChange = (next: boolean) => {
+ if (busy || encodingRef.current) return;
+ onOpenChange(next);
+ };
+
+ const disabled = pending || !objectUrl || loadError || !croppedAreaPixels;
return (
<Dialog
open={open}
- onOpenChange={(next) => {
- // Never let a close slip through while an upload is committing.
- if (busy) return;
- onOpenChange(next);
- }}
+ onOpenChange={handleOpenChange}
>
- <DialogContent showCloseButton={!busy} className="sm:max-w-md">
+ <DialogContent showCloseButton={!pending} className="sm:max-w-md">
<DialogHeader>
<DialogTitle>{t(($) => $.avatar_crop.title)}</DialogTitle>
</DialogHeader>
@@ -136,9 +149,18 @@ export function AvatarCropDialog({
maxZoom={MAX_ZOOM}
cropShape="round"
showGrid={false}
- onCropChange={setCrop}
- onZoomChange={setZoom}
- onRotationChange={setRotation}
+ style={{
+ containerStyle: { pointerEvents: pending ? "none" : undefined },
+ }}
+ onCropChange={(next) => {
+ if (!pending) setCrop(next);
+ }}
+ onZoomChange={(next) => {
+ if (!pending) setZoom(next);
+ }}
+ onRotationChange={(next) => {
+ if (!pending) setRotation(next);
+ }}
onCropComplete={(_: Area, areaPixels: Area) =>
setCroppedAreaPixels(areaPixels)
}
@@ -147,7 +169,7 @@ export function AvatarCropDialog({
<button
type="button"
onClick={() => setRotation((r) => (r + 90) % 360)}
- disabled={busy}
+ disabled={pending}
aria-label={t(($) => $.avatar_crop.rotate)}
className="absolute right-2 top-2 z-10 flex h-8 w-8 items-center justify-center rounded-full bg-background/90 text-foreground shadow-sm transition-colors hover:bg-background disabled:opacity-50"
>
@@ -202,26 +224,22 @@ export function AvatarCropDialog({
</div>
<div className="flex items-center justify-between">
- <Button variant="ghost" onClick={resetTransform} disabled={busy}>
+ <Button variant="ghost" onClick={resetTransform} disabled={pending}>
{t(($) => $.avatar_crop.reset)}
</Button>
<div className="flex gap-2">
<Button
variant="outline"
- onClick={() => onOpenChange(false)}
- disabled={busy}
+ onClick={() => handleOpenChange(false)}
+ disabled={pending}
>
{t(($) => $.avatar_crop.cancel)}
</Button>
- <Button onClick={handleConfirm} disabled={disabled}>
- {busy ? (
- <>
- <Loader2 className="h-3.5 w-3.5 animate-spin" />
- {t(($) => $.avatar_crop.uploading)}
- </>
- ) : (
- t(($) => $.avatar_crop.apply)
- )}
+ <Button onClick={handleConfirm} disabled={disabled} aria-busy={pending}>
+ {pending && <Loader2 className="h-3.5 w-3.5 animate-spin" />}
+ {busy
+ ? t(($) => $.avatar_crop.uploading)
+ : t(($) => $.avatar_crop.apply)}
</Button>
</div>
</div>
diff --git a/packages/views/common/avatar-upload-control.test.tsx b/packages/views/common/avatar-upload-control.test.tsx
index 92f29ed987..a0efd6e999 100644
--- a/packages/views/common/avatar-upload-control.test.tsx
+++ b/packages/views/common/avatar-upload-control.test.tsx
@@ -7,6 +7,7 @@ import { renderWithI18n } from "../test/i18n";
const uploadMock = vi.hoisted(() => vi.fn());
const toastError = vi.hoisted(() => vi.fn());
const toastSuccess = vi.hoisted(() => vi.fn());
+const cropDismiss = vi.hoisted(() => ({ request: (_open: boolean) => {} }));
vi.mock("sonner", () => ({
toast: { error: toastError, success: toastSuccess },
@@ -26,15 +27,19 @@ vi.mock("./avatar-crop-dialog", () => ({
AvatarCropDialog: ({
open,
onCropped,
+ onOpenChange,
}: {
open: boolean;
onCropped: (file: File) => void;
- }) =>
- open ? (
+ onOpenChange: (open: boolean) => void;
+ }) => {
+ cropDismiss.request = onOpenChange;
+ return open ? (
<button type="button" onClick={() => onCropped(imageFile())}>
crop
</button>
- ) : null,
+ ) : null;
+ },
}));
import { AvatarUploadControl } from "./avatar-upload-control";
@@ -251,6 +256,29 @@ describe("AvatarUploadControl", () => {
await waitFor(() => expect(toastError).toHaveBeenCalledWith("network down"));
});
+ it("blocks dismissal before the upload busy state commits and releases it on failure", async () => {
+ let rejectUpload!: (reason: Error) => void;
+ uploadMock.mockImplementationOnce(() => {
+ // A close request can reach the previous render's handler before busy
+ // commits, while the cropper is handing off to the upload.
+ cropDismiss.request(false);
+ return new Promise((_, reject) => { rejectUpload = reject; });
+ });
+ const { container } = renderWithI18n(
+ <AvatarUploadControl variant="agent" value={null} onUploaded={vi.fn()} />,
+ );
+
+ uploadImage(container);
+ expect(uploadMock).toHaveBeenCalledTimes(1);
+ const dialogStayedOpen = screen.queryByRole("button", { name: "crop" }) !== null;
+
+ await act(async () => rejectUpload(new Error("network down")));
+ expect(dialogStayedOpen).toBe(true);
+ expect(toastError).toHaveBeenCalledWith("network down");
+ act(() => cropDismiss.request(false));
+ expect(screen.queryByRole("button", { name: "crop" })).not.toBeInTheDocument();
+ });
+
it("cannot be opened when the caller lacks edit permission", () => {
renderWithI18n(
<AvatarUploadControl
diff --git a/packages/views/common/avatar-upload-control.tsx b/packages/views/common/avatar-upload-control.tsx
index e08c53cb89..a70c994c9e 100644
--- a/packages/views/common/avatar-upload-control.tsx
+++ b/packages/views/common/avatar-upload-control.tsx
@@ -149,6 +149,7 @@ export function AvatarUploadControl({
const { t } = useT("common");
const { upload } = useFileUpload(api);
const fileInputRef = useRef<HTMLInputElement>(null);
+ const uploadPendingRef = useRef(false);
const [pickedFile, setPickedFile] = useState<File | null>(null);
const [dialogOpen, setDialogOpen] = useState(false);
const [busy, setBusy] = useState(false);
@@ -188,6 +189,8 @@ export function AvatarUploadControl({
};
const handleCropped = async (cropped: File) => {
+ // Block dismissal during the cropper handoff, before busy has committed.
+ uploadPendingRef.current = true;
setBusy(true);
try {
const result = await upload(cropped);
@@ -202,6 +205,7 @@ export function AvatarUploadControl({
err instanceof Error ? err.message : t(($) => $.avatar_upload.failed),
);
} finally {
+ uploadPendingRef.current = false;
setBusy(false);
}
};
@@ -388,7 +392,7 @@ export function AvatarUploadControl({
open={dialogOpen}
busy={busy}
onOpenChange={(next) => {
- if (busy) return;
+ if (busy || uploadPendingRef.current) return;
setDialogOpen(next);
if (!next) setPickedFile(null);
}}