diff --git a/CHANGELOG.md b/CHANGELOG.md index f25ddce22..eec3876f1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,8 @@ All notable changes to **omp-web** (`@kahme247/ompweb`) are documented in this f ### Fixes & Improvements +- **Uploads larger than 10 MB failed with a body-parse 500.** Next reads and buffers every proxied request body up to `experimental.proxyClientMaxBodySize` (10 MB by default) before the proxy can answer, so a 25 MB per-file upload was truncated and the route answered `500 "Failed to parse body as FormData."`. The buffer now covers exactly one upload request (the per-file cap plus multipart framing), derived from shared constants in `lib/upload-limits.ts` so it cannot grow with the selection: the web uploader sends a larger selection as batches of at most one request's worth, and the route's own per-file and per-request 413 checks stay authoritative inside that buffer. +- **The first update check after a cold start no longer reports a failure.** `omp update --check` regularly needs ~20 s on a cold start (Node CLI startup plus network) and the 15 s timeout aborted it; it is now 30 s. - **In-app updates work when ompweb runs as a systemd service.** The update worker ran inside the service's cgroup, so stopping the server killed the worker too: nothing was installed, the service could stay down (`Restart=on-failure` does not restart a clean SIGTERM exit), and every page load reopened the update dialog at "Stop ompweb-managed sessions". The worker now runs in its own transient scope (`systemd-run --scope`) and stops, updates and starts the unit through `systemctl`, starting it again if the install fails. - **An update whose worker died is reported as failed.** A running update whose worker process is gone, or whose lease has expired, now becomes a failed attempt the dialog can show and clean up, instead of waiting forever. diff --git a/app/api/files/[...path]/route.ts b/app/api/files/[...path]/route.ts index 4f59f883e..13041fc4a 100644 --- a/app/api/files/[...path]/route.ts +++ b/app/api/files/[...path]/route.ts @@ -23,6 +23,11 @@ import { validateUploadFileNames, } from "@/lib/file-upload"; import { parseFormDataWithinLimit, parseJsonWithinLimit, RequestBodyTooLargeError } from "@/lib/bounded-form-data"; +import { + MAX_UPLOAD_FILE_BYTES, + MAX_UPLOAD_REQUEST_BYTES, + MAX_UPLOAD_REQUEST_FILE_BYTES, +} from "@/lib/upload-limits"; const IGNORED_NAMES = new Set([ "node_modules", ".git", ".next", "dist", "build", "__pycache__", @@ -35,10 +40,6 @@ const IGNORED_SUFFIXES = [".pyc"]; const FILE_REQUEST_TYPES = ["list", "read", "download", "meta", "preview"] as const; type FileRequestType = typeof FILE_REQUEST_TYPES[number]; const FILE_REQUEST_TYPE_SET = new Set(FILE_REQUEST_TYPES); -const MAX_UPLOAD_FILE_BYTES = 25 * 1024 * 1024; -const MAX_UPLOAD_TOTAL_BYTES = 100 * 1024 * 1024; -// Multipart boundaries and headers are not file bytes, but must be bounded too. -const MAX_UPLOAD_REQUEST_BYTES = MAX_UPLOAD_TOTAL_BYTES + 1024 * 1024; const MAX_UPLOAD_CHECK_REQUEST_BYTES = 1024 * 1024; const EXT_TO_LANGUAGE: Record = { @@ -159,7 +160,7 @@ export async function POST( formData = await parseFormDataWithinLimit(request, MAX_UPLOAD_REQUEST_BYTES); } catch (error) { if (error instanceof RequestBodyTooLargeError) { - return NextResponse.json({ error: "Uploads must total 100MB or less", code: "upload_total_too_large" }, { status: 413 }); + return NextResponse.json({ error: "Uploads must total 25MB or less per request", code: "upload_total_too_large" }, { status: 413 }); } throw error; } @@ -167,8 +168,10 @@ export async function POST( if (files.some((file) => file.size > MAX_UPLOAD_FILE_BYTES)) { return NextResponse.json({ error: "Each upload must be 25MB or smaller", code: "upload_file_too_large" }, { status: 413 }); } - if (files.reduce((total, file) => total + file.size, 0) > MAX_UPLOAD_TOTAL_BYTES) { - return NextResponse.json({ error: "Uploads must total 100MB or less", code: "upload_total_too_large" }, { status: 413 }); + // One request carries one batch: a larger selection arrives as several + // requests, so the pre-auth body buffer never has to hold all of it. + if (files.reduce((total, file) => total + file.size, 0) > MAX_UPLOAD_REQUEST_FILE_BYTES) { + return NextResponse.json({ error: "Uploads must total 25MB or less per request", code: "upload_total_too_large" }, { status: 413 }); } const fileNames = files.map((file) => file.name); const validationError = validateUploadFileNames(fileNames); diff --git a/components/FileExplorer.tsx b/components/FileExplorer.tsx index d257878f2..be1f4f4e2 100644 --- a/components/FileExplorer.tsx +++ b/components/FileExplorer.tsx @@ -28,6 +28,7 @@ import { } from "@/lib/file-paths"; import type { GitFileStatus, GitFileStatusKind, GitStatusResponse } from "@/lib/git-types"; import { MAX_RESULT_LIMIT, type FileIndexEntry } from "@/lib/file-fuzzy"; +import { batchUploadFiles } from "@/lib/upload-limits"; import { buildSearchRows } from "@/lib/search-results"; interface FileEntry { @@ -879,22 +880,54 @@ export const FileExplorer = forwardRef(function FileE setUploadProgress(0); setUploadPhase("uploading"); + // The server buffers one request body before it authenticates it, so a + // selection is uploaded as batches of at most MAX_UPLOAD_REQUEST_FILE_BYTES + // and the selection total (MAX_UPLOAD_TOTAL_BYTES) never reaches the wire at once. + const batches = batchUploadFiles(files); + const totalBytes = files.reduce((total, file) => total + file.size, 0); + const summary: UploadSummary = { uploaded: [], skipped: [], errors: [] }; + const merge = (data: UploadResponse) => { + summary.uploaded.push(...(data.uploaded ?? [])); + summary.skipped.push(...(data.skipped ?? [])); + summary.errors.push(...(data.errors ?? [])); + }; + let sentBytes = 0; + let sentFiles = 0; + try { - const { status, data } = await uploadFiles(cwd, files, strategy, setUploadProgress); - if (status === 409 && data.conflicts?.length) { - setPendingConflict({ - files, - conflicts: data.conflicts, - nonReplaceable: data.nonReplaceable ?? [], + for (const batch of batches) { + const batchBytes = batch.reduce((total, file) => total + file.size, 0); + const { status, data } = await uploadFiles(cwd, batch, strategy, (percent) => { + const inFlight = Math.round((batchBytes * percent) / 100); + setUploadProgress(totalBytes > 0 + ? Math.min(99, Math.round(((sentBytes + inFlight) / totalBytes) * 100)) + : Math.min(99, percent)); }); - return; - } - if (status < 200 || status >= 300) { - throw new Error(data.error ?? translate("fileExplorer.uploadFailed", { status })); + if (status === 409 && data.conflicts?.length) { + // The dialog keeps its meaning. Batches already accepted stay + // uploaded, so only the rest of the selection is asked about again. + merge(data); + applyUploadResult(summary); + setPendingConflict({ + files: files.slice(sentFiles), + conflicts: data.conflicts, + nonReplaceable: data.nonReplaceable ?? [], + }); + return; + } + if (status < 200 || status >= 300) { + throw new Error(data.error ?? translate("fileExplorer.uploadFailed", { status })); + } + merge(data); + sentBytes += batchBytes; + sentFiles += batch.length; + setUploadProgress(totalBytes > 0 ? Math.round((sentBytes / totalBytes) * 100) : 100); } setUploadProgress(100); - applyUploadResult(data); + applyUploadResult(summary); } catch (uploadFailure) { + // Whatever earlier batches already wrote stays visible next to the error. + if (summary.uploaded.length > 0 || summary.skipped.length > 0 || summary.errors.length > 0) applyUploadResult(summary); setUploadError(uploadFailure instanceof Error ? uploadFailure.message : String(uploadFailure)); } finally { setUploadPhase("idle"); diff --git a/lib/api-contract.test.mjs b/lib/api-contract.test.mjs index f5b3298e9..8d472c90f 100644 --- a/lib/api-contract.test.mjs +++ b/lib/api-contract.test.mjs @@ -179,8 +179,8 @@ test("agent routes bound requests with the shared attachment budget", async () = assert.match(route, /parseJsonWithinLimit<[^>]*>\(req, MAX_AGENT_COMMAND_REQUEST_BYTES\)/); assert.doesNotMatch(route, /REQUEST_BYTES = /); } - // Below Next's 10 MB proxy buffering boundary, with base64 headroom for the - // aggregate image cap. + // With base64 headroom for the aggregate image cap; the proxy buffer limit + // (`next.config.ts`) is far above this by design. assert.match(budget, /MAX_AGENT_COMMAND_REQUEST_BYTES = 8 \* 1024 \* 1024/); assert.match(budget, /MAX_TOTAL_ATTACHED_IMAGE_BYTES = 5 \* 1024 \* 1024/); }); @@ -229,3 +229,35 @@ test("new-session route never forwards a session id into the child RPC", async ( const route = await readFile(new URL("../app/api/agent/new/route.ts", import.meta.url), "utf8"); assert.match(route, /delete promptCommand\.sessionId/); }); + +test("the proxy body limit stays just above one upload request, never a whole selection", async () => { + const config = await readFile(new URL("../next.config.ts", import.meta.url), "utf8"); + const route = await readFile(new URL("../app/api/files/[...path]/route.ts", import.meta.url), "utf8"); + const limits = await readFile(new URL("./upload-limits.ts", import.meta.url), "utf8"); + + // Next buffers every proxied request body up to this limit *before* the proxy + // can answer 401, so it is the unauthenticated memory budget. It must cover + // one request (a per-file cap plus multipart framing) and must not grow with + // the selection: clients send a selection in batches of at most + // MAX_UPLOAD_REQUEST_FILE_BYTES. + assert.match(config, /proxyClientMaxBodySize: MAX_UPLOAD_REQUEST_BYTES/); + assert.match(config, /import \{ MAX_UPLOAD_REQUEST_BYTES \} from "\.\/lib\/upload-limits"/); + assert.match(limits, /MAX_UPLOAD_FILE_BYTES = 25 \* 1024 \* 1024/); + assert.match(limits, /MAX_UPLOAD_REQUEST_FILE_BYTES = 25 \* 1024 \* 1024/); + assert.match(limits, /MAX_UPLOAD_TOTAL_BYTES = 100 \* 1024 \* 1024/); + assert.match(limits, /MAX_UPLOAD_REQUEST_BYTES = MAX_UPLOAD_REQUEST_FILE_BYTES \+ MAX_UPLOAD_MULTIPART_OVERHEAD_BYTES/); + + // The route keeps the per-file and per-request policy authoritative, reads the + // shared constants instead of a second copy that can drift, and its clean 413 + // fires inside the proxy's buffer rather than after a silent truncation. + assert.match(route, /from "@\/lib\/upload-limits"/); + assert.match(route, /parseFormDataWithinLimit\(request, MAX_UPLOAD_REQUEST_BYTES\)/); + assert.match(route, /files\.reduce\(\(total, file\) => total \+ file\.size, 0\) > MAX_UPLOAD_REQUEST_FILE_BYTES/); + assert.doesNotMatch(route, /MAX_UPLOAD_TOTAL_BYTES/); + assert.doesNotMatch(route, /const MAX_UPLOAD_(FILE|TOTAL|REQUEST)_BYTES = /); + + // Both clients batch with the same cap; a client that sent a selection at once + // would hit the proxy's truncation instead of the route's 413. + const webUpload = await readFile(new URL("../components/FileExplorer.tsx", import.meta.url), "utf8"); + assert.match(webUpload, /batchUploadFiles\(files\)/); +}); diff --git a/lib/image-attachments.ts b/lib/image-attachments.ts index 3903d30bb..25ecfc927 100644 --- a/lib/image-attachments.ts +++ b/lib/image-attachments.ts @@ -1,11 +1,10 @@ /** * The attachment budget shared by the composer and the agent routes. * - * Next 16.3 buffers a request body in `proxy.ts` before the route handler runs - * and rejects anything past its 10 MB default, so the whole JSON command has to - * stay under that ceiling. Everything below is derived from it: the request cap - * leaves margin under the proxy boundary, and the aggregate image cap leaves - * room for base64's 4/3 inflation plus the prompt text inside the request cap. + * Next 16.3 buffers a request body in `proxy.ts` before the route handler runs; + * the ceiling is `experimental.proxyClientMaxBodySize` (`next.config.ts`). This + * JSON command stays far below it anyway: the aggregate image cap leaves room + * for base64's 4/3 inflation plus the prompt text inside the request cap. * * Browser-safe by construction (no Node imports): the composer preflights the * exact prompt it is about to send with the same numbers the routes enforce. diff --git a/lib/omp/updates.ts b/lib/omp/updates.ts index 992082a2f..763d297d1 100644 --- a/lib/omp/updates.ts +++ b/lib/omp/updates.ts @@ -11,7 +11,9 @@ export interface OmpUpdateStatus { updatesDisabled?: boolean; } -export const OMP_UPDATE_CHECK_TIMEOUT_MS = 15_000; +// A cold `omp update --check` on Windows regularly needs ~20 s (Node CLI startup +// plus network); 15 s made the very first check after boot fail with update_failed. +export const OMP_UPDATE_CHECK_TIMEOUT_MS = 30_000; export const OMP_UPDATE_CHECK_TTL_MS = 60 * 60 * 1000; /** Run a raw `omp update [args]` subcommand. Install durability diff --git a/lib/upload-limits.test.mjs b/lib/upload-limits.test.mjs new file mode 100644 index 000000000..9a7933438 --- /dev/null +++ b/lib/upload-limits.test.mjs @@ -0,0 +1,56 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { createJiti } from "jiti"; + +const jiti = createJiti(import.meta.url, { tsconfigPaths: true }); +const limits = await jiti.import("./upload-limits.ts"); + +const MiB = 1024 * 1024; + +test("one request fits the pre-auth body buffer; a selection does not", () => { + assert.equal(limits.MAX_UPLOAD_FILE_BYTES, 25 * MiB); + assert.equal(limits.MAX_UPLOAD_REQUEST_FILE_BYTES, 25 * MiB); + assert.equal(limits.MAX_UPLOAD_TOTAL_BYTES, 100 * MiB); + assert.equal( + limits.MAX_UPLOAD_REQUEST_BYTES, + limits.MAX_UPLOAD_REQUEST_FILE_BYTES + limits.MAX_UPLOAD_MULTIPART_OVERHEAD_BYTES, + ); + // A full per-file upload plus multipart framing must reach the route intact. + assert.ok(limits.MAX_UPLOAD_REQUEST_BYTES >= limits.MAX_UPLOAD_FILE_BYTES + limits.MAX_UPLOAD_MULTIPART_OVERHEAD_BYTES); + // The buffer must stay far below a whole selection: Next reads it before auth. + assert.ok(limits.MAX_UPLOAD_REQUEST_BYTES <= limits.MAX_UPLOAD_TOTAL_BYTES / 3); +}); + +test("a 60 MB selection is sent as three bounded requests", () => { + const files = [{ size: 20 * MiB }, { size: 20 * MiB }, { size: 20 * MiB }]; + assert.deepEqual(limits.batchUploadFiles(files).map((batch) => batch.length), [1, 1, 1]); +}); + +test("batching keeps every file, in order, and never exceeds the per-request cap", () => { + const files = [ + { size: 10 * MiB }, + { size: 10 * MiB }, + { size: 6 * MiB }, + { size: 30 * MiB }, + { size: 1 }, + ]; + const batches = limits.batchUploadFiles(files); + assert.deepEqual(batches.map((batch) => batch.map((file) => file.size)), [ + [10 * MiB, 10 * MiB], + [6 * MiB], + // A single file above the cap keeps its own request: the server answers its + // per-file 413 instead of the batch silently dropping it. + [30 * MiB], + [1], + ]); + assert.deepEqual(batches.flat(), files); + for (const batch of batches) { + const total = batch.reduce((sum, file) => sum + file.size, 0); + assert.ok(batch.length === 1 || total <= limits.MAX_UPLOAD_REQUEST_FILE_BYTES, `batch of ${total} bytes`); + } +}); + +test("empty and empty-file selections produce no request", () => { + assert.deepEqual(limits.batchUploadFiles([]), []); + assert.deepEqual(limits.batchUploadFiles([{ size: 0 }, { size: 0 }]).map((batch) => batch.length), [2]); +}); diff --git a/lib/upload-limits.ts b/lib/upload-limits.ts new file mode 100644 index 000000000..99635bdae --- /dev/null +++ b/lib/upload-limits.ts @@ -0,0 +1,50 @@ +/** + * Wire limits for `POST /api/files/[...path]?type=upload`, shared by the route, + * `next.config.ts` and the clients (web `components/FileExplorer.tsx`, the + * Android `FileTransfer`). + * + * `experimental.proxyClientMaxBodySize` is the pre-auth body buffer: Next reads + * and buffers every proxied request body up to that size *before* `proxy.ts` + * can answer 401, so it is an unauthenticated memory budget (an anonymous + * `POST` of N bytes costs N bytes of server memory until the body is read). + * It therefore sits just above [MAX_UPLOAD_FILE_BYTES] + multipart framing, not + * above a whole selection: one request carries at most + * [MAX_UPLOAD_REQUEST_FILE_BYTES] of file bytes, and a larger selection is + * uploaded as several requests (`batchUploadFiles`). [MAX_UPLOAD_TOTAL_BYTES] + * is the budget of one such selection across those requests; the server cannot + * see across requests, so each side enforces its half. + */ +export const MAX_UPLOAD_FILE_BYTES = 25 * 1024 * 1024; +/** File bytes one request may carry (also enforced by the route, per request). */ +export const MAX_UPLOAD_REQUEST_FILE_BYTES = 25 * 1024 * 1024; +/** One user selection uploads at most this much, in `MAX_UPLOAD_REQUEST_FILE_BYTES` batches. */ +export const MAX_UPLOAD_TOTAL_BYTES = 100 * 1024 * 1024; +/** Multipart boundaries, part headers and file names are not file bytes, but must be bounded too. */ +export const MAX_UPLOAD_MULTIPART_OVERHEAD_BYTES = 1024 * 1024; +/** Body limit of one upload request: the route's parse cap and the proxy's pre-auth buffer. */ +export const MAX_UPLOAD_REQUEST_BYTES = MAX_UPLOAD_REQUEST_FILE_BYTES + MAX_UPLOAD_MULTIPART_OVERHEAD_BYTES; + +/** + * Split one selection into requests of at most `maxBytes` file bytes. A single + * file larger than the cap keeps a batch of its own: the server answers its + * unchanged per-file 413 instead of the batch silently dropping it. + */ +export function batchUploadFiles( + files: readonly T[], + maxBytes: number = MAX_UPLOAD_REQUEST_FILE_BYTES, +): T[][] { + const batches: T[][] = []; + let current: T[] = []; + let currentBytes = 0; + for (const file of files) { + if (current.length > 0 && currentBytes + file.size > maxBytes) { + batches.push(current); + current = []; + currentBytes = 0; + } + current.push(file); + currentBytes += file.size; + } + if (current.length > 0) batches.push(current); + return batches; +} diff --git a/next.config.ts b/next.config.ts index 021b63d53..cd19b35e8 100644 --- a/next.config.ts +++ b/next.config.ts @@ -4,6 +4,7 @@ import { readFileSync } from "fs"; import { dirname, join } from "path"; import { fileURLToPath } from "url"; import { PHASE_DEVELOPMENT_SERVER } from "next/constants.js"; +import { MAX_UPLOAD_REQUEST_BYTES } from "./lib/upload-limits"; // The WASM SWC build used on wasm-first targets (e.g. aarch64-linux-android) // does not transpile ESM to CJS, so this file loads as ESM there and @@ -28,6 +29,14 @@ const eventStreamWorkerVersion = createHash("sha256") const nextConfig = (phase: string): NextConfig => { const isDev = phase === PHASE_DEVELOPMENT_SERVER; return { + experimental: { + // Next buffers every proxied request body up to this many bytes *before* + // the proxy can answer 401, so this is an unauthenticated memory budget. + // It must cover one upload request (a per-file cap plus multipart + // framing) but must not grow with the selection: clients upload a larger + // selection as batches, each at most MAX_UPLOAD_REQUEST_FILE_BYTES. + proxyClientMaxBodySize: MAX_UPLOAD_REQUEST_BYTES, + }, // Keep standalone/server tracing inside this package. Without this explicit // root, Next can choose a parent lockfile on Windows and traverse protected // user-profile junctions while compiling.