Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

fix(attachments): retry video/audio previews that stop receiving bytes

wlals08745fcd4f9d21e1
diff --git a/src/components/AttachmentGallery.test.ts b/src/components/AttachmentGallery.test.ts
index e3357d151a..19536e0bea 100644
--- a/src/components/AttachmentGallery.test.ts
+++ b/src/components/AttachmentGallery.test.ts
@@ -60,7 +60,7 @@ describe("audio attachments", () => {
const signal = new AbortController().signal;
const blob = await loadMessageAudio(clip, message, signal);
expect(fetcher).toHaveBeenCalledWith("/api/threads/thread%2Fone/messages/message%20two/file", {
- method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ path: clip.path }), signal,
+ method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ path: clip.path }), signal: expect.any(AbortSignal),
});
expect(blob.type).toBe("audio/mpeg");
expect(await blob.text()).toBe("audio bytes");
@@ -178,7 +178,7 @@ describe("explicit local video preview", () => {
const signal = new AbortController().signal;
const blob = await loadMessageVideo(file, message, signal);
expect(fetcher).toHaveBeenCalledWith("/api/threads/thread%2Fone/messages/message%20two/file", {
- method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ path: file.path }), signal,
+ method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ path: file.path }), signal: expect.any(AbortSignal),
});
expect(blob.type).toBe("video/mp4");
expect(await blob.text()).toBe("video bytes");
@@ -221,4 +221,42 @@ describe("explicit local video preview", () => {
await expect(loadMessageVideo(file, message, request.signal)).rejects.toMatchObject({ name: "AbortError" });
expect(cancel).toHaveBeenCalledOnce();
});
+
+ it("retries a download that stops sending bytes instead of loading forever", async () => {
+ vi.useFakeTimers();
+ try {
+ const stuck = (signal: AbortSignal) => new Response(new ReadableStream<Uint8Array>({
+ start(controller) {
+ controller.enqueue(new Uint8Array([1]));
+ signal.addEventListener("abort", () => controller.error(new DOMException("Aborted", "AbortError")));
+ },
+ }), { headers: { "content-type": "video/mp4" } });
+ const fetcher = vi.fn(async (_url: string, init: RequestInit) => fetcher.mock.calls.length === 1
+ ? stuck(init.signal!)
+ : new Response("video bytes", { headers: { "content-type": "video/mp4" } }));
+ vi.stubGlobal("fetch", fetcher);
+ const pending = loadMessageVideo(file, message, new AbortController().signal);
+ await vi.advanceTimersByTimeAsync(15_000);
+ expect(await (await pending).text()).toBe("video bytes");
+ expect(fetcher).toHaveBeenCalledTimes(2);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("gives up with a retryable error after repeated stalls", async () => {
+ vi.useFakeTimers();
+ try {
+ const fetcher = vi.fn((_url: string, init: RequestInit) => new Promise<Response>((_resolve, reject) => {
+ init.signal!.addEventListener("abort", () => reject(new DOMException("Aborted", "AbortError")));
+ }));
+ vi.stubGlobal("fetch", fetcher);
+ const pending = expect(loadMessageVideo(file, message, new AbortController().signal)).rejects.toThrow("cannot be played");
+ await vi.advanceTimersByTimeAsync(45_000);
+ await pending;
+ expect(fetcher).toHaveBeenCalledTimes(3);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
});
diff --git a/src/components/AttachmentGallery.tsx b/src/components/AttachmentGallery.tsx
index 1872ed7514..f1de8912c9 100644
--- a/src/components/AttachmentGallery.tsx
+++ b/src/components/AttachmentGallery.tsx
@@ -124,13 +124,59 @@ export function MessageAttachmentGallery({ text, attachments = NO_GENERATED_ATTA
return <AttachmentGallery images={attached.images} files={files} message={message} eager={eager} className={className} />;
}
+const MEDIA_STALL_MS = 15_000;
+const MEDIA_STALL_RETRIES = 2;
+
+/**
+ * A proxy or tailnet hiccup can leave a response open with no bytes moving, which would spin "Loading" forever.
+ * Abort an attempt after a quiet stretch and start a fresh request; the caller's signal still cancels everything.
+ */
+async function withStallRetry<T>(
+ signal: AbortSignal,
+ unavailable: string,
+ load: (signal: AbortSignal, progress: () => void) => Promise<T>,
+): Promise<T> {
+ for (let attempt = 0; ; attempt++) {
+ if (signal.aborted) throw new DOMException("Aborted", "AbortError");
+ const controller = new AbortController();
+ let stalled = false;
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const progress = () => {
+ clearTimeout(timer);
+ timer = setTimeout(() => { stalled = true; controller.abort(); }, MEDIA_STALL_MS);
+ };
+ const forward = () => controller.abort();
+ signal.addEventListener("abort", forward, { once: true });
+ progress();
+ try {
+ return await load(controller.signal, progress);
+ } catch (reason) {
+ if (!stalled || signal.aborted) throw reason;
+ if (attempt >= MEDIA_STALL_RETRIES) throw new Error(unavailable);
+ } finally {
+ clearTimeout(timer);
+ signal.removeEventListener("abort", forward);
+ }
+ }
+}
+
/** Security: the server's MIME is required as well as the filename, so arbitrary bytes never become UI. */
-export async function loadMessageVideo(
+export function loadMessageVideo(
+ file: GalleryFile,
+ message: MessageAttachmentContext,
+ signal: AbortSignal,
+): Promise<Blob> {
+ return withStallRetry(signal, t("attach.videoUnavailable"), (attempt, progress) => readMessageVideo(file, message, attempt, progress));
+}
+
+async function readMessageVideo(
file: GalleryFile,
message: MessageAttachmentContext,
signal: AbortSignal,
+ progress: () => void,
): Promise<Blob> {
const response = await requestMessageFile(file.path, message, signal);
+ progress();
const mime = response.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase();
if (!mime || !["video/mp4", "video/webm", "video/quicktime", "video/x-m4v"].includes(mime)) {
await response.body?.cancel();
@@ -154,6 +200,7 @@ export async function loadMessageVideo(
size += value.byteLength;
if (size > FILE_MAX_BYTES) throw new Error(t("attach.fileTooLarge"));
chunks.push(new Uint8Array(value));
+ progress();
}
} finally {
await reader.cancel().catch(() => undefined);
@@ -245,12 +292,22 @@ function VideoAttachment({ file, message }: { file: GalleryFile; message: Messag
const AUDIO_MIMES = ["audio/mpeg", "audio/mp4", "audio/x-m4a", "audio/aac", "audio/wav", "audio/x-wav", "audio/wave", "audio/ogg", "audio/opus", "audio/flac", "audio/x-flac"];
-export async function loadMessageAudio(
+export function loadMessageAudio(
+ file: GalleryFile,
+ message: MessageAttachmentContext,
+ signal: AbortSignal,
+): Promise<Blob> {
+ return withStallRetry(signal, t("attach.audioUnavailable"), (attempt, progress) => readMessageAudio(file, message, attempt, progress));
+}
+
+async function readMessageAudio(
file: GalleryFile,
message: MessageAttachmentContext,
signal: AbortSignal,
+ progress: () => void,
): Promise<Blob> {
const response = await requestMessageFile(file.path, message, signal);
+ progress();
const mime = response.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase();
if (!mime || !AUDIO_MIMES.includes(mime)) {
await response.body?.cancel();
@@ -273,6 +330,7 @@ export async function loadMessageAudio(
size += value.byteLength;
if (size > FILE_MAX_BYTES) throw new Error(t("attach.fileTooLarge"));
chunks.push(new Uint8Array(value));
+ progress();
}
} finally {
await reader.cancel().catch(() => undefined);