Skip to content

Commit e74c68d

Browse files
klopez4212codex
andcommitted
Fix attachment upload recovery and preview interactions
Co-authored-by: Codex <[email protected]> Signed-off-by: klopez4212 <[email protected]>
1 parent 021ae50 commit e74c68d

8 files changed

Lines changed: 232 additions & 2 deletions

‎src/features/messages/ComposerAttachmentViewer.tsx‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import { galleryMotion } from "./use-image-gallery-motion";
88
import { useRef, useState, useLayoutEffect, type RefObject } from "react";
99
import { MediaReviewFrame } from "./MediaReviewFrame";
1010
import { ImageReviewStage } from "./ImageReviewStage";
11+
import { useMediaElementSource } from "./use-media-element-source";
1112
import { VideoPlayer } from "./VideoPlayer";
1213
import { AudioAttachment } from "./AudioAttachment";
1314
import { FileAttachment } from "./FileAttachment";
@@ -220,6 +221,9 @@ function DraftMedia({
220221
const source = item.uploaded
221222
? resolvedSource
222223
: (initialSource ?? resolvedSource);
224+
const sourceUnavailable = useMediaElementSource(
225+
isVideo ? source : undefined,
226+
).unavailable;
223227
useLayoutEffect(() => {
224228
if (!activeVideo || !source) return;
225229
const element = video.current;
@@ -251,7 +255,7 @@ function DraftMedia({
251255
No preview available for this file type.
252256
</p>
253257
);
254-
if (!source || failed === source)
258+
if (!source || sourceUnavailable || failed === source)
255259
return (
256260
<p className={styles.mediaReviewUnavailable} role="status">
257261
Preview unavailable

‎src/features/messages/ComposerAttachments.test.tsx‎

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@ import { ConversationPresentation } from "../conversation/ConversationPresentati
1212
import { ComposerAttachments } from "./ComposerAttachments";
1313
import type { DraftAttachment } from "./attachment-draft";
1414

15+
vi.mock("@tauri-apps/api/core", () => ({ invoke: vi.fn(async () => null) }));
16+
1517
beforeEach(() => {
1618
vi.spyOn(HTMLMediaElement.prototype, "play").mockResolvedValue(undefined);
1719
vi.spyOn(HTMLMediaElement.prototype, "pause").mockImplementation(() => {});
@@ -233,6 +235,10 @@ it("explains an upload failure on focus and preserves retry and removal", async
233235
key: "Delete",
234236
});
235237
expect(remove).toHaveBeenCalledWith("failed-file");
238+
remove.mockClear();
239+
fireEvent.click(screen.getByRole("button", { name: "Remove report.pdf" }));
240+
expect(remove).toHaveBeenCalledExactlyOnceWith("failed-file");
241+
expect(retry).toHaveBeenCalledOnce();
236242
});
237243

238244
it("keeps removal available during upload", () => {
@@ -429,3 +435,80 @@ it("navigates local image and video previews while uploading without sent-messag
429435
expect(remove).not.toHaveBeenCalled();
430436
expect(retry).not.toHaveBeenCalled();
431437
});
438+
439+
it("shows unavailable playback when the native media listener cannot start", async () => {
440+
const url = `https://relay.test/media/${"a".repeat(64)}.mp4`;
441+
render(
442+
<ComposerAttachments
443+
items={[
444+
{
445+
id: "native-video",
446+
file: new File([], "clip.mp4", { type: "video/mp4" }),
447+
status: "ready",
448+
uploaded: {
449+
url,
450+
name: "clip.mp4",
451+
type: "video/mp4",
452+
size: 8,
453+
sha256: "a".repeat(64),
454+
},
455+
},
456+
]}
457+
disabled={false}
458+
remove={vi.fn()}
459+
retry={vi.fn()}
460+
media={() => `buzz-media://localhost/${encodeURIComponent(url)}`}
461+
/>,
462+
);
463+
await screen.findByText("Preview unavailable");
464+
fireEvent.click(screen.getByRole("button", { name: "Preview clip.mp4" }));
465+
await waitFor(() =>
466+
expect(screen.getByRole("dialog").textContent).toContain(
467+
"Preview unavailable",
468+
),
469+
);
470+
expect(screen.getByRole("dialog").querySelector("video")).toBeNull();
471+
});
472+
473+
it("returns focus to the selected generic attachment after viewer navigation", async () => {
474+
vi.stubGlobal(
475+
"URL",
476+
Object.assign(URL, {
477+
createObjectURL: vi.fn(() => "blob:photo"),
478+
revokeObjectURL: vi.fn(),
479+
}),
480+
);
481+
render(
482+
<ComposerAttachments
483+
items={[
484+
{
485+
id: "image",
486+
file: new File(["png"], "photo.png", { type: "image/png" }),
487+
status: "uploading",
488+
},
489+
{
490+
id: "pdf",
491+
file: new File(["pdf"], "report.pdf", { type: "application/pdf" }),
492+
status: "queued",
493+
},
494+
]}
495+
disabled={false}
496+
remove={vi.fn()}
497+
retry={vi.fn()}
498+
media={() => undefined}
499+
/>,
500+
);
501+
const image = screen.getByRole("button", { name: "Preview photo.png" });
502+
image.focus();
503+
fireEvent.click(image);
504+
fireEvent.keyDown(screen.getByRole("dialog"), { key: "ArrowRight" });
505+
expect(screen.getByRole("dialog").textContent).toContain(
506+
"No preview available for this file type.",
507+
);
508+
fireEvent.keyDown(screen.getByRole("dialog"), { key: "Escape" });
509+
await waitFor(() =>
510+
expect(document.activeElement).toBe(
511+
screen.getByRole("button", { name: "Preview report.pdf" }),
512+
),
513+
);
514+
});

‎src/features/messages/ComposerAttachments.tsx‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -241,6 +241,7 @@ function AttachmentItem({
241241
) : (
242242
<button
243243
type="button"
244+
data-draft-preview={item.id}
244245
className={styles.preview}
245246
aria-label={`Preview ${item.file.name}`}
246247
onClick={(event) => preview(event.currentTarget)}
@@ -362,6 +363,17 @@ function AttachmentItem({
362363
)
363364
}
364365
/>
366+
{item.status === "error" && (
367+
<IconButton
368+
size="xs"
369+
shape="round"
370+
variant="primary"
371+
disabled={disabled}
372+
aria-label={`Remove ${item.file.name}`}
373+
onClick={() => remove(item.id)}
374+
icon={<XIcon size={16} />}
375+
/>
376+
)}
365377
{item.error && (
366378
<span role="alert" className="sr-only">
367379
{item.error}

‎src/features/messages/MessageComposer.test.tsx‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4900,6 +4900,42 @@ it("does not ask about outside recipients in a session media-comment composer",
49004900
expect(add).not.toHaveBeenCalled();
49014901
});
49024902

4903+
it("keeps the draft and requires explicit Retry when an eager upload fails during nonmember admission", async () => {
4904+
const h = mount();
4905+
const result = deferred<ReturnType<typeof uploadDescriptor>>();
4906+
const upload = vi.fn(() => result.promise);
4907+
const list = {
4908+
status: "ready",
4909+
channels: [
4910+
{ id: "channel", channelType: "stream", members: [second.pubkey] },
4911+
],
4912+
};
4913+
Object.assign(h.session, {
4914+
attachments: { upload },
4915+
channels: {
4916+
...h.session.channels,
4917+
list: () => list,
4918+
},
4919+
memberAdditions: { add: vi.fn() },
4920+
});
4921+
h.retarget({});
4922+
h.fill("Keep my draft");
4923+
act(() => h.commands().insertMention(first));
4924+
attachByPaste(h.input(), attachmentFile());
4925+
await waitFor(() => expect(upload).toHaveBeenCalledOnce());
4926+
fireEvent.submit(screen.getByRole("form"));
4927+
expect(screen.getByRole("dialog")).toBeInTheDocument();
4928+
await act(async () => result.reject(new Error("relay down")));
4929+
fireEvent.click(screen.getByRole("button", { name: "Send anyway" }));
4930+
await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());
4931+
expect(upload).toHaveBeenCalledOnce();
4932+
expect(h.messages.send).not.toHaveBeenCalled();
4933+
expect(h.input().value).toContain("Keep my draft");
4934+
expect(
4935+
screen.getByRole("button", { name: "Retry notes.txt" }),
4936+
).toBeInTheDocument();
4937+
});
4938+
49034939
for (const channelType of ["stream", "forum"] as const)
49044940
it.each([undefined, "f".repeat(64)])(
49054941
`keeps mixed nonmember mentions as references after Send anyway in ${channelType}, root=%s`,

‎src/features/messages/MessageComposer.tsx‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1118,6 +1118,8 @@ function Composer({
11181118
}
11191119
}
11201120
attempt.signal.throwIfAborted();
1121+
if (attachments.store.snapshot().some((item) => item.status === "error"))
1122+
return;
11211123
if (
11221124
valueRef.current !== captured ||
11231125
!sameAttachmentSelection(

‎src/features/messages/attachment-draft.test.tsx‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -220,6 +220,9 @@ it("aborting a send cancels eager uploads and retains ready descriptors", async
220220
]);
221221
expect(draft.result.current.blocked).toBe(true);
222222

223+
act(() =>
224+
draft.result.current.store.retry(draft.result.current.items[1]?.id ?? ""),
225+
);
223226
const retry = new AbortController();
224227
let retryWork: Promise<readonly UploadedAttachment[]>;
225228
await act(async () => {
@@ -480,3 +483,24 @@ it("renders real host transfer bytes as a determinate ring through completion",
480483
await waitFor(() => expect(screen.queryByRole("progressbar")).toBeNull());
481484
expect(screen.getByRole("button", { name: "Remove notes.txt" })).toBeTruthy();
482485
});
486+
487+
it("rejects eager upload errors until explicit Retry, including after Send handoff", async () => {
488+
const h = fixture();
489+
const draft = renderHook(() => useAttachmentDraft(h.session, "one", "one"));
490+
act(() => draft.result.current.store.add([file()]));
491+
await waitFor(() => expect(h.calls).toHaveLength(1));
492+
await act(async () => h.calls[0]?.result.reject(new Error("relay down")));
493+
expect(draft.result.current.blocked).toBe(true);
494+
const target = attachmentDraft(h.session, "send", "one");
495+
act(() => transferAttachmentDraft(draft.result.current.store, target));
496+
await expect(
497+
target.prepareForSend(new AbortController().signal),
498+
).rejects.toThrow("relay down");
499+
expect(h.calls).toHaveLength(1);
500+
expect(target.snapshot()[0]?.status).toBe("error");
501+
target.retry(target.snapshot()[0]?.id ?? "");
502+
await waitFor(() => expect(h.calls).toHaveLength(2));
503+
const work = target.prepareForSend(new AbortController().signal);
504+
h.calls[1]?.result.resolve(uploaded());
505+
await expect(work).resolves.toEqual([uploaded()]);
506+
});

‎src/features/messages/attachment-draft.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -218,6 +218,10 @@ export function attachmentDraft(
218218
if (next) start(next);
219219
}
220220
function start(item: DraftAttachment, signal = new AbortController().signal) {
221+
if (item.status === "error")
222+
return Promise.reject(
223+
new Error(item.error || "Retry or remove this file."),
224+
);
221225
const existing = pending.get(item.id);
222226
if (existing && active.has(item.id)) return abortable(existing, signal);
223227
const work = prepareOne(item, signal);

‎tests/browser/composer-attachments.spec.mjs‎

Lines changed: 66 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,18 @@ test("picker, pane drop and clipboard files use the same attachment draft and ex
129129
});
130130
await expect(form.getByText(/Ready$/)).toHaveCount(3);
131131
expect(uploadRequests).toHaveLength(3);
132+
// Real modal focus returns to the navigated generic preview, not its opener.
133+
await form.getByRole("button", { name: "Preview picked.txt" }).click();
134+
const preview = page.getByRole("dialog", { name: "Attachment preview" });
135+
await preview.getByRole("button", { name: "Next attachment" }).click();
136+
await expect(
137+
preview.getByText("dropped.txt", { exact: true }).first(),
138+
).toBeVisible();
139+
await page.keyboard.press("Escape");
140+
await expect(preview).toHaveCount(0);
141+
await expect(
142+
form.getByRole("button", { name: "Preview dropped.txt" }),
143+
).toBeFocused();
132144
// Completed eager uploads leave the remove control available.
133145
await expect(form.locator("[data-uploading]")).toHaveCount(0);
134146
await expect(remove.locator("svg")).toHaveCount(1);
@@ -567,7 +579,7 @@ test("local previews stay interactive during eager upload and removal collapses
567579
if (req.url !== "/api/relay/upload" || req.method !== "POST")
568580
return next();
569581
req.resume();
570-
const status = ++requests === 1 ? 503 : 204;
582+
const status = [1, 4].includes(++requests) ? 503 : 204;
571583
void held.then(() => {
572584
res.writeHead(status);
573585
res.end();
@@ -914,12 +926,65 @@ test("local previews stay interactive during eager upload and removal collapses
914926
await expect
915927
.poll(() => form.evaluate((el) => el.getBoundingClientRect().height))
916928
.toBe(beforeFailure);
929+
const failedRemove = form.getByRole("button", { name: "Remove photo.png" });
930+
await expect(failedRemove).toBeVisible();
931+
// Both error actions must fit inside the real strip scrollport.
932+
for (const action of [retry, failedRemove]) {
933+
expect(
934+
await action.evaluate((el) => {
935+
const control = el.getBoundingClientRect();
936+
const strip = el.closest("ul").getBoundingClientRect();
937+
return Math.min(
938+
control.left - strip.left,
939+
strip.right - control.right,
940+
control.top - strip.top,
941+
);
942+
}),
943+
).toBeGreaterThanOrEqual(0);
944+
}
945+
for (const mode of ["light", "dark"]) {
946+
await page.evaluate(
947+
(mode) =>
948+
document.documentElement.classList.toggle("dark", mode === "dark"),
949+
mode,
950+
);
951+
for (const width of [390, 1280]) {
952+
await page.setViewportSize({ width, height: 800 });
953+
await page.evaluate(() => {
954+
document.documentElement.style.fontSize = "200%";
955+
});
956+
await retry.click({ trial: true });
957+
await failedRemove.click({ trial: true });
958+
}
959+
}
960+
await page.evaluate(() => {
961+
document.documentElement.style.fontSize = "";
962+
});
963+
await page.setViewportSize({ width: 1440, height: 950 });
917964
await form.screenshot({
918965
path: test.info().outputPath("compact-upload-retry.png"),
919966
});
920967
await retry.click();
921968
await expect(retry).toHaveCount(0);
922969
await expect(form.getByRole("progressbar")).toHaveCount(0);
970+
await form.getByLabel("Choose attachments").setInputFiles({
971+
name: "failed.txt",
972+
mimeType: "text/plain",
973+
buffer: Buffer.from("failed"),
974+
});
975+
await expect(
976+
form.getByRole("button", { name: "Retry failed.txt" }),
977+
).toBeVisible();
978+
await expect(
979+
form.getByRole("button", { name: "Send message" }),
980+
).toBeDisabled();
981+
await form.getByRole("button", { name: "Remove failed.txt" }).click();
982+
await expect(
983+
form.getByRole("button", { name: "Retry failed.txt" }),
984+
).toHaveCount(0);
985+
await expect(
986+
form.getByRole("button", { name: "Send message" }),
987+
).toBeEnabled();
923988
await page.emulateMedia({ reducedMotion: "reduce" });
924989
await page.evaluate(() => {
925990
window.reviewTransitions = [];

0 commit comments

Comments
 (0)