Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(views): unify avatar upload with crop editing (#5074)
Naiyuan Qingc6783efd8808
diff --git a/packages/ui/components/common/actor-avatar.tsx b/packages/ui/components/common/actor-avatar.tsxindex 52cae45a5a..db24e27a10 100644--- a/packages/ui/components/common/actor-avatar.tsx+++ b/packages/ui/components/common/actor-avatar.tsx@@ -32,14 +32,18 @@ function ActorAvatar({setImgError(false);}, [avatarUrl]);+ // Only humans (members) read as a circle. Non-human actors — agents, squads,+ // and the system identity — get a rounded square so they don't read as a+ // single person. This is the single source of truth for avatar shape; the+ // upload editors mirror it (packages/views/common/avatar-upload-control.tsx).+ const isHuman = !isAgent && !isSystem && !isSquad;+return (<divdata-slot="avatar"className={cn("inline-flex shrink-0 items-center justify-center font-medium overflow-hidden",- // Squads (a group, non-human) get a square tile so they don't read as- // a single person; everyone else stays round.- isSquad ? "rounded-md" : "rounded-full",+ isHuman ? "rounded-full" : "rounded-md",(!avatarUrl || imgError) && "bg-muted text-muted-foreground",className)}diff --git a/packages/views/agents/components/agent-detail-inspector.tsx b/packages/views/agents/components/agent-detail-inspector.tsxindex 8514e25999..74d710453a 100644--- a/packages/views/agents/components/agent-detail-inspector.tsx+++ b/packages/views/agents/components/agent-detail-inspector.tsx@@ -2,12 +2,10 @@import {useEffect,- useRef,useState,type ReactNode,} from "react";-import { Camera, Loader2, Pencil } from "lucide-react";-import { toast } from "sonner";+import { Loader2, Pencil } from "lucide-react";import type {Agent,AgentRuntime,@@ -17,12 +15,11 @@ import {AGENT_DESCRIPTION_MAX_LENGTH,type AgentPresenceDetail,} from "@multica/core/agents";-import { api } from "@multica/core/api";-import { useFileUpload } from "@multica/core/hooks/use-file-upload";import { isImeComposing } from "@multica/core/utils";import { useTimeAgo } from "../../i18n";import { Button } from "@multica/ui/components/ui/button";import { ActorAvatar } from "../../common/actor-avatar";+import { AvatarUploadControl } from "../../common/avatar-upload-control";import { Input } from "@multica/ui/components/ui/input";import {Dialog,@@ -296,10 +293,6 @@ function AvatarEditor({canEdit: boolean;onUpdate: (data: Record<string, unknown>) => Promise<void>;}) {- const { t } = useT("agents");- const fileInputRef = useRef<HTMLInputElement>(null);- const { upload, uploading } = useFileUpload(api);-if (!canEdit) {return (<div className="h-14 w-14 shrink-0 overflow-hidden rounded-lg">@@ -313,53 +306,14 @@ function AvatarEditor({);}- const handleFile = async (e: React.ChangeEvent<HTMLInputElement>) => {- const file = e.target.files?.[0];- if (!file) return;- e.target.value = "";- try {- const result = await upload(file);- if (!result) return;- await onUpdate({ avatar_url: result.link });- toast.success(t(($) => $.inspector.avatar_updated_toast));- } catch (err) {- toast.error(err instanceof Error ? err.message : t(($) => $.inspector.avatar_upload_failed_toast));- }- };-return (- <>- <button- type="button"- // rounded-lg matches the standard agent avatar treatment used in- // list rows. Avoid rounded-full — circles are reserved for humans.- className="group relative h-14 w-14 shrink-0 overflow-hidden rounded-lg focus:outline-none focus-visible:ring-2 focus-visible:ring-ring"- onClick={() => fileInputRef.current?.click()}- disabled={uploading}- aria-label={t(($) => $.inspector.change_avatar_aria)}- >- <ActorAvatar- actorType="agent"- actorId={agent.id}- size={56}- className="rounded-none"- />- <div className="absolute inset-0 flex items-center justify-center bg-black/40 opacity-0 transition-opacity group-hover:opacity-100">- {uploading ? (- <Loader2 className="h-4 w-4 animate-spin text-white" />- ) : (- <Camera className="h-4 w-4 text-white" />- )}- </div>- </button>- <input- ref={fileInputRef}- type="file"- accept="image/*"- className="hidden"- onChange={handleFile}- />- </>+ <AvatarUploadControl+ variant="agent"+ value={agent.avatar_url ?? null}+ name={agent.name}+ size={56}+ onUploaded={(url) => onUpdate({ avatar_url: url })}+ />);}diff --git a/packages/views/agents/components/avatar-picker.tsx b/packages/views/agents/components/avatar-picker.tsxdeleted file mode 100644index 236c38ae4c..0000000000--- a/packages/views/agents/components/avatar-picker.tsx+++ /dev/null@@ -1,144 +0,0 @@-"use client";--import { useRef, useState } from "react";-import { Camera, ImagePlus, Loader2, X } from "lucide-react";-import { toast } from "sonner";-import { api } from "@multica/core/api";-import { useFileUpload } from "@multica/core/hooks/use-file-upload";-import { resolvePublicFileUrl } from "@multica/core/workspace/avatar-url";-import { cn } from "@multica/ui/lib/utils";-import { useT } from "../../i18n";--interface AvatarPickerProps {- /** Current avatar URL. null when nothing chosen yet. */- value: string | null;- /** Fires after a successful upload — the parent stashes the URL for the- * create call. Re-fires with null when the user clears the choice. */- onChange: (url: string | null) => void;- /** Pixel size of the square. Defaults to 56 (h-14 / w-14), which lines- * up vertically with the Name + Description stack in the create-agent- * form so the two read as a single visual row. */- size?: number;-}--/**- * Compact avatar picker — a single square that lives next to the Name- * input in the create-agent form. Mirrors the visual language of- * agent-detail-inspector.tsx (Camera overlay on hover, file input behind- * the scenes), so users who've configured an avatar elsewhere in the app- * recognise the affordance immediately.- *- * No avatar yet → dashed placeholder with an ImagePlus icon.- * Has avatar → image fills the square, hover dims it with a Camera- * overlay for "click to change". A small × in the corner- * clears the choice.- */-export function AvatarPicker({ value, onChange, size = 56 }: AvatarPickerProps) {- const { t } = useT("agents");- const fileInputRef = useRef<HTMLInputElement>(null);- const { upload, uploading } = useFileUpload(api);- const [previewError, setPreviewError] = useState(false);-- const handleFile = async (e: React.ChangeEvent<HTMLInputElement>) => {- const file = e.target.files?.[0];- if (!file) return;- e.target.value = ""; // allow re-selecting the same file- if (!file.type.startsWith("image/")) {- toast.error(t(($) => $.create_dialog.avatar.select_image_toast));- return;- }- try {- const result = await upload(file);- if (!result) return;- setPreviewError(false);- onChange(result.link);- } catch (err) {- toast.error(- err instanceof Error- ? err.message- : t(($) => $.create_dialog.avatar.upload_failed_toast),- );- }- };-- const hasValue = !!value && !previewError;- const dimensionStyle = { width: size, height: size };-- return (- <div className="relative shrink-0" style={dimensionStyle}>- <button- type="button"- onClick={() => fileInputRef.current?.click()}- disabled={uploading}- className={cn(- "group relative h-full w-full overflow-hidden rounded-lg outline-none transition-colors",- "focus-visible:ring-2 focus-visible:ring-ring",- hasValue- ? "border"- : "border border-dashed bg-muted/40 hover:bg-muted",- )}- aria-label={- hasValue- ? t(($) => $.create_dialog.avatar.change_aria)- : t(($) => $.create_dialog.avatar.upload_aria)- }- style={dimensionStyle}- >- {hasValue ? (- <img- src={resolvePublicFileUrl(value) ?? undefined}- alt=""- className="h-full w-full object-cover"- onError={() => setPreviewError(true)}- />- ) : (- <div className="flex h-full w-full items-center justify-center text-muted-foreground">- {uploading ? (- <Loader2 className="h-5 w-5 animate-spin" />- ) : (- <ImagePlus className="h-5 w-5" />- )}- </div>- )}-- {/* Hover overlay only when there's already an image — otherwise the- placeholder icon already invites the click. */}- {hasValue && (- <div className="absolute inset-0 flex items-center justify-center bg-black/40 opacity-0 transition-opacity group-hover:opacity-100">- {uploading ? (- <Loader2 className="h-4 w-4 animate-spin text-white" />- ) : (- <Camera className="h-4 w-4 text-white" />- )}- </div>- )}- </button>-- {/* Tiny X to clear, only shown when there's a value. Positioned just- outside the avatar's top-right corner so it doesn't cover the- image. */}- {hasValue && !uploading && (- <button- type="button"- onClick={(e) => {- e.stopPropagation();- onChange(null);- setPreviewError(false);- }}- className="absolute -right-1.5 -top-1.5 flex h-5 w-5 items-center justify-center rounded-full border bg-background text-muted-foreground shadow-sm transition-colors hover:bg-muted hover:text-foreground"- aria-label={t(($) => $.create_dialog.avatar.remove_aria)}- >- <X className="h-3 w-3" />- </button>- )}-- <input- ref={fileInputRef}- type="file"- accept="image/*"- className="hidden"- onChange={handleFile}- />- </div>- );-}diff --git a/packages/views/agents/components/create-agent-dialog.tsx b/packages/views/agents/components/create-agent-dialog.tsxindex 49754b8fab..9dcb1a5e02 100644--- a/packages/views/agents/components/create-agent-dialog.tsx+++ b/packages/views/agents/components/create-agent-dialog.tsx@@ -7,7 +7,7 @@ import { ModelDropdown } from "./model-dropdown";import { RuntimePicker, isRuntimeUsableForUser } from "./runtime-picker";import { InstructionsEditor } from "./instructions-editor";import { SkillMultiSelect } from "./skill-multi-select";-import { AvatarPicker } from "./avatar-picker";+import { AvatarUploadControl } from "../../common/avatar-upload-control";import { api } from "@multica/core/api";import { useWorkspaceId } from "@multica/core/hooks";import { useFeatureEnabled } from "@multica/core/config";@@ -326,7 +326,14 @@ export function CreateAgentDialog({same shape as detail-page header so the affordance isinstantly familiar. */}<div className="flex items-start gap-4">- <AvatarPicker value={avatarUrl} onChange={setAvatarUrl} size={64} />+ <AvatarUploadControl+ variant="agent"+ value={avatarUrl}+ name={name}+ size={64}+ onUploaded={setAvatarUrl}+ onClear={() => setAvatarUrl(null)}+ /><div className="flex-1 min-w-0 space-y-3"><div><Label className="text-xs text-muted-foreground">{t(($) => $.create_dialog.name_label)}</Label>diff --git a/packages/views/common/avatar-crop-dialog.tsx b/packages/views/common/avatar-crop-dialog.tsxnew file mode 100644index 0000000000..3f09c32c13--- /dev/null+++ b/packages/views/common/avatar-crop-dialog.tsx@@ -0,0 +1,233 @@+"use client";++import { useEffect, useState } from "react";+import Cropper, { type Area, type Point } from "react-easy-crop";+import { Loader2, Minus, Plus, RotateCw } from "lucide-react";+import { Button } from "@multica/ui/components/ui/button";+import { Slider } from "@multica/ui/components/ui/slider";+import {+ Dialog,+ DialogContent,+ DialogHeader,+ DialogTitle,+} from "@multica/ui/components/ui/dialog";+import { useT } from "../i18n";+import {+ AVATAR_OUTPUT_SIZE,+ blobToAvatarFile,+ getCroppedAvatarBlob,+ pickOutputType,+ type PixelCrop,+} from "./avatar-crop";++const MIN_ZOOM = 1;+const MAX_ZOOM = 3;+const ZOOM_STEP = 0.1;+const ROUNDED_SQUARE_CROP_AREA_STYLE = { borderRadius: "0.5rem" };++export type AvatarCropShape = "circle" | "square";++interface AvatarCropDialogProps {+ /** The picked source file. `null` keeps the dialog empty. */+ file: File | null;+ open: boolean;+ shape: AvatarCropShape;+ /** Parent's upload/save is in flight — locks the controls and blocks close. */+ busy?: boolean;+ onOpenChange: (open: boolean) => void;+ /** Fires with the cropped, compressed file. The parent uploads + persists. */+ onCropped: (file: File) => void;+}++/**+ * Avatar cropper. The image pans/zooms/rotates beneath a fixed crop window+ * (round for people, rounded-square for non-human actors); everything outside+ * the window is dimmed. Output is a square {@link AVATAR_OUTPUT_SIZE}px image —+ * the round/square mask is display-only, never baked into the pixels.+ *+ * Interaction (drag / zoom / rotate + the dim overlay) is delegated to+ * react-easy-crop; this component owns the chrome (header, zoom slider, rotate+ * / reset controls) and the encode/upload handoff.+ */+export function AvatarCropDialog({+ file,+ open,+ shape,+ busy = false,+ onOpenChange,+ onCropped,+}: AvatarCropDialogProps) {+ const { t } = useT("common");+ const [objectUrl, setObjectUrl] = useState<string | null>(null);+ const [crop, setCrop] = useState<Point>({ x: 0, y: 0 });+ const [zoom, setZoom] = useState(MIN_ZOOM);+ const [rotation, setRotation] = useState(0);+ const [croppedAreaPixels, setCroppedAreaPixels] = useState<PixelCrop | null>(+ null,+ );+ const [loadError, setLoadError] = useState(false);++ // One object URL per picked file, alive for the dialog's lifetime; reset the+ // transform so a new pick starts centered and unrotated.+ useEffect(() => {+ if (!file) {+ setObjectUrl(null);+ return;+ }+ const url = URL.createObjectURL(file);+ setObjectUrl(url);+ setCrop({ x: 0, y: 0 });+ setZoom(MIN_ZOOM);+ setRotation(0);+ setCroppedAreaPixels(null);+ setLoadError(false);+ return () => URL.revokeObjectURL(url);+ }, [file]);++ const clampZoom = (value: number) =>+ Math.min(MAX_ZOOM, Math.max(MIN_ZOOM, Math.round(value * 100) / 100));++ const resetTransform = () => {+ setCrop({ x: 0, y: 0 });+ setZoom(MIN_ZOOM);+ setRotation(0);+ };++ const handleConfirm = async () => {+ if (!objectUrl || !croppedAreaPixels || !file) return;+ const { type, quality } = pickOutputType();+ try {+ const blob = await getCroppedAvatarBlob(objectUrl, croppedAreaPixels, rotation, {+ output: AVATAR_OUTPUT_SIZE,+ type,+ quality,+ // JPEG has no alpha; give transparent/rotated corners a white bed+ // instead of the canvas default black.+ background: type === "image/jpeg" ? "#ffffff" : undefined,+ });+ onCropped(blobToAvatarFile(blob, file.name, type));+ } catch {+ setLoadError(true);+ }+ };++ const disabled = busy || !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);+ }}+ >+ <DialogContent showCloseButton={!busy} className="sm:max-w-md">+ <DialogHeader>+ <DialogTitle>{t(($) => $.avatar_crop.title)}</DialogTitle>+ </DialogHeader>++ <div className="relative aspect-square w-full overflow-hidden rounded-lg bg-neutral-900">+ {objectUrl && !loadError ? (+ <>+ <Cropper+ image={objectUrl}+ crop={crop}+ zoom={zoom}+ rotation={rotation}+ aspect={1}+ minZoom={MIN_ZOOM}+ maxZoom={MAX_ZOOM}+ cropShape={shape === "circle" ? "round" : "rect"}+ style={{+ cropAreaStyle:+ shape === "circle" ? undefined : ROUNDED_SQUARE_CROP_AREA_STYLE,+ }}+ showGrid={false}+ onCropChange={setCrop}+ onZoomChange={setZoom}+ onRotationChange={setRotation}+ onCropComplete={(_: Area, areaPixels: Area) =>+ setCroppedAreaPixels(areaPixels)+ }+ />+ <button+ type="button"+ onClick={() => setRotation((r) => (r + 90) % 360)}+ disabled={busy}+ 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"+ >+ <RotateCw className="h-4 w-4" />+ </button>+ </>+ ) : (+ <div className="flex h-full w-full items-center justify-center text-xs text-muted-foreground">+ {loadError+ ? t(($) => $.avatar_crop.load_failed)+ : t(($) => $.avatar_crop.loading)}+ </div>+ )}+ </div>++ <div className="flex items-center gap-3">+ <button+ type="button"+ onClick={() => setZoom((z) => clampZoom(z - ZOOM_STEP))}+ disabled={disabled}+ aria-label={t(($) => $.avatar_crop.zoom_out)}+ className="shrink-0 text-muted-foreground transition-colors hover:text-foreground disabled:opacity-40"+ >+ <Minus className="h-4 w-4" />+ </button>+ <Slider+ value={[zoom]}+ min={MIN_ZOOM}+ max={MAX_ZOOM}+ step={0.01}+ disabled={disabled}+ onValueChange={(value) =>+ setZoom((Array.isArray(value) ? value[0] : value) ?? MIN_ZOOM)+ }+ aria-label={t(($) => $.avatar_crop.zoom)}+ className="flex-1"+ />+ <button+ type="button"+ onClick={() => setZoom((z) => clampZoom(z + ZOOM_STEP))}+ disabled={disabled}+ aria-label={t(($) => $.avatar_crop.zoom_in)}+ className="shrink-0 text-muted-foreground transition-colors hover:text-foreground disabled:opacity-40"+ >+ <Plus className="h-4 w-4" />+ </button>+ </div>++ <div className="flex items-center justify-between">+ <Button variant="ghost" onClick={resetTransform} disabled={busy}>+ {t(($) => $.avatar_crop.reset)}+ </Button>+ <div className="flex gap-2">+ <Button+ variant="outline"+ onClick={() => onOpenChange(false)}+ disabled={busy}+ >+ {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>+ </div>+ </div>+ </DialogContent>+ </Dialog>+ );+}diff --git a/packages/views/common/avatar-crop.test.ts b/packages/views/common/avatar-crop.test.tsnew file mode 100644index 0000000000..6460ef7bab--- /dev/null+++ b/packages/views/common/avatar-crop.test.ts@@ -0,0 +1,38 @@+import { describe, it, expect } from "vitest";+import { blobToAvatarFile } from "./avatar-crop";++describe("blobToAvatarFile", () => {+ const blob = new Blob(["x"], { type: "image/webp" });++ it("maps the output type to the matching extension", () => {+ expect(blobToAvatarFile(blob, "photo.png", "image/webp").name).toBe(+ "photo.webp",+ );+ expect(blobToAvatarFile(blob, "photo.png", "image/jpeg").name).toBe(+ "photo.jpg",+ );+ expect(blobToAvatarFile(blob, "photo.gif", "image/png").name).toBe(+ "photo.png",+ );+ });++ it("strips only the final extension from the source name", () => {+ expect(blobToAvatarFile(blob, "my.avatar.jpeg", "image/webp").name).toBe(+ "my.avatar.webp",+ );+ expect(blobToAvatarFile(blob, "no-extension", "image/webp").name).toBe(+ "no-extension.webp",+ );+ });++ it("falls back to a stable base name when the source has none", () => {+ expect(blobToAvatarFile(blob, "", "image/jpeg").name).toBe("avatar.jpg");+ expect(blobToAvatarFile(blob, ".png", "image/jpeg").name).toBe("avatar.jpg");+ });++ it("carries the output mime type onto the File", () => {+ expect(blobToAvatarFile(blob, "photo.png", "image/webp").type).toBe(+ "image/webp",+ );+ });+});diff --git a/packages/views/common/avatar-crop.ts b/packages/views/common/avatar-crop.tsnew file mode 100644index 0000000000..15cac20676--- /dev/null+++ b/packages/views/common/avatar-crop.ts@@ -0,0 +1,150 @@+// Canvas rendering + encoding for the shared avatar cropper.+//+// react-easy-crop owns the interactive geometry (pan / zoom / rotate) and hands+// back the crop rectangle in source-image pixels via `onCropComplete`. This+// module turns that rectangle into a fixed-size square, compressed avatar file.++/** Square side of the encoded avatar. Avatars never need the original bitmap. */+export const AVATAR_OUTPUT_SIZE = 512;++const AVATAR_QUALITY = 0.85;++/** react-easy-crop's `croppedAreaPixels` shape (source-image px). */+export interface PixelCrop {+ x: number;+ y: number;+ width: number;+ height: number;+}++let webpEncodeSupport: boolean | null = null;++/**+ * Whether the browser can *encode* WebP via canvas. Safari < 17 decodes WebP+ * but cannot encode it, silently emitting PNG from toDataURL — so we probe the+ * data URL's mime rather than assuming.+ */+export function supportsWebpEncode(): boolean {+ if (webpEncodeSupport !== null) return webpEncodeSupport;+ try {+ const canvas = document.createElement("canvas");+ canvas.width = 1;+ canvas.height = 1;+ webpEncodeSupport = canvas+ .toDataURL("image/webp")+ .startsWith("data:image/webp");+ } catch {+ webpEncodeSupport = false;+ }+ return webpEncodeSupport;+}++/** Preferred output type: WebP (keeps alpha, smaller) with a JPEG fallback. */+export function pickOutputType(): { type: string; quality: number } {+ return supportsWebpEncode()+ ? { type: "image/webp", quality: AVATAR_QUALITY }+ : { type: "image/jpeg", quality: AVATAR_QUALITY };+}++/** Wrap an encoded blob in a File, swapping the source extension for the output's. */+export function blobToAvatarFile(+ blob: Blob,+ sourceName: string,+ type: string,+): File {+ const ext = type === "image/webp" ? "webp" : type === "image/png" ? "png" : "jpg";+ const base = sourceName.replace(/\.[^./\\]+$/, "") || "avatar";+ return new File([blob], `${base}.${ext}`, { type });+}++function canvasToBlob(+ canvas: HTMLCanvasElement,+ type: string,+ quality: number,+): Promise<Blob> {+ return new Promise((resolve, reject) => {+ canvas.toBlob(+ (blob) => (blob ? resolve(blob) : reject(new Error("Canvas is empty"))),+ type,+ quality,+ );+ });+}++function loadImage(src: string): Promise<HTMLImageElement> {+ return new Promise((resolve, reject) => {+ const image = new Image();+ image.addEventListener("load", () => resolve(image));+ image.addEventListener("error", () => reject(new Error("Could not load image")));+ image.src = src;+ });+}++function toRadians(degrees: number): number {+ return (degrees * Math.PI) / 180;+}++/** Bounding box of an image after rotation, in px. */+function rotatedBoundingBox(width: number, height: number, degrees: number) {+ const rad = toRadians(degrees);+ return {+ width: Math.abs(Math.cos(rad) * width) + Math.abs(Math.sin(rad) * height),+ height: Math.abs(Math.sin(rad) * width) + Math.abs(Math.cos(rad) * height),+ };+}++export interface RenderOptions {+ output: number;+ type: string;+ quality: number;+ /** Fill color drawn behind the image, for opaque formats (JPEG). */+ background?: string;+}++/**+ * Draw the (possibly rotated) crop region into a square canvas and encode it.+ * `pixelCrop` is react-easy-crop's `croppedAreaPixels`, expressed in the+ * rotated-image bounding-box coordinate space — so we first rotate the whole+ * image into a bounding-box canvas, then sample the crop rect from it.+ */+export async function getCroppedAvatarBlob(+ imageSrc: string,+ pixelCrop: PixelCrop,+ rotation: number,+ options: RenderOptions,+): Promise<Blob> {+ const image = await loadImage(imageSrc);+ const bBox = rotatedBoundingBox(image.width, image.height, rotation);++ const rotated = document.createElement("canvas");+ rotated.width = Math.round(bBox.width);+ rotated.height = Math.round(bBox.height);+ const rctx = rotated.getContext("2d");+ if (!rctx) throw new Error("Canvas 2D context unavailable");+ rctx.translate(rotated.width / 2, rotated.height / 2);+ rctx.rotate(toRadians(rotation));+ rctx.drawImage(image, -image.width / 2, -image.height / 2);++ const out = document.createElement("canvas");+ out.width = options.output;+ out.height = options.output;+ const octx = out.getContext("2d");+ if (!octx) throw new Error("Canvas 2D context unavailable");+ octx.imageSmoothingQuality = "high";+ if (options.background) {+ octx.fillStyle = options.background;+ octx.fillRect(0, 0, options.output, options.output);+ }+ octx.drawImage(+ rotated,+ pixelCrop.x,+ pixelCrop.y,+ pixelCrop.width,+ pixelCrop.height,+ 0,+ 0,+ options.output,+ options.output,+ );+ return canvasToBlob(out, options.type, options.quality);+}diff --git a/packages/views/common/avatar-upload-control.tsx b/packages/views/common/avatar-upload-control.tsxnew file mode 100644index 0000000000..ead3ef865a--- /dev/null+++ b/packages/views/common/avatar-upload-control.tsx@@ -0,0 +1,225 @@+"use client";++import { useRef, useState } from "react";+import { Bot, Camera, Loader2, Users, X } from "lucide-react";+import { toast } from "sonner";+import { api } from "@multica/core/api";+import { useFileUpload } from "@multica/core/hooks/use-file-upload";+import { resolvePublicFileUrl } from "@multica/core/workspace/avatar-url";+import { cn } from "@multica/ui/lib/utils";+import { useT } from "../i18n";+import { AvatarCropDialog, type AvatarCropShape } from "./avatar-crop-dialog";++export type AvatarUploadVariant = "user" | "agent" | "squad" | "workspace";++interface AvatarUploadControlProps {+ /** Current avatar URL, raw (unresolved). `null` renders the empty state. */+ value: string | null;+ /** Drives display shape and the empty-state fallback icon/initials. */+ variant: AvatarUploadVariant;+ /** Name used for initials / first-letter fallback and the image alt. */+ name?: string;+ /** Pixel side of the square/circle. Defaults to 64. */+ size?: number;+ disabled?: boolean;+ /**+ * Fires with the uploaded file URL after a successful crop + upload. The+ * parent persists it (updateMe / updateWorkspace / updateAgent /+ * updateSquad, or stashing it for a create call). The crop dialog stays in+ * its busy state until this resolves, then closes.+ */+ onUploaded: (url: string) => void | Promise<unknown>;+ /**+ * When provided, shows a small clear affordance. Used by create flows to+ * drop a not-yet-persisted choice; edit flows omit it (removing a saved+ * avatar is out of scope).+ */+ onClear?: () => void;+ className?: string;+ ariaLabel?: string;+}++// Humans read as a circle; non-human actors (agent, squad, workspace) get a+// rounded square so they don't read as a single person. Matches the shared+// display avatar (packages/ui/components/common/actor-avatar.tsx).+const VARIANT_SHAPE: Record<AvatarUploadVariant, AvatarCropShape> = {+ user: "circle",+ agent: "square",+ squad: "square",+ workspace: "square",+};++function initialsOf(name: string): string {+ return name+ .split(" ")+ .map((word) => word[0])+ .join("")+ .toUpperCase()+ .slice(0, 2);+}++function AvatarFallback({+ variant,+ name,+ size,+}: {+ variant: AvatarUploadVariant;+ name: string;+ size: number;+}) {+ if (variant === "agent") {+ return <Bot style={{ width: size * 0.5, height: size * 0.5 }} />;+ }+ if (variant === "squad") {+ return <Users style={{ width: size * 0.5, height: size * 0.5 }} />;+ }+ const text =+ variant === "workspace"+ ? name.charAt(0).toUpperCase()+ : initialsOf(name);+ return (+ <span className="font-semibold" style={{ fontSize: size * 0.4 }}>+ {text}+ </span>+ );+}++/**+ * Shared click-to-upload avatar control for web/desktop. Renders the current+ * avatar with a hover "change" affordance; on pick it opens {@link+ * AvatarCropDialog} for reposition/zoom, then uploads the cropped image+ * through the existing `/api/upload-file` chain and hands the URL back via+ * `onUploaded`. Business persistence stays with the caller.+ */+export function AvatarUploadControl({+ value,+ variant,+ name = "",+ size = 64,+ disabled = false,+ onUploaded,+ onClear,+ className,+ ariaLabel,+}: AvatarUploadControlProps) {+ const { t } = useT("common");+ const { upload } = useFileUpload(api);+ const fileInputRef = useRef<HTMLInputElement>(null);+ const [pickedFile, setPickedFile] = useState<File | null>(null);+ const [dialogOpen, setDialogOpen] = useState(false);+ const [busy, setBusy] = useState(false);+ const [previewError, setPreviewError] = useState(false);++ const resolved = value ? resolvePublicFileUrl(value) : null;+ const hasImage = !!resolved && !previewError;+ const shape = VARIANT_SHAPE[variant];+ const radiusClass = shape === "circle" ? "rounded-full" : "rounded-lg";++ const handlePick = (e: React.ChangeEvent<HTMLInputElement>) => {+ const file = e.target.files?.[0];+ e.target.value = ""; // allow re-selecting the same file+ if (!file) return;+ if (!file.type.startsWith("image/")) {+ toast.error(t(($) => $.avatar_upload.select_image));+ return;+ }+ setPreviewError(false);+ setPickedFile(file);+ setDialogOpen(true);+ };++ const handleCropped = async (cropped: File) => {+ setBusy(true);+ try {+ const result = await upload(cropped);+ if (!result) return;+ await onUploaded(result.link);+ setDialogOpen(false);+ setPickedFile(null);+ toast.success(t(($) => $.avatar_upload.updated));+ } catch (err) {+ toast.error(+ err instanceof Error ? err.message : t(($) => $.avatar_upload.failed),+ );+ } finally {+ setBusy(false);+ }+ };++ return (+ <div className="relative shrink-0" style={{ width: size, height: size }}>+ <button+ type="button"+ onClick={() => fileInputRef.current?.click()}+ disabled={disabled || busy}+ aria-label={ariaLabel ?? t(($) => $.avatar_upload.change)}+ className={cn(+ "group relative h-full w-full overflow-hidden bg-muted text-muted-foreground outline-none",+ "flex items-center justify-center",+ "focus-visible:ring-2 focus-visible:ring-ring",+ "disabled:cursor-not-allowed disabled:opacity-60",+ radiusClass,+ className,+ )}+ style={{ width: size, height: size }}+ >+ {hasImage ? (+ <img+ src={resolved ?? undefined}+ alt={name}+ className="h-full w-full object-cover"+ onError={() => setPreviewError(true)}+ />+ ) : (+ <AvatarFallback variant={variant} name={name} size={size} />+ )}++ {!disabled && (+ <div className="absolute inset-0 flex items-center justify-center bg-black/40 opacity-0 transition-opacity group-hover:opacity-100">+ {busy ? (+ <Loader2 className="h-5 w-5 animate-spin text-white" />+ ) : (+ <Camera className="h-5 w-5 text-white" />+ )}+ </div>+ )}+ </button>++ {onClear && hasImage && !busy && !disabled && (+ <button+ type="button"+ onClick={(e) => {+ e.stopPropagation();+ setPreviewError(false);+ onClear();+ }}+ className="absolute -right-1.5 -top-1.5 flex h-5 w-5 items-center justify-center rounded-full border bg-background text-muted-foreground shadow-sm transition-colors hover:bg-muted hover:text-foreground"+ aria-label={t(($) => $.avatar_upload.remove)}+ >+ <X className="h-3 w-3" />+ </button>+ )}++ <input+ ref={fileInputRef}+ type="file"+ accept="image/*"+ className="hidden"+ onChange={handlePick}+ />++ <AvatarCropDialog+ file={pickedFile}+ open={dialogOpen}+ shape={shape}+ busy={busy}+ onOpenChange={(next) => {+ if (busy) return;+ setDialogOpen(next);+ if (!next) setPickedFile(null);+ }}+ onCropped={handleCropped}+ />+ </div>+ );+}diff --git a/packages/views/locales/en/common.json b/packages/views/locales/en/common.jsonindex c9c548a3e6..2fe0739d5e 100644--- a/packages/views/locales/en/common.json+++ b/packages/views/locales/en/common.json@@ -1,4 +1,24 @@{+ "avatar_upload": {+ "change": "Change avatar",+ "remove": "Remove",+ "select_image": "Please choose an image file.",+ "updated": "Avatar updated",+ "failed": "Failed to upload avatar"+ },+ "avatar_crop": {+ "title": "Edit avatar",+ "zoom": "Zoom",+ "zoom_in": "Zoom in",+ "zoom_out": "Zoom out",+ "rotate": "Rotate",+ "reset": "Reset",+ "cancel": "Cancel",+ "apply": "Save",+ "uploading": "Uploading…",+ "loading": "Loading…",+ "load_failed": "Couldn't load image"+ },"save": "Save","cancel": "Cancel","delete": "Delete",diff --git a/packages/views/locales/ja/common.json b/packages/views/locales/ja/common.jsonindex ffd486890e..06e8b2c1a9 100644--- a/packages/views/locales/ja/common.json+++ b/packages/views/locales/ja/common.json@@ -1,4 +1,24 @@{+ "avatar_upload": {+ "change": "アバターを変更",+ "remove": "削除",+ "select_image": "画像ファイルを選択してください。",+ "updated": "アバターを更新しました",+ "failed": "アバターのアップロードに失敗しました"+ },+ "avatar_crop": {+ "title": "アバターを編集",+ "zoom": "ズーム",+ "zoom_in": "拡大",+ "zoom_out": "縮小",+ "rotate": "回転",+ "reset": "リセット",+ "cancel": "キャンセル",+ "apply": "保存",+ "uploading": "アップロード中…",+ "loading": "読み込み中…",+ "load_failed": "画像を読み込めませんでした"+ },"save": "保存","cancel": "キャンセル","delete": "削除",diff --git a/packages/views/locales/ko/common.json b/packages/views/locales/ko/common.jsonindex 90d08d0a7b..abbaa784de 100644--- a/packages/views/locales/ko/common.json+++ b/packages/views/locales/ko/common.json@@ -1,4 +1,24 @@{+ "avatar_upload": {+ "change": "아바타 변경",+ "remove": "제거",+ "select_image": "이미지 파일을 선택하세요.",+ "updated": "아바타를 업데이트했어요",+ "failed": "아바타 업로드에 실패했어요"+ },+ "avatar_crop": {+ "title": "아바타 편집",+ "zoom": "확대/축소",+ "zoom_in": "확대",+ "zoom_out": "축소",+ "rotate": "회전",+ "reset": "초기화",+ "cancel": "취소",+ "apply": "저장",+ "uploading": "업로드 중…",+ "loading": "불러오는 중…",+ "load_failed": "이미지를 불러오지 못했어요"+ },"save": "저장","cancel": "취소","delete": "삭제",diff --git a/packages/views/locales/zh-Hans/common.json b/packages/views/locales/zh-Hans/common.jsonindex ae94144bbc..f753a09288 100644--- a/packages/views/locales/zh-Hans/common.json+++ b/packages/views/locales/zh-Hans/common.json@@ -1,4 +1,24 @@{+ "avatar_upload": {+ "change": "更换头像",+ "remove": "移除",+ "select_image": "请选择一张图片文件。",+ "updated": "头像已更新",+ "failed": "头像上传失败"+ },+ "avatar_crop": {+ "title": "编辑头像",+ "zoom": "缩放",+ "zoom_in": "放大",+ "zoom_out": "缩小",+ "rotate": "旋转",+ "reset": "重置",+ "cancel": "取消",+ "apply": "保存",+ "uploading": "上传中…",+ "loading": "加载中…",+ "load_failed": "图片加载失败"+ },"save": "保存","cancel": "取消","delete": "删除",diff --git a/packages/views/modals/create-squad.test.tsx b/packages/views/modals/create-squad.test.tsxindex 772195fd4c..1b8d75db31 100644--- a/packages/views/modals/create-squad.test.tsx+++ b/packages/views/modals/create-squad.test.tsx@@ -86,19 +86,19 @@ vi.mock("../common/actor-avatar", () => ({),}));-vi.mock("../agents/components/avatar-picker", () => ({- AvatarPicker: ({+vi.mock("../common/avatar-upload-control", () => ({+ AvatarUploadControl: ({value,- onChange,+ onUploaded,}: {value: string | null;- onChange: (v: string | null) => void;+ onUploaded: (v: string) => void;}) => (<buttontype="button"data-testid="avatar-picker"data-value={value ?? ""}- onClick={() => onChange("https://example.com/avatar.png")}+ onClick={() => onUploaded("https://example.com/avatar.png")}>avatar</button>diff --git a/packages/views/modals/create-squad.tsx b/packages/views/modals/create-squad.tsxindex 164ec488bf..8f2717c602 100644--- a/packages/views/modals/create-squad.tsx+++ b/packages/views/modals/create-squad.tsx@@ -34,7 +34,7 @@ import { toast } from "sonner";import { useNavigation } from "../navigation";import { ActorAvatar } from "../common/actor-avatar";-import { AvatarPicker } from "../agents/components/avatar-picker";+import { AvatarUploadControl } from "../common/avatar-upload-control";import { CharCounter } from "../agents/components/char-counter";import {PickerEmpty,@@ -157,7 +157,14 @@ export function CreateSquadModal({ onClose }: { onClose: () => void }) {{/* Identity row mirrors CreateAgentDialog so the two creates readas siblings — avatar (left) + name/description stack (right). */}<div className="flex items-start gap-4">- <AvatarPicker value={avatarUrl} onChange={setAvatarUrl} size={64} />+ <AvatarUploadControl+ variant="squad"+ value={avatarUrl}+ name={name}+ size={64}+ onUploaded={setAvatarUrl}+ onClear={() => setAvatarUrl(null)}+ /><div className="flex-1 min-w-0 space-y-3"><div><Label className="text-xs text-muted-foreground">diff --git a/packages/views/package.json b/packages/views/package.jsonindex 2e496aa33a..9855631213 100644--- a/packages/views/package.json+++ b/packages/views/package.json@@ -92,6 +92,7 @@"mermaid": "catalog:","motion": "^12.38.0","pinyin-pro": "3.26.0",+ "react-easy-crop": "^6.2.0","react-markdown": "^10.1.0","react-qr-code": "catalog:","react-resizable-panels": "^4.7.5",diff --git a/packages/views/settings/components/account-tab.tsx b/packages/views/settings/components/account-tab.tsxindex e0a5fd58b8..2304e6ae54 100644--- a/packages/views/settings/components/account-tab.tsx+++ b/packages/views/settings/components/account-tab.tsx@@ -1,7 +1,7 @@"use client";-import { useEffect, useRef, useState } from "react";-import { Camera, Loader2, Save } from "lucide-react";+import { useEffect, useState } from "react";+import { Save } from "lucide-react";import { Input } from "@multica/ui/components/ui/input";import { Label } from "@multica/ui/components/ui/label";import { Button } from "@multica/ui/components/ui/button";@@ -10,8 +10,7 @@ import { Textarea } from "@multica/ui/components/ui/textarea";import { toast } from "sonner";import { useAuthStore } from "@multica/core/auth";import { api } from "@multica/core/api";-import { resolvePublicFileUrl } from "@multica/core/workspace/avatar-url";-import { useFileUpload } from "@multica/core/hooks/use-file-upload";+import { AvatarUploadControl } from "../../common/avatar-upload-control";import { useT } from "../../i18n";// Mirror server/internal/handler/auth.go:MaxProfileDescriptionLen. Counted in@@ -30,8 +29,6 @@ export function AccountTab() {user?.profile_description ?? "",);const [profileSaving, setProfileSaving] = useState(false);- const { upload, uploading } = useFileUpload(api);- const fileInputRef = useRef<HTMLInputElement>(null);useEffect(() => {setProfileName(user?.name ?? "");@@ -40,29 +37,6 @@ export function AccountTab() {const descriptionTooLong = profileDescription.length > MAX_PROFILE_DESCRIPTION_LEN;- const initials = (user?.name ?? "")- .split(" ")- .map((w) => w[0])- .join("")- .toUpperCase()- .slice(0, 2);-- const handleAvatarUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {- const file = e.target.files?.[0];- if (!file) return;- // Reset input so the same file can be re-selected- e.target.value = "";- try {- const result = await upload(file);- if (!result) return;- const updated = await api.updateMe({ avatar_url: result.link });- setUser(updated);- toast.success(t(($) => $.account.toast_avatar_updated));- } catch (err) {- toast.error(err instanceof Error ? err.message : t(($) => $.account.toast_avatar_failed));- }- };-const handleProfileSave = async () => {if (descriptionTooLong) return;setProfileSaving(true);@@ -89,37 +63,15 @@ export function AccountTab() {<CardContent className="space-y-4">{/* Avatar upload */}<div className="flex items-center gap-4">- <button- type="button"- className="group relative h-16 w-16 shrink-0 rounded-full bg-muted overflow-hidden focus:outline-none focus-visible:ring-2 focus-visible:ring-ring"- onClick={() => fileInputRef.current?.click()}- disabled={uploading}- >- {user?.avatar_url ? (- <img- src={resolvePublicFileUrl(user.avatar_url) ?? undefined}- alt={user.name}- className="h-full w-full object-cover"- />- ) : (- <span className="flex h-full w-full items-center justify-center text-lg font-semibold text-muted-foreground">- {initials}- </span>- )}- <div className="absolute inset-0 flex items-center justify-center bg-black/40 opacity-0 transition-opacity group-hover:opacity-100">- {uploading ? (- <Loader2 className="h-5 w-5 animate-spin text-white" />- ) : (- <Camera className="h-5 w-5 text-white" />- )}- </div>- </button>- <input- ref={fileInputRef}- type="file"- accept="image/*"- className="hidden"- onChange={handleAvatarUpload}+ <AvatarUploadControl+ variant="user"+ value={user?.avatar_url ?? null}+ name={user?.name ?? ""}+ size={64}+ onUploaded={async (url) => {+ const updated = await api.updateMe({ avatar_url: url });+ setUser(updated);+ }}/><div className="text-xs text-muted-foreground">{t(($) => $.account.click_avatar_hint)}diff --git a/packages/views/settings/components/workspace-tab.tsx b/packages/views/settings/components/workspace-tab.tsxindex d26e244824..1edd13330e 100644--- a/packages/views/settings/components/workspace-tab.tsx+++ b/packages/views/settings/components/workspace-tab.tsx@@ -1,7 +1,7 @@"use client";-import { useEffect, useRef, useState } from "react";-import { Camera, Loader2, Save, LogOut } from "lucide-react";+import { useEffect, useState } from "react";+import { Save, LogOut } from "lucide-react";import { Input } from "@multica/ui/components/ui/input";import { Textarea } from "@multica/ui/components/ui/textarea";import { Label } from "@multica/ui/components/ui/label";@@ -28,8 +28,6 @@ import {} from "@multica/core/workspace/queries";import { issueKeys } from "@multica/core/issues/queries";import { api } from "@multica/core/api";-import { useFileUpload } from "@multica/core/hooks/use-file-upload";-import { resolvePublicFileUrl } from "@multica/core/workspace/avatar-url";import {resolvePostAuthDestination,useCurrentWorkspace,@@ -37,6 +35,7 @@ import {} from "@multica/core/paths";import { setCurrentWorkspace } from "@multica/core/platform";import type { Workspace } from "@multica/core/types";+import { AvatarUploadControl } from "../../common/avatar-upload-control";import { useNavigation } from "../../navigation";import { DeleteWorkspaceDialog } from "./delete-workspace-dialog";import { useT } from "../../i18n";@@ -198,28 +197,6 @@ export function WorkspaceTab() {void performSave(false);};- const fileInputRef = useRef<HTMLInputElement>(null);- const { upload, uploading } = useFileUpload(api);-- const handleLogoUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {- if (!workspace) return;- const file = e.target.files?.[0];- if (!file) return;- // Reset input so the same file can be re-selected- e.target.value = "";- try {- const result = await upload(file);- if (!result) return;- const updated = await api.updateWorkspace(workspace.id, { avatar_url: result.link });- qc.setQueryData(workspaceKeys.list(), (old: Workspace[] | undefined) =>- old?.map((ws) => (ws.id === updated.id ? updated : ws)),- );- toast.success(t(($) => $.workspace.toast_logo_updated));- } catch (err) {- toast.error(err instanceof Error ? err.message : t(($) => $.workspace.toast_logo_failed));- }- };-const handleLeaveWorkspace = () => {if (!workspace) return;setConfirmAction({@@ -263,8 +240,6 @@ export function WorkspaceTab() {if (!workspace) return null;- const logoUrl = resolvePublicFileUrl(workspace.avatar_url);-return (<div className="space-y-8">{/* Workspace settings */}@@ -274,40 +249,23 @@ export function WorkspaceTab() {<Card><CardContent className="space-y-3"><div className="flex items-center gap-4">- <button- type="button"- className="group relative h-16 w-16 shrink-0 overflow-hidden rounded-md bg-muted focus:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50"- onClick={() => fileInputRef.current?.click()}- disabled={uploading || !canManageWorkspace}- aria-label={t(($) => $.workspace.change_logo_aria)}- >- {logoUrl ? (- <img- src={logoUrl}- alt={workspace.name}- className="h-full w-full object-cover"- />- ) : (- <span className="flex h-full w-full items-center justify-center text-lg font-semibold text-muted-foreground">- {workspace.name.charAt(0).toUpperCase()}- </span>- )}- {canManageWorkspace && (- <div className="absolute inset-0 flex items-center justify-center bg-black/40 opacity-0 transition-opacity group-hover:opacity-100">- {uploading ? (- <Loader2 className="h-5 w-5 animate-spin text-white" />- ) : (- <Camera className="h-5 w-5 text-white" />- )}- </div>- )}- </button>- <input- ref={fileInputRef}- type="file"- accept="image/png,image/jpeg,image/webp"- className="hidden"- onChange={handleLogoUpload}+ <AvatarUploadControl+ variant="workspace"+ value={workspace.avatar_url ?? null}+ name={workspace.name}+ size={64}+ disabled={!canManageWorkspace}+ ariaLabel={t(($) => $.workspace.change_logo_aria)}+ onUploaded={async (url) => {+ const updated = await api.updateWorkspace(workspace.id, {+ avatar_url: url,+ });+ qc.setQueryData(+ workspaceKeys.list(),+ (old: Workspace[] | undefined) =>+ old?.map((ws) => (ws.id === updated.id ? updated : ws)),+ );+ }}/><div className="text-xs text-muted-foreground">{t(($) => $.workspace.click_logo_hint)}diff --git a/packages/views/squads/components/squad-detail-page.tsx b/packages/views/squads/components/squad-detail-page.tsxindex 92d5269542..a960c08a25 100644--- a/packages/views/squads/components/squad-detail-page.tsx+++ b/packages/views/squads/components/squad-detail-page.tsx@@ -1,13 +1,12 @@"use client";-import { useEffect, useMemo, useRef, useState, type ReactNode } from "react";+import { useEffect, useMemo, useState, type ReactNode } from "react";import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";import { api } from "@multica/core/api";import { useAuthStore } from "@multica/core/auth";import { useCurrentWorkspace, useWorkspacePaths } from "@multica/core/paths";import { useWorkspaceId } from "@multica/core/hooks";import { resolvePublicFileUrl } from "@multica/core/workspace/avatar-url";-import { useFileUpload } from "@multica/core/hooks/use-file-upload";import { isImeComposing } from "@multica/core/utils";import { useTimeAgo } from "../../i18n";import { agentListOptions, memberListOptions, squadMemberStatusOptions, workspaceKeys } from "@multica/core/workspace/queries";@@ -17,7 +16,7 @@ import { useNavigation } from "../../navigation";import { AppLink } from "../../navigation";import { BreadcrumbHeader } from "../../layout/breadcrumb-header";import { PageHeader } from "../../layout/page-header";-import { Users, Plus, Trash2, ArrowUpRight, Crown, Camera, Loader2, Pencil, FileText, Save } from "lucide-react";+import { Users, Plus, Trash2, ArrowUpRight, Crown, Loader2, Pencil, FileText, Save } from "lucide-react";import { Button } from "@multica/ui/components/ui/button";import { Input } from "@multica/ui/components/ui/input";import { Label } from "@multica/ui/components/ui/label";@@ -52,6 +51,7 @@ import {} from "@multica/ui/components/ui/alert-dialog";import { ActorAvatar as ActorAvatarBase } from "@multica/ui/components/common/actor-avatar";import { ActorAvatar } from "../../common/actor-avatar";+import { AvatarUploadControl } from "../../common/avatar-upload-control";import { ContentEditor } from "../../editor/content-editor";import {PickerItem,@@ -259,7 +259,6 @@ export function SquadDetailPage() {leaderName={getEntityName("agent", squad.leader_id)}creatorName={getEntityName("member", squad.creator_id)}canManage={canManage}- uploadingAvatar={updateSquadMut.isPending}onUploadAvatar={(url) => updateSquadMut.mutateAsync({ avatar_url: url })}onRename={async (next) => { await updateSquadMut.mutateAsync({ name: next.trim() }); }}onUpdateDescription={async (next) => { await updateSquadMut.mutateAsync({ description: next }); }}@@ -396,81 +395,9 @@ function SquadHeaderAvatar({ squad, initials }: { squad: Squad; initials: string);}-// Large click-to-upload avatar editor. Mirrors AvatarEditor in-// agent-detail-inspector.tsx — square (rounded-md) treatment is reserved-// for non-human actors (agent, squad), circles for humans.-function SquadAvatarEditor({- squad,- initials,- uploading,- onUpload,-}: {- squad: Squad;- initials: string;- uploading: boolean;- onUpload: (url: string) => Promise<unknown>;-}) {- const fileInputRef = useRef<HTMLInputElement>(null);- const { upload, uploading: fileUploading } = useFileUpload(api);- const busy = uploading || fileUploading;-- const handleFile = async (e: React.ChangeEvent<HTMLInputElement>) => {- const file = e.target.files?.[0];- if (!file) return;- e.target.value = "";- try {- const result = await upload(file);- if (!result) return;- await onUpload(result.link);- toast.success("Avatar updated");- } catch (err) {- toast.error(err instanceof Error ? err.message : "Failed to upload avatar");- }- };-- return (- <>- <button- type="button"- className="group relative h-16 w-16 shrink-0 overflow-hidden rounded-lg bg-muted focus:outline-none focus-visible:ring-2 focus-visible:ring-ring"- onClick={() => fileInputRef.current?.click()}- disabled={busy}- aria-label="Change squad avatar"- >- {squad.avatar_url ? (- <ActorAvatarBase- name={squad.name}- initials={initials}- avatarUrl={resolvePublicFileUrl(squad.avatar_url)}- size={64}- className="rounded-none"- />- ) : (- <div className="flex h-full w-full items-center justify-center text-muted-foreground">- <Users className="h-7 w-7" />- </div>- )}- <div className="absolute inset-0 flex items-center justify-center bg-black/40 opacity-0 transition-opacity group-hover:opacity-100">- {busy ? (- <Loader2 className="h-4 w-4 animate-spin text-white" />- ) : (- <Camera className="h-4 w-4 text-white" />- )}- </div>- </button>- <input- ref={fileInputRef}- type="file"- accept="image/*"- className="hidden"- onChange={handleFile}- />- </>- );-}-// Read-only 64px avatar for viewers who can't manage the squad — same visual-// as SquadAvatarEditor's resting state but without the click/upload affordance.+// as the editable control's resting state but without the click/upload+// affordance.function SquadStaticAvatar({ squad, initials }: { squad: Squad; initials: string }) {return (<div className="h-16 w-16 shrink-0 overflow-hidden rounded-lg bg-muted">@@ -837,7 +764,6 @@ function SquadDetailInspector({leaderName,creatorName,canManage,- uploadingAvatar,onUploadAvatar,onRename,onUpdateDescription,@@ -850,7 +776,6 @@ function SquadDetailInspector({// no rename/description popovers) — the viewer can read the squad but not// edit it. Mirrors the agent inspector's `canEdit` read-only treatment.canManage: boolean;- uploadingAvatar: boolean;onUploadAvatar: (url: string) => Promise<unknown>;onRename: (next: string) => Promise<void>;onUpdateDescription: (next: string) => Promise<void>;@@ -870,11 +795,12 @@ function SquadDetailInspector({<div className="flex flex-col gap-3 border-b px-5 pb-5 pt-5">{canManage ? (<>- <SquadAvatarEditor- squad={squad}- initials={initials}- uploading={uploadingAvatar}- onUpload={onUploadAvatar}+ <AvatarUploadControl+ variant="squad"+ value={squad.avatar_url ?? null}+ name={squad.name}+ size={64}+ onUploaded={onUploadAvatar}/><div className="flex flex-col gap-1"><SquadNameEditor value={squad.name} onSave={onRename} />diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 3e0ac8a765..6038bcda56 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -1077,6 +1077,9 @@ importers:react-dom:specifier: 'catalog:'version: 19.2.3([email protected])+ react-easy-crop:+ specifier: ^6.2.0react-i18next:specifier: 'catalog:'version: 17.0.6([email protected]([email protected]))([email protected]([email protected]))([email protected])([email protected])@@ -8407,6 +8410,9 @@ packages:resolution: {integrity: sha512-DlL+XwOy3NxAQ8xuC0okPgK46iuVNAK01YN7RueYBqqFeGsBjV9XmCAzAdgt+667bCl5kPh9EqKKDwnaPG1I7A==}engines: {node: '>=10'}+ resolution: {integrity: sha512-1OnlAPZ3zgrk8B91HyRj+eVv+kS5u+Z0SCsak6Xil/kmgEia50ga7zfkumayonZrImffAxPU/5WcyGhzetHNPA==}+resolution: {integrity: sha512-sHGJy8sOC1YraBywpzQlIKBE4pBbGbiF95U6Auspzyem956E0+FtDtsx1ZxlOJkQCZ1AFXAY/yuvtFYrOxF+Bw==}engines: {node: ^16.14.0 || >=18.0.0}@@ -8996,6 +9002,12 @@ packages:peerDependencies:react: ^19.2.3+ resolution: {integrity: sha512-8CEes7M8UkNoRPaz/krm70xMTbpar07crz/OrPSJwdGopV6lPcqdEmamDYTXgsqukb/1e2fbFd9/mROi8Qkp+A==}+ peerDependencies:+ react: '>=16.4.0'+ react-dom: '>=16.4.0'+resolution: {integrity: sha512-nsO+KSNgo1SbJqJEYRE9ERzo7YtYbou/OqjSQKxV7jcKox7+usiUVZOAC+XnDOABXggQTno0Y1CpVnuWEc1boQ==}@@ -19685,6 +19697,8 @@ snapshots:+ [email protected]: {}+dependencies:hosted-git-info: 7.0.2@@ -20349,6 +20363,12 @@ snapshots:react: 19.2.3scheduler: 0.27.0+ dependencies:+ normalize-wheel: 1.0.1+ react: 19.2.3+ react-dom: 19.2.3([email protected])+