Skip to content

YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context

fix(feedback): stop send-logs hanging forever in sending state (#5364)

Ansh Grover756c32926238
diff --git a/apps/screenpipe-app-tauri/components/share-logs-button.test.tsx b/apps/screenpipe-app-tauri/components/share-logs-button.test.tsx
index f2be09ec7..3182c50eb 100644
--- a/apps/screenpipe-app-tauri/components/share-logs-button.test.tsx
+++ b/apps/screenpipe-app-tauri/components/share-logs-button.test.tsx
@@ -6,7 +6,7 @@ import React from "react";
import "@testing-library/jest-dom/vitest";
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { ShareLogsButton } from "./share-logs-button";
+import { ShareLogsButton, withTimeout } from "./share-logs-button";
const {
toastMock,
@@ -20,6 +20,7 @@ const {
toastMock: vi.fn(),
commandsMock: {
getLogFiles: vi.fn(),
+ readLogTail: vi.fn(),
redactPiiForFeedback: vi.fn(),
uploadFileToS3: vi.fn(),
},
@@ -197,6 +198,7 @@ describe("ShareLogsButton attachments", () => {
fsMock.stat.mockResolvedValue({ size: 3 });
loadAllConversationsMock.mockResolvedValue([]);
commandsMock.getLogFiles.mockResolvedValue({ status: "ok", data: [] });
+ commandsMock.readLogTail.mockResolvedValue({ status: "ok", data: "" });
commandsMock.redactPiiForFeedback.mockResolvedValue({
status: "ok",
data: "redacted",
@@ -212,6 +214,7 @@ describe("ShareLogsButton attachments", () => {
vi.restoreAllMocks();
toastMock.mockReset();
commandsMock.getLogFiles.mockReset();
+ commandsMock.readLogTail.mockReset();
commandsMock.redactPiiForFeedback.mockReset();
commandsMock.uploadFileToS3.mockReset();
});
@@ -598,4 +601,102 @@ describe("ShareLogsButton attachments", () => {
);
expect(sendButton()).toBeEnabled();
});
+
+ it("reads log tails via rust instead of pulling whole files into the webview", async () => {
+ stubServer({ videoPath: "logs/machine/m1/t_video.mp4" });
+ commandsMock.getLogFiles.mockResolvedValue({
+ status: "ok",
+ data: [{ name: "screenpipe.log", path: "/logs/screenpipe.log", modified_at: 1 }],
+ });
+ commandsMock.readLogTail.mockResolvedValue({ status: "ok", data: "tail" });
+ render(<ShareLogsButton />);
+
+ fireEvent.click(sendButton());
+
+ await waitFor(() =>
+ expect(toastMock).toHaveBeenCalledWith(
+ expect.objectContaining({ title: "feedback sent" }),
+ ),
+ );
+ expect(commandsMock.readLogTail).toHaveBeenCalledWith(
+ "/logs/screenpipe.log",
+ 100 * 1024,
+ );
+ });
+
+ it("still sends the report when the log-file listing never settles", async () => {
+ vi.useFakeTimers();
+ stubServer({ videoPath: "logs/machine/m1/t_video.mp4" });
+ // A stalled filesystem/IPC call: the Tauri command never resolves.
+ commandsMock.getLogFiles.mockReturnValue(new Promise(() => {}));
+ render(<ShareLogsButton />);
+
+ fireEvent.click(sendButton());
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(0);
+ });
+ // still waiting on the hung listing
+ expect(screen.getByRole("button", { name: /sending/i })).toBeDisabled();
+
+ // 30s: listing times out, and the send proceeds without log files
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(31_000);
+ });
+
+ expect(toastMock).toHaveBeenCalledWith(
+ expect.objectContaining({ title: "feedback sent" }),
+ );
+ vi.useRealTimers();
+ });
+
+ it("recovers from a hung request instead of sticking on sending forever (#5360)", async () => {
+ vi.useFakeTimers();
+ // A stalled connection: fetch never settles, but honors abort like the
+ // real implementation does.
+ const hungFetch = vi.fn(
+ (_url: string, init?: RequestInit) =>
+ new Promise((_, reject) => {
+ init?.signal?.addEventListener("abort", () =>
+ reject(new DOMException("Aborted", "AbortError")),
+ );
+ }),
+ );
+ vi.stubGlobal("fetch", hungFetch);
+ render(<ShareLogsButton />);
+
+ fireEvent.click(sendButton());
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(0);
+ });
+ // stuck mid-send: button shows the sending state and is disabled
+ expect(screen.getByRole("button", { name: /sending/i })).toBeDisabled();
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(31_000);
+ });
+
+ expect(toastMock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ title: "sharing failed",
+ description: expect.stringContaining("timed out"),
+ }),
+ );
+ expect(sendButton()).toBeEnabled();
+ vi.useRealTimers();
+ });
+});
+
+describe("withTimeout", () => {
+ it("rejects with a readable error once the deadline passes", async () => {
+ vi.useFakeTimers();
+ const hung = withTimeout(new Promise(() => {}), 1_000, "test call");
+ const assertion = expect(hung).rejects.toThrow("test call timed out");
+ await vi.advanceTimersByTimeAsync(1_001);
+ await assertion;
+ vi.useRealTimers();
+ });
+
+ it("passes through the result when the promise settles in time", async () => {
+ await expect(withTimeout(Promise.resolve(7), 1_000, "x")).resolves.toBe(7);
+ });
});
diff --git a/apps/screenpipe-app-tauri/components/share-logs-button.tsx b/apps/screenpipe-app-tauri/components/share-logs-button.tsx
index 38d16e99e..b48ad0d4d 100644
--- a/apps/screenpipe-app-tauri/components/share-logs-button.tsx
+++ b/apps/screenpipe-app-tauri/components/share-logs-button.tsx
@@ -14,7 +14,7 @@ import {
Play,
Plus,
} from "lucide-react";
-import { readTextFile, readFile } from "@tauri-apps/plugin-fs";
+import { readFile } from "@tauri-apps/plugin-fs";
import { open as openFileDialog } from "@tauri-apps/plugin-dialog";
import { getCurrentWebview } from "@tauri-apps/api/webview";
import { commands } from "@/lib/utils/tauri";
@@ -72,6 +72,55 @@ async function compressImageFile(file: File): Promise<string> {
return canvas.toDataURL("image/jpeg", 0.8);
}
+// Every await in sendLogs must be bounded: one stalled call with no timeout
+// leaves `phase` stuck on "sending" forever (#5360).
+const TIMEOUT_API_MS = 30_000; // JSON endpoints and IPC listings
+const TIMEOUT_UPLOAD_MS = 60_000; // log text / screenshot PUTs
+const TIMEOUT_VIDEO_MS = 300_000; // must cover the Rust retry budget (280s)
+const TIMEOUT_REDACT_MS = 60_000; // must exceed Rust's 45s enclave budget
+// Backstop above the sum of all per-step budgets, so a step added later
+// without its own deadline still can't strand the dialog.
+const TIMEOUT_SEND_TOTAL_MS = 720_000;
+
+function timeoutError(label: string): Error {
+ return new Error(`${label} timed out — check your connection and try again`);
+}
+
+async function fetchWithTimeout(
+ url: string,
+ init: RequestInit,
+ ms: number,
+ label: string,
+): Promise<Response> {
+ const controller = new AbortController();
+ const timer = setTimeout(() => controller.abort(), ms);
+ try {
+ return await fetch(url, { ...init, signal: controller.signal });
+ } catch (err) {
+ // Surface a readable message instead of the raw AbortError.
+ if (controller.signal.aborted) throw timeoutError(label);
+ throw err;
+ } finally {
+ clearTimeout(timer);
+ }
+}
+
+// For Tauri command awaits — the IPC promise can hang even when the Rust
+// side is internally bounded.
+export function withTimeout<T>(
+ promise: Promise<T>,
+ ms: number,
+ label: string,
+): Promise<T> {
+ let timer: ReturnType<typeof setTimeout>;
+ return Promise.race([
+ promise.finally(() => clearTimeout(timer)),
+ new Promise<never>((_, reject) => {
+ timer = setTimeout(() => reject(timeoutError(label)), ms);
+ }),
+ ]);
+}
+
// PUT with real upload progress — fetch() has no upload progress events, and
// the design shows a live "uploading… n%" line for dropped files.
function putWithProgress(
@@ -84,6 +133,7 @@ function putWithProgress(
const xhr = new XMLHttpRequest();
xhr.open("PUT", url);
xhr.setRequestHeader("Content-Type", contentType);
+ xhr.timeout = TIMEOUT_VIDEO_MS;
xhr.upload.onprogress = (e) => {
if (e.lengthComputable && onProgress)
onProgress(Math.round((e.loaded / e.total) * 100));
@@ -93,6 +143,7 @@ function putWithProgress(
? resolve()
: reject(new Error(`upload failed with status ${xhr.status}`));
xhr.onerror = () => reject(new Error("upload failed"));
+ xhr.ontimeout = () => reject(timeoutError("video upload"));
xhr.send(body);
});
}
@@ -462,35 +513,41 @@ export const ShareLogsButton = ({
const sendLogs = async () => {
setPhase("sending");
setUploadPct(null);
- try {
+ const send = async () => {
// Log files are best-effort. If none are found (fresh install, or an
// unreadable/misconfigured data dir — common on Windows), we still send
// the feedback text, screenshot, settings and console logs, which are
// valuable on their own. Bailing here silently was the original bug:
// clicking the button did nothing, with no toast and no spinner.
- const logFiles = await getLogFiles();
+ // Same policy for a hung listing: proceed without log files rather
+ // than fail the whole report.
+ const logFiles = await withTimeout(
+ getLogFiles(),
+ TIMEOUT_API_MS,
+ "log listing",
+ ).catch(() => [] as Awaited<ReturnType<typeof getLogFiles>>);
const BASE_URL = "https://screenpipe.com";
const identifier = settings.user?.id || machineId;
const type = settings.user?.id ? "user" : "machine";
+ // Tail-read in Rust: a runaway log can be hundreds of MB, and pulling
+ // it whole across IPC just to slice 100KB froze the dialog (#5360).
const MAX_LOG_SIZE = 100 * 1024;
const logContents = await Promise.all(
logFiles.slice(0, 5).map(async (file) => {
- try {
- const content = await readTextFile(file.path);
- const truncatedContent =
- content.length > MAX_LOG_SIZE
- ? `... [truncated, showing last ${MAX_LOG_SIZE / 1024}KB] ...\n` +
- content.slice(-MAX_LOG_SIZE)
- : content;
- return {
- name: file.name,
- content: truncatedContent,
- };
- } catch (e) {
- return { name: file.name, content: `[Error reading file: ${e}]` };
- }
+ const result = await withTimeout(
+ commands.readLogTail(file.path, MAX_LOG_SIZE),
+ TIMEOUT_REDACT_MS,
+ "log read",
+ ).catch((e) => ({ status: "error" as const, error: String(e) }));
+ return {
+ name: file.name,
+ content:
+ result.status === "ok"
+ ? result.data
+ : `[Error reading file: ${result.error}]`,
+ };
}),
);
@@ -501,17 +558,25 @@ export const ShareLogsButton = ({
);
} catch {}
- const signedRes = await fetch(`${BASE_URL}/api/logs`, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- identifier,
- type,
- // Ask for a video slot matching the attachment's real container so
- // QuickTime bytes are never stored under a `.mp4` key.
- video_ext: video?.source === "file" ? video.ext : "mp4",
- }),
- });
+ const signedRes = await fetchWithTimeout(
+ `${BASE_URL}/api/logs`,
+ {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ identifier,
+ type,
+ // Ask for a video slot matching the attachment's real container so
+ // QuickTime bytes are never stored under a `.mp4` key.
+ video_ext: video?.source === "file" ? video.ext : "mp4",
+ }),
+ },
+ TIMEOUT_API_MS,
+ "upload request",
+ );
+ if (!signedRes.ok) {
+ throw new Error(`upload request failed with status ${signedRes.status}`);
+ }
const {
data: {
@@ -527,7 +592,11 @@ export const ShareLogsButton = ({
let chatSection = "";
if (includeChatHistory) {
try {
- const conversations = await loadAllConversations();
+ const conversations = await withTimeout(
+ loadAllConversations(),
+ TIMEOUT_API_MS,
+ "chat history",
+ );
const MAX_CHAT_SIZE = 200 * 1024;
const recentConvs = conversations.slice(0, 5);
let chatData = "";
@@ -573,9 +642,10 @@ export const ShareLogsButton = ({
"\n\n=== Browser Console Logs ===\n" +
consoleLog;
- const redaction = await commands.redactPiiForFeedback(
- rawBundle,
- settingsJson,
+ const redaction = await withTimeout(
+ commands.redactPiiForFeedback(rawBundle, settingsJson),
+ TIMEOUT_REDACT_MS,
+ "redaction",
);
if (redaction.status !== "ok") {
// The command never returns Err (worst case is regex-only redaction), so
@@ -584,30 +654,41 @@ export const ShareLogsButton = ({
}
const redactedLogs = redaction.data;
- await fetch(signedUrl, {
- method: "PUT",
- body: redactedLogs,
- headers: { "Content-Type": "text/plain" },
- });
+ await fetchWithTimeout(
+ signedUrl,
+ {
+ method: "PUT",
+ body: redactedLogs,
+ headers: { "Content-Type": "text/plain" },
+ },
+ TIMEOUT_UPLOAD_MS,
+ "log upload",
+ );
const imageReady = image?.status === "ready" && image.dataUrl;
if (imageReady && signedUrlScreenshot) {
const response = await fetch(image.dataUrl!);
const blob = await response.blob();
- await fetch(signedUrlScreenshot, {
- method: "PUT",
- body: blob,
- headers: { "Content-Type": blob.type },
- });
+ await fetchWithTimeout(
+ signedUrlScreenshot,
+ {
+ method: "PUT",
+ body: blob,
+ headers: { "Content-Type": blob.type },
+ },
+ TIMEOUT_UPLOAD_MS,
+ "screenshot upload",
+ );
}
let videoUploaded = false;
if (video?.status === "ready" && signedUrlVideo) {
if (video.source === "recording" && video.localPath) {
- const videoResult = await commands.uploadFileToS3(
- video.localPath,
- signedUrlVideo,
+ const videoResult = await withTimeout(
+ commands.uploadFileToS3(video.localPath, signedUrlVideo),
+ TIMEOUT_VIDEO_MS,
+ "video upload",
);
if (videoResult.status !== "ok")
throw new Error("Failed to upload video");
@@ -643,22 +724,27 @@ export const ShareLogsButton = ({
const os_version = osVersion();
const app_version = await getVersion();
- const confirmResponse = await fetch(`${BASE_URL}/api/logs/confirm`, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- path,
- identifier,
- type,
- os,
- os_version,
- app_version,
- feedback_text: feedbackText,
- screenshot_url: imageReady ? screenshotPath : undefined,
- video_url: videoUploaded ? videoPath : undefined,
- screenpipe_id: settings.analyticsId,
- }),
- });
+ const confirmResponse = await fetchWithTimeout(
+ `${BASE_URL}/api/logs/confirm`,
+ {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ path,
+ identifier,
+ type,
+ os,
+ os_version,
+ app_version,
+ feedback_text: feedbackText,
+ screenshot_url: imageReady ? screenshotPath : undefined,
+ video_url: videoUploaded ? videoPath : undefined,
+ screenpipe_id: settings.analyticsId,
+ }),
+ },
+ TIMEOUT_API_MS,
+ "confirmation",
+ );
if (!confirmResponse.ok) {
throw new Error("failed to confirm log upload");
}
@@ -695,6 +781,9 @@ export const ShareLogsButton = ({
setPhase("idle");
if (onComplete) onComplete();
}, 1500);
+ };
+ try {
+ await withTimeout(send(), TIMEOUT_SEND_TOTAL_MS, "sending feedback");
} catch (err) {
console.error("log sharing failed:", err);
setPhase("idle");
diff --git a/apps/screenpipe-app-tauri/lib/utils/tauri.ts b/apps/screenpipe-app-tauri/lib/utils/tauri.ts
index 0f0eda1a3..8fcbd5e80 100644
--- a/apps/screenpipe-app-tauri/lib/utils/tauri.ts
+++ b/apps/screenpipe-app-tauri/lib/utils/tauri.ts
@@ -1632,6 +1632,14 @@ async readAudioExclusions() : Promise<Result<ExcludedApp[], string>> {
else return { status: "error", error: e as any };
}
},
+async readLogTail(path: string, maxBytes: number) : Promise<Result<string, string>> {
+ try {
+ return { status: "ok", data: await TAURI_INVOKE("read_log_tail", { path, maxBytes }) };
+} catch (e) {
+ if(e instanceof Error) throw e;
+ else return { status: "error", error: e as any };
+}
+},
/**
* Read a file for the viewer. Returns text for text-like files, a
* base64 data URL for images. Files larger than `MAX_VIEWER_FILE_BYTES`
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/log_files.rs b/apps/screenpipe-app-tauri/src-tauri/src/log_files.rs
index 4db4fe89c..e6bdba9dc 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/log_files.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/log_files.rs
@@ -21,6 +21,43 @@ pub struct LogFile {
pub modified_at: u64,
}
+#[tauri::command]
+#[specta::specta]
+pub async fn read_log_tail(path: String, max_bytes: u32) -> Result<String, String> {
+ read_tail(Path::new(&path), max_bytes as u64)
+ .await
+ .map_err(|e| e.to_string())
+}
+
+/// Read at most the last `max_bytes` of a file. Replaces reading whole log
+/// files into the webview, where a runaway multi-hundred-MB log froze the
+/// report dialog on "sending..." (#5360).
+pub(crate) async fn read_tail(path: &Path, max_bytes: u64) -> anyhow::Result<String> {
+ use tokio::io::{AsyncReadExt, AsyncSeekExt};
+
+ let mut file = tokio::fs::File::open(path).await?;
+ let len = file.metadata().await?.len();
+
+ let mut buf = Vec::with_capacity(len.min(max_bytes) as usize);
+ let truncated = len > max_bytes;
+ if truncated {
+ file.seek(std::io::SeekFrom::End(-(max_bytes as i64))).await?;
+ }
+ file.take(max_bytes).read_to_end(&mut buf).await?;
+
+ // Lossy: the seek may land mid-way through a multi-byte character.
+ let text = String::from_utf8_lossy(&buf).into_owned();
+ if truncated {
+ Ok(format!(
+ "... [truncated, showing last {}KB] ...\n{}",
+ max_bytes / 1024,
+ text
+ ))
+ } else {
+ Ok(text)
+ }
+}
+
#[tauri::command]
#[specta::specta]
pub async fn get_log_files(app: AppHandle) -> Result<Vec<LogFile>, String> {
@@ -238,6 +275,39 @@ mod tests {
);
}
+ #[tokio::test]
+ async fn read_tail_returns_small_file_whole() {
+ let dir = tempdir().unwrap();
+ let path = write_file(dir.path(), "small.log", "just a few lines").await;
+
+ let text = read_tail(&path, 100 * 1024).await.unwrap();
+
+ assert_eq!(text, "just a few lines");
+ }
+
+ #[tokio::test]
+ async fn read_tail_truncates_large_file_to_tail() {
+ let dir = tempdir().unwrap();
+ let contents = format!("{}END", "x".repeat(5000));
+ let path = write_file(dir.path(), "big.log", &contents).await;
+
+ let text = read_tail(&path, 1024).await.unwrap();
+
+ assert!(text.starts_with("... [truncated, showing last 1KB] ...\n"));
+ assert!(text.ends_with("END"));
+ // banner + exactly 1024 bytes of tail
+ let tail = text.split_once('\n').unwrap().1;
+ assert_eq!(tail.len(), 1024);
+ }
+
+ #[tokio::test]
+ async fn read_tail_missing_file_is_err() {
+ let dir = tempdir().unwrap();
+ let missing = dir.path().join("nope.log");
+
+ assert!(read_tail(&missing, 1024).await.is_err());
+ }
+
#[tokio::test]
async fn merges_logs_across_distinct_dirs() {
let a = tempdir().unwrap();
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/media_commands.rs b/apps/screenpipe-app-tauri/src-tauri/src/media_commands.rs
index 00bca66aa..ae709b70c 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/media_commands.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/media_commands.rs
@@ -107,6 +107,23 @@ fn get_mime_type(path: &str) -> String {
}
}
+/// Wall-clock budget for the whole retry loop. The webview abandons this
+/// command after 5 minutes; stopping earlier lets the last attempt report a
+/// real error instead of the UI racing us.
+const UPLOAD_OVERALL_BUDGET: Duration = Duration::from_secs(280);
+
+/// Slowest acceptable upload rate (~1 Mbps); below this the connection is
+/// treated as stalled, not slow.
+const MIN_UPLOAD_BYTES_PER_SEC: u64 = 125_000;
+
+/// Per-attempt deadline: sized to the file so a slow-but-progressing upload
+/// isn't killed by a flat timeout, floored at 60s, capped by what's left of
+/// the overall budget — the first attempt may use most of it.
+fn attempt_timeout(file_len: u64, remaining: Duration) -> Duration {
+ let size_aware = Duration::from_secs((file_len / MIN_UPLOAD_BYTES_PER_SEC).max(60));
+ size_aware.min(remaining)
+}
+
#[tauri::command]
#[specta::specta]
pub async fn upload_file_to_s3(file_path: &str, signed_url: &str) -> Result<bool, String> {
@@ -124,13 +141,25 @@ pub async fn upload_file_to_s3(file_path: &str, signed_url: &str) -> Result<bool
}
};
- let client = reqwest::Client::new();
+ // The default client has no timeout, so a stalled connection hung this
+ // command forever — the stuck "sending..." state in #5360. Requests get
+ // a size-aware deadline per attempt via `attempt_timeout`.
+ let client = reqwest::Client::builder()
+ .connect_timeout(Duration::from_secs(10))
+ .build()
+ .map_err(|e| e.to_string())?;
let max_retries = 3;
let mut attempt = 0;
let mut last_error = String::new();
+ let started = std::time::Instant::now();
while attempt < max_retries {
attempt += 1;
+ let remaining = UPLOAD_OVERALL_BUDGET.saturating_sub(started.elapsed());
+ if remaining < Duration::from_secs(5) {
+ last_error = format!("upload budget exhausted ({last_error})");
+ break;
+ }
debug!("Upload attempt {} of {}", attempt, max_retries);
match client
@@ -139,6 +168,7 @@ pub async fn upload_file_to_s3(file_path: &str, signed_url: &str) -> Result<bool
// without it videos land as application/octet-stream.
.header("Content-Type", get_mime_type(file_path))
.body(file_contents.clone())
+ .timeout(attempt_timeout(file_contents.len() as u64, remaining))
.send()
.await
{
@@ -177,10 +207,36 @@ pub async fn upload_file_to_s3(file_path: &str, signed_url: &str) -> Result<bool
#[cfg(test)]
mod tests {
- use super::{get_media_file, get_mime_type, upload_file_to_s3};
+ use super::{attempt_timeout, get_media_file, get_mime_type, upload_file_to_s3};
+ use std::time::Duration;
use wiremock::matchers::{body_bytes, method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};
+ #[test]
+ fn attempt_timeout_floors_small_files_at_60s() {
+ let remaining = Duration::from_secs(280);
+ assert_eq!(attempt_timeout(1024, remaining), Duration::from_secs(60));
+ }
+
+ #[test]
+ fn attempt_timeout_scales_with_file_size() {
+ // 25MB at the 125KB/s floor rate needs 200s — a flat 90s timeout
+ // would have killed this legitimate upload on every attempt.
+ let remaining = Duration::from_secs(280);
+ assert_eq!(
+ attempt_timeout(25_000_000, remaining),
+ Duration::from_secs(200)
+ );
+ }
+
+ #[test]
+ fn attempt_timeout_never_exceeds_remaining_budget() {
+ // A 50MB file wants 400s; the first attempt gets everything left of
+ // the overall budget instead.
+ let remaining = Duration::from_secs(280);
+ assert_eq!(attempt_timeout(50_000_000, remaining), remaining);
+ }
+
#[test]
fn maps_media_mime_types_and_preserves_fallbacks() {
for (path, expected) in [