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): cache HTML previews by application version (#1120)
Generf348196c25ce
diff --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 d39bcdfa0..557a1dd37 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@@ -52,6 +52,7 @@ vi.mock("@/lib/middleware/community-actor", async () => {})import { GET } from "./route"+import { ATTACHMENT_PRIVATE_IMMUTABLE_CACHE } from "@/lib/community/storage"function req(headers: Record<string, string> = {}): NextRequest {return new NextRequest("http://localhost/api/community/channels/c1/attachments/att_1", {@@ -364,28 +365,30 @@ describe("GET /api/community/channels/[id]/attachments/[attachmentId]", () => {})describe("HTML attachment preview mode", () => {- const previewReq = (headers: Record<string, string> = {}) => new NextRequest("http://localhost/api/community/channels/c1/attachments/att_1?preview=html", { headers })+ const previewReq = (headers: Record<string, string> = {}, version = "1.2.3") => new NextRequest(`http://localhost/api/community/channels/c1/attachments/att_1?preview=html&v=${encodeURIComponent(version)}`, { headers })const htmlRow = (over: Record<string, unknown> = {}) => persistedRow({ filename: "page.html", contentType: "text/html", size: 40, ...over })beforeEach(() => { vi.clearAllMocks() })- it("checks readability before type validation or reading the object", async () => {+ it.each(["1.2.3", "1.2.4+build &next=2"])("checks readability before type validation or reading the object at version %s", async (version) => {mockGetReadableAttachmentById.mockResolvedValue(null)- const response = await GET(previewReq(), ctx())+ const response = await GET(previewReq({}, version), ctx())expect(response.status).toBe(404)+ expect(response.headers.get("cache-control")).toBe("private, no-store")expect(await response.json()).toEqual({ error: "attachment not found" })expect(mockR2Get).not.toHaveBeenCalled()})- it("returns inline executable HTML with opaque-origin CSP, no storage cache and an early bootstrap", async () => {+ it.each(["1.2.3", "1.2.4+build &next=2"])("returns privately cacheable HTML with opaque-origin CSP and an early bootstrap at version %s", async (version) => {allowPersistedHuman(htmlRow())mockR2Get.mockResolvedValue(r2Object({}, new TextEncoder().encode('<!doctype html><html><body><button onclick="this.textContent=2">1</button></body></html>')))- const response = await GET(previewReq({ Range: "bytes=0-5" }), ctx())+ const response = await GET(previewReq({ Range: "bytes=0-5" }, version), ctx())expect(response.status).toBe(200)expect(mockGetReadableAttachmentById).toHaveBeenCalledWith(expect.anything(), "att_1", "u1")expect(response.headers.get("content-type")).toBe("text/html; charset=utf-8")expect(response.headers.get("content-disposition")).toContain("inline")expect(response.headers.get("content-security-policy")).toContain("sandbox allow-scripts")expect(response.headers.get("content-security-policy")).not.toContain("allow-same-origin")- expect(response.headers.get("cache-control")).toBe("private, no-store")+ expect(response.headers.get("cache-control")).toBe(ATTACHMENT_PRIVATE_IMMUTABLE_CACHE)+ expect(response.headers.get("vary")).toBe("Authorization")expect(response.headers.get("referrer-policy")).toBe("no-referrer")expect(response.headers.get("x-content-type-options")).toBe("nosniff")expect(response.headers.get("content-length")).toBeNull()@@ -400,14 +403,21 @@ describe("HTML attachment preview mode", () => {expect(await response.text()).toBe("<p>original</p>")expect(response.headers.get("content-security-policy")).toContain("default-src 'none'")expect(response.headers.get("content-security-policy")).not.toContain("allow-scripts")- if (request.headers.has("authorization")) expect(response.headers.get("x-alook-filename")).toBe("page.html")- else expect(response.headers.get("content-disposition")).toContain("attachment")+ if (request.headers.has("authorization")) {+ expect(response.headers.get("x-alook-filename")).toBe("page.html")+ expect(response.headers.get("cache-control")).toBeNull()+ } else {+ expect(response.headers.get("content-disposition")).toContain("attachment")+ expect(response.headers.get("cache-control")).toBe(ATTACHMENT_PRIVATE_IMMUTABLE_CACHE)+ }}})it("rejects incompatible type and declared oversize without an object read", async () => {for (const [row, status] of [[htmlRow({ contentType: "image/png" }), 415], [htmlRow({ size: 2 * 1024 * 1024 + 1 }), 422]] as const) {allowPersistedHuman(row)- expect((await GET(previewReq(), ctx())).status).toBe(status)+ const response = await GET(previewReq(), ctx())+ expect(response.status).toBe(status)+ expect(response.headers.get("cache-control")).toBe("private, no-store")}expect(mockR2Get).not.toHaveBeenCalled()})@@ -425,12 +435,17 @@ describe("HTML attachment preview mode", () => {const response = await GET(previewReq(), ctx())expect(response.status).toBe(422)expect(cancel).toHaveBeenCalledOnce()+ expect(response.headers.get("cache-control")).toBe("private, no-store")})it("separates missing storage from a failed object stream", async () => {allowPersistedHuman(htmlRow())mockR2Get.mockResolvedValue(null)- expect((await GET(previewReq(), ctx())).status).toBe(502)+ const missing = await GET(previewReq(), ctx())+ expect(missing.status).toBe(502)+ expect(missing.headers.get("cache-control")).toBe("private, no-store")mockR2Get.mockResolvedValue(r2Object({ body: new ReadableStream({ start(c) { c.error(new Error("read failure")) } }) }))- expect((await GET(previewReq(), ctx())).status).toBe(500)+ const failed = await GET(previewReq(), ctx())+ expect(failed.status).toBe(500)+ expect(failed.headers.get("cache-control")).toBe("private, no-store")})})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 2036d0947..06ea39d57 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@@ -85,7 +85,7 @@ export const GET = withPrivateMediaCache(withCommunityActor(async (req: NextRequ"Content-Type": "text/html; charset=utf-8","Content-Disposition": contentDisposition("inline", row.filename),"Content-Security-Policy": HTML_PREVIEW_CSP,- "Cache-Control": "private, no-store",+ "Cache-Control": ATTACHMENT_PRIVATE_IMMUTABLE_CACHE,"X-Content-Type-Options": "nosniff","Referrer-Policy": "no-referrer",} })diff --git a/src/web/src/components/community/messages/html-attachment-preview.dom.test.tsx b/src/web/src/components/community/messages/html-attachment-preview.dom.test.tsxindex 9a8bcfffd..b8557fdda 100644--- a/src/web/src/components/community/messages/html-attachment-preview.dom.test.tsx+++ b/src/web/src/components/community/messages/html-attachment-preview.dom.test.tsx@@ -7,6 +7,7 @@ import { ThreadOpener } from "./thread-opener"import { HtmlAttachmentPreview } from "./html-attachment-preview"import { MessageBodyView } from "./message-body-view"import { tid } from "@/lib/community/testids"+import { attachmentDownloadKey } from "@/lib/community/attachment-download"import { NATIVE_MOBILE_BACK_EVENT, useNativeMobileBack } from "@/hooks/community/use-native-mobile-back"const opener = vi.hoisted(() => ({ message: {} }))@@ -29,7 +30,7 @@ function BackListener({ replacePath }: { replacePath: (path: string) => void })useNativeMobileBack({ dismissShellOverlay: () => false, parentPath: "/c/me", replacePath })return null}-afterEach(() => { for (const owner of owners.splice(0)) owner.queryClient.clear(); vi.restoreAllMocks(); vi.unstubAllGlobals(); theme.resolvedTheme = "light"; vi.useRealTimers() })+afterEach(() => { for (const owner of owners.splice(0)) owner.queryClient.clear(); vi.restoreAllMocks(); vi.unstubAllGlobals(); vi.unstubAllEnvs(); theme.resolvedTheme = "light"; vi.useRealTimers() })describe("HTML attachment frame", () => {it("keeps the filename out of content and groups floating preview actions", () => {@@ -44,9 +45,10 @@ describe("HTML attachment frame", () => {expect(view.getByTestId(tid.htmlPreview("a1"))).toHaveAccessibleName(file.name)})it("keeps one opaque-origin frame and clamps valid current-frame measurements", () => {+ vi.stubEnv("NEXT_PUBLIC_APP_VERSION", "1.2.3")const view = setup()const frame = view.getByTestId(tid.htmlPreviewFrame("a1")) as HTMLIFrameElement- expect(frame).toHaveAttribute("src", `${file.url}?preview=html`)+ expect(frame).toHaveAttribute("src", `${file.url}?preview=html&v=1.2.3`)expect(frame.getAttribute("sandbox")).toContain("allow-scripts")expect(frame.getAttribute("sandbox")).not.toContain("allow-same-origin")expect(frame).toHaveAttribute("referrerpolicy", "no-referrer")@@ -63,6 +65,19 @@ describe("HTML attachment frame", () => {frameMessage(frame, { type: "alook-html-ready" })expect(view.getByTestId(tid.htmlPreview("a1"))).toHaveAttribute("data-html-preview-status", "ready")})+ it("changes only the preview URL with the existing application version", () => {+ vi.stubEnv("NEXT_PUBLIC_APP_VERSION", "1.2.3")+ const view = setup()+ const frame = view.getByTestId(tid.htmlPreviewFrame("a1"))+ expect(frame).toHaveAttribute("src", `${file.url}?preview=html&v=1.2.3`)+ const download = view.owner.queryClient.getQueryCache().find({ queryKey: attachmentDownloadKey(view.owner, file), exact: true })+ expect(download).toBeDefined()+ vi.stubEnv("NEXT_PUBLIC_APP_VERSION", "1.2.4+build &next=2")+ view.rerender(view.tree(<HtmlAttachmentPreview attachment={file} />))+ expect(frame).toHaveAttribute("src", `${file.url}?preview=html&v=1.2.4%2Bbuild%20%26next%3D2`)+ expect(view.owner.queryClient.getQueryCache().find({ queryKey: attachmentDownloadKey(view.owner, file), exact: true })).toBe(download)+ expect(file.url).toBe("/api/community/channels/c1/attachments/a1")+ })it("posts updated Alook theme without replacing the document", () => {const view = setup(), frame = view.getByTestId(tid.htmlPreviewFrame("a1")) as HTMLIFrameElementconst post = vi.spyOn(frame.contentWindow!, "postMessage")diff --git a/src/web/src/components/community/messages/html-attachment-preview.tsx b/src/web/src/components/community/messages/html-attachment-preview.tsxindex 3f94b4424..75e852695 100644--- a/src/web/src/components/community/messages/html-attachment-preview.tsx+++ b/src/web/src/components/community/messages/html-attachment-preview.tsx@@ -44,7 +44,7 @@ function HtmlPreviewDocument({ attachment }: { attachment: FileAttachment & { idconst ready = useRef(false)const download = useAttachmentDownload(attachment)const id = attachment.id- const url = `${attachment.url}?preview=html`+ const url = `${attachment.url}?preview=html&v=${encodeURIComponent(process.env.NEXT_PUBLIC_APP_VERSION ?? "")}`const error = status === "error"useEffect(() => {diff --git a/src/web/src/test/e2e-ui/20-community-attachment-thumbnails.spec.ts b/src/web/src/test/e2e-ui/20-community-attachment-thumbnails.spec.tsindex adf522434..cbbe2caa1 100644--- a/src/web/src/test/e2e-ui/20-community-attachment-thumbnails.spec.ts+++ b/src/web/src/test/e2e-ui/20-community-attachment-thumbnails.spec.ts@@ -1,4 +1,5 @@import { CURRENT_COMMUNITY_FIXTURE_HEADERS, confirmCommunityFixtureApiResponse } from "./_fixtures/business-contract"+import { readFileSync } from "node:fs"import type { Locator, Page, TestInfo } from "@playwright/test"import sharp from "sharp"import { test, expect } from "./_fixtures/case-fixture"@@ -6,6 +7,9 @@ import { tid } from "./_fixtures/testids"import { composerEditable, createServer, gotoAfterUserWsAuth } from "./_fixtures/actions"import { holdRoute } from "./_fixtures/held-route"import { solidPngFixture } from "../fixtures/media"+import { REPO_ROOT } from "./_setup/paths"++const APP_VERSION = (JSON.parse(readFileSync(`${REPO_ROOT}/src/web/package.json`, "utf8")) as { version: string }).versionconst LANDSCAPE_FIXTURE = solidPngFixture(800, 450, [91, 110, 225])const PORTRAIT_FIXTURE = solidPngFixture(450, 800, [225, 91, 142])@@ -971,11 +975,14 @@ test("HTML attachment markers render once with interactive isolated content acroawait expect(actions.getByRole("button", { name: "Download interactive.html", exact: true })).toBeVisible()await expect(preview).not.toHaveAttribute("aria-modal", "true")- const previewUrl = `/api/community/channels/${channelId}/attachments/${attachmentId}?preview=html`- const direct = await page.request.get(previewUrl)+ const previewUrl = await iframe.getAttribute("src")+ expect(previewUrl).toBe(`/api/community/channels/${channelId}/attachments/${attachmentId}?preview=html&v=${encodeURIComponent(APP_VERSION)}`)+ const direct = await page.request.get(previewUrl!)expect(direct.status()).toBe(200)expect(direct.headers()["content-security-policy"]).toContain("sandbox allow-scripts")- expect(direct.headers()["cache-control"]).toBe("private, no-store")+ expect(direct.headers()["cache-control"]).toBe("private, max-age=31536000, immutable")+ expect(direct.headers()["vary"].toLowerCase().split(",").map(field => field.trim())).toContain("authorization")+ expect(direct.headers()["vary"].toLowerCase().split(",").map(field => field.trim())).not.toContain("cookie")const original = await page.request.get(`/api/community/channels/${channelId}/attachments/${attachmentId}`)expect(original.headers()["content-disposition"]).toContain("attachment")expect(await original.text()).toBe(html)@@ -992,17 +999,22 @@ test("HTML attachment markers render once with interactive isolated content acroawait expect(readerPreview).not.toHaveAttribute("aria-modal", "true")await expect(readerPreview.getByTestId(tid.htmlPreviewFrame(attachmentId)).contentFrame().locator("#count")).toHaveText("0")const { page: outsider } = await actors.asUser("carol")- const denied = await outsider.request.get(previewUrl)+ const denied = await outsider.request.get(previewUrl!)expect(denied.status()).toBe(404)+ const deniedCacheControl = denied.headers()["cache-control"] ?? ""+ const deniedCacheDirectives = deniedCacheControl.split(",").map(directive => directive.trim().toLowerCase())+ expect(deniedCacheDirectives).toContain("private")+ expect(deniedCacheDirectives).toContain("no-store")+ expect(deniedCacheDirectives).not.toContain("public")await testInfo.attach("html-preview-headers.json", {- body: JSON.stringify({ serverId, channelId, messageId, attachmentId, preview: Object.fromEntries(Object.entries(direct.headers()).filter(([name]) => ["content-type", "content-disposition", "content-security-policy", "cache-control", "referrer-policy", "x-content-type-options"].includes(name))), download: Object.fromEntries(Object.entries(original.headers()).filter(([name]) => ["content-type", "content-disposition", "cache-control"].includes(name))), outsiderStatus: denied.status() }, null, 2),+ body: JSON.stringify({ serverId, channelId, messageId, attachmentId, preview: Object.fromEntries(Object.entries(direct.headers()).filter(([name]) => ["content-type", "content-disposition", "content-security-policy", "cache-control", "referrer-policy", "x-content-type-options"].includes(name))), download: Object.fromEntries(Object.entries(original.headers()).filter(([name]) => ["content-type", "content-disposition", "cache-control"].includes(name))), outsiderStatus: denied.status(), outsiderCacheControl: deniedCacheControl }, null, 2),contentType: "application/json",})const transparentHtml = `<!doctype html><html style="background:purple!important;padding:17px;color:#123456"><head><style>:root{color-scheme:light dark;background:linear-gradient(red,blue)!important}html,body{margin:0;background:orange!important}body{min-height:112px;color:var(--foreground)}#authored{position:absolute;left:0;top:48px;width:160px;height:48px;background:#73a3b2;color:#112233}input{position:absolute;left:180px;top:48px}#repaint{position:absolute;left:180px;top:80px}</style></head><body style="background:yellow!important"><div id="authored"></div><input id="state" value="original"><button id="repaint" onclick="document.documentElement.style.setProperty('background','linear-gradient(red,blue)','important');document.body.style.setProperty('background','red','important');document.getElementById('rows').innerHTML='<div style=height:360px></div>'">Repaint canvas and grow</button><div id="rows"></div></body></html>`const transparentId = await upload("transparent.html", "text/html", transparentHtml)await appearance("Dark")- const transparentPreviewUrl = new URL(`/api/community/channels/${channelId}/attachments/${transparentId}?preview=html`, page.url()).href+ const transparentPreviewUrl = new URL(`/api/community/channels/${channelId}/attachments/${transparentId}?preview=html&v=${encodeURIComponent(APP_VERSION)}`, page.url()).hrefconst heldPreview = await holdRoute(page, transparentPreviewUrl, caseResources)let transparentPreview: Locator, transparentFrame: Locatorlet loading: Awaited<ReturnType<typeof captureCanvas>>