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): reuse media cache and let slow images finish (#886)
Gener208c24c9ae3e
diff --git a/src/web/src/app/api/artifacts/[id]/thumbnail/route.test.ts b/src/web/src/app/api/artifacts/[id]/thumbnail/route.test.tsindex a471a2c36..2fab8494c 100644--- a/src/web/src/app/api/artifacts/[id]/thumbnail/route.test.ts+++ b/src/web/src/app/api/artifacts/[id]/thumbnail/route.test.ts@@ -58,6 +58,7 @@ describe("GET /api/artifacts/[id]/thumbnail", () => {);expect(res.status).toBe(200);+ expect(res.headers.get("Vary")).toBe("Authorization");expect(res.headers.get("Content-Type")).toBe("image/jpeg");expect(res.headers.get("Cache-Control")).toBe("private, max-age=31536000, immutable");expect(mockBucketGet).toHaveBeenCalledWith("artifacts/w1/ag1/c1/art_1/thumbnail.jpg");@@ -77,6 +78,7 @@ describe("GET /api/artifacts/[id]/thumbnail", () => {);expect(res.status).toBe(404);+ expect(res.headers.get("Cache-Control")).toBe("private, no-store");expect(mockBucketGet).not.toHaveBeenCalled();});@@ -89,6 +91,7 @@ describe("GET /api/artifacts/[id]/thumbnail", () => {);expect(res.status).toBe(404);+ expect(res.headers.get("Cache-Control")).toBe("private, no-store");});it("returns 404 when agent not accessible to user", async () => {@@ -105,5 +108,6 @@ describe("GET /api/artifacts/[id]/thumbnail", () => {);expect(res.status).toBe(404);+ expect(res.headers.get("Cache-Control")).toBe("private, no-store");});});diff --git a/src/web/src/app/api/artifacts/[id]/thumbnail/route.ts b/src/web/src/app/api/artifacts/[id]/thumbnail/route.tsindex 1c97b11fb..00afa431b 100644--- a/src/web/src/app/api/artifacts/[id]/thumbnail/route.ts+++ b/src/web/src/app/api/artifacts/[id]/thumbnail/route.ts@@ -2,10 +2,11 @@ import { NextRequest } from "next/server";import { queries } from "@alook/shared";import { getDb } from "@/lib/db"import { withAuth } from "@/lib/middleware/auth";+import { withPrivateMediaCache } from "@/lib/middleware/private-media-cache"import { withWorkspaceMember } from "@/lib/middleware/workspace";import { writeError } from "@/lib/middleware/helpers";-export const GET = withAuth(async (req: NextRequest, ctx) => {+export const GET = withPrivateMediaCache(withAuth(async (req: NextRequest, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;@@ -38,4 +39,4 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {"Cache-Control": "private, max-age=31536000, immutable",},});-});+}));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 4cb545751..39f899d45 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@@ -106,12 +106,14 @@ describe("GET /api/community/bots/[id]/avatar", () => {isAuthed = falseconst res = await GET(getReq(), ctx("b1"))expect(res.status).toBe(401)+ expect(res.headers.get("Cache-Control")).toBe("private, no-store")expect(mediaGet).not.toHaveBeenCalled()})it("serves a live canonical avatar by the deterministic key without an owner check", async () => {const res = await GET(getReq(), ctx("b1"))expect(res.status).toBe(200)+ expect(res.headers.get("Vary")).toBe("Authorization")expect(res.headers.get("Content-Type")).toBe("image/webp")expect(mediaGet).toHaveBeenCalledWith("bot-avatar/b1")expect(mockGetBotOwnedBy).not.toHaveBeenCalled()@@ -122,6 +124,7 @@ describe("GET /api/community/bots/[id]/avatar", () => {mockGetLiveBotAvatar.mockResolvedValue(null)const res = await GET(getReq(), ctx("b1"))expect(res.status).toBe(404)+ expect(res.headers.get("Cache-Control")).toBe("private, no-store")expect(mediaGet).not.toHaveBeenCalled()})@@ -134,6 +137,7 @@ describe("GET /api/community/bots/[id]/avatar", () => {})const res = await GET(getReq(), ctx("b1"))expect(res.status).toBe(404)+ expect(res.headers.get("Cache-Control")).toBe("private, no-store")expect(mediaGet).not.toHaveBeenCalled()})@@ -148,12 +152,14 @@ describe("GET /api/community/bots/[id]/avatar", () => {const res = await GET(getReq(4), ctx("b1"))expect(res.status).toBe(404)+ expect(res.headers.get("Cache-Control")).toBe("private, no-store")expect(mediaGet).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(res.headers.get("Cache-Control")).toBe("private, no-store")expect(mediaGet).not.toHaveBeenCalled()})@@ -161,6 +167,7 @@ describe("GET /api/community/bots/[id]/avatar", () => {mediaGet.mockResolvedValue(null)const res = await GET(getReq(), ctx("b1"))expect(res.status).toBe(404)+ expect(res.headers.get("Cache-Control")).toBe("private, no-store")})it("redirects the stable route to the authoritative immutable version", async () => {@@ -190,6 +197,7 @@ describe("GET /api/community/bots/[id]/avatar", () => {const res = await GET(getReq(4), ctx("b1"))expect(res.status).toBe(200)+ expect(res.headers.get("Vary")).toBe("Authorization")expect(res.headers.get("Cache-Control")).toBe("private, max-age=31536000, immutable")expect(mediaGet).toHaveBeenCalledWith("bot-avatar/b1/objects/object-4")})@@ -198,6 +206,7 @@ describe("GET /api/community/bots/[id]/avatar", () => {const res = await GET(getReq(4), ctx("b1"))expect(res.status).toBe(307)+ expect(res.headers.get("Cache-Control")).toBe("private, no-store")expect(res.headers.get("Location")).toBe("/api/community/bots/b1/avatar")expect(mediaGet).not.toHaveBeenCalled()})@@ -215,6 +224,7 @@ describe("GET /api/community/bots/[id]/avatar", () => {})const res = await GET(req, ctx("b1"))expect(res.status).toBe(304)+ expect(res.headers.get("Vary")).toBe("Authorization")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 aaa3d0dd2..b9d4e9e1c 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@@ -1,6 +1,7 @@import { NextRequest } from "next/server"import { CACHE_REVALIDATE, createLogger, queries } from "@alook/shared"import { withAuth } from "@/lib/middleware/auth"+import { withPrivateMediaCache } from "@/lib/middleware/private-media-cache"import { writeJSON, writeError } from "@/lib/middleware/helpers"import { getDb } from "@/lib/db"import { handleBotAvatarUpload } from "@/lib/community/upload"@@ -20,7 +21,7 @@ import { fanOutIdentityUpdate } from "@/lib/community/fanout"const log = createLogger({ service: "community-bot-avatar-route" })const PRIVATE_NO_STORE = "private, no-store"-export const GET = withAuth(async (req: NextRequest, ctx) => {+export const GET = withPrivateMediaCache(withAuth(async (req: NextRequest, ctx) => {const botId = ctx.params?.idif (!botId) return writeError("missing bot id", 400)@@ -71,7 +72,7 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {...(etag ? { ETag: etag } : {}),},})-})+}))export const POST = withAuth(async (req: NextRequest, ctx) => {const botId = ctx.params?.iddiff --git a/src/web/src/app/api/community/channels/[id]/attachments/[attachmentId]/route.test.ts b/src/web/src/app/api/community/channels/[id]/attachments/[attachmentId]/route.test.tsindex e617c17ad..09ea8a694 100644--- a/src/web/src/app/api/community/channels/[id]/attachments/[attachmentId]/route.test.ts+++ b/src/web/src/app/api/community/channels/[id]/attachments/[attachmentId]/route.test.ts@@ -121,12 +121,14 @@ describe("GET /api/community/channels/[id]/attachments/[attachmentId]", () => {it("404 when attachmentId is missing", async () => {const res = await GET(req({ Authorization: "Bearer crk_abc" }), ctx(undefined))expect(res.status).toBe(404)+ expect(res.headers.get("Cache-Control")).toBe("private, no-store")})it("404 when the id doesn't exist (bot)", async () => {mockGetAttachmentById.mockResolvedValue(null)const res = await GET(req({ Authorization: "Bearer crk_abc" }), ctx())expect(res.status).toBe(404)+ expect(res.headers.get("Cache-Control")).toBe("private, no-store")expect(await res.json()).toEqual({ error: "attachment not found" })})@@ -143,6 +145,7 @@ describe("GET /api/community/channels/[id]/attachments/[attachmentId]", () => {const res = await GET(req({ Authorization: "Bearer crk_abc" }), ctx("att_1", "c1"))expect(res.status).toBe(404)+ expect(res.headers.get("Cache-Control")).toBe("private, no-store")// The membership gate was called with the ROW's message channel, not "c1".expect(mockRequireChannelMember).toHaveBeenCalledWith({}, "c_real", "bot_1")// No path-id was consulted for authz.@@ -154,6 +157,7 @@ describe("GET /api/community/channels/[id]/attachments/[attachmentId]", () => {mockGetAttachmentById.mockResolvedValue(persistedRow({ messageId: null, uploaderId: "other" }))const res = await GET(req({ Authorization: "Bearer crk_abc" }), ctx())expect(res.status).toBe(404)+ expect(res.headers.get("Cache-Control")).toBe("private, no-store")expect(await res.json()).toEqual({ error: "attachment not found" })expect(mockR2Get).not.toHaveBeenCalled()})@@ -163,6 +167,7 @@ describe("GET /api/community/channels/[id]/attachments/[attachmentId]", () => {mockR2Get.mockResolvedValue(r2Object())const res = await GET(req({ Authorization: "Bearer crk_abc" }), ctx())expect(res.status).toBe(200)+ expect(res.headers.get("Vary")).toBe("Authorization")expect(res.headers.get("Content-Type")).toBe("image/png")expect(res.headers.get("Content-Length")).toBe("10")expect(res.headers.get("X-Alook-Filename")).toBe(encodeURIComponent("a.png"))@@ -182,6 +187,7 @@ describe("GET /api/community/channels/[id]/attachments/[attachmentId]", () => {const res = await GET(req({ Authorization: "Bearer crk_abc", Range: "bytes=2-4" }), ctx())expect(res.status).toBe(200)+ expect(res.headers.get("Vary")).toBe("Authorization")expect(mockR2Get).toHaveBeenCalledWith("channel/c_row/uuid/a.png")expect(res.headers.get("X-Alook-Filename")).toBe(encodeURIComponent("clip.mp4"))expect(res.headers.get("Content-Range")).toBeNull()@@ -193,6 +199,7 @@ describe("GET /api/community/channels/[id]/attachments/[attachmentId]", () => {mockR2Get.mockResolvedValue(r2Object())const res = await GET(req({ Authorization: "Bearer crk_abc" }), ctx())expect(res.status).toBe(200)+ expect(res.headers.get("Vary")).toBe("Authorization")const encoded = res.headers.get("X-Alook-Filename")expect(encoded).toBeTruthy()expect(decodeURIComponent(encoded!)).toBe("图表.png")@@ -206,6 +213,7 @@ describe("GET /api/community/channels/[id]/attachments/[attachmentId]", () => {mockR2Get.mockResolvedValue(r2Object())const res = await GET(req(), ctx()) // no crk_ → human armexpect(res.status).toBe(200)+ expect(res.headers.get("Vary")).toBe("Authorization")expect(res.headers.get("Content-Type")).toBe("image/png")expect(res.headers.get("Content-Disposition")).toBe("inline")expect(res.headers.get("Cache-Control")).toBe("private, max-age=31536000, immutable")@@ -220,6 +228,7 @@ describe("GET /api/community/channels/[id]/attachments/[attachmentId]", () => {mockR2Get.mockResolvedValue(r2Object({ httpMetadata: { contentType: "application/pdf" } }))const res = await GET(req(), ctx())expect(res.status).toBe(200)+ expect(res.headers.get("Vary")).toBe("Authorization")expect(res.headers.get("Content-Disposition")).toBe("attachment; filename=\"doc.pdf\"; filename*=UTF-8''doc.pdf")})@@ -229,6 +238,7 @@ describe("GET /api/community/channels/[id]/attachments/[attachmentId]", () => {mockR2Get.mockResolvedValue(r2Object({ size: bytes.length }, bytes))const res = await GET(req(), ctx())expect(res.status).toBe(200)+ expect(res.headers.get("Vary")).toBe("Authorization")expect(decodeURIComponent(res.headers.get("Content-Disposition")!.split("filename*=UTF-8''")[1])).toBe(filename)expect(new Uint8Array(await res.arrayBuffer())).toEqual(bytes)})@@ -245,6 +255,7 @@ describe("GET /api/community/channels/[id]/attachments/[attachmentId]", () => {const res = await GET(req(), ctx())expect(res.status).toBe(200)+ expect(res.headers.get("Vary")).toBe("Authorization")expect(res.headers.get("Content-Type")).toBe("video/mp4")expect(res.headers.get("Content-Disposition")).toBe("inline")expect(res.headers.get("Accept-Ranges")).toBe("bytes")@@ -264,6 +275,7 @@ describe("GET /api/community/channels/[id]/attachments/[attachmentId]", () => {const res = await GET(req(), ctx())expect(res.status).toBe(200)+ expect(res.headers.get("Vary")).toBe("Authorization")expect(res.headers.get("Content-Type")).toBe("audio/mp4")expect(res.headers.get("Content-Disposition")).toBe("inline")expect(res.headers.get("Accept-Ranges")).toBe("bytes")@@ -285,6 +297,7 @@ describe("GET /api/community/channels/[id]/attachments/[attachmentId]", () => {const res = await GET(req({ Range: range }), ctx())expect(res.status).toBe(206)+ expect(res.headers.get("Vary")).toBe("Authorization")expect(mockR2Get).toHaveBeenCalledWith("channel/c_row/uuid/a.png", { range: { offset, length } })expect(res.headers.get("Content-Range")).toBe(contentRange)expect(res.headers.get("Content-Length")).toBe(String(length))@@ -307,6 +320,7 @@ describe("GET /api/community/channels/[id]/attachments/[attachmentId]", () => {const res = await GET(req({ Range: range }), ctx())expect(res.status).toBe(416)+ expect(res.headers.get("Cache-Control")).toBe("private, no-store")expect(res.headers.get("Content-Range")).toBe("bytes */10")expect(res.headers.get("Accept-Ranges")).toBe("bytes")expect(mockR2Get).not.toHaveBeenCalled()@@ -323,6 +337,7 @@ describe("GET /api/community/channels/[id]/attachments/[attachmentId]", () => {expect(mockR2Head).toHaveBeenCalledWith("channel/c_row/uuid/a.png")expect(mockR2Get).toHaveBeenCalledWith("channel/c_row/uuid/a.png", { range: { offset: 4, length: 3 } })expect(res.status).toBe(206)+ expect(res.headers.get("Vary")).toBe("Authorization")expect(res.headers.get("Content-Range")).toBe("bytes 4-6/10")})@@ -333,6 +348,7 @@ describe("GET /api/community/channels/[id]/attachments/[attachmentId]", () => {const res = await GET(req({ Range: "bytes=0-2" }), ctx())expect(res.status).toBe(502)+ expect(res.headers.get("Cache-Control")).toBe("private, no-store")expect(mockR2Get).toHaveBeenCalledWith("channel/c_row/uuid/a.png", { range: { offset: 0, length: 3 } })})@@ -343,6 +359,7 @@ describe("GET /api/community/channels/[id]/attachments/[attachmentId]", () => {const res = await GET(req({ Range: "bytes=2-4" }), ctx())expect(res.status).toBe(200)+ expect(res.headers.get("Vary")).toBe("Authorization")expect(res.headers.get("Content-Disposition")).toBe("attachment; filename=\"doc.pdf\"; filename*=UTF-8''doc.pdf")expect(res.headers.get("Accept-Ranges")).toBeNull()expect(res.headers.get("Content-Range")).toBeNull()@@ -357,6 +374,7 @@ describe("GET /api/community/channels/[id]/attachments/[attachmentId]", () => {mockR2Get.mockResolvedValue(r2Object())const res = await GET(req({ Authorization: "Bearer crk_abc" }), ctx())expect(res.status).toBe(200)+ expect(res.headers.get("Vary")).toBe("Authorization")expect(mockRequireDMAccess).toHaveBeenCalledWith({}, "dm_1", "bot_1")expect(mockRequireChannelMember).not.toHaveBeenCalled()})@@ -366,12 +384,14 @@ describe("GET /api/community/channels/[id]/attachments/[attachmentId]", () => {mockR2Get.mockResolvedValue(null)const res = await GET(req({ Authorization: "Bearer crk_abc" }), ctx())expect(res.status).toBe(502)+ expect(res.headers.get("Cache-Control")).toBe("private, no-store")})it("getAttachmentById throws → 500 JSON envelope (no binary body leak)", async () => {mockGetAttachmentById.mockRejectedValueOnce(new Error("d1_transient"))const res = await GET(req({ Authorization: "Bearer crk_abc" }), ctx())expect(res.status).toBe(500)+ expect(res.headers.get("Cache-Control")).toBe("private, no-store")expect(await res.json()).toEqual({ error: "internal error", code: "internal" })})@@ -386,6 +406,7 @@ describe("GET /api/community/channels/[id]/attachments/[attachmentId]", () => {)const res = await GET(req({ Authorization: "Bearer crk_abc" }), ctx())expect(res.status).toBe(500)+ expect(res.headers.get("Cache-Control")).toBe("private, no-store")expect(await res.json()).toEqual({ error: "internal error", code: "internal" })})})diff --git a/src/web/src/app/api/community/channels/[id]/attachments/[attachmentId]/route.ts b/src/web/src/app/api/community/channels/[id]/attachments/[attachmentId]/route.tsindex d90556335..96e19bcba 100644--- a/src/web/src/app/api/community/channels/[id]/attachments/[attachmentId]/route.ts+++ b/src/web/src/app/api/community/channels/[id]/attachments/[attachmentId]/route.ts@@ -3,6 +3,7 @@ import { NextResponse, type NextRequest } from "next/server"import { createLogger } from "@alook/shared"import { getDb } from "@/lib/db"import { withCommunityActor } from "@/lib/middleware/community-actor"+import { withPrivateMediaCache } from "@/lib/middleware/private-media-cache"import { authorizeAttachment } from "@/lib/community/attachment-authorization"import { ATTACHMENT_PRIVATE_IMMUTABLE_CACHE } from "@/lib/community/storage"import { resolveAttachmentPresentation, resolveMediaContentType } from "@/lib/community/attachment-presentation"@@ -56,7 +57,7 @@ function parseByteRange(value: string, size: number): ParsedByteRange | null {* when the DB row exists but R2 has drifted (infra fault, not a user-facing* gate). Response FORM forks by actor; the authz core is identical.*/-export const GET = withCommunityActor(async (req: NextRequest, ctx) => {+export const GET = withPrivateMediaCache(withCommunityActor(async (req: NextRequest, ctx) => {const attachmentId = ctx.params?.attachmentIdif (!attachmentId) {return NextResponse.json({ error: "attachment not found" }, { status: 404 })@@ -159,4 +160,4 @@ export const GET = withCommunityActor(async (req: NextRequest, ctx) => {})return NextResponse.json({ error: "internal error", code: "internal" }, { status: 500 })}-})+}))diff --git a/src/web/src/app/api/community/channels/[id]/attachments/[attachmentId]/thumbnail/route.test.ts b/src/web/src/app/api/community/channels/[id]/attachments/[attachmentId]/thumbnail/route.test.tsindex 2384d5999..ff57cd157 100644--- a/src/web/src/app/api/community/channels/[id]/attachments/[attachmentId]/thumbnail/route.test.ts+++ b/src/web/src/app/api/community/channels/[id]/attachments/[attachmentId]/thumbnail/route.test.ts@@ -31,6 +31,7 @@ describe("GET attachment thumbnail", () => {mockAuthorizeAttachment.mockResolvedValue(authz)const response = await GET(request, ctx)expect(response.status).toBe(404)+ expect(response.headers.get("Cache-Control")).toBe("private, no-store")expect(mockR2Get).not.toHaveBeenCalled()})@@ -46,6 +47,7 @@ describe("GET attachment thumbnail", () => {mockR2Get.mockResolvedValue({ body })const response = await GET(request, ctx)expect(response.status).toBe(200)+ expect(response.headers.get("Vary")).toBe("Authorization")expect(mockR2Get).toHaveBeenCalledWith("key.thumb")expect(response.headers.get("Content-Type")).toBe("image/jpeg")expect(response.headers.get("Content-Disposition")).toBe("inline")diff --git a/src/web/src/app/api/community/channels/[id]/attachments/[attachmentId]/thumbnail/route.ts b/src/web/src/app/api/community/channels/[id]/attachments/[attachmentId]/thumbnail/route.tsindex bbb731bce..f1810073a 100644--- a/src/web/src/app/api/community/channels/[id]/attachments/[attachmentId]/thumbnail/route.ts+++ b/src/web/src/app/api/community/channels/[id]/attachments/[attachmentId]/thumbnail/route.ts@@ -2,12 +2,13 @@ import { NextResponse, type NextRequest } from "next/server"import { createLogger } from "@alook/shared"import { getDb } from "@/lib/db"import { withCommunityActor } from "@/lib/middleware/community-actor"+import { withPrivateMediaCache } from "@/lib/middleware/private-media-cache"import { authorizeAttachment } from "@/lib/community/attachment-authorization"import { ATTACHMENT_PRIVATE_IMMUTABLE_CACHE } from "@/lib/community/storage"const log = createLogger({ service: "community-attachment-thumbnail-download" })-export const GET = withCommunityActor(async (_req: NextRequest, ctx) => {+export const GET = withPrivateMediaCache(withCommunityActor(async (_req: NextRequest, ctx) => {const attachmentId = ctx.params?.attachmentIdif (!attachmentId) {return NextResponse.json({ error: "attachment not found" }, { status: 404 })@@ -41,4 +42,4 @@ export const GET = withCommunityActor(async (_req: NextRequest, ctx) => {})return NextResponse.json({ error: "internal error", code: "internal" }, { status: 500 })}-})+}))diff --git a/src/web/src/app/api/community/servers/[id]/icon/route.test.ts b/src/web/src/app/api/community/servers/[id]/icon/route.test.tsindex 780183f18..47ef5c58a 100644--- a/src/web/src/app/api/community/servers/[id]/icon/route.test.ts+++ b/src/web/src/app/api/community/servers/[id]/icon/route.test.ts@@ -135,12 +135,14 @@ describe("GET /api/community/servers/[id]/icon", () => {isAuthed = falseconst res = await GET(getReq(), ctx())expect(res.status).toBe(401)+ expect(res.headers.get("Cache-Control")).toBe("private, no-store")expect(mediaGet).not.toHaveBeenCalled()})it("serves the icon by direct R2 key (no LIST)", async () => {const res = await GET(getReq(), ctx())expect(res.status).toBe(200)+ expect(res.headers.get("Vary")).toBe("Authorization")expect(res.headers.get("Content-Type")).toBe("image/webp")expect(res.headers.get("Cache-Control")).toBe("private, max-age=31536000, immutable")expect(res.headers.get("ETag")).toBe('"icon-abc"')@@ -159,6 +161,7 @@ describe("GET /api/community/servers/[id]/icon", () => {it("returns a private 304 for the current unchanged object", async () => {const res = await GET(getReq("server-icon/s1/abc", { "If-None-Match": '"icon-abc"' }), ctx())expect(res.status).toBe(304)+ expect(res.headers.get("Vary")).toBe("Authorization")expect(res.headers.get("ETag")).toBe('"icon-abc"')expect(res.headers.get("Cache-Control")).toBe("private, max-age=31536000, immutable")expect(await res.text()).toBe("")@@ -169,6 +172,7 @@ describe("GET /api/community/servers/[id]/icon", () => {// `media/[...key]` treatment of `server-icon`.const res = await GET(getReq(), ctx())expect(res.status).toBe(200)+ expect(res.headers.get("Vary")).toBe("Authorization")expect(mockGetMember).not.toHaveBeenCalled()})@@ -176,6 +180,7 @@ describe("GET /api/community/servers/[id]/icon", () => {mockGetServer.mockResolvedValue({ id: "s1", icon: null })const res = await GET(getReq(), ctx())expect(res.status).toBe(404)+ expect(res.headers.get("Cache-Control")).toBe("private, no-store")expect(mediaGet).not.toHaveBeenCalled()})@@ -183,6 +188,7 @@ describe("GET /api/community/servers/[id]/icon", () => {mediaGet.mockResolvedValue(null)const res = await GET(getReq(), ctx())expect(res.status).toBe(404)+ expect(res.headers.get("Cache-Control")).toBe("private, no-store")})})diff --git a/src/web/src/app/api/community/servers/[id]/icon/route.ts b/src/web/src/app/api/community/servers/[id]/icon/route.tsindex d07bd993f..e33f8220e 100644--- a/src/web/src/app/api/community/servers/[id]/icon/route.ts+++ b/src/web/src/app/api/community/servers/[id]/icon/route.ts@@ -1,6 +1,7 @@import { NextRequest } from "next/server"import { getCloudflareContext } from "@opennextjs/cloudflare"import { withAuth } from "@/lib/middleware/auth"+import { withPrivateMediaCache } from "@/lib/middleware/private-media-cache"import { writeJSON, writeError } from "@/lib/middleware/helpers"import { getDb } from "@/lib/db"import { queries, WS_EVENTS, createLogger } from "@alook/shared"@@ -16,7 +17,7 @@ import {const log = createLogger({ service: "community-server-icon" })-export const GET = withAuth(async (req: NextRequest, ctx) => {+export const GET = withPrivateMediaCache(withAuth(async (req: NextRequest, ctx) => {const serverId = ctx.params?.idif (!serverId) return writeError("missing server id", 400)@@ -46,7 +47,7 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {return new Response(obj.body, {headers,})-})+}))export const POST = withAuth(async (req: NextRequest, ctx) => {const serverId = ctx.params?.iddiff --git a/src/web/src/app/api/community/share-image/avatar/[userId]/route.test.ts b/src/web/src/app/api/community/share-image/avatar/[userId]/route.test.tsindex 1987ba380..4b26da62b 100644--- a/src/web/src/app/api/community/share-image/avatar/[userId]/route.test.ts+++ b/src/web/src/app/api/community/share-image/avatar/[userId]/route.test.ts@@ -7,7 +7,8 @@ const routeMocks = vi.hoisted(() => ({}))vi.mock("@/lib/db", () => ({ getDb: routeMocks.getDb }))-vi.mock("@alook/shared", () => ({+vi.mock("@alook/shared", async () => ({+ ...(await vi.importActual<typeof import("@alook/shared")>("@alook/shared")),queries: {communityUserProfile: {getPublicProfileForViewer: (...args: unknown[]) => routeMocks.getPublicProfileForViewer(...args),@@ -82,6 +83,7 @@ describe("GET /api/community/share-image/avatar/[userId]", () => {const response = await request("u2", "?url=http://169.254.169.254/latest/meta-data&token=leak")expect(response.status).toBe(200)+ expect(response.headers.get("Vary")).toBe("Authorization")expect(routeMocks.getDb).toHaveBeenCalledWith("database")expect(routeMocks.getPublicProfileForViewer).toHaveBeenCalledWith(expect.anything(),@@ -114,6 +116,7 @@ describe("GET /api/community/share-image/avatar/[userId]", () => {const response = await request()expect(response.status).toBe(404)+ expect(response.headers.get("Cache-Control")).toBe("private, no-store")expect(fetch).not.toHaveBeenCalled()})@@ -126,6 +129,7 @@ describe("GET /api/community/share-image/avatar/[userId]", () => {const response = await request()expect(response.status).toBe(502)+ expect(response.headers.get("Cache-Control")).toBe("private, no-store")expect(await response.json()).toEqual({ error: "external avatar redirect rejected" })})@@ -137,6 +141,7 @@ describe("GET /api/community/share-image/avatar/[userId]", () => {const response = await request()expect(response.status).toBe(502)+ expect(response.headers.get("Cache-Control")).toBe("private, no-store")expect(await response.json()).toEqual({ error: "external avatar unavailable" })})@@ -148,6 +153,7 @@ describe("GET /api/community/share-image/avatar/[userId]", () => {const response = await request()expect(response.status).toBe(502)+ expect(response.headers.get("Cache-Control")).toBe("private, no-store")expect(await response.json()).toEqual({ error: "external avatar unavailable" })})@@ -164,6 +170,7 @@ describe("GET /api/community/share-image/avatar/[userId]", () => {const response = await request()expect(response.status).toBe(502)+ expect(response.headers.get("Cache-Control")).toBe("private, no-store")expect(await response.json()).toEqual({ error: "external avatar unavailable" })})@@ -180,6 +187,7 @@ describe("GET /api/community/share-image/avatar/[userId]", () => {const response = await pendingexpect(response.status).toBe(504)+ expect(response.headers.get("Cache-Control")).toBe("private, no-store")expect(await response.json()).toEqual({ error: "external avatar timed out" })})@@ -192,6 +200,7 @@ describe("GET /api/community/share-image/avatar/[userId]", () => {const response = await request()expect(response.status).toBe(502)+ expect(response.headers.get("Cache-Control")).toBe("private, no-store")expect(log).not.toHaveBeenCalled()expect(warn).not.toHaveBeenCalled()expect(error).not.toHaveBeenCalled()diff --git a/src/web/src/app/api/community/share-image/avatar/[userId]/route.ts b/src/web/src/app/api/community/share-image/avatar/[userId]/route.tsindex 06f0f707c..d9e53aef8 100644--- a/src/web/src/app/api/community/share-image/avatar/[userId]/route.ts+++ b/src/web/src/app/api/community/share-image/avatar/[userId]/route.ts@@ -2,6 +2,7 @@ import { NextRequest } from "next/server"import { queries } from "@alook/shared"import { getDb } from "@/lib/db"import { withAuth } from "@/lib/middleware/auth"+import { withPrivateMediaCache } from "@/lib/middleware/private-media-cache"import { writeError } from "@/lib/middleware/helpers"const ALLOWED_AVATAR_HOSTS = new Set([@@ -72,7 +73,7 @@ async function readLimitedImage(response: Response): Promise<{ bytes: Uint8Arrayreturn { bytes, type }}-export const GET = withAuth(async (_req: NextRequest, ctx) => {+export const GET = withPrivateMediaCache(withAuth(async (_req: NextRequest, ctx) => {const userId = ctx.params?.userIdif (!userId) return writeError("missing user id", 400)@@ -114,4 +115,4 @@ export const GET = withAuth(async (_req: NextRequest, ctx) => {} finally {clearTimeout(timer)}-})+}))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 2f81765e5..833125037 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,12 +78,14 @@ describe("GET /api/community/users/[userId]/avatar", () => {isAuthed = falseconst res = await GET(getReq(), ctx("u1"))expect(res.status).toBe(401)+ expect(res.headers.get("Cache-Control")).toBe("private, no-store")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("Vary")).toBe("Authorization")expect(res.headers.get("Content-Type")).toBe("image/webp")expect(mediaGet).toHaveBeenCalledWith("user-avatar/u1")})@@ -91,6 +93,7 @@ describe("GET /api/community/users/[userId]/avatar", () => {it("returns 400 when the userId route param is missing", async () => {const res = await GET(getReq(), ctx(undefined))expect(res.status).toBe(400)+ expect(res.headers.get("Cache-Control")).toBe("private, no-store")expect(mediaGet).not.toHaveBeenCalled()})@@ -98,6 +101,7 @@ describe("GET /api/community/users/[userId]/avatar", () => {mediaGet.mockResolvedValue(null)const res = await GET(getReq(), ctx("u1"))expect(res.status).toBe(404)+ expect(res.headers.get("Cache-Control")).toBe("private, no-store")})it("returns 404 before R2 for an inconsistent version/object-key pair", async () => {@@ -109,6 +113,7 @@ describe("GET /api/community/users/[userId]/avatar", () => {const res = await GET(getReq(4), ctx("u1"))expect(res.status).toBe(404)+ expect(res.headers.get("Cache-Control")).toBe("private, no-store")expect(mediaGet).not.toHaveBeenCalled()})@@ -135,6 +140,7 @@ describe("GET /api/community/users/[userId]/avatar", () => {const res = await GET(getReq(3), ctx("u1"))expect(res.status).toBe(200)+ expect(res.headers.get("Vary")).toBe("Authorization")expect(res.headers.get("Cache-Control")).toBe("private, max-age=31536000, immutable")expect(mediaGet).toHaveBeenCalledWith("user-avatar/u1/objects/object-3")})@@ -143,6 +149,7 @@ describe("GET /api/community/users/[userId]/avatar", () => {const res = await GET(getReq(3), ctx("u1"))expect(res.status).toBe(307)+ expect(res.headers.get("Cache-Control")).toBe("private, no-store")expect(res.headers.get("Location")).toBe("/api/community/users/u1/avatar")expect(mediaGet).not.toHaveBeenCalled()})@@ -160,6 +167,7 @@ describe("GET /api/community/users/[userId]/avatar", () => {})const res = await GET(req, ctx("u1"))expect(res.status).toBe(304)+ expect(res.headers.get("Vary")).toBe("Authorization")expect(res.headers.get("ETag")).toBe('"etag-1"')expect(res.headers.get("Cache-Control")).toBe("private, max-age=0, stale-while-revalidate=31536000")})@@ -171,5 +179,6 @@ describe("GET /api/community/users/[userId]/avatar", () => {})const res = await GET(req, ctx("u1"))expect(res.status).toBe(200)+ expect(res.headers.get("Vary")).toBe("Authorization")})})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 ea4d947ae..6dde0db2f 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@@ -1,6 +1,7 @@import { NextRequest } from "next/server"import { CACHE_REVALIDATE, createLogger, queries } from "@alook/shared"import { withAuth } from "@/lib/middleware/auth"+import { withPrivateMediaCache } from "@/lib/middleware/private-media-cache"import { writeError } from "@/lib/middleware/helpers"import { getDb } from "@/lib/db"import {@@ -13,7 +14,7 @@ import {const log = createLogger({ service: "community-user-avatar" })const PRIVATE_NO_STORE = "private, no-store"-export const GET = withAuth(async (req: NextRequest, ctx) => {+export const GET = withPrivateMediaCache(withAuth(async (req: NextRequest, ctx) => {const userId = ctx.params?.userIdif (!userId) return writeError("missing user id", 400)@@ -66,4 +67,4 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {...(etag ? { ETag: etag } : {}),},})-})+}))diff --git a/src/web/src/app/api/email/[id]/attachment/[index]/route.test.ts b/src/web/src/app/api/email/[id]/attachment/[index]/route.test.tsindex b2bc14c21..a473360a3 100644--- a/src/web/src/app/api/email/[id]/attachment/[index]/route.test.ts+++ b/src/web/src/app/api/email/[id]/attachment/[index]/route.test.ts@@ -44,11 +44,13 @@ describe("GET /api/email/[id]/attachment/[index]", () => {it("400 when email id missing", async () => {const res = await get({ index: "0" });expect(res.status).toBe(400);+ expect(res.headers.get("Cache-Control")).toBe("private, no-store");});it("400 when index is not a valid number", async () => {const res = await get({ id: "e1", index: "abc" });expect(res.status).toBe(400);+ expect(res.headers.get("Cache-Control")).toBe("private, no-store");expect((await res.json()).error).toBe("invalid attachment index");});@@ -56,6 +58,7 @@ describe("GET /api/email/[id]/attachment/[index]", () => {mockGetById.mockResolvedValue(null);const res = await get({ id: "e1", index: "0" });expect(res.status).toBe(404);+ expect(res.headers.get("Cache-Control")).toBe("private, no-store");expect(mockGetById).toHaveBeenCalledWith({}, "e1", "w1");});@@ -65,6 +68,7 @@ describe("GET /api/email/[id]/attachment/[index]", () => {mockBucketGet.mockResolvedValue(null);const res = await get({ id: "e1", index: "0" });expect(res.status).toBe(404);+ expect(res.headers.get("Cache-Control")).toBe("private, no-store");expect((await res.json()).error).toBe("email content not available");});@@ -76,6 +80,7 @@ describe("GET /api/email/[id]/attachment/[index]", () => {mockFilter.mockReturnValue([]);const res = await get({ id: "e1", index: "0" });expect(res.status).toBe(404);+ expect(res.headers.get("Cache-Control")).toBe("private, no-store");expect((await res.json()).error).toBe("attachment not found");});@@ -88,6 +93,7 @@ describe("GET /api/email/[id]/attachment/[index]", () => {mockFilter.mockReturnValue([{ filename, mimeType: "application/octet-stream", content: bytes.buffer }]);const res = await get({ id: "e1", index: "0" });expect(res.status).toBe(200);+ expect(res.headers.get("Vary")).toBe("Authorization");expect(decodeURIComponent(res.headers.get("Content-Disposition")!.split("filename*=UTF-8''")[1])).toBe(filename);expect(new Uint8Array(await res.arrayBuffer())).toEqual(bytes);});@@ -102,6 +108,7 @@ describe("GET /api/email/[id]/attachment/[index]", () => {]);const res = await get({ id: "e1", index: "0" });expect(res.status).toBe(200);+ expect(res.headers.get("Vary")).toBe("Authorization");expect(res.headers.get("Content-Type")).toBe("application/pdf");expect(res.headers.get("Content-Disposition")).toContain("report.pdf");});diff --git a/src/web/src/app/api/email/[id]/attachment/[index]/route.ts b/src/web/src/app/api/email/[id]/attachment/[index]/route.tsindex 9e666ffed..befa9e540 100644--- a/src/web/src/app/api/email/[id]/attachment/[index]/route.ts+++ b/src/web/src/app/api/email/[id]/attachment/[index]/route.ts@@ -3,10 +3,11 @@ import PostalMime from "postal-mime";import { queries, filterDownloadableAttachments } from "@alook/shared";import { getDb } from "@/lib/db"import { withAuth } from "@/lib/middleware/auth";+import { withPrivateMediaCache } from "@/lib/middleware/private-media-cache"import { withWorkspaceMember } from "@/lib/middleware/workspace";import { writeError } from "@/lib/middleware/helpers";-export const GET = withAuth(async (req, ctx) => {+export const GET = withPrivateMediaCache(withAuth(async (req, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;@@ -46,4 +47,4 @@ export const GET = withAuth(async (req, ctx) => {"Cache-Control": "private, max-age=3600",},});-});+}));diff --git a/src/web/src/components/avatar/profile-avatar.error.dom.test.ts b/src/web/src/components/avatar/profile-avatar.error.dom.test.tsindex 09d08cb4f..96f7408f9 100644--- a/src/web/src/components/avatar/profile-avatar.error.dom.test.ts+++ b/src/web/src/components/avatar/profile-avatar.error.dom.test.ts@@ -98,25 +98,27 @@ describe("ProfileAvatar photo errors", () => {expect(photo(rendered.container)).toHaveAttribute("data-avatar-photo-state", "ready")})- it("settles a pending photo to a static placeholder after the readiness timeout", async () => {+ it("keeps a slow photo pending and reveals its late success", async () => {vi.useFakeTimers()const rendered = render(createElement(ProfileAvatar, {label: "Ada",- src: "https://cdn.example.com/never.png",+ src: "https://cdn.example.com/slow.png",seed: "user_1",}))- await act(async () => vi.advanceTimersByTime(5_000))+ await act(async () => vi.advanceTimersByTime(30_000))const image = photo(rendered.container)- expect(image).toHaveAttribute("data-avatar-photo-state", "failed")- expect(placeholder(rendered.container)).toHaveAttribute("data-avatar-photo-placeholder", "failed")- expect(placeholder(rendered.container)).not.toHaveClass("animate-pulse")+ expect(image).toHaveAttribute("data-avatar-photo-state", "pending")+ expect(placeholder(rendered.container)).toHaveAttribute("data-avatar-photo-placeholder", "pending")+ expect(placeholder(rendered.container)).toHaveClass("animate-pulse")setLoadedImageMetrics(image)fireEvent.load(image)await act(async () => { await Promise.resolve() })- expect(photo(rendered.container)).toHaveAttribute("data-avatar-photo-state", "failed")+ expect(photo(rendered.container)).toHaveAttribute("data-avatar-photo-state", "ready")+ expect(placeholder(rendered.container)).not.toHaveAttribute("data-avatar-photo-placeholder")+ expect(placeholder(rendered.container)).not.toHaveClass("animate-pulse")})it("retries from a neutral skeleton when the photo source changes", () => {diff --git a/src/web/src/components/community/messages/image-lightbox.dom.test.ts b/src/web/src/components/community/messages/image-lightbox.dom.test.tsindex fdecd4987..9d49282b7 100644--- a/src/web/src/components/community/messages/image-lightbox.dom.test.ts+++ b/src/web/src/components/community/messages/image-lightbox.dom.test.ts@@ -256,18 +256,32 @@ describe("ImageLightbox", () => {expect(renderer.getByTestId(tid.imageLightbox).style.aspectRatio).toBe("1 / 1")})- it("turns a stalled eager original into a static retryable error", async () => {- vi.useFakeTimers()+ it("keeps a slow original pending and displays its success beyond five seconds", async () => {+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] })const { renderer } = renderLightbox({ originalUrl: "/stalled", name: "stalled" })const loading = renderer.getByTestId(tid.imageLightboxLoading)expect(loading).toHaveClass("motion-reduce:animate-none")- await act(async () => vi.advanceTimersByTime(5_000))+ await act(async () => vi.advanceTimersByTime(30_000))+ expect(renderer.getByTestId(tid.imageLightboxLoading)).toBe(loading)+ expect(renderer.queryByTestId(tid.imageLightboxError)).not.toBeInTheDocument()+ await loadImage(image(renderer, tid.imageLightboxOriginal), 800, 600, () => Promise.resolve())+ expect(image(renderer, tid.imageLightboxOriginal)).toHaveClass("opacity-100")+ expect(renderer.queryByTestId(tid.imageLightboxLoading)).not.toBeInTheDocument()+ })- expect(renderer.queryAllByTestId(tid.imageLightboxLoading)).toHaveLength(0)- const error = renderer.getByTestId(tid.imageLightboxError)- expect(error.querySelector("span")).toHaveTextContent("Failed to load original image")- expect(renderer.getByTestId(tid.imageLightboxRetry)).toHaveClass("min-w-12")+ it("reveals a decoded original even when its thumbnail stays pending", async () => {+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] })+ const { renderer } = renderLightbox({ originalUrl: "/original", thumbnailUrl: "/stalled-thumbnail", name: "Photo" })+ await act(async () => vi.advanceTimersByTime(30_000))+ expect(image(renderer, tid.imageLightboxThumbnail)).toHaveAttribute("data-remote-image-state", "pending")+ await loadImage(image(renderer, tid.imageLightboxOriginal), 1200, 600, () => Promise.resolve())+ expect(image(renderer, tid.imageLightboxOriginal)).toHaveClass("opacity-100")+ expect(image(renderer, tid.imageLightboxThumbnail)).toHaveAttribute("data-remote-image-state", "pending")+ expect(renderer.queryByTestId(tid.imageLightboxLoading)).not.toBeInTheDocument()+ await loadThumbnail(renderer, 512, 256)+ expect(image(renderer, tid.imageLightboxThumbnail)).toHaveClass("opacity-0")+ expect(image(renderer, tid.imageLightboxOriginal)).toHaveClass("opacity-100")})it("shows a cold pending frame, then paints the thumbnail before an already-decoded original", async () => {diff --git a/src/web/src/components/community/messages/image-lightbox.tsx b/src/web/src/components/community/messages/image-lightbox.tsxindex f427a1ace..7b455acdb 100644--- a/src/web/src/components/community/messages/image-lightbox.tsx+++ b/src/web/src/components/community/messages/image-lightbox.tsx@@ -27,7 +27,7 @@ function PreviewFrame({ image }: { image: ImagePreview }) {thumbnailRef,onThumbnailLoad,onThumbnailError,- ] = useRemoteImageAttempt({ eligible: !!image.thumbnailUrl })+ ] = useRemoteImageAttempt()const [originalStatus,originalAttempt,@@ -40,11 +40,10 @@ function PreviewFrame({ image }: { image: ImagePreview }) {const frameStyle = previewFrameStyle(dimensions)const thumbnailReady = !!image.thumbnailUrl && thumbnailStatus === "ready"- const thumbnailSettled = !image.thumbnailUrl || thumbnailStatus !== "pending"const originalReady = originalStatus === "ready" && revealedAttempt === originalAttemptuseEffect(() => {- if (originalStatus !== "ready" || !originalImage || !thumbnailSettled) return+ if (originalStatus !== "ready" || !originalImage) returnconst requestKey = originalAttemptconst naturalDimensions = validImageDimensions(originalImage.naturalWidth, originalImage.naturalHeight)const reveal = () => {@@ -57,7 +56,7 @@ function PreviewFrame({ image }: { image: ImagePreview }) {}const frameId = requestAnimationFrame(reveal)return () => cancelAnimationFrame(frameId)- }, [knownDimensions, originalAttempt, originalImage, originalStatus, setDimensions, setRevealedAttempt, thumbnailSettled])+ }, [knownDimensions, originalAttempt, originalImage, originalStatus, setDimensions, setRevealedAttempt])return (<div className="relative w-fit">diff --git a/src/web/src/components/remote-image/remote-image-attempt.ts b/src/web/src/components/remote-image/remote-image-attempt.tsindex 93bae6e8c..265006486 100644--- a/src/web/src/components/remote-image/remote-image-attempt.ts+++ b/src/web/src/components/remote-image/remote-image-attempt.ts@@ -2,15 +2,12 @@import {useCallback,- useEffect,useLayoutEffect,useMemo,type RefCallback,type SyntheticEvent,} from "react"-import { createStore, useSelector, useAtom, useCreateAtom } from "@tanstack/react-store"--export const REMOTE_IMAGE_TIMEOUT_MS = 5_000+import { createStore, useSelector } from "@tanstack/react-store"export type RemoteImageStatus = "pending" | "ready" | "error"@@ -35,15 +32,7 @@ function reduceAttempt(state: AttemptState, action: AttemptAction): AttemptState: { attempt: state.attempt, status: "error" }}-type RemoteImageAttemptOptions = {- eligible?: boolean- timeoutMs?: number-}--export function useRemoteImageAttempt({- eligible = true,- timeoutMs = REMOTE_IMAGE_TIMEOUT_MS,-}: RemoteImageAttemptOptions = {}) {+export function useRemoteImageAttempt() {const store = useMemo(() => createStore({ attempt: 0, status: "pending", active: true, generation: 0 } as AttemptState & { active: boolean; generation: number }), [])const state = useSelector(store, (value) => value)const dispatch = useCallback((action: AttemptAction, generation = store.get().generation) => store.setState((current) => {@@ -89,13 +78,6 @@ export function useRemoteImageAttempt({const retry = useCallback(() => dispatch({ type: "retry" }), [dispatch])- useEffect(() => {- if (!eligible || state.status !== "pending") return- const attempt = state.attempt- const timeout = setTimeout(() => dispatch({ type: "error", attempt }), timeoutMs)- return () => clearTimeout(timeout)- }, [dispatch, eligible, state.attempt, state.status, timeoutMs])-return [state.status,state.attempt,@@ -106,30 +88,3 @@ export function useRemoteImageAttempt({retry,] as const}--export function useRemoteImageEligibility(lazy: boolean) {- const [element, setElement] = useAtom(useCreateAtom<HTMLElement | null>(null))- const [eligible, setEligible] = useAtom(useCreateAtom(!lazy))- const ref = useCallback((next: HTMLElement | null) => setElement(next), [setElement])-- useEffect(() => {- if (!lazy) {- setEligible(true)- return- }- if (!element || eligible) return- if (typeof IntersectionObserver === "undefined") {- setEligible(true)- return- }- const observer = new IntersectionObserver((entries) => {- if (!entries.some((entry) => entry.isIntersecting)) return- setEligible(true)- observer.disconnect()- }, { rootMargin: "300px" })- observer.observe(element)- return () => observer.disconnect()- }, [element, eligible, lazy, setEligible])-- return [eligible, ref] as const-}diff --git a/src/web/src/components/remote-image/remote-image.dom.test.ts b/src/web/src/components/remote-image/remote-image.dom.test.tsindex 6ba1fcf9f..ef987f17d 100644--- a/src/web/src/components/remote-image/remote-image.dom.test.ts+++ b/src/web/src/components/remote-image/remote-image.dom.test.ts@@ -3,6 +3,7 @@ import { afterEach, describe, expect, it, vi } from "vitest"import { act, fireEvent, render, screen } from "@/test/react-dom-harness"import { RemoteContentImage, RemoteIdentityImage } from "./remote-image"import { RemoteMarkdownImage } from "./remote-markdown-image"+import { ApplicationOwnerProvider, createApplicationOwner } from "@/lib/application-owner"function setImageMetrics(image: HTMLImageElement,@@ -132,35 +133,64 @@ describe("remote image state adapters", () => {expect(contentImage(rendered.container)).toHaveAttribute("data-remote-image-state", "ready")})- it("does not start a lazy timeout until the frame becomes viewport-eligible", async () => {+ it.each([+ { name: "identity", element: () => React.createElement(RemoteIdentityImage, { src: "/slow-avatar.png", alt: "Avatar" }) },+ { name: "eager content", element: () => React.createElement(RemoteContentImage, { src: "/slow-eager.png", alt: "Eager", loading: "eager" }) },+ { name: "lazy content", element: () => React.createElement(RemoteContentImage, { src: "/slow-lazy.png", alt: "Lazy", loading: "lazy" }) },+ { name: "Markdown", element: () => React.createElement(RemoteMarkdownImage, { src: "/slow-markdown.png", alt: "Markdown" }) },+ ])("keeps $name pending beyond five seconds and reveals its late decoded success", async ({ element }) => {vi.useFakeTimers()- let observe!: IntersectionObserverCallback- vi.stubGlobal("IntersectionObserver", class {- constructor(callback: IntersectionObserverCallback) {- observe = callback- }- observe() {}- disconnect() {}- unobserve() {}- takeRecords() { return [] }- readonly root = null- readonly rootMargin = "300px"- readonly thresholds = [0]- })+ let finishDecode!: () => void+ const decode = new Promise<void>((resolve) => { finishDecode = resolve })+ const owner = createApplicationOwner("slow-image-viewer")+ const rendered = render(React.createElement(ApplicationOwnerProvider, { owner }, element()))+ const image = rendered.container.querySelector<HTMLImageElement>("img")!+ await act(async () => vi.advanceTimersByTime(30_000))+ expect(image).toHaveAttribute("data-remote-image-state", "pending")+ expect(image).toHaveClass("opacity-0")+ expect(rendered.queryByRole("button", { name: "Retry" })).not.toBeInTheDocument()- const rendered = render(React.createElement(RemoteContentImage, {- src: "/below-the-fold.png",- alt: "Below the fold",- loading: "lazy",- timeoutMs: 100,- frameStyle: { width: 300, aspectRatio: "4/3" },- }))- await act(async () => vi.advanceTimersByTime(500))+ setImageMetrics(image, () => decode)+ fireEvent.load(image)+ await act(async () => vi.advanceTimersByTime(30_000))+ expect(image).toHaveAttribute("data-remote-image-state", "pending")+ await act(async () => { finishDecode(); await decode })+ expect(image).toHaveAttribute("data-remote-image-state", "ready")+ expect(image).toHaveClass("opacity-100")+ rendered.unmount()+ owner.queryClient.clear()+ })++ it("keeps lazy loading native while a real decode failure remains retryable", async () => {+ const rendered = render(React.createElement(RemoteContentImage, { src: "/decode.png", alt: "Photo", loading: "lazy" }))+ const image = contentImage(rendered.container)+ expect(image).toHaveAttribute("loading", "lazy")+ setImageMetrics(image, () => Promise.reject(new Error("decode failed")))+ fireEvent.load(image)+ await act(async () => { await Promise.resolve() })+ expect(image).toHaveAttribute("data-remote-image-state", "error")+ fireEvent.click(rendered.getByRole("button", { name: "Retry" }))+ expect(contentImage(rendered.container)).toHaveAttribute("src", "/decode.png")expect(contentImage(rendered.container)).toHaveAttribute("data-remote-image-state", "pending")+ })- act(() => observe([{ isIntersecting: true } as IntersectionObserverEntry], {} as IntersectionObserver))- await act(async () => vi.advanceTimersByTime(100))- expect(contentImage(rendered.container)).toHaveAttribute("data-remote-image-state", "error")+ it("ignores a late decoded success after the source changes", async () => {+ let finishOldDecode!: () => void+ const oldDecode = new Promise<void>((resolve) => { finishOldDecode = resolve })+ const element = (src: string) => React.createElement(RemoteContentImage, { src, alt: "Photo" })+ const rendered = render(element("/old.png"))+ const oldImage = contentImage(rendered.container)+ setImageMetrics(oldImage, () => oldDecode)+ fireEvent.load(oldImage)+ rendered.rerender(element("/new.png"))+ await act(async () => { finishOldDecode(); await oldDecode })+ const current = contentImage(rendered.container)+ expect(current).toHaveAttribute("src", "/new.png")+ expect(current).toHaveAttribute("data-remote-image-state", "pending")+ setImageMetrics(current)+ fireEvent.load(current)+ await act(async () => { await Promise.resolve() })+ expect(current).toHaveAttribute("data-remote-image-state", "ready")})it("rejects a decoded image without natural pixels", async () => {diff --git a/src/web/src/components/remote-image/remote-image.tsx b/src/web/src/components/remote-image/remote-image.tsxindex 64247f974..cf109b4d8 100644--- a/src/web/src/components/remote-image/remote-image.tsx+++ b/src/web/src/components/remote-image/remote-image.tsx@@ -10,9 +10,7 @@ import {} from "react"import { cn } from "@/lib/utils"import {- REMOTE_IMAGE_TIMEOUT_MS,useRemoteImageAttempt,- useRemoteImageEligibility,type RemoteImageStatus,} from "./remote-image-attempt"@@ -22,7 +20,6 @@ type IdentityImageProps = {className?: stringplaceholderClassName?: stringprofilePhoto?: boolean- timeoutMs?: number"data-testid"?: string}@@ -32,10 +29,9 @@ function IdentityImageAttempt({className,placeholderClassName,profilePhoto = false,- timeoutMs,"data-testid": testId,}: IdentityImageProps) {- const [status, attempt, , imageRef, onLoad, onError, retry] = useRemoteImageAttempt({ timeoutMs })+ const [status, attempt, , imageRef, onLoad, onError, retry] = useRemoteImageAttempt()const retryAfterReconnect = useEffectEvent(() => {if (status !== "ready") retry()})@@ -99,7 +95,6 @@ type ContentImageProps = Omit<loadingLabel?: stringerrorLabel?: stringretryLabel?: string- timeoutMs?: numberonActivate?: (event: MouseEvent<HTMLButtonElement>) => voidactivateLabel?: stringonReady?: (image: HTMLImageElement) => void@@ -118,7 +113,6 @@ function ContentImageAttempt({loadingLabel,errorLabel = "Image failed to load",retryLabel = "Retry",- timeoutMs = REMOTE_IMAGE_TIMEOUT_MS,onActivate,activateLabel,onReady,@@ -126,11 +120,7 @@ function ContentImageAttempt({"data-testid": testId,...imageProps}: ContentImageProps) {- const [eligible, eligibilityRef] = useRemoteImageEligibility(loading === "lazy")- const [status, attempt, readyImage, imageRef, onLoad, onError, retry] = useRemoteImageAttempt({- eligible,- timeoutMs,- })+ const [status, attempt, readyImage, imageRef, onLoad, onError, retry] = useRemoteImageAttempt()const notifyReady = useEffectEvent((image: HTMLImageElement) => onReady?.(image))useEffect(() => onStateChange?.(status), [onStateChange, status])@@ -176,7 +166,6 @@ function ContentImageAttempt({return (<div- ref={eligibilityRef}data-remote-image-framedata-remote-image-state={status}className={cn("relative overflow-hidden bg-muted/30", frameClassName)}diff --git a/src/web/src/components/remote-image/remote-markdown-image.tsx b/src/web/src/components/remote-image/remote-markdown-image.tsxindex 194c36356..da28c74de 100644--- a/src/web/src/components/remote-image/remote-markdown-image.tsx+++ b/src/web/src/components/remote-image/remote-markdown-image.tsx@@ -3,7 +3,7 @@import { Download } from "lucide-react"import { FileDownloadButton } from "@/components/file-download-button"import { cn } from "@/lib/utils"-import { useRemoteImageAttempt, useRemoteImageEligibility } from "./remote-image-attempt"+import { useRemoteImageAttempt } from "./remote-image-attempt"function dimension(value: unknown): number | undefined {const parsed = typeof value === "number" ? value : Number.parseFloat(String(value ?? ""))@@ -28,10 +28,7 @@ function MarkdownImageAttempt({...rest}: MarkdownImageProps) {void node- const [eligible, eligibilityRef] = useRemoteImageEligibility(true)- const [status, attempt, , imageRef, onLoad, onError, retry] = useRemoteImageAttempt({- eligible,- })+ const [status, attempt, , imageRef, onLoad, onError, retry] = useRemoteImageAttempt()const imageWidth = dimension(width)const imageHeight = dimension(height)const aspectRatio = imageWidth && imageHeight ? `${imageWidth}/${imageHeight}` : "4/3"@@ -43,7 +40,6 @@ function MarkdownImageAttempt({return (<div- ref={eligibilityRef}data-streamdown="image-wrapper"data-remote-image-state={status}className="group relative my-4 inline-block max-w-full overflow-hidden rounded-lg bg-muted/30"diff --git a/src/web/src/lib/middleware/private-media-cache.test.ts b/src/web/src/lib/middleware/private-media-cache.test.tsnew file mode 100644index 000000000..c87d0c1fd--- /dev/null+++ b/src/web/src/lib/middleware/private-media-cache.test.ts@@ -0,0 +1,198 @@+import { beforeEach, describe, expect, it, vi } from "vitest"+import { NextRequest, NextResponse } from "next/server"++const mocks = vi.hoisted(() => ({+ getSession: vi.fn(),+ signOut: vi.fn(),+ getMachineToken: vi.fn(),+ updateMachineToken: vi.fn(),+ resolveBotActor: vi.fn(),+}))++vi.mock("@opennextjs/cloudflare", () => ({+ getCloudflareContext: vi.fn(async () => ({ env: { DB: {} } })),+}))+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))+vi.mock("@/lib/auth", () => ({+ getAuth: vi.fn(() => ({ api: { getSession: mocks.getSession, signOut: mocks.signOut } })),+}))+vi.mock("@alook/shared", async () => {+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")+ return {+ ...actual,+ queries: {+ ...actual.queries,+ machineToken: {+ ...actual.queries.machineToken,+ getMachineTokenByToken: mocks.getMachineToken,+ updateMachineTokenLastUsed: mocks.updateMachineToken,+ },+ },+ }+})+vi.mock("./community-agent-runner-auth", () => ({ resolveBotActor: mocks.resolveBotActor }))++import { withAuth, type AuthenticatedHandler } from "./auth"+import { withCommunityActor, type CommunityActorHandler } from "./community-actor"+import { withPrivateMediaCache } from "./private-media-cache"++const IMMUTABLE = "private, max-age=31536000, immutable"+const request = (headers: Record<string, string> = {}) =>+ new NextRequest("https://example.com/api/media/fixed?v=1", { headers })+const session = (id = "A", fields: Record<string, unknown> = {}) => ({+ headers: new Headers({ "Set-Cookie": "better-auth.session_data=fixture-refresh; Path=/; HttpOnly" }),+ response: { user: { id, email: `${id}@example.com`, ...fields } },+})+const media = (status = 200, headers: Record<string, string> = {}) =>+ new Response(status === 304 ? null : "fixed media", {+ status,+ headers: { "Cache-Control": IMMUTABLE, ETag: '"media-v1"', ...headers },+ })++beforeEach(() => {+ vi.resetAllMocks()+ mocks.getSession.mockResolvedValue(session())+ mocks.getMachineToken.mockResolvedValue({ id: "mt1", userId: "A", userEmail: "[email protected]", workspaceId: "ws1" })+ mocks.resolveBotActor.mockResolvedValue({+ kind: "bot",+ actor: { botUserId: "bot1", ownerUserId: "owner1", machineId: "machine1", isActive: true },+ })+})++describe("selected private media response policy", () => {+ it.each([200, 206, 304])("preserves status %s, streaming body, validators and existing framework Vary", async (status) => {+ const original = media(status, {+ Vary: "Accept-Encoding, cOoKiE, RSC, Next-Router-State-Tree, Authorization",+ ...(status === 206 ? { "Content-Range": "bytes 0-10/100", "Accept-Ranges": "bytes" } : {}),+ })+ const result = await withPrivateMediaCache(async () => original)(request())+ expect(result.status).toBe(status)+ expect(result.body).toBe(original.body)+ expect(original.bodyUsed).toBe(false)+ expect(result.headers.get("Cache-Control")).toBe(IMMUTABLE)+ expect(result.headers.get("ETag")).toBe('"media-v1"')+ expect(result.headers.get("Vary")).toBe("Accept-Encoding, RSC, Next-Router-State-Tree, Authorization")+ if (status === 206) expect(result.headers.get("Content-Range")).toBe("bytes 0-10/100")+ })++ it.each(["*", "Accept-Encoding, *", "Cookie, *"])("preserves wildcard Vary %s", async (vary) => {+ const original = media(200, { Vary: vary })+ expect(await withPrivateMediaCache(async () => original)(request())).toBe(original)+ })++ it("preserves an explicit no-store success policy", async () => {+ const original = media(200, { "Cache-Control": "private, no-store", Vary: "Cookie, Authorization" })+ expect(await withPrivateMediaCache(async () => original)(request())).toBe(original)+ })++ it.each([307, 400, 401, 403, 404, 416, 500, 502, 503, 504])("prohibits storage of returned status %s without altering its body or cookies", async (status) => {+ const original = new NextResponse("failure", {+ status,+ headers: { "Cache-Control": "private, max-age=60", Location: "/new-version", Vary: "Accept-Encoding" },+ })+ original.headers.append("Set-Cookie", "fixture1=clear; Path=/")+ original.headers.append("Set-Cookie", "fixture2=clear; Path=/")+ const result = await withPrivateMediaCache(async () => original)(request())+ expect(result.status).toBe(status)+ expect(result.body).toBe(original.body)+ expect(result.headers.get("Cache-Control")).toBe("private, no-store")+ expect(result.headers.get("Location")).toBe("/new-version")+ expect(result.headers.getSetCookie()).toEqual(original.headers.getSetCookie())+ expect(await result.text()).toBe("failure")+ })++ it("returns a non-storable generic 500 for an unhandled storage failure", async () => {+ const result = await withPrivateMediaCache(async () => { throw new Error("storage detail") })(request())+ expect(result.status).toBe(500)+ expect(result.headers.get("Cache-Control")).toBe("private, no-store")+ expect(await result.json()).toEqual({ error: "internal error" })+ })+})++describe("real authentication wrappers inside media policy", () => {+ it.each([200, 304])("keeps fixed media status %s independent of GA, session refresh and authenticated viewer cookies", async (status) => {+ const handler = vi.fn<AuthenticatedHandler>(async () => media(status, { Vary: "Accept-Encoding" }))+ const route = withPrivateMediaCache(withAuth(handler))+ const params = { params: Promise.resolve({ id: "fixed" }) }+ for (const [viewer, ga, sessionData] of [["A", "first", "old"], ["A", "second", "renewed"], ["B", "third", "other"]]) {+ mocks.getSession.mockResolvedValueOnce(session(viewer))+ const result = await route(request({ Cookie: `viewer=${viewer}; _ga=${ga}; better-auth.session_data=${sessionData}` }), params)+ expect(result.status).toBe(status)+ expect(result.headers.get("Vary")).toBe("Accept-Encoding, Authorization")+ expect(result.headers.get("Cache-Control")).toBe(IMMUTABLE)+ expect(result.headers.get("Set-Cookie")).toContain("better-auth.session_data=fixture-refresh")+ expect(handler.mock.lastCall?.[1]).toMatchObject({ userId: viewer, params: { id: "fixed" } })+ }+ expect(mocks.getSession).toHaveBeenCalledTimes(3)+ expect(handler).toHaveBeenCalledTimes(3)+ })++ it.each(["none", "error", "bot", "deleted"])("makes an early %s session rejection non-storable and never invokes media", async (kind) => {+ if (kind === "none") mocks.getSession.mockResolvedValue({ headers: new Headers(), response: null })+ if (kind === "error") mocks.getSession.mockRejectedValue(new Error("session infrastructure"))+ if (kind === "bot") mocks.getSession.mockResolvedValue(session("bot1", { isBot: true }))+ if (kind === "deleted") mocks.getSession.mockResolvedValue(session("A", { deletedAt: "2026-10-01" }))+ const handler = vi.fn<AuthenticatedHandler>(async () => media())+ const result = await withPrivateMediaCache(withAuth(handler))(request())+ expect(result.status).toBe(kind === "error" ? 503 : 401)+ expect(result.headers.get("Cache-Control")).toBe("private, no-store")+ expect(handler).not.toHaveBeenCalled()+ if (kind === "bot" || kind === "deleted") {+ expect(mocks.signOut).toHaveBeenCalledOnce()+ expect(result.headers.get("Set-Cookie")).toContain("Max-Age=0")+ }+ })++ it.each([200, 304])("retains Authorization on machine-authenticated media status %s", async (status) => {+ const handler = vi.fn<AuthenticatedHandler>(async () => media(status))+ const result = await withPrivateMediaCache(withAuth(handler))(request({ Authorization: "Bearer al_fixture" }))+ expect(result.status).toBe(status)+ expect(result.headers.get("Vary")).toBe("Authorization")+ expect(mocks.getSession).not.toHaveBeenCalled()+ expect(handler.mock.lastCall?.[1]).toMatchObject({ userId: "A", workspaceId: "ws1" })+ })++ it.each(["invalid", "unavailable"])("makes early %s machine auth non-storable", async (kind) => {+ if (kind === "invalid") mocks.getMachineToken.mockResolvedValue(null)+ else mocks.getMachineToken.mockRejectedValue(new Error("database unavailable"))+ const handler = vi.fn<AuthenticatedHandler>(async () => media())+ const result = await withPrivateMediaCache(withAuth(handler))(request({ Authorization: "Bearer al_fixture" }))+ expect(result.status).toBe(kind === "invalid" ? 401 : 503)+ expect(result.headers.get("Cache-Control")).toBe("private, no-store")+ expect(handler).not.toHaveBeenCalled()+ })++ it.each(["human", "bot"])("preserves %s actor resolution on fixed attachment thumbnails", async (kind) => {+ const handler = vi.fn<CommunityActorHandler>(async () => media())+ const headers: Record<string, string> = kind === "bot" ? { Authorization: "Bearer crk_fixture" } : { Cookie: "viewer=A; _ga=changed" }+ const result = await withPrivateMediaCache(withCommunityActor(handler))(request(headers))+ expect(result.headers.get("Vary")).toBe("Authorization")+ expect(handler.mock.lastCall?.[1].actor.kind).toBe(kind)+ expect(mocks.getSession).toHaveBeenCalledTimes(kind === "human" ? 1 : 0)+ })++ it("adds no cache TTL to bot downloads and separates them by Authorization", async () => {+ const result = await withPrivateMediaCache(withCommunityActor(async () => new Response("bot bytes", {+ headers: { "X-Alook-Filename": "file.bin", "Content-Length": "9" },+ })))(request({ Authorization: "Bearer crk_fixture" }))+ expect(result.headers.get("Cache-Control")).toBeNull()+ expect(result.headers.get("Vary")).toBe("Authorization")+ expect(result.headers.get("X-Alook-Filename")).toBe("file.bin")+ expect(await result.text()).toBe("bot bytes")+ })++ it.each([401, 503])("makes bot auth status %s non-storable without falling through to the human session", async (status) => {+ mocks.resolveBotActor.mockResolvedValue({ kind: "error", response: NextResponse.json({ error: "runner auth" }, { status }) })+ const handler = vi.fn<CommunityActorHandler>(async () => media())+ const result = await withPrivateMediaCache(withCommunityActor(handler))(request({ Authorization: "Bearer crk_fixture" }))+ expect(result.status).toBe(status)+ expect(result.headers.get("Cache-Control")).toBe("private, no-store")+ expect(handler).not.toHaveBeenCalled()+ expect(mocks.getSession).not.toHaveBeenCalled()+ })++ it("keeps default private account responses credential-specific outside the selected media wrapper", async () => {+ const result = await withAuth(async () => media())(request())+ expect(result.headers.get("Vary")).toBe("Cookie, Authorization")+ })+})diff --git a/src/web/src/lib/middleware/private-media-cache.ts b/src/web/src/lib/middleware/private-media-cache.tsnew file mode 100644index 000000000..831d1966d--- /dev/null+++ b/src/web/src/lib/middleware/private-media-cache.ts@@ -0,0 +1,43 @@+import { createLogger } from "@alook/shared"+import type { NextRequest } from "next/server"+import { writeError } from "./helpers"++const log = createLogger({ service: "private-media-cache" })+const PRIVATE_NO_STORE = "private, no-store"++type MediaRouteHandler = (+ req: NextRequest,+ context?: { params?: Promise<Record<string, string>> | Record<string, string> },+) => Promise<Response>++export function withPrivateMediaCache(handler: MediaRouteHandler): MediaRouteHandler {+ return async (req, context) => {+ let response: Response+ try {+ response = await handler(req, context)+ } catch (error) {+ log.error("private_media_request_failed", {+ path: req.nextUrl.pathname,+ errorCategory: error instanceof Error ? error.name : "unknown",+ })+ return writeError("internal error", 500, { "Cache-Control": PRIVATE_NO_STORE })+ }++ if (!response.ok && response.status !== 304) {+ const result = new Response(response.body, response)+ result.headers.set("Cache-Control", PRIVATE_NO_STORE)+ return result+ }++ const directives = response.headers.get("Cache-Control")?.split(",") ?? []+ if (directives.some((directive) => directive.trim().toLowerCase() === "no-store")) return response++ const vary = response.headers.get("Vary")?.split(",").map((field) => field.trim()).filter(Boolean) ?? []+ if (vary.some((field) => field === "*")) return response+ const fields = vary.filter((field) => field.toLowerCase() !== "cookie")+ if (!fields.some((field) => field.toLowerCase() === "authorization")) fields.push("Authorization")+ const result = new Response(response.body, response)+ result.headers.set("Vary", fields.join(", "))+ return result+ }+}diff --git a/src/web/src/lib/use-user-ws.test.ts b/src/web/src/lib/use-user-ws.test.tsindex 66d9cd8f6..f5395bdc7 100644--- a/src/web/src/lib/use-user-ws.test.ts+++ b/src/web/src/lib/use-user-ws.test.ts@@ -600,6 +600,41 @@ describe("useUserWs", () => {expect(MockWebSocket.instances).toHaveLength(2)})+ it("manual Retry replaces a connecting online recovery and fences its late authentication", async () => {+ setupTokenFetch()+ const onAuthenticated = vi.fn()+ await mountHook(vi.fn(), { onAuthenticated, requestDaemonStatusOnAuth: false })+ const first = MockWebSocket.instances[0]!+ first.simulateOpen()+ first.simulateMessage({ type: "auth.ok" })++ mockNavigator.onLine = false+ mockWindow.dispatch("offline")+ first.simulateClose()+ mockNavigator.onLine = true+ mockWindow.dispatch("online")+ await flushPromises()+ const automatic = MockWebSocket.instances[1]!+ expect(automatic.readyState).toBe(MockWebSocket.CONNECTING)++ latestHookResult!.reconnectNow()+ await flushPromises()+ expect(automatic.closed).toBe(true)+ expect(mockFetch).toHaveBeenCalledTimes(3)+ expect(MockWebSocket.instances).toHaveLength(3)+ const manual = MockWebSocket.instances[2]!+ automatic.simulateOpen()+ automatic.simulateMessage({ type: "auth.ok" })+ expect(onAuthenticated).toHaveBeenCalledOnce()+ manual.simulateOpen()+ manual.simulateMessage({ type: "auth.ok" })+ expect(onAuthenticated).toHaveBeenCalledTimes(2)+ await vi.advanceTimersByTimeAsync(5_000)+ expect(mockFetch).toHaveBeenCalledTimes(3)+ expect(MockWebSocket.instances).toHaveLength(3)+ expect(manual.closed).toBe(false)+ })+it("reports local retirement and remote close exactly once per socket", async () => {setupTokenFetch()await mountHook(vi.fn(), { requestDaemonStatusOnAuth: false })diff --git a/src/web/src/test/e2e-ui/32-mobile-ws-foreground-validation.spec.ts b/src/web/src/test/e2e-ui/32-mobile-ws-foreground-validation.spec.tsindex ea5da4903..b74acdf0f 100644--- a/src/web/src/test/e2e-ui/32-mobile-ws-foreground-validation.spec.ts+++ b/src/web/src/test/e2e-ui/32-mobile-ws-foreground-validation.spec.ts@@ -298,6 +298,10 @@ test("mobile foreground proof is exact, bounded, and recovers through one currenawait expect(wsOverlay).toHaveCount(0, { timeout: 10_000 })await expect(composerEditable(alice.page)).toBeVisible()+ const onlineRecoveryFrameStart = proxy.connectionFrames.length+ const onlineRecoveryConnectionBaseline = proxy.connectionCount()+ const onlineRecoveryTokenBaseline = tokenRequests+ const onlineRecoverySuccessfulTokenBaseline = successfulTokenResponsestry {await alice.context.setOffline(true)await proxy.disconnect()@@ -311,22 +315,34 @@ test("mobile foreground proof is exact, bounded, and recovers through one curren"failed",{ timeout: 40_000 },)+ const retry = alice.page.getByTestId(tid.wsRetry)+ await retry.focus()+ await alice.page.keyboard.press("Enter")+ await expect(wsOverlay).toHaveCount(0)+ await expect(composerEditable(alice.page)).toBeVisible()+ expect(proxy.connectionCount()).toBe(onlineRecoveryConnectionBaseline)+ expect(tokenRequests).toBe(onlineRecoveryTokenBaseline)+ expect(successfulTokenResponses).toBe(onlineRecoverySuccessfulTokenBaseline)+ await alice.page.evaluate(() => {+ document.documentElement.removeAttribute("data-e2e-user-ws-authenticated")+ })} finally {await alice.context.setOffline(false)}- const retryConnectionBaseline = proxy.connectionCount()- const retrySuccessfulTokenBaseline = successfulTokenResponses- const retry = alice.page.getByTestId(tid.wsRetry)- await retry.focus()- await alice.page.keyboard.press("Enter")await expect(wsOverlay).toHaveCount(0, { timeout: 20_000 })- // The failed-only overlay disappears as soon as Retry starts connecting.- // Wait for that generation to authenticate before measuring a hard reload,- // otherwise the retry socket can race the discarded document's replacement- // and make the reload look like it opened two connections.- await expect.poll(() => proxy.connectionCount()).toBe(retryConnectionBaseline + 1)- await expect.poll(() => successfulTokenResponses).toBe(retrySuccessfulTokenBaseline + 1)+ await expect(alice.page.locator("html")).toHaveAttribute(+ "data-e2e-user-ws-authenticated",+ "true",+ { timeout: 20_000 },+ )+ await expect.poll(() => proxy.connectionCount()).toBe(onlineRecoveryConnectionBaseline + 1)+ await expect.poll(() => successfulTokenResponses).toBe(onlineRecoverySuccessfulTokenBaseline + 1)+ expect(proxy.connectionFrames.slice(onlineRecoveryFrameStart).filter((frame) =>+ frame.direction === "server-to-client"+ && frame.connectionId === onlineRecoveryConnectionBaseline + 1+ && frame.type === "auth.ok",+ )).toHaveLength(1)const reloadFrameStart = proxy.connectionFrames.lengthconst reloadConnectionBaseline = proxy.connectionCount()