Ship the Files tab container-side only

Four successive audits found the same thing: host filesystem paths crossing
IPC is where the criticals in this work live. The most recent one found the
`link(2)` upload reservation returning success against a *directory* (linking
into it, leaving permanent stray files, and via a symlink-to-directory writing
outside the validated write root), failing every upload permanently on any
filesystem without hard links, and the post-resolution credential check
weakened from a general rule to an eleven-name denylist.

Rather than fix that a fifth time, the Files tab ships as what it is good at:
a browser, viewer and renamer that never touches the host.

Removed: `upload_file_to_container`, `download_container_file`, and everything
that existed only for them — the whole reservation (`UPLOAD_RESERVATION_SCRIPT`,
`reserve_upload_destination`, the placeholder rollback, `exec_oneshot_as_within`
which had no other caller), `stream_container_file_to_host`, `ChannelReader`,
`save_to_host`, the download ceiling, and the collision marker with its
frontend contract. On the frontend: the upload button, the pane's
`onDragDropEvent` handler, both "Save to host…" affordances, `uploadPaths` /
`downloadFile` / the overwrite prompt, and `OverwriteConfirmModal`.
`lib/uploadErrors.ts` is now `lib/refusalText.ts` and keeps only the half that
turns any backend refusal into the sentence a person reads.

Kept, and not weakened: `upload_host_file_to_terminal` and
`download_container_backup`. They predate this work, their hardening is a real
improvement over main, and they are now the whole answer to "how do I get a
file in or out" — drop it on the Terminal, or Back up container. The drop gate
(`lib/dropTarget.ts`, `PaneVisibility`) is untouched.

`resolve_host_path` gets the general hidden-component rule back. Round 3
replaced it with `HOST_CREDENTIAL_DIRS`, which is allow-by-omission for the
rest of `$HOME`: `~/.local/bin` (write there and you own the user's next shell
command), `~/.password-store`, browser profiles and `~/.pki/nssdb` were all
reachable through a planted symlink with a visible name — verified against a
real home directory, and all five refused now. It over-catches `.pnpm` and
`~/.cache`; for two occasional callers that is the cheaper mistake, and the
refusal says which folder it resolved through.

Two defects fixed while in here:

  * A symlinked directory listed as empty. `find` defaults to `-P`, which does
    not follow a symlink even as the starting point, so `-mindepth 1` discarded
    the only match and a real directory rendered as "Empty directory" — a
    first-order defect now that browsing *is* the feature. `-H` follows the
    starting point and nothing else, so a loop is `ELOOP` rather than a walk
    that does not end; verified against a live container for a symlinked
    directory, a broken link and a loop. `find`'s errno for the loop case is
    now a sentence.
  * `finish_download`'s replace path fired on *any* rename failure with a
    destination present — a vanished partial, a permission error, a directory
    at the destination — and deleted the user's file to complete a move that
    could not complete. It is now fenced to Windows (where a rename onto an
    existing path genuinely fails) and to a partial that still exists.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GBq2rGum6GX7xXgsas1fDc
This commit is contained in:
2026-08-23 17:05:56 -07:00
co-authored by Claude Opus 5
parent 168b61d632
commit 06ccb4d818
19 changed files with 761 additions and 2928 deletions
@@ -4,16 +4,12 @@ import FilesTab from "./FilesTab";
import type { FileContents, FileEntry, Project } from "../../../lib/types";
const listContainerFiles = vi.fn();
const downloadContainerFile = vi.fn(async () => {});
const uploadFileToContainer = vi.fn(async () => {});
const renameContainerPath = vi.fn(async () => "");
const createContainerDirectory = vi.fn(async () => "");
const readContainerFile = vi.fn();
vi.mock("../../../lib/tauri-commands", () => ({
listContainerFiles: (p: string, path: string) => listContainerFiles(p, path),
downloadContainerFile: (p: string, c: string, h: string) => downloadContainerFile(p, c, h),
uploadFileToContainer: (...args: unknown[]) => uploadFileToContainer(...args),
renameContainerPath: (p: string, f: string, t: string) => renameContainerPath(p, f, t),
createContainerDirectory: (p: string, parent: string, n: string) =>
createContainerDirectory(p, parent, n),
@@ -31,29 +27,6 @@ const toastText = () =>
.map(([toast]) => `${toast.kind}: ${toast.message} ${toast.detail ?? ""}`)
.join("\n");
const save = vi.fn(async () => "/host/out");
vi.mock("@tauri-apps/plugin-dialog", () => ({
save: (o: unknown) => save(o),
open: vi.fn(async () => null),
}));
/** The webview's window-wide native drag-drop listener, captured for driving. */
type DragPayload =
| { type: "enter" | "over"; position: { x: number; y: number }; paths: string[] }
| { type: "leave" }
| { type: "drop"; position: { x: number; y: number }; paths: string[] };
let dragHandler: ((e: { payload: DragPayload }) => void | Promise<void>) | null = null;
const unlistenDrag = vi.fn();
vi.mock("@tauri-apps/api/webview", () => ({
getCurrentWebview: () => ({
onDragDropEvent: async (cb: (e: { payload: DragPayload }) => void) => {
dragHandler = cb;
return unlistenDrag;
},
}),
}));
const project = { id: "p1", name: "api", status: "running" } as unknown as Project;
const entry = (name: string, extra: Partial<FileEntry> = {}): FileEntry => ({
@@ -82,39 +55,17 @@ async function renderTab() {
return view;
}
/** Fire the native drop payload at a point inside the pane's stubbed rect. */
async function drop(paths: string[], position = { x: 100, y: 100 }) {
await act(async () => {
await dragHandler?.({ payload: { type: "drop", position, paths } });
});
}
/** Every row that is part of the grid's roving tabindex, in order. */
const gridRows = () => Array.from(document.querySelectorAll("tr[data-file-row]"));
/** The rows that are actually tab stops. There must never be more than one. */
const tabStops = () => gridRows().filter((r) => r.getAttribute("tabindex") === "0");
/** Fire a drop without awaiting it — for the paths that stop to ask a question. */
function dropWithoutWaiting(paths: string[], position = { x: 100, y: 100 }) {
let pending: unknown;
act(() => {
pending = dragHandler?.({ payload: { type: "drop", position, paths } });
});
return pending as Promise<void> | undefined;
}
beforeEach(() => {
vi.clearAllMocks();
dragHandler = null;
listContainerFiles.mockResolvedValue([
entry("src", { is_directory: true, path: "/workspace/src" }),
entry("notes.txt"),
]);
// jsdom lays nothing out, so the pane's hit-test rect has to be supplied.
vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockReturnValue({
x: 0, y: 0, left: 0, top: 0, right: 800, bottom: 600, width: 800, height: 600,
toJSON: () => ({}),
} as DOMRect);
// Not implemented in jsdom; the image preview needs both halves.
URL.createObjectURL = vi.fn(() => "blob:mock-url");
URL.revokeObjectURL = vi.fn();
@@ -224,7 +175,9 @@ describe("FilesTab viewer", () => {
});
expect(await screen.findByText(/too large to preview/)).toBeTruthy();
expect(screen.queryByAltText("huge.png")).toBeNull();
expect(screen.getByRole("button", { name: "Save to host…" })).toBeTruthy();
// The way out is named, and it is not a host path this pane could write:
// a terminal inside the container, or a backup.
expect(screen.getByText(/take a backup/)).toBeTruthy();
});
it("says so in words when only a prefix of a big text file came back", async () => {
@@ -239,7 +192,7 @@ describe("FilesTab viewer", () => {
expect(screen.getByText("first megabyte")).toBeTruthy();
});
it("offers Save to host for a file it cannot render", async () => {
it("says there is no preview, and where to open the file instead", async () => {
listContainerFiles.mockResolvedValue([entry("blob.bin")]);
readContainerFile.mockResolvedValue(contents("a\x00b"));
await renderTab();
@@ -314,191 +267,6 @@ describe("FilesTab new folder", () => {
});
});
describe("FilesTab host drag-and-drop", () => {
it("uploads dropped paths into the directory on screen, then re-lists", async () => {
await renderTab();
listContainerFiles.mockClear();
await drop(["/host/a.png", "/host/b.png"]);
expect(uploadFileToContainer).toHaveBeenNthCalledWith(1, "p1", "/host/a.png", "/workspace");
expect(uploadFileToContainer).toHaveBeenNthCalledWith(2, "p1", "/host/b.png", "/workspace");
expect(listContainerFiles).toHaveBeenCalledWith("p1", "/workspace");
});
it("drops into the directory the user has navigated to", async () => {
await renderTab();
await act(async () => {
fireEvent.doubleClick(screen.getByText("src"));
});
await drop(["/host/a.png"]);
expect(uploadFileToContainer).toHaveBeenCalledWith("p1", "/host/a.png", "/workspace/src");
});
it("ignores a drop outside the pane — the listener is window-wide", async () => {
// This is the whole routing discipline: the terminal's listener is live at
// the same time, and only the hit-test keeps them apart.
await renderTab();
await drop(["/host/a.png"], { x: 5000, y: 5000 });
expect(uploadFileToContainer).not.toHaveBeenCalled();
});
it("divides the payload position by devicePixelRatio on Windows only", async () => {
// Only wry's WebView2 backend hands over *physical* pixels; the macOS and
// GTK ones deliver logical points and `tauri-runtime-wry` does not rescale
// them. At dpr 2 a physical (900, 900) is a CSS (450, 450) — inside the
// 800x600 pane — but the same payload on a HiDPI Mac or Linux box really
// is (900, 900) and belongs to nobody.
const originalDpr = window.devicePixelRatio;
const originalUa = window.navigator.userAgent;
Object.defineProperty(window, "devicePixelRatio", { value: 2, configurable: true });
Object.defineProperty(window.navigator, "userAgent", {
value: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
configurable: true,
});
await renderTab();
await drop(["/host/a.png"], { x: 900, y: 900 });
expect(uploadFileToContainer).toHaveBeenCalled();
Object.defineProperty(window.navigator, "userAgent", {
value: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15",
configurable: true,
});
vi.mocked(uploadFileToContainer).mockClear();
await drop(["/host/a.png"], { x: 900, y: 900 });
expect(uploadFileToContainer).not.toHaveBeenCalled();
// …and the *unhalved* point still lands, which is the half a HiDPI Mac
// user was losing.
await drop(["/host/a.png"], { x: 400, y: 300 });
expect(uploadFileToContainer).toHaveBeenCalled();
Object.defineProperty(window, "devicePixelRatio", {
value: originalDpr,
configurable: true,
});
Object.defineProperty(window.navigator, "userAgent", {
value: originalUa,
configurable: true,
});
});
it("accepts a drop that lands on a toast floating over the pane", async () => {
// Round 1. `ToastHost` is `fixed bottom-4 right-4 z-[60]` and 24rem wide,
// and its error cards stay until dismissed — so a z-order gate asking "is
// what is painted here part of my pane?" made the bottom-right corner of
// this pane refuse drops for as long as one error was on screen. jsdom has
// no `elementFromPoint`, so that branch only ran when a test supplied one;
// the gate no longer asks, and this pins that nothing painted over a pane
// can refuse a drop on its own account.
await renderTab();
const toastCard = document.createElement("div");
document.body.appendChild(toastCard);
Object.defineProperty(document, "elementFromPoint", {
configurable: true,
writable: true,
value: () => toastCard,
});
await drop(["/host/a.png"], { x: 700, y: 550 });
expect(uploadFileToContainer).toHaveBeenCalled();
delete (document as Partial<Document>).elementFromPoint;
toastCard.remove();
});
it("refuses a drop while a dialog is open, toast painted over it or not", async () => {
// Round 2, which is the reason this file exists in its current shape. The
// refusal pushes a toast; `ToastHost` is `z-[60]` and the `Modal` backdrop
// is `z-50` in the same stacking context, so the *toast* becomes the
// topmost element over a covered pane. A gate that asked `elementFromPoint`
// "is a blocker painted here?" then answered no and uploaded into the
// directory the dialog was covering — one refused drop was all it took to
// open the hole. Both stubs below therefore have to be refused.
await renderTab();
const backdrop = document.createElement("div");
backdrop.setAttribute("data-blocks-drop", "true");
document.body.appendChild(backdrop);
const toastCard = document.createElement("div"); // z-[60], above the backdrop
document.body.appendChild(toastCard);
const stub = (top: Element) =>
Object.defineProperty(document, "elementFromPoint", {
configurable: true,
writable: true,
value: () => top,
});
stub(backdrop);
await drop(["/host/a.png"], { x: 400, y: 300 });
expect(uploadFileToContainer).not.toHaveBeenCalled();
stub(toastCard);
await drop(["/host/a.png"], { x: 700, y: 550 });
expect(uploadFileToContainer).not.toHaveBeenCalled();
delete (document as Partial<Document>).elementFromPoint;
toastCard.remove();
backdrop.remove();
});
it("highlights the pane while a drag hovers it, and drops the highlight on leave", async () => {
await renderTab();
await act(async () => {
await dragHandler?.({
payload: { type: "over", position: { x: 100, y: 100 }, paths: [] },
});
});
expect(screen.getByText(/Drop files into \/workspace/)).toBeTruthy();
await act(async () => {
await dragHandler?.({ payload: { type: "leave" } });
});
expect(screen.queryByText(/Drop files into/)).toBeNull();
});
});
describe("FilesTab save to host", () => {
it("copies a file out to the path the user picks", async () => {
await renderTab();
await act(async () => {
fireEvent.click(screen.getByRole("button", { name: "Save to host… — notes.txt" }));
});
expect(downloadContainerFile).toHaveBeenCalledWith("p1", "/workspace/notes.txt", "/host/out");
});
it("does not offer a directory download, which cannot work", async () => {
await renderTab();
expect(screen.queryByRole("button", { name: "Save to host… — src" })).toBeNull();
});
});
describe("FilesTab drop hit test", () => {
it("uploads nothing when a dialog is covering the pane", async () => {
// The pane still has its rect underneath the viewer's `fixed inset-0`
// portal, which is exactly why a rect alone was the wrong test.
readContainerFile.mockResolvedValue(contents("hello"));
await renderTab();
await act(async () => {
fireEvent.doubleClick(screen.getByText("notes.txt"));
});
await screen.findByRole("dialog");
await drop(["/host/a.png"]);
expect(uploadFileToContainer).not.toHaveBeenCalled();
});
it("does not paint the hint under a dialog either", async () => {
readContainerFile.mockResolvedValue(contents("hello"));
await renderTab();
await act(async () => {
fireEvent.doubleClick(screen.getByText("notes.txt"));
});
await screen.findByRole("dialog");
await act(async () => {
await dragHandler?.({ payload: { type: "over", position: { x: 100, y: 100 }, paths: [] } });
});
expect(screen.queryByText(/Drop files into/)).toBeNull();
});
});
describe("FilesTab grid focus", () => {
it("gives the grid exactly one tab stop and moves it with the arrows", async () => {
// Every row used to be `tabIndex={0}`: a 400-entry directory was ~1200 tab
@@ -592,22 +360,28 @@ describe("FilesTab grid semantics", () => {
await renderTab();
const rename = screen.getByRole("button", { name: "Rename — notes.txt" });
expect(rename.textContent).toBe("Rename");
expect(rename.getAttribute("aria-label")).toContain("Rename");
const saveTo = screen.getByRole("button", { name: "Save to host… — notes.txt" });
expect(saveTo.getAttribute("aria-label")).toContain(saveTo.textContent!);
expect(rename.getAttribute("aria-label")).toContain(rename.textContent!);
});
it("mounts the live region empty, then fills it", async () => {
// A `role="status"` node inserted already carrying its text is frequently
// not announced at all, which is how every one of these went by in silence.
createContainerDirectory.mockResolvedValue("/workspace/new");
await renderTab();
const live = screen.getByRole("status");
expect(live.textContent).toBe("");
await drop(["/host/a.png"]);
await act(async () => {
fireEvent.click(screen.getByRole("button", { name: "New folder" }));
});
const input = screen.getByLabelText("New folder name");
fireEvent.change(input, { target: { value: "new" } });
await act(async () => {
fireEvent.blur(input);
});
// Same node throughout — it is never unmounted.
expect(screen.getByRole("status")).toBe(live);
expect(live.textContent).toContain("Uploaded 1 item");
expect(live.textContent).toContain('Created "new"');
});
it("keeps a listing failure inline, where the rows it explains are missing", async () => {
@@ -618,130 +392,3 @@ describe("FilesTab grid semantics", () => {
expect(screen.getByRole("alert").textContent).toContain("Permission denied");
});
});
describe("FilesTab overwrite prompt", () => {
it("asks before replacing, and re-uploads with overwrite on Replace", async () => {
uploadFileToContainer.mockRejectedValueOnce("FILE_EXISTS: /workspace/notes.txt already exists");
await renderTab();
const pending = dropWithoutWaiting(["/host/notes.txt"]);
const dialog = await screen.findByRole("dialog");
expect(dialog.textContent).toContain("notes.txt");
await act(async () => {
fireEvent.click(screen.getByRole("button", { name: "Replace" }));
await pending;
});
expect(uploadFileToContainer).toHaveBeenLastCalledWith(
"p1",
"/host/notes.txt",
"/workspace",
true,
);
expect(screen.queryByRole("dialog")).toBeNull();
});
it("uploads nothing more on Skip", async () => {
uploadFileToContainer.mockRejectedValueOnce("FILE_EXISTS: /workspace/notes.txt already exists");
await renderTab();
const pending = dropWithoutWaiting(["/host/notes.txt"]);
await screen.findByRole("dialog");
await act(async () => {
fireEvent.click(screen.getByRole("button", { name: "Skip" }));
await pending;
});
expect(uploadFileToContainer).toHaveBeenCalledTimes(1);
expect(screen.queryByRole("dialog")).toBeNull();
});
it("offers the blanket answers only when files are queued behind this one", async () => {
uploadFileToContainer.mockRejectedValueOnce("FILE_EXISTS: /workspace/a.txt already exists");
await renderTab();
const pending = dropWithoutWaiting(["/host/a.txt", "/host/b.txt"]);
await screen.findByRole("dialog");
expect(screen.getByRole("button", { name: "Replace all" })).toBeTruthy();
await act(async () => {
fireEvent.click(screen.getByRole("button", { name: "Skip all" }));
await pending;
});
expect(screen.queryByRole("dialog")).toBeNull();
});
});
/**
* Dismissal. `Modal` gives every dialog Escape, a ✕ and click-outside for free,
* and `OverwriteConfirmModal` maps all three onto `onChoose("skip")` — because
* the destructive answer has to be chosen, and because a dialog that is closed
* rather than answered must not leave the batch waiting forever or throw away
* the files behind it.
*/
describe("FilesTab overwrite prompt dismissal", () => {
/**
* Drop two files where the first name is taken, and stop at the dialog. The
* unsettled batch comes back wrapped — returning it bare from an `async`
* helper would adopt it, and awaiting the helper would then wait for an
* upload that cannot proceed until the helper has returned.
*/
async function dropIntoConflict(): Promise<{ batch: Promise<void> | undefined }> {
uploadFileToContainer.mockRejectedValueOnce("FILE_EXISTS: /workspace/a.txt already exists");
await renderTab();
const batch = dropWithoutWaiting(["/host/a.txt", "/host/b.txt"]);
await screen.findByRole("dialog");
return { batch };
}
/** What every dismissal has to leave behind: one skip, one upload, no clobber. */
function expectSkippedAndCarriedOn() {
expect(screen.queryByRole("dialog")).toBeNull();
expect(uploadFileToContainer).toHaveBeenCalledTimes(2);
expect(uploadFileToContainer).toHaveBeenLastCalledWith("p1", "/host/b.txt", "/workspace");
expect(uploadFileToContainer.mock.calls.some((call) => call[3] === true)).toBe(false);
expect(screen.getByRole("status").textContent).toContain("skipped 1");
}
it("counts Escape as a Skip", async () => {
const { batch } = await dropIntoConflict();
await act(async () => {
fireEvent.keyDown(document, { key: "Escape" });
await batch;
});
expectSkippedAndCarriedOn();
});
it("counts the ✕ as a Skip", async () => {
const { batch } = await dropIntoConflict();
await act(async () => {
fireEvent.click(screen.getByRole("button", { name: "Close dialog" }));
await batch;
});
expectSkippedAndCarriedOn();
});
it("counts a click on the backdrop as a Skip", async () => {
const { batch } = await dropIntoConflict();
// The overlay is the dialog panel's parent — `Modal` only closes when the
// click landed on the overlay itself, not on anything inside the panel.
const overlay = screen.getByRole("dialog").parentElement!;
await act(async () => {
fireEvent.click(overlay);
await batch;
});
expectSkippedAndCarriedOn();
});
it("does not dismiss on a click inside the dialog", async () => {
const { batch } = await dropIntoConflict();
fireEvent.click(screen.getByRole("dialog"));
expect(screen.queryByRole("dialog")).not.toBeNull();
await act(async () => {
fireEvent.click(screen.getByRole("button", { name: "Replace" }));
await batch;
});
expect(uploadFileToContainer).toHaveBeenNthCalledWith(2, "p1", "/host/a.txt", "/workspace", true);
});
});