Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat(community): user/bot avatar upload with crop & zoom

Gusd920ff661408
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index d3e6ddb71..9d9d6aad5 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -420,6 +420,9 @@ importers:
react-dom:
specifier: 19.2.7
version: 19.2.7([email protected])
+ react-easy-crop:
+ specifier: ^6.1.0
react-resizable-panels:
specifier: ^4.12.1
@@ -7054,6 +7057,9 @@ packages:
resolution: {integrity: sha512-Uzmd6LXpouKo8EUK68IjH4+E01w/hXyV3R3g/geCJo+rXLNfh1xucB+LOzYEOQPSiUK3h/xZf0cQGcSsmyL2Og==}
engines: {node: '>=18'}
+ resolution: {integrity: sha512-1OnlAPZ3zgrk8B91HyRj+eVv+kS5u+Z0SCsak6Xil/kmgEia50ga7zfkumayonZrImffAxPU/5WcyGhzetHNPA==}
+
resolution: {integrity: sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw==}
engines: {node: '>=8'}
@@ -7476,6 +7482,12 @@ packages:
peerDependencies:
react: ^19.2.7
+ resolution: {integrity: sha512-b0HOicSvLYoNk1yvZTwjH8sNjF5uD9xLtWrSDnv+fx1dXTbwd8bNLQaP6gjXw//A+tni9Mw5KDmPNOEjKF55NQ==}
+ peerDependencies:
+ react: '>=16.4.0'
+ react-dom: '>=16.4.0'
+
resolution: {integrity: sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==}
@@ -12401,7 +12413,7 @@ snapshots:
obug: 2.1.3
std-env: 4.1.0
tinyrainbow: 3.1.0
'@vitest/[email protected]':
dependencies:
@@ -13726,8 +13738,8 @@ snapshots:
'@next/eslint-plugin-next': 16.2.10
eslint: 9.39.4([email protected])
eslint-import-resolver-node: 0.3.10
- eslint-import-resolver-typescript: 3.10.1([email protected])([email protected]([email protected]))
- eslint-plugin-import: 2.32.0([email protected])([email protected]([email protected]))
eslint-plugin-jsx-a11y: 6.10.2([email protected]([email protected]))
eslint-plugin-react: 7.37.5([email protected]([email protected]))
eslint-plugin-react-hooks: 7.1.1([email protected]([email protected]))
@@ -13749,7 +13761,7 @@ snapshots:
transitivePeerDependencies:
- supports-color
dependencies:
'@nolyfill/is-core-module': 1.0.39
debug: 4.4.3
@@ -13760,21 +13772,21 @@ snapshots:
tinyglobby: 0.2.17
unrs-resolver: 1.12.2
optionalDependencies:
- eslint-plugin-import: 2.32.0([email protected])([email protected]([email protected]))
transitivePeerDependencies:
- supports-color
dependencies:
debug: 3.2.7
optionalDependencies:
eslint: 9.39.4([email protected])
eslint-import-resolver-node: 0.3.10
- eslint-import-resolver-typescript: 3.10.1([email protected])([email protected]([email protected]))
transitivePeerDependencies:
- supports-color
dependencies:
'@rtsao/scc': 1.1.0
array-includes: 3.1.9
@@ -13785,7 +13797,7 @@ snapshots:
doctrine: 2.1.0
eslint: 9.39.4([email protected])
eslint-import-resolver-node: 0.3.10
hasown: 2.0.4
is-core-module: 2.16.2
is-glob: 4.0.3
@@ -16090,6 +16102,8 @@ snapshots:
+
dependencies:
path-key: 3.1.1
@@ -16660,6 +16674,12 @@ snapshots:
react: 19.2.7
scheduler: 0.27.0
+ dependencies:
+ normalize-wheel: 1.0.1
+ react: 19.2.7
+ react-dom: 19.2.7([email protected])
+
diff --git a/src/shared/src/constants/community.test.ts b/src/shared/src/constants/community.test.ts
new file mode 100644
index 000000000..c4aba0c50
--- /dev/null
+++ b/src/shared/src/constants/community.test.ts
@@ -0,0 +1,38 @@
+import { describe, it, expect } from "vitest"
+import * as alook from "../index"
+import {
+ ICON_CROP_MIN_ZOOM,
+ ICON_CROP_MAX_ZOOM,
+ ICON_CROP_OUTPUT_SIZE,
+ MAX_ICON_SOURCE_FILE_SIZE_BYTES,
+ ALLOWED_ICON_SOURCE_MIME_TYPES,
+} from "./community"
+
+describe("icon-crop constants", () => {
+ it("ICON_CROP_MIN_ZOOM is less than ICON_CROP_MAX_ZOOM", () => {
+ expect(ICON_CROP_MIN_ZOOM).toBeLessThan(ICON_CROP_MAX_ZOOM)
+ })
+
+ it("ICON_CROP_OUTPUT_SIZE is a positive number", () => {
+ expect(ICON_CROP_OUTPUT_SIZE).toBeGreaterThan(0)
+ })
+
+ it("MAX_ICON_SOURCE_FILE_SIZE_BYTES is a positive number", () => {
+ expect(MAX_ICON_SOURCE_FILE_SIZE_BYTES).toBeGreaterThan(0)
+ })
+
+ it("ALLOWED_ICON_SOURCE_MIME_TYPES excludes gif", () => {
+ expect(ALLOWED_ICON_SOURCE_MIME_TYPES).toContain("image/png")
+ expect(ALLOWED_ICON_SOURCE_MIME_TYPES).toContain("image/jpeg")
+ expect(ALLOWED_ICON_SOURCE_MIME_TYPES).toContain("image/webp")
+ expect(ALLOWED_ICON_SOURCE_MIME_TYPES).not.toContain("image/gif")
+ })
+
+ it("all four constants round-trip through the @alook/shared index re-export", () => {
+ expect(alook.ICON_CROP_MIN_ZOOM).toBe(ICON_CROP_MIN_ZOOM)
+ expect(alook.ICON_CROP_MAX_ZOOM).toBe(ICON_CROP_MAX_ZOOM)
+ expect(alook.ICON_CROP_OUTPUT_SIZE).toBe(ICON_CROP_OUTPUT_SIZE)
+ expect(alook.MAX_ICON_SOURCE_FILE_SIZE_BYTES).toBe(MAX_ICON_SOURCE_FILE_SIZE_BYTES)
+ expect(alook.ALLOWED_ICON_SOURCE_MIME_TYPES).toEqual(ALLOWED_ICON_SOURCE_MIME_TYPES)
+ })
+})
diff --git a/src/shared/src/constants/community.ts b/src/shared/src/constants/community.ts
index bf01c63b6..e3afb11fb 100644
--- a/src/shared/src/constants/community.ts
+++ b/src/shared/src/constants/community.ts
@@ -41,6 +41,19 @@ export const ALLOWED_ICON_MIME_TYPES = [
"image/gif",
] as const
+// Client-side crop/zoom picker (server icon, user avatar, bot avatar) — the
+// server-side upload handlers still enforce `MAX_SERVER_ICON_SIZE_BYTES` /
+// `ALLOWED_ICON_MIME_TYPES` above; these are the pre-cropper picker gates.
+export const MAX_ICON_SOURCE_FILE_SIZE_BYTES = 15 * 1024 * 1024 // 15 MB
+export const ICON_CROP_OUTPUT_SIZE = 512
+export const ICON_CROP_MIN_ZOOM = 1
+export const ICON_CROP_MAX_ZOOM = 3
+export const ALLOWED_ICON_SOURCE_MIME_TYPES = [
+ "image/png",
+ "image/jpeg",
+ "image/webp",
+] as const
+
// Search
export const MIN_SEARCH_LENGTH = 2
export const MAX_SEARCH_LENGTH = 200
@@ -96,3 +109,8 @@ export type NotificationLevelValue = typeof NOTIFICATION_LEVEL_VALUES[number]
// Cache headers
export const CACHE_IMMUTABLE = "public, max-age=31536000, immutable"
export const CACHE_SHORT = "public, max-age=3600"
+// For content served from a URL that stays fixed across re-uploads (user/bot
+// avatars overwrite the same R2 key in place) — always revalidate so a
+// replace is visible immediately, but pair with an ETag so revalidation is a
+// cheap 304 rather than a full re-fetch.
+export const CACHE_REVALIDATE = "no-cache, must-revalidate"
diff --git a/src/shared/src/index.ts b/src/shared/src/index.ts
index 3f88a8a8d..6f6ccd638 100644
--- a/src/shared/src/index.ts
+++ b/src/shared/src/index.ts
@@ -134,6 +134,11 @@ export {
MAX_SERVER_ICON_SIZE_BYTES,
ALLOWED_ATTACHMENT_MIME_PREFIXES,
ALLOWED_ICON_MIME_TYPES,
+ MAX_ICON_SOURCE_FILE_SIZE_BYTES,
+ ICON_CROP_OUTPUT_SIZE,
+ ICON_CROP_MIN_ZOOM,
+ ICON_CROP_MAX_ZOOM,
+ ALLOWED_ICON_SOURCE_MIME_TYPES,
MIN_SEARCH_LENGTH,
MAX_SEARCH_LENGTH,
DEFAULT_SEARCH_LIMIT,
@@ -155,6 +160,7 @@ export {
NOTIF_LEVELS,
CACHE_IMMUTABLE,
CACHE_SHORT,
+ CACHE_REVALIDATE,
} from "./constants/community";
export type { NotifLevel, NotificationLevelValue } from "./constants/community";
diff --git a/src/shared/src/schemas.test.ts b/src/shared/src/schemas.test.ts
new file mode 100644
index 000000000..5e1d66e7b
--- /dev/null
+++ b/src/shared/src/schemas.test.ts
@@ -0,0 +1,77 @@
+import { describe, it, expect } from "vitest"
+import { CommunityBotCreateRequestSchema, CommunityBotPatchRequestSchema } from "./schemas"
+
+function validCreatePayload(image?: string) {
+ return {
+ name: "MyBot",
+ machineId: "m1",
+ runtime: "node",
+ ...(image !== undefined ? { image } : {}),
+ }
+}
+
+describe("BotImageUrlSchema (via CommunityBotCreateRequestSchema)", () => {
+ it("accepts an https URL", () => {
+ const res = CommunityBotCreateRequestSchema.safeParse(validCreatePayload("https://cdn.example.com/a.png"))
+ expect(res.success).toBe(true)
+ })
+
+ it("accepts an avatar: procedural config", () => {
+ const res = CommunityBotCreateRequestSchema.safeParse(validCreatePayload("avatar:shape=star"))
+ expect(res.success).toBe(true)
+ })
+
+ it("accepts a leading-/ routable path (bot-avatar upload route shape)", () => {
+ const res = CommunityBotCreateRequestSchema.safeParse(validCreatePayload("/api/community/bots/b1/avatar"))
+ expect(res.success).toBe(true)
+ })
+
+ it("rejects a bare (non-routable, non-https, non-avatar:) string", () => {
+ const res = CommunityBotCreateRequestSchema.safeParse(validCreatePayload("not-a-url"))
+ expect(res.success).toBe(false)
+ })
+
+ it("rejects http:// (only https:// is allowed)", () => {
+ const res = CommunityBotCreateRequestSchema.safeParse(validCreatePayload("http://cdn.example.com/a.png"))
+ expect(res.success).toBe(false)
+ })
+
+ it("rejects a protocol-relative URL (starts with `/` but resolves off-origin)", () => {
+ const res = CommunityBotCreateRequestSchema.safeParse(validCreatePayload("//evil.com/pixel.gif"))
+ expect(res.success).toBe(false)
+ })
+
+ it("rejects an arbitrary same-origin path that isn't the bot avatar route", () => {
+ const res = CommunityBotCreateRequestSchema.safeParse(validCreatePayload("/some/internal/route"))
+ expect(res.success).toBe(false)
+ })
+
+ it("rejects a bot avatar route for a different bot id shape (path traversal attempt)", () => {
+ const res = CommunityBotCreateRequestSchema.safeParse(
+ validCreatePayload("/api/community/bots/../../etc/passwd/avatar"),
+ )
+ expect(res.success).toBe(false)
+ })
+
+ it("image field remains optional", () => {
+ const res = CommunityBotCreateRequestSchema.safeParse(validCreatePayload())
+ expect(res.success).toBe(true)
+ })
+})
+
+describe("BotImageUrlSchema (via CommunityBotPatchRequestSchema)", () => {
+ it("accepts a leading-/ routable path", () => {
+ const res = CommunityBotPatchRequestSchema.safeParse({ image: "/api/community/bots/b1/avatar" })
+ expect(res.success).toBe(true)
+ })
+
+ it("still accepts null to clear the image", () => {
+ const res = CommunityBotPatchRequestSchema.safeParse({ image: null })
+ expect(res.success).toBe(true)
+ })
+
+ it("rejects an invalid image string", () => {
+ const res = CommunityBotPatchRequestSchema.safeParse({ image: "ftp://nope" })
+ expect(res.success).toBe(false)
+ })
+})
diff --git a/src/shared/src/schemas.ts b/src/shared/src/schemas.ts
index 88b5105bb..b91bce4d8 100644
--- a/src/shared/src/schemas.ts
+++ b/src/shared/src/schemas.ts
@@ -980,14 +980,26 @@ import {
COMMUNITY_BOT_IMAGE_URL_MAX,
} from "./constants";
-// Accepts either an https URL or the in-house `avatar:` serialized config
-// produced by `serializeAvatarConfig` in the web avatar picker.
+// Accepts an https URL, the exact bot-avatar route shape
+// (`/api/community/bots/{id}/avatar` — see plans/icon-range-selector.md), or
+// the in-house `avatar:` serialized config produced by `serializeAvatarConfig`
+// in the web avatar picker. This gates client-supplied input on the plain
+// create/patch endpoints, so it must NOT accept an arbitrary leading-`/`
+// path: that would let a bot owner point every viewer's browser at a
+// protocol-relative URL (`//evil.com/...`) or an arbitrary same-origin path.
+const BOT_AVATAR_ROUTE_PATTERN = /^\/api\/community\/bots\/[A-Za-z0-9_-]+\/avatar$/;
const BotImageUrlSchema = z
.string()
.max(COMMUNITY_BOT_IMAGE_URL_MAX)
- .refine((v) => v.startsWith("https://") || v.startsWith("avatar:"), {
- message: "image must be an https URL or an avatar: config",
- });
+ .refine(
+ (v) =>
+ v.startsWith("https://") ||
+ v.startsWith("avatar:") ||
+ BOT_AVATAR_ROUTE_PATTERN.test(v),
+ {
+ message: "image must be an https URL, the bot avatar route, or an avatar: config",
+ },
+ );
export const CommunityBotCreateRequestSchema = z.object({
name: z
diff --git a/src/web/package.json b/src/web/package.json
index 1caa6ad39..cba0b4c16 100644
--- a/src/web/package.json
+++ b/src/web/package.json
@@ -73,6 +73,7 @@
"postal-mime": "^2.7.5",
"react": "19.2.7",
"react-dom": "19.2.7",
+ "react-easy-crop": "^6.1.0",
"react-resizable-panels": "^4.12.1",
"rehype-autolink-headings": "^7.1.0",
"rehype-external-links": "^3.0.0",
@@ -108,4 +109,4 @@
"vitest": "^4.1.9",
"wrangler": "^4.107.0"
}
-}
+}
\ No newline at end of file
diff --git a/src/web/src/app/api/community/bots/[id]/avatar/route.test.ts b/src/web/src/app/api/community/bots/[id]/avatar/route.test.ts
new file mode 100644
index 000000000..57222c2b1
--- /dev/null
+++ b/src/web/src/app/api/community/bots/[id]/avatar/route.test.ts
@@ -0,0 +1,174 @@
+import { describe, it, expect, vi, beforeEach } from "vitest"
+import { NextRequest } from "next/server"
+
+const mediaGet = vi.fn()
+const mockGetBotOwnedBy = vi.fn()
+const mockUpdateBot = vi.fn()
+const mockHandleBotAvatarUpload = vi.fn()
+
+vi.mock("@opennextjs/cloudflare", () => ({
+ getCloudflareContext: vi.fn(() => ({ env: { DB: {}, COMMUNITY_MEDIA: { get: (...a: unknown[]) => mediaGet(...a) } } })),
+}))
+
+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))
+
+vi.mock("@alook/shared", async () => {
+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")
+ return {
+ ...actual,
+ queries: {
+ communityBot: {
+ getBotOwnedBy: (...a: unknown[]) => mockGetBotOwnedBy(...a),
+ updateBot: (...a: unknown[]) => mockUpdateBot(...a),
+ },
+ },
+ }
+})
+
+vi.mock("@/lib/community/upload", () => ({
+ handleBotAvatarUpload: (...a: unknown[]) => mockHandleBotAvatarUpload(...a),
+}))
+
+let isAuthed = true
+
+vi.mock("@/lib/middleware/auth", () => ({
+ withAuth: (handler: any) => async (req: any, ctx?: any) => {
+ if (!isAuthed) {
+ const { NextResponse } = require("next/server")
+ return NextResponse.json({ error: "unauthorized" }, { status: 401 })
+ }
+ const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params
+ return handler(req, {
+ env: { DB: {}, COMMUNITY_MEDIA: { get: (...a: unknown[]) => mediaGet(...a) } },
+ userId: "u1",
+ email: "[email protected]",
+ params,
+ })
+ },
+}))
+
+vi.mock("@/lib/middleware/helpers", () => {
+ const { NextResponse } = require("next/server")
+ return {
+ writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),
+ writeError: (message: string, status: number) => NextResponse.json({ error: message }, { status }),
+ }
+})
+
+import { GET, POST } from "./route"
+
+function getReq() {
+ return new NextRequest("http://localhost/api/community/bots/b1/avatar", { method: "GET" })
+}
+function postReq() {
+ return new NextRequest("http://localhost/api/community/bots/b1/avatar", { method: "POST" })
+}
+function ctx(id?: string) {
+ return { params: Promise.resolve(id ? { id } : {}) } as any
+}
+
+describe("GET /api/community/bots/[id]/avatar", () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ isAuthed = true
+ mediaGet.mockResolvedValue({
+ body: new ReadableStream(),
+ httpMetadata: { contentType: "image/webp" },
+ httpEtag: '"etag-1"',
+ })
+ })
+
+ it("returns 401 for anonymous callers", async () => {
+ isAuthed = false
+ const res = await GET(getReq(), ctx("b1"))
+ expect(res.status).toBe(401)
+ expect(mediaGet).not.toHaveBeenCalled()
+ })
+
+ it("serves the avatar by the deterministic bot-avatar/{botId} key with no ownership check (DM peers/members need it)", async () => {
+ const res = await GET(getReq(), ctx("b1"))
+ expect(res.status).toBe(200)
+ expect(res.headers.get("Content-Type")).toBe("image/webp")
+ expect(mediaGet).toHaveBeenCalledWith("bot-avatar/b1")
+ expect(mockGetBotOwnedBy).not.toHaveBeenCalled()
+ })
+
+ it("returns 400 when the bot id route param is missing", async () => {
+ const res = await GET(getReq(), ctx(undefined))
+ expect(res.status).toBe(400)
+ expect(mediaGet).not.toHaveBeenCalled()
+ })
+
+ it("returns 404 when the R2 object is missing", async () => {
+ mediaGet.mockResolvedValue(null)
+ const res = await GET(getReq(), ctx("b1"))
+ expect(res.status).toBe(404)
+ })
+
+ it("revalidates on every request instead of a long max-age (deterministic key never changes on re-upload)", async () => {
+ const res = await GET(getReq(), ctx("b1"))
+ expect(res.headers.get("Cache-Control")).toBe("no-cache, must-revalidate")
+ expect(res.headers.get("ETag")).toBe('"etag-1"')
+ })
+
+ it("returns 304 with no body when If-None-Match matches the current ETag", async () => {
+ const req = new NextRequest("http://localhost/api/community/bots/b1/avatar", {
+ method: "GET",
+ headers: { "if-none-match": '"etag-1"' },
+ })
+ const res = await GET(req, ctx("b1"))
+ expect(res.status).toBe(304)
+ expect(res.headers.get("ETag")).toBe('"etag-1"')
+ })
+})
+
+describe("POST /api/community/bots/[id]/avatar", () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ isAuthed = true
+ mockGetBotOwnedBy.mockResolvedValue({ id: "b1", ownerId: "u1" })
+ mockUpdateBot.mockResolvedValue(undefined)
+ mockHandleBotAvatarUpload.mockResolvedValue({
+ ok: true,
+ id: "b1",
+ key: "bot-avatar/b1",
+ url: "/api/community/media/bot-avatar/b1",
+ filename: "bot.png",
+ contentType: "image/png",
+ size: 10,
+ })
+ })
+
+ it("returns 400 when the bot id route param is missing", async () => {
+ const res = await POST(postReq(), ctx(undefined))
+ expect(res.status).toBe(400)
+ expect(mockHandleBotAvatarUpload).not.toHaveBeenCalled()
+ })
+
+ it("returns 404 (bot not found) when the caller does not own the bot — scoped by userId ahead of the query", async () => {
+ mockGetBotOwnedBy.mockResolvedValue(null)
+ const res = await POST(postReq(), ctx("b1"))
+ expect(res.status).toBe(404)
+ expect(mockGetBotOwnedBy).toHaveBeenCalledWith(expect.anything(), "b1", "u1")
+ expect(mockHandleBotAvatarUpload).not.toHaveBeenCalled()
+ })
+
+ it("forwards upload failures unchanged (e.g. 413 too large)", async () => {
+ const { NextResponse } = await import("next/server")
+ mockHandleBotAvatarUpload.mockResolvedValue({
+ ok: false,
+ response: NextResponse.json({ error: "avatar too large (max 8MB)" }, { status: 413 }),
+ })
+ const res = await POST(postReq(), ctx("b1"))
+ expect(res.status).toBe(413)
+ expect(mockUpdateBot).not.toHaveBeenCalled()
+ })
+
+ it("uploads and updates the bot's image to the routable avatar URL", async () => {
+ const res = await POST(postReq(), ctx("b1"))
+ expect(res.status).toBe(200)
+ const body = await res.json() as { url: string }
+ expect(body.url).toBe("/api/community/bots/b1/avatar")
+ expect(mockUpdateBot).toHaveBeenCalledWith(expect.anything(), "b1", "u1", { image: "/api/community/bots/b1/avatar" })
+ })
+})
diff --git a/src/web/src/app/api/community/bots/[id]/avatar/route.ts b/src/web/src/app/api/community/bots/[id]/avatar/route.ts
new file mode 100644
index 000000000..3d1c8edd2
--- /dev/null
+++ b/src/web/src/app/api/community/bots/[id]/avatar/route.ts
@@ -0,0 +1,51 @@
+import { NextRequest } from "next/server"
+import { queries, CACHE_REVALIDATE } from "@alook/shared"
+import { withAuth } from "@/lib/middleware/auth"
+import { writeJSON, writeError } from "@/lib/middleware/helpers"
+import { getDb } from "@/lib/db"
+import { handleBotAvatarUpload } from "@/lib/community/upload"
+import { buildBotAvatarKey, botAvatarUrl } from "@/lib/community/storage"
+
+// No ownership check — other members/DM peers need to see a bot's avatar.
+//
+// The URL never changes across re-uploads (deterministic key), so caching by
+// max-age alone would keep every other viewer's browser stuck on the old
+// bytes for up to an hour after a replace. Revalidate on every request but
+// key it off the R2 ETag so a cache hit is a cheap 304, not a full re-fetch.
+export const GET = withAuth(async (req: NextRequest, ctx) => {
+ const botId = ctx.params?.id
+ if (!botId) return writeError("missing bot id", 400)
+
+ const obj = await ctx.env.COMMUNITY_MEDIA.get(buildBotAvatarKey(botId))
+ if (!obj) return writeError("not found", 404)
+
+ const etag = obj.httpEtag
+ if (etag && req.headers.get("if-none-match") === etag) {
+ return new Response(null, { status: 304, headers: { ETag: etag, "Cache-Control": CACHE_REVALIDATE } })
+ }
+
+ return new Response(obj.body, {
+ headers: {
+ "Content-Type": obj.httpMetadata?.contentType ?? "image/png",
+ "Cache-Control": CACHE_REVALIDATE,
+ ...(etag ? { ETag: etag } : {}),
+ },
+ })
+})
+
+export const POST = withAuth(async (req: NextRequest, ctx) => {
+ const botId = ctx.params?.id
+ if (!botId) return writeError("missing bot id", 400)
+
+ const db = getDb(ctx.env.DB)
+ const bot = await queries.communityBot.getBotOwnedBy(db, botId, ctx.userId)
+ if (!bot) return writeError("bot not found", 404)
+
+ const result = await handleBotAvatarUpload(req, ctx.env, botId)
+ if (!result.ok) return result.response
+
+ const url = botAvatarUrl(botId)
+ await queries.communityBot.updateBot(db, botId, ctx.userId, { image: url })
+
+ return writeJSON({ url })
+})
diff --git a/src/web/src/app/api/community/users/[userId]/avatar/route.test.ts b/src/web/src/app/api/community/users/[userId]/avatar/route.test.ts
new file mode 100644
index 000000000..ef42864ba
--- /dev/null
+++ b/src/web/src/app/api/community/users/[userId]/avatar/route.test.ts
@@ -0,0 +1,105 @@
+import { describe, it, expect, vi, beforeEach } from "vitest"
+import { NextRequest } from "next/server"
+
+const mediaGet = vi.fn()
+
+vi.mock("@opennextjs/cloudflare", () => ({
+ getCloudflareContext: vi.fn(() => ({ env: { DB: {}, COMMUNITY_MEDIA: { get: (...a: unknown[]) => mediaGet(...a) } } })),
+}))
+
+let isAuthed = true
+
+vi.mock("@/lib/middleware/auth", () => ({
+ withAuth: (handler: any) => async (req: any, ctx?: any) => {
+ if (!isAuthed) {
+ const { NextResponse } = require("next/server")
+ return NextResponse.json({ error: "unauthorized" }, { status: 401 })
+ }
+ const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params
+ return handler(req, {
+ env: { DB: {}, COMMUNITY_MEDIA: { get: (...a: unknown[]) => mediaGet(...a) } },
+ userId: "caller",
+ email: "[email protected]",
+ params,
+ })
+ },
+}))
+
+vi.mock("@/lib/middleware/helpers", () => {
+ const { NextResponse } = require("next/server")
+ return {
+ writeError: (message: string, status: number) => NextResponse.json({ error: message }, { status }),
+ }
+})
+
+import { GET } from "./route"
+
+function getReq() {
+ return new NextRequest("http://localhost/api/community/users/u1/avatar", { method: "GET" })
+}
+function ctx(userId?: string) {
+ return { params: Promise.resolve(userId ? { userId } : {}) } as any
+}
+
+describe("GET /api/community/users/[userId]/avatar", () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ isAuthed = true
+ mediaGet.mockResolvedValue({
+ body: new ReadableStream(),
+ httpMetadata: { contentType: "image/webp" },
+ httpEtag: '"etag-1"',
+ })
+ })
+
+ it("returns 401 for anonymous callers", async () => {
+ isAuthed = false
+ const res = await GET(getReq(), ctx("u1"))
+ expect(res.status).toBe(401)
+ expect(mediaGet).not.toHaveBeenCalled()
+ })
+
+ it("serves the avatar by the deterministic user-avatar/{userId} key for ANY authenticated caller (not just self)", async () => {
+ const res = await GET(getReq(), ctx("u1"))
+ expect(res.status).toBe(200)
+ expect(res.headers.get("Content-Type")).toBe("image/webp")
+ expect(mediaGet).toHaveBeenCalledWith("user-avatar/u1")
+ })
+
+ it("returns 400 when the userId route param is missing", async () => {
+ const res = await GET(getReq(), ctx(undefined))
+ expect(res.status).toBe(400)
+ expect(mediaGet).not.toHaveBeenCalled()
+ })
+
+ it("returns 404 when the R2 object is missing", async () => {
+ mediaGet.mockResolvedValue(null)
+ const res = await GET(getReq(), ctx("u1"))
+ expect(res.status).toBe(404)
+ })
+
+ it("revalidates on every request instead of a long max-age (deterministic key never changes on re-upload)", async () => {
+ const res = await GET(getReq(), ctx("u1"))
+ expect(res.headers.get("Cache-Control")).toBe("no-cache, must-revalidate")
+ expect(res.headers.get("ETag")).toBe('"etag-1"')
+ })
+
+ it("returns 304 with no body when If-None-Match matches the current ETag", async () => {
+ const req = new NextRequest("http://localhost/api/community/users/u1/avatar", {
+ method: "GET",
+ headers: { "if-none-match": '"etag-1"' },
+ })
+ const res = await GET(req, ctx("u1"))
+ expect(res.status).toBe(304)
+ expect(res.headers.get("ETag")).toBe('"etag-1"')
+ })
+
+ it("returns 200 with the full body when If-None-Match is stale", async () => {
+ const req = new NextRequest("http://localhost/api/community/users/u1/avatar", {
+ method: "GET",
+ headers: { "if-none-match": '"stale-etag"' },
+ })
+ const res = await GET(req, ctx("u1"))
+ expect(res.status).toBe(200)
+ })
+})
diff --git a/src/web/src/app/api/community/users/[userId]/avatar/route.ts b/src/web/src/app/api/community/users/[userId]/avatar/route.ts
new file mode 100644
index 000000000..035838b86
--- /dev/null
+++ b/src/web/src/app/api/community/users/[userId]/avatar/route.ts
@@ -0,0 +1,34 @@
+import { NextRequest } from "next/server"
+import { CACHE_REVALIDATE } from "@alook/shared"
+import { withAuth } from "@/lib/middleware/auth"
+import { writeError } from "@/lib/middleware/helpers"
+import { buildUserAvatarKey } from "@/lib/community/storage"
+
+// Any authenticated user can fetch — mirrors the server-icon serve route's
+// "readable by any authenticated user" gate. Message authors, member lists,
+// DM peers, etc. all need to render this avatar without an ownership check.
+//
+// The URL never changes across re-uploads (deterministic key), so caching by
+// max-age alone would keep every other viewer's browser stuck on the old
+// bytes for up to an hour after a replace. Revalidate on every request but
+// key it off the R2 ETag so a cache hit is a cheap 304, not a full re-fetch.
+export const GET = withAuth(async (req: NextRequest, ctx) => {
+ const userId = ctx.params?.userId
+ if (!userId) return writeError("missing user id", 400)
+
+ const obj = await ctx.env.COMMUNITY_MEDIA.get(buildUserAvatarKey(userId))
+ if (!obj) return writeError("not found", 404)
+
+ const etag = obj.httpEtag
+ if (etag && req.headers.get("if-none-match") === etag) {
+ return new Response(null, { status: 304, headers: { ETag: etag, "Cache-Control": CACHE_REVALIDATE } })
+ }
+
+ return new Response(obj.body, {
+ headers: {
+ "Content-Type": obj.httpMetadata?.contentType ?? "image/png",
+ "Cache-Control": CACHE_REVALIDATE,
+ ...(etag ? { ETag: etag } : {}),
+ },
+ })
+})
diff --git a/src/web/src/app/api/community/users/me/avatar/route.test.ts b/src/web/src/app/api/community/users/me/avatar/route.test.ts
new file mode 100644
index 000000000..21c86816a
--- /dev/null
+++ b/src/web/src/app/api/community/users/me/avatar/route.test.ts
@@ -0,0 +1,99 @@
+import { describe, it, expect, vi, beforeEach } from "vitest"
+import { NextRequest } from "next/server"
+
+const mockHandleUserAvatarUpload = vi.fn()
+const mockUpdateUser = vi.fn()
+
+vi.mock("@opennextjs/cloudflare", () => ({
+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),
+}))
+
+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))
+
+vi.mock("@alook/shared", async () => {
+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")
+ return {
+ ...actual,
+ queries: {
+ user: {
+ updateUser: (...a: unknown[]) => mockUpdateUser(...a),
+ },
+ },
+ }
+})
+
+vi.mock("@/lib/community/upload", () => ({
+ handleUserAvatarUpload: (...a: unknown[]) => mockHandleUserAvatarUpload(...a),
+}))
+
+let isAuthed = true
+
+vi.mock("@/lib/middleware/auth", () => ({
+ withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {
+ if (!isAuthed) {
+ const { NextResponse } = require("next/server")
+ return NextResponse.json({ error: "unauthorized" }, { status: 401 })
+ }
+ const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params
+ return handler(req, { env: { DB: {} }, userId: "u1", email: "[email protected]", params })
+ }),
+}))
+
+vi.mock("@/lib/middleware/helpers", () => {
+ const { NextResponse } = require("next/server")
+ return {
+ writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),
+ writeError: (message: string, status: number) => NextResponse.json({ error: message }, { status }),
+ }
+})
+
+import { POST } from "./route"
+
+function postReq() {
+ return new NextRequest("http://localhost/api/community/users/me/avatar", { method: "POST" })
+}
+
+describe("POST /api/community/users/me/avatar", () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ isAuthed = true
+ mockUpdateUser.mockResolvedValue(undefined)
+ })
+
+ it("rejects unauthenticated requests with 401", async () => {
+ isAuthed = false
+ const res = await POST(postReq(), {} as never)
+ expect(res.status).toBe(401)
+ expect(mockHandleUserAvatarUpload).not.toHaveBeenCalled()
+ })
+
+ it("forwards upload failures unchanged (e.g. 413 too large)", async () => {
+ const { NextResponse } = await import("next/server")
+ mockHandleUserAvatarUpload.mockResolvedValue({
+ ok: false,
+ response: NextResponse.json({ error: "avatar too large (max 8MB)" }, { status: 413 }),
+ })
+ const res = await POST(postReq(), {} as never)
+ expect(res.status).toBe(413)
+ expect(mockUpdateUser).not.toHaveBeenCalled()
+ })
+
+ it("uploads for the caller's own userId (never a body-supplied id) and updates image to the routable URL", async () => {
+ mockHandleUserAvatarUpload.mockResolvedValue({
+ ok: true,
+ id: "u1",
+ key: "user-avatar/u1",
+ url: "/api/community/media/user-avatar/u1",
+ filename: "me.png",
+ contentType: "image/png",
+ size: 10,
+ })
+ const res = await POST(postReq(), {} as never)
+ expect(res.status).toBe(200)
+ const body = await res.json() as { url: string }
+ expect(body.url).toBe("/api/community/users/u1/avatar")
+
+ expect(mockHandleUserAvatarUpload).toHaveBeenCalledWith(expect.anything(), expect.anything(), "u1")
+ expect(mockUpdateUser).toHaveBeenCalledWith(expect.anything(), "u1", { image: "/api/community/users/u1/avatar" })
+ })
+})
diff --git a/src/web/src/app/api/community/users/me/avatar/route.ts b/src/web/src/app/api/community/users/me/avatar/route.ts
new file mode 100644
index 000000000..617f0e592
--- /dev/null
+++ b/src/web/src/app/api/community/users/me/avatar/route.ts
@@ -0,0 +1,18 @@
+import { NextRequest } from "next/server"
+import { queries } from "@alook/shared"
+import { withAuth } from "@/lib/middleware/auth"
+import { writeJSON } from "@/lib/middleware/helpers"
+import { getDb } from "@/lib/db"
+import { handleUserAvatarUpload } from "@/lib/community/upload"
+import { userAvatarUrl } from "@/lib/community/storage"
+
+export const POST = withAuth(async (req: NextRequest, ctx) => {
+ const result = await handleUserAvatarUpload(req, ctx.env, ctx.userId)
+ if (!result.ok) return result.response
+
+ const db = getDb(ctx.env.DB)
+ const url = userAvatarUrl(ctx.userId)
+ await queries.user.updateUser(db, ctx.userId, { image: url })
+
+ return writeJSON({ url })
+})
diff --git a/src/web/src/app/community/channels/layout.tsx b/src/web/src/app/community/channels/layout.tsx
index f8dfa0e13..ceec19f22 100644
--- a/src/web/src/app/community/channels/layout.tsx
+++ b/src/web/src/app/community/channels/layout.tsx
@@ -14,6 +14,8 @@ import type { ServerDetail } from "@/hooks/community/use-servers"
import { ShellFrame } from "@/components/community/shell-frame"
import { ChannelSidebar } from "@/components/community/channel-sidebar"
import { ServerSettings } from "@/components/community/server-settings"
+import { ImageCropDialog } from "@/components/community/image-crop-dialog"
+import { validateIconSourceFile } from "@/lib/community/image-crop"
import type { MobileZone, SettingsSection } from "@/components/community/_types"
import { canManageServer, type ChannelType } from "@alook/shared"
import {
@@ -163,6 +165,7 @@ export default function ServerLayout({ children }: { children: ReactNode }) {
const [serverSettingsOpen, setServerSettingsOpen] = useState(false)
const [settingsSection, setSettingsSection] = useState<SettingsSection>("overview")
const [invitePopoverOpen, setInvitePopoverOpen] = useState(false)
+ const [pendingIconCrop, setPendingIconCrop] = useState<{ src: string; fileName: string } | null>(null)
// Close server-scoped dialogs when the user navigates to another server —
// without this, settings for server A would remain open after switching
@@ -404,15 +407,18 @@ export default function ServerLayout({ children }: { children: ReactNode }) {
})
}}
onUploadIcon={() => {
- const input = document.createElement("input"); input.type = "file"; input.accept = "image/*"
- input.onchange = async () => {
+ const input = document.createElement("input")
+ input.type = "file"
+ input.accept = "image/png,image/jpeg,image/webp"
+ input.onchange = () => {
const f = input.files?.[0]
- if (f) {
- uploadServerIconMut.mutate({ serverId, file: f }, {
- onSuccess: () => toast("Server icon updated"),
- onError: () => toast("Failed to upload icon"),
- })
+ if (!f) return
+ const check = validateIconSourceFile(f)
+ if (!check.ok) {
+ toast(check.error)
+ return
}
+ setPendingIconCrop({ src: URL.createObjectURL(f), fileName: f.name })
}
input.click()
}}
@@ -432,6 +438,26 @@ export default function ServerLayout({ children }: { children: ReactNode }) {
</Dialog>
)
+ const iconCropDialog = pendingIconCrop && (
+ <ImageCropDialog
+ imageSrc={pendingIconCrop.src}
+ originalFileName={pendingIconCrop.fileName}
+ maskShape="square"
+ onCropped={(file) => {
+ uploadServerIconMut.mutate({ serverId, file }, {
+ onSuccess: () => toast("Server icon updated"),
+ onError: () => toast("Failed to upload icon"),
+ })
+ URL.revokeObjectURL(pendingIconCrop.src)
+ setPendingIconCrop(null)
+ }}
+ onCancel={() => {
+ URL.revokeObjectURL(pendingIconCrop.src)
+ setPendingIconCrop(null)
+ }}
+ />
+ )
+
return (
<ShellFrame
view="server"
@@ -439,7 +465,7 @@ export default function ServerLayout({ children }: { children: ReactNode }) {
mobileZone={mobileZone}
setMobileZone={setMobileZone}
sidebar={sidebar}
- extraDialogs={serverSettingsDialog}
+ extraDialogs={<>{serverSettingsDialog}{iconCropDialog}</>}
goHome={goHome}
goServer={goServer}
>
diff --git a/src/web/src/app/community/preview/page.tsx b/src/web/src/app/community/preview/page.tsx
index 44743f8f3..4b92cbdaa 100644
--- a/src/web/src/app/community/preview/page.tsx
+++ b/src/web/src/app/community/preview/page.tsx
@@ -118,7 +118,7 @@ export default function CommunityPreview() {
unreadDms={[]}
mentions={MENTIONS}
onOpenChannel={openServerChannel}
- onMarkAllRead={() => {}}
+ onMarkAllRead={() => { }}
/>
),
hasUnread: unreadFeed.length > 0 || MENTIONS.length > 0,
@@ -440,7 +440,7 @@ export default function CommunityPreview() {
<MessageList
channel={openThread.name}
messages={threadMessages[openThread.id] ?? []}
- onOpenThread={() => {}}
+ onOpenThread={() => { }}
{...profileProps}
/>
<Composer channel={openThread.name} context="thread" members={composerMembers} onSend={sendThreadMessage} />
@@ -456,7 +456,7 @@ export default function CommunityPreview() {
<MessageList
channel={dm.name}
messages={dmMessages[dm.id] ?? []}
- onOpenThread={() => {}}
+ onOpenThread={() => { }}
{...profileProps}
hero={
<>
@@ -524,7 +524,7 @@ export default function CommunityPreview() {
<NewThreadDialog channel={activeChannel} open={creatingThread} onClose={() => setCreatingThread(false)} onCreate={(name, firstMessage) => createThread(name, { firstMessage })} />
<Dialog open={editingProfile} onOpenChange={(o) => { if (!o) setEditingProfile(false) }}>
<DialogContent className="flex h-[calc(100vh-4rem)] w-[calc(100vw-4rem)] sm:max-w-none flex-col gap-0 overflow-hidden rounded-xl p-0" showCloseButton={false}>
- <UserSettings onClose={() => setEditingProfile(false)} userId={null} userName="Preview User" aboutMe={myAboutMe} onSave={(data) => { if (data.aboutMe !== undefined) setMyAboutMe(data.aboutMe) }} onLogout={() => toast("Logged out")} />
+ <UserSettings onClose={() => setEditingProfile(false)} userId={null} userName="Preview User" aboutMe={myAboutMe} avatar="Preview User" onSave={(data) => { if (data.aboutMe !== undefined) setMyAboutMe(data.aboutMe) }} onLogout={() => toast("Logged out")} />
</DialogContent>
</Dialog>
<Dialog open={view === "settings"} onOpenChange={(o) => { if (!o) goServer() }}>
diff --git a/src/web/src/components/avatar/agent-avatar.test.ts b/src/web/src/components/avatar/agent-avatar.test.ts
new file mode 100644
index 000000000..f35473a71
--- /dev/null
+++ b/src/web/src/components/avatar/agent-avatar.test.ts
@@ -0,0 +1,45 @@
+import { describe, it, expect } from "vitest"
+import { AgentAvatar } from "./agent-avatar"
+import { AvatarRenderer, serializeAvatarConfig, DEFAULT_CONFIG } from "./avatar-parts"
+
+type ImgEl = { type: "img"; props: { src: string; alt: string; style: { width: number; height: number } } }
+type SpanEl = { type: "span"; props: { children: string; style: { width: number; height: number } } }
+type RendererEl = { type: typeof AvatarRenderer; props: { size: number } }
+
+describe("AgentAvatar", () => {
+ it("renders an <img> for a photo URL (https)", () => {
+ const el = AgentAvatar({ name: "Bot", avatarUrl: "https://cdn.example.com/a.png", size: 40 }) as unknown as ImgEl
+ expect(el.type).toBe("img")
+ expect(el.props.src).toBe("https://cdn.example.com/a.png")
+ expect(el.props.style).toEqual({ width: 40, height: 40 })
+ })
+
+ it("renders an <img> for a routable leading-/ avatar URL (bot/user avatar routes)", () => {
+ const el = AgentAvatar({
+ name: "Bot",
+ avatarUrl: "/api/community/bots/b1/avatar",
+ size: 24,
+ }) as unknown as ImgEl
+ expect(el.type).toBe("img")
+ expect(el.props.src).toBe("/api/community/bots/b1/avatar")
+ })
+
+ it("renders AvatarRenderer for a procedural avatar: config", () => {
+ const url = serializeAvatarConfig(DEFAULT_CONFIG)
+ const el = AgentAvatar({ name: "Bot", avatarUrl: url, size: 32 }) as unknown as RendererEl
+ expect(el.type).toBe(AvatarRenderer)
+ expect(el.props.size).toBe(32)
+ })
+
+ it("falls back to the initial-letter span when avatarUrl is null/undefined", () => {
+ const el = AgentAvatar({ name: "Zara", avatarUrl: null, size: 32 }) as unknown as SpanEl
+ expect(el.type).toBe("span")
+ expect(el.props.children).toBe("Z")
+ })
+
+ it("falls back to '?' when both name and avatarUrl are missing", () => {
+ const el = AgentAvatar({}) as unknown as SpanEl
+ expect(el.type).toBe("span")
+ expect(el.props.children).toBe("?")
+ })
+})
diff --git a/src/web/src/components/avatar/agent-avatar.tsx b/src/web/src/components/avatar/agent-avatar.tsx
index 133986a91..04c149322 100644
--- a/src/web/src/components/avatar/agent-avatar.tsx
+++ b/src/web/src/components/avatar/agent-avatar.tsx
@@ -1,8 +1,18 @@
"use client";
-import { AvatarRenderer, parseAvatarUrl } from "./avatar-parts";
+import { AvatarRenderer, parseAvatarUrl, isPhotoAvatarUrl } from "./avatar-parts";
export function AgentAvatar({ name, avatarUrl, size = 32 }: { name?: string | null; avatarUrl?: string | null; size?: number }) {
+ if (isPhotoAvatarUrl(avatarUrl)) {
+ return (
+ <img
+ src={avatarUrl!}
+ alt={name ?? ""}
+ className="rounded-full shrink-0 object-cover"
+ style={{ width: size, height: size }}
+ />
+ );
+ }
const config = parseAvatarUrl(avatarUrl);
if (config) return <AvatarRenderer config={config} size={size} className="rounded-full shrink-0" />;
return (
diff --git a/src/web/src/components/avatar/avatar-parts.test.ts b/src/web/src/components/avatar/avatar-parts.test.ts
index 9567f9fc0..2f4925184 100644
--- a/src/web/src/components/avatar/avatar-parts.test.ts
+++ b/src/web/src/components/avatar/avatar-parts.test.ts
@@ -12,6 +12,7 @@ import {
PRESETS,
randomConfig,
configFromName,
+ isPhotoAvatarUrl,
} from "./avatar-parts"
const NEW_SHAPE_KEYS = [
@@ -133,6 +134,21 @@ describe("PRESETS", () => {
})
})
+describe("isPhotoAvatarUrl", () => {
+ it("recognizes https URLs, http URLs, and leading-/ routable paths as photos", () => {
+ expect(isPhotoAvatarUrl("https://cdn.example.com/a.png")).toBe(true)
+ expect(isPhotoAvatarUrl("http://cdn.example.com/a.png")).toBe(true)
+ expect(isPhotoAvatarUrl("/api/community/users/u1/avatar")).toBe(true)
+ })
+
+ it("rejects null, undefined, empty string, and avatar: configs", () => {
+ expect(isPhotoAvatarUrl(null)).toBe(false)
+ expect(isPhotoAvatarUrl(undefined)).toBe(false)
+ expect(isPhotoAvatarUrl("")).toBe(false)
+ expect(isPhotoAvatarUrl("avatar:shape=star")).toBe(false)
+ })
+})
+
describe("star shape", () => {
it("uses rounded (curved) corners instead of sharp straight-line points", () => {
const markup = renderToStaticMarkup(Shapes.star!.render() as React.ReactElement)
diff --git a/src/web/src/components/avatar/avatar-parts.tsx b/src/web/src/components/avatar/avatar-parts.tsx
index d5091a42f..55c066623 100644
--- a/src/web/src/components/avatar/avatar-parts.tsx
+++ b/src/web/src/components/avatar/avatar-parts.tsx
@@ -736,3 +736,23 @@ export function parseAvatarUrl(avatarUrl: string | null | undefined): AvatarConf
return null;
}
}
+
+// ─────────────────────────────────────────────────────────────
+// PHOTO AVATAR DETECTION — same leading-`/`/`https://`/`http://` check as
+// community `avatar.tsx`'s private `isUrl`, duplicated intentionally rather
+// than cross-imported: `components/avatar/` is the generic module,
+// `components/community/avatar.tsx` is community-specific, and the reverse
+// import would invert that layering.
+// ─────────────────────────────────────────────────────────────
+export function isPhotoAvatarUrl(url: string | null | undefined): boolean {
+ return !!url && (url.startsWith("http://") || url.startsWith("https://") || url.startsWith("/"));
+}
+
+// ─────────────────────────────────────────────────────────────
+// AVATAR DRAFT — the dual-mode draft used by `BotAvatarPickerDialog`.
+// `file` is null when re-opening an *existing* photo untouched (edit); a
+// real `File` once freshly cropped this session.
+// ─────────────────────────────────────────────────────────────
+export type AvatarDraft =
+ | { kind: "procedural"; image: string }
+ | { kind: "photo"; file: File | null; previewUrl: string };
diff --git a/src/web/src/components/avatar/bot-avatar-picker-dialog.tsx b/src/web/src/components/avatar/bot-avatar-picker-dialog.tsx
new file mode 100644
index 000000000..627a64c95
--- /dev/null
+++ b/src/web/src/components/avatar/bot-avatar-picker-dialog.tsx
@@ -0,0 +1,251 @@
+"use client";
+
+import { useEffect, useRef, useState } from "react";
+import { Camera } from "lucide-react";
+import {
+ Dialog,
+ DialogTrigger,
+ DialogContent,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+import { Button } from "@/components/ui/button";
+import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs";
+import { ImageCropDialog } from "@/components/community/image-crop-dialog";
+import { validateIconSourceFile } from "@/lib/community/image-crop";
+import { toast } from "sonner";
+import {
+ type AvatarConfig,
+ type AvatarDraft,
+ AvatarRenderer,
+ DEFAULT_CONFIG,
+ parseAvatarUrl,
+ serializeAvatarConfig,
+} from "./avatar-parts";
+import { AvatarGenerator } from "./avatar-generator";
+import { useIsMobile } from "@/hooks/use-mobile";
+
+interface BotAvatarPickerDialogProps {
+ image: string | null;
+ onChange: (draft: AvatarDraft) => void;
+}
+
+type PhotoDraft = { file: File | null; previewUrl: string };
+
+/**
+ * Dual-mode ("Generate" | "Photo") bot avatar picker. A NEW component —
+ * `AvatarPickerDialog` itself is untouched; it's also used by the unrelated
+ * workspace-agent feature (`agent-create-form.tsx` / `agent-edit-form.tsx`)
+ * on the procedural-only `{ config, onChange }` contract.
+ */
+export function BotAvatarPickerDialog({ image, onChange }: BotAvatarPickerDialogProps) {
+ const [open, setOpen] = useState(false);
+ const isMobile = useIsMobile();
+ const fileInputRef = useRef<HTMLInputElement>(null);
+ const [pendingCropSrc, setPendingCropSrc] = useState<{ src: string; fileName: string } | null>(null);
+
+ // `image` can be a persisted URL (http/https/leading-`/`), or — echoed back
+ // from this session's own `onChange({ kind: "photo", previewUrl })` — a
+ // `blob:` object URL, which `isPhotoAvatarUrl` deliberately doesn't
+ // recognize (it's not a value the DB ever stores). Anything that isn't the
+ // `avatar:` procedural prefix is a photo here, blob URL included.
+ const isPhoto = (url: string | null) => !!url && parseAvatarUrl(url) === null;
+
+ const [tab, setTab] = useState<"generate" | "photo">(isPhoto(image) ? "photo" : "generate");
+ const [draftConfig, setDraftConfig] = useState<AvatarConfig>(
+ () => parseAvatarUrl(image) ?? DEFAULT_CONFIG,
+ );
+ const [photoDraft, setPhotoDraft] = useState<PhotoDraft | null>(
+ () => (isPhoto(image) ? { file: null, previewUrl: image! } : null),
+ );
+ // Tracks which draft last won — the active tab decides which one wins on
+ // Save, not which one was most recently edited (plan: "whichever tab
+ // you're on when you hit Create/Save wins").
+ const [activeKind, setActiveKind] = useState<"procedural" | "photo">(
+ isPhoto(image) ? "photo" : "procedural",
+ );
+
+ // Keeps the trigger-button preview (the "identity anchor") honest when
+ // `image` changes from *outside* this component — e.g. the parent
+ // randomizing the draft on dialog mount — without waiting for the user to
+ // open the inner popup first (that resync only happened in `onOpenChange`
+ // below). Idempotent against this component's own `onChange` echoes: the
+ // parent hands back exactly the string this component just emitted, so
+ // re-parsing it here reproduces the same state.
+ useEffect(() => {
+ const nowPhoto = isPhoto(image);
+ setDraftConfig(parseAvatarUrl(image) ?? DEFAULT_CONFIG);
+ setPhotoDraft((prev) =>
+ nowPhoto
+ ? prev && prev.previewUrl === image
+ ? prev
+ : { file: null, previewUrl: image! }
+ : null,
+ );
+ setActiveKind(nowPhoto ? "photo" : "procedural");
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [image]);
+
+ const emitForTab = (nextTab: "generate" | "photo", config: AvatarConfig, photo: PhotoDraft | null) => {
+ if (nextTab === "photo" && photo) {
+ setActiveKind("photo");
+ onChange({ kind: "photo", file: photo.file, previewUrl: photo.previewUrl });
+ } else {
+ setActiveKind("procedural");
+ onChange({ kind: "procedural", image: serializeAvatarConfig(config) });
+ }
+ };
+
+ const pickPhoto = () => fileInputRef.current?.click();
+ const onFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
+ const file = e.target.files?.[0];
+ e.target.value = "";
+ if (!file) return;
+ const check = validateIconSourceFile(file);
+ if (!check.ok) {
+ toast.error(check.error);
+ return;
+ }
+ setPendingCropSrc({ src: URL.createObjectURL(file), fileName: file.name });
+ };
+
+ const triggerPreview = activeKind === "photo" ? photoDraft?.previewUrl : null;
+
+ return (
+ <>
+ <Dialog
+ open={open}
+ onOpenChange={(nextOpen) => {
+ if (nextOpen) {
+ const nowPhoto = isPhoto(image);
+ const config = parseAvatarUrl(image) ?? DEFAULT_CONFIG;
+ setDraftConfig(config);
+ if (nowPhoto) {
+ // Reopening with the *same* previewUrl this instance already
+ // holds (the round-trip through the parent's `avatarDraft`)
+ // must not clobber a real `File` back to `null` — only reset
+ // when `image` genuinely changed (e.g. first open on an
+ // existing persisted photo, or a different URL entirely).
+ setPhotoDraft((prev) =>
+ prev && prev.previewUrl === image ? prev : { file: null, previewUrl: image! },
+ );
+ } else {
+ setPhotoDraft(null);
+ }
+ setTab(nowPhoto ? "photo" : "generate");
+ setActiveKind(nowPhoto ? "photo" : "procedural");
+ }
+ setOpen(nextOpen);
+ }}
+ >
+ <div className="flex justify-center">
+ <DialogTrigger
+ render={
+ <button
+ type="button"
+ className="rounded-2xl bg-background p-2 shadow-sm border border-border hover:border-primary/40 transition-colors cursor-pointer"
+ />
+ }
+ >
+ {triggerPreview ? (
+ <img src={triggerPreview} alt="" className="size-20 rounded-2xl object-cover" />
+ ) : (
+ <AvatarRenderer config={draftConfig} size={80} />
+ )}
+ </DialogTrigger>
+ </div>
+
+ <DialogContent className={
+ isMobile
+ ? "top-auto left-0 translate-x-0 translate-y-0 bottom-0 max-w-full sm:max-w-full w-full rounded-b-none rounded-t-xl max-h-[85dvh] overflow-y-auto thin-scrollbar pb-[env(safe-area-inset-bottom)]"
+ : "sm:max-w-180"
+ }>
+ <DialogHeader>
+ <DialogTitle>Choose Avatar</DialogTitle>
+ </DialogHeader>
+ <Tabs
+ value={tab}
+ onValueChange={(v) => {
+ const nextTab = v as "generate" | "photo";
+ setTab(nextTab);
+ emitForTab(nextTab, draftConfig, photoDraft);
+ }}
+ >
+ <TabsList className="mx-auto">
+ <TabsTrigger value="generate">Generate</TabsTrigger>
+ <TabsTrigger value="photo">Photo</TabsTrigger>
+ </TabsList>
+ <TabsContent value="generate">
+ <AvatarGenerator
+ config={draftConfig}
+ layout={isMobile ? "vertical" : "horizontal"}
+ onChange={(next) => {
+ setDraftConfig(next);
+ setActiveKind("procedural");
+ onChange({ kind: "procedural", image: serializeAvatarConfig(next) });
+ }}
+ mobile={isMobile}
+ />
+ </TabsContent>
+ <TabsContent value="photo">
+ <div className="flex flex-col items-center gap-3 py-6">
+ <input
+ ref={fileInputRef}
+ type="file"
+ accept="image/png,image/jpeg,image/webp"
+ className="hidden"
+ onChange={onFileChange}
+ />
+ <button
+ type="button"
+ onClick={pickPhoto}
+ className="grid size-32 place-items-center overflow-hidden rounded-full border-2 border-dashed border-input text-muted-foreground hover:border-primary hover:text-foreground"
+ >
+ {photoDraft ? (
+ <img src={photoDraft.previewUrl} alt="" className="size-full object-cover" />
+ ) : (
+ <Camera className="size-8" />
+ )}
+ </button>
+ <Button type="button" variant="secondary" size="sm" onClick={pickPhoto}>
+ {photoDraft ? "Change photo" : "Upload Photo"}
+ </Button>
+ </div>
+ </TabsContent>
+ </Tabs>
+ {isMobile && (
+ <button
+ type="button"
+ onClick={() => setOpen(false)}
+ className="w-full rounded-xl bg-primary py-3 text-sm font-medium text-primary-foreground hover:bg-primary/90 transition-colors"
+ >
+ Done
+ </button>
+ )}
+ </DialogContent>
+ </Dialog>
+ {pendingCropSrc && (
+ <ImageCropDialog
+ imageSrc={pendingCropSrc.src}
+ originalFileName={pendingCropSrc.fileName}
+ maskShape="circle"
+ onCropped={(file) => {
+ const previewUrl = URL.createObjectURL(file);
+ if (photoDraft?.previewUrl.startsWith("blob:")) {
+ URL.revokeObjectURL(photoDraft.previewUrl);
+ }
+ setPhotoDraft({ file, previewUrl });
+ setActiveKind("photo");
+ onChange({ kind: "photo", file, previewUrl });
+ URL.revokeObjectURL(pendingCropSrc.src);
+ setPendingCropSrc(null);
+ }}
+ onCancel={() => {
+ URL.revokeObjectURL(pendingCropSrc.src);
+ setPendingCropSrc(null);
+ }}
+ />
+ )}
+ </>
+ );
+}
diff --git a/src/web/src/components/avatar/index.ts b/src/web/src/components/avatar/index.ts
index d38533eb8..a2edf432f 100644
--- a/src/web/src/components/avatar/index.ts
+++ b/src/web/src/components/avatar/index.ts
@@ -1,13 +1,16 @@
export {
type AvatarConfig,
+ type AvatarDraft,
AvatarRenderer,
DEFAULT_CONFIG,
serializeAvatarConfig,
parseAvatarUrl,
randomConfig,
configFromName,
+ isPhotoAvatarUrl,
} from "./avatar-parts";
export { AnimatedAvatar } from "./animated-avatar";
export { AvatarPickerDialog } from "./avatar-picker-dialog";
+export { BotAvatarPickerDialog } from "./bot-avatar-picker-dialog";
export { AgentAvatar } from "./agent-avatar";
diff --git a/src/web/src/components/community/bots/create-bot-dialog.tsx b/src/web/src/components/community/bots/create-bot-dialog.tsx
index edd6e8558..18d2db776 100644
--- a/src/web/src/components/community/bots/create-bot-dialog.tsx
+++ b/src/web/src/components/community/bots/create-bot-dialog.tsx
@@ -23,13 +23,14 @@ import {
} from "@/components/ui/select"
import {
type AvatarConfig,
- AvatarPickerDialog,
+ type AvatarDraft,
+ BotAvatarPickerDialog,
randomConfig,
serializeAvatarConfig,
} from "@/components/avatar"
import { ProviderLogo } from "@/components/provider-logo"
import { useMachines } from "@/hooks/community/use-machines"
-import { useCreateBot } from "@/hooks/community/use-bots"
+import { useCreateBot, useUploadBotAvatar } from "@/hooks/community/use-bots"
import {
COMMUNITY_BOT_NAME_MAX,
COMMUNITY_BOT_DESCRIPTION_MAX,
@@ -66,11 +67,15 @@ export function CreateBotDialog({
}) {
const { machines } = useMachines()
const create = useCreateBot()
+ const uploadBotAvatar = useUploadBotAvatar()
const [name, setName] = useState("")
const [description, setDescription] = useState("")
const [machineId, setMachineId] = useState<string>("")
const [runtime, setRuntime] = useState<string>("")
- const [avatarConfig, setAvatarConfig] = useState<AvatarConfig>(INITIAL_AVATAR)
+ const [avatarDraft, setAvatarDraft] = useState<AvatarDraft>({
+ kind: "procedural",
+ image: serializeAvatarConfig(INITIAL_AVATAR),
+ })
const selectedMachine = machines.find((m) => m.id === machineId)
const runtimeOptions = useMemo(() => {
@@ -100,7 +105,7 @@ export function CreateBotDialog({
if (initializedFor.current) return
initializedFor.current = true
setName(randomBotName())
- setAvatarConfig(randomConfig())
+ setAvatarDraft({ kind: "procedural", image: serializeAvatarConfig(randomConfig()) })
setDescription("")
setMachineId("")
setRuntime("")
@@ -115,14 +120,27 @@ export function CreateBotDialog({
if (!machineId) return toast.error("Pick a machine")
if (!runtime) return toast.error("Pick a runtime")
try {
- await create.mutateAsync({
+ const data = await create.mutateAsync({
name: name.trim(),
description: description.trim() || undefined,
machineId,
runtime,
- image: serializeAvatarConfig(avatarConfig) ?? undefined,
+ image: avatarDraft.kind === "procedural" ? avatarDraft.image : undefined,
})
- toast.success(`Created ${name.trim()}`)
+ // Bots don't have an id until creation resolves — the photo upload is
+ // deferred until now so a cropped-then-cancelled dialog never uploads
+ // anything. Surface an upload failure without blocking on it; the bot
+ // itself was already created successfully.
+ let avatarFailed = false
+ if (avatarDraft.kind === "photo" && avatarDraft.file) {
+ try {
+ await uploadBotAvatar.mutateAsync({ botId: data.bot.id, file: avatarDraft.file })
+ } catch {
+ avatarFailed = true
+ toast.error("Bot created, but the avatar photo failed to upload")
+ }
+ }
+ if (!avatarFailed) toast.success(`Created ${name.trim()}`)
onOpenChange(false)
} catch (err) {
toast.error(err instanceof Error ? err.message : "Couldn't create the bot")
@@ -141,7 +159,10 @@ export function CreateBotDialog({
<div className="flex flex-col gap-4">
{/* Centered avatar picker — the identity anchor. */}
<div className="flex justify-center pt-1">
- <AvatarPickerDialog config={avatarConfig} onChange={setAvatarConfig} />
+ <BotAvatarPickerDialog
+ image={avatarDraft.kind === "procedural" ? avatarDraft.image : avatarDraft.previewUrl}
+ onChange={setAvatarDraft}
+ />
</div>
<div className="flex flex-col gap-2">
diff --git a/src/web/src/components/community/bots/edit-bot-dialog.tsx b/src/web/src/components/community/bots/edit-bot-dialog.tsx
index 927ee4c97..a34332128 100644
--- a/src/web/src/components/community/bots/edit-bot-dialog.tsx
+++ b/src/web/src/components/community/bots/edit-bot-dialog.tsx
@@ -16,11 +16,12 @@ import { Label } from "@/components/ui/label"
import { Textarea } from "@/components/ui/textarea"
import {
type AvatarConfig,
- AvatarPickerDialog,
- parseAvatarUrl,
+ type AvatarDraft,
+ BotAvatarPickerDialog,
+ isPhotoAvatarUrl,
serializeAvatarConfig,
} from "@/components/avatar"
-import { useUpdateBot, type BotSummary } from "@/hooks/community/use-bots"
+import { useUpdateBot, useUploadBotAvatar, type BotSummary } from "@/hooks/community/use-bots"
import {
COMMUNITY_BOT_NAME_MAX,
COMMUNITY_BOT_DESCRIPTION_MAX,
@@ -44,21 +45,36 @@ export function EditBotDialog({
}) {
const [name, setName] = useState(bot.name)
const [description, setDescription] = useState(bot.description ?? "")
- const [avatarConfig, setAvatarConfig] = useState<AvatarConfig>(() => {
- return parseAvatarUrl(bot.image ?? "") ?? DEFAULT_AVATAR
- })
+ const [avatarDraft, setAvatarDraft] = useState<AvatarDraft>(() =>
+ isPhotoAvatarUrl(bot.image)
+ ? { kind: "photo", file: null, previewUrl: bot.image! }
+ : { kind: "procedural", image: bot.image ?? serializeAvatarConfig(DEFAULT_AVATAR) },
+ )
const update = useUpdateBot()
+ const uploadBotAvatar = useUploadBotAvatar()
async function submit() {
if (!name.trim()) return toast.error("name is required")
try {
+ // Sequence matters — only attempt the avatar upload AFTER the
+ // name/description update resolves, inside the same try block, so a
+ // failed field update never triggers an upload.
await update.mutateAsync({
id: bot.id,
name: name.trim(),
description: description.trim() || undefined,
- image: serializeAvatarConfig(avatarConfig) ?? null,
+ image: avatarDraft.kind === "procedural" ? avatarDraft.image : undefined,
})
- toast.success("Bot updated")
+ let avatarFailed = false
+ if (avatarDraft.kind === "photo" && avatarDraft.file) {
+ try {
+ await uploadBotAvatar.mutateAsync({ botId: bot.id, file: avatarDraft.file })
+ } catch {
+ avatarFailed = true
+ toast.error("Bot updated, but the avatar photo failed to upload")
+ }
+ }
+ if (!avatarFailed) toast.success("Bot updated")
onOpenChange(false)
} catch (err) {
toast.error(err instanceof Error ? err.message : "Update failed")
@@ -76,7 +92,10 @@ export function EditBotDialog({
</DialogHeader>
<div className="space-y-4">
<div className="flex items-center justify-center">
- <AvatarPickerDialog config={avatarConfig} onChange={setAvatarConfig} />
+ <BotAvatarPickerDialog
+ image={avatarDraft.kind === "procedural" ? avatarDraft.image : avatarDraft.previewUrl}
+ onChange={setAvatarDraft}
+ />
</div>
<div className="space-y-2">
<Label htmlFor="bot-name">Name</Label>
diff --git a/src/web/src/components/community/create-server-dialog.tsx b/src/web/src/components/community/create-server-dialog.tsx
index 29850913c..49f35b519 100644
--- a/src/web/src/components/community/create-server-dialog.tsx
+++ b/src/web/src/components/community/create-server-dialog.tsx
@@ -1,13 +1,16 @@
"use client"
import { useRef, useState } from "react"
+import { toast } from "sonner"
import { Plus, ChevronRight, Link2 } from "lucide-react"
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Field } from "./field"
import { SlugHint } from "./slug-hint"
+import { ImageCropDialog } from "./image-crop-dialog"
import { previewSlug } from "@/lib/community/slug-preview"
+import { validateIconSourceFile } from "@/lib/community/image-crop"
// Create / join server dialog.
export function CreateServerDialog({ onClose, onCreateServer, onJoinServer }: {
@@ -20,78 +23,106 @@ export function CreateServerDialog({ onClose, onCreateServer, onJoinServer }: {
const [invite, setInvite] = useState("")
const [iconFile, setIconFile] = useState<File | null>(null)
const [iconPreview, setIconPreview] = useState<string | null>(null)
+ const [pendingCropSrc, setPendingCropSrc] = useState<{ src: string; fileName: string } | null>(null)
const fileRef = useRef<HTMLInputElement>(null)
const namePreview = previewSlug(name)
const pickIcon = () => fileRef.current?.click()
const onFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0]
+ e.target.value = ""
if (!file) return
- setIconFile(file)
- setIconPreview(URL.createObjectURL(file))
+ const check = validateIconSourceFile(file)
+ if (!check.ok) {
+ toast.error(check.error)
+ return
+ }
+ setPendingCropSrc({ src: URL.createObjectURL(file), fileName: file.name })
}
return (
- <Dialog open onOpenChange={(o) => { if (!o) onClose() }}>
- <DialogContent className="w-105 max-w-[calc(100vw-2rem)] p-0">
- <DialogHeader className="border-b border-border px-4 py-4">
- <DialogTitle>{step === "choose" ? "Create a Server" : step === "create" ? "Customize your server" : "Join a Server"}</DialogTitle>
- </DialogHeader>
- <div className="px-4 pb-5">
- {step === "choose" && (
- <div className="space-y-2">
- <p className="mb-3 text-sm text-muted-foreground">Your server is where you and your agents hang out. Make yours and start talking.</p>
- <button onClick={() => setStep("create")} className="flex w-full items-center gap-3 rounded-lg border border-border bg-card p-3 text-left hover:bg-accent">
- <span className="grid size-10 shrink-0 place-items-center rounded-full bg-primary text-primary-foreground"><Plus className="size-5" /></span>
- <span className="flex-1 text-sm font-medium">Create a server</span>
- <ChevronRight className="size-4 text-muted-foreground" />
- </button>
- <button onClick={() => setStep("join")} className="flex w-full items-center gap-3 rounded-lg border border-border bg-card p-3 text-left hover:bg-accent">
- <span className="grid size-10 shrink-0 place-items-center rounded-full bg-secondary text-foreground"><Link2 className="size-5" /></span>
- <span className="flex-1 text-sm font-medium">Join with invite</span>
- <ChevronRight className="size-4 text-muted-foreground" />
- </button>
- </div>
- )}
- {step === "create" && (
- <div className="space-y-4">
- <div className="flex flex-col items-center gap-2">
- <input ref={fileRef} type="file" accept="image/*" className="hidden" onChange={onFileChange} />
- <button onClick={pickIcon} className="grid size-20 place-items-center overflow-hidden rounded-full border-2 border-dashed border-input text-muted-foreground hover:border-primary hover:text-foreground">
- {iconPreview ? (
- <img src={iconPreview} alt="" className="size-full object-cover" />
- ) : (
- <Plus className="size-6" />
- )}
+ <>
+ <Dialog open onOpenChange={(o) => { if (!o) onClose() }}>
+ <DialogContent className="w-105 max-w-[calc(100vw-2rem)] p-0">
+ <DialogHeader className="border-b border-border px-4 py-4">
+ <DialogTitle>{step === "choose" ? "Create a Server" : step === "create" ? "Customize your server" : "Join a Server"}</DialogTitle>
+ </DialogHeader>
+ <div className="px-4 pb-5">
+ {step === "choose" && (
+ <div className="space-y-2">
+ <p className="mb-3 text-sm text-muted-foreground">Your server is where you and your agents hang out. Make yours and start talking.</p>
+ <button onClick={() => setStep("create")} className="flex w-full items-center gap-3 rounded-lg border border-border bg-card p-3 text-left hover:bg-accent">
+ <span className="grid size-10 shrink-0 place-items-center rounded-full bg-primary text-primary-foreground"><Plus className="size-5" /></span>
+ <span className="flex-1 text-sm font-medium">Create a server</span>
+ <ChevronRight className="size-4 text-muted-foreground" />
+ </button>
+ <button onClick={() => setStep("join")} className="flex w-full items-center gap-3 rounded-lg border border-border bg-card p-3 text-left hover:bg-accent">
+ <span className="grid size-10 shrink-0 place-items-center rounded-full bg-secondary text-foreground"><Link2 className="size-5" /></span>
+ <span className="flex-1 text-sm font-medium">Join with invite</span>
+ <ChevronRight className="size-4 text-muted-foreground" />
</button>
- <span className="text-xs text-muted-foreground">{iconPreview ? "Change icon" : "Upload an icon"}</span>
</div>
- <Field label="Server name">
- <Input value={name} onChange={(e) => setName(e.target.value)} placeholder="My community" />
- <SlugHint {...namePreview} />
- </Field>
- </div>
- )}
- {step === "join" && (
- <Field label="Invite link"><Input value={invite} onChange={(e) => setInvite(e.target.value)} placeholder="Paste an invite link or code" /></Field>
+ )}
+ {step === "create" && (
+ <div className="space-y-4">
+ <div className="flex flex-col items-center gap-2">
+ <input ref={fileRef} type="file" accept="image/png,image/jpeg,image/webp" className="hidden" onChange={onFileChange} />
+ <button onClick={pickIcon} className="grid size-20 place-items-center overflow-hidden rounded-full border-2 border-dashed border-input text-muted-foreground hover:border-primary hover:text-foreground">
+ {iconPreview ? (
+ <img src={iconPreview} alt="" className="size-full object-cover" />
+ ) : (
+ <Plus className="size-6" />
+ )}
+ </button>
+ <span className="text-xs text-muted-foreground">{iconPreview ? "Change icon" : "Upload an icon"}</span>
+ </div>
+ <Field label="Server name">
+ <Input value={name} onChange={(e) => setName(e.target.value)} placeholder="My community" />
+ <SlugHint {...namePreview} />
+ </Field>
+ </div>
+ )}
+ {step === "join" && (
+ <Field label="Invite link"><Input value={invite} onChange={(e) => setInvite(e.target.value)} placeholder="Paste an invite link or code" /></Field>
+ )}
+ </div>
+ {step !== "choose" && (
+ <DialogFooter className="mx-0 mb-0 flex-row items-center justify-between rounded-b-xl border-t border-border bg-card px-4 py-3">
+ <Button variant="ghost" size="sm" onClick={() => setStep("choose")}>Back</Button>
+ <Button
+ size="sm"
+ disabled={step === "create" ? !namePreview.slug : !invite.trim()}
+ onClick={() => {
+ if (step === "create") onCreateServer?.(name.trim(), iconFile ?? undefined)
+ else onJoinServer?.(invite.trim())
+ onClose()
+ }}
+ >
+ {step === "create" ? "Create" : "Join Server"}
+ </Button>
+ </DialogFooter>
)}
- </div>
- {step !== "choose" && (
- <DialogFooter className="mx-0 mb-0 flex-row items-center justify-between rounded-b-xl border-t border-border bg-card px-4 py-3">
- <Button variant="ghost" size="sm" onClick={() => setStep("choose")}>Back</Button>
- <Button
- size="sm"
- disabled={step === "create" ? !namePreview.slug : !invite.trim()}
- onClick={() => {
- if (step === "create") onCreateServer?.(name.trim(), iconFile ?? undefined)
- else onJoinServer?.(invite.trim())
- onClose()
- }}
- >
- {step === "create" ? "Create" : "Join Server"}
- </Button>
- </DialogFooter>
- )}
- </DialogContent>
- </Dialog>
+ </DialogContent>
+ </Dialog>
+ {pendingCropSrc && (
+ <ImageCropDialog
+ imageSrc={pendingCropSrc.src}
+ originalFileName={pendingCropSrc.fileName}
+ maskShape="square"
+ onCropped={(file) => {
+ setIconFile(file)
+ setIconPreview((prev) => {
+ if (prev) URL.revokeObjectURL(prev)
+ return URL.createObjectURL(file)
+ })
+ URL.revokeObjectURL(pendingCropSrc.src)
+ setPendingCropSrc(null)
+ }}
+ onCancel={() => {
+ URL.revokeObjectURL(pendingCropSrc.src)
+ setPendingCropSrc(null)
+ }}
+ />
+ )}
+ </>
)
}
diff --git a/src/web/src/components/community/edit-profile-dialog.tsx b/src/web/src/components/community/edit-profile-dialog.tsx
index a2c9e8675..4101dd0e7 100644
--- a/src/web/src/components/community/edit-profile-dialog.tsx
+++ b/src/web/src/components/community/edit-profile-dialog.tsx
@@ -11,6 +11,7 @@ import { Separator } from "@/components/ui/separator"
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs"
import { ConfirmDialog } from "@/components/ui/confirm-dialog"
import { clearPersistedCache } from "@/lib/query-persister"
+import { Avatar } from "./avatar"
import { Field } from "./field"
const THEME_OPTIONS = [
@@ -108,13 +109,15 @@ function AdvancedSettings({ userId }: { userId: string | null }) {
)
}
-export function UserSettings({ onClose, userId, userName, aboutMe, onSave, onLogout }: {
+export function UserSettings({ onClose, userId, userName, aboutMe, avatar, onSave, onLogout, onUploadAvatar }: {
onClose: () => void
userId: string | null
userName: string
aboutMe: string
+ avatar: string
onSave: (data: { name?: string; aboutMe?: string }) => void
onLogout?: () => void
+ onUploadAvatar?: () => void
}) {
const [name, setName] = useState(userName)
const [value, setValue] = useState(aboutMe)
@@ -185,6 +188,14 @@ export function UserSettings({ onClose, userId, userName, aboutMe, onSave, onLog
<div className="flex-1 overflow-y-auto thin-scrollbar p-4">
<TabsContent value="profile">
<div className="max-w-xl space-y-4">
+ <div className="flex items-center gap-4">
+ <Avatar label={avatar} size={80} />
+ <div>
+ <div className="text-sm font-medium">Avatar</div>
+ <div className="text-xs text-muted-foreground">PNG, JPG, or WEBP. You&apos;ll be able to crop and zoom before saving.</div>
+ <Button variant="secondary" size="sm" className="mt-2" onClick={onUploadAvatar}>Upload Photo</Button>
+ </div>
+ </div>
<Field label={<span>Display Name {saving && <span className="ml-2 text-xs text-muted-foreground">Saving...</span>}</span>}>
<Input value={name} onChange={(e) => handleNameChange(e.target.value)} />
</Field>
diff --git a/src/web/src/components/community/image-crop-dialog.tsx b/src/web/src/components/community/image-crop-dialog.tsx
new file mode 100644
index 000000000..bf8ab5ad9
--- /dev/null
+++ b/src/web/src/components/community/image-crop-dialog.tsx
@@ -0,0 +1,107 @@
+"use client"
+
+import { useCallback, useState } from "react"
+import Cropper, { type Area } from "react-easy-crop"
+import { toast } from "sonner"
+import {
+ Dialog,
+ DialogContent,
+ DialogHeader,
+ DialogTitle,
+ DialogFooter,
+} from "@/components/ui/dialog"
+import { Button } from "@/components/ui/button"
+import { Slider, SliderControl, SliderTrack, SliderRange, SliderThumb } from "@/components/ui/slider"
+import { ICON_CROP_MIN_ZOOM, ICON_CROP_MAX_ZOOM, ICON_CROP_OUTPUT_SIZE } from "@alook/shared"
+import { getCroppedIconBlob, buildCroppedIconFile } from "@/lib/community/image-crop"
+
+/**
+ * Shared crop/zoom dialog for server icons (square) and user/bot avatars
+ * (circle). Does NOT call `URL.revokeObjectURL` on `imageSrc` — it doesn't
+ * own that URL; every caller is responsible for creating and revoking it
+ * symmetrically on both the cropped and cancelled paths.
+ */
+export function ImageCropDialog({
+ imageSrc,
+ originalFileName,
+ maskShape,
+ onCancel,
+ onCropped,
+}: {
+ imageSrc: string
+ originalFileName: string
+ maskShape: "circle" | "square"
+ onCancel: () => void
+ onCropped: (file: File) => void
+}) {
+ const [crop, setCrop] = useState({ x: 0, y: 0 })
+ const [zoom, setZoom] = useState(1)
+ const [cropPixels, setCropPixels] = useState<Area | null>(null)
+ const [saving, setSaving] = useState(false)
+
+ const onCropComplete = useCallback((_area: Area, areaPixels: Area) => {
+ setCropPixels(areaPixels)
+ }, [])
+
+ const save = async () => {
+ if (!cropPixels) return
+ setSaving(true)
+ try {
+ const blob = await getCroppedIconBlob(imageSrc, cropPixels, ICON_CROP_OUTPUT_SIZE)
+ if (!blob) {
+ toast.error("Failed to process image — please try again")
+ return
+ }
+ onCropped(buildCroppedIconFile(blob, originalFileName))
+ } catch {
+ toast.error("Failed to process image — please try again")
+ } finally {
+ setSaving(false)
+ }
+ }
+
+ return (
+ <Dialog open onOpenChange={(o) => { if (!o) onCancel() }}>
+ <DialogContent className="sm:max-w-md">
+ <DialogHeader>
+ <DialogTitle>Crop image</DialogTitle>
+ </DialogHeader>
+ <div className="relative h-80 w-full overflow-hidden rounded-md bg-muted">
+ <Cropper
+ image={imageSrc}
+ crop={crop}
+ zoom={zoom}
+ aspect={1}
+ cropShape={maskShape === "circle" ? "round" : "rect"}
+ minZoom={ICON_CROP_MIN_ZOOM}
+ maxZoom={ICON_CROP_MAX_ZOOM}
+ onCropChange={setCrop}
+ onZoomChange={setZoom}
+ onCropComplete={onCropComplete}
+ />
+ </div>
+ <Slider
+ aria-label="Zoom"
+ min={ICON_CROP_MIN_ZOOM}
+ max={ICON_CROP_MAX_ZOOM}
+ step={0.01}
+ value={zoom}
+ onValueChange={(v) => setZoom(v as number)}
+ >
+ <SliderControl>
+ <SliderTrack>
+ <SliderRange />
+ <SliderThumb />
+ </SliderTrack>
+ </SliderControl>
+ </Slider>
+ <DialogFooter>
+ <Button variant="ghost" onClick={onCancel}>Cancel</Button>
+ <Button onClick={save} disabled={!cropPixels || saving}>
+ {saving ? "Saving…" : "Save"}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ )
+}
diff --git a/src/web/src/components/community/server-settings.tsx b/src/web/src/components/community/server-settings.tsx
index cff0bad6d..253b56ad1 100644
--- a/src/web/src/components/community/server-settings.tsx
+++ b/src/web/src/components/community/server-settings.tsx
@@ -146,7 +146,7 @@ function SettingsOverview({ serverName, serverDescription, serverIcon, onUploadI
)}
<div>
<div className="text-sm font-medium">Server icon</div>
- <div className="text-xs text-muted-foreground">Recommended 512×512. PNG, JPG, or GIF.</div>
+ <div className="text-xs text-muted-foreground">PNG, JPG, or WEBP. You&apos;ll be able to crop and zoom before saving.</div>
<Button variant="secondary" size="sm" className="mt-2" onClick={onUploadIcon}>Upload image</Button>
</div>
</div>
diff --git a/src/web/src/components/community/shell-frame.tsx b/src/web/src/components/community/shell-frame.tsx
index d5941312c..9d56ef13e 100644
--- a/src/web/src/components/community/shell-frame.tsx
+++ b/src/web/src/components/community/shell-frame.tsx
@@ -18,6 +18,8 @@ import { InboxPopover } from "./community-inbox-popover"
import { UserSettings } from "./edit-profile-dialog"
import { ProfileCard } from "./profile-card"
import { ImageLightbox } from "./image-lightbox"
+import { ImageCropDialog } from "./image-crop-dialog"
+import { validateIconSourceFile } from "@/lib/community/image-crop"
import type { MobileZone, Profile, View } from "./_types"
import { signOut } from "@/lib/auth-client"
import { clearPersistedCache } from "@/lib/query-persister"
@@ -44,6 +46,7 @@ import {
useDeleteMention,
useUpdateProfile,
useSendDmMessage,
+ useUploadUserAvatar,
} from "@/hooks/community/mutations"
/**
@@ -118,10 +121,12 @@ export function ShellFrame({
const markAllInboxRead = useMarkAllInboxRead()
const deleteMention = useDeleteMention()
const updateProfile = useUpdateProfile()
+ const uploadUserAvatar = useUploadUserAvatar()
const [editingProfile, setEditingProfile] = useState(false)
const [profile, setProfile] = useState<{ data: Profile; x: number; y: number } | null>(null)
const [preview, setPreview] = useState<string | null>(null)
+ const [pendingAvatarCrop, setPendingAvatarCrop] = useState<{ src: string; fileName: string } | null>(null)
// Rail wiring — universal, since navigation is URL-driven and doesn't
// depend on the current view.
@@ -460,6 +465,23 @@ export function ShellFrame({
userId={currentUser.id}
userName={currentUser.name}
aboutMe={currentUser.aboutMe ?? ""}
+ avatar={currentUser.avatar}
+ onUploadAvatar={() => {
+ const input = document.createElement("input")
+ input.type = "file"
+ input.accept = "image/png,image/jpeg,image/webp"
+ input.onchange = () => {
+ const f = input.files?.[0]
+ if (!f) return
+ const check = validateIconSourceFile(f)
+ if (!check.ok) {
+ toast(check.error)
+ return
+ }
+ setPendingAvatarCrop({ src: URL.createObjectURL(f), fileName: f.name })
+ }
+ input.click()
+ }}
onSave={async (data) => {
try {
await updateProfile.mutateAsync(data)
@@ -480,7 +502,7 @@ export function ShellFrame({
useCommunityWsStore.getState().reset()
// Drop the persisted IDB blob so the next user on this machine
// doesn't see the previous session's cached message rows.
- await clearPersistedCache(currentUser.id).catch(() => {})
+ await clearPersistedCache(currentUser.id).catch(() => { })
await signOut()
router.push("/sign-in")
}}
@@ -489,6 +511,29 @@ export function ShellFrame({
</Dialog>
)
+ const avatarCropDialog = pendingAvatarCrop && (
+ <ImageCropDialog
+ imageSrc={pendingAvatarCrop.src}
+ originalFileName={pendingAvatarCrop.fileName}
+ maskShape="circle"
+ onCropped={(file) => {
+ uploadUserAvatar.mutate({ file }, {
+ onSuccess: (data) => {
+ setCurrentUser((u) => ({ ...u, avatar: `${data.url}?t=${Date.now()}` }))
+ toast("Avatar updated")
+ },
+ onError: () => toast("Failed to upload avatar"),
+ })
+ URL.revokeObjectURL(pendingAvatarCrop.src)
+ setPendingAvatarCrop(null)
+ }}
+ onCancel={() => {
+ URL.revokeObjectURL(pendingAvatarCrop.src)
+ setPendingAvatarCrop(null)
+ }}
+ />
+ )
+
const sidebarPanelRef = useRef<HTMLDivElement>(null)
const [sidebarW, setSidebarW] = useState(240)
useEffect(() => {
@@ -525,6 +570,7 @@ export function ShellFrame({
{profile && <ProfileCard data={profile.data} x={profile.x} y={profile.y} bp={bp} onClose={() => setProfile(null)} onMessage={profileMessage} isSelf={profile.data.name === currentUser.name} />}
{preview && <ImageLightbox src={preview} onClose={() => setPreview(null)} />}
{userSettingsDialog}
+ {avatarCropDialog}
{extraDialogs}
</Shell>
)
@@ -549,6 +595,7 @@ export function ShellFrame({
{profile && <ProfileCard data={profile.data} x={profile.x} y={profile.y} bp={bp} onClose={() => setProfile(null)} onMessage={profileMessage} isSelf={profile.data.name === currentUser.name} />}
{preview && <ImageLightbox src={preview} onClose={() => setPreview(null)} />}
{userSettingsDialog}
+ {avatarCropDialog}
{extraDialogs}
</Shell>
)
diff --git a/src/web/src/components/ui/slider.tsx b/src/web/src/components/ui/slider.tsx
new file mode 100644
index 000000000..80291c4c8
--- /dev/null
+++ b/src/web/src/components/ui/slider.tsx
@@ -0,0 +1,66 @@
+"use client"
+
+import { Slider as SliderPrimitive } from "@base-ui/react/slider"
+
+import { cn } from "@/lib/utils"
+
+function Slider<Value extends number | readonly number[]>({
+ className,
+ ...props
+}: SliderPrimitive.Root.Props<Value>) {
+ return (
+ <SliderPrimitive.Root
+ data-slot="slider"
+ className={cn("relative flex w-full touch-none items-center select-none", className)}
+ {...props}
+ />
+ )
+}
+
+function SliderControl({ className, ...props }: SliderPrimitive.Control.Props) {
+ return (
+ <SliderPrimitive.Control
+ data-slot="slider-control"
+ className={cn("relative flex w-full items-center py-2", className)}
+ {...props}
+ />
+ )
+}
+
+function SliderTrack({ className, ...props }: SliderPrimitive.Track.Props) {
+ return (
+ <SliderPrimitive.Track
+ data-slot="slider-track"
+ className={cn(
+ "relative h-1.5 w-full grow rounded-full bg-muted",
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+function SliderRange({ className, ...props }: SliderPrimitive.Indicator.Props) {
+ return (
+ <SliderPrimitive.Indicator
+ data-slot="slider-range"
+ className={cn("absolute h-full rounded-full bg-primary", className)}
+ {...props}
+ />
+ )
+}
+
+function SliderThumb({ className, ...props }: SliderPrimitive.Thumb.Props) {
+ return (
+ <SliderPrimitive.Thumb
+ data-slot="slider-thumb"
+ className={cn(
+ "block size-4 shrink-0 rounded-full border border-primary bg-background shadow-sm outline-none transition-[color,box-shadow] focus-visible:ring-4 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-50",
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+export { Slider, SliderControl, SliderTrack, SliderRange, SliderThumb }
diff --git a/src/web/src/hooks/community/mutations/profile.ts b/src/web/src/hooks/community/mutations/profile.ts
index d6bd9e3fe..b770bc96e 100644
--- a/src/web/src/hooks/community/mutations/profile.ts
+++ b/src/web/src/hooks/community/mutations/profile.ts
@@ -23,3 +23,28 @@ export function useUpdateProfile() {
},
})
}
+
+export type UploadUserAvatarArgs = { file: File }
+export type UploadUserAvatarResult = { url: string }
+
+/**
+ * Uploads the current user's avatar. Mirrors `useUploadServerIcon`'s raw
+ * `fetch`-with-`FormData` pattern. Consumers apply the returned URL to their
+ * own local `CurrentUser` state — the identity lives outside the community
+ * query cache (see `contexts/community/current-user.tsx`).
+ */
+export function useUploadUserAvatar() {
+ return useMutation<UploadUserAvatarResult, Error, UploadUserAvatarArgs>({
+ mutationFn: async ({ file }) => {
+ const formData = new FormData()
+ formData.append("file", file)
+ const res = await fetch("/api/community/users/me/avatar", {
+ method: "POST",
+ body: formData,
+ credentials: "include",
+ })
+ if (!res.ok) throw new Error("Upload failed")
+ return (await res.json()) as UploadUserAvatarResult
+ },
+ })
+}
diff --git a/src/web/src/hooks/community/use-bots.ts b/src/web/src/hooks/community/use-bots.ts
index c807a17f2..d5aeb59d4 100644
--- a/src/web/src/hooks/community/use-bots.ts
+++ b/src/web/src/hooks/community/use-bots.ts
@@ -79,3 +79,24 @@ export function useDeleteBot() {
onSuccess: () => invalidateBotSurfaces(qc),
})
}
+
+export type UploadBotAvatarArgs = { botId: string; file: File }
+export type UploadBotAvatarResult = { url: string }
+
+export function useUploadBotAvatar() {
+ const qc = useQueryClient()
+ return useMutation<UploadBotAvatarResult, Error, UploadBotAvatarArgs>({
+ mutationFn: async ({ botId, file }) => {
+ const formData = new FormData()
+ formData.append("file", file)
+ const res = await fetch(`/api/community/bots/${botId}/avatar`, {
+ method: "POST",
+ body: formData,
+ credentials: "include",
+ })
+ if (!res.ok) throw new Error("Upload failed")
+ return (await res.json()) as UploadBotAvatarResult
+ },
+ onSuccess: () => invalidateBotSurfaces(qc),
+ })
+}
diff --git a/src/web/src/lib/community/image-crop.test.ts b/src/web/src/lib/community/image-crop.test.ts
new file mode 100644
index 000000000..d56de1e8d
--- /dev/null
+++ b/src/web/src/lib/community/image-crop.test.ts
@@ -0,0 +1,52 @@
+import { describe, it, expect } from "vitest"
+import { MAX_ICON_SOURCE_FILE_SIZE_BYTES } from "@alook/shared"
+import { validateIconSourceFile, deriveCroppedFileName, buildCroppedIconFile } from "./image-crop"
+
+function fakeFile(name: string, type: string, size: number): File {
+ return {
+ name,
+ type,
+ size,
+ } as File
+}
+
+describe("validateIconSourceFile", () => {
+ it("accepts png/jpeg/webp under the size cap", () => {
+ for (const type of ["image/png", "image/jpeg", "image/webp"]) {
+ expect(validateIconSourceFile(fakeFile("f.png", type, 1024))).toEqual({ ok: true })
+ }
+ })
+
+ it("rejects oversized files regardless of MIME", () => {
+ const file = fakeFile("big.png", "image/png", MAX_ICON_SOURCE_FILE_SIZE_BYTES + 1)
+ const result = validateIconSourceFile(file)
+ expect(result.ok).toBe(false)
+ })
+
+ it("rejects disallowed MIME types (e.g. image/gif) even under the size cap", () => {
+ const file = fakeFile("f.gif", "image/gif", 1024)
+ const result = validateIconSourceFile(file)
+ expect(result.ok).toBe(false)
+ })
+})
+
+describe("deriveCroppedFileName", () => {
+ it("strips various extensions and appends exactly one .webp", () => {
+ expect(deriveCroppedFileName("photo.png")).toBe("photo.webp")
+ expect(deriveCroppedFileName("photo.jpeg")).toBe("photo.webp")
+ expect(deriveCroppedFileName("my.photo.jpg")).toBe("my.photo.webp")
+ })
+
+ it("appends .webp when there is no extension", () => {
+ expect(deriveCroppedFileName("photo")).toBe("photo.webp")
+ })
+})
+
+describe("buildCroppedIconFile", () => {
+ it("resulting File.type is always image/webp, name ends in .webp", () => {
+ const blob = new Blob(["x"], { type: "image/png" })
+ const file = buildCroppedIconFile(blob, "original.png")
+ expect(file.type).toBe("image/webp")
+ expect(file.name.endsWith(".webp")).toBe(true)
+ })
+})
diff --git a/src/web/src/lib/community/image-crop.ts b/src/web/src/lib/community/image-crop.ts
new file mode 100644
index 000000000..aaf783e00
--- /dev/null
+++ b/src/web/src/lib/community/image-crop.ts
@@ -0,0 +1,73 @@
+import {
+ MAX_ICON_SOURCE_FILE_SIZE_BYTES,
+ ALLOWED_ICON_SOURCE_MIME_TYPES,
+} from "@alook/shared"
+
+export type CropPixels = { x: number; y: number; width: number; height: number }
+
+/**
+ * Client-side pre-cropper gate — shared by the server-icon, user-avatar, and
+ * bot-avatar pickers. The server-side upload handlers re-validate with their
+ * own (looser) size/MIME constants; this is just fast UX feedback before the
+ * crop dialog even opens.
+ */
+export function validateIconSourceFile(file: File): { ok: true } | { ok: false; error: string } {
+ if (file.size > MAX_ICON_SOURCE_FILE_SIZE_BYTES) {
+ return { ok: false, error: `Image too large (max ${Math.floor(MAX_ICON_SOURCE_FILE_SIZE_BYTES / 1024 / 1024)}MB)` }
+ }
+ if (!(ALLOWED_ICON_SOURCE_MIME_TYPES as readonly string[]).includes(file.type)) {
+ return { ok: false, error: "Image must be PNG, JPEG, or WebP" }
+ }
+ return { ok: true }
+}
+
+/** Strips the original extension and appends `.webp` — the crop export is always WebP. */
+export function deriveCroppedFileName(originalName: string): string {
+ const dot = originalName.lastIndexOf(".")
+ const base = dot > 0 ? originalName.slice(0, dot) : originalName
+ return `${base}.webp`
+}
+
+/**
+ * Browser-only canvas export: draws the cropped source rect into a fresh
+ * `outputSize × outputSize` canvas and encodes as WebP. Mirrors the pattern
+ * in `lib/image-thumbnail.ts`. Not unit-tested — no jsdom/canvas in this
+ * repo's vitest env (same precedent as `image-thumbnail.ts`).
+ */
+export async function getCroppedIconBlob(
+ imageSrc: string,
+ cropPixels: CropPixels,
+ outputSize: number,
+): Promise<Blob | null> {
+ const img = await loadImage(imageSrc)
+ const canvas = document.createElement("canvas")
+ canvas.width = outputSize
+ canvas.height = outputSize
+ const ctx = canvas.getContext("2d")
+ if (!ctx) return null
+ ctx.drawImage(
+ img,
+ cropPixels.x,
+ cropPixels.y,
+ cropPixels.width,
+ cropPixels.height,
+ 0,
+ 0,
+ outputSize,
+ outputSize,
+ )
+ return new Promise((resolve) => canvas.toBlob(resolve, "image/webp", 0.9))
+}
+
+export function buildCroppedIconFile(blob: Blob, originalName: string): File {
+ return new File([blob], deriveCroppedFileName(originalName), { type: "image/webp" })
+}
+
+function loadImage(src: string): Promise<HTMLImageElement> {
+ return new Promise((resolve, reject) => {
+ const img = new Image()
+ img.onload = () => resolve(img)
+ img.onerror = reject
+ img.src = src
+ })
+}
diff --git a/src/web/src/lib/community/storage.test.ts b/src/web/src/lib/community/storage.test.ts
new file mode 100644
index 000000000..631beec84
--- /dev/null
+++ b/src/web/src/lib/community/storage.test.ts
@@ -0,0 +1,49 @@
+import { describe, it, expect } from "vitest"
+import {
+ buildUserAvatarKey,
+ buildBotAvatarKey,
+ userAvatarUrl,
+ botAvatarUrl,
+} from "./storage"
+
+describe("buildUserAvatarKey", () => {
+ it("is deterministic (no randomness)", () => {
+ expect(buildUserAvatarKey("u1")).toBe(buildUserAvatarKey("u1"))
+ })
+
+ it("has the correct format", () => {
+ expect(buildUserAvatarKey("u1")).toBe("user-avatar/u1")
+ })
+})
+
+describe("buildBotAvatarKey", () => {
+ it("is deterministic (no randomness)", () => {
+ expect(buildBotAvatarKey("b1")).toBe(buildBotAvatarKey("b1"))
+ })
+
+ it("has the correct format", () => {
+ expect(buildBotAvatarKey("b1")).toBe("bot-avatar/b1")
+ })
+})
+
+describe("userAvatarUrl", () => {
+ it("has the correct format", () => {
+ expect(userAvatarUrl("u1")).toBe("/api/community/users/u1/avatar")
+ })
+})
+
+describe("botAvatarUrl", () => {
+ it("has the correct format", () => {
+ expect(botAvatarUrl("b1")).toBe("/api/community/bots/b1/avatar")
+ })
+})
+
+describe("no collisions between user and bot avatar keys for the same id", () => {
+ it("distinct R2 keys", () => {
+ expect(buildUserAvatarKey("same-id")).not.toBe(buildBotAvatarKey("same-id"))
+ })
+
+ it("distinct routable URLs", () => {
+ expect(userAvatarUrl("same-id")).not.toBe(botAvatarUrl("same-id"))
+ })
+})
diff --git a/src/web/src/lib/community/storage.ts b/src/web/src/lib/community/storage.ts
index cd43fbb7c..2531bcc5b 100644
--- a/src/web/src/lib/community/storage.ts
+++ b/src/web/src/lib/community/storage.ts
@@ -7,6 +7,25 @@ export function buildServerIconKey(serverId: string, fileId: string): string {
return `server-icon/${serverId}/${fileId}`
}
+// Deterministic keys — unlike server icons (random `fileId`, old key deleted
+// on replace), user/bot avatars overwrite the same R2 object in place, so the
+// routable URL stored on the DB row never changes across re-uploads.
+export function buildUserAvatarKey(userId: string): string {
+ return `user-avatar/${userId}`
+}
+
+export function userAvatarUrl(userId: string): string {
+ return `/api/community/users/${userId}/avatar`
+}
+
+export function buildBotAvatarKey(botId: string): string {
+ return `bot-avatar/${botId}`
+}
+
+export function botAvatarUrl(botId: string): string {
+ return `/api/community/bots/${botId}/avatar`
+}
+
/**
* Map a `communityServer` row to the public icon URL. The DB stores the R2
* key; clients need a routable URL. Returns `null` when no icon is set so
diff --git a/src/web/src/lib/community/upload.test.ts b/src/web/src/lib/community/upload.test.ts
index cee59946b..05c74ddb5 100644
--- a/src/web/src/lib/community/upload.test.ts
+++ b/src/web/src/lib/community/upload.test.ts
@@ -17,6 +17,8 @@ vi.mock("@/lib/db", () => ({ getDb: (...a: unknown[]) => mockGetDb(...a) }))
import {
handleAttachmentUpload,
handleServerIconUpload,
+ handleUserAvatarUpload,
+ handleBotAvatarUpload,
runAttachmentUpload,
} from "./upload"
import { MAX_ATTACHMENT_SIZE_BYTES, MAX_SERVER_ICON_SIZE_BYTES } from "@alook/shared"
@@ -35,7 +37,7 @@ function reqWithFile(file: unknown | null): NextRequest {
if (file) {
// FormData.set requires a real Blob; stash the test object on the
// FormData proxy directly instead.
- ;(fd as unknown as { __file: unknown }).__file = file
+ ; (fd as unknown as { __file: unknown }).__file = file
}
const req = new NextRequest("http://localhost/u", { method: "POST" })
req.formData = (async () => {
@@ -196,6 +198,112 @@ describe("handleServerIconUpload", () => {
})
})
+describe("handleUserAvatarUpload", () => {
+ beforeEach(() => vi.clearAllMocks())
+
+ it("uploads a valid png avatar under the deterministic user-avatar/{userId} key", async () => {
+ const put = vi.fn().mockResolvedValue(undefined)
+ const file = fakeFile("me.png", "image/png", 10)
+ const res = await handleUserAvatarUpload(reqWithFile(file), envWithR2(put), "u1")
+ expect(res.ok).toBe(true)
+ if (!res.ok) return
+ expect(res.key).toBe("user-avatar/u1")
+ })
+
+ it("returns the routable avatar route URL, not the (404-ing) media catch-all shape", async () => {
+ const put = vi.fn().mockResolvedValue(undefined)
+ const file = fakeFile("me.png", "image/png", 10)
+ const res = await handleUserAvatarUpload(reqWithFile(file), envWithR2(put), "u1")
+ expect(res.ok).toBe(true)
+ if (!res.ok) return
+ expect(res.url).toBe("/api/community/users/u1/avatar")
+ })
+
+ it("re-uploading the same user overwrites the same key (no fileId)", async () => {
+ const put = vi.fn().mockResolvedValue(undefined)
+ const first = await handleUserAvatarUpload(
+ reqWithFile(fakeFile("a.png", "image/png", 10)),
+ envWithR2(put),
+ "u1",
+ )
+ const second = await handleUserAvatarUpload(
+ reqWithFile(fakeFile("b.png", "image/png", 10)),
+ envWithR2(put),
+ "u1",
+ )
+ expect(first.ok && second.ok).toBe(true)
+ if (!first.ok || !second.ok) return
+ expect(first.key).toBe(second.key)
+ })
+
+ it("rejects oversize avatars with 413", async () => {
+ const put = vi.fn()
+ const file = fakeFile("big.png", "image/png", MAX_SERVER_ICON_SIZE_BYTES + 1)
+ const res = await handleUserAvatarUpload(reqWithFile(file), envWithR2(put), "u1")
+ expect(res.ok).toBe(false)
+ if (res.ok) return
+ expect(res.response.status).toBe(413)
+ expect(put).not.toHaveBeenCalled()
+ })
+
+ it("rejects non-image MIME types with 400", async () => {
+ const put = vi.fn()
+ const file = fakeFile("me.bmp", "image/bmp", 10)
+ const res = await handleUserAvatarUpload(reqWithFile(file), envWithR2(put), "u1")
+ expect(res.ok).toBe(false)
+ if (res.ok) return
+ expect(res.response.status).toBe(400)
+ })
+
+ it("rejects when no file is provided", async () => {
+ const put = vi.fn()
+ const res = await handleUserAvatarUpload(reqWithFile(null), envWithR2(put), "u1")
+ expect(res.ok).toBe(false)
+ if (res.ok) return
+ expect(res.response.status).toBe(400)
+ })
+})
+
+describe("handleBotAvatarUpload", () => {
+ beforeEach(() => vi.clearAllMocks())
+
+ it("uploads a valid png avatar under the deterministic bot-avatar/{botId} key", async () => {
+ const put = vi.fn().mockResolvedValue(undefined)
+ const file = fakeFile("bot.png", "image/png", 10)
+ const res = await handleBotAvatarUpload(reqWithFile(file), envWithR2(put), "b1")
+ expect(res.ok).toBe(true)
+ if (!res.ok) return
+ expect(res.key).toBe("bot-avatar/b1")
+ })
+
+ it("returns the routable avatar route URL, not the (404-ing) media catch-all shape", async () => {
+ const put = vi.fn().mockResolvedValue(undefined)
+ const file = fakeFile("bot.png", "image/png", 10)
+ const res = await handleBotAvatarUpload(reqWithFile(file), envWithR2(put), "b1")
+ expect(res.ok).toBe(true)
+ if (!res.ok) return
+ expect(res.url).toBe("/api/community/bots/b1/avatar")
+ })
+
+ it("rejects oversize avatars with 413", async () => {
+ const put = vi.fn()
+ const file = fakeFile("big.png", "image/png", MAX_SERVER_ICON_SIZE_BYTES + 1)
+ const res = await handleBotAvatarUpload(reqWithFile(file), envWithR2(put), "b1")
+ expect(res.ok).toBe(false)
+ if (res.ok) return
+ expect(res.response.status).toBe(413)
+ })
+
+ it("rejects non-image MIME types with 400", async () => {
+ const put = vi.fn()
+ const file = fakeFile("bot.bmp", "image/bmp", 10)
+ const res = await handleBotAvatarUpload(reqWithFile(file), envWithR2(put), "b1")
+ expect(res.ok).toBe(false)
+ if (res.ok) return
+ expect(res.response.status).toBe(400)
+ })
+})
+
describe("runAttachmentUpload", () => {
beforeEach(() => vi.clearAllMocks())
diff --git a/src/web/src/lib/community/upload.ts b/src/web/src/lib/community/upload.ts
index 1fe8a9833..b50e30600 100644
--- a/src/web/src/lib/community/upload.ts
+++ b/src/web/src/lib/community/upload.ts
@@ -10,7 +10,14 @@ import { writeError, writeJSON } from "@/lib/middleware/helpers"
import { getDb } from "@/lib/db"
import type { AuthContext } from "@/lib/middleware/auth"
import type { Result } from "./permissions"
-import { buildMediaKey, buildServerIconKey } from "./storage"
+import {
+ buildMediaKey,
+ buildServerIconKey,
+ buildUserAvatarKey,
+ buildBotAvatarKey,
+ userAvatarUrl,
+ botAvatarUrl,
+} from "./storage"
type UploadOk = {
ok: true
@@ -144,6 +151,71 @@ export async function handleServerIconUpload(
}
}
+/**
+ * Validate + upload a user/bot avatar to a deterministic key — unlike server
+ * icons, there's no `fileId`/old-key-delete dance since R2 `.put()` overwrites
+ * the same object in place on every re-upload. Shared by
+ * `handleUserAvatarUpload` and `handleBotAvatarUpload`, which only differ in
+ * key/URL builder.
+ */
+async function handleAvatarUpload(
+ req: NextRequest,
+ env: Env,
+ ownerId: string,
+ key: string,
+ url: string,
+): Promise<UploadResult> {
+ const fileOrErr = await readFile(req)
+ if ("ok" in fileOrErr && fileOrErr.ok === false) return fileOrErr
+ const file = fileOrErr as File
+
+ if (file.size > MAX_SERVER_ICON_SIZE_BYTES) {
+ return {
+ ok: false,
+ response: writeError(
+ `avatar too large (max ${Math.floor(MAX_SERVER_ICON_SIZE_BYTES / 1024 / 1024)}MB)`,
+ 413,
+ ),
+ }
+ }
+ if (!mimeAllowed(file.type, ALLOWED_ICON_MIME_TYPES as readonly string[])) {
+ return { ok: false, response: writeError("avatar must be png / jpeg / webp / gif", 400) }
+ }
+
+ await env.COMMUNITY_MEDIA.put(key, file, {
+ httpMetadata: { contentType: file.type },
+ })
+
+ return {
+ ok: true,
+ id: ownerId,
+ key,
+ // Not `/api/community/media/${key}` — that catch-all route only recognizes
+ // channel/thread/dm/server-icon kinds and would 404. `url` is the real
+ // routable dedicated avatar route (`userAvatarUrl`/`botAvatarUrl`).
+ url,
+ filename: file.name,
+ contentType: file.type,
+ size: file.size,
+ }
+}
+
+export function handleUserAvatarUpload(
+ req: NextRequest,
+ env: Env,
+ userId: string,
+): Promise<UploadResult> {
+ return handleAvatarUpload(req, env, userId, buildUserAvatarKey(userId), userAvatarUrl(userId))
+}
+
+export function handleBotAvatarUpload(
+ req: NextRequest,
+ env: Env,
+ botId: string,
+): Promise<UploadResult> {
+ return handleAvatarUpload(req, env, botId, buildBotAvatarKey(botId), botAvatarUrl(botId))
+}
+
/**
* Route body shared by the three attachment-upload endpoints
* (`channels/[id]/upload`, `dm/[id]/upload`, `threads/[id]/upload`). Parses