Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(web): preserve composer attachment drafts (#623)

Gustavo Yee33ce4db76e7
diff --git a/scripts/ci/e2e-shards.test.ts b/scripts/ci/e2e-shards.test.ts
index f0d06529d..f3897db88 100644
--- a/scripts/ci/e2e-shards.test.ts
+++ b/scripts/ci/e2e-shards.test.ts
@@ -70,7 +70,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([380, 382, 383, 385, 385])
+ expect(totals.sort((left, right) => left - right)).toEqual([394, 395, 395, 395, 396])
expect(Math.max(...totals) / Math.min(...totals)).toBeLessThanOrEqual(1.15)
})
diff --git a/src/web/src/components/community/messages/composer.send-lifecycle.test.ts b/src/web/src/components/community/messages/composer.send-lifecycle.test.ts
index 69ae91bcc..12b81d7ed 100644
--- a/src/web/src/components/community/messages/composer.send-lifecycle.test.ts
+++ b/src/web/src/components/community/messages/composer.send-lifecycle.test.ts
@@ -93,6 +93,7 @@ describe("Composer committed send lifecycle", () => {
pendingFiles,
setPendingFiles: vi.fn(),
transferPendingFiles,
+ restorePendingFiles: vi.fn(),
awaitPendingFiles,
addPendingFiles: vi.fn(),
fileInputRef: { current: null },
diff --git a/src/web/src/components/community/messages/use-composer-controller.test.ts b/src/web/src/components/community/messages/use-composer-controller.test.ts
index 7b91d7c18..2871eda6c 100644
--- a/src/web/src/components/community/messages/use-composer-controller.test.ts
+++ b/src/web/src/components/community/messages/use-composer-controller.test.ts
@@ -12,6 +12,14 @@ const mocks = vi.hoisted(() => ({
writeDraft: vi.fn(),
detectMentionType: vi.fn(),
addPendingFiles: vi.fn(),
+ restorePendingFiles: vi.fn(),
+ appendAttachmentSession: vi.fn(),
+ clearAttachmentSession: vi.fn(),
+ readAttachmentSession: vi.fn(),
+ removeAttachmentFiles: vi.fn(),
+ transferAttachmentSession: vi.fn(),
+ toastInfo: vi.fn(),
+ toastError: vi.fn(),
starterConfigure: vi.fn(),
placeholderConfigure: vi.fn(),
buildPasteDom: vi.fn(),
@@ -50,6 +58,19 @@ vi.mock("@/lib/community/composer-draft", () => ({
readComposerDraft: (...args: unknown[]) => mocks.readDraft(...args),
writeComposerDraft: (...args: unknown[]) => mocks.writeDraft(...args),
}))
+vi.mock("@/lib/community/composer-attachment-session", () => ({
+ appendComposerAttachmentSession: (...args: unknown[]) => mocks.appendAttachmentSession(...args),
+ clearComposerAttachmentSession: (...args: unknown[]) => mocks.clearAttachmentSession(...args),
+ readComposerAttachmentSession: (...args: unknown[]) => mocks.readAttachmentSession(...args),
+ removeComposerAttachmentSessionFiles: (...args: unknown[]) => mocks.removeAttachmentFiles(...args),
+ transferComposerAttachmentSession: (...args: unknown[]) => mocks.transferAttachmentSession(...args),
+}))
+vi.mock("sonner", () => ({
+ toast: {
+ info: (...args: unknown[]) => mocks.toastInfo(...args),
+ error: (...args: unknown[]) => mocks.toastError(...args),
+ },
+}))
vi.mock("@/lib/community/mention-extension", () => ({
detectMentionType: (...args: unknown[]) => mocks.detectMentionType(...args),
}))
@@ -181,6 +202,7 @@ describe("useComposerController", () => {
pendingFiles,
setPendingFiles,
transferPendingFiles,
+ restorePendingFiles: mocks.restorePendingFiles,
awaitPendingFiles,
addPendingFiles: mocks.addPendingFiles,
fileInputRef: { current: { click: filePickerClick } },
@@ -205,6 +227,9 @@ describe("useComposerController", () => {
}))
mocks.detectMentionType.mockReturnValue("everyone")
mocks.readDraft.mockReturnValue(null)
+ mocks.readAttachmentSession.mockReturnValue([])
+ mocks.appendAttachmentSession.mockReturnValue({ accepted: true, evictedScopes: 0 })
+ mocks.restorePendingFiles.mockResolvedValue(undefined)
mocks.breakpoint = "desktop"
})
@@ -246,10 +271,12 @@ describe("useComposerController", () => {
TestRenderer.create(createElement(Harness, acceptedProps(vi.fn(() => true))))
})
- expect(mocks.useFileAttachments).toHaveBeenCalledWith({
+ expect(mocks.useFileAttachments).toHaveBeenCalledWith(expect.objectContaining({
maxFileSize: 25 * 1024 * 1024,
+ maxFiles: 10,
thumbnailPolicy: "community",
- })
+ draftSessionScope: "server/channel",
+ }))
})
it("forwards the optional channel source into suggestions and its presentation into the view", async () => {
@@ -499,6 +526,29 @@ describe("useComposerController", () => {
expect(afterResetFile.name).toBe("copy-1.md")
})
+ it("passes the canonical channel and DM draft scopes into the attachment hook", async () => {
+ let renderer!: TestRenderer.ReactTestRenderer
+ const accept = vi.fn(() => true)
+ await act(async () => {
+ renderer = TestRenderer.create(createElement(Harness, acceptedProps(accept)))
+ })
+ expect(mocks.useFileAttachments).toHaveBeenLastCalledWith(expect.objectContaining({
+ draftSessionScope: "server/channel",
+ }))
+
+ await act(async () => {
+ renderer.update(createElement(Harness, {
+ ...acceptedProps(accept),
+ channel: "person",
+ context: "dm",
+ draftKey: "dm/person",
+ }))
+ })
+ expect(mocks.useFileAttachments).toHaveBeenLastCalledWith(expect.objectContaining({
+ draftSessionScope: "dm/person",
+ }))
+ })
+
it("skips long-paste names already used by pending files", async () => {
const props = acceptedProps(() => true)
let renderer!: TestRenderer.ReactTestRenderer
diff --git a/src/web/src/components/community/messages/use-composer-controller.ts b/src/web/src/components/community/messages/use-composer-controller.ts
index 90358a8cf..3f9154a4d 100644
--- a/src/web/src/components/community/messages/use-composer-controller.ts
+++ b/src/web/src/components/community/messages/use-composer-controller.ts
@@ -12,7 +12,7 @@ import { useEditor, type JSONContent } from "@tiptap/react"
import StarterKit from "@tiptap/starter-kit"
import Placeholder from "@tiptap/extension-placeholder"
import { DOMParser as PMDOMParser } from "@tiptap/pm/model"
-import { MAX_ATTACHMENT_SIZE_BYTES } from "@alook/shared"
+import { MAX_ATTACHMENTS_PER_MESSAGE, MAX_ATTACHMENT_SIZE_BYTES } from "@alook/shared"
import { useFileAttachments } from "@/hooks/use-file-attachments"
import { useBreakpoint } from "@/hooks/use-mobile"
import {
@@ -66,7 +66,9 @@ export function useComposerController(
useLayoutEffect(() => {
breakpointRef.current = breakpoint
}, [breakpoint])
- const attachments = useFileAttachments({ maxFileSize: MAX_ATTACHMENT_SIZE_BYTES, thumbnailPolicy: "community" })
+ const attachments = useFileAttachments({ maxFileSize: MAX_ATTACHMENT_SIZE_BYTES,
+ maxFiles: MAX_ATTACHMENTS_PER_MESSAGE, thumbnailPolicy: "community",
+ draftSessionScope: isForumThreadBody ? undefined : draftKey })
const {
pendingFiles,
setPendingFiles,
diff --git a/src/web/src/hooks/use-file-attachments.test.ts b/src/web/src/hooks/use-file-attachments.test.ts
index 0a478004d..07caae8dd 100644
--- a/src/web/src/hooks/use-file-attachments.test.ts
+++ b/src/web/src/hooks/use-file-attachments.test.ts
@@ -2,6 +2,10 @@ import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"
import React from "react"
import TestRenderer, { act } from "react-test-renderer"
import { useFileAttachments, type PendingFile } from "./use-file-attachments"
+import {
+ readComposerAttachmentSession,
+ resetComposerAttachmentSessionsForTest,
+} from "../lib/community/composer-attachment-session"
// `generateThumbnail` runs entirely against browser APIs unavailable under
// this repo's `environment: "node"` vitest config — mocked at the module
@@ -21,6 +25,7 @@ beforeEach(() => {
generateThumbnailMock.mockReset()
prepareCommunityImageMock.mockReset()
toastErrorMock.mockReset()
+ resetComposerAttachmentSessionsForTest()
vi.stubGlobal("URL", { createObjectURL: vi.fn(() => "blob:fake"), revokeObjectURL: vi.fn() })
})
@@ -45,8 +50,9 @@ function Capture({
async function renderCapture(options?: Parameters<typeof useFileAttachments>[0]) {
let latest!: ReturnType<typeof useFileAttachments>
+ let renderer!: TestRenderer.ReactTestRenderer
await act(async () => {
- TestRenderer.create(
+ renderer = TestRenderer.create(
React.createElement(Capture, { onResult: (r) => { latest = r }, options }),
)
})
@@ -59,6 +65,16 @@ async function renderCapture(options?: Parameters<typeof useFileAttachments>[0])
await latest.addPendingFiles(files)
})
},
+ async rerender(nextOptions?: Parameters<typeof useFileAttachments>[0]) {
+ await act(async () => {
+ renderer.update(
+ React.createElement(Capture, { onResult: (r) => { latest = r }, options: nextOptions }),
+ )
+ })
+ },
+ unmount() {
+ act(() => renderer.unmount())
+ },
}
}
@@ -91,9 +107,12 @@ describe("useFileAttachments — PendingFile width/height", () => {
it("transfers accepted files without revoking their preview URLs", async () => {
generateThumbnailMock.mockResolvedValue({ blob: { size: 1 } as Blob, width: 640, height: 480 })
- const hook = await renderCapture()
+ const hook = await renderCapture({ draftSessionScope: "server/channel" })
const file = new File([new Uint8Array([1])], "photo.png", { type: "image/png" })
await hook.addFiles([file])
+ expect(readComposerAttachmentSession("server/channel")).toEqual([
+ { draftId: expect.stringMatching(/.+/), file },
+ ])
let transferred: PendingFile[] = []
await act(async () => {
@@ -104,6 +123,7 @@ describe("useFileAttachments — PendingFile width/height", () => {
expect.objectContaining({ file, thumbnailUrl: "blob:fake", width: 640, height: 480 }),
])
expect(hook.current.pendingFiles).toEqual([])
+ expect(readComposerAttachmentSession("server/channel")).toEqual([])
expect(URL.revokeObjectURL).not.toHaveBeenCalled()
})
@@ -169,12 +189,159 @@ describe("useFileAttachments — PendingFile width/height", () => {
it("rejects a Community image when a required preview cannot be prepared", async () => {
prepareCommunityImageMock.mockRejectedValue(new Error("required image preview"))
- const hook = await renderCapture({ thumbnailPolicy: "community" })
+ const hook = await renderCapture({
+ thumbnailPolicy: "community",
+ draftSessionScope: "server/channel",
+ })
const file = new File([new Uint8Array(1)], "photo.png", { type: "image/png" })
await hook.addFiles([file])
expect(hook.current.pendingFiles).toEqual([])
expect(toastErrorMock).toHaveBeenCalledWith('Could not prepare "photo.png" for upload')
+ expect(readComposerAttachmentSession("server/channel")).toEqual([])
+ })
+
+ it("registers raw Community Files synchronously before async image preparation", async () => {
+ let release!: (value: null) => void
+ prepareCommunityImageMock.mockReturnValue(new Promise((resolve) => { release = resolve }))
+ const hook = await renderCapture({
+ thumbnailPolicy: "community",
+ draftSessionScope: "server/channel",
+ })
+ const file = new File(["image"], "fast-switch.png", { type: "image/png" })
+
+ let pending!: Promise<void>
+ act(() => {
+ pending = hook.current.addPendingFiles([file])
+ })
+ expect(readComposerAttachmentSession("server/channel")).toEqual([
+ { draftId: expect.stringMatching(/.+/), file },
+ ])
+ expect(hook.current.pendingFiles).toEqual([])
+
+ await act(async () => {
+ release(null)
+ await pending
+ })
+ expect(hook.current.pendingFiles).toEqual([
+ expect.objectContaining({ file, draftId: expect.stringMatching(/.+/) }),
+ ])
+ })
+
+ it("restores by stable ID, rebuilds image URLs, and revokes only mounted previews", async () => {
+ prepareCommunityImageMock.mockResolvedValue({ blob: null, width: 10, height: 20 })
+ vi.mocked(URL.createObjectURL)
+ .mockReturnValueOnce("blob:first")
+ .mockReturnValueOnce("blob:restored")
+ const hook = await renderCapture({ thumbnailPolicy: "community" })
+ const file = new File(["image"], "restore.png", { type: "image/png" })
+ await hook.addFiles([file])
+ const draftId = hook.current.pendingFiles[0].draftId!
+
+ await act(async () => {
+ await hook.current.restorePendingFiles([{ draftId, file }])
+ })
+
+ expect(URL.revokeObjectURL).toHaveBeenCalledWith("blob:first")
+ expect(hook.current.pendingFiles).toEqual([
+ expect.objectContaining({ draftId, file, thumbnailUrl: "blob:restored" }),
+ ])
+ hook.unmount()
+ expect(URL.revokeObjectURL).toHaveBeenCalledWith("blob:restored")
+ })
+
+ it("keeps selected files added while restoration is queued and never duplicates IDs", async () => {
+ let releaseRestore!: (value: null) => void
+ prepareCommunityImageMock
+ .mockReturnValueOnce(new Promise((resolve) => { releaseRestore = resolve }))
+ .mockResolvedValueOnce(null)
+ const hook = await renderCapture({
+ thumbnailPolicy: "community",
+ draftSessionScope: "server/channel",
+ })
+ const restored = new File(["old"], "old.txt", { type: "text/plain" })
+ const selected = new File(["new"], "new.txt", { type: "text/plain" })
+
+ let restore!: Promise<void>
+ let add!: Promise<void>
+ act(() => {
+ restore = hook.current.restorePendingFiles([{ draftId: "old-id", file: restored }])
+ add = hook.current.addPendingFiles([selected])
+ })
+ expect(readComposerAttachmentSession("server/channel")).toEqual([
+ { draftId: expect.stringMatching(/.+/), file: selected },
+ ])
+ await act(async () => {
+ releaseRestore(null)
+ await Promise.all([restore, add])
+ })
+ expect(hook.current.pendingFiles.map(({ file }) => file)).toEqual([restored, selected])
+ expect(new Set(hook.current.pendingFiles.map(({ draftId }) => draftId)).size).toBe(2)
+ })
+
+ it("keeps the current reservation when a stale A→B→A preparation resolves for the same ID", async () => {
+ let releaseStale!: (value: null) => void
+ let releaseCurrent!: (value: null) => void
+ prepareCommunityImageMock
+ .mockReturnValueOnce(new Promise((resolve) => { releaseStale = resolve }))
+ .mockReturnValueOnce(new Promise((resolve) => { releaseCurrent = resolve }))
+ .mockResolvedValue(null)
+ const options = {
+ thumbnailPolicy: "community" as const,
+ draftSessionScope: "scope-a",
+ maxFiles: 10,
+ }
+ const hook = await renderCapture(options)
+ const restored = new File(["old"], "old.txt", { type: "text/plain" })
+
+ let stalePreparation!: Promise<void>
+ act(() => {
+ stalePreparation = hook.current.addPendingFiles([restored])
+ })
+ const [{ draftId }] = readComposerAttachmentSession("scope-a")
+
+ await hook.rerender({ ...options, draftSessionScope: "scope-b" })
+ await hook.rerender(options)
+ expect(readComposerAttachmentSession("scope-a")).toEqual([{ draftId, file: restored }])
+
+ await act(async () => {
+ releaseStale(null)
+ await stalePreparation
+ await Promise.resolve()
+ })
+ expect(prepareCommunityImageMock).toHaveBeenCalledTimes(2)
+
+ const tenFiles = Array.from({ length: 10 }, (_, index) =>
+ new File([String(index)], `${index}.txt`, { type: "text/plain" }))
+ let addTen!: Promise<void>
+ act(() => {
+ addTen = hook.current.addPendingFiles(tenFiles)
+ })
+ expect(readComposerAttachmentSession("scope-a")).toEqual([{ draftId, file: restored }])
+ expect(toastErrorMock).toHaveBeenCalledWith("You can attach up to 10 files")
+
+ await act(async () => {
+ releaseCurrent(null)
+ await addTen
+ })
+ expect(hook.current.pendingFiles).toEqual([
+ expect.objectContaining({ draftId, file: restored }),
+ ])
+ })
+
+ it("enforces an optional Community count limit without changing the generic default", async () => {
+ prepareCommunityImageMock.mockResolvedValue(null)
+ generateThumbnailMock.mockResolvedValue(null)
+ const files = Array.from({ length: 11 }, (_, index) =>
+ new File([String(index)], `${index}.txt`, { type: "text/plain" }))
+ const community = await renderCapture({ thumbnailPolicy: "community", maxFiles: 10 })
+ await community.addFiles(files)
+ expect(community.current.pendingFiles).toEqual([])
+ expect(toastErrorMock).toHaveBeenCalledWith("You can attach up to 10 files")
+
+ const generic = await renderCapture()
+ await generic.addFiles(files)
+ expect(generic.current.pendingFiles).toHaveLength(11)
})
})
diff --git a/src/web/src/hooks/use-file-attachments.ts b/src/web/src/hooks/use-file-attachments.ts
index ecd146235..707a8f122 100644
--- a/src/web/src/hooks/use-file-attachments.ts
+++ b/src/web/src/hooks/use-file-attachments.ts
@@ -1,10 +1,19 @@
-import React, { useCallback, useEffect, useRef, useState } from "react";
+import React, { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";
import { toast } from "sonner";
import { generateThumbnail, prepareCommunityImage } from "../lib/image-thumbnail";
+import {
+ appendComposerAttachmentSession,
+ clearComposerAttachmentSession,
+ readComposerAttachmentSession,
+ removeComposerAttachmentSessionFiles,
+ transferComposerAttachmentSession,
+} from "../lib/community/composer-attachment-session";
const DEFAULT_MAX_FILE_SIZE = 10 * 1024 * 1024; // 10 MB
export type PendingFile = {
+ /** Stable for the lifetime of a same-tab Community attachment draft. */
+ draftId?: string;
file: File;
thumbnailUrl: string | null;
thumbnailBlob: Blob | null;
@@ -12,12 +21,27 @@ export type PendingFile = {
height?: number;
};
+export type AttachmentDraftFile = {
+ draftId: string;
+ file: File;
+};
+
export type UseFileAttachmentsOptions = {
/** Per-file byte ceiling. Defaults to 10 MB. */
maxFileSize?: number;
+ /** Optional count ceiling. Generic consumers remain unbounded by default. */
+ maxFiles?: number;
thumbnailPolicy?: "legacy" | "community";
+ /** Enables same-tab Community draft restoration for this canonical scope. */
+ draftSessionScope?: string;
};
+let fallbackDraftId = 0;
+
+function createDraftId() {
+ return globalThis.crypto?.randomUUID?.() ?? `attachment-draft-${++fallbackDraftId}`;
+}
+
function revokeThumbnailUrls(files: PendingFile[]) {
for (const pf of files) {
if (pf.thumbnailUrl) URL.revokeObjectURL(pf.thumbnailUrl);
@@ -26,60 +50,84 @@ function revokeThumbnailUrls(files: PendingFile[]) {
export function useFileAttachments(opts: UseFileAttachmentsOptions = {}) {
const maxFileSize = opts.maxFileSize ?? DEFAULT_MAX_FILE_SIZE;
+ const maxFiles = opts.maxFiles;
const thumbnailPolicy = opts.thumbnailPolicy ?? "legacy";
// Options are read via ref so `addPendingFiles`'s stable identity survives
// caller re-renders while still observing an updated size limit.
- const optsRef = useRef({ maxFileSize, thumbnailPolicy });
- useEffect(() => {
- optsRef.current = { maxFileSize, thumbnailPolicy };
+ const optsRef = useRef({
+ maxFileSize,
+ maxFiles,
+ thumbnailPolicy,
+ draftSessionScope: opts.draftSessionScope,
+ });
+ useLayoutEffect(() => {
+ optsRef.current = {
+ maxFileSize,
+ maxFiles,
+ thumbnailPolicy,
+ draftSessionScope: opts.draftSessionScope,
+ };
});
const [pendingFiles, _setPendingFiles] = useState<PendingFile[]>([]);
const pendingFilesRef = useRef(pendingFiles);
const preparationTailRef = useRef<Promise<void>>(Promise.resolve());
+ const preparationGenerationRef = useRef(0);
+ const queuedDraftGenerationsRef = useRef(new Map<string, number>());
+ const mountedRef = useRef(true);
const setPendingFiles = useCallback((next: PendingFile[] | ((prev: PendingFile[]) => PendingFile[])) => {
const prev = pendingFilesRef.current;
const nextVal = typeof next === "function" ? next(prev) : next;
- if (nextVal.length === 0 && prev.length > 0) revokeThumbnailUrls(prev);
+ if (nextVal.length === 0) {
+ if (optsRef.current.draftSessionScope) {
+ clearComposerAttachmentSession(optsRef.current.draftSessionScope);
+ }
+ preparationGenerationRef.current++;
+ queuedDraftGenerationsRef.current.clear();
+ if (prev.length > 0) revokeThumbnailUrls(prev);
+ }
pendingFilesRef.current = nextVal;
_setPendingFiles(nextVal);
}, []);
const transferPendingFiles = useCallback(() => {
const transferred = pendingFilesRef.current;
+ if (optsRef.current.draftSessionScope) {
+ transferComposerAttachmentSession(optsRef.current.draftSessionScope);
+ }
+ preparationGenerationRef.current++;
+ queuedDraftGenerationsRef.current.clear();
pendingFilesRef.current = [];
_setPendingFiles([]);
return transferred;
}, []);
useEffect(() => {
- return () => revokeThumbnailUrls(pendingFilesRef.current);
+ mountedRef.current = true;
+ return () => {
+ mountedRef.current = false;
+ revokeThumbnailUrls(pendingFilesRef.current);
+ };
}, []);
const fileInputRef = useRef<HTMLInputElement>(null);
- const addPendingFiles = useCallback(async (files: File[]) => {
+ const queuePreparation = useCallback(async (
+ drafts: readonly AttachmentDraftFile[],
+ generation: number,
+ policy: "legacy" | "community",
+ draftSessionScope: string | undefined,
+ ) => {
const prior = preparationTailRef.current;
const preparation = prior.then(async () => {
- const { maxFileSize: maxSize, thumbnailPolicy: policy } = 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);
- }
- if (valid.length === 0) return;
-
const prepared = await Promise.all(
- valid.map(async (file): Promise<PendingFile | null> => {
+ drafts.map(async ({ draftId, file }): Promise<PendingFile | null> => {
if (policy === "community") {
try {
const image = await prepareCommunityImage(file);
const previewSource = image?.blob ?? (image ? file : null);
return {
+ draftId,
file,
thumbnailUrl: previewSource ? URL.createObjectURL(previewSource) : null,
thumbnailBlob: image?.blob ?? null,
@@ -87,13 +135,19 @@ export function useFileAttachments(opts: UseFileAttachmentsOptions = {}) {
height: image?.height,
} satisfies PendingFile;
} catch {
- toast.error(`Could not prepare "${file.name}" for upload`);
+ if (mountedRef.current && preparationGenerationRef.current === generation) {
+ toast.error(`Could not prepare "${file.name}" for upload`);
+ if (draftSessionScope) {
+ removeComposerAttachmentSessionFiles(draftSessionScope, [draftId]);
+ }
+ }
return null;
}
}
const thumbnail = await generateThumbnail(file);
const thumbnailUrl = thumbnail ? URL.createObjectURL(thumbnail.blob) : null;
return {
+ draftId,
file,
thumbnailUrl,
thumbnailBlob: thumbnail?.blob ?? null,
@@ -102,10 +156,24 @@ export function useFileAttachments(opts: UseFileAttachmentsOptions = {}) {
};
}),
);
+ for (const { draftId } of drafts) {
+ if (queuedDraftGenerationsRef.current.get(draftId) === generation) {
+ queuedDraftGenerationsRef.current.delete(draftId);
+ }
+ }
const pending = prepared.filter((file): file is PendingFile => file !== null);
if (pending.length === 0) return;
- const next = [...pendingFilesRef.current, ...pending];
+ if (!mountedRef.current || preparationGenerationRef.current !== generation) {
+ revokeThumbnailUrls(pending);
+ return;
+ }
+
+ const currentIds = new Set(pendingFilesRef.current.map((file) => file.draftId));
+ const next = [
+ ...pendingFilesRef.current,
+ ...pending.filter((file) => !currentIds.has(file.draftId)),
+ ];
pendingFilesRef.current = next;
_setPendingFiles(next);
});
@@ -113,6 +181,82 @@ export function useFileAttachments(opts: UseFileAttachmentsOptions = {}) {
await preparation;
}, []);
+ const addPendingFiles = useCallback(async (files: File[]) => {
+ const {
+ maxFileSize: maxSize,
+ maxFiles: countLimit,
+ thumbnailPolicy: policy,
+ draftSessionScope,
+ } = 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);
+ }
+ if (valid.length === 0) return;
+
+ const reservedCount = pendingFilesRef.current.length + queuedDraftGenerationsRef.current.size;
+ if (countLimit !== undefined && reservedCount + valid.length > countLimit) {
+ toast.error(`You can attach up to ${countLimit} files`);
+ return;
+ }
+
+ const drafts = valid.map((file) => ({ draftId: createDraftId(), file }));
+ if (draftSessionScope) {
+ const result = appendComposerAttachmentSession(draftSessionScope, drafts);
+ if (result.evictedScopes > 0) {
+ toast.info("Older attachment drafts were cleared to free memory");
+ }
+ if (!result.accepted) {
+ toast.error("These files exceed the attachment draft memory limit");
+ return;
+ }
+ }
+ const generation = preparationGenerationRef.current;
+ for (const { draftId } of drafts) queuedDraftGenerationsRef.current.set(draftId, generation);
+ await queuePreparation(
+ drafts,
+ generation,
+ policy,
+ draftSessionScope,
+ );
+ }, [queuePreparation]);
+
+ const restorePendingFiles = useCallback(async (
+ drafts: readonly AttachmentDraftFile[],
+ ) => {
+ const previous = pendingFilesRef.current;
+ preparationGenerationRef.current++;
+ const generation = preparationGenerationRef.current;
+ queuedDraftGenerationsRef.current.clear();
+ pendingFilesRef.current = [];
+ _setPendingFiles([]);
+ revokeThumbnailUrls(previous);
+
+ const {
+ maxFiles: countLimit,
+ thumbnailPolicy: policy,
+ draftSessionScope,
+ } = optsRef.current;
+ const accepted = countLimit === undefined ? drafts : drafts.slice(0, countLimit);
+ for (const { draftId } of accepted) queuedDraftGenerationsRef.current.set(draftId, generation);
+ if (accepted.length > 0) {
+ await queuePreparation(accepted, generation, policy, draftSessionScope);
+ }
+ }, [queuePreparation]);
+
+ useLayoutEffect(() => {
+ if (thumbnailPolicy !== "community") return;
+ const snapshot = opts.draftSessionScope
+ ? readComposerAttachmentSession(opts.draftSessionScope)
+ : [];
+ void restorePendingFiles(snapshot);
+ }, [opts.draftSessionScope, restorePendingFiles, thumbnailPolicy]);
+
const awaitPendingFiles = useCallback(async (): Promise<readonly PendingFile[]> => {
while (true) {
const tail = preparationTailRef.current;
@@ -134,6 +278,9 @@ export function useFileAttachments(opts: UseFileAttachmentsOptions = {}) {
const removePendingFile = useCallback((index: number) => {
const prev = pendingFilesRef.current;
const removed = prev[index];
+ if (removed?.draftId && optsRef.current.draftSessionScope) {
+ removeComposerAttachmentSessionFiles(optsRef.current.draftSessionScope, [removed.draftId]);
+ }
if (removed?.thumbnailUrl) URL.revokeObjectURL(removed.thumbnailUrl);
const next = prev.filter((_, i) => i !== index);
pendingFilesRef.current = next;
@@ -181,6 +328,7 @@ export function useFileAttachments(opts: UseFileAttachmentsOptions = {}) {
pendingFiles,
setPendingFiles,
transferPendingFiles,
+ restorePendingFiles,
awaitPendingFiles,
fileInputRef,
addPendingFiles,
diff --git a/src/web/src/lib/community/composer-attachment-session.test.ts b/src/web/src/lib/community/composer-attachment-session.test.ts
new file mode 100644
index 000000000..cb21af44e
--- /dev/null
+++ b/src/web/src/lib/community/composer-attachment-session.test.ts
@@ -0,0 +1,129 @@
+import { beforeEach, describe, expect, it } from "vitest"
+import {
+ appendComposerAttachmentSession,
+ clearComposerAttachmentSession,
+ COMPOSER_ATTACHMENT_SESSION_MAX_BYTES,
+ COMPOSER_ATTACHMENT_SESSION_TTL_MS,
+ getComposerAttachmentSessionStats,
+ readComposerAttachmentSession,
+ removeComposerAttachmentSessionFiles,
+ resetComposerAttachmentSessionsForTest,
+ transferComposerAttachmentSession,
+} from "./composer-attachment-session"
+
+function file(name: string, size = 1, type = "application/octet-stream") {
+ return {
+ name,
+ size,
+ type,
+ lastModified: 123,
+ } as File
+}
+
+describe("composer attachment same-tab session", () => {
+ beforeEach(() => resetComposerAttachmentSessionsForTest())
+
+ it("preserves stable IDs, File identity, metadata, order, and strict scopes", () => {
+ const image = file("image.png", 4, "image/png")
+ const document = file("notes.txt", 6, "text/plain")
+ appendComposerAttachmentSession("server/channel", [
+ { draftId: "image", file: image },
+ { draftId: "document", file: document },
+ ], 10)
+ appendComposerAttachmentSession("dm/person", [
+ { draftId: "dm", file: file("dm.pdf", 3, "application/pdf") },
+ ], 11)
+
+ const channel = readComposerAttachmentSession("server/channel", 12)
+ expect(channel).toEqual([
+ { draftId: "image", file: image },
+ { draftId: "document", file: document },
+ ])
+ expect(channel[0].file).toBe(image)
+ expect(channel[0].file).toMatchObject({
+ name: "image.png",
+ size: 4,
+ type: "image/png",
+ lastModified: 123,
+ })
+ expect(readComposerAttachmentSession("server/thread", 12)).toEqual([])
+ expect(readComposerAttachmentSession("dm/person", 12)).toHaveLength(1)
+ })
+
+ it("removes exact IDs, deletes empty scopes, transfers once, and clears accounting", () => {
+ const first = file("first", 4)
+ const second = file("second", 6)
+ appendComposerAttachmentSession("scope", [
+ { draftId: "first", file: first },
+ { draftId: "second", file: second },
+ ], 1)
+ expect(getComposerAttachmentSessionStats()).toEqual({ scopes: 1, bytes: 10 })
+
+ removeComposerAttachmentSessionFiles("scope", ["first"], 2)
+ expect(readComposerAttachmentSession("scope", 3)).toEqual([
+ { draftId: "second", file: second },
+ ])
+ expect(transferComposerAttachmentSession("scope")).toEqual([
+ { draftId: "second", file: second },
+ ])
+ expect(transferComposerAttachmentSession("scope")).toEqual([])
+ expect(getComposerAttachmentSessionStats()).toEqual({ scopes: 0, bytes: 0 })
+
+ appendComposerAttachmentSession("scope", [{ draftId: "again", file: first }], 4)
+ clearComposerAttachmentSession("scope")
+ expect(getComposerAttachmentSessionStats()).toEqual({ scopes: 0, bytes: 0 })
+ })
+
+ it("expires idle scopes before restore", () => {
+ appendComposerAttachmentSession("old", [{ draftId: "old", file: file("old") }], 1)
+ expect(readComposerAttachmentSession("old", COMPOSER_ATTACHMENT_SESSION_TTL_MS + 1)).toEqual([])
+ expect(getComposerAttachmentSessionStats()).toEqual({ scopes: 0, bytes: 0 })
+ })
+
+ it("expires first, then evicts inactive LRU scopes while protecting a legal active draft", () => {
+ const mib = 1024 * 1024
+ appendComposerAttachmentSession("expired", [
+ { draftId: "expired", file: file("expired", 1) },
+ ], 0)
+ appendComposerAttachmentSession("recent-a", [
+ { draftId: "a", file: file("a", 4 * mib) },
+ ], COMPOSER_ATTACHMENT_SESSION_TTL_MS - 2)
+ appendComposerAttachmentSession("recent-b", [
+ { draftId: "b", file: file("b", 4 * mib) },
+ ], COMPOSER_ATTACHMENT_SESSION_TTL_MS - 1)
+
+ const activeFiles = Array.from({ length: 10 }, (_, index) => ({
+ draftId: `active-${index}`,
+ file: file(`active-${index}`, 25 * mib),
+ }))
+ const result = appendComposerAttachmentSession(
+ "active",
+ activeFiles,
+ COMPOSER_ATTACHMENT_SESSION_TTL_MS,
+ )
+
+ expect(result).toEqual({ accepted: true, evictedScopes: 2 })
+ expect(readComposerAttachmentSession("active", COMPOSER_ATTACHMENT_SESSION_TTL_MS + 1))
+ .toEqual(activeFiles)
+ expect(readComposerAttachmentSession("recent-a", COMPOSER_ATTACHMENT_SESSION_TTL_MS + 1)).toEqual([])
+ expect(readComposerAttachmentSession("recent-b", COMPOSER_ATTACHMENT_SESSION_TTL_MS + 1)).toHaveLength(1)
+ expect(getComposerAttachmentSessionStats()).toEqual({
+ scopes: 2,
+ bytes: 254 * mib,
+ })
+ })
+
+ it("rejects only an independently oversized active scope without evicting inactive work", () => {
+ const existing = file("existing", 1)
+ appendComposerAttachmentSession("inactive", [{ draftId: "keep", file: existing }], 1)
+ const result = appendComposerAttachmentSession("active", [{
+ draftId: "too-large",
+ file: file("too-large", COMPOSER_ATTACHMENT_SESSION_MAX_BYTES + 1),
+ }], 2)
+
+ expect(result).toEqual({ accepted: false, evictedScopes: 0 })
+ expect(readComposerAttachmentSession("inactive", 3)).toEqual([
+ { draftId: "keep", file: existing },
+ ])
+ })
+})
diff --git a/src/web/src/lib/community/composer-attachment-session.ts b/src/web/src/lib/community/composer-attachment-session.ts
new file mode 100644
index 000000000..e8cd23d19
--- /dev/null
+++ b/src/web/src/lib/community/composer-attachment-session.ts
@@ -0,0 +1,159 @@
+export const COMPOSER_ATTACHMENT_SESSION_TTL_MS = 24 * 60 * 60 * 1_000
+const COMPOSER_ATTACHMENT_SESSION_MAX_SCOPES = 50
+export const COMPOSER_ATTACHMENT_SESSION_MAX_BYTES = 256 * 1024 * 1024
+
+export type ComposerAttachmentSessionFile = {
+ draftId: string
+ file: File
+}
+
+type ComposerAttachmentSessionEntry = ComposerAttachmentSessionFile & {
+ touchedAt: number
+}
+
+export type ComposerAttachmentSessionWriteResult = {
+ accepted: boolean
+ evictedScopes: number
+}
+
+const attachmentSessions = new Map<string, ComposerAttachmentSessionEntry[]>()
+
+function scopeBytes(entries: readonly ComposerAttachmentSessionEntry[]) {
+ return entries.reduce((total, entry) => total + entry.file.size, 0)
+}
+
+function totalBytes() {
+ let total = 0
+ for (const entries of attachmentSessions.values()) total += scopeBytes(entries)
+ return total
+}
+
+function touchScope(
+ scope: string,
+ entries: readonly ComposerAttachmentSessionEntry[],
+ now: number,
+) {
+ const touched = entries.map((entry) => ({ ...entry, touchedAt: now }))
+ attachmentSessions.delete(scope)
+ if (touched.length > 0) attachmentSessions.set(scope, touched)
+ return touched
+}
+
+function isExpired(entries: readonly ComposerAttachmentSessionEntry[], now: number) {
+ return entries.length === 0 || now - entries[0].touchedAt >= COMPOSER_ATTACHMENT_SESSION_TTL_MS
+}
+
+function removeExpiredInactiveScopes(activeScope: string, now: number) {
+ let removed = 0
+ for (const [scope, entries] of attachmentSessions) {
+ if (scope !== activeScope && isExpired(entries, now)) {
+ attachmentSessions.delete(scope)
+ removed++
+ }
+ }
+ return removed
+}
+
+/**
+ * Returns a same-tab snapshot and promotes the scope to most-recently-used.
+ * A scope that was already idle beyond the TTL expires before it can restore.
+ */
+export function readComposerAttachmentSession(
+ scope: string,
+ now = Date.now(),
+): ComposerAttachmentSessionFile[] {
+ const entries = attachmentSessions.get(scope)
+ if (!entries) {
+ removeExpiredInactiveScopes(scope, now)
+ return []
+ }
+ if (isExpired(entries, now)) {
+ attachmentSessions.delete(scope)
+ removeExpiredInactiveScopes(scope, now)
+ return []
+ }
+ const touched = touchScope(scope, entries, now)
+ removeExpiredInactiveScopes(scope, now)
+ return touched.map(({ draftId, file }) => ({ draftId, file }))
+}
+
+/**
+ * Registers raw Files synchronously before thumbnail preparation. The active
+ * scope is protected; expired and then least-recently-used inactive scopes are
+ * discarded to make the current user action fit.
+ */
+export function appendComposerAttachmentSession(
+ scope: string,
+ files: readonly ComposerAttachmentSessionFile[],
+ now = Date.now(),
+): ComposerAttachmentSessionWriteResult {
+ if (files.length === 0) return { accepted: true, evictedScopes: 0 }
+
+ const current = attachmentSessions.get(scope) ?? []
+ const currentIds = new Set(current.map((entry) => entry.draftId))
+ const additions = files
+ .filter((entry) => !currentIds.has(entry.draftId))
+ .map((entry) => ({ ...entry, touchedAt: now }))
+ const nextActive = [...current, ...additions]
+
+ // A legal Community draft is at most 10 × 25 MiB, so this only rejects an
+ // independently invalid active scope rather than sacrificing current work.
+ if (scopeBytes(nextActive) > COMPOSER_ATTACHMENT_SESSION_MAX_BYTES) {
+ return { accepted: false, evictedScopes: 0 }
+ }
+
+ let evictedScopes = removeExpiredInactiveScopes(scope, now)
+ const activeWasPresent = attachmentSessions.has(scope)
+ const projectedScopeCount = () => attachmentSessions.size + (activeWasPresent ? 0 : 1)
+ const projectedBytes = () => totalBytes() - scopeBytes(current) + scopeBytes(nextActive)
+
+ while (
+ projectedScopeCount() > COMPOSER_ATTACHMENT_SESSION_MAX_SCOPES ||
+ projectedBytes() > COMPOSER_ATTACHMENT_SESSION_MAX_BYTES
+ ) {
+ const oldestInactive = [...attachmentSessions.keys()].find((key) => key !== scope)
+ if (!oldestInactive) return { accepted: false, evictedScopes }
+ attachmentSessions.delete(oldestInactive)
+ evictedScopes++
+ }
+
+ touchScope(scope, nextActive, now)
+ return { accepted: true, evictedScopes }
+}
+
+export function removeComposerAttachmentSessionFiles(
+ scope: string,
+ draftIds: readonly string[],
+ now = Date.now(),
+) {
+ if (draftIds.length === 0) return
+ const entries = attachmentSessions.get(scope)
+ if (!entries) return
+ const removed = new Set(draftIds)
+ touchScope(
+ scope,
+ entries.filter((entry) => !removed.has(entry.draftId)),
+ now,
+ )
+}
+
+export function clearComposerAttachmentSession(scope: string) {
+ attachmentSessions.delete(scope)
+}
+
+export function transferComposerAttachmentSession(
+ scope: string,
+): ComposerAttachmentSessionFile[] {
+ const entries = attachmentSessions.get(scope) ?? []
+ attachmentSessions.delete(scope)
+ return entries.map(({ draftId, file }) => ({ draftId, file }))
+}
+
+/** Test-only inspection/reset helpers; the production registry remains one Map. */
+export function getComposerAttachmentSessionStats() {
+ return { scopes: attachmentSessions.size, bytes: totalBytes() }
+}
+
+export function resetComposerAttachmentSessionsForTest() {
+ attachmentSessions.clear()
+}
diff --git a/src/web/src/test/e2e-ui/02-server-channel-message.spec.ts b/src/web/src/test/e2e-ui/02-server-channel-message.spec.ts
index cee6d49ca..af8908249 100644
--- a/src/web/src/test/e2e-ui/02-server-channel-message.spec.ts
+++ b/src/web/src/test/e2e-ui/02-server-channel-message.spec.ts
@@ -261,10 +261,13 @@ test("server → channel → message", async ({ asUser }) => {
})
await expect(page.getByText("rejected.txt", { exact: true })).toBeVisible()
await expect.poll(() => restored.evaluate((element) => document.activeElement === element)).toBe(true)
+ const nonceCallsAfterAttachmentSelection = await page.evaluate(() =>
+ (window as unknown as { __messageStreamNonceCalls: number }).__messageStreamNonceCalls,
+ )
await page.keyboard.press("Enter")
await expect.poll(() => page.evaluate(() =>
(window as unknown as { __messageStreamNonceCalls: number }).__messageStreamNonceCalls,
- )).toBe(2)
+ )).toBe(nonceCallsAfterAttachmentSelection + 1)
await expect.poll(() => pendingPostCount).toBe(1)
await expect(restored).toContainText(rejectedDraft)
await expect(page.getByText("rejected.txt", { exact: true })).toBeVisible()
diff --git a/src/web/src/test/e2e-ui/43-composer-attachment-drafts.spec.ts b/src/web/src/test/e2e-ui/43-composer-attachment-drafts.spec.ts
new file mode 100644
index 000000000..0b64163ee
--- /dev/null
+++ b/src/web/src/test/e2e-ui/43-composer-attachment-drafts.spec.ts
@@ -0,0 +1,269 @@
+import type { Page } from "@playwright/test"
+import { test, expect, userId } from "./_fixtures/community-fixture"
+import { composerEditable } from "./_fixtures/actions"
+import { seedChannel, seedDm, seedMessage, seedServer, seedThread } from "./_fixtures/seed"
+import { tid } from "./_fixtures/testids"
+
+const PNG_1X1 = Buffer.from(
+ "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=",
+ "base64",
+)
+
+async function navigateChannel(page: Page, serverId: string, channelId: string) {
+ const route = `/c/channels/${serverId}/${channelId}`
+ const row = page.getByTestId(tid.channelRow(channelId))
+ if (!await row.isVisible()) {
+ const serverCrumb = page.getByTestId(tid.channelHeaderServer(serverId))
+ if (await serverCrumb.isVisible()) await serverCrumb.evaluate((element) => (element as HTMLElement).click())
+ else await page.getByTestId(tid.serverIcon(serverId)).evaluate((element) => (element as HTMLElement).click())
+ }
+ await expect(row).toBeVisible()
+ await row.evaluate((element) => (element as HTMLElement).click())
+ await page.waitForURL((url) => url.pathname === route)
+ await expect(composerEditable(page)).toBeVisible({ timeout: 20_000 })
+}
+
+async function navigateDm(page: Page, dmId: string) {
+ await page.getByTestId(tid.homeButton).evaluate((element) => (element as HTMLElement).click())
+ const row = page.getByTestId(tid.dmRow(dmId))
+ await expect(row).toBeVisible()
+ await row.evaluate((element) => (element as HTMLElement).click())
+ await page.waitForURL((url) => url.pathname === `/c/me/${dmId}`)
+ await expect(composerEditable(page)).toBeVisible({ timeout: 20_000 })
+}
+
+function composerAttachments(page: Page) {
+ return page.getByTestId(tid.composerInput).locator("../..")
+}
+
+test.describe.serial("same-tab Community attachment drafts", () => {
+ let serverId: string
+ let channelAId: string
+ let channelBId: string
+ let openerId: string
+ let threadId: string
+ let dmId: string
+
+ test.beforeAll(async () => {
+ serverId = await seedServer("alice", `attachment-drafts-${Date.now()}`)
+ channelAId = await seedChannel("alice", serverId, "attachment-draft-a")
+ channelBId = await seedChannel("alice", serverId, "attachment-draft-b")
+ openerId = await seedMessage("alice", channelAId, "attachment draft thread opener")
+ threadId = await seedThread("alice", openerId, "attachment-draft-thread")
+ dmId = await seedDm("alice", userId("bob"))
+ })
+
+ test("desktop restores scoped real image/file drafts, rebuilds URLs, and removal never revives", async ({ asUser }) => {
+ test.setTimeout(120_000)
+ const { page } = await asUser("alice")
+ const channelA = `/c/channels/${serverId}/${channelAId}`
+ await page.goto(channelA, { waitUntil: "commit" })
+ await expect(composerEditable(page)).toBeVisible({ timeout: 20_000 })
+ await page.evaluate(() => {
+ const created: string[] = []
+ const revoked: string[] = []
+ const create = URL.createObjectURL.bind(URL)
+ const revoke = URL.revokeObjectURL.bind(URL)
+ Object.defineProperty(window, "__attachmentDraftUrls", {
+ configurable: true,
+ value: { created, revoked },
+ })
+ URL.createObjectURL = (object) => {
+ const url = create(object)
+ created.push(url)
+ return url
+ }
+ URL.revokeObjectURL = (url) => {
+ revoked.push(url)
+ revoke(url)
+ }
+ })
+ let attachmentPosts = 0
+ let messagePosts = 0
+ page.on("request", (request) => {
+ const path = new URL(request.url()).pathname
+ if (request.method() === "POST" && /\/attachments$/.test(path)) attachmentPosts++
+ if (request.method() === "POST" && /\/messages$/.test(path)) messagePosts++
+ })
+
+ const channelAText = `image draft ${Date.now()}`
+ await composerEditable(page).fill(channelAText)
+ await page.getByTestId(tid.composerFileInput).setInputFiles({
+ name: "scope-image.png",
+ mimeType: "image/png",
+ buffer: PNG_1X1,
+ })
+ await expect(composerAttachments(page).getByText("scope-image.png", { exact: true })).toBeVisible()
+ await expect.poll(() => page.evaluate(() =>
+ (window as unknown as { __attachmentDraftUrls: { created: string[] } }).__attachmentDraftUrls.created.length,
+ )).toBeGreaterThanOrEqual(1)
+ const initialUrlEvidence = await page.evaluate(() =>
+ (window as unknown as { __attachmentDraftUrls: { created: string[]; revoked: string[] } }).__attachmentDraftUrls,
+ )
+ const initialPreviewUrl = initialUrlEvidence.created.at(-1)!
+
+ await navigateChannel(page, serverId, channelBId)
+ expect(await page.evaluate(() => "__attachmentDraftUrls" in window)).toBe(true)
+ await expect(composerAttachments(page).getByText("scope-image.png", { exact: true })).toHaveCount(0)
+ const channelBText = `file draft ${Date.now()}`
+ await composerEditable(page).fill(channelBText)
+ await page.getByTestId(tid.composerFileInput).setInputFiles({
+ name: "scope-file.txt",
+ mimeType: "text/plain",
+ buffer: Buffer.from("generic draft bytes"),
+ })
+ await expect(composerAttachments(page).getByText("scope-file.txt", { exact: true })).toBeVisible()
+
+ await navigateChannel(page, serverId, channelAId)
+ await expect(composerAttachments(page).getByText("scope-image.png", { exact: true })).toBeVisible()
+ await page.getByTestId(tid.threadIndicator(openerId)).click()
+ await page.waitForURL((url) => url.pathname === `/c/channels/${serverId}/${threadId}`)
+ await expect(composerEditable(page)).toBeVisible()
+ await expect(composerEditable(page)).toHaveText("")
+ await expect(page.getByRole("button", { name: "Remove file" })).toHaveCount(0)
+ await navigateDm(page, dmId)
+ await expect(composerEditable(page)).toHaveText("")
+ await expect(page.getByRole("button", { name: "Remove file" })).toHaveCount(0)
+
+ await navigateChannel(page, serverId, channelAId)
+ await expect(composerEditable(page)).toContainText(channelAText)
+ await expect(composerAttachments(page).getByText("scope-image.png", { exact: true })).toBeVisible()
+ const urlEvidence = await page.evaluate(() =>
+ (window as unknown as { __attachmentDraftUrls: { created: string[]; revoked: string[] } }).__attachmentDraftUrls,
+ )
+ expect(urlEvidence.created.length).toBeGreaterThan(initialUrlEvidence.created.length)
+ expect(urlEvidence.created.at(-1)).not.toBe(initialPreviewUrl)
+ expect(urlEvidence.revoked).toContain(initialPreviewUrl)
+ await page.getByRole("button", { name: "Remove file" }).click()
+
+ await navigateChannel(page, serverId, channelBId)
+ await expect(composerEditable(page)).toContainText(channelBText)
+ await expect(composerAttachments(page).getByText("scope-file.txt", { exact: true })).toBeVisible()
+ await navigateChannel(page, serverId, channelAId)
+ await expect(composerEditable(page)).toContainText(channelAText)
+ await expect(composerAttachments(page).getByText("scope-image.png", { exact: true })).toHaveCount(0)
+ expect(attachmentPosts).toBe(0)
+ expect(messagePosts).toBe(0)
+ })
+
+ test("desktop restored generic file survives upload failure, retries once, and never revives", async ({ asUser }) => {
+ test.setTimeout(120_000)
+ const { page } = await asUser("alice")
+ const channelA = `/c/channels/${serverId}/${channelAId}`
+ await page.goto(channelA, { waitUntil: "commit" })
+ await expect(composerEditable(page)).toBeVisible({ timeout: 20_000 })
+ const body = `retry restored file ${Date.now()}`
+ await composerEditable(page).fill(body)
+ await page.getByTestId(tid.composerFileInput).setInputFiles({
+ name: "retry-restored.txt",
+ mimeType: "text/plain",
+ buffer: Buffer.from("retry restored bytes"),
+ })
+ await expect(composerAttachments(page).getByText("retry-restored.txt", { exact: true })).toBeVisible()
+ await navigateChannel(page, serverId, channelBId)
+ await navigateChannel(page, serverId, channelAId)
+ await expect(composerEditable(page)).toContainText(body)
+ await expect(composerAttachments(page).getByText("retry-restored.txt", { exact: true })).toBeVisible()
+
+ let uploadAttempts = 0
+ let messagePosts = 0
+ await page.route(`**/api/community/channels/${channelAId}/attachments`, async (route) => {
+ if (route.request().method() !== "POST") return route.continue()
+ uploadAttempts++
+ if (uploadAttempts === 1) {
+ await route.fulfill({
+ status: 500,
+ contentType: "application/json",
+ body: JSON.stringify({ error: "forced upload failure" }),
+ })
+ return
+ }
+ await route.continue()
+ })
+ page.on("request", (request) => {
+ if (
+ request.method() === "POST"
+ && new URL(request.url()).pathname === `/api/community/channels/${channelAId}/messages`
+ ) messagePosts++
+ })
+ await composerEditable(page).press("Enter")
+ await expect(page.getByText("Message failed to send. Click to retry.", { exact: true })).toBeVisible()
+ await expect(composerEditable(page)).toHaveText("")
+ await expect(composerAttachments(page).getByText("retry-restored.txt", { exact: true })).toHaveCount(0)
+ expect(uploadAttempts).toBe(1)
+ expect(messagePosts).toBe(0)
+
+ const committed = page.waitForResponse((response) =>
+ response.request().method() === "POST"
+ && new URL(response.url()).pathname === `/api/community/channels/${channelAId}/messages`,
+ )
+ await page.getByText("Message failed to send. Click to retry.", { exact: true }).click()
+ expect((await committed).status()).toBe(201)
+ await expect.poll(() => uploadAttempts).toBe(2)
+ await expect.poll(() => messagePosts).toBe(1)
+ await expect(page.getByText("Message failed to send. Click to retry.", { exact: true })).toHaveCount(0)
+
+ await navigateChannel(page, serverId, channelBId)
+ await navigateChannel(page, serverId, channelAId)
+ await expect(composerEditable(page)).toHaveText("")
+ await expect(composerAttachments(page).getByText("retry-restored.txt", { exact: true })).toHaveCount(0)
+ })
+
+ test("mobile restores scoped attachments, sends explicitly once, and reload restores text only", async ({ asUser }) => {
+ test.setTimeout(120_000)
+ const { page } = await asUser("alice")
+ await page.setViewportSize({ width: 390, height: 844 })
+ const channelA = `/c/channels/${serverId}/${channelAId}`
+ await page.goto(channelA, { waitUntil: "commit" })
+ await expect(composerEditable(page)).toBeVisible({ timeout: 20_000 })
+ const body = `mobile restored image ${Date.now()}`
+ await composerEditable(page).fill(body)
+ await page.getByTestId(tid.composerFileInput).setInputFiles({
+ name: "mobile-image.png",
+ mimeType: "image/png",
+ buffer: PNG_1X1,
+ })
+ await expect(composerAttachments(page).getByText("mobile-image.png", { exact: true })).toBeVisible()
+ await navigateChannel(page, serverId, channelBId)
+ await page.getByTestId(tid.composerFileInput).setInputFiles({
+ name: "mobile-file.txt",
+ mimeType: "text/plain",
+ buffer: Buffer.from("mobile generic bytes"),
+ })
+ await expect(composerAttachments(page).getByText("mobile-file.txt", { exact: true })).toBeVisible()
+ await navigateChannel(page, serverId, channelAId)
+ await expect(composerEditable(page)).toContainText(body)
+ await expect(composerAttachments(page).getByText("mobile-image.png", { exact: true })).toBeVisible()
+
+ let uploads = 0
+ let messages = 0
+ page.on("request", (request) => {
+ const path = new URL(request.url()).pathname
+ if (request.method() === "POST" && path.endsWith("/attachments")) uploads++
+ if (request.method() === "POST" && path.endsWith("/messages")) messages++
+ })
+ const send = page.getByTestId(tid.composerSend)
+ await expect(send).toBeEnabled()
+ const committed = page.waitForResponse((response) =>
+ response.request().method() === "POST"
+ && new URL(response.url()).pathname === `/api/community/channels/${channelAId}/messages`,
+ )
+ await send.evaluate((button) => (button as HTMLButtonElement).click())
+ expect((await committed).status()).toBe(201)
+ await expect.poll(() => uploads).toBe(1)
+ await expect.poll(() => messages).toBe(1)
+ await expect(composerEditable(page)).toHaveText("")
+
+ await navigateChannel(page, serverId, channelBId)
+ const reloadText = `mobile reload text ${Date.now()}`
+ await composerEditable(page).fill(reloadText)
+ await expect(composerAttachments(page).getByText("mobile-file.txt", { exact: true })).toBeVisible()
+ const beforeReloadUploads = uploads
+ const beforeReloadMessages = messages
+ await page.reload({ waitUntil: "commit" })
+ await expect(composerEditable(page)).toContainText(reloadText)
+ await expect(composerAttachments(page).getByText("mobile-file.txt", { exact: true })).toHaveCount(0)
+ expect(uploads).toBe(beforeReloadUploads)
+ expect(messages).toBe(beforeReloadMessages)
+ })
+})