Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 19 additions & 2 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -1275,11 +1275,28 @@ during the wait.
with 504 `upload_stalled` and forgets it without aborting it on the host, so
the tab's automatic resume continues it. Page navigation settles pending
WebSocket-upload promises before the worker's `bye`: a composer retained by
bfcache shows Retry after restoration, not a permanently uploading chip.
bfcache shows Retry after restoration, not a permanently uploading chip. That
failure (410) gives the chip a new upload id, so its Retry starts over and the
old id's pending cancel (worker, HTTP DELETE or host) can never delete it.
The daemon's `sweep` deletes staged files older than 24 h and aborts open uploads
idle (no start/write) over 24 h (`STAGED_MAX_AGE_MS`).
idle (no start/write) over 24 h (`STAGED_MAX_AGE_MS`): at start, on every
`uploadStart`, and every hour (`UPLOAD_SWEEP_INTERVAL_MS`). It never rejects
(a file it cannot delete is logged and tried again next sweep): a rejection
from its timer would stop the daemon, and one before `uploadStart` would fail
every new upload.
`uploadAttach` has a 10-minute op timeout (a 2 GiB EXDEV copy), not
`opTimeoutMs`.
- Cancels are durable (spec U4 "Durable cancel"): the tab always hands
`{op: "up_abort", id, host}` to the worker, which keeps it until the server
has it (link line until acked and resent on a resync; in `sse` mode a
`DELETE …?host=` with a 40 s deadline, retried until a 2xx or a 4xx other
than 408/429). Main keeps an `uploadAbort` its host could not take (503/504)
per host and resends it on that host's next hello (`onHostHello`). A Retry of
the same id supersedes it on every layer: a new `uploadStart` drops a kept
abort, an in-flight one that fails after the id is registered again is not
kept, and the worker drops its own pending cancel on a new upload of the id.
An id main does not register goes to the browser's `host`
if known. All of it is in memory: the hourly sweep is the backstop.
- Error codes: composer uploads use `upload_id_conflict` (another upload has
this id); `upload_conflict` stays the file manager's.
- SSE mode uses the same registry over HTTP (`/api/uploads`). Upload owner =
Expand Down
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ All notable changes to **omp-web** (`@kahme247/ompweb`) are documented in this f

### Fixes & Improvements

- **Removing an upload while offline still deletes it from the host.** A file you remove (or a finished upload you discard) is now deleted from the host's staging area once the browser, the server and the host can reach each other again, even if the browser connection dropped or the host was offline when you removed it. As a backstop, a running host now deletes staged files older than a day every hour, not only when it starts or receives a new upload, which also covers a removal that ompweb lost because it restarted while the host was offline.
- **Reconnecting uploads no longer leave Send blocked by a hanging retry.** The five-minute deadline stops an in-flight retry as well as its back-off, keeping staged bytes for Retry. A connection lost midway through an HTTP response resumes automatically, and tooltips identify network failures instead of showing only “Upload failed”.
- **Uploads no longer leave submitted messages or restored pages stuck.** A slow attachment copy keeps its session alive even after you switch chats. Commands that change Advisor wait until that preparation is dispatched before they may replace the session's child. Returning through browser Back/Forward shows Retry for an interrupted upload instead of leaving Send permanently blocked.
- **Attachment retries no longer accept missing files or stale upload errors.** An attachment removed or replaced by a directory is reported as missing before it is marked complete. Failed receipt writes leave the staged file available to retry without creating a duplicate, and cancellation cannot be undone by an attachment still finishing. Replies from earlier upload attempts no longer fail a newer Retry. Retrying also waits for failed-write cleanup, so an old attempt cannot delete the new attempt's staged files.
Expand Down
6 changes: 4 additions & 2 deletions app/api/uploads/[id]/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,10 @@ export async function PUT(req: Request, { params }: Params) {
}
}

/** DELETE /api/uploads/<id>: cancel the upload and delete its staged file. */
/** DELETE /api/uploads/<id>?host=<hostId>: cancel the upload and delete its staged file, now or on the host's next hello.
* `host` reaches an upload this server no longer registers. */
export async function DELETE(req: Request, { params }: Params) {
await abortUpload((await params).id, requestOwner(req));
const host = new URL(req.url).searchParams.get("host");
await abortUpload((await params).id, requestOwner(req), host && host.length <= 128 ? host : undefined);
return new Response(null, { status: 204 });
}
11 changes: 7 additions & 4 deletions components/ChatInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ import {
uploadRecovery,
type AttachedUpload,
} from "./ChatInput-uploads";
import { discardUpload, newUploadId, uploadFile, type UploadHandle } from "@/lib/event-stream";
import { discardUpload, newUploadId, uploadFile, UploadFailedError, type UploadHandle } from "@/lib/event-stream";
import { MAX_UPLOAD_BYTES, MAX_UPLOADS_PER_MESSAGE } from "@/lib/upload-limits";
import { LOCAL_HOST_ID } from "@/lib/project-ordering";
import {
Expand Down Expand Up @@ -628,7 +628,9 @@ export const ChatInput = memo(forwardRef<ChatInputHandle, Props>(function ChatIn
};
handle.promise.then(
() => settle({ status: "done", received: size, error: null }),
(error: unknown) => settle({ status: "error", error: uploadErrorMessage(error) }),
// 410: the worker already cancelled it on its host (the page went into the back/forward cache). A Retry under a
// new id starts over, so the cancel still pending for this one can never reach it.
(error: unknown) => settle({ status: "error", error: uploadErrorMessage(error), ...(error instanceof UploadFailedError && error.status === 410 ? { id: newUploadId() } : {}) }),
);
}, [patchUpload]);

Expand Down Expand Up @@ -844,8 +846,9 @@ export const ChatInput = memo(forwardRef<ChatInputHandle, Props>(function ChatIn
const removeUpload = useCallback((id: string) => {
const handle = uploadHandlesRef.current.get(id);
uploadHandlesRef.current.delete(id);
const hostId = attachedUploadsRef.current.find((upload) => upload.id === id)?.hostId;
if (handle) handle.abort();
else discardUpload(id);
else if (hostId !== undefined) discardUpload(id, hostId);
setAttachedUploads((prev) => {
const removed = prev.find((upload) => upload.id === id);
if (removed?.previewUrl) URL.revokeObjectURL(removed.previewUrl);
Expand Down Expand Up @@ -886,7 +889,7 @@ export const ChatInput = memo(forwardRef<ChatInputHandle, Props>(function ChatIn
const handle = uploadHandlesRef.current.get(id);
uploadHandlesRef.current.delete(id);
if (handle) handle.abort();
else discardUpload(id);
else discardUpload(id, upload.hostId);
setAttachedUploads((prev) => prev.filter((each) => each.id !== id));
setAttachedImages((prev) => [...prev, { data, mimeType: file.type, previewUrl, file }]);
} catch {
Expand Down
57 changes: 46 additions & 11 deletions components/ChatInput.uploads.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ function putOf(id) {
});
}

const deleted = (id) => requests.some((each) => each.method === "DELETE" && each.url === `/api/uploads/${id}`);
const deleted = (id) => requests.some((each) => each.method === "DELETE" && each.url === `/api/uploads/${id}?host=local`);
const chipOf = (name) => screen.getByText(name).parentElement;
const pressEnter = () => act(async () => { fireEvent.keyDown(screen.getByRole("textbox"), { key: "Enter" }); });

Expand Down Expand Up @@ -366,17 +366,25 @@ test("a draft keeps finished uploads only, and restores them as done chips", asy
assert.deepEqual(sent[0][2], [done.id]);
});

/** The tab's one shared-worker transport (a module singleton), faked once and switched to `ws` by each test. */
let fakePort;
function wsPort() {
if (!fakePort) {
globalThis.SharedWorker = class {
constructor() {
fakePort = this.port = { posted: [], postMessage(message) { this.posted.push(message); }, onmessage: null, start() {} };
}
};
openEventStream({ kind: "running" });
delete globalThis.SharedWorker;
}
fakePort.onmessage({ data: { transport: "ws" } });
return fakePort;
}

test("a stall the worker reports shows Reconnecting… and resumes by itself under the same id", async () => {
// The browser-link path: a fake shared worker, switched to `ws`, answers the upload with the worker's stall error.
let port;
globalThis.SharedWorker = class {
constructor() {
port = this.port = { posted: [], postMessage(message) { this.posted.push(message); }, onmessage: null, start() {} };
}
};
openEventStream({ kind: "running" });
delete globalThis.SharedWorker;
port.onmessage({ data: { transport: "ws" } });
// The browser-link path: the fake shared worker answers the upload with the worker's stall error.
const port = wsPort();
try {
const ref = renderComposer("uploads-stall", []);
await act(async () => { ref.current.addFiles([binaryFile("data.zip")]); });
Expand All @@ -400,3 +408,30 @@ test("a stall the worker reports shows Reconnecting… and resumes by itself und
port.onmessage({ data: { transport: "sse" } });
}
});

test("Retry after the page left the back/forward cache starts a new upload id: the old one's cancel can never delete it", async () => {
const port = wsPort();
try {
const ref = renderComposer("uploads-bfcache-retry", []);
await act(async () => { ref.current.addFiles([binaryFile("cached.zip")]); });
const first = await waitFor(() => {
const message = port.posted.find((each) => each.op === "upload" && each.name === "cached.zip");
assert.ok(message);
return message;
});
// pagehide: the worker cancelled it on the host (410, not resumable).
await act(async () => { port.onmessage({ data: { up: first.id, error: { status: 410, code: "upload_failed", message: "The upload failed. Retry it." } } }); });
const retry = await waitFor(() => within(chipOf("cached.zip")).getByRole("button", { name: RETRY }));
await act(async () => { retry.click(); });
const second = await waitFor(() => {
const starts = port.posted.filter((each) => each.op === "upload" && each.name === "cached.zip");
assert.equal(starts.length, 2);
return starts[1];
});
assert.notEqual(second.id, first.id, "a new id: the cancel still pending for the old one cannot reach it");
await act(async () => { port.onmessage({ data: { up: second.id, received: 8, done: true } }); });
await waitFor(() => assert.equal(screen.getByRole("button", { name: SEND }).disabled, false));
} finally {
fakePort.onmessage({ data: { transport: "sse" } });
}
});
10 changes: 6 additions & 4 deletions docs/specs/2026-11-02-file-uploads-design.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ The composer refuses every file that is neither an image nor text (a `.zip` cann
- HTTP body-read network failures remain transient just like failures while fetching headers; malformed JSON is not reclassified as a network failure. Chip tooltips use the existing localized network-error explanation rather than the generic upload-failed message.
- An image chip sent As file has no room for the label: while it waits it shows a reconnecting badge (an icon labelled "Reconnecting…") where a failed chip shows Retry, so touch screens see it without a tooltip.
- A draft keeps finished uploads (id, name, size, host); an upload still in flight is lost on reload and must be attached again. Edit-move merges source and destination uploads by id, keeping the first occurrence (source first).
- A page retained in the browser's back/forward cache must not retain an unresolved WebSocket-upload promise after the worker drops its client. Leaving the page fails uploads in flight visibly (410: the worker aborted them on the host); restoring it offers Retry rather than an indefinitely blocked Send. An upload already waiting to resume when the page left keeps its timer and resumes after restoration.
- A page retained in the browser's back/forward cache must not retain an unresolved WebSocket-upload promise after the worker drops its client. Leaving the page fails uploads in flight visibly (410: the worker aborted them on the host); restoring it offers Retry rather than an indefinitely blocked Send. That Retry starts over under a new upload id: the old id's cancel may still be pending in the worker or on its way to the host, and must never reach the new upload. An upload already waiting to resume when the page left keeps its timer and resumes after restoration.
- The target host is the open session's host, or for a new chat the host selected on the new-session screen.

### U3. Staging on the host, attach on send
Expand All @@ -58,7 +58,7 @@ The upload id is a client-generated UUID. It doubles as the binary frame id on b
|---|---|---|---|---|
| `up_start {id, n, host, name, size, mime}` | ↑ | yes | `up:<id>` | open, or resume, an upload on `host`; `n` is allocated from a worker-wide increasing sequence and is never reused by a Retry, `mime` is the file's type (`type` is the message's) |
| binary `[n][id][payload]` | ↑ | no | `up:<id>` | the next ≤ `pieceBytes` (256 KiB) of the file, in order |
| `up_abort {id}` | ↑ | yes | `up:<id>` | cancel and delete the staged file |
| `up_abort {id, host?}` | ↑ | yes | `up:<id>` | cancel and delete the staged file; `host` (the upload's host, from the tab) reaches an upload the server no longer registers |
| `up_ack {id, received, done, start}` | ↓ | yes | `up:<id>` | the host has written `received` bytes; `done` once all `size` bytes are written and synced. Start replies and asynchronous progress/completion carry the originating `start: n` |
| `up_error {id, status, code, message, start?}` | ↓ | yes | `up:<id>` | the upload failed (host offline, disk full, too large, old host). Failures belonging to a start, including delayed sink errors, carry its `start: n`; malformed messages without a valid generation may receive an untagged error |

Expand All @@ -70,18 +70,20 @@ The upload id is a client-generated UUID. It doubles as the binary frame id on b
- **Host-link drop:** each in-flight upload on that host fails with `up_error` 503 `host_offline`; the tab resumes it by itself from the host's offset once the host is back (U2).
- The tab hands the worker `Blob` slices (`File.slice`, read in the worker) rather than buffers, so the tab holds no file bytes.
- `lib/browser-link.ts` accepts binary frames only for an upload this link started, and only up to `pieceBytes` plus the header. Any other binary frame still closes with 1007. Main forwards a frame only while the sending link's sink is the upload's current sink: after a WS→HTTP handoff (or a newer start) the old socket's late frames are refused, never appended after the offset the new start reported. `BROWSER_LINK_VERSION` stays 1: the worker is served by the same server (content-hashed URL), and an old worker never sends the new types.
- **Durable cancel:** removing a chip, or discarding a finished upload, posts `{op: "up_abort", id, host}` to the worker whatever its mode, and the worker keeps the abort until the server has it (at most 256; the oldest past that is left to the daemon's sweep). In `ws` mode it is an `up_abort` line, queued once the link has a token (the worker dials for it if needed) and kept until the server acks its seq; a resync sends it again. In `sse` mode, and on a switch to it, it is `DELETE /api/uploads/<id>?host=<host>` with a 40 s deadline: a 2xx, or a 4xx other than 408 and 429, settles it; a network error, a timeout, a 5xx, 408 or 429 is retried after 5, 15, then every 60 s and at once on a wake (`online`, `network`, `visible`). Only a tab without a worker sends the DELETE itself, once. A cancel made while offline is lost only if the browser closes before it is delivered, or if the server restarts while it waits for an offline host (main keeps it in memory); the daemon's hourly sweep (U5) then deletes the file once it is 24 h old.

**SSE mode (and the WebSocket fallback)** uses HTTP with the same semantics:
- `POST /api/uploads {id, host, name, size, type}` corresponds to `up_start` and answers `{received}`.
- `PUT /api/uploads/<id>?offset=N` carries a body of up to 1 MiB. The server cuts it into ≤ 256 KiB frames, forwards them, and answers once the host has acked through `N + length`, which is the HTTP form of the window. The final PUT waits for `done: true`, not just `received == size`, so it does not finish ahead of the daemon's final fsync.
- `DELETE /api/uploads/<id>` corresponds to `up_abort`.
- `DELETE /api/uploads/<id>?host=<host>` corresponds to `up_abort` and always answers 204: from there main owns the delivery (U5).

### U5. Server → host (host link v6)

- **Ops:**
- `uploadStart {id, name, size, type, attempt}` creates the staging file, or opens an existing one, and returns `{received, done}`. Main generates a fresh UUIDv4 `attempt` for every start, including after a registry deletion or server restart.
- `uploadAbort {id}` deletes the staging file.
- `uploadAbort {id}` deletes the staging file. Main delivers it once the host can take it: an abort that fails 503 `host_offline` or 504 `host_timeout` is kept per host (in memory, at most 1000 per host) and sent again on that host's next hello. A Retry supersedes it: a new `uploadStart` of the same id drops a kept abort, and an abort still in flight is not kept if it fails after such a start registered the id again (the host runs an id's ops in arrival order, so a late abort still lands before the Retry's start). The worker likewise drops its own pending cancel when the same id is uploaded again (U4). An abort for an id main does not register goes to the host the browser named, if that host is known; a registered upload of another owner is never aborted.
- `uploadAttach` is described in U3.
- **Sweep:** the daemon deletes staged files untouched for `STAGED_MAX_AGE_MS` (24 h) at start, on every `uploadStart`, and every hour (`UPLOAD_SWEEP_INTERVAL_MS`), so an idle host also loses what an undelivered cancel left behind.
- **Down:** binary frames `[n][id][payload]`, the format the daemon already sends up for large results, sent by the hub as `{id, blob}` units of its `LinkSender` under key `up:<id>`. The hub's `flush` learns blob units: a blob unit is sent with the same Bun `send` → `-1` → `drain` handling and is not counted in the line window. The browser's window (U4) bounds it.
- **Up:** `upload_ack {seq, id, attempt, received, done}`, a sequenced line. The daemon queues one after each write, coalesced to at most one per `flushMs` per upload, plus a final one with `done`. Each ack retains the attempt that produced it, even when fair scheduling delivers it after a newer start's reply. Main drops acks whose attempt is not the registry's current attempt before applying progress, completion or errors; only current-attempt acks reach the browser link or HTTP waiter.
- **Daemon writes** at the staged file's current length. A frame for an unknown or finished upload is dropped, and the next `uploadStart` reports the real offset. Bytes beyond `size` fail the upload. A failed attempt remains registered while its write chain removes the old staging files, so a resumed start drains that cleanup before creating or reopening its files.
Expand Down
2 changes: 1 addition & 1 deletion graphify-out/graph.json

Large diffs are not rendered by default.

Loading
Loading