Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
fix(web): refresh avatar cache without fallback flashes (#484)
Gustavo Yee47a3552e957
diff --git a/src/shared/src/constants/community.ts b/src/shared/src/constants/community.tsindex b4c30a672..28986624b 100644--- a/src/shared/src/constants/community.ts+++ b/src/shared/src/constants/community.ts@@ -189,8 +189,7 @@ export type MentionKind = typeof MENTION_KIND[keyof typeof MENTION_KIND]// Cache headersexport 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"+// For user/bot avatars whose URL stays fixed across re-uploads. The browser+// may paint cached bytes immediately, then revalidate the R2 ETag in the+// background and replace its cache only when the object changed.+export const CACHE_REVALIDATE = "private, max-age=0, stale-while-revalidate=31536000"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.tsindex 57222c2b1..fec41dea9 100644--- 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@@ -105,9 +105,9 @@ describe("GET /api/community/bots/[id]/avatar", () => {expect(res.status).toBe(404)})- it("revalidates on every request instead of a long max-age (deterministic key never changes on re-upload)", async () => {+ it("serves cached bytes while revalidating the deterministic URL in the background", async () => {const res = await GET(getReq(), ctx("b1"))- expect(res.headers.get("Cache-Control")).toBe("no-cache, must-revalidate")+ expect(res.headers.get("Cache-Control")).toBe("private, max-age=0, stale-while-revalidate=31536000")expect(res.headers.get("ETag")).toBe('"etag-1"')})@@ -119,6 +119,7 @@ describe("GET /api/community/bots/[id]/avatar", () => {const res = await GET(req, ctx("b1"))expect(res.status).toBe(304)expect(res.headers.get("ETag")).toBe('"etag-1"')+ expect(res.headers.get("Cache-Control")).toBe("private, max-age=0, stale-while-revalidate=31536000")})})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.tsindex 3d1c8edd2..99a13a424 100644--- a/src/web/src/app/api/community/bots/[id]/avatar/route.ts+++ b/src/web/src/app/api/community/bots/[id]/avatar/route.ts@@ -8,10 +8,9 @@ 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.+// The URL never changes across re-uploads (deterministic key). Let the browser+// paint stale bytes while it revalidates the R2 ETag in the background, so a+// warm avatar never waits behind a network round trip.export const GET = withAuth(async (req: NextRequest, ctx) => {const botId = ctx.params?.idif (!botId) return writeError("missing bot id", 400)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.tsindex ef42864ba..67f6c1437 100644--- 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@@ -78,9 +78,9 @@ describe("GET /api/community/users/[userId]/avatar", () => {expect(res.status).toBe(404)})- it("revalidates on every request instead of a long max-age (deterministic key never changes on re-upload)", async () => {+ it("serves cached bytes while revalidating the deterministic URL in the background", async () => {const res = await GET(getReq(), ctx("u1"))- expect(res.headers.get("Cache-Control")).toBe("no-cache, must-revalidate")+ expect(res.headers.get("Cache-Control")).toBe("private, max-age=0, stale-while-revalidate=31536000")expect(res.headers.get("ETag")).toBe('"etag-1"')})@@ -92,6 +92,7 @@ describe("GET /api/community/users/[userId]/avatar", () => {const res = await GET(req, ctx("u1"))expect(res.status).toBe(304)expect(res.headers.get("ETag")).toBe('"etag-1"')+ expect(res.headers.get("Cache-Control")).toBe("private, max-age=0, stale-while-revalidate=31536000")})it("returns 200 with the full body when If-None-Match is stale", async () => {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.tsindex 035838b86..1e85c3e33 100644--- a/src/web/src/app/api/community/users/[userId]/avatar/route.ts+++ b/src/web/src/app/api/community/users/[userId]/avatar/route.ts@@ -8,10 +8,9 @@ import { buildUserAvatarKey } from "@/lib/community/storage"// "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.+// The URL never changes across re-uploads (deterministic key). Let the browser+// paint stale bytes while it revalidates the R2 ETag in the background, so a+// warm avatar never waits behind a network round trip.export const GET = withAuth(async (req: NextRequest, ctx) => {const userId = ctx.params?.userIdif (!userId) return writeError("missing user id", 400)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.tsindex 007a8a93e..734fa1fdb 100644--- 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@@ -4,6 +4,7 @@ import { NextRequest } from "next/server"const mockHandleUserAvatarUpload = vi.fn()const mockHandleBotAvatarUpload = vi.fn()const mockUpdateUser = vi.fn()+const mockAuthUpdateUser = vi.fn()vi.mock("@opennextjs/cloudflare", () => ({getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),@@ -11,6 +12,12 @@ vi.mock("@opennextjs/cloudflare", () => ({vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))+vi.mock("@/lib/auth", () => ({+ createAuth: vi.fn(() => ({+ api: { updateUser: (...a: unknown[]) => mockAuthUpdateUser(...a) },+ })),+}))+vi.mock("@alook/shared", async () => {const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")return {@@ -68,6 +75,7 @@ describe("POST /api/community/users/me/avatar", () => {isAuthed = trueactorKind = "human"mockUpdateUser.mockResolvedValue(undefined)+ mockAuthUpdateUser.mockResolvedValue({ headers: new Headers() })})it("rejects unauthenticated requests with 401", async () => {@@ -75,6 +83,7 @@ describe("POST /api/community/users/me/avatar", () => {const res = await POST(postReq(), {} as never)expect(res.status).toBe(401)expect(mockHandleUserAvatarUpload).not.toHaveBeenCalled()+ expect(mockAuthUpdateUser).not.toHaveBeenCalled()})it("forwards upload failures unchanged (e.g. 413 too large)", async () => {@@ -86,9 +95,13 @@ describe("POST /api/community/users/me/avatar", () => {const res = await POST(postReq(), {} as never)expect(res.status).toBe(413)expect(mockUpdateUser).not.toHaveBeenCalled()+ expect(mockAuthUpdateUser).not.toHaveBeenCalled()})- it("uploads for the caller's own userId (never a body-supplied id) and updates image to the routable URL", async () => {+ it("uploads for the caller's own userId and refreshes the signed session image", async () => {+ const headers = new Headers()+ headers.append("Set-Cookie", "better-auth.session_data=fresh; Path=/")+ mockAuthUpdateUser.mockResolvedValue({ headers })mockHandleUserAvatarUpload.mockResolvedValue({ok: true,id: "u1",@@ -104,7 +117,12 @@ describe("POST /api/community/users/me/avatar", () => {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" })+ expect(mockAuthUpdateUser).toHaveBeenCalledWith(expect.objectContaining({+ body: { image: "/api/community/users/u1/avatar" },+ returnHeaders: true,+ }))+ expect(mockUpdateUser).not.toHaveBeenCalled()+ expect(res.headers.getSetCookie()).toContain("better-auth.session_data=fresh; Path=/")})it("uses the bot avatar key and URL for a bot actor", async () => {@@ -124,5 +142,6 @@ describe("POST /api/community/users/me/avatar", () => {expect(mockHandleBotAvatarUpload).toHaveBeenCalledWith(expect.anything(), expect.anything(), "b1")expect(mockHandleUserAvatarUpload).not.toHaveBeenCalled()expect(mockUpdateUser).toHaveBeenCalledWith(expect.anything(), "b1", { image: "/api/community/bots/b1/avatar" })+ expect(mockAuthUpdateUser).not.toHaveBeenCalled()})})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.tsindex c77361056..2b40a8c33 100644--- a/src/web/src/app/api/community/users/me/avatar/route.ts+++ b/src/web/src/app/api/community/users/me/avatar/route.ts@@ -1,8 +1,9 @@-import { NextRequest } from "next/server"+import { NextRequest, NextResponse } from "next/server"import { queries } from "@alook/shared"import { withCommunityActor } from "@/lib/middleware/community-actor"import { writeJSON } from "@/lib/middleware/helpers"import { getDb } from "@/lib/db"+import { createAuth } from "@/lib/auth"import { handleBotAvatarUpload, handleUserAvatarUpload } from "@/lib/community/upload"import { botAvatarUrl, userAvatarUrl } from "@/lib/community/storage"@@ -15,7 +16,28 @@ export const POST = withCommunityActor(async (req: NextRequest, ctx) => {const db = getDb(ctx.env.DB)const url = ctx.actor.kind === "bot" ? botAvatarUrl(userId) : userAvatarUrl(userId)- await queries.user.updateUser(db, userId, { image: url })+ let sessionHeaders: Headers | undefined+ if (ctx.actor.kind === "bot") {+ await queries.user.updateUser(db, userId, { image: url })+ } else {+ // Better Auth updates the row and re-signs its cached session payload.+ // Without forwarding that cookie, a full /c remount starts from the old+ // session image and briefly paints a generated avatar until the canonical+ // profile request finishes.+ const auth = createAuth(ctx.env)+ const result = (await auth.api.updateUser({+ body: { image: url },+ headers: req.headers,+ returnHeaders: true,+ })) as { headers: Headers }+ sessionHeaders = result.headers+ }- return writeJSON({ url })+ const res = writeJSON({ url })+ const setCookies = sessionHeaders?.getSetCookie() ?? []+ if (setCookies.length === 0) return res++ const response = new NextResponse(res.body, res)+ for (const cookie of setCookies) response.headers.append("Set-Cookie", cookie)+ return response})diff --git a/src/web/src/components/avatar/profile-avatar.error.test.ts b/src/web/src/components/avatar/profile-avatar.error.test.tsnew file mode 100644index 000000000..5264b8d9c--- /dev/null+++ b/src/web/src/components/avatar/profile-avatar.error.test.ts@@ -0,0 +1,28 @@+import { createElement } from "react"+import TestRenderer, { act } from "react-test-renderer"+import { describe, expect, it } from "vitest"+import { ProfileAvatar } from "./profile-avatar"++globalThis.IS_REACT_ACT_ENVIRONMENT = true++describe("ProfileAvatar photo errors", () => {+ it("shows the fallback only after the photo reports an error", async () => {+ let renderer: TestRenderer.ReactTestRenderer++ await act(async () => {+ renderer = TestRenderer.create(createElement(ProfileAvatar, {+ label: "Ada",+ src: "https://cdn.example.com/missing.png",+ seed: "user_1",+ }))+ })++ const image = renderer!.root.findByProps({ "data-slot": "avatar-image" })+ await act(async () => {+ image.props.onError()+ })++ expect(renderer!.root.findAllByProps({ "data-slot": "avatar-image" })).toHaveLength(0)+ expect(JSON.stringify(renderer!.toJSON())).toContain('"children":["A"]')+ })+})diff --git a/src/web/src/components/avatar/profile-avatar.test.ts b/src/web/src/components/avatar/profile-avatar.test.tsindex afecb3aaa..3b87d82d6 100644--- a/src/web/src/components/avatar/profile-avatar.test.ts+++ b/src/web/src/components/avatar/profile-avatar.test.ts@@ -1,4 +1,4 @@-import { Children, createElement, type ReactElement, type ReactNode } from "react"+import { createElement } from "react"import { renderToStaticMarkup } from "react-dom/server"import { describe, expect, it } from "vitest"import { serializeBeamSeed } from "@/lib/avatar/seed-url"@@ -12,18 +12,8 @@ function render(props: ProfileAvatarProps): string {return renderToStaticMarkup(createElement(ProfileAvatar, props))}-function resolvedImageProps(props: ProfileAvatarProps): { src: string; alt: string } {- const root = ProfileAvatar(props) as ReactElement<{ children: ReactNode }>- const branch = Children.toArray(root.props.children)[0] as ReactElement<{ children: ReactNode }>- const image = Children.toArray(branch.props.children)[0] as ReactElement<{- src: string- alt: string- }>- return image.props-}-describe("ProfileAvatar", () => {- it("renders a photo with the requested label, size, and caller class", () => {+ it("mounts a photo immediately without showing the loading fallback", () => {const html = render({label: "Ada",src: "https://cdn.example.com/ada.png",@@ -35,10 +25,8 @@ describe("ProfileAvatar", () => {expect(html).toContain('data-testid="profile-avatar"')expect(html).toContain('data-avatar-kind="photo"')- expect(resolvedImageProps({- label: "Ada",- src: "https://cdn.example.com/ada.png",- })).toMatchObject({ src: "https://cdn.example.com/ada.png", alt: "Ada" })+ expect(html).toContain('<img data-slot="avatar-image" src="https://cdn.example.com/ada.png" alt="Ada"')+ expect(html).not.toContain('data-slot="avatar-fallback"')expect(html).toContain("width:40px;height:40px")expect(html).toContain("ring-2")})@@ -83,7 +71,7 @@ describe("ProfileAvatar", () => {})expect(html).toContain('data-avatar-kind="photo"')- expect(resolvedImageProps({ label: "Ada", src: "/api/avatar", alt: "" }).alt).toBe("")+ expect(html).toContain('<img data-slot="avatar-image" src="/api/avatar" alt=""')expect(html).toContain('aria-hidden="true"')expect(html).not.toContain('role="img"')expect(html).not.toContain("aria-label")diff --git a/src/web/src/components/avatar/profile-avatar.tsx b/src/web/src/components/avatar/profile-avatar.tsxindex 0045c6a2d..e579e0730 100644--- a/src/web/src/components/avatar/profile-avatar.tsx+++ b/src/web/src/components/avatar/profile-avatar.tsx@@ -1,10 +1,9 @@"use client"-import type { ReactNode } from "react"+import { useState, type ReactNode } from "react"import {Avatar as UiAvatar,AvatarFallback,- AvatarImage,} from "@/components/ui/avatar"import { resolveAvatar } from "@/lib/avatar/resolve"import { avatarInitial } from "@/lib/community/avatar"@@ -23,6 +22,33 @@ export type ProfileAvatarProps = {"data-testid"?: string}+function ProfilePhoto({ src, alt, fallback, fontSize }: {+ src: string+ alt: string+ fallback: string+ fontSize: number+}) {+ const [failed, setFailed] = useState(false)++ if (failed) {+ return (+ <AvatarFallback className="font-medium" style={{ fontSize }}>+ {fallback}+ </AvatarFallback>+ )+ }++ return (+ <img+ data-slot="avatar-image"+ src={src}+ alt={alt}+ className="aspect-square size-full rounded-full object-cover"+ onError={() => setFailed(true)}+ />+ )+}+export function ProfileAvatar({label,src,@@ -50,12 +76,13 @@ export function ProfileAvatar({aria-hidden={decorative ? true : undefined}>{resolved.kind === "photo" ? (- <>- <AvatarImage src={resolved.url} alt={accessibleLabel} />- <AvatarFallback className="font-medium" style={{ fontSize: size * 0.4 }}>- {avatarInitial(safeLabel)}- </AvatarFallback>- </>+ <ProfilePhoto+ key={resolved.url}+ src={resolved.url}+ alt={accessibleLabel}+ fallback={avatarInitial(safeLabel)}+ fontSize={size * 0.4}+ />) : resolved.kind === "beam" ? (<span className="size-full overflow-hidden rounded-full"><GeneratedAvatar seed={resolved.seed} size={size} className="size-full rounded-full" />diff --git a/src/web/src/components/community/avatar.test.ts b/src/web/src/components/community/avatar.test.tsindex ac1216861..d380e4a06 100644--- a/src/web/src/components/community/avatar.test.ts+++ b/src/web/src/components/community/avatar.test.ts@@ -39,11 +39,13 @@ describe("Avatar seed contract", () => {expect(html).not.toContain('data-slot="avatar-fallback"')})- it("keeps stored avatar sources out of the accessibility tree", () => {- for (const source of [+ it("keeps stored avatar sources out of accessible labels", () => {+ const sources = [serializeBeamSeed("private-seed"),"https://cdn.example.com/private-avatar.png",- ]) {+ ]++ for (const source of sources) {const element = Avatar({ label: source, seed: "usr_1" })const html = render({ label: source, seed: "usr_1" })@@ -52,8 +54,10 @@ describe("Avatar seed contract", () => {expect(html).toContain('aria-hidden="true"')expect(html).not.toContain('role="img"')expect(html).not.toContain("aria-label")- expect(html).not.toContain(source)}++ expect(render({ label: sources[0]!, seed: "usr_1" })).not.toContain(sources[0]!)+ expect(render({ label: sources[1]!, seed: "usr_1" })).toContain(`src="${sources[1]}"`)})it("is stable for the same seed", () => {