Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat: add community attachment thumbnails

Gusa2e622585841
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index bb734c16f..dc7080386 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -117,6 +117,9 @@ importers:
commander:
specifier: ^15.0.0
version: 15.0.0
+ sharp:
+ specifier: ^0.35.0
+ version: 0.35.3(@types/[email protected])
ws:
specifier: ^8.21.2
version: 8.21.2
@@ -14228,7 +14231,7 @@ snapshots:
eslint: 9.39.5([email protected])
eslint-import-resolver-node: 0.3.10
- eslint-plugin-import: 2.32.0([email protected])([email protected]([email protected]))
eslint-plugin-jsx-a11y: 6.10.2([email protected]([email protected]))
eslint-plugin-react: 7.37.5([email protected]([email protected]))
eslint-plugin-react-hooks: 7.1.1([email protected]([email protected]))
@@ -14261,7 +14264,7 @@ snapshots:
tinyglobby: 0.2.17
unrs-resolver: 1.12.2
optionalDependencies:
- eslint-plugin-import: 2.32.0([email protected])([email protected]([email protected]))
transitivePeerDependencies:
- supports-color
@@ -14275,7 +14278,7 @@ snapshots:
transitivePeerDependencies:
- supports-color
dependencies:
'@rtsao/scc': 1.1.0
array-includes: 3.1.9
@@ -17851,6 +17854,39 @@ snapshots:
'@img/sharp-win32-ia32': 0.35.2
'@img/sharp-win32-x64': 0.35.2
+ dependencies:
+ '@img/colour': 1.1.0
+ detect-libc: 2.1.2
+ semver: 7.8.5
+ optionalDependencies:
+ '@img/sharp-darwin-arm64': 0.35.3
+ '@img/sharp-darwin-x64': 0.35.3
+ '@img/sharp-freebsd-wasm32': 0.35.3
+ '@img/sharp-libvips-darwin-arm64': 1.3.2
+ '@img/sharp-libvips-darwin-x64': 1.3.2
+ '@img/sharp-libvips-linux-arm': 1.3.2
+ '@img/sharp-libvips-linux-arm64': 1.3.2
+ '@img/sharp-libvips-linux-ppc64': 1.3.2
+ '@img/sharp-libvips-linux-riscv64': 1.3.2
+ '@img/sharp-libvips-linux-s390x': 1.3.2
+ '@img/sharp-libvips-linux-x64': 1.3.2
+ '@img/sharp-libvips-linuxmusl-arm64': 1.3.2
+ '@img/sharp-libvips-linuxmusl-x64': 1.3.2
+ '@img/sharp-linux-arm': 0.35.3
+ '@img/sharp-linux-arm64': 0.35.3
+ '@img/sharp-linux-ppc64': 0.35.3
+ '@img/sharp-linux-riscv64': 0.35.3
+ '@img/sharp-linux-s390x': 0.35.3
+ '@img/sharp-linux-x64': 0.35.3
+ '@img/sharp-linuxmusl-arm64': 0.35.3
+ '@img/sharp-linuxmusl-x64': 0.35.3
+ '@img/sharp-webcontainers-wasm32': 0.35.3
+ '@img/sharp-win32-arm64': 0.35.3
+ '@img/sharp-win32-ia32': 0.35.3
+ '@img/sharp-win32-x64': 0.35.3
+ '@types/node': 20.19.43
+
dependencies:
'@img/colour': 1.1.0
diff --git a/scripts/ci/e2e-shards.mjs b/scripts/ci/e2e-shards.mjs
index 0432a30ea..44d645a78 100644
--- a/scripts/ci/e2e-shards.mjs
+++ b/scripts/ci/e2e-shards.mjs
@@ -26,6 +26,7 @@ export const SPEC_SECONDS = {
"17-forum-sidebar-stage-b.spec.ts": 35,
"18-new-divider-scroll.spec.ts": 46,
"19-marketing-seo.spec.ts": 5,
+ "20-community-attachment-thumbnails.spec.ts": 60,
}
function walk(directory) {
diff --git a/scripts/ci/e2e-shards.test.ts b/scripts/ci/e2e-shards.test.ts
index 430f5fdf8..634b7ac4b 100644
--- a/scripts/ci/e2e-shards.test.ts
+++ b/scripts/ci/e2e-shards.test.ts
@@ -37,7 +37,7 @@ describe("planE2eShards", () => {
expect(first).toHaveLength(E2E_SHARD_COUNT)
expect([...assigned].sort()).toEqual(specs)
expect(new Set(assigned).size).toBe(specs.length)
- expect(totals.sort((left, right) => left - right)).toEqual([121, 121, 122, 123, 126])
+ expect(totals.sort((left, right) => left - right)).toEqual([132, 134, 135, 136, 136])
expect(Math.max(...totals) / Math.min(...totals)).toBeLessThanOrEqual(1.15)
})
diff --git a/src/daemon/package.json b/src/daemon/package.json
index c93bcd4ce..164edce3e 100644
--- a/src/daemon/package.json
+++ b/src/daemon/package.json
@@ -30,13 +30,13 @@
"LICENSE"
],
"engines": {
- "node": ">=20"
+ "node": ">=20.9"
},
"publishConfig": {
"access": "public"
},
"scripts": {
- "build": "bun build src/index.ts --outdir dist --target node --format esm --external commander --external ws && bun build src/cli/index.ts --outdir dist/cli --target node --format esm --external commander --external ws && node scripts/prepare-dist.mjs",
+ "build": "bun build src/index.ts --outdir dist --target node --format esm --external commander --external ws --external sharp && bun build src/cli/index.ts --outdir dist/cli --target node --format esm --external commander --external ws --external sharp && node scripts/prepare-dist.mjs",
"prepack": "pnpm run build",
"typecheck": "tsc --noEmit",
"test": "vitest run",
@@ -47,6 +47,7 @@
},
"dependencies": {
"commander": "^15.0.0",
+ "sharp": "^0.35.0",
"ws": "^8.21.2"
},
"devDependencies": {
diff --git a/src/daemon/scripts/thumbnail-pack-smoke.mjs b/src/daemon/scripts/thumbnail-pack-smoke.mjs
new file mode 100644
index 000000000..cee55b6f7
--- /dev/null
+++ b/src/daemon/scripts/thumbnail-pack-smoke.mjs
@@ -0,0 +1,76 @@
+import assert from "node:assert/strict"
+import { execFileSync, spawn } from "node:child_process"
+import fs from "node:fs"
+import http from "node:http"
+import os from "node:os"
+import path from "node:path"
+
+const tarball = path.resolve(process.argv[2] ?? "")
+assert(fs.existsSync(tarball), `tarball not found: ${tarball}`)
+const temp = fs.mkdtempSync(path.join(os.tmpdir(), "alook-daemon-thumbnail-smoke-"))
+
+try {
+ execFileSync("npm", ["install", "--ignore-scripts=false", tarball], { cwd: temp, stdio: "inherit" })
+ const installedPackage = JSON.parse(fs.readFileSync(path.join(temp, "node_modules/@alook/daemon/package.json"), "utf8"))
+ assert(installedPackage.dependencies?.sharp, "packed daemon must declare sharp as a runtime dependency")
+
+ const png = path.join(temp, "valid.png")
+ // 1x1 opaque PNG.
+ fs.writeFileSync(png, Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=", "base64"))
+ const token = path.join(temp, "voucher")
+ fs.writeFileSync(token, "crk_smoke", { mode: 0o600 })
+
+ let resolveBody
+ const bodyPromise = new Promise((resolve) => { resolveBody = resolve })
+ const server = http.createServer((req, res) => {
+ const chunks = []
+ req.on("data", (chunk) => chunks.push(chunk))
+ req.on("end", () => {
+ resolveBody({ body: Buffer.concat(chunks), contentType: req.headers["content-type"] ?? "" })
+ res.writeHead(200, { "content-type": "application/json" })
+ res.end(JSON.stringify({ id: "att_smoke", filename: "valid.png", contentType: "image/png", size: 68, hasThumbnail: true }))
+ })
+ })
+ await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve))
+ const address = server.address()
+ assert(address && typeof address === "object")
+ const cli = path.join(temp, "node_modules/@alook/daemon/dist/cli/index.js")
+ const child = spawn(process.execPath, [cli, "message", "attachment", "upload", "--target", "/demo#1234/general", "--file", png], {
+ env: {
+ ...process.env,
+ ALOOK_PROXY_URL: `http://127.0.0.1:${address.port}`,
+ ALOOK_PROXY_TOKEN_FILE: token,
+ ALOOK_AGENT_ID: "agent_smoke",
+ },
+ })
+ let stdout = ""
+ let stderr = ""
+ child.stdout.setEncoding("utf8").on("data", (chunk) => { stdout += chunk })
+ child.stderr.setEncoding("utf8").on("data", (chunk) => { stderr += chunk })
+ const status = await new Promise((resolve) => child.on("close", resolve))
+ server.close()
+ assert.equal(status, 0, stderr)
+ assert.deepEqual(JSON.parse(stdout), {
+ success: { id: "att_smoke", filename: "valid.png", contentType: "image/png", size: 68, hasThumbnail: true },
+ })
+
+ const { body, contentType } = await bodyPromise
+ const boundary = /boundary=([^;]+)/.exec(contentType)?.[1]
+ assert(boundary, "multipart boundary missing")
+ const binary = body.toString("latin1")
+ assert(binary.includes('name="file"; filename="valid.png"'))
+ assert(binary.includes('name="thumbnail"; filename="thumbnail.jpg"'))
+ assert(binary.includes("Content-Type: image/jpeg"))
+ assert(binary.includes('name="width"\r\n\r\n1'))
+ assert(binary.includes('name="height"\r\n\r\n1'))
+ const thumbnailStart = binary.indexOf('name="thumbnail"')
+ const payloadStart = binary.indexOf("\r\n\r\n", thumbnailStart) + 4
+ const payloadEnd = binary.indexOf(`\r\n--${boundary}`, payloadStart)
+ const thumbnail = body.subarray(payloadStart, payloadEnd)
+ assert(thumbnail.length <= 50 * 1024)
+ assert.deepEqual([...thumbnail.subarray(0, 2)], [0xff, 0xd8])
+ assert.deepEqual([...thumbnail.subarray(-2)], [0xff, 0xd9])
+ process.stdout.write("daemon thumbnail pack smoke passed\n")
+} finally {
+ fs.rmSync(temp, { recursive: true, force: true })
+}
diff --git a/src/daemon/src/cli/index.test.ts b/src/daemon/src/cli/index.test.ts
index d0658971f..061051dba 100644
--- a/src/daemon/src/cli/index.test.ts
+++ b/src/daemon/src/cli/index.test.ts
@@ -1004,6 +1004,86 @@ describe("message emoji", () => {
});
describe("message attachment upload", () => {
+ it("generates a bounded JPEG thumbnail and sends original dimensions", async () => {
+ const fs = await import("node:fs")
+ const os = await import("node:os")
+ const path = await import("node:path")
+ const { default: sharp } = await import("sharp")
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "alook-thumbnail-upload-"))
+ const file = path.join(dir, "source.png")
+ fs.writeFileSync(file, await sharp({
+ create: { width: 640, height: 480, channels: 3, background: "#336699" },
+ }).png().toBuffer())
+ const uploadSpy = vi.fn(async (req: Parameters<ServerApi["attachmentUpload"]>[0]) => ({
+ id: "att_image",
+ filename: req.file.filename,
+ contentType: req.file.contentType ?? "application/octet-stream",
+ size: req.file.data instanceof Uint8Array ? req.file.data.byteLength : req.file.data.size,
+ hasThumbnail: req.thumbnail !== undefined,
+ }))
+ setApiForTesting(stubApi({ attachmentUpload: uploadSpy }))
+ try {
+ await main(["message", "attachment", "upload", "--target", "/demo#0042/general", "--file", file])
+ } finally {
+ fs.rmSync(dir, { recursive: true, force: true })
+ }
+ const request = uploadSpy.mock.calls[0]![0]
+ expect(request).toMatchObject({ width: 640, height: 480 })
+ expect(request.thumbnail?.contentType).toBe("image/jpeg")
+ expect(request.thumbnail?.data).toBeInstanceOf(Uint8Array)
+ const bytes = request.thumbnail!.data as Uint8Array
+ expect(bytes.byteLength).toBeLessThanOrEqual(50 * 1024)
+ expect([...bytes.slice(0, 2)]).toEqual([0xff, 0xd8])
+ expect([...bytes.slice(-2)]).toEqual([0xff, 0xd9])
+ expect(parseEnvelope(cap.lines())).toMatchObject({ success: { hasThumbnail: true } })
+ })
+
+ it.each(["jpg", "webp", "gif"])("generates a thumbnail for valid .%s raster input", async (extension) => {
+ const fs = await import("node:fs")
+ const os = await import("node:os")
+ const path = await import("node:path")
+ const { default: sharp } = await import("sharp")
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "alook-raster-matrix-"))
+ const file = path.join(dir, `source.${extension}`)
+ let pipeline = sharp({ create: { width: 32, height: 24, channels: 3, background: "#123456" } })
+ pipeline = extension === "jpg" ? pipeline.jpeg() : extension === "webp" ? pipeline.webp() : pipeline.gif()
+ fs.writeFileSync(file, await pipeline.toBuffer())
+ const uploadSpy = vi.fn(async () => ({
+ id: "att", filename: `source.${extension}`, contentType: "image/test", size: 1, hasThumbnail: true,
+ }))
+ setApiForTesting(stubApi({ attachmentUpload: uploadSpy }))
+ try {
+ await main(["message", "attachment", "upload", "--target", "/demo#0042/general", "--file", file])
+ } finally {
+ fs.rmSync(dir, { recursive: true, force: true })
+ }
+ expect(uploadSpy.mock.calls[0]![0]).toMatchObject({ width: 32, height: 24 })
+ expect(uploadSpy.mock.calls[0]![0].thumbnail?.contentType).toBe("image/jpeg")
+ })
+
+ it("uploads corrupt declared raster input without thumbnail or dimensions", async () => {
+ const fs = await import("node:fs")
+ const os = await import("node:os")
+ const path = await import("node:path")
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "alook-corrupt-image-"))
+ const file = path.join(dir, "corrupt.png")
+ fs.writeFileSync(file, "not an image")
+ const uploadSpy = vi.fn(async () => ({
+ id: "att", filename: "corrupt.png", contentType: "image/png", size: 12, hasThumbnail: false,
+ }))
+ setApiForTesting(stubApi({ attachmentUpload: uploadSpy }))
+ try {
+ await main(["message", "attachment", "upload", "--target", "/demo#0042/general", "--file", file])
+ } finally {
+ fs.rmSync(dir, { recursive: true, force: true })
+ }
+ const request = uploadSpy.mock.calls[0]![0]
+ expect(request.thumbnail).toBeUndefined()
+ expect(request.width).toBeUndefined()
+ expect(request.height).toBeUndefined()
+ expect(parseEnvelope(cap.lines())).toMatchObject({ success: { hasThumbnail: false } })
+ })
+
it.each([
{ extension: "html", contentType: "text/html" },
{ extension: "htm", contentType: "text/html" },
diff --git a/src/daemon/src/cli/index.ts b/src/daemon/src/cli/index.ts
index e6c99a77b..3115424ad 100755
--- a/src/daemon/src/cli/index.ts
+++ b/src/daemon/src/cli/index.ts
@@ -23,7 +23,10 @@ import { parseRef } from "../server/contract.js";
import { proxyServerApiFromEnv } from "./proxyServerApi.js";
import { daemonRunFromIpc, daemonStart, daemonStop, daemonList, daemonStatus, type DaemonInfo } from "./daemonStart.js";
import { parseInviteToken } from "@alook/shared/lib/invite-link";
-import { MAX_EMOJI_BYTES } from "@alook/shared/constants/community";
+import {
+ MAX_ATTACHMENT_THUMBNAIL_SIZE_BYTES,
+ MAX_EMOJI_BYTES,
+} from "@alook/shared/constants/community";
import { nowLocalISO, toLocalISO } from "../util/localTime.js";
/**
@@ -428,10 +431,41 @@ async function cmdAttachmentUpload(opts: Record<string, unknown>): Promise<unkno
const filename = pathMod.basename(filePath);
const contentType = contentTypeFromFilename(filename);
+ let thumbnail: { data: Uint8Array; filename: string; contentType: string } | undefined;
+ let width: number | undefined;
+ let height: number | undefined;
+ if (["image/png", "image/jpeg", "image/webp", "image/gif"].includes(contentType)) {
+ try {
+ const { default: sharp } = await import("sharp");
+ const image = sharp(bytes, { failOn: "error" });
+ const metadata = await image.metadata();
+ if (metadata.width && metadata.height) {
+ width = metadata.width;
+ height = metadata.height;
+ }
+ const jpeg = await image
+ .resize({ width: 200, height: 200, fit: "inside", withoutEnlargement: true })
+ .jpeg({ quality: 70 })
+ .toBuffer();
+ if (jpeg.byteLength <= MAX_ATTACHMENT_THUMBNAIL_SIZE_BYTES) {
+ thumbnail = {
+ data: new Uint8Array(jpeg),
+ filename: "thumbnail.jpg",
+ contentType: "image/jpeg",
+ };
+ }
+ } catch {
+ // Thumbnailing is an optimization. Corrupt/unsupported images still upload.
+ }
+ }
+
const result = await api.attachmentUpload({
agentId: agent,
target,
file: { data: new Uint8Array(bytes), filename, contentType },
+ ...(thumbnail ? { thumbnail } : {}),
+ ...(width !== undefined ? { width } : {}),
+ ...(height !== undefined ? { height } : {}),
});
return result;
}
diff --git a/src/daemon/src/cli/proxyServerApi.test.ts b/src/daemon/src/cli/proxyServerApi.test.ts
index 1e297b33a..900b9904c 100644
--- a/src/daemon/src/cli/proxyServerApi.test.ts
+++ b/src/daemon/src/cli/proxyServerApi.test.ts
@@ -506,6 +506,29 @@ describe("createProxyServerApi — callUpload via parseJsonResponse", () => {
expect(u.searchParams.get("target")).toBe("/demo#1234/general");
expect(seen[0].init?.method).toBe("POST");
});
+
+ it("includes thumbnail and dimensions in the canonical multipart body", async () => {
+ let form: FormData | undefined;
+ const fetchImpl: FetchLike = vi.fn(async (_url: string, init?: RequestInit) => {
+ form = init?.body as FormData;
+ return jsonBody(JSON.stringify({
+ id: "att_1", filename: "x.png", contentType: "image/png", size: 3, hasThumbnail: true,
+ }), { status: 200 });
+ });
+ const api = createProxyServerApi({ ...cfg, fetchImpl: fetchImpl as typeof fetch });
+ const out = await api.attachmentUpload({
+ agentId: "a1",
+ target: "/demo#1234/general",
+ file: { data: new Uint8Array([1, 2, 3]), filename: "x.png", contentType: "image/png" },
+ thumbnail: { data: new Uint8Array([0xff, 0xd8, 0xff, 0xd9]), filename: "thumbnail.jpg", contentType: "image/jpeg" },
+ width: 640,
+ height: 480,
+ });
+ expect(out.hasThumbnail).toBe(true);
+ expect((form!.get("thumbnail") as File).type).toBe("image/jpeg");
+ expect(form!.get("width")).toBe("640");
+ expect(form!.get("height")).toBe("480");
+ });
});
describe("createProxyServerApi — callDownload", () => {
diff --git a/src/daemon/src/cli/proxyServerApi.ts b/src/daemon/src/cli/proxyServerApi.ts
index 63c2a132b..d375732bf 100644
--- a/src/daemon/src/cli/proxyServerApi.ts
+++ b/src/daemon/src/cli/proxyServerApi.ts
@@ -127,6 +127,15 @@ export function createProxyServerApi(config: ProxyServerApiConfig): ServerApi {
? new Blob([new Uint8Array(req.file.data)], { type: blobType })
: req.file.data;
form.append("file", bytes as Blob, req.file.filename);
+ if (req.thumbnail) {
+ const thumbnailType = req.thumbnail.contentType ?? "image/jpeg";
+ const thumbnailBytes = req.thumbnail.data instanceof Uint8Array
+ ? new Blob([new Uint8Array(req.thumbnail.data)], { type: thumbnailType })
+ : req.thumbnail.data;
+ form.append("thumbnail", thumbnailBytes as Blob, req.thumbnail.filename);
+ }
+ if (req.width !== undefined) form.append("width", String(req.width));
+ if (req.height !== undefined) form.append("height", String(req.height));
// Canonical attachments door: POST channels/{id}/attachments. The bot holds
// a REF (not an id), so it uses the `resolve` placeholder id and carries the
// ref on `?target=` (kept — Gener #68); the door's bot arm resolves it
diff --git a/src/shared/src/community-cli-contract.ts b/src/shared/src/community-cli-contract.ts
index dbc12b69f..0c1ba32b7 100644
--- a/src/shared/src/community-cli-contract.ts
+++ b/src/shared/src/community-cli-contract.ts
@@ -218,6 +218,7 @@ export type AgentAttachmentUploadResult = {
filename: string;
contentType: string;
size: number;
+ hasThumbnail?: boolean;
};
export type AgentAttachmentDownloadResult = {
@@ -352,6 +353,9 @@ export interface AttachmentUploadRequest {
agentId: AgentId;
target: ChannelRef;
file: FileHandle;
+ thumbnail?: FileHandle;
+ width?: number;
+ height?: number;
}
export interface AttachmentDownloadRequest {
diff --git a/src/shared/src/community-ws-events.ts b/src/shared/src/community-ws-events.ts
index 624d82cb8..3a5222d01 100644
--- a/src/shared/src/community-ws-events.ts
+++ b/src/shared/src/community-ws-events.ts
@@ -26,6 +26,7 @@ const messageAttachmentSchema = z.strictObject({
id: string,
filename: string,
url: string,
+ thumbnailUrl: string.optional(),
contentType: string.optional(),
size: z.number().optional(),
width: z.number().nullable().optional(),
diff --git a/src/shared/src/constants/community.ts b/src/shared/src/constants/community.ts
index 414dc93bc..6dd1754e0 100644
--- a/src/shared/src/constants/community.ts
+++ b/src/shared/src/constants/community.ts
@@ -26,6 +26,7 @@ export const MAX_EMOJI_BYTES = 32
// Attachments / uploads
export const MAX_ATTACHMENTS_PER_MESSAGE = 10
export const MAX_ATTACHMENT_SIZE_BYTES = 25 * 1024 * 1024 // 25 MB
+export const MAX_ATTACHMENT_THUMBNAIL_SIZE_BYTES = 50 * 1024 // 50 KiB
export const MAX_SERVER_ICON_SIZE_BYTES = 5 * 1024 * 1024 // 5 MB
export const ALLOWED_ICON_MIME_TYPES = [
"image/png",
diff --git a/src/shared/src/db/community-schema.ts b/src/shared/src/db/community-schema.ts
index e300868cd..971869497 100644
--- a/src/shared/src/db/community-schema.ts
+++ b/src/shared/src/db/community-schema.ts
@@ -391,8 +391,8 @@ export const communityReaction = sqliteTable(
//
// `messageId` is nullable — pending rows created by the agent
// `attachment upload` command exist before the send that links them. The
-// human-composer path always writes with `messageId` set at insert time (see
-// message-handler.ts). `position` is stamped 0-indexed at link time in the
+// human and bot uploads both create pending rows first; send reserves them by
+// id and sets `messageId`. `position` is stamped 0-indexed at link time in the
// caller-specified order; NULL on pending rows.
export const communityAttachment = sqliteTable(
"community_attachment",
@@ -404,6 +404,7 @@ export const communityAttachment = sqliteTable(
uploaderId: text("uploader_id").notNull(),
targetId: text("target_id").notNull(),
r2Key: text("r2_key").notNull(),
+ thumbnailR2Key: text("thumbnail_r2_key"),
filename: text("filename").notNull(),
contentType: text("content_type"),
size: integer("size"),
diff --git a/src/shared/src/db/queries/community/attachment.ts b/src/shared/src/db/queries/community/attachment.ts
index ef19c122f..6d8358b07 100644
--- a/src/shared/src/db/queries/community/attachment.ts
+++ b/src/shared/src/db/queries/community/attachment.ts
@@ -18,6 +18,7 @@ export async function createPendingAttachment(
uploaderId: string;
targetId: string;
r2Key: string;
+ thumbnailR2Key?: string | null;
filename: string;
contentType?: string | null;
size?: number | null;
@@ -33,6 +34,7 @@ export async function createPendingAttachment(
uploaderId: data.uploaderId,
targetId: data.targetId,
r2Key: data.r2Key,
+ thumbnailR2Key: data.thumbnailR2Key ?? null,
filename: data.filename,
position: null,
contentType: data.contentType ?? null,
diff --git a/src/shared/src/index.ts b/src/shared/src/index.ts
index d619c1688..e4e53ad82 100644
--- a/src/shared/src/index.ts
+++ b/src/shared/src/index.ts
@@ -136,6 +136,7 @@ export {
MAX_EMOJI_BYTES,
MAX_ATTACHMENTS_PER_MESSAGE,
MAX_ATTACHMENT_SIZE_BYTES,
+ MAX_ATTACHMENT_THUMBNAIL_SIZE_BYTES,
MAX_SERVER_ICON_SIZE_BYTES,
ALLOWED_ICON_MIME_TYPES,
MAX_ICON_SOURCE_FILE_SIZE_BYTES,
diff --git a/src/shared/src/schemas.ts b/src/shared/src/schemas.ts
index 01d3850b3..2a0090058 100644
--- a/src/shared/src/schemas.ts
+++ b/src/shared/src/schemas.ts
@@ -1187,6 +1187,7 @@ export const CommunityAgentAttachmentUploadResponseSchema = z.object({
filename: z.string(),
contentType: z.string(),
size: z.number(),
+ hasThumbnail: z.boolean().optional(),
});
export type CommunityAgentAttachmentUploadResponse = z.infer<
typeof CommunityAgentAttachmentUploadResponseSchema
diff --git a/src/shared/test/community-cli-contract.test.ts b/src/shared/test/community-cli-contract.test.ts
index 3d5513ece..d9f976208 100644
--- a/src/shared/test/community-cli-contract.test.ts
+++ b/src/shared/test/community-cli-contract.test.ts
@@ -9,6 +9,15 @@ import {
HostCommandSchema,
type HostCommand,
} from "../src/community-cli-contract";
+import { CommunityAgentAttachmentUploadResponseSchema } from "../src/schemas";
+
+describe("attachment thumbnail upload contract", () => {
+ it("accepts the optional server-confirmed hasThumbnail flag", () => {
+ expect(CommunityAgentAttachmentUploadResponseSchema.parse({
+ id: "a1", filename: "photo.png", contentType: "image/png", size: 10, hasThumbnail: true,
+ })).toMatchObject({ hasThumbnail: true });
+ });
+});
describe("parseRef", () => {
it('parses "/studio#0042/general" as a plain channel ref', () => {
diff --git a/src/shared/test/community-ws-events.fixtures.ts b/src/shared/test/community-ws-events.fixtures.ts
index 99956cd32..39c2bb80e 100644
--- a/src/shared/test/community-ws-events.fixtures.ts
+++ b/src/shared/test/community-ws-events.fixtures.ts
@@ -35,6 +35,13 @@ export const communityWsEventFixtures = {
authorName: "Author",
content: "hello",
type: "chat",
+ attachments: [{
+ id: "attachment-1",
+ filename: "photo.png",
+ url: "/api/community/channels/channel-1/attachments/attachment-1",
+ thumbnailUrl: "/api/community/channels/channel-1/attachments/attachment-1/thumbnail",
+ contentType: "image/png",
+ }],
createdAt: "2026-01-01T00:00:00.000Z",
},
},
diff --git a/src/shared/test/queries/community-attachment-thumbnail.test.ts b/src/shared/test/queries/community-attachment-thumbnail.test.ts
new file mode 100644
index 000000000..1881a28ab
--- /dev/null
+++ b/src/shared/test/queries/community-attachment-thumbnail.test.ts
@@ -0,0 +1,35 @@
+import { describe, expect, it, vi } from "vitest"
+import { createPendingAttachment } from "../../src/db/queries/community/attachment"
+
+function database() {
+ const chain: any = {}
+ chain.values = vi.fn((value) => {
+ chain.value = value
+ return chain
+ })
+ chain.returning = vi.fn(async () => [{ ...chain.value, id: chain.value.id ?? "generated" }])
+ return { insert: vi.fn(() => chain), chain }
+}
+
+describe("community attachment thumbnail persistence", () => {
+ it("preserves an exact thumbnail key without changing the original", async () => {
+ const db = database()
+ const row = await createPendingAttachment(db as any, {
+ id: "a1", uploaderId: "u1", targetId: "c1", r2Key: "original-key",
+ thumbnailR2Key: "original-key.thumbnail.jpg", filename: "photo.png",
+ })
+ expect(row).toMatchObject({
+ r2Key: "original-key",
+ thumbnailR2Key: "original-key.thumbnail.jpg",
+ messageId: null,
+ })
+ })
+
+ it("writes null for legacy/original-only uploads", async () => {
+ const db = database()
+ const row = await createPendingAttachment(db as any, {
+ id: "a1", uploaderId: "u1", targetId: "c1", r2Key: "original-key", filename: "file.txt",
+ })
+ expect(row.thumbnailR2Key).toBeNull()
+ })
+})
diff --git a/src/web/migrations/0085_community_attachment_thumbnail.sql b/src/web/migrations/0085_community_attachment_thumbnail.sql
new file mode 100644
index 000000000..d38e7ace9
--- /dev/null
+++ b/src/web/migrations/0085_community_attachment_thumbnail.sql
@@ -0,0 +1 @@
+ALTER TABLE community_attachment ADD COLUMN thumbnail_r2_key TEXT;
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.ts
index 06cd96b36..ce72878c3 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
@@ -149,6 +149,7 @@ describe("GET /api/community/channels/[id]/attachments/[attachmentId]", () => {
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"))
+ expect(res.headers.get("Cache-Control")).toBeNull()
})
it("bot: percent-encodes non-ASCII filenames per RFC 5987", async () => {
@@ -171,7 +172,7 @@ describe("GET /api/community/channels/[id]/attachments/[attachmentId]", () => {
expect(res.status).toBe(200)
expect(res.headers.get("Content-Type")).toBe("image/png")
expect(res.headers.get("Content-Disposition")).toBe("inline")
- expect(res.headers.get("Cache-Control")).toBeTruthy()
+ expect(res.headers.get("Cache-Control")).toBe("private, max-age=31536000, immutable")
// Human arm never emits the bot download header.
expect(res.headers.get("X-Alook-Filename")).toBeNull()
})
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.ts
index 73525dc3d..3e72ce2d0 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
@@ -1,8 +1,9 @@
import { NextResponse, type NextRequest } from "next/server"
-import { queries, createLogger, CACHE_IMMUTABLE } from "@alook/shared"
+import { createLogger } from "@alook/shared"
import { getDb } from "@/lib/db"
-import { withCommunityActor, type CommunityActor } from "@/lib/middleware/community-actor"
-import { requireChannelMember, requireDMAccess } from "@/lib/community/permissions"
+import { withCommunityActor } from "@/lib/middleware/community-actor"
+import { authorizeAttachment } from "@/lib/community/attachment-authorization"
+import { ATTACHMENT_PRIVATE_IMMUTABLE_CACHE } from "@/lib/community/storage"
const log = createLogger({ service: "community-attachments-download" })
@@ -93,7 +94,7 @@ export const GET = withCommunityActor(async (req: NextRequest, ctx) => {
"Content-Disposition": isImage
? "inline"
: `attachment; filename="${row.filename}"`,
- "Cache-Control": CACHE_IMMUTABLE,
+ "Cache-Control": ATTACHMENT_PRIVATE_IMMUTABLE_CACHE,
},
})
} catch (err) {
@@ -106,48 +107,3 @@ export const GET = withCommunityActor(async (req: NextRequest, ctx) => {
return NextResponse.json({ error: "internal error", code: "internal" }, { status: 500 })
}
})
-
-type AuthzOk = {
- ok: true
- row: NonNullable<Awaited<ReturnType<typeof queries.communityAttachment.getAttachmentById>>>
-}
-
-/**
- * Confused-deputy-safe attachment authorization. Returns the row ONLY when the
- * caller may read it, deriving scope from the row's own channel — the path
- * `[id]` is never consulted. Both actor arms run the identical gate:
- * - pending row (messageId = NULL) → only the uploading actor (round-trip).
- * - persisted row → resolve the row's message → its channel → membership /
- * DM access.
- * Any deny collapses to `{ ok: false }` so the caller can render a uniform 404.
- */
-async function authorizeAttachment(
- actor: CommunityActor,
- db: ReturnType<typeof getDb>,
- attachmentId: string,
-): Promise<AuthzOk | { ok: false }> {
- const userId = actor.userId
- const row = await queries.communityAttachment.getAttachmentById(db, attachmentId)
- if (!row) return { ok: false }
-
- if (row.messageId === null) {
- // Pending row — only the uploading actor may see it (round-trip verify).
- if (row.uploaderId !== userId) return { ok: false }
- return { ok: true, row }
- }
-
- // Persisted row — resolve target scope FROM THE ROW, then run the standard
- // membership gate. Any non-ok collapses to a generic deny so a prober can't
- // tell "not a member" from "row doesn't exist".
- const message = await queries.communityMessage.getMessage(db, row.messageId)
- if (!message) return { ok: false }
- const channelType = await queries.communityChannel.getChannelType(db, message.channelId)
- if (channelType === "dm") {
- const gate = await requireDMAccess(db, message.channelId, userId)
- if (!gate.ok) return { ok: false }
- } else {
- const gate = await requireChannelMember(db, message.channelId, userId)
- if (!gate.ok) return { ok: false }
- }
- return { ok: true, row }
-}
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.ts
new file mode 100644
index 000000000..2384d5999
--- /dev/null
+++ b/src/web/src/app/api/community/channels/[id]/attachments/[attachmentId]/thumbnail/route.test.ts
@@ -0,0 +1,55 @@
+import { beforeEach, describe, expect, it, vi } from "vitest"
+import { NextRequest } from "next/server"
+
+const mockAuthorizeAttachment = vi.fn()
+const mockR2Get = vi.fn()
+
+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))
+vi.mock("@/lib/community/attachment-authorization", () => ({
+ authorizeAttachment: (...args: unknown[]) => mockAuthorizeAttachment(...args),
+}))
+vi.mock("@/lib/middleware/community-actor", () => ({
+ withCommunityActor: (handler: any) => async (req: NextRequest, ctx: any) => handler(req, {
+ params: ctx.params,
+ actor: { kind: "human", userId: "u1", email: "[email protected]", isBot: false },
+ env: { DB: {}, COMMUNITY_MEDIA: { get: (...args: unknown[]) => mockR2Get(...args) } },
+ }),
+}))
+
+import { GET } from "./route"
+
+const request = new NextRequest("http://localhost/api/community/channels/c1/attachments/a1/thumbnail")
+const ctx = { params: { id: "c1", attachmentId: "a1" } } as any
+
+describe("GET attachment thumbnail", () => {
+ beforeEach(() => vi.clearAllMocks())
+
+ it.each([
+ { authz: { ok: false }, label: "unauthorized" },
+ { authz: { ok: true, row: { thumbnailR2Key: null } }, label: "legacy row" },
+ ])("returns enumeration-safe 404 for $label", async ({ authz }) => {
+ mockAuthorizeAttachment.mockResolvedValue(authz)
+ const response = await GET(request, ctx)
+ expect(response.status).toBe(404)
+ expect(mockR2Get).not.toHaveBeenCalled()
+ })
+
+ it("returns 502 when a declared thumbnail object is missing", async () => {
+ mockAuthorizeAttachment.mockResolvedValue({ ok: true, row: { thumbnailR2Key: "key.thumb" } })
+ mockR2Get.mockResolvedValue(null)
+ expect((await GET(request, ctx)).status).toBe(502)
+ })
+
+ it("serves private immutable JPEG bytes with nosniff", async () => {
+ const body = new ReadableStream()
+ mockAuthorizeAttachment.mockResolvedValue({ ok: true, row: { thumbnailR2Key: "key.thumb" } })
+ mockR2Get.mockResolvedValue({ body })
+ const response = await GET(request, ctx)
+ expect(response.status).toBe(200)
+ expect(mockR2Get).toHaveBeenCalledWith("key.thumb")
+ expect(response.headers.get("Content-Type")).toBe("image/jpeg")
+ expect(response.headers.get("Content-Disposition")).toBe("inline")
+ expect(response.headers.get("Cache-Control")).toBe("private, max-age=31536000, immutable")
+ expect(response.headers.get("X-Content-Type-Options")).toBe("nosniff")
+ })
+})
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.ts
new file mode 100644
index 000000000..bbb731bce
--- /dev/null
+++ b/src/web/src/app/api/community/channels/[id]/attachments/[attachmentId]/thumbnail/route.ts
@@ -0,0 +1,44 @@
+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 { 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) => {
+ const attachmentId = ctx.params?.attachmentId
+ if (!attachmentId) {
+ return NextResponse.json({ error: "attachment not found" }, { status: 404 })
+ }
+
+ try {
+ const authz = await authorizeAttachment(ctx.actor, getDb(ctx.env.DB), attachmentId)
+ if (!authz.ok || authz.row.thumbnailR2Key === null) {
+ return NextResponse.json({ error: "attachment not found" }, { status: 404 })
+ }
+
+ const obj = await ctx.env.COMMUNITY_MEDIA.get(authz.row.thumbnailR2Key)
+ if (!obj) {
+ return NextResponse.json({ error: "attachment storage unavailable" }, { status: 502 })
+ }
+
+ return new Response(obj.body, {
+ headers: {
+ "Content-Type": "image/jpeg",
+ "Content-Disposition": "inline",
+ "Cache-Control": ATTACHMENT_PRIVATE_IMMUTABLE_CACHE,
+ "X-Content-Type-Options": "nosniff",
+ },
+ })
+ } catch (err) {
+ log.error("attachment_thumbnail_route_failure", {
+ route: "channels/[id]/attachments/[attachmentId]/thumbnail",
+ actorKind: ctx.actor.kind,
+ userId: ctx.actor.userId,
+ cause: err instanceof Error ? err.stack ?? err.message : String(err),
+ })
+ return NextResponse.json({ error: "internal error", code: "internal" }, { status: 500 })
+ }
+})
diff --git a/src/web/src/app/api/community/channels/[id]/attachments/route.test.ts b/src/web/src/app/api/community/channels/[id]/attachments/route.test.ts
index 66af38edd..a0160b783 100644
--- a/src/web/src/app/api/community/channels/[id]/attachments/route.test.ts
+++ b/src/web/src/app/api/community/channels/[id]/attachments/route.test.ts
@@ -26,11 +26,13 @@ const mockGetChannelForMember = vi.fn()
const mockGetDM = vi.fn()
const mockGetDMBetween = vi.fn()
const mockCreatePendingAttachment = vi.fn()
+const mockLogError = vi.fn()
vi.mock("@alook/shared", async () => {
const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")
return {
...actual,
+ createLogger: () => ({ error: (...args: unknown[]) => mockLogError(...args) }),
queries: {
...actual.queries,
communityMachine: { findActiveAgentRunnerKeyByBearer: (...a: unknown[]) => mockFindActiveAgentRunnerKeyByBearer(...a) },
@@ -84,10 +86,12 @@ describe("POST /api/community/channels/[id]/attachments — bot arm (folds attac
filename: "hi.png",
contentType: "image/png",
size: 10,
+ hasThumbnail: false,
})
mockHandleAttachmentUpload.mockResolvedValue({
ok: true,
r2Key: "channel/c1/uuid/hi.png",
+ thumbnailR2Key: null,
filename: "hi.png",
contentType: "image/png",
size: 10,
@@ -119,6 +123,7 @@ describe("POST /api/community/channels/[id]/attachments — bot arm (folds attac
filename: "hi.png",
contentType: "image/png",
size: 10,
+ hasThumbnail: false,
})
// No leaked internals.
expect(body.url).toBeUndefined()
@@ -139,6 +144,31 @@ describe("POST /api/community/channels/[id]/attachments — bot arm (folds attac
}))
})
+ it("persists thumbnail key and dimensions, returning hasThumbnail true", async () => {
+ mockResolveServerByNameForMember.mockResolvedValue([{ id: "srv_1" }])
+ mockResolveChannelByNameForMember.mockResolvedValue([
+ { id: "c1", serverId: "srv_1", parentChannelId: null },
+ ])
+ mockGetChannelForMember.mockResolvedValue({ id: "c1", serverId: "srv_1", parentChannelId: null })
+ mockHandleAttachmentUpload.mockResolvedValue({
+ ok: true,
+ r2Key: "channel/c1/uuid/hi.png",
+ thumbnailR2Key: "channel/c1/uuid/hi.png.thumbnail.jpg",
+ filename: "hi.png",
+ contentType: "image/png",
+ size: 10,
+ width: 640,
+ height: 480,
+ })
+ const response = await POST(botReq("/studio#0042/general", { Authorization: "Bearer crk_abc" }), botCtx)
+ expect(await response.json()).toMatchObject({ hasThumbnail: true })
+ expect(mockCreatePendingAttachment).toHaveBeenCalledWith({}, expect.objectContaining({
+ thumbnailR2Key: "channel/c1/uuid/hi.png.thumbnail.jpg",
+ width: 640,
+ height: 480,
+ }))
+ })
+
it("createPendingAttachment throws → 500 JSON envelope, R2 delete fired with r2Key", async () => {
mockResolveServerByNameForMember.mockResolvedValue([{ id: "srv_1" }])
mockResolveChannelByNameForMember.mockResolvedValue([
@@ -153,6 +183,56 @@ describe("POST /api/community/channels/[id]/attachments — bot arm (folds attac
expect(mockR2Delete).toHaveBeenCalledWith("channel/c1/uuid/hi.png")
})
+ it("D1 failure after a thumbnail upload deletes both objects together", async () => {
+ mockResolveServerByNameForMember.mockResolvedValue([{ id: "srv_1" }])
+ mockResolveChannelByNameForMember.mockResolvedValue([
+ { id: "c1", serverId: "srv_1", parentChannelId: null },
+ ])
+ mockGetChannelForMember.mockResolvedValue({ id: "c1", serverId: "srv_1", parentChannelId: null })
+ mockHandleAttachmentUpload.mockResolvedValue({
+ ok: true,
+ r2Key: "original-key",
+ thumbnailR2Key: "thumbnail-key",
+ filename: "hi.png",
+ contentType: "image/png",
+ size: 10,
+ })
+ mockCreatePendingAttachment.mockRejectedValueOnce(new Error("d1"))
+ expect((await POST(botReq("/studio#0042/general", { Authorization: "Bearer crk_abc" }), botCtx)).status).toBe(500)
+ expect(mockR2Delete).toHaveBeenCalledWith(["original-key", "thumbnail-key"])
+ })
+
+ it("redacts object keys when compensation cleanup also fails", async () => {
+ mockResolveServerByNameForMember.mockResolvedValue([{ id: "srv_1" }])
+ mockResolveChannelByNameForMember.mockResolvedValue([
+ { id: "c1", serverId: "srv_1", parentChannelId: null },
+ ])
+ mockGetChannelForMember.mockResolvedValue({ id: "c1", serverId: "srv_1", parentChannelId: null })
+ mockHandleAttachmentUpload.mockResolvedValue({
+ ok: true,
+ r2Key: "secret-original-key",
+ thumbnailR2Key: "secret-thumbnail-key",
+ filename: "hi.png",
+ contentType: "image/png",
+ size: 10,
+ })
+ mockCreatePendingAttachment.mockRejectedValueOnce(new Error("d1"))
+ mockR2Delete.mockRejectedValueOnce(new Error("cleanup failed"))
+
+ const response = await POST(
+ botReq("/studio#0042/general", { Authorization: "Bearer crk_abc" }),
+ botCtx,
+ )
+
+ expect(response.status).toBe(500)
+ const cleanupLog = mockLogError.mock.calls.find(
+ ([event]) => event === "attachment_route_r2_cleanup_failed",
+ )
+ expect(cleanupLog?.[1]).toEqual(expect.objectContaining({ objectCount: 2 }))
+ expect(JSON.stringify(cleanupLog)).not.toContain("secret-original-key")
+ expect(JSON.stringify(cleanupLog)).not.toContain("secret-thumbnail-key")
+ })
+
it("pre-R2 throw (resolveTargetForMember errors) → 500 JSON, R2 delete NOT called", async () => {
mockResolveServerByNameForMember.mockRejectedValueOnce(new Error("d1_outage"))
const res = await POST(botReq("/studio#0042/general", { Authorization: "Bearer crk_abc" }), botCtx)
diff --git a/src/web/src/app/api/community/channels/[id]/attachments/route.ts b/src/web/src/app/api/community/channels/[id]/attachments/route.ts
index 5c6533fec..713bf8c89 100644
--- a/src/web/src/app/api/community/channels/[id]/attachments/route.ts
+++ b/src/web/src/app/api/community/channels/[id]/attachments/route.ts
@@ -66,7 +66,7 @@ async function handleBotAttachmentUpload(
// Track any R2 blob written before the D1 insert throws so the catch below
// can best-effort delete it. Hoisted here so the try/catch can see it.
- let r2KeyToCleanUp: string | null = null
+ let r2KeysToCleanUp: string[] = []
try {
const target = req.nextUrl.searchParams.get("target")
@@ -101,15 +101,18 @@ async function handleBotAttachmentUpload(
// R2 blob is committed — remember its key so the D1-throw path can
// compensate.
- r2KeyToCleanUp = result.r2Key
+ r2KeysToCleanUp = [result.r2Key, ...(result.thumbnailR2Key ? [result.thumbnailR2Key] : [])]
const row = await queries.communityAttachment.createPendingAttachment(db, {
uploaderId: botUserId,
targetId,
r2Key: result.r2Key,
+ thumbnailR2Key: result.thumbnailR2Key,
filename: result.filename,
contentType: result.contentType,
size: result.size,
+ width: result.width,
+ height: result.height,
})
return NextResponse.json({
@@ -117,18 +120,21 @@ async function handleBotAttachmentUpload(
filename: row.filename,
contentType: result.contentType || "application/octet-stream",
size: result.size,
+ hasThumbnail: result.thumbnailR2Key !== null,
})
} catch (err) {
let r2KeyCleaned = false
- if (r2KeyToCleanUp !== null) {
+ if (r2KeysToCleanUp.length > 0) {
try {
- await ctx.env.COMMUNITY_MEDIA.delete(r2KeyToCleanUp)
+ await ctx.env.COMMUNITY_MEDIA.delete(
+ r2KeysToCleanUp.length === 1 ? r2KeysToCleanUp[0]! : r2KeysToCleanUp,
+ )
r2KeyCleaned = true
} catch (cleanupErr) {
log.error("attachment_route_r2_cleanup_failed", {
route: "channels/[id]/attachments",
botUserId,
- r2Key: r2KeyToCleanUp,
+ objectCount: r2KeysToCleanUp.length,
cleanupErr: cleanupErr instanceof Error ? cleanupErr.message : String(cleanupErr),
})
}
diff --git a/src/web/src/app/c/me/[dmId]/page.tsx b/src/web/src/app/c/me/[dmId]/page.tsx
index 214c33a35..db9f3b2a5 100644
--- a/src/web/src/app/c/me/[dmId]/page.tsx
+++ b/src/web/src/app/c/me/[dmId]/page.tsx
@@ -9,7 +9,7 @@ import { Avatar } from "@/components/community/avatar"
import { MessageList } from "@/components/community/message-list"
import { MessageContextSheet } from "@/components/community/message-context-sheet"
import { Composer, ComposerSkeleton, type SendAttachment } from "@/components/community/composer"
-import type { OpenProfile } from "@/components/community/_types"
+import type { ImagePreview, OpenProfile } from "@/components/community/_types"
import {
useCommunityStore,
useCurrentChannelId,
@@ -292,8 +292,8 @@ function DmView() {
{ type: "dismissFailed", nonce: m.clientNonce },
)
},
- onPreviewImage: (url: string) => {
- uiHandlers.previewImage?.(url)
+ onPreviewImage: (image: ImagePreview) => {
+ uiHandlers.previewImage?.(image)
},
onDownloadFile: (url: string) => {
const a = document.createElement("a")
diff --git a/src/web/src/components/community/_types.ts b/src/web/src/components/community/_types.ts
index ff2bb57d1..20dd8ab17 100644
--- a/src/web/src/components/community/_types.ts
+++ b/src/web/src/components/community/_types.ts
@@ -78,9 +78,11 @@ export type Category = {
// ── Messages ───────────────────────────────────────────────────────────────
export type Attachment =
- | { kind: "image"; name: string; url: string; width?: number; height?: number }
+ | { kind: "image"; name: string; url: string; thumbnailUrl?: string; width?: number; height?: number }
| { kind: "file"; name: string; url: string; size: string }
+export type ImagePreview = { originalUrl: string; thumbnailUrl?: string; name: string }
+
type Embed = {
provider?: string
url?: string
diff --git a/src/web/src/components/community/composer.send-lifecycle.test.ts b/src/web/src/components/community/composer.send-lifecycle.test.ts
index ad3d22c98..dbbcad8d4 100644
--- a/src/web/src/components/community/composer.send-lifecycle.test.ts
+++ b/src/web/src/components/community/composer.send-lifecycle.test.ts
@@ -54,6 +54,7 @@ describe("Composer committed send lifecycle", () => {
let pendingFiles: PendingFile[]
let clearContent: ReturnType<typeof vi.fn>
let transferPendingFiles: ReturnType<typeof vi.fn>
+ let awaitPendingFiles: ReturnType<typeof vi.fn>
beforeEach(() => {
firstEditorOptions = undefined
@@ -62,6 +63,7 @@ describe("Composer committed send lifecycle", () => {
pendingFiles = []
clearContent = vi.fn()
transferPendingFiles = vi.fn(() => pendingFiles)
+ awaitPendingFiles = vi.fn(async () => pendingFiles)
const editor = {
isEmpty: false,
@@ -87,6 +89,7 @@ describe("Composer committed send lifecycle", () => {
pendingFiles,
setPendingFiles: vi.fn(),
transferPendingFiles,
+ awaitPendingFiles,
addPendingFiles: vi.fn(),
fileInputRef: { current: null },
handleFileSelect: vi.fn(),
@@ -182,4 +185,196 @@ describe("Composer committed send lifecycle", () => {
expect(clearContent).toHaveBeenCalledOnce()
expect(transferPendingFiles).toHaveBeenCalledOnce()
})
+
+ it("waits for same-tick file preparation and sends once with the exact thumbnail Blob", async () => {
+ let releasePreparation!: () => void
+ const preparation = new Promise<void>((resolve) => { releasePreparation = resolve })
+ const file = new File(["original"], "photo.png", { type: "image/png" })
+ const thumbnailBlob = new Blob(["thumbnail"], { type: "image/jpeg" })
+ const prepared = [{
+ file,
+ thumbnailUrl: "blob:thumbnail",
+ thumbnailBlob,
+ width: 640,
+ height: 480,
+ }]
+ awaitPendingFiles.mockImplementationOnce(async () => {
+ await preparation
+ pendingFiles = prepared
+ return prepared
+ })
+ const accept = vi.fn(() => true)
+ await act(async () => {
+ TestRenderer.create(React.createElement(Composer, {
+ channel: "general",
+ context: "channel",
+ members: [],
+ sendContract: "accepted",
+ onAcceptSend: accept,
+ draftKey: "server/channel",
+ } satisfies ComposerProps))
+ })
+
+ const immediateEnter = () => firstEditorOptions!.editorProps.handleKeyDown({} as never, {
+ key: "Enter",
+ shiftKey: false,
+ isComposing: false,
+ preventDefault: vi.fn(),
+ } as unknown as KeyboardEvent)
+ await act(async () => {
+ expect(immediateEnter()).toBe(true)
+ expect(immediateEnter()).toBe(true)
+ await Promise.resolve()
+ })
+ expect(accept).not.toHaveBeenCalled()
+
+ await act(async () => {
+ releasePreparation()
+ await preparation
+ await Promise.resolve()
+ })
+ expect(accept).toHaveBeenCalledOnce()
+ expect(accept).toHaveBeenCalledWith("latest draft", [{
+ file,
+ thumbnailBlob,
+ previewObjectUrl: "blob:thumbnail",
+ width: 640,
+ height: 480,
+ }], undefined)
+ expect(accept.mock.calls[0][1]?.[0].thumbnailBlob).toBe(thumbnailBlob)
+ expect(clearContent).toHaveBeenCalledOnce()
+ expect(transferPendingFiles).toHaveBeenCalledOnce()
+ })
+
+ it("cancels a pending send across an A → B → A scope cycle", async () => {
+ let releasePreparation!: () => void
+ const preparation = new Promise<void>((resolve) => { releasePreparation = resolve })
+ const file = new File(["original"], "photo.png", { type: "image/png" })
+ awaitPendingFiles.mockImplementationOnce(async () => {
+ await preparation
+ return [{ file, thumbnailUrl: null, thumbnailBlob: null }]
+ })
+ const accept = vi.fn(() => true)
+ const props = (draftKey: string) => ({
+ channel: draftKey,
+ context: "channel" as const,
+ members: [],
+ sendContract: "accepted" as const,
+ onAcceptSend: accept,
+ draftKey,
+ })
+ let renderer!: TestRenderer.ReactTestRenderer
+ await act(async () => {
+ renderer = TestRenderer.create(React.createElement(Composer, props("server/one")))
+ })
+ await act(async () => {
+ firstEditorOptions!.editorProps.handleKeyDown({} as never, {
+ key: "Enter", shiftKey: false, isComposing: false, preventDefault: vi.fn(),
+ } as unknown as KeyboardEvent)
+ await Promise.resolve()
+ })
+ await act(async () => {
+ renderer.update(React.createElement(Composer, props("server/two")))
+ })
+ await act(async () => {
+ renderer.update(React.createElement(Composer, props("server/one")))
+ })
+ await act(async () => {
+ releasePreparation()
+ await preparation
+ await Promise.resolve()
+ })
+
+ expect(accept).not.toHaveBeenCalled()
+ expect(clearContent).not.toHaveBeenCalled()
+ expect(transferPendingFiles).not.toHaveBeenCalled()
+ })
+
+ it("does not route an old pending file into a new scope without a fresh Enter", async () => {
+ let releaseOld!: () => void
+ const oldPreparation = new Promise<void>((resolve) => { releaseOld = resolve })
+ const oldFile = new File(["old"], "old.png", { type: "image/png" })
+ awaitPendingFiles.mockImplementationOnce(async () => {
+ await oldPreparation
+ pendingFiles = [{ file: oldFile, thumbnailUrl: null, thumbnailBlob: null }]
+ return pendingFiles
+ })
+ const accept = vi.fn(() => true)
+ const props = (draftKey: string) => ({
+ channel: draftKey,
+ context: "channel" as const,
+ members: [],
+ sendContract: "accepted" as const,
+ onAcceptSend: accept,
+ draftKey,
+ })
+ let renderer!: TestRenderer.ReactTestRenderer
+ await act(async () => {
+ renderer = TestRenderer.create(React.createElement(Composer, props("server/one")))
+ })
+ const enter = () => firstEditorOptions!.editorProps.handleKeyDown({} as never, {
+ key: "Enter", shiftKey: false, isComposing: false, preventDefault: vi.fn(),
+ } as unknown as KeyboardEvent)
+ await act(async () => {
+ enter()
+ await Promise.resolve()
+ })
+ await act(async () => {
+ renderer.update(React.createElement(Composer, props("server/two")))
+ })
+ await act(async () => {
+ enter()
+ await Promise.resolve()
+ })
+ expect(accept).not.toHaveBeenCalled()
+ await act(async () => {
+ releaseOld()
+ await oldPreparation
+ await Promise.resolve()
+ })
+ expect(accept).not.toHaveBeenCalled()
+ await act(async () => {
+ enter()
+ await Promise.resolve()
+ })
+ expect(accept).toHaveBeenCalledOnce()
+ expect(accept.mock.calls[0][1]).toEqual([expect.objectContaining({ file: oldFile })])
+ })
+
+ it("cancels a pending send before layout unmount completes", async () => {
+ let releasePreparation!: () => void
+ const preparation = new Promise<void>((resolve) => { releasePreparation = resolve })
+ const file = new File(["old"], "old.png", { type: "image/png" })
+ awaitPendingFiles.mockImplementationOnce(async () => {
+ await preparation
+ return [{ file, thumbnailUrl: null, thumbnailBlob: null }]
+ })
+ const accept = vi.fn(() => true)
+ let renderer!: TestRenderer.ReactTestRenderer
+ await act(async () => {
+ renderer = TestRenderer.create(React.createElement(Composer, {
+ channel: "general",
+ context: "channel",
+ members: [],
+ sendContract: "accepted",
+ onAcceptSend: accept,
+ } satisfies ComposerProps))
+ })
+ await act(async () => {
+ firstEditorOptions!.editorProps.handleKeyDown({} as never, {
+ key: "Enter", shiftKey: false, isComposing: false, preventDefault: vi.fn(),
+ } as unknown as KeyboardEvent)
+ await Promise.resolve()
+ })
+ act(() => renderer.unmount())
+ await act(async () => {
+ releasePreparation()
+ await preparation
+ await Promise.resolve()
+ })
+
+ expect(accept).not.toHaveBeenCalled()
+ expect(clearContent).not.toHaveBeenCalled()
+ expect(transferPendingFiles).not.toHaveBeenCalled()
+ })
})
diff --git a/src/web/src/components/community/composer.test.ts b/src/web/src/components/community/composer.test.ts
index 344f148a7..9ebd3d116 100644
--- a/src/web/src/components/community/composer.test.ts
+++ b/src/web/src/components/community/composer.test.ts
@@ -63,13 +63,21 @@ describe("pendingFilesToSendAttachments", () => {
expect(pendingFilesToSendAttachments([])).toBeUndefined()
})
- it("maps each PendingFile to {file, width, height}, preserving width/height when present", () => {
+ it("preserves the exact thumbnail Blob with the file and dimensions", () => {
const file = new File(["x"], "photo.png", { type: "image/png" })
+ const thumbnailBlob = new Blob(["thumbnail"], { type: "image/jpeg" })
const pending: PendingFile[] = [
- { file, thumbnailUrl: null, thumbnailBlob: null, width: 1920, height: 1080 },
+ { file, thumbnailUrl: "blob:thumbnail", thumbnailBlob, width: 1920, height: 1080 },
]
const result = pendingFilesToSendAttachments(pending)
- expect(result).toEqual([{ file, width: 1920, height: 1080 }])
+ expect(result).toEqual([{
+ file,
+ thumbnailBlob,
+ previewObjectUrl: "blob:thumbnail",
+ width: 1920,
+ height: 1080,
+ }])
+ expect(result?.[0].thumbnailBlob).toBe(thumbnailBlob)
})
it("carries width/height through as undefined for a non-image PendingFile", () => {
diff --git a/src/web/src/components/community/composer.tsx b/src/web/src/components/community/composer.tsx
index a20cf7088..0ef47c2b7 100644
--- a/src/web/src/components/community/composer.tsx
+++ b/src/web/src/components/community/composer.tsx
@@ -1,6 +1,6 @@
"use client"
-import { forwardRef, useEffect, useImperativeHandle, useRef, useState } from "react"
+import { forwardRef, useEffect, useImperativeHandle, useLayoutEffect, useRef, useState } from "react"
import { createPortal } from "react-dom"
import { FileIcon, ImageIcon, PlusCircle, Smile, Upload, Users, X } from "lucide-react"
import { useEditor, EditorContent, type JSONContent } from "@tiptap/react"
@@ -38,7 +38,13 @@ import {
type ChannelRefPopupState,
} from "@/lib/community/channel-ref-extension"
-export type SendAttachment = { file: File; previewObjectUrl?: string; width?: number; height?: number }
+export type SendAttachment = {
+ file: File
+ thumbnailBlob?: Blob
+ previewObjectUrl?: string
+ width?: number
+ height?: number
+}
// Pure mapping from `useFileAttachments`'s pending-file state to `onSend`'s
// attachments argument. Extracted so the width/height threading through
@@ -47,6 +53,7 @@ export function pendingFilesToSendAttachments(pendingFiles: PendingFile[]): Send
if (pendingFiles.length === 0) return undefined
return pendingFiles.map((pf) => ({
file: pf.file,
+ thumbnailBlob: pf.thumbnailBlob ?? undefined,
previewObjectUrl: pf.thumbnailUrl ?? undefined,
width: pf.width,
height: pf.height,
@@ -178,6 +185,7 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
pendingFiles,
setPendingFiles,
transferPendingFiles,
+ awaitPendingFiles,
addPendingFiles,
fileInputRef,
handleFileSelect,
@@ -192,12 +200,24 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
})
const typingTimer = useRef<NodeJS.Timeout | null>(null)
const sendRef = useRef<() => void>(() => {})
+ const sendInFlightRef = useRef<Promise<void> | null>(null)
+ const lifecycleVersionRef = useRef(0)
// Draft cache key, held in a ref so the editor's `onUpdate` closure (captured
// once at build) always persists under the current scope. Restore is
// suppressed via this flag so hydrating the editor doesn't fire `onTyping`.
const draftKeyRef = useRef(draftKey)
- useEffect(() => { draftKeyRef.current = draftKey }, [draftKey])
+ const sendScopeRef = useRef<string | null>(null)
+ const sendScopeVersionRef = useRef(0)
+ useLayoutEffect(() => {
+ const nextScope = `${context}\u0000${channel}\u0000${draftKey ?? ""}`
+ if (sendScopeRef.current !== nextScope) {
+ sendScopeRef.current = nextScope
+ sendScopeVersionRef.current++
+ }
+ draftKeyRef.current = draftKey
+ }, [channel, context, draftKey])
+ useLayoutEffect(() => () => { lifecycleVersionRef.current++ }, [])
const restoringDraftRef = useRef(false)
const [mentionPopup, setMentionPopup] = useState<MentionPopupState>(EMPTY_MENTION_STATE)
@@ -443,39 +463,54 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
}, [pendingFiles, editor])
const send = () => {
- if (!editor || (editor.isEmpty && pendingFiles.length === 0)) return
- // Block separator `\n\n` — paragraph breaks serialize as a markdown blank
- // line (a real paragraph), while in-paragraph hard breaks serialize as a
- // single `\n` (HardBreak's `renderText`). `remark-breaks` on render turns
- // the single `\n` into `<br>` and the blank line into a new paragraph, so
- // the compose → send → render round-trip preserves both newline levels.
- const markdown = editor.isEmpty ? "" : editor.getText({ blockSeparator: "\n\n" }).trim()
- const mentionType = detectMentionType(markdown)
- const attachments = pendingFilesToSendAttachments(pendingFiles)
- if (sendContract === "accepted") {
- if (!onAcceptSend?.(markdown, attachments, mentionType)) return
- } else {
- void onDeferredSubmit?.(markdown, attachments, mentionType)
- }
- // In forumThreadBody mode the parent needs to await mutation success before
- // clearing — otherwise a failed create wipes the user's typed content.
- // Reset is delegated to the parent via `resetAfterSubmit()` on the ref.
- if (isForumThreadBody) return
- editor.commands.clearContent()
- if (draftKeyRef.current) clearComposerDraft(draftKeyRef.current)
- transferPendingFiles()
- setMentionPopup(EMPTY_MENTION_STATE)
- setChannelRefPopup(EMPTY_CHANNEL_REF_STATE)
+ if (!editor || sendInFlightRef.current) return
+ const attemptScopeVersion = sendScopeVersionRef.current
+ const attemptLifecycle = lifecycleVersionRef.current
+ const attempt = (async () => {
+ const preparedFiles = await awaitPendingFiles()
+ if (
+ lifecycleVersionRef.current !== attemptLifecycle ||
+ sendScopeVersionRef.current !== attemptScopeVersion
+ ) return
+ if (editor.isEmpty && preparedFiles.length === 0) return
+ // Block separator `\n\n` — paragraph breaks serialize as a markdown blank
+ // line (a real paragraph), while in-paragraph hard breaks serialize as a
+ // single `\n` (HardBreak's `renderText`). `remark-breaks` on render turns
+ // the single `\n` into `<br>` and the blank line into a new paragraph, so
+ // the compose → send → render round-trip preserves both newline levels.
+ const markdown = editor.isEmpty ? "" : editor.getText({ blockSeparator: "\n\n" }).trim()
+ const mentionType = detectMentionType(markdown)
+ const attachments = pendingFilesToSendAttachments([...preparedFiles])
+ if (sendContract === "accepted") {
+ if (!onAcceptSend?.(markdown, attachments, mentionType)) return
+ } else {
+ await onDeferredSubmit?.(markdown, attachments, mentionType)
+ }
+ // In forumThreadBody mode the parent needs to await mutation success before
+ // clearing — otherwise a failed create wipes the user's typed content.
+ // Reset is delegated to the parent via `resetAfterSubmit()` on the ref.
+ if (isForumThreadBody) return
+ editor.commands.clearContent()
+ if (draftKeyRef.current) clearComposerDraft(draftKeyRef.current)
+ transferPendingFiles()
+ setMentionPopup(EMPTY_MENTION_STATE)
+ setChannelRefPopup(EMPTY_CHANNEL_REF_STATE)
+ })()
+ sendInFlightRef.current = attempt
+ void attempt.then(() => {
+ if (sendInFlightRef.current === attempt) sendInFlightRef.current = null
+ }, () => {
+ if (sendInFlightRef.current === attempt) sendInFlightRef.current = null
+ })
}
- useEffect(() => {
+ useLayoutEffect(() => {
sendRef.current = send
})
useImperativeHandle(ref, () => ({
focusEditor: () => { editor?.commands.focus("end") },
submitNow: () => {
- if (!editor || (editor.isEmpty && pendingFiles.length === 0)) return
send()
},
resetAfterSubmit: () => {
diff --git a/src/web/src/components/community/create-forum-thread.test.ts b/src/web/src/components/community/create-forum-thread.test.ts
index 260d145f7..9fe95f201 100644
--- a/src/web/src/components/community/create-forum-thread.test.ts
+++ b/src/web/src/components/community/create-forum-thread.test.ts
@@ -3,9 +3,12 @@
* mounts a real tiptap editor (needs DOM); everything else here is pure JSX
* that renderToStaticMarkup can walk.
*/
-import { describe, it, expect, vi } from "vitest"
+import { beforeEach, describe, it, expect, vi } from "vitest"
import { createElement } from "react"
import { renderToStaticMarkup } from "react-dom/server"
+import TestRenderer, { act } from "react-test-renderer"
+
+const uploadMock = vi.hoisted(() => vi.fn())
vi.mock("./composer", () => ({
Composer: (props: Record<string, unknown>) =>
@@ -16,12 +19,14 @@ vi.mock("./composer", () => ({
"data-has-deferred-submit": String(typeof props.onDeferredSubmit === "function"),
"data-hide-emoji": String(!!props.hideEmoji),
"data-placeholder": (props.placeholder as string) ?? "",
+ onSubmit: props.onDeferredSubmit,
+ onDirty: props.onDirty,
}),
}))
vi.mock("@/hooks/community/mutations/uploads", () => ({
- useUploadFile: () => ({ mutateAsync: vi.fn() }),
- zipUploadResultsWithDimensions: () => [],
+ useUploadFile: () => ({ mutateAsync: uploadMock }),
+ zipUploadResultsWithDimensions: (results: unknown[]) => results,
}))
import { CreateForumThread } from "./create-forum-thread"
@@ -39,6 +44,7 @@ function render(over: Partial<Parameters<typeof CreateForumThread>[0]> = {}) {
}
describe("CreateForumThread — copy + structure", () => {
+ beforeEach(() => uploadMock.mockReset())
it("renders the region role + label so keyboard/SR users land in a named region", () => {
const html = render()
expect(html).toContain('role="region"')
@@ -98,4 +104,49 @@ describe("CreateForumThread — copy + structure", () => {
const html = render()
expect(html).toContain('aria-label="Cancel post"')
})
+
+ it("keeps server hasThumbnail in the forum upload cache across create retry", async () => {
+ const onCreatePost = vi.fn()
+ .mockRejectedValueOnce(new Error("create failed"))
+ .mockResolvedValueOnce(undefined)
+ uploadMock.mockResolvedValue({
+ id: "att_thumb",
+ filename: "photo.png",
+ contentType: "image/png",
+ size: 8,
+ hasThumbnail: true,
+ })
+ const file = new File(["original"], "photo.png", { type: "image/png" })
+ const thumbnailBlob = new Blob(["thumbnail"], { type: "image/jpeg" })
+ let renderer: TestRenderer.ReactTestRenderer
+ act(() => {
+ renderer = TestRenderer.create(createElement(CreateForumThread, {
+ forumChannelId: "cha_forum",
+ members: [],
+ onCancel: () => {},
+ onCreatePost,
+ }))
+ })
+ const input = renderer!.root.findByType("input")
+ const composer = () => renderer!.root.findByProps({ "data-testid": "mock-composer" })
+ act(() => {
+ input.props.onChange({ target: { value: "Post" } })
+ composer().props.onDirty(true)
+ })
+ const attachments = [{ file, thumbnailBlob, width: 640, height: 480 }]
+
+ await act(async () => {
+ await composer().props.onSubmit("photo", attachments, undefined)
+ })
+ await act(async () => {
+ await composer().props.onSubmit("photo", attachments, undefined)
+ })
+
+ expect(uploadMock).toHaveBeenCalledTimes(1)
+ expect(uploadMock).toHaveBeenCalledWith(expect.objectContaining({ thumbnailBlob }))
+ expect(onCreatePost).toHaveBeenCalledTimes(2)
+ for (const [post] of onCreatePost.mock.calls) {
+ expect(post.attachments).toEqual([expect.objectContaining({ hasThumbnail: true })])
+ }
+ })
})
diff --git a/src/web/src/components/community/create-forum-thread.tsx b/src/web/src/components/community/create-forum-thread.tsx
index 080659127..9e594b279 100644
--- a/src/web/src/components/community/create-forum-thread.tsx
+++ b/src/web/src/components/community/create-forum-thread.tsx
@@ -95,6 +95,7 @@ export function CreateForumThread({
const res = await uploadFile.mutateAsync({
target: { channelId: forumChannelId },
file: att.file,
+ thumbnailBlob: att.thumbnailBlob,
width: att.width,
height: att.height,
})
diff --git a/src/web/src/components/community/image-lightbox.test.ts b/src/web/src/components/community/image-lightbox.test.ts
new file mode 100644
index 000000000..c3d58e58f
--- /dev/null
+++ b/src/web/src/components/community/image-lightbox.test.ts
@@ -0,0 +1,41 @@
+import React from "react"
+import TestRenderer, { act } from "react-test-renderer"
+import { describe, expect, it, vi } from "vitest"
+
+vi.mock("@/components/ui/dialog", () => ({
+ Dialog: ({ children }: { children: React.ReactNode }) => React.createElement("div", null, children),
+ DialogContent: ({ children }: { children: React.ReactNode }) => React.createElement("section", null, children),
+}))
+
+import { ImageLightbox } from "./image-lightbox"
+
+describe("ImageLightbox", () => {
+ it("keeps the thumbnail painted until the clicked original loads", () => {
+ let renderer: TestRenderer.ReactTestRenderer
+ act(() => {
+ renderer = TestRenderer.create(React.createElement(ImageLightbox, {
+ image: { originalUrl: "/original", thumbnailUrl: "/thumbnail", name: "photo" },
+ onClose: vi.fn(),
+ }))
+ })
+ const images = renderer!.root.findAllByType("img")
+ expect(images.map((image) => image.props.src)).toEqual(["/thumbnail", "/original"])
+ expect(images[1].props.className).toContain("invisible")
+ act(() => images[1].props.onLoad())
+ expect(renderer!.root.findAllByType("img")[1].props.className).not.toContain("invisible")
+ })
+
+ it("retains the thumbnail when the original fails", () => {
+ let renderer: TestRenderer.ReactTestRenderer
+ act(() => {
+ renderer = TestRenderer.create(React.createElement(ImageLightbox, {
+ image: { originalUrl: "/original", thumbnailUrl: "/thumbnail", name: "photo" },
+ onClose: vi.fn(),
+ }))
+ })
+ act(() => renderer!.root.findAllByType("img")[1].props.onError())
+ const images = renderer!.root.findAllByType("img")
+ expect(images).toHaveLength(1)
+ expect(images[0].props.src).toBe("/thumbnail")
+ })
+})
diff --git a/src/web/src/components/community/image-lightbox.tsx b/src/web/src/components/community/image-lightbox.tsx
index 7697a5735..aa46be995 100644
--- a/src/web/src/components/community/image-lightbox.tsx
+++ b/src/web/src/components/community/image-lightbox.tsx
@@ -1,25 +1,35 @@
"use client"
-import { Image as ImageIcon } from "lucide-react"
+import { useState } from "react"
import { Dialog, DialogContent } from "@/components/ui/dialog"
+import type { ImagePreview } from "./_types"
+import { tid } from "@/lib/community/testids"
// Full-screen image preview. Uses shadcn Dialog for accessibility (focus trap, Esc, aria).
-export function ImageLightbox({ src, onClose }: { src: string; onClose: () => void }) {
- const isUrl = src.startsWith("http://") || src.startsWith("https://") || src.startsWith("/")
+export function ImageLightbox({ image, onClose }: { image: ImagePreview; onClose: () => void }) {
+ const [originalLoaded, setOriginalLoaded] = useState(false)
+ const [originalFailed, setOriginalFailed] = useState(false)
return (
<Dialog open onOpenChange={(o) => { if (!o) onClose() }}>
<DialogContent
className="flex max-h-[90vh] w-auto sm:max-w-none items-center justify-center border-none bg-transparent p-0 shadow-none"
showCloseButton={false}
>
- {isUrl ? (
- <img src={src} alt="Preview" className="max-h-[85vh] max-w-[90vw] rounded-lg object-contain" />
- ) : (
- <div className="flex aspect-16/10 w-120 flex-col items-center justify-center gap-2 rounded-lg bg-muted text-muted-foreground">
- <ImageIcon className="size-16" />
- <span className="text-sm">{src}</span>
- </div>
- )}
+ <div data-testid={tid.imageLightbox} className="grid max-h-[85vh] max-w-[90vw] place-items-center">
+ {image.thumbnailUrl && (
+ <img data-testid={tid.imageLightboxThumbnail} src={image.thumbnailUrl} alt={image.name} className="col-start-1 row-start-1 max-h-[85vh] max-w-[90vw] rounded-lg object-contain" />
+ )}
+ {!originalFailed && (
+ <img
+ data-testid={tid.imageLightboxOriginal}
+ src={image.originalUrl}
+ alt={image.name}
+ onLoad={() => setOriginalLoaded(true)}
+ onError={() => setOriginalFailed(true)}
+ className={`col-start-1 row-start-1 max-h-[85vh] max-w-[90vw] rounded-lg object-contain ${originalLoaded || !image.thumbnailUrl ? "opacity-100" : "invisible opacity-0"}`}
+ />
+ )}
+ </div>
</DialogContent>
</Dialog>
)
diff --git a/src/web/src/components/community/message-channel-controller.tsx b/src/web/src/components/community/message-channel-controller.tsx
index c4efe6636..41cba910d 100644
--- a/src/web/src/components/community/message-channel-controller.tsx
+++ b/src/web/src/components/community/message-channel-controller.tsx
@@ -6,7 +6,7 @@ import { toast } from "sonner"
import { deriveThreadName, type MentionType } from "@alook/shared"
import { apiFetch, toastApiError } from "@/lib/api/client"
import { avatarInitial } from "@/lib/community/avatar"
-import type { Msg } from "@/components/community/_types"
+import type { ImagePreview, Msg } from "@/components/community/_types"
import type { SendAttachment } from "@/components/community/composer"
import type { useChannelMessageFeed } from "@/hooks/community/use-channel-message-feed"
import {
@@ -46,7 +46,7 @@ type Viewer = {
type MessageUiHandlers = {
navigate?: (serverId: string, channelId: string) => void
- previewImage?: (url: string) => void
+ previewImage?: (image: ImagePreview) => void
}
export function MessageChannelController({
@@ -241,6 +241,9 @@ export function MessageChannelController({
filename: local.file.name,
contentType: local.file.type,
size: local.file.size,
+ ...(attachment.kind === "image" && attachment.thumbnailUrl !== undefined
+ ? { hasThumbnail: true }
+ : {}),
width: local.width,
height: local.height,
}
@@ -253,6 +256,7 @@ export function MessageChannelController({
uploadFileAsync({
target: { channelId },
file: upload.file,
+ thumbnailBlob: upload.thumbnailBlob,
width: upload.width,
height: upload.height,
}).catch((error) => {
@@ -368,7 +372,7 @@ export function MessageChannelController({
nonce: message.clientNonce,
})
},
- onPreviewImage: (url: string) => actionContext.current.uiHandlers.previewImage?.(url),
+ onPreviewImage: (image: ImagePreview) => actionContext.current.uiHandlers.previewImage?.(image),
onDownloadFile: (url: string) => {
const link = document.createElement("a")
link.href = url
@@ -414,6 +418,7 @@ export function MessageChannelController({
if (!attachment.previewObjectUrl) createdPreviewUrls.push(previewObjectUrl)
return {
file: attachment.file,
+ thumbnailBlob: attachment.thumbnailBlob,
previewObjectUrl,
width: attachment.width,
height: attachment.height,
@@ -504,7 +509,7 @@ export type MessageChannelControllerValue = {
onEdit: (id: string) => void
onRetry: (id: string) => void
onDismiss: (id: string) => void
- onPreviewImage: (url: string) => void
+ onPreviewImage: (image: ImagePreview) => void
onDownloadFile: (url: string) => void
}
threadActions: Omit<MessageChannelControllerValue["messageActions"], "onCreateThread"> & {
diff --git a/src/web/src/components/community/message-context-sheet.tsx b/src/web/src/components/community/message-context-sheet.tsx
index 87037dc06..0bd0568f1 100644
--- a/src/web/src/components/community/message-context-sheet.tsx
+++ b/src/web/src/components/community/message-context-sheet.tsx
@@ -18,7 +18,7 @@ import { DateDivider } from "./dividers"
import { useCurrentUser } from "@/contexts/community/current-user"
import { useUiHandlers } from "@/stores/community"
import { usePinMessage, useUnpinMessage, useCreateThread, useToggleMark } from "@/hooks/community/mutations"
-import type { Msg, OpenProfile, Reaction, RenderMsg } from "./_types"
+import type { ImagePreview, Msg, OpenProfile, Reaction, RenderMsg } from "./_types"
import type { MessagesPage } from "@/hooks/community/use-messages"
export type ReplyTarget = { id: string; authorName: string; text: string }
@@ -316,8 +316,8 @@ export function MessageContextSheet({
onOpenChange(false)
}, [type, router, routeParams, onOpenChange])
- const onPreviewImage = useCallback((url: string) => {
- uiHandlers.previewImage?.(url)
+ const onPreviewImage = useCallback((image: ImagePreview) => {
+ uiHandlers.previewImage?.(image)
}, [uiHandlers])
const onDownloadFile = useCallback((url: string) => {
@@ -469,7 +469,7 @@ function ContextRows({
onPin?: (id: string) => void
onMark?: (id: string) => void
onCreateThread?: (id: string) => void
- onPreviewImage: (url: string) => void
+ onPreviewImage: (image: ImagePreview) => void
onDownloadFile: (url: string) => void
}) {
// Single-message share from the peek sheet. The sheet has no select-mode
diff --git a/src/web/src/components/community/message-list.tsx b/src/web/src/components/community/message-list.tsx
index dd7fb57a7..693fb41e3 100644
--- a/src/web/src/components/community/message-list.tsx
+++ b/src/web/src/components/community/message-list.tsx
@@ -16,7 +16,7 @@ import { useScrollAnchor } from "@/hooks/community/use-scroll-anchor"
import { flattenMessageItems } from "./message-list-items"
import { VirtualRows } from "./virtual-cursor-list"
import { useVirtualCursorSentinel } from "@/hooks/community/use-virtual-cursor-sentinel"
-import type { Msg, OpenProfile } from "./_types"
+import type { ImagePreview, Msg, OpenProfile } from "./_types"
// Channel message list — welcome hero, date dividers, messages (with the NEW divider),
// and typing indicator. Data via props.
@@ -47,7 +47,7 @@ export function MessageList({
onEdit?: (id: string) => void
onRetry?: (id: string) => void
onDismiss?: (id: string) => void
- onPreviewImage?: (name: string) => void
+ onPreviewImage?: (image: ImagePreview) => void
onDownloadFile?: (name: string) => void
resolveUserName?: (userId: string) => string
scrollToMessageId?: string | null
diff --git a/src/web/src/components/community/message-row.tsx b/src/web/src/components/community/message-row.tsx
index 52d62fbe7..dc2454f48 100644
--- a/src/web/src/components/community/message-row.tsx
+++ b/src/web/src/components/community/message-row.tsx
@@ -2,7 +2,7 @@
import { memo, useCallback } from "react"
import { Message } from "./message"
-import type { RenderMsg, OpenProfile } from "./_types"
+import type { ImagePreview, RenderMsg, OpenProfile } from "./_types"
// A thin, memoized per-row wrapper between the virtualized list and `Message`.
//
@@ -32,7 +32,7 @@ export interface MessageRowProps {
onRetryId?: (id: string) => void
onDismissId?: (id: string) => void
onJumpToId?: (id: string) => void
- onPreviewImage?: (name: string) => void
+ onPreviewImage?: (image: ImagePreview) => void
onDownloadFile?: (name: string) => void
resolveUserName?: (userId: string) => string
onImageLoad?: () => void
diff --git a/src/web/src/components/community/message.render.test.ts b/src/web/src/components/community/message.render.test.ts
index d138acb48..114e72c41 100644
--- a/src/web/src/components/community/message.render.test.ts
+++ b/src/web/src/components/community/message.render.test.ts
@@ -144,6 +144,7 @@ describe("Message image attachment layout", () => {
})
const image = renderer!.root.findByType("img")
+ expect(image.props.src).toBe("/portrait.png")
expect(image.props).toMatchObject({ width: 396, height: 702 })
expect(image.props.className).toContain("h-auto")
expect(image.props.className).toContain("w-auto")
@@ -152,6 +153,28 @@ describe("Message image attachment layout", () => {
expect(image.parent?.props.className).toContain("w-fit")
expect(image.parent?.props.className).toContain("max-w-full")
})
+
+ it("loads the canonical thumbnail in-list and opens the original identity on click", () => {
+ const onPreviewImage = vi.fn()
+ let renderer: TestRenderer.ReactTestRenderer
+ act(() => {
+ renderer = TestRenderer.create(makeTree({
+ m: baseMsg({ attachments: [{
+ kind: "image", name: "photo.png", url: "/original", thumbnailUrl: "/thumbnail",
+ width: 640, height: 480,
+ }] }),
+ onOpenThread: vi.fn(),
+ onPreviewImage,
+ }), { createNodeMock: () => genericMock })
+ })
+ const image = renderer!.root.findByType("img")
+ expect(image.props.src).toBe("/thumbnail")
+ expect(image.props.loading).toBe("lazy")
+ act(() => image.parent!.props.onClick())
+ expect(onPreviewImage).toHaveBeenCalledWith({
+ originalUrl: "/original", thumbnailUrl: "/thumbnail", name: "photo.png",
+ })
+ })
})
describe("Message lazy overlays", () => {
diff --git a/src/web/src/components/community/message.tsx b/src/web/src/components/community/message.tsx
index b5041fb51..8dab72cf0 100644
--- a/src/web/src/components/community/message.tsx
+++ b/src/web/src/components/community/message.tsx
@@ -21,7 +21,7 @@ import { tid } from "@/lib/community/testids"
import { avatarInitial } from "@/lib/community/avatar"
import { displayName } from "@/lib/community/display-name"
import { stripInlineMarkup } from "@alook/shared"
-import type { RenderMsg, OpenProfile } from "./_types"
+import type { ImagePreview, RenderMsg, OpenProfile } from "./_types"
import { attachmentAspectRatio } from "./attachment-layout"
// Whether the "Share as Image" action is offered for a message. Share is
@@ -62,7 +62,7 @@ function MessageImpl({
onEdit?: () => void
onRetry?: () => void
onDismiss?: () => void
- onPreviewImage?: (name: string) => void
+ onPreviewImage?: (image: ImagePreview) => void
onDownloadFile?: (name: string) => void
highlighted?: boolean
resolveUserName?: (userId: string) => string
@@ -251,17 +251,19 @@ function MessageImpl({
if (a.kind === "image") return (
<button
key={i}
- onClick={() => onPreviewImage?.(a.url)}
+ onClick={() => onPreviewImage?.({ originalUrl: a.url, thumbnailUrl: a.thumbnailUrl, name: a.name })}
className="block w-fit max-w-full overflow-hidden rounded-lg border border-border transition-colors hover:border-primary/40"
>
<img
- src={a.url}
+ data-testid={tid.messageImage(m.id, i)}
+ src={a.thumbnailUrl ?? a.url}
alt={a.name}
width={a.width}
height={a.height}
className="block h-auto w-auto max-h-75 max-w-full rounded-lg object-contain"
style={{ aspectRatio: attachmentAspectRatio(a.width, a.height) }}
onLoad={onImageLoad}
+ loading="lazy"
/>
</button>
)
diff --git a/src/web/src/components/community/shell-frame.tsx b/src/web/src/components/community/shell-frame.tsx
index e282bb13b..668db2e89 100644
--- a/src/web/src/components/community/shell-frame.tsx
+++ b/src/web/src/components/community/shell-frame.tsx
@@ -28,7 +28,7 @@ import { ProfileCard } from "./profile-card"
import { ImageLightbox } from "./image-lightbox"
import { ImageCropDialog } from "./image-crop-dialog"
import { validateIconSourceFile } from "@/lib/community/image-crop"
-import type { Marked, MobileZone, Profile, View } from "./_types"
+import type { ImagePreview, Marked, MobileZone, Profile, View } from "./_types"
import { resolveProfileTarget, buildSelfProfile } from "./profile-lookup"
import { resolveProfilePresence } from "@/lib/community/presence"
import { avatarInitial } from "@/lib/community/avatar"
@@ -178,7 +178,7 @@ export function ShellFrame({
initialStatusEmoji: string | null
initialStatusText: string | null
} | null>(null)
- const [preview, setPreview] = useState<string | null>(null)
+ const [preview, setPreview] = useState<ImagePreview | null>(null)
const [pendingAvatarCrop, setPendingAvatarCrop] = useState<{ src: string; fileName: string } | null>(null)
// Rail wiring — universal, since navigation is URL-driven and doesn't
@@ -426,7 +426,7 @@ export function ShellFrame({
[currentUser, members, friends, queryClient, onlineUserIds],
)
- const previewImage = useCallback((url: string) => setPreview(url), [])
+ const previewImage = useCallback((image: ImagePreview) => setPreview(image), [])
const goBackMobile = useCallback(() => setMobileZone("nav"), [setMobileZone])
// Navigate for channel/server-ref pills. They live deep in the memoized
// Streamdown message tree where a subtree `useRouter().push` is a no-op; the
@@ -733,7 +733,7 @@ export function ShellFrame({
</div>
</div>
{profile && <ProfileCard key={`${profile.data.userId ?? profile.data.name}:${profile.x}:${profile.y}`} data={profile.data} x={profile.x} y={profile.y} bp={bp} onClose={() => setProfile(null)} onMessage={profileMessage} isSelf={!!profile.data.userId && profile.data.userId === currentUser.id} onUpdateStatus={updateOwnStatus} initialStatusEmoji={profile.initialStatusEmoji} initialStatusText={profile.initialStatusText} />}
- {preview && <ImageLightbox src={preview} onClose={() => setPreview(null)} />}
+ {preview && <ImageLightbox image={preview} onClose={() => setPreview(null)} />}
{userSettingsDialog}
{avatarCropDialog}
{extraDialogs}
@@ -758,7 +758,7 @@ export function ShellFrame({
</div>
)}
{profile && <ProfileCard key={`${profile.data.userId ?? profile.data.name}:${profile.x}:${profile.y}`} data={profile.data} x={profile.x} y={profile.y} bp={bp} onClose={() => setProfile(null)} onMessage={profileMessage} isSelf={!!profile.data.userId && profile.data.userId === currentUser.id} onUpdateStatus={updateOwnStatus} />}
- {preview && <ImageLightbox src={preview} onClose={() => setPreview(null)} />}
+ {preview && <ImageLightbox image={preview} onClose={() => setPreview(null)} />}
{userSettingsDialog}
{avatarCropDialog}
{extraDialogs}
diff --git a/src/web/src/components/community/text-channel-surface.test.ts b/src/web/src/components/community/text-channel-surface.test.ts
index e230d10c5..b9c110555 100644
--- a/src/web/src/components/community/text-channel-surface.test.ts
+++ b/src/web/src/components/community/text-channel-surface.test.ts
@@ -4,6 +4,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
import { MessageChannelController } from "./message-channel-controller"
import type { MessageChannelControllerValue } from "./message-channel-controller"
import type { useChannelMessageFeed } from "@/hooks/community/use-channel-message-feed"
+import { buildAttachmentUploadFormData } from "@/hooks/community/mutations/uploads"
+import { useMessageStreamStore } from "@/stores/community/message-stream"
const mutationMocks = vi.hoisted(() => ({
sendMessage: vi.fn(),
@@ -22,7 +24,10 @@ vi.mock("next/navigation", () => ({
}))
vi.mock("sonner", () => ({ toast: vi.fn() }))
vi.mock("@/lib/api/client", () => ({ apiFetch: vi.fn(), toastApiError: vi.fn() }))
-vi.mock("@alook/shared", () => ({ deriveThreadName: () => "thread" }))
+vi.mock("@alook/shared", () => ({
+ deriveThreadName: () => "thread",
+ MAX_ATTACHMENT_THUMBNAIL_SIZE_BYTES: 50 * 1024,
+}))
vi.mock("@/stores/community", () => {
const state = {
pendingReply: null,
@@ -50,6 +55,7 @@ vi.mock("@/hooks/community/mutations", () => ({
useUploadFile: () => ({ mutateAsync: mutationMocks.uploadFile }),
zipUploadResultsWithDimensions: () => [],
sendNonce: () => "nonce_1",
+ tempMessageId: () => "temp_1",
}))
vi.mock("@/hooks/community/use-community-ws", () => ({
communityWsSendTyping: vi.fn(),
@@ -122,6 +128,7 @@ function ControllerProbe({ controller }: { controller: MessageChannelControllerV
describe("MessageChannelController scroll target ownership", () => {
beforeEach(() => {
vi.useFakeTimers()
+ useMessageStreamStore.getState().resetAll()
})
afterEach(() => {
@@ -236,4 +243,54 @@ describe("MessageChannelController scroll target ownership", () => {
expect(latestOpenPinned).toHaveBeenCalledTimes(1)
expect(firstOpenPinned).not.toHaveBeenCalled()
})
+
+ it("retries a failed channel upload with the identical thumbnail Blob in multipart", async () => {
+ const thumbnailBlob = new Blob([new Uint8Array([0xff, 0xd8, 0xff, 0xd9])], { type: "image/jpeg" })
+ const file = new File(["original"], "photo.png", { type: "image/png" })
+ mutationMocks.uploadFile
+ .mockRejectedValueOnce(new Error("upload failed"))
+ .mockResolvedValueOnce({
+ id: "att_thumb",
+ filename: "photo.png",
+ contentType: "image/png",
+ size: 8,
+ hasThumbnail: true,
+ })
+ mutationMocks.sendMessage.mockResolvedValueOnce({ message: { id: "server_thumb", seq: 10 } })
+ let renderer: TestRenderer.ReactTestRenderer
+
+ act(() => {
+ renderer = TestRenderer.create(renderController(feed()))
+ })
+ const firstController = renderer!.root.findByType(ControllerProbe).props.controller as MessageChannelControllerValue
+ await act(async () => {
+ firstController.acceptMessage("photo", [{
+ file,
+ thumbnailBlob,
+ previewObjectUrl: "blob:thumbnail",
+ width: 640,
+ height: 480,
+ }])
+ await Promise.resolve()
+ await Promise.resolve()
+ })
+
+ act(() => {
+ renderer!.update(renderController(feed({
+ messages: [{ id: "temp_1", clientNonce: "nonce_1", type: "chat", content: "photo" }],
+ })))
+ })
+ const retriedController = renderer!.root.findByType(ControllerProbe).props.controller as MessageChannelControllerValue
+ await act(async () => {
+ retriedController.messageActions.onRetry("temp_1")
+ await Promise.resolve()
+ await Promise.resolve()
+ })
+
+ expect(mutationMocks.uploadFile).toHaveBeenCalledTimes(2)
+ for (const [args] of mutationMocks.uploadFile.mock.calls) {
+ expect(args.thumbnailBlob).toBe(thumbnailBlob)
+ expect((buildAttachmentUploadFormData(args).get("thumbnail") as File).size).toBe(4)
+ }
+ })
})
diff --git a/src/web/src/components/community/text-channel-surface.tsx b/src/web/src/components/community/text-channel-surface.tsx
index 1275d5357..2080200cd 100644
--- a/src/web/src/components/community/text-channel-surface.tsx
+++ b/src/web/src/components/community/text-channel-surface.tsx
@@ -13,7 +13,7 @@ import { MessageList } from "@/components/community/message-list"
import {
MessageChannelController,
} from "@/components/community/message-channel-controller"
-import type { OpenProfile, RightPanel } from "@/components/community/_types"
+import type { ImagePreview, OpenProfile, RightPanel } from "@/components/community/_types"
export function TextChannelSurface({
channelId,
@@ -53,7 +53,7 @@ export function TextChannelSurface({
manageMembersDialog: ReactNode
uiHandlers: {
navigate?: (serverId: string, channelId: string) => void
- previewImage?: (url: string) => void
+ previewImage?: (image: ImagePreview) => void
}
onOpenThread: (threadId: string) => void
onOpenProfile: OpenProfile
diff --git a/src/web/src/components/community/thread-channel-surface.tsx b/src/web/src/components/community/thread-channel-surface.tsx
index 7191a4eff..68fcb6568 100644
--- a/src/web/src/components/community/thread-channel-surface.tsx
+++ b/src/web/src/components/community/thread-channel-surface.tsx
@@ -14,7 +14,7 @@ import { MessageChannelController } from "@/components/community/message-channel
import { MessageContextSheet } from "@/components/community/message-context-sheet"
import { MessageList } from "@/components/community/message-list"
import { ThreadOpener } from "@/components/community/thread-opener"
-import type { OpenProfile, RightPanel } from "@/components/community/_types"
+import type { ImagePreview, OpenProfile, RightPanel } from "@/components/community/_types"
import type { ChannelMemberPanelProps } from "@/components/community/channel-member-view-model"
const ignoreNestedThread = () => {}
@@ -71,7 +71,7 @@ export function ThreadChannelSurface({
manageMembersDialog: ReactNode
uiHandlers: {
navigate?: (serverId: string, channelId: string) => void
- previewImage?: (url: string) => void
+ previewImage?: (image: ImagePreview) => void
}
onOpenChild: (childId: string) => void
onOpenProfile: OpenProfile
@@ -154,7 +154,7 @@ export function ThreadChannelSurface({
<ThreadOpener
parentMessageId={parentMessageId}
onOpenProfile={onOpenProfile}
- onPreviewImage={(url) => uiHandlers.previewImage?.(url)}
+ onPreviewImage={(image) => uiHandlers.previewImage?.(image)}
onDownloadFile={(url) => {
const link = document.createElement("a")
link.href = url
diff --git a/src/web/src/components/community/thread-opener.test.ts b/src/web/src/components/community/thread-opener.test.ts
index 3e1c0e0de..5c6d521fa 100644
--- a/src/web/src/components/community/thread-opener.test.ts
+++ b/src/web/src/components/community/thread-opener.test.ts
@@ -46,6 +46,7 @@ describe("ThreadOpener image attachment layout", () => {
})
const image = renderer!.root.findByType("img")
+ expect(image.props.src).toBe("/portrait.png")
expect(image.props).toMatchObject({ width: 396, height: 702 })
expect(image.props.className).toContain("h-auto")
expect(image.props.className).toContain("w-auto")
@@ -54,4 +55,30 @@ describe("ThreadOpener image attachment layout", () => {
expect(image.parent?.props.className).toContain("w-fit")
expect(image.parent?.props.className).toContain("max-w-full")
})
+
+ it("uses thumbnailUrl for the list image and passes the original on click", () => {
+ const onPreviewImage = vi.fn()
+ useMessageMock.mockReturnValue({
+ isLoading: false,
+ isError: false,
+ message: {
+ id: "opener_1", type: "chat", authorId: "u1", authorName: "Alice",
+ content: "Photo", createdAt: "2026-08-08T00:00:00.000Z",
+ attachments: [{ kind: "image", name: "photo.png", url: "/original", thumbnailUrl: "/thumbnail" }],
+ },
+ })
+ let renderer: TestRenderer.ReactTestRenderer
+ act(() => {
+ renderer = TestRenderer.create(
+ React.createElement(ThreadOpener, { parentMessageId: "opener_1", onPreviewImage }),
+ { createNodeMock: () => genericMock },
+ )
+ })
+ const image = renderer!.root.findByType("img")
+ expect(image.props).toMatchObject({ src: "/thumbnail", loading: "lazy" })
+ act(() => image.parent!.props.onClick())
+ expect(onPreviewImage).toHaveBeenCalledWith({
+ originalUrl: "/original", thumbnailUrl: "/thumbnail", name: "photo.png",
+ })
+ })
})
diff --git a/src/web/src/components/community/thread-opener.tsx b/src/web/src/components/community/thread-opener.tsx
index 0ed5dbab2..a0c744d37 100644
--- a/src/web/src/components/community/thread-opener.tsx
+++ b/src/web/src/components/community/thread-opener.tsx
@@ -9,7 +9,8 @@ import { Skeleton } from "@/components/ui/skeleton"
import { NumberTicker } from "@/components/ui/number-ticker"
import { avatarInitial } from "@/lib/community/avatar"
import { useMessage } from "@/hooks/community/use-message"
-import type { OpenProfile } from "./_types"
+import { tid } from "@/lib/community/testids"
+import type { ImagePreview, OpenProfile } from "./_types"
// Thread opener — the parent message the thread was created from, pinned at
// the top of the thread's message list. Deliberately styled like a REGULAR
@@ -34,7 +35,7 @@ export function ThreadOpener({
}: {
parentMessageId: string
onOpenProfile?: OpenProfile
- onPreviewImage?: (url: string) => void
+ onPreviewImage?: (image: ImagePreview) => void
onDownloadFile?: (url: string) => void
// Jump to the parent message in its channel. When provided, a hover-revealed
// "Jump" button appears in the opener's top-right.
@@ -109,16 +110,18 @@ export function ThreadOpener({
if (a.kind === "image") return (
<button
key={i}
- onClick={() => onPreviewImage?.(a.url)}
+ onClick={() => onPreviewImage?.({ originalUrl: a.url, thumbnailUrl: a.thumbnailUrl, name: a.name })}
className="block w-fit max-w-full overflow-hidden rounded-lg border border-border transition-colors hover:border-primary/40"
>
<img
- src={a.url}
+ data-testid={tid.threadOpenerImage(i)}
+ src={a.thumbnailUrl ?? a.url}
alt={a.name}
width={a.width}
height={a.height}
className="block h-auto w-auto max-h-75 max-w-full rounded-lg object-contain"
style={{ aspectRatio: attachmentAspectRatio(a.width, a.height) }}
+ loading="lazy"
/>
</button>
)
diff --git a/src/web/src/hooks/community/mutations/messages.ts b/src/web/src/hooks/community/mutations/messages.ts
index 7e2e07342..e16b2a1e7 100644
--- a/src/web/src/hooks/community/mutations/messages.ts
+++ b/src/web/src/hooks/community/mutations/messages.ts
@@ -11,6 +11,7 @@ import { apiFetch, toastApiError } from "@/lib/api/client"
import { ApiError } from "@/lib/errors"
import { communityKeys } from "@/lib/query-keys"
import { isInlineAttachmentContentType } from "@/lib/community/attachment-content-type"
+import { attachmentThumbnailUrl, attachmentUrl } from "@/lib/community/storage"
import {
projectPostedMessage,
type PostedMessage,
@@ -152,7 +153,7 @@ export function useEditMessage() {
*/
export function toAttachmentVm(
channelId: string,
- a: { id: string; filename: string; contentType: string; size: number; width?: number; height?: number },
+ a: { id: string; filename: string; contentType: string; size: number; hasThumbnail?: boolean; width?: number; height?: number },
): Attachment {
// Reserve-by-id (route/disc step 2b): the server no longer returns a `url` for
// a fresh upload — it returns the attachment `id`. The display URL is
@@ -160,9 +161,16 @@ export function toAttachmentVm(
// and derived HERE client-side, matching what the server's read path emits via
// `attachmentUrl`. This keeps the optimistic row's image src identical to the
// reconciled row that arrives over WS.
- const url = `/api/community/channels/${channelId}/attachments/${a.id}`
+ const url = attachmentUrl(channelId, a.id)
const isImage = isInlineAttachmentContentType(a.contentType)
- if (isImage) return { kind: "image", name: a.filename, url, width: a.width, height: a.height }
+ if (isImage) return {
+ kind: "image",
+ name: a.filename,
+ url,
+ ...(a.hasThumbnail ? { thumbnailUrl: attachmentThumbnailUrl(channelId, a.id) } : {}),
+ width: a.width,
+ height: a.height,
+ }
return {
kind: "file",
name: a.filename,
@@ -202,7 +210,7 @@ export type SendMessageArgs = {
// sent to the server (in an id array); the rest drive the optimistic VM
// (whose url is derived client-side from `id`). No `url` field — the upload
// no longer returns one.
- attachments?: { id: string; filename: string; contentType: string; size: number; width?: number; height?: number }[]
+ attachments?: { id: string; filename: string; contentType: string; size: number; hasThumbnail?: boolean; width?: number; height?: number }[]
author: { id: string; name: string; avatar: string }
// Idempotency nonce. Omitted on a fresh send (the hook mints one); the
// retry-pill caller passes the failed row's nonce back so the resend reuses
diff --git a/src/web/src/hooks/community/mutations/to-attachment-vm.test.ts b/src/web/src/hooks/community/mutations/to-attachment-vm.test.ts
index 3a2862607..c799547a8 100644
--- a/src/web/src/hooks/community/mutations/to-attachment-vm.test.ts
+++ b/src/web/src/hooks/community/mutations/to-attachment-vm.test.ts
@@ -9,6 +9,20 @@ import { toAttachmentVm } from "./messages"
// The image branch must carry width/height through — a silent-drop site flagged
// in plans/attachment-image-dimensions.md's plan review.
describe("toAttachmentVm", () => {
+ it("derives the canonical thumbnail URL only from server confirmation", () => {
+ expect(toAttachmentVm("c1", {
+ id: "att_1", filename: "a.png", contentType: "image/png", size: 1000, hasThumbnail: true,
+ })).toMatchObject({
+ thumbnailUrl: "/api/community/channels/c1/attachments/att_1/thumbnail",
+ })
+ expect(toAttachmentVm("c1", {
+ id: "att_1", filename: "a.png", contentType: "image/png", size: 1000, hasThumbnail: false,
+ })).not.toHaveProperty("thumbnailUrl")
+ expect(toAttachmentVm("c1", {
+ id: "att_1", filename: "a.png", contentType: "image/png", size: 1000,
+ })).not.toHaveProperty("thumbnailUrl")
+ })
+
it("carries width/height through on an image attachment + derives the id-addressed url", () => {
const result = toAttachmentVm("c1", {
id: "att_1",
diff --git a/src/web/src/hooks/community/mutations/uploads.test.ts b/src/web/src/hooks/community/mutations/uploads.test.ts
index 81e6e1a72..081bc70b7 100644
--- a/src/web/src/hooks/community/mutations/uploads.test.ts
+++ b/src/web/src/hooks/community/mutations/uploads.test.ts
@@ -1,5 +1,9 @@
import { describe, it, expect } from "vitest"
-import { zipUploadResultsWithDimensions } from "./uploads"
+import {
+ appendGeneratedThumbnail,
+ buildAttachmentUploadFormData,
+ zipUploadResultsWithDimensions,
+} from "./uploads"
import type { UploadFileResult } from "./uploads"
// The zip must happen BEFORE filtering out failed uploads (`null` results),
@@ -56,3 +60,43 @@ describe("zipUploadResultsWithDimensions", () => {
expect(zipUploadResultsWithDimensions([], [])).toEqual([])
})
})
+
+describe("appendGeneratedThumbnail", () => {
+ it("appends an in-cap JPEG", () => {
+ const form = new FormData()
+ const blob = new Blob([new Uint8Array([0xff, 0xd8, 0xff, 0xd9])], { type: "image/jpeg" })
+ expect(appendGeneratedThumbnail(form, "image/png", blob)).toBe(true)
+ expect((form.get("thumbnail") as File).type).toBe("image/jpeg")
+ })
+
+ it("degrades to original-only when the generated thumbnail exceeds 50 KiB", () => {
+ const form = new FormData()
+ const blob = new Blob([new Uint8Array(50 * 1024 + 1)], { type: "image/jpeg" })
+ expect(appendGeneratedThumbnail(form, "image/png", blob)).toBe(false)
+ expect(form.has("thumbnail")).toBe(false)
+ })
+
+ it.each(["image/avif", "image/bmp"])(
+ "degrades a browser-decodable %s original to original-only",
+ (contentType) => {
+ const form = new FormData()
+ const blob = new Blob([new Uint8Array([0xff, 0xd8, 0xff, 0xd9])], { type: "image/jpeg" })
+ expect(appendGeneratedThumbnail(form, contentType, blob)).toBe(false)
+ expect(form.has("thumbnail")).toBe(false)
+ },
+ )
+
+ it.each([
+ ["channel", { channelId: "channel_1" }],
+ ["DM", { dmId: "dm_1" }],
+ ])("builds %s retry multipart with the generated thumbnail", (_label, _target) => {
+ const file = new File(["original"], "photo.png", { type: "image/png" })
+ const thumbnailBlob = new Blob([new Uint8Array([0xff, 0xd8, 0xff, 0xd9])], { type: "image/jpeg" })
+ const form = buildAttachmentUploadFormData({ file, thumbnailBlob, width: 640, height: 480 })
+
+ expect(form.get("file")).toBe(file)
+ expect(form.get("thumbnail")).toEqual(expect.objectContaining({ type: "image/jpeg", size: 4 }))
+ expect(form.get("width")).toBe("640")
+ expect(form.get("height")).toBe("480")
+ })
+})
diff --git a/src/web/src/hooks/community/mutations/uploads.ts b/src/web/src/hooks/community/mutations/uploads.ts
index 7be09cd7c..738d65f87 100644
--- a/src/web/src/hooks/community/mutations/uploads.ts
+++ b/src/web/src/hooks/community/mutations/uploads.ts
@@ -1,13 +1,15 @@
"use client"
import { useMutation } from "@tanstack/react-query"
+import { MAX_ATTACHMENT_THUMBNAIL_SIZE_BYTES } from "@alook/shared"
import { readUploadError } from "@/lib/api/client"
+import { isInlineAttachmentContentType } from "@/lib/community/attachment-content-type"
/**
* File upload mutations. These POST multipart to the channel/dm/thread upload
- * routes; the response includes the R2-hosted URL + metadata. Consumers pass
- * the returned attachment payload into `useSendMessage` / `useSendDmMessage`
- * so the message row references the freshly uploaded blob.
+ * routes; the response includes a stable attachment id + metadata. Consumers
+ * pass the returned attachment payload into `useSendMessage` /
+ * `useSendDmMessage` so the message row references the freshly uploaded blob.
*/
export type UploadTarget = {
@@ -16,7 +18,13 @@ export type UploadTarget = {
threadId?: string
}
-export type UploadFileArgs = { target: UploadTarget; file: File; width?: number; height?: number }
+export type UploadFileArgs = {
+ target: UploadTarget
+ file: File
+ thumbnailBlob?: Blob
+ width?: number
+ height?: number
+}
// Reserve-by-id (route/disc step 2b): the upload now creates a PENDING
// attachment row and returns its stable `id` (mirroring the bot flow). The
@@ -29,20 +37,49 @@ export type UploadFileResult = {
filename: string
contentType: string
size: number
+ hasThumbnail?: boolean
width?: number
height?: number
}
export type UploadedAttachment = UploadFileResult & { width?: number; height?: number }
+export function appendGeneratedThumbnail(
+ formData: FormData,
+ originalContentType: string,
+ thumbnailBlob?: Blob,
+): boolean {
+ if (
+ !isInlineAttachmentContentType(originalContentType) ||
+ !thumbnailBlob ||
+ thumbnailBlob.size > MAX_ATTACHMENT_THUMBNAIL_SIZE_BYTES
+ ) return false
+ formData.append("thumbnail", thumbnailBlob, "thumbnail.jpg")
+ return true
+}
+
+export function buildAttachmentUploadFormData({
+ file,
+ thumbnailBlob,
+ width,
+ height,
+}: Pick<UploadFileArgs, "file" | "thumbnailBlob" | "width" | "height">): FormData {
+ const formData = new FormData()
+ formData.append("file", file)
+ appendGeneratedThumbnail(formData, file.type, thumbnailBlob)
+ if (width !== undefined) formData.append("width", String(width))
+ if (height !== undefined) formData.append("height", String(height))
+ return formData
+}
+
/**
* Zip each upload result back to its ORIGINAL INDEX in the input attachments
* array (not by `File` identity — `Promise.all` already preserves input
* order regardless of completion order, so a plain index is enough and can't
* collide if two attachments happen to share a `File` reference) to pull
- * width/height in. Dimensions never cross the network to the upload
- * endpoint; they're only known client-side and get attached here, after the
- * upload resolves.
+ * width/height in. Dimensions also ride the upload multipart so the pending
+ * row can persist them; this zip keeps the optimistic result aligned with the
+ * same original input index after the response resolves.
*
* The zip MUST happen before dropping failed (`null`) results, or indices
* between `results` and `attachments` misalign once a failed upload is
@@ -64,23 +101,18 @@ function uploadPath(target: UploadTarget): string | null {
// door. Whichever id the target carries, it's a channelId to channels/{id}.
// Canonical attachments door (route/disc trunk): POST channels/{id}/attachments
// (re-pointed off the old channels/{id}/upload, which stays alive through the
- // deploy window and is deleted at the flat-delete step). Response shape is
- // unchanged — the human arm still returns the `{ url, filename, ... }` carrier.
+ // deploy window and is deleted at the flat-delete step). The response is the
+ // stable attachment-id carrier consumed by the later message send.
const id = target.threadId ?? target.dmId ?? target.channelId
return id ? `/api/community/channels/${id}/attachments` : null
}
export function useUploadFile() {
return useMutation<UploadFileResult, Error, UploadFileArgs>({
- mutationFn: async ({ target, file, width, height }) => {
+ mutationFn: async ({ target, file, thumbnailBlob, width, height }) => {
const path = uploadPath(target)
if (!path) throw new Error("Upload target requires channelId, dmId, or threadId")
- const formData = new FormData()
- formData.append("file", file)
- // Image dimensions ride the upload body (single source — written onto the
- // pending row server-side; never re-sent on the message `send`).
- if (width !== undefined) formData.append("width", String(width))
- if (height !== undefined) formData.append("height", String(height))
+ const formData = buildAttachmentUploadFormData({ file, thumbnailBlob, width, height })
const res = await fetch(path, {
method: "POST",
body: formData,
diff --git a/src/web/src/hooks/community/use-dm-message-sender.test.ts b/src/web/src/hooks/community/use-dm-message-sender.test.ts
index 39228cd04..dffda60e7 100644
--- a/src/web/src/hooks/community/use-dm-message-sender.test.ts
+++ b/src/web/src/hooks/community/use-dm-message-sender.test.ts
@@ -2,6 +2,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest"
import { getMessageOverlay, useMessageStreamStore } from "@/stores/community/message-stream"
import { materializeMessageStream } from "@/lib/community/message-stream"
import { MESSAGE_PREVIEW_LENGTH } from "@alook/shared"
+import { buildAttachmentUploadFormData } from "./mutations/uploads"
vi.mock("react", () => ({
useCallback: (fn: Function) => fn,
@@ -95,6 +96,42 @@ describe("useDmMessageSender", () => {
expect(intent?.status).toBe("failed")
})
+ it("retries a failed DM upload with the identical thumbnail Blob in multipart", async () => {
+ const thumbnailBlob = new Blob([new Uint8Array([0xff, 0xd8, 0xff, 0xd9])], { type: "image/jpeg" })
+ uploadMock
+ .mockRejectedValueOnce(new Error("upload failed"))
+ .mockResolvedValueOnce({
+ id: "att_thumb",
+ filename: "photo.png",
+ contentType: "image/png",
+ size: 8,
+ hasThumbnail: true,
+ })
+ postMock.mockResolvedValueOnce({ message: { id: "server_thumb", seq: 10 } })
+ const { useDmMessageSender } = await import("./use-dm-message-sender")
+ const sender = useDmMessageSender()
+ const file = new File(["original"], "photo.png", { type: "image/png" })
+ const receipt = sender.accept({
+ dmId: "dm_1",
+ content: "photo",
+ attachments: [{ file, thumbnailBlob, previewObjectUrl: "blob:thumbnail", width: 640, height: 480 }],
+ author: { id: "u_me", name: "Me", avatar: "M" },
+ })
+
+ if (!receipt.accepted) throw new Error("expected accepted receipt")
+ await expect(receipt.committed).resolves.toEqual({ ok: false, error: expect.any(Error) })
+ await expect(sender.retry("dm_1", "fresh_nonce")).resolves.toEqual({
+ ok: true,
+ message: { id: "server_thumb", seq: 10 },
+ })
+
+ expect(uploadMock).toHaveBeenCalledTimes(2)
+ for (const [args] of uploadMock.mock.calls) {
+ expect(args.thumbnailBlob).toBe(thumbnailBlob)
+ expect((buildAttachmentUploadFormData(args).get("thumbnail") as File).size).toBe(4)
+ }
+ })
+
it("retries the same nonce and reports network failure without emitting a terminal event itself", async () => {
postMock.mockRejectedValueOnce(new Error("offline"))
const { useDmMessageSender } = await import("./use-dm-message-sender")
diff --git a/src/web/src/hooks/community/use-dm-message-sender.ts b/src/web/src/hooks/community/use-dm-message-sender.ts
index f8a9e1cac..521b98abb 100644
--- a/src/web/src/hooks/community/use-dm-message-sender.ts
+++ b/src/web/src/hooks/community/use-dm-message-sender.ts
@@ -63,6 +63,9 @@ export function useDmMessageSender() {
filename: local.file.name,
contentType: local.file.type,
size: local.file.size,
+ ...(attachment.kind === "image" && attachment.thumbnailUrl !== undefined
+ ? { hasThumbnail: true }
+ : {}),
width: local.width,
height: local.height,
}
@@ -76,6 +79,7 @@ export function useDmMessageSender() {
uploadFileAsync({
target: { dmId },
file: upload.file,
+ thumbnailBlob: upload.thumbnailBlob,
width: upload.width,
height: upload.height,
}).catch((error) => {
@@ -134,6 +138,7 @@ export function useDmMessageSender() {
if (!attachment.previewObjectUrl) createdPreviewUrls.push(previewObjectUrl)
return {
file: attachment.file,
+ thumbnailBlob: attachment.thumbnailBlob,
previewObjectUrl,
width: attachment.width,
height: attachment.height,
diff --git a/src/web/src/hooks/use-file-attachments.test.ts b/src/web/src/hooks/use-file-attachments.test.ts
index bac547293..9aff30fdd 100644
--- a/src/web/src/hooks/use-file-attachments.test.ts
+++ b/src/web/src/hooks/use-file-attachments.test.ts
@@ -94,4 +94,34 @@ describe("useFileAttachments — PendingFile width/height", () => {
expect(hook.current.pendingFiles).toEqual([])
expect(URL.revokeObjectURL).not.toHaveBeenCalled()
})
+
+ it("registers preparation synchronously and returns a fresh stable snapshot", async () => {
+ let resolveThumbnail!: (value: { blob: Blob; width: number; height: number }) => void
+ generateThumbnailMock.mockReturnValueOnce(new Promise((resolve) => { resolveThumbnail = resolve }))
+ const hook = await renderCapture()
+ const file = new File(["original"], "photo.png", { type: "image/png" })
+ const thumbnailBlob = new Blob(["thumbnail"], { type: "image/jpeg" })
+
+ let addPromise!: Promise<void>
+ let snapshotPromise!: Promise<readonly PendingFile[]>
+ await act(async () => {
+ addPromise = hook.current.addPendingFiles([file])
+ snapshotPromise = hook.current.awaitPendingFiles()
+ await Promise.resolve()
+ })
+ let settled = false
+ void snapshotPromise.then(() => { settled = true })
+ await Promise.resolve()
+ expect(settled).toBe(false)
+
+ await act(async () => {
+ resolveThumbnail({ blob: thumbnailBlob, width: 640, height: 480 })
+ await addPromise
+ })
+ const snapshot = await snapshotPromise
+ expect(snapshot).toHaveLength(1)
+ expect(snapshot[0].file).toBe(file)
+ expect(snapshot[0].thumbnailBlob).toBe(thumbnailBlob)
+ expect(hook.current.pendingFiles[0]).toBe(snapshot[0])
+ })
})
diff --git a/src/web/src/hooks/use-file-attachments.ts b/src/web/src/hooks/use-file-attachments.ts
index c003597e9..ee809d36a 100644
--- a/src/web/src/hooks/use-file-attachments.ts
+++ b/src/web/src/hooks/use-file-attachments.ts
@@ -33,18 +33,14 @@ export function useFileAttachments(opts: UseFileAttachmentsOptions = {}) {
});
const [pendingFiles, _setPendingFiles] = useState<PendingFile[]>([]);
const pendingFilesRef = useRef(pendingFiles);
- useEffect(() => {
- pendingFilesRef.current = pendingFiles;
- });
+ const preparationTailRef = useRef<Promise<void>>(Promise.resolve());
const setPendingFiles = useCallback((next: PendingFile[] | ((prev: PendingFile[]) => PendingFile[])) => {
- _setPendingFiles((prev) => {
- const nextVal = typeof next === "function" ? next(prev) : next;
- if (nextVal.length === 0 && prev.length > 0) {
- revokeThumbnailUrls(prev);
- }
- return nextVal;
- });
+ const prev = pendingFilesRef.current;
+ const nextVal = typeof next === "function" ? next(prev) : next;
+ if (nextVal.length === 0 && prev.length > 0) revokeThumbnailUrls(prev);
+ pendingFilesRef.current = nextVal;
+ _setPendingFiles(nextVal);
}, []);
const transferPendingFiles = useCallback(() => {
@@ -61,33 +57,48 @@ export function useFileAttachments(opts: UseFileAttachmentsOptions = {}) {
const fileInputRef = useRef<HTMLInputElement>(null);
const addPendingFiles = useCallback(async (files: File[]) => {
- const { maxFileSize: maxSize } = optsRef.current;
- const valid: File[] = [];
- for (const file of files) {
- if (file.size > maxSize) {
- const mb = Math.floor(maxSize / 1024 / 1024);
- toast.error(`"${file.name}" exceeds ${mb} MB limit`);
- continue;
+ const prior = preparationTailRef.current;
+ const preparation = prior.then(async () => {
+ const { maxFileSize: maxSize } = optsRef.current;
+ const valid: File[] = [];
+ for (const file of files) {
+ if (file.size > maxSize) {
+ const mb = Math.floor(maxSize / 1024 / 1024);
+ toast.error(`"${file.name}" exceeds ${mb} MB limit`);
+ continue;
+ }
+ valid.push(file);
}
- valid.push(file);
+ if (valid.length === 0) return;
+
+ const pending: PendingFile[] = await Promise.all(
+ valid.map(async (file) => {
+ const thumbnail = await generateThumbnail(file);
+ const thumbnailUrl = thumbnail ? URL.createObjectURL(thumbnail.blob) : null;
+ return {
+ file,
+ thumbnailUrl,
+ thumbnailBlob: thumbnail?.blob ?? null,
+ width: thumbnail?.width,
+ height: thumbnail?.height,
+ };
+ }),
+ );
+
+ const next = [...pendingFilesRef.current, ...pending];
+ pendingFilesRef.current = next;
+ _setPendingFiles(next);
+ });
+ preparationTailRef.current = preparation.catch(() => {});
+ await preparation;
+ }, []);
+
+ const awaitPendingFiles = useCallback(async (): Promise<readonly PendingFile[]> => {
+ while (true) {
+ const tail = preparationTailRef.current;
+ await tail;
+ if (tail === preparationTailRef.current) return pendingFilesRef.current;
}
- if (valid.length === 0) return;
-
- const pending: PendingFile[] = await Promise.all(
- valid.map(async (file) => {
- const thumbnail = await generateThumbnail(file);
- const thumbnailUrl = thumbnail ? URL.createObjectURL(thumbnail.blob) : null;
- return {
- file,
- thumbnailUrl,
- thumbnailBlob: thumbnail?.blob ?? null,
- width: thumbnail?.width,
- height: thumbnail?.height,
- };
- }),
- );
-
- _setPendingFiles((prev) => [...prev, ...pending]);
}, []);
const handleFileSelect = useCallback(
@@ -101,11 +112,12 @@ export function useFileAttachments(opts: UseFileAttachmentsOptions = {}) {
);
const removePendingFile = useCallback((index: number) => {
- _setPendingFiles((prev) => {
- const removed = prev[index];
- if (removed?.thumbnailUrl) URL.revokeObjectURL(removed.thumbnailUrl);
- return prev.filter((_, i) => i !== index);
- });
+ const prev = pendingFilesRef.current;
+ const removed = prev[index];
+ if (removed?.thumbnailUrl) URL.revokeObjectURL(removed.thumbnailUrl);
+ const next = prev.filter((_, i) => i !== index);
+ pendingFilesRef.current = next;
+ _setPendingFiles(next);
}, []);
const [dragging, setDragging] = useState(false);
@@ -149,6 +161,7 @@ export function useFileAttachments(opts: UseFileAttachmentsOptions = {}) {
pendingFiles,
setPendingFiles,
transferPendingFiles,
+ awaitPendingFiles,
fileInputRef,
addPendingFiles,
handleFileSelect,
diff --git a/src/web/src/lib/community/attachment-authorization.test.ts b/src/web/src/lib/community/attachment-authorization.test.ts
new file mode 100644
index 000000000..601bbfc77
--- /dev/null
+++ b/src/web/src/lib/community/attachment-authorization.test.ts
@@ -0,0 +1,55 @@
+import { beforeEach, describe, expect, it, vi } from "vitest"
+
+const getAttachmentById = vi.fn()
+const getMessage = vi.fn()
+const getChannelType = vi.fn()
+const requireChannelMember = vi.fn()
+const requireDMAccess = vi.fn()
+
+vi.mock("@alook/shared", () => ({
+ queries: {
+ communityAttachment: { getAttachmentById: (...args: unknown[]) => getAttachmentById(...args) },
+ communityMessage: { getMessage: (...args: unknown[]) => getMessage(...args) },
+ communityChannel: { getChannelType: (...args: unknown[]) => getChannelType(...args) },
+ },
+}))
+vi.mock("./permissions", () => ({
+ requireChannelMember: (...args: unknown[]) => requireChannelMember(...args),
+ requireDMAccess: (...args: unknown[]) => requireDMAccess(...args),
+}))
+
+import { authorizeAttachment } from "./attachment-authorization"
+
+const db = {} as any
+const actor = { kind: "human", userId: "u1", email: "[email protected]", isBot: false } as any
+const row = { id: "a1", messageId: "m1", uploaderId: "u2", targetId: "routing-only" }
+
+describe("authorizeAttachment", () => {
+ beforeEach(() => vi.clearAllMocks())
+
+ it("allows only the uploader for a pending row", async () => {
+ getAttachmentById.mockResolvedValue({ ...row, messageId: null, uploaderId: "u1" })
+ expect((await authorizeAttachment(actor, db, "a1")).ok).toBe(true)
+ getAttachmentById.mockResolvedValue({ ...row, messageId: null, uploaderId: "u2" })
+ expect((await authorizeAttachment(actor, db, "a1")).ok).toBe(false)
+ })
+
+ it("authorizes persisted channel rows from the message channel", async () => {
+ getAttachmentById.mockResolvedValue(row)
+ getMessage.mockResolvedValue({ id: "m1", channelId: "actual-channel" })
+ getChannelType.mockResolvedValue("text")
+ requireChannelMember.mockResolvedValue({ ok: true })
+ expect((await authorizeAttachment(actor, db, "a1")).ok).toBe(true)
+ expect(requireChannelMember).toHaveBeenCalledWith(db, "actual-channel", "u1")
+ })
+
+ it("uses the DM access gate for persisted DM rows", async () => {
+ getAttachmentById.mockResolvedValue(row)
+ getMessage.mockResolvedValue({ id: "m1", channelId: "dm1" })
+ getChannelType.mockResolvedValue("dm")
+ requireDMAccess.mockResolvedValue({ ok: false })
+ expect((await authorizeAttachment(actor, db, "a1")).ok).toBe(false)
+ expect(requireDMAccess).toHaveBeenCalledWith(db, "dm1", "u1")
+ expect(requireChannelMember).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/web/src/lib/community/attachment-authorization.ts b/src/web/src/lib/community/attachment-authorization.ts
new file mode 100644
index 000000000..abb41eb5e
--- /dev/null
+++ b/src/web/src/lib/community/attachment-authorization.ts
@@ -0,0 +1,31 @@
+import { queries, type Database } from "@alook/shared"
+import type { CommunityActor } from "@/lib/middleware/community-actor"
+import { requireChannelMember, requireDMAccess } from "./permissions"
+
+type AuthzOk = {
+ ok: true
+ row: NonNullable<Awaited<ReturnType<typeof queries.communityAttachment.getAttachmentById>>>
+}
+
+/** Authorize solely from the attachment row; route target ids are never trusted. */
+export async function authorizeAttachment(
+ actor: CommunityActor,
+ db: Database,
+ attachmentId: string,
+): Promise<AuthzOk | { ok: false }> {
+ const userId = actor.userId
+ const row = await queries.communityAttachment.getAttachmentById(db, attachmentId)
+ if (!row) return { ok: false }
+
+ if (row.messageId === null) {
+ return row.uploaderId === userId ? { ok: true, row } : { ok: false }
+ }
+
+ const message = await queries.communityMessage.getMessage(db, row.messageId)
+ if (!message) return { ok: false }
+ const channelType = await queries.communityChannel.getChannelType(db, message.channelId)
+ const gate = channelType === "dm"
+ ? await requireDMAccess(db, message.channelId, userId)
+ : await requireChannelMember(db, message.channelId, userId)
+ return gate.ok ? { ok: true, row } : { ok: false }
+}
diff --git a/src/web/src/lib/community/create-channels.test.ts b/src/web/src/lib/community/create-channels.test.ts
index 88f7f485d..36fe73eeb 100644
--- a/src/web/src/lib/community/create-channels.test.ts
+++ b/src/web/src/lib/community/create-channels.test.ts
@@ -183,7 +183,11 @@ describe("createMessageWithThread (phase2 forum≡thread — atomic-by-compensat
mockGetThreadChannelByParentMessage.mockResolvedValue({
id: "th_1", creatorId: "u1", createdAt: "t0", name: "Title",
})
- mockListMessageAttachments.mockResolvedValue([])
+ mockListMessageAttachments.mockResolvedValue([{
+ id: "att_1", targetId: "forum_1", filename: "photo.png",
+ contentType: "image/png", size: 10, width: 640, height: 480,
+ thumbnailR2Key: "original.thumbnail.jpg",
+ }])
const res = await createMessageWithThread({
db: {} as any,
@@ -199,6 +203,9 @@ describe("createMessageWithThread (phase2 forum≡thread — atomic-by-compensat
ok: true,
deduped: true,
thread: expect.objectContaining({ id: "th_1" }),
+ attachments: [expect.objectContaining({
+ thumbnailUrl: "/api/community/channels/forum_1/attachments/att_1/thumbnail",
+ })],
}))
expect(mockCreateCommunityMessage).toHaveBeenCalledTimes(1)
expect(mockCreateChannel).not.toHaveBeenCalled()
diff --git a/src/web/src/lib/community/create-channels.ts b/src/web/src/lib/community/create-channels.ts
index 91d150a46..1c9f2b055 100644
--- a/src/web/src/lib/community/create-channels.ts
+++ b/src/web/src/lib/community/create-channels.ts
@@ -19,7 +19,7 @@ import { requireServerMember, requireChannelMember } from "@/lib/community/permi
import { requireMessageBearingSurface } from "@/lib/community/channel-write-guard"
import { guardDmOpen } from "@/lib/community/dm-guard"
import { createCommunityMessage, type IncomingMessageBody } from "@/lib/community/message-handler"
-import { attachmentUrl } from "@/lib/community/storage"
+import { attachmentThumbnailUrl, attachmentUrl } from "@/lib/community/storage"
const log = createLogger({ service: "community-create-channels" })
@@ -340,8 +340,14 @@ export async function createMessageWithThread(params: {
// bound to the deduped reply (whole command previously succeeded).
const storedAttachments = await queries.communityAttachment.listMessageAttachments(db, messageId)
const toCreatedAttachment = (row: (typeof storedAttachments)[number]) => ({
- ...row,
+ id: row.id,
+ filename: row.filename,
url: attachmentUrl(row.targetId, row.id),
+ ...(row.thumbnailR2Key ? { thumbnailUrl: attachmentThumbnailUrl(row.targetId, row.id) } : {}),
+ contentType: row.contentType,
+ size: row.size,
+ width: row.width,
+ height: row.height,
})
return {
ok: true,
diff --git a/src/web/src/lib/community/enrich-messages.test.ts b/src/web/src/lib/community/enrich-messages.test.ts
new file mode 100644
index 000000000..74bbe7c16
--- /dev/null
+++ b/src/web/src/lib/community/enrich-messages.test.ts
@@ -0,0 +1,103 @@
+import { beforeEach, describe, expect, it, vi } from "vitest"
+
+const mocks = vi.hoisted(() => ({
+ listAttachments: vi.fn(),
+ listReactions: vi.fn(),
+ getReplies: vi.fn(),
+ listChildren: vi.fn(),
+ getLatestSeq: vi.fn(),
+}))
+
+vi.mock("@alook/shared", async () => {
+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")
+ return {
+ ...actual,
+ withD1Retry: (operation: () => unknown) => operation(),
+ queries: {
+ ...actual.queries,
+ communityAttachment: {
+ ...actual.queries.communityAttachment,
+ listByMessageIds: (...args: unknown[]) => mocks.listAttachments(...args),
+ },
+ communityReaction: {
+ ...actual.queries.communityReaction,
+ listReactionsByMessageIds: (...args: unknown[]) => mocks.listReactions(...args),
+ },
+ communityMessage: {
+ ...actual.queries.communityMessage,
+ getMessagesByIdsInScope: (...args: unknown[]) => mocks.getReplies(...args),
+ getLatestMessageSeq: (...args: unknown[]) => mocks.getLatestSeq(...args),
+ },
+ communityChannel: {
+ ...actual.queries.communityChannel,
+ listChildChannels: (...args: unknown[]) => mocks.listChildren(...args),
+ },
+ },
+ }
+})
+
+import { enrichMessages } from "./enrich-messages"
+
+describe("enrichMessages attachment projection", () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ mocks.listReactions.mockResolvedValue([])
+ mocks.listChildren.mockResolvedValue([])
+ mocks.getLatestSeq.mockResolvedValue(9)
+ })
+
+ it("projects a canonical thumbnail beside reply enrichment", async () => {
+ mocks.listAttachments.mockResolvedValue([{
+ id: "att_1",
+ messageId: "m1",
+ targetId: "c1",
+ filename: "photo.png",
+ r2Key: "private-original-key",
+ thumbnailR2Key: "private-thumbnail-key",
+ contentType: "image/png",
+ size: 100,
+ width: 640,
+ height: 480,
+ }])
+ mocks.getReplies.mockResolvedValue([{
+ id: "reply_1",
+ authorName: "Bob",
+ content: "original",
+ channelId: "c1",
+ }])
+
+ const result = await enrichMessages(
+ {} as never,
+ "u1",
+ { channelId: "c1" },
+ [{
+ id: "m1",
+ seq: 9,
+ authorId: "u1",
+ authorName: "Alice",
+ authorImage: null,
+ content: "reply",
+ type: "default",
+ mentionType: null,
+ replyToId: "reply_1",
+ embeds: null,
+ createdAt: "2026-08-13T00:00:00.000Z",
+ channelId: "c1",
+ }],
+ )
+
+ expect(result.messages).toEqual([
+ expect.objectContaining({
+ replyTo: { id: "reply_1", authorName: "Bob", text: "original" },
+ attachments: [{
+ kind: "image",
+ name: "photo.png",
+ url: "/api/community/channels/c1/attachments/att_1",
+ thumbnailUrl: "/api/community/channels/c1/attachments/att_1/thumbnail",
+ width: 640,
+ height: 480,
+ }],
+ }),
+ ])
+ })
+})
diff --git a/src/web/src/lib/community/message-handler.test.ts b/src/web/src/lib/community/message-handler.test.ts
index 029717a35..e56768f34 100644
--- a/src/web/src/lib/community/message-handler.test.ts
+++ b/src/web/src/lib/community/message-handler.test.ts
@@ -2,6 +2,7 @@ import { describe, it, expect, vi, beforeEach } from "vitest"
const mockCreateMessage = vi.fn()
const mockGetMessage = vi.fn()
+const mockGetMessageByAuthorAndNonce = vi.fn()
const mockGetMessageInScope = vi.fn()
const mockHardDeleteMessage = vi.fn()
const mockGetUserInternal = vi.fn()
@@ -33,6 +34,7 @@ vi.mock("@alook/shared", async () => {
communityMessage: {
createMessage: (...a: unknown[]) => mockCreateMessage(...a),
getMessage: (...a: unknown[]) => mockGetMessage(...a),
+ getMessageByAuthorAndNonce: (...a: unknown[]) => mockGetMessageByAuthorAndNonce(...a),
getMessageInScope: (...a: unknown[]) => mockGetMessageInScope(...a),
hardDeleteMessage: (...a: unknown[]) => mockHardDeleteMessage(...a),
},
@@ -88,6 +90,7 @@ vi.mock("../broadcast", () => ({
import {
createCommunityMessage,
+ getCommunityMessageReplay,
isDmTarget,
isThreadTarget,
isChannelTarget,
@@ -357,6 +360,7 @@ describe("createCommunityMessage — attachment width/height reach the live WS b
targetId: "c1",
filename: "photo.png",
r2Key: "channel/c1/uuid/photo.png",
+ thumbnailR2Key: "channel/c1/uuid/photo.png.thumbnail.jpg",
contentType: "image/png",
size: 1000,
width: 1920,
@@ -378,7 +382,11 @@ describe("createCommunityMessage — attachment width/height reach the live WS b
const [, event] = mockFanOutToChannel.mock.calls[0]!
expect(event).toMatchObject({ serverId: "srv_1" })
expect(event.message.attachments).toEqual([
- expect.objectContaining({ width: 1920, height: 1080 }),
+ expect.objectContaining({
+ width: 1920,
+ height: 1080,
+ thumbnailUrl: "/api/community/channels/c1/attachments/att_1/thumbnail",
+ }),
])
})
@@ -811,6 +819,70 @@ describe("createCommunityMessage — attachment reservation-first flow (agent pa
mockListByMessageIds.mockResolvedValue([])
})
+ const replayAttachment = {
+ id: "att_thumbnail",
+ messageId: "msg_replay",
+ targetId: "c1",
+ filename: "photo.png",
+ r2Key: "private-original-key",
+ thumbnailR2Key: "private-thumbnail-key",
+ contentType: "image/png",
+ size: 100,
+ width: 640,
+ height: 480,
+ position: 0,
+ }
+
+ it("hydrates thumbnail URLs for a same-nonce precheck replay", async () => {
+ mockGetMessageByAuthorAndNonce.mockResolvedValue(
+ messageRow({ id: "msg_replay", clientNonce: "nonce_replay" }),
+ )
+ mockListByMessageIds.mockResolvedValue([replayAttachment])
+
+ const replay = await getCommunityMessageReplay({
+ db: {} as never,
+ authorId: "author_1",
+ channelId: "c1",
+ clientNonce: "nonce_replay",
+ })
+
+ expect(replay?.attachments).toEqual([
+ expect.objectContaining({
+ id: "att_thumbnail",
+ url: "/api/community/channels/c1/attachments/att_thumbnail",
+ thumbnailUrl: "/api/community/channels/c1/attachments/att_thumbnail/thumbnail",
+ }),
+ ])
+ })
+
+ it("hydrates thumbnail URLs when an insert-race recovers the committed nonce", async () => {
+ mockGetMessageByAuthorAndNonce
+ .mockResolvedValueOnce(null)
+ .mockResolvedValueOnce(messageRow({ id: "msg_replay", clientNonce: "nonce_race" }))
+ mockCreateMessage.mockRejectedValue(
+ Object.assign(new Error("UNIQUE constraint failed"), {
+ code: "SQLITE_CONSTRAINT_UNIQUE",
+ }),
+ )
+ mockListByMessageIds.mockResolvedValue([replayAttachment])
+
+ const replay = await createCommunityMessage({
+ db: {} as never,
+ authorId: "author_1",
+ target: { kind: "channel", channelId: "c1", serverId: "srv_1" },
+ body: { content: "retry after unknown commit" },
+ clientNonce: "nonce_race",
+ })
+
+ expect(replay).toEqual(expect.objectContaining({
+ ok: true,
+ deduped: true,
+ attachments: [expect.objectContaining({
+ thumbnailUrl: "/api/community/channels/c1/attachments/att_thumbnail/thumbnail",
+ })],
+ }))
+ })
+
it("reservation-mismatch → unreserve partial, hard-delete the orphan message, generic 400", async () => {
mockCreateMessage.mockResolvedValue({ id: "msg_preminted" })
mockReserveAttachmentsForMessage.mockResolvedValue(["att_1"]) // only 1 of 2 reserved
@@ -999,6 +1071,7 @@ describe("createCommunityMessage — attachment reservation-first flow (agent pa
filename: "photo.png",
targetId: "c1",
r2Key: "channel/c1/uuid/photo.png",
+ thumbnailR2Key: "channel/c1/uuid/photo.png.thumbnail.jpg",
contentType: "image/png",
size: 100,
width: null,
@@ -1025,6 +1098,7 @@ describe("createCommunityMessage — attachment reservation-first flow (agent pa
// id-addressed render URL (attachments fold) — served by the canonical
// channels/{targetId}/attachments/{attachmentId} door.
url: "/api/community/channels/c1/attachments/att_1",
+ thumbnailUrl: "/api/community/channels/c1/attachments/att_1/thumbnail",
}),
])
expect(mockUnreserveAttachments).not.toHaveBeenCalled()
diff --git a/src/web/src/lib/community/message-handler.ts b/src/web/src/lib/community/message-handler.ts
index 7c6b15aab..c49ab85c1 100644
--- a/src/web/src/lib/community/message-handler.ts
+++ b/src/web/src/lib/community/message-handler.ts
@@ -17,7 +17,7 @@ import type { Database } from "@alook/shared"
import { broadcastToUserSafe, fanOutToChannel, resolveChannelRecipients } from "./fanout"
import { dispatchMessageNotify } from "./notify"
import { mapMessageForWs } from "./message-payload"
-import { attachmentUrl } from "./storage"
+import { attachmentThumbnailUrl, attachmentUrl } from "./storage"
const log = createLogger({ service: "community-message-handler" })
@@ -78,6 +78,7 @@ type CreatedAttachment = {
id: string
filename: string
url: string
+ thumbnailUrl?: string
contentType: string | null
size: number | null
width?: number | null
@@ -90,6 +91,7 @@ async function hydrateStoredAttachments(db: Database, messageId: string): Promis
id: row.id,
filename: row.filename,
url: attachmentUrl(row.targetId, row.id),
+ ...(row.thumbnailR2Key ? { thumbnailUrl: attachmentThumbnailUrl(row.targetId, row.id) } : {}),
contentType: row.contentType,
size: row.size,
width: row.width,
@@ -512,6 +514,7 @@ export async function createCommunityMessage(params: {
id: r.id,
filename: r.filename,
url: attachmentUrl(r.targetId, r.id),
+ ...(r.thumbnailR2Key ? { thumbnailUrl: attachmentThumbnailUrl(r.targetId, r.id) } : {}),
contentType: r.contentType,
size: r.size,
width: r.width,
@@ -712,6 +715,7 @@ export async function createCommunityMessage(params: {
id: a.id,
filename: a.filename,
url: a.url,
+ thumbnailUrl: a.thumbnailUrl,
contentType: a.contentType ?? undefined,
size: a.size ?? undefined,
width: a.width ?? undefined,
diff --git a/src/web/src/lib/community/message-payload.ts b/src/web/src/lib/community/message-payload.ts
index 8ec522233..7e31f10cb 100644
--- a/src/web/src/lib/community/message-payload.ts
+++ b/src/web/src/lib/community/message-payload.ts
@@ -44,8 +44,8 @@ export type MessageRow = {
type ReplyTargetRow = { id: string; authorName: string; content: string | null }
-type UiAttachment = { kind: "image" | "file"; name: string; url: string; size?: string; width?: number; height?: number }
-type WsAttachment = { id: string; filename: string; url: string; contentType?: string; size?: number; width?: number; height?: number }
+type UiAttachment = { kind: "image" | "file"; name: string; url: string; thumbnailUrl?: string; size?: string; width?: number; height?: number }
+type WsAttachment = { id: string; filename: string; url: string; thumbnailUrl?: string; contentType?: string; size?: number; width?: number; height?: number }
type UiReaction = { emoji: string; count: number; me: boolean; userIds: string[] }
type ReplyPreview = { id: string; authorName: string; text: string; deleted?: boolean }
@@ -180,6 +180,7 @@ export function mapMessageForWs(row: MessageRow, ctx: WsMessageContext) {
id: a.id,
filename: a.filename,
url: a.url,
+ thumbnailUrl: a.thumbnailUrl,
contentType: a.contentType,
size: a.size,
width: a.width,
diff --git a/src/web/src/lib/community/message-stream.test.ts b/src/web/src/lib/community/message-stream.test.ts
index c953d9dc2..343e0654c 100644
--- a/src/web/src/lib/community/message-stream.test.ts
+++ b/src/web/src/lib/community/message-stream.test.ts
@@ -448,9 +448,18 @@ describe("message stream monotonic visibility", () => {
describe("attachment ownership effects", () => {
const retryFile = { name: "notes.txt", size: 1024, type: "text/plain" } as File
+ const retryThumbnail = new Blob(["thumbnail"], { type: "image/jpeg" })
+ const settledAttachments: NonNullable<Msg["attachments"]> = [{
+ kind: "image",
+ name: "photo.png",
+ url: "/media/photo",
+ thumbnailUrl: "/media/photo/thumbnail",
+ width: 320,
+ height: 240,
+ }]
const attachedIntent = () => intent("files", 1, {
localUploads: [
- { file: retryFile, previewObjectUrl: "blob:a", width: 640, height: 480 },
+ { file: retryFile, thumbnailBlob: retryThumbnail, previewObjectUrl: "blob:a", width: 640, height: 480 },
{ file: { name: "photo.png", size: 2048, type: "image/png" } as File, previewObjectUrl: "blob:b", width: 320, height: 240 },
{ file: { name: "copy.txt", size: 1024, type: "text/plain" } as File, previewObjectUrl: "blob:a" },
],
@@ -468,6 +477,8 @@ describe("attachment ownership effects", () => {
const retried = state.outboxByNonce.get("files")
expect(retried?.localUploads[0].file).toBe(retryFile)
+ expect(retried?.localUploads[0].thumbnailBlob).toBe(retryThumbnail)
+ expect(getOutboxRetryPayload(state, "files")?.localUploads[0].thumbnailBlob).toBe(retryThumbnail)
expect(retried?.localUploads[0].previewObjectUrl).toBe("blob:a")
expect(retried?.localUploads[0].width).toBe(640)
expect(retried?.localUploads[0].height).toBe(480)
@@ -509,6 +520,103 @@ describe("attachment ownership effects", () => {
expect(ids([], replay.state)).toEqual(["mf"])
})
+ it.each([
+ ["POST ack then base", (state: MessageOverlayState) => {
+ const acked = apply(state, ack("files", "mf", 20))
+ return apply(acked.state, {
+ type: "baseChanged",
+ messages: [canonical("mf", 20, "files")],
+ }).state
+ }],
+ ["WS then base", (state: MessageOverlayState) => {
+ const ws = apply(state, {
+ type: "wsMessage",
+ message: canonical("mf", 20, "files", { attachments: settledAttachments }),
+ })
+ return apply(ws.state, {
+ type: "baseChanged",
+ messages: [canonical("mf", 20, "files")],
+ }).state
+ }],
+ ["base before POST ack", (state: MessageOverlayState) => {
+ const based = apply(state, {
+ type: "baseChanged",
+ messages: [canonical("mf", 20, "files")],
+ })
+ return apply(based.state, ack("files", "mf", 20)).state
+ }],
+ ])("preserves settled attachments through a lagging canonical %s", (_label, arrange) => {
+ let state = submit(emptyMessageOverlay(), attachedIntent())
+ state = apply(state, {
+ type: "uploadSettled",
+ nonce: "files",
+ attachments: settledAttachments,
+ }).state
+
+ const converged = arrange(state)
+ const laggingBase = canonical("mf", 20, "files")
+
+ expect(converged.outboxByNonce.size).toBe(0)
+ expect(converged.liveById.get("mf")?.attachments).toEqual(settledAttachments)
+ expect(materializeMessageStream([laggingBase], converged)[0]?.attachments).toEqual(
+ settledAttachments,
+ )
+ })
+
+ it("lets an explicit canonical empty attachment list replace prior attachments", () => {
+ let state = apply(emptyMessageOverlay(), {
+ type: "wsMessage",
+ message: canonical("mf", 20, "files", { attachments: settledAttachments }),
+ }).state
+
+ const emptyCanonical = canonical("mf", 20, "files", { attachments: [] })
+ state = apply(state, {
+ type: "baseChanged",
+ messages: [emptyCanonical],
+ }).state
+
+ expect(state.liveById.get("mf")?.attachments).toEqual([])
+ expect(materializeMessageStream([emptyCanonical], state)[0]?.attachments).toEqual([])
+ })
+
+ it("lets explicit canonical attachments replace prior attachments", () => {
+ const replacement: NonNullable<Msg["attachments"]> = [{
+ kind: "file",
+ name: "canonical.txt",
+ url: "/media/canonical",
+ size: "2 KB",
+ }]
+ let state = apply(emptyMessageOverlay(), {
+ type: "wsMessage",
+ message: canonical("mf", 20, "files", { attachments: settledAttachments }),
+ }).state
+
+ const replacementCanonical = canonical("mf", 20, "files", {
+ attachments: replacement,
+ })
+ state = apply(state, {
+ type: "baseChanged",
+ messages: [replacementCanonical],
+ }).state
+
+ expect(state.liveById.get("mf")?.attachments).toEqual(replacement)
+ expect(materializeMessageStream([replacementCanonical], state)[0]?.attachments).toEqual(
+ replacement,
+ )
+ })
+
+ it("preserves attachments when materialization reconciles a matching nonce under a new id", () => {
+ const state = apply(emptyMessageOverlay(), {
+ type: "wsMessage",
+ message: canonical("ws-id", 20, "files", { attachments: settledAttachments }),
+ }).state
+ const laggingBase = canonical("base-id", 20, "files")
+
+ expect(materializeMessageStream([laggingBase], state)).toEqual([
+ expect.objectContaining({ id: "base-id", attachments: settledAttachments }),
+ ])
+ })
+
it("revokes once when WS wins before ack, while postFail keeps previews owned", () => {
const submitted = submit(emptyMessageOverlay(), attachedIntent())
const failed = apply(submitted, { type: "postFail", nonce: "files" })
diff --git a/src/web/src/lib/community/message-stream.ts b/src/web/src/lib/community/message-stream.ts
index 3a7acae12..d888539a3 100644
--- a/src/web/src/lib/community/message-stream.ts
+++ b/src/web/src/lib/community/message-stream.ts
@@ -12,6 +12,7 @@ export type MessageScope =
type LocalUploadInput = Readonly<{
file: File
+ thumbnailBlob?: Blob
previewObjectUrl?: string
width?: number
height?: number
@@ -144,6 +145,16 @@ function upsertLiveCanonical(
liveById.set(message.id, { ...message, failed: false })
}
+function mergeCanonicalAttachments(
+ current: Pick<Msg, "attachments">,
+ canonical: CanonicalMessage,
+): CanonicalMessage {
+ if (canonical.attachments !== undefined || !current.attachments?.length) {
+ return canonical
+ }
+ return { ...canonical, attachments: current.attachments }
+}
+
function materializeIntent(intent: OutboxIntent): Msg {
return {
...intent.message,
@@ -195,6 +206,18 @@ function upsertMaterialized(
byId.set(message.id, entry)
}
+function findMaterializedMatch(
+ byId: ReadonlyMap<string, MaterializedEntry>,
+ idByIdentity: ReadonlyMap<string, string>,
+ message: Msg,
+): MaterializedEntry | undefined {
+ const exact = byId.get(message.id)
+ if (exact) return exact
+ const identity = compoundIdentity(message)
+ const matchedId = identity ? idByIdentity.get(identity) : undefined
+ return matchedId ? byId.get(matchedId) : undefined
+}
+
function materializedOrder(a: MaterializedEntry, b: MaterializedEntry): number {
const aSeq = a.message.seq
const bSeq = b.message.seq
@@ -220,8 +243,8 @@ export function materializeMessageStream(
const byId = new Map<string, MaterializedEntry>()
const idByIdentity = new Map<string, string>()
- // Later sources replace earlier presentation for the same id/nonce:
- // optimistic outbox < complete WS row < complete base row.
+ // Later sources replace earlier presentation for the same id/nonce. An
+ // omitted attachment projection cannot erase richer presentation state.
for (const intent of overlay.outboxByNonce.values()) {
upsertMaterialized(byId, idByIdentity, {
message: materializeIntent(intent),
@@ -232,7 +255,12 @@ export function materializeMessageStream(
upsertMaterialized(byId, idByIdentity, { message })
}
for (const message of baseMessages) {
- upsertMaterialized(byId, idByIdentity, { message })
+ const current = findMaterializedMatch(byId, idByIdentity, message)
+ upsertMaterialized(byId, idByIdentity, {
+ message: current
+ ? mergeCanonicalAttachments(current.message, message)
+ : message,
+ })
}
return [...byId.values()].sort(materializedOrder).map((entry) => entry.message)
@@ -436,7 +464,9 @@ export function reduceMessageOverlay(
const identity = compoundIdentity(message)
const canonical = baseById.get(message.id)
?? (identity ? baseByIdentity.get(identity) : undefined)
- if (canonical) upsertLiveCanonical(liveById, canonical)
+ if (canonical) {
+ upsertLiveCanonical(liveById, mergeCanonicalAttachments(message, canonical))
+ }
}
for (const [nonce, intent] of outboxByNonce) {
const canonicalById = intent.serverMessageId
@@ -453,7 +483,10 @@ export function reduceMessageOverlay(
: undefined
if (!canonical) continue
outboxByNonce.delete(nonce)
- upsertLiveCanonical(liveById, canonical)
+ upsertLiveCanonical(
+ liveById,
+ mergeCanonicalAttachments(intent.message, canonical),
+ )
effects.push(...revokeEffects(intent))
}
trimLiveDeltas(liveById)
diff --git a/src/web/src/lib/community/message-wire.ts b/src/web/src/lib/community/message-wire.ts
index f7e513f63..4672bc019 100644
--- a/src/web/src/lib/community/message-wire.ts
+++ b/src/web/src/lib/community/message-wire.ts
@@ -97,6 +97,7 @@ export function projectCommunityMessageCreate(
kind: "image" as const,
name: attachment.filename,
url: attachment.url,
+ ...(attachment.thumbnailUrl ? { thumbnailUrl: attachment.thumbnailUrl } : {}),
width: attachment.width ?? undefined,
height: attachment.height ?? undefined,
}
diff --git a/src/web/src/lib/community/messages.test.ts b/src/web/src/lib/community/messages.test.ts
index 7485eaed6..839ebb107 100644
--- a/src/web/src/lib/community/messages.test.ts
+++ b/src/web/src/lib/community/messages.test.ts
@@ -55,6 +55,18 @@ describe("buildSinceResponse", () => {
// optional on the output shape, so we assert on the actual returned object
// rather than relying on the declared type to catch a missing field.
describe("groupAttachments", () => {
+ it("projects a canonical thumbnail URL only when the row declares one", () => {
+ const result = groupAttachments([
+ { id: "att1", messageId: "m1", targetId: "c1", filename: "a.png", r2Key: "original", thumbnailR2Key: "thumb", contentType: "image/png", size: 1000 },
+ { id: "att2", messageId: "m2", targetId: "c1", filename: "legacy.png", r2Key: "legacy", thumbnailR2Key: null, contentType: "image/png", size: 1000 },
+ ])
+ expect(result.m1?.[0]).toMatchObject({
+ url: "/api/community/channels/c1/attachments/att1",
+ thumbnailUrl: "/api/community/channels/c1/attachments/att1/thumbnail",
+ })
+ expect(result.m2?.[0]).not.toHaveProperty("thumbnailUrl")
+ })
+
it("projects width/height onto an image-kind entry when present on the row", () => {
const result = groupAttachments([
{ id: "att1", messageId: "m1", targetId: "c1", filename: "a.png", r2Key: "channel/c1/uuid/a.png", contentType: "image/png", size: 1000, width: 1920, height: 1080 },
diff --git a/src/web/src/lib/community/messages.ts b/src/web/src/lib/community/messages.ts
index b8460d630..ebd73c6b0 100644
--- a/src/web/src/lib/community/messages.ts
+++ b/src/web/src/lib/community/messages.ts
@@ -1,6 +1,6 @@
import { DEFAULT_MESSAGE_PAGE_SIZE, MAX_MESSAGE_PAGE_SIZE } from "@alook/shared"
import { isInlineAttachmentContentType } from "./attachment-content-type"
-import { attachmentUrl } from "./storage"
+import { attachmentThumbnailUrl, attachmentUrl } from "./storage"
// Format file sizes for display
function formatBytes(bytes: number): string {
@@ -153,9 +153,9 @@ export function buildMemberPaginatedResponse<T extends { joinedAt: string; id: s
// with `messageId = null` (pending, not yet linked to a message) are skipped —
// the read paths never surface them.
export function groupAttachments(
- attachments: Array<{ id: string; messageId: string | null; targetId: string; filename: string; r2Key: string; contentType: string | null; size: number | null; width?: number | null; height?: number | null }>
-): Record<string, Array<{ kind: "image" | "file"; name: string; url: string; size?: string; width?: number; height?: number }>> {
- const map: Record<string, Array<{ kind: "image" | "file"; name: string; url: string; size?: string; width?: number; height?: number }>> = {}
+ attachments: Array<{ id: string; messageId: string | null; targetId: string; filename: string; r2Key: string; thumbnailR2Key?: string | null; contentType: string | null; size: number | null; width?: number | null; height?: number | null }>
+): Record<string, Array<{ kind: "image" | "file"; name: string; url: string; thumbnailUrl?: string; size?: string; width?: number; height?: number }>> {
+ const map: Record<string, Array<{ kind: "image" | "file"; name: string; url: string; thumbnailUrl?: string; size?: string; width?: number; height?: number }>> = {}
for (const a of attachments) {
if (!a.messageId) continue
const kind = isInlineAttachmentContentType(a.contentType) ? "image" : "file"
@@ -163,9 +163,12 @@ export function groupAttachments(
kind,
name: a.filename,
url: attachmentUrl(a.targetId, a.id),
+ ...(kind === "image" && a.thumbnailR2Key
+ ? { thumbnailUrl: attachmentThumbnailUrl(a.targetId, a.id) }
+ : {}),
...(kind === "file" && a.size ? { size: formatBytes(a.size) } : {}),
...(kind === "image" ? { width: a.width ?? undefined, height: a.height ?? undefined } : {}),
- } as { kind: "image" | "file"; name: string; url: string; size?: string; width?: number; height?: number }
+ } as { kind: "image" | "file"; name: string; url: string; thumbnailUrl?: string; size?: string; width?: number; height?: number }
;(map[a.messageId] ??= []).push(entry)
}
return map
diff --git a/src/web/src/lib/community/storage.test.ts b/src/web/src/lib/community/storage.test.ts
index a179694ab..948e6b4dc 100644
--- a/src/web/src/lib/community/storage.test.ts
+++ b/src/web/src/lib/community/storage.test.ts
@@ -4,6 +4,9 @@ import {
buildUserAvatarKey,
buildBotAvatarKey,
attachmentUrl,
+ attachmentThumbnailUrl,
+ buildAttachmentThumbnailKey,
+ ATTACHMENT_PRIVATE_IMMUTABLE_CACHE,
sanitizeAttachmentFilename,
userAvatarUrl,
botAvatarUrl,
@@ -88,3 +91,21 @@ describe("attachmentUrl", () => {
expect(attachmentUrl("c1", "att_1")).toBe("/api/community/channels/c1/attachments/att_1")
})
})
+
+describe("attachment thumbnail addressing", () => {
+ it("builds sibling canonical URLs", () => {
+ expect(attachmentThumbnailUrl("c1", "att_1")).toBe(
+ "/api/community/channels/c1/attachments/att_1/thumbnail",
+ )
+ })
+
+ it("uses a reserved suffix on the complete original key", () => {
+ expect(buildAttachmentThumbnailKey("channel/c1/id/thumbnail.jpg")).toBe(
+ "channel/c1/id/thumbnail.jpg.thumbnail.jpg",
+ )
+ })
+})
+
+it("uses a private immutable cache policy for authorized attachment bytes", () => {
+ expect(ATTACHMENT_PRIVATE_IMMUTABLE_CACHE).toBe("private, max-age=31536000, immutable")
+})
diff --git a/src/web/src/lib/community/storage.ts b/src/web/src/lib/community/storage.ts
index 12b0b3ffd..70d6e2bc1 100644
--- a/src/web/src/lib/community/storage.ts
+++ b/src/web/src/lib/community/storage.ts
@@ -1,3 +1,5 @@
+export const ATTACHMENT_PRIVATE_IMMUTABLE_CACHE = "private, max-age=31536000, immutable"
+
/**
* Sanitize a filename component that will be embedded into an R2 key. Strips
* `..`, replaces `/` and any C0 / DEL control character with `_`, and caps
@@ -29,6 +31,14 @@ export function attachmentUrl(targetId: string, attachmentId: string): string {
return `/api/community/channels/${targetId}/attachments/${attachmentId}`
}
+export function attachmentThumbnailUrl(targetId: string, attachmentId: string): string {
+ return `${attachmentUrl(targetId, attachmentId)}/thumbnail`
+}
+
+export function buildAttachmentThumbnailKey(originalKey: string): string {
+ return `${originalKey}.thumbnail.jpg`
+}
+
// R2 storage key builders
export function buildMediaKey(type: "channel" | "dm" | "thread", id: string, fileId: string, filename: string): string {
return `${type}/${id}/${fileId}/${sanitizeAttachmentFilename(filename)}`
diff --git a/src/web/src/lib/community/testids.ts b/src/web/src/lib/community/testids.ts
index 1b474d066..b66b2e725 100644
--- a/src/web/src/lib/community/testids.ts
+++ b/src/web/src/lib/community/testids.ts
@@ -27,8 +27,13 @@ export const tid = {
botAvatarPickerTrigger: "community-bot-avatar-picker-trigger",
forumTagDialog: "community-forum-tag-dialog",
+ imageLightbox: "community-image-lightbox",
+ imageLightboxThumbnail: "community-image-lightbox-thumbnail",
+ imageLightboxOriginal: "community-image-lightbox-original",
message: (id: string) => `community-message-${id}`,
+ messageImage: (id: string, index: number) => `community-message-image-${id}-${index}`,
+ threadOpenerImage: (index: number) => `community-thread-opener-image-${index}`,
channelRow: (id: string) => `community-channel-row-${id}`,
serverIcon: (id: string) => `community-server-icon-${id}`,
dmRow: (id: string) => `community-dm-row-${id}`,
diff --git a/src/web/src/lib/community/upload.test.ts b/src/web/src/lib/community/upload.test.ts
index 66d6f6bb3..6e79cad7c 100644
--- a/src/web/src/lib/community/upload.test.ts
+++ b/src/web/src/lib/community/upload.test.ts
@@ -16,10 +16,12 @@ vi.mock("@/lib/db", () => ({ getDb: (...a: unknown[]) => mockGetDb(...a) }))
const mockGetChannelType = vi.fn()
const mockCreatePendingAttachment = vi.fn()
+const mockLogError = vi.fn()
vi.mock("@alook/shared", async () => {
const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")
return {
...actual,
+ createLogger: () => ({ error: (...args: unknown[]) => mockLogError(...args) }),
queries: {
...actual.queries,
communityChannel: {
@@ -51,8 +53,8 @@ import {
} from "./upload"
import { MAX_ATTACHMENT_SIZE_BYTES, MAX_SERVER_ICON_SIZE_BYTES } from "@alook/shared"
-function envWithR2(put: ReturnType<typeof vi.fn>) {
- return { COMMUNITY_MEDIA: { put } } as unknown as Env
+function envWithR2(put: ReturnType<typeof vi.fn>, del = vi.fn().mockResolvedValue(undefined)) {
+ return { COMMUNITY_MEDIA: { put, delete: del } } as unknown as Env
}
/**
@@ -83,6 +85,15 @@ function reqWithFile(file: unknown | null): NextRequest {
return req
}
+function reqWithUpload(file: unknown, thumbnail: unknown, width = "640", height = "480"): NextRequest {
+ const req = new NextRequest("http://localhost/u", { method: "POST" })
+ req.formData = (async () => {
+ const values: Record<string, unknown> = { file, thumbnail, width, height }
+ return { get: (key: string) => values[key] ?? null } as unknown as FormData
+ }) as typeof req.formData
+ return req
+}
+
/**
* A File-shaped object with an overridable `size`. Real `File.size` is
* derived from the underlying byte length and ignores `Object.defineProperty`,
@@ -120,6 +131,88 @@ describe("handleAttachmentUpload", () => {
expect(options.customMetadata).toMatchObject({ uploader: "user" })
})
+ it("stores a validated JPEG thumbnail beside the original with matching provenance", async () => {
+ const put = vi.fn().mockResolvedValue(undefined)
+ const file = fakeFile("hi.png", "image/png", 10)
+ const thumbnail = {
+ ...fakeFile("thumbnail.jpg", "image/jpeg", 4),
+ arrayBuffer: async () => Uint8Array.from([0xff, 0xd8, 0xff, 0xd9]).buffer,
+ }
+ const res = await handleAttachmentUpload(
+ reqWithUpload(file, thumbnail), envWithR2(put), "channel", "c1", USER_TAG,
+ )
+ expect(res.ok).toBe(true)
+ if (!res.ok) return
+ expect(res.thumbnailR2Key).toBe(`${res.r2Key}.thumbnail.jpg`)
+ expect(res).toMatchObject({ width: 640, height: 480 })
+ expect(put).toHaveBeenCalledTimes(2)
+ expect(put.mock.calls[0]?.[2]?.customMetadata).toMatchObject({ variant: "original" })
+ expect(put.mock.calls[1]).toEqual([
+ res.thumbnailR2Key,
+ thumbnail,
+ expect.objectContaining({
+ httpMetadata: { contentType: "image/jpeg" },
+ customMetadata: expect.objectContaining({ uploader: "user", variant: "thumbnail" }),
+ }),
+ ])
+ })
+
+ it("rejects malformed supplied thumbnails before either R2 put", async () => {
+ const put = vi.fn()
+ const thumbnail = {
+ ...fakeFile("thumbnail.jpg", "image/jpeg", 4),
+ arrayBuffer: async () => Uint8Array.from([0, 1, 2, 3]).buffer,
+ }
+ const res = await handleAttachmentUpload(
+ reqWithUpload(fakeFile("hi.png", "image/png", 10), thumbnail),
+ envWithR2(put), "channel", "c1", USER_TAG,
+ )
+ expect(res.ok).toBe(false)
+ expect(put).not.toHaveBeenCalled()
+ })
+
+ it.each([
+ {
+ label: "non-raster original",
+ file: fakeFile("doc.pdf", "application/pdf", 10),
+ thumbnail: { ...fakeFile("thumbnail.jpg", "image/jpeg", 4), arrayBuffer: async () => Uint8Array.from([0xff, 0xd8, 0xff, 0xd9]).buffer },
+ },
+ {
+ label: "wrong thumbnail MIME",
+ file: fakeFile("photo.png", "image/png", 10),
+ thumbnail: { ...fakeFile("thumbnail.png", "image/png", 4), arrayBuffer: async () => Uint8Array.from([0xff, 0xd8, 0xff, 0xd9]).buffer },
+ },
+ {
+ label: "oversized thumbnail",
+ file: fakeFile("photo.png", "image/png", 10),
+ thumbnail: { ...fakeFile("thumbnail.jpg", "image/jpeg", 50 * 1024 + 1), arrayBuffer: async () => new ArrayBuffer(0) },
+ },
+ ])("rejects $label before either R2 put", async ({ file, thumbnail }) => {
+ const put = vi.fn()
+ const res = await handleAttachmentUpload(
+ reqWithUpload(file, thumbnail), envWithR2(put), "channel", "c1", USER_TAG,
+ )
+ expect(res.ok).toBe(false)
+ if (res.ok) return
+ expect(res.response.status).toBe(400)
+ expect(put).not.toHaveBeenCalled()
+ })
+
+ it("deletes the original when the thumbnail put fails", async () => {
+ const put = vi.fn().mockResolvedValueOnce(undefined).mockRejectedValueOnce(new Error("r2 thumbnail"))
+ const del = vi.fn().mockResolvedValue(undefined)
+ const thumbnail = {
+ ...fakeFile("thumbnail.jpg", "image/jpeg", 4),
+ arrayBuffer: async () => Uint8Array.from([0xff, 0xd8, 0xff, 0xd9]).buffer,
+ }
+ await expect(handleAttachmentUpload(
+ reqWithUpload(fakeFile("hi.png", "image/png", 10), thumbnail),
+ envWithR2(put, del), "channel", "c1", USER_TAG,
+ )).rejects.toThrow("r2 thumbnail")
+ expect(del).toHaveBeenCalledOnce()
+ expect(del.mock.calls[0]?.[0]).toMatch(/\/hi\.png$/)
+ })
+
it("stamps customMetadata.uploader=bot + bot_user_id when the caller is a bot", async () => {
const put = vi.fn().mockResolvedValue(undefined)
const file = fakeFile("hi.png", "image/png", 10)
@@ -129,7 +222,11 @@ describe("handleAttachmentUpload", () => {
})
expect(res.ok).toBe(true)
const [, , options] = put.mock.calls[0]
- expect(options.customMetadata).toEqual({ uploader: "bot", bot_user_id: "bot_ada" })
+ expect(options.customMetadata).toEqual({
+ uploader: "bot",
+ bot_user_id: "bot_ada",
+ variant: "original",
+ })
})
it("passes a known-length File body to R2", async () => {
@@ -544,4 +641,48 @@ describe("runAttachmentUpload", () => {
expect(res.status).toBe(413)
expect(put).not.toHaveBeenCalled()
})
+
+ it("deletes the original and thumbnail when the human pending-row insert fails", async () => {
+ surfaceChannel("text")
+ mockCreatePendingAttachment.mockRejectedValueOnce(new Error("d1"))
+ const put = vi.fn().mockResolvedValue(undefined)
+ const del = vi.fn().mockResolvedValue(undefined)
+ const thumbnail = {
+ ...fakeFile("thumbnail.jpg", "image/jpeg", 4),
+ arrayBuffer: async () => Uint8Array.from([0xff, 0xd8, 0xff, 0xd9]).buffer,
+ }
+ const response = await runAttachmentUpload(
+ reqWithUpload(fakeFile("hi.png", "image/png", 10), thumbnail),
+ ctxWith(envWithR2(put, del), { id: "c1" }),
+ )
+ expect(response.status).toBe(500)
+ expect(del).toHaveBeenCalledOnce()
+ const keys = del.mock.calls[0]?.[0] as string[]
+ expect(keys).toHaveLength(2)
+ expect(keys[1]).toBe(`${keys[0]}.thumbnail.jpg`)
+ })
+
+ it("redacts object keys when human compensation cleanup also fails", async () => {
+ surfaceChannel("text")
+ mockCreatePendingAttachment.mockRejectedValueOnce(new Error("d1"))
+ const put = vi.fn().mockResolvedValue(undefined)
+ const del = vi.fn().mockRejectedValueOnce(new Error("cleanup failed"))
+ const thumbnail = {
+ ...fakeFile("thumbnail.jpg", "image/jpeg", 4),
+ arrayBuffer: async () => Uint8Array.from([0xff, 0xd8, 0xff, 0xd9]).buffer,
+ }
+
+ const response = await runAttachmentUpload(
+ reqWithUpload(fakeFile("hi.png", "image/png", 10), thumbnail),
+ ctxWith(envWithR2(put, del), { id: "c1" }),
+ )
+
+ expect(response.status).toBe(500)
+ const keys = del.mock.calls[0]?.[0] as string[]
+ const cleanupLog = mockLogError.mock.calls.find(
+ ([event]) => event === "attachment_upload_r2_cleanup_failed",
+ )
+ expect(cleanupLog?.[1]).toEqual(expect.objectContaining({ objectCount: 2 }))
+ for (const key of keys) expect(JSON.stringify(cleanupLog)).not.toContain(key)
+ })
})
diff --git a/src/web/src/lib/community/upload.ts b/src/web/src/lib/community/upload.ts
index 31655f35b..dd8e8b312 100644
--- a/src/web/src/lib/community/upload.ts
+++ b/src/web/src/lib/community/upload.ts
@@ -1,6 +1,7 @@
import { NextRequest, NextResponse } from "next/server"
import {
MAX_ATTACHMENT_SIZE_BYTES,
+ MAX_ATTACHMENT_THUMBNAIL_SIZE_BYTES,
MAX_SERVER_ICON_SIZE_BYTES,
ALLOWED_ICON_MIME_TYPES,
queries,
@@ -12,8 +13,10 @@ import { requireMessageSurfaceAccess } from "./permissions"
import { writeError, writeJSON } from "@/lib/middleware/helpers"
import { getDb } from "@/lib/db"
import type { AuthContext } from "@/lib/middleware/auth"
+import { isInlineAttachmentContentType } from "./attachment-content-type"
import {
buildMediaKey,
+ buildAttachmentThumbnailKey,
buildServerIconKey,
buildUserAvatarKey,
buildBotAvatarKey,
@@ -46,6 +49,7 @@ export type UploadResult = UploadOk | UploadErr
type AttachmentUploadOk = {
ok: true
r2Key: string
+ thumbnailR2Key: string | null
filename: string
contentType: string
size: number
@@ -85,7 +89,18 @@ function mimeAllowed(contentType: string, allowed: readonly string[]): boolean {
* has none). This is the SINGLE source of an attachment's dimensions: they are
* written onto the pending row at upload time and never re-supplied on send.
*/
-type ParsedUpload = { file: File; width?: number; height?: number }
+type ParsedUpload = {
+ file: File
+ thumbnail?: File
+ width?: number
+ height?: number
+}
+
+function isFileLike(value: FormDataEntryValue | null): value is File {
+ return value !== null && typeof value !== "string" &&
+ typeof value.name === "string" && typeof value.type === "string" &&
+ typeof value.size === "number" && typeof value.arrayBuffer === "function"
+}
function parseDimension(raw: FormDataEntryValue | null): number | undefined {
if (typeof raw !== "string") return undefined
@@ -100,10 +115,15 @@ async function readFile(req: NextRequest): Promise<ParsedUpload | UploadErr> {
} catch {
return { ok: false, response: writeError("invalid form data", 400) }
}
- const file = formData.get("file") as File | null
- if (!file) return { ok: false, response: writeError("no file provided", 400) }
+ const file = formData.get("file")
+ if (!isFileLike(file)) return { ok: false, response: writeError("no file provided", 400) }
+ const thumbnailEntry = formData.get("thumbnail")
+ if (thumbnailEntry !== null && !isFileLike(thumbnailEntry)) {
+ return { ok: false, response: writeError("invalid thumbnail", 400) }
+ }
return {
file,
+ ...(isFileLike(thumbnailEntry) ? { thumbnail: thumbnailEntry } : {}),
width: parseDimension(formData.get("width")),
height: parseDimension(formData.get("height")),
}
@@ -132,7 +152,7 @@ export async function handleAttachmentUpload(
): Promise<AttachmentUploadResult> {
const parsed = await readFile(req)
if ("ok" in parsed && parsed.ok === false) return parsed
- const { file, width, height } = parsed as ParsedUpload
+ const { file, thumbnail, width, height } = parsed as ParsedUpload
if (file.size > MAX_ATTACHMENT_SIZE_BYTES) {
return {
@@ -145,20 +165,66 @@ export async function handleAttachmentUpload(
}
const contentType = file.type || "application/octet-stream"
+ if (thumbnail) {
+ if (!isInlineAttachmentContentType(contentType)) {
+ return { ok: false, response: writeError("thumbnail requires a supported raster image", 400) }
+ }
+ if (thumbnail.type !== "image/jpeg") {
+ return { ok: false, response: writeError("thumbnail must be image/jpeg", 400) }
+ }
+ if (thumbnail.size > MAX_ATTACHMENT_THUMBNAIL_SIZE_BYTES) {
+ return { ok: false, response: writeError("thumbnail too large", 400) }
+ }
+ const signature = new Uint8Array(await thumbnail.arrayBuffer())
+ if (
+ signature.length < 4 ||
+ signature[0] !== 0xff ||
+ signature[1] !== 0xd8 ||
+ signature.at(-2) !== 0xff ||
+ signature.at(-1) !== 0xd9
+ ) {
+ return { ok: false, response: writeError("invalid jpeg thumbnail", 400) }
+ }
+ }
+
const fileId = crypto.randomUUID()
const key = buildMediaKey(kind, targetId, fileId, file.name)
+ const customMetadata = {
+ uploader: uploaderTag.uploader,
+ bot_user_id: uploaderTag.uploader === "bot" ? uploaderTag.uploaderUserId : "",
+ }
+
await env.COMMUNITY_MEDIA.put(key, file, {
httpMetadata: { contentType },
- customMetadata: {
- uploader: uploaderTag.uploader,
- bot_user_id: uploaderTag.uploader === "bot" ? uploaderTag.uploaderUserId : "",
- },
+ customMetadata: { ...customMetadata, variant: "original" },
})
+ let thumbnailR2Key: string | null = null
+ if (thumbnail) {
+ thumbnailR2Key = buildAttachmentThumbnailKey(key)
+ try {
+ await env.COMMUNITY_MEDIA.put(thumbnailR2Key, thumbnail, {
+ httpMetadata: { contentType: "image/jpeg" },
+ customMetadata: { ...customMetadata, variant: "thumbnail" },
+ })
+ } catch (err) {
+ try {
+ await env.COMMUNITY_MEDIA.delete(key)
+ } catch (cleanupErr) {
+ log.error("attachment_thumbnail_put_cleanup_failed", {
+ uploader: uploaderTag.uploader,
+ cleanupErr: cleanupErr instanceof Error ? cleanupErr.message : String(cleanupErr),
+ })
+ }
+ throw err
+ }
+ }
+
return {
ok: true,
r2Key: key,
+ thumbnailR2Key,
filename: file.name,
contentType,
size: file.size,
@@ -335,14 +401,14 @@ export async function runAttachmentUpload(
// Track any R2 blob written before the D1 insert throws so the catch can
// best-effort delete it (mirrors the bot upload route's orphan-cleanup).
- let r2KeyToCleanUp: string | null = null
+ let r2KeysToCleanUp: string[] = []
try {
const result = await handleAttachmentUpload(req, ctx.env, kind, id, {
uploader: "user",
uploaderUserId: ctx.userId,
})
if (!result.ok) return result.response
- r2KeyToCleanUp = result.r2Key
+ r2KeysToCleanUp = [result.r2Key, ...(result.thumbnailR2Key ? [result.thumbnailR2Key] : [])]
// Reserve-by-id (route/disc step 2b): the human composer now mirrors the
// bot flow — the upload creates a PENDING row (messageId = NULL) and returns
@@ -357,6 +423,7 @@ export async function runAttachmentUpload(
uploaderId: ctx.userId,
targetId: id,
r2Key: result.r2Key,
+ thumbnailR2Key: result.thumbnailR2Key,
filename: result.filename,
contentType: result.contentType,
size: result.size,
@@ -369,18 +436,21 @@ export async function runAttachmentUpload(
filename: row.filename,
contentType: result.contentType,
size: result.size,
+ hasThumbnail: result.thumbnailR2Key !== null,
...(result.width !== undefined ? { width: result.width } : {}),
...(result.height !== undefined ? { height: result.height } : {}),
})
} catch (err) {
- if (r2KeyToCleanUp !== null) {
+ if (r2KeysToCleanUp.length > 0) {
try {
- await ctx.env.COMMUNITY_MEDIA.delete(r2KeyToCleanUp)
+ await ctx.env.COMMUNITY_MEDIA.delete(
+ r2KeysToCleanUp.length === 1 ? r2KeysToCleanUp[0]! : r2KeysToCleanUp,
+ )
} catch (cleanupErr) {
log.error("attachment_upload_r2_cleanup_failed", {
route: "channels/[id]/attachments",
userId: ctx.userId,
- r2Key: r2KeyToCleanUp,
+ objectCount: r2KeysToCleanUp.length,
cleanupErr: cleanupErr instanceof Error ? cleanupErr.message : String(cleanupErr),
})
}
diff --git a/src/web/src/stores/community/index.ts b/src/web/src/stores/community/index.ts
index 405b4b3bb..6ef776e58 100644
--- a/src/web/src/stores/community/index.ts
+++ b/src/web/src/stores/community/index.ts
@@ -72,7 +72,7 @@ type CommunitySubscription = {
}
type CommunityUiHandlers = {
- previewImage?: (url: string) => void
+ previewImage?: (image: import("@/components/community/_types").ImagePreview) => void
openProfile?: (name: string, e: React.MouseEvent, discriminator?: string, userId?: string) => void
goBackMobile?: () => void
// Jump to message `seq` within the CURRENT channel/DM — the page registers
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.ts
new file mode 100644
index 000000000..fc9a19fb6
--- /dev/null
+++ b/src/web/src/test/e2e-ui/20-community-attachment-thumbnails.spec.ts
@@ -0,0 +1,159 @@
+import { test, expect } from "./_fixtures/community-fixture"
+import { readFileSync } from "node:fs"
+import { tid } from "./_fixtures/testids"
+import { composerEditable, createServer } from "./_fixtures/actions"
+
+const PNG_FIXTURE = readFileSync("public/icon-192.png")
+
+test("image thumbnails defer original loading and survive original errors", async ({ asUser }) => {
+ test.setTimeout(120_000)
+ const { page } = await asUser("alice")
+ const browserErrors: string[] = []
+ page.on("pageerror", (error) => browserErrors.push(error.message))
+ page.on("console", (message) => {
+ if (message.type() === "error") browserErrors.push(message.text())
+ })
+ await page.goto("/c")
+ await page.waitForURL(/\/c/, { timeout: 20_000, waitUntil: "commit" })
+ await createServer(page, `Thumbnail E2E ${Date.now()}`)
+ const channelId = new URL(page.url()).pathname.split("/").at(-1)!
+ const observedGetPaths: string[] = []
+ let messagePostCount = 0
+ page.on("request", (request) => {
+ if (request.method() === "GET") observedGetPaths.push(new URL(request.url()).pathname)
+ if (
+ request.method() === "POST"
+ && new URL(request.url()).pathname === `/api/community/channels/${channelId}/messages`
+ ) messagePostCount++
+ })
+
+ const uploadResponsePromise = page.waitForResponse((response) => {
+ const pathname = new URL(response.url()).pathname
+ return response.request().method() === "POST"
+ && pathname === `/api/community/channels/${channelId}/attachments`
+ })
+ const messageResponsePromise = page.waitForResponse((response) => {
+ const pathname = new URL(response.url()).pathname
+ return response.request().method() === "POST"
+ && pathname === `/api/community/channels/${channelId}/messages`
+ })
+
+ const editable = composerEditable(page)
+ await editable.click()
+ await editable.pressSequentially("thumbnail network gate")
+ await page.locator('input[type="file"]').last().setInputFiles({
+ name: "pixel.png",
+ mimeType: "image/png",
+ buffer: PNG_FIXTURE,
+ })
+ await expect.poll(() => editable.evaluate((element) => document.activeElement === element)).toBe(true)
+ await page.keyboard.press("Enter")
+
+ const uploadResponse = await uploadResponsePromise
+ expect(uploadResponse.ok()).toBe(true)
+ const uploaded = await uploadResponse.json() as { id: string; hasThumbnail?: boolean }
+ // This is server-authoritative proof that the browser multipart contained a
+ // valid JPEG thumbnail and that both objects were persisted.
+ expect(uploaded.hasThumbnail).toBe(true)
+
+ const originalPath = `/api/community/channels/${channelId}/attachments/${uploaded.id}`
+ const thumbnailPath = `${originalPath}/thumbnail`
+ const messageResponse = await messageResponsePromise
+ expect(messageResponse.status()).toBe(201)
+ expect((messageResponse.request().postDataJSON() as { attachments?: string[] }).attachments).toEqual([uploaded.id])
+ expect(messagePostCount).toBe(1)
+ const sent = await messageResponse.json() as { message: { id: string } }
+ const listImage = page.getByTestId(tid.messageImage(sent.message.id, 0))
+ await expect(listImage).toHaveAttribute("src", thumbnailPath)
+ await expect.poll(() => observedGetPaths.filter((path) => path === thumbnailPath).length).toBeGreaterThan(0)
+ expect(observedGetPaths.filter((path) => path === originalPath)).toHaveLength(0)
+
+ let releaseOriginal!: () => void
+ const originalGate = new Promise<void>((resolve) => { releaseOriginal = resolve })
+ await page.route(`**${originalPath}`, async (route) => {
+ if (
+ route.request().method() === "GET"
+ && new URL(route.request().url()).pathname === originalPath
+ ) {
+ await originalGate
+ }
+ await route.continue()
+ })
+
+ const listImageButton = page.getByRole("button", { name: "pixel.png" })
+ // Message action controls lazy-activate on pointer entry. Let that stable
+ // render settle before the click, matching a real pointer's hover→press.
+ await listImageButton.hover()
+ await listImageButton.click()
+ await page.waitForTimeout(500)
+ if (await page.getByTestId(tid.imageLightbox).count() === 0 && browserErrors.length > 0) {
+ throw new Error(`lightbox render errors: ${browserErrors.join(" | ")}`)
+ }
+ await expect(page.getByTestId(tid.imageLightbox)).toBeVisible()
+ await expect(page.getByTestId(tid.imageLightboxThumbnail)).toHaveAttribute("src", thumbnailPath)
+ await expect(page.getByTestId(tid.imageLightboxOriginal)).toHaveClass(/invisible/)
+ await expect.poll(() => observedGetPaths.filter((path) => path === originalPath).length).toBe(1)
+
+ releaseOriginal()
+ await expect(page.getByTestId(tid.imageLightboxOriginal)).toHaveAttribute("src", originalPath)
+ await expect(page.getByTestId(tid.imageLightboxOriginal)).not.toHaveClass(/invisible/)
+ await page.keyboard.press("Escape")
+ await expect(page.getByTestId(tid.imageLightbox)).toHaveCount(0)
+
+ const errorUploadResponsePromise = page.waitForResponse((response) =>
+ response.request().method() === "POST"
+ && new URL(response.url()).pathname === `/api/community/channels/${channelId}/attachments`,
+ )
+ const errorMessageResponsePromise = page.waitForResponse((response) =>
+ response.request().method() === "POST"
+ && new URL(response.url()).pathname === `/api/community/channels/${channelId}/messages`,
+ )
+
+ await editable.click()
+ await editable.pressSequentially("original error gate")
+ await page.locator('input[type="file"]').last().setInputFiles({
+ name: "broken.png",
+ mimeType: "image/png",
+ buffer: PNG_FIXTURE,
+ })
+ await expect.poll(() => editable.evaluate((element) => document.activeElement === element)).toBe(true)
+ await page.keyboard.press("Enter")
+
+ const errorUploaded = await (await errorUploadResponsePromise).json() as {
+ id: string
+ hasThumbnail?: boolean
+ }
+ expect(errorUploaded.hasThumbnail).toBe(true)
+ const errorMessageResponse = await errorMessageResponsePromise
+ expect(errorMessageResponse.status()).toBe(201)
+ const errorSent = await errorMessageResponse.json() as { message: { id: string } }
+ const errorOriginalPath = `/api/community/channels/${channelId}/attachments/${errorUploaded.id}`
+ const errorThumbnailPath = `${errorOriginalPath}/thumbnail`
+ const originalRequests: string[] = []
+ page.on("request", (request) => {
+ if (request.method() === "GET" && new URL(request.url()).pathname === errorOriginalPath) {
+ originalRequests.push(request.url())
+ }
+ })
+ const errorListImage = page.getByTestId(tid.messageImage(errorSent.message.id, 0))
+ await expect(errorListImage).toHaveAttribute("src", errorThumbnailPath)
+ expect(originalRequests).toHaveLength(0)
+ await page.route(`**${errorOriginalPath}`, async (route) => {
+ if (route.request().method() === "GET" && new URL(route.request().url()).pathname === errorOriginalPath) {
+ await route.fulfill({ status: 500, contentType: "text/plain", body: "forced original failure" })
+ return
+ }
+ await route.continue()
+ })
+
+ const errorListImageButton = page.getByRole("button", { name: "broken.png" })
+ await errorListImageButton.hover()
+ await errorListImageButton.click()
+ await expect.poll(() => originalRequests.length).toBe(1)
+ await expect(page.getByTestId(tid.imageLightboxThumbnail)).toHaveAttribute("src", errorThumbnailPath)
+ await expect(page.getByTestId(tid.imageLightboxThumbnail)).toBeVisible()
+ await expect(page.getByTestId(tid.imageLightboxOriginal)).toHaveCount(0)
+ await page.waitForTimeout(500)
+ expect(originalRequests).toHaveLength(1)
+ await expect(errorListImage).toHaveAttribute("src", errorThumbnailPath)
+})
diff --git a/src/web/src/test/e2e-ui/_fixtures/actions.ts b/src/web/src/test/e2e-ui/_fixtures/actions.ts
index 8bca8c124..951ea13a3 100644
--- a/src/web/src/test/e2e-ui/_fixtures/actions.ts
+++ b/src/web/src/test/e2e-ui/_fixtures/actions.ts
@@ -46,8 +46,9 @@ export async function gotoAfterUserWsAuth(page: Page, url: string): Promise<void
// correct, non-flaky signal.
// Create a server through the rail. `openViaAddButton` clicks the "+" (the
-// empty-list auto-dialog covers the first-server case separately). Waits for
-// the URL to settle on a channel of the new server, then returns its id.
+// empty-list auto-dialog covers the first-server case separately). The product
+// first navigates to the server root; if its default-channel redirect lags,
+// select the rendered default channel explicitly before returning.
export async function createServer(page: Page, name: string, opts?: { autoDialog?: boolean }): Promise<string> {
if (!opts?.autoDialog) {
await page.getByTestId(tid.serverAdd).click()
@@ -55,11 +56,22 @@ export async function createServer(page: Page, name: string, opts?: { autoDialog
await page.getByLabel("Server name").fill(name)
await page.getByTestId(tid.createServerSubmit).click()
- // Land on the new server's default channel.
- await page.waitForURL(/\/c\/channels\/[^/]+\/[^/]+/, { timeout: 45_000, waitUntil: "commit" })
- const m = page.url().match(/\/c\/channels\/([^/]+)\//)
+ await page.waitForURL(/\/c\/channels\/[^/]+(?:\/[^/]+)?$/, {
+ timeout: 45_000,
+ waitUntil: "commit",
+ })
+ const m = page.url().match(/\/c\/channels\/([^/]+)/)
if (!m) throw new Error(`createServer: no serverId in URL ${page.url()}`)
- return m[1]
+ const serverId = m[1]
+ if (new URL(page.url()).pathname === `/c/channels/${serverId}`) {
+ const channelRowPrefix = tid.channelRow("")
+ await page.locator(`[data-testid^="${channelRowPrefix}"]`).first().click()
+ await page.waitForURL(new RegExp(`/c/channels/${serverId}/[^/]+$`), {
+ timeout: 45_000,
+ waitUntil: "commit",
+ })
+ }
+ return serverId
}
// Create a channel inside the named category via its "+" button. Returns the