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
+23 -354
View File
@@ -4,15 +4,11 @@ import { useFileManager } from "./useFileManager";
import type { FileEntry } from "../lib/types";
const listContainerFiles = vi.fn();
const downloadContainerFile = vi.fn();
const uploadFileToContainer = vi.fn();
const renameContainerPath = vi.fn();
const createContainerDirectory = 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),
@@ -35,13 +31,6 @@ const toastText = () =>
.map(([toast]) => `${toast.kind}: ${toast.message} ${toast.detail ?? ""}`)
.join("\n");
const save = vi.fn();
const openDialog = vi.fn();
vi.mock("@tauri-apps/plugin-dialog", () => ({
save: (opts: unknown) => save(opts),
open: (opts: unknown) => openDialog(opts),
}));
const file = (name: string, extra: Partial<FileEntry> = {}): FileEntry => ({
name,
path: `/workspace/${name}`,
@@ -100,48 +89,6 @@ describe("useFileManager navigation", () => {
});
});
describe("useFileManager uploads", () => {
it("uploads every dropped path into the current directory, then re-lists once", async () => {
const { result } = renderHook(() => useFileManager("p1"));
await act(async () => {
await result.current.navigate("/workspace/app");
});
listContainerFiles.mockClear();
await act(async () => {
await result.current.uploadPaths(["/host/a.png", "/host/b.png"]);
});
expect(uploadFileToContainer).toHaveBeenNthCalledWith(1, "p1", "/host/a.png", "/workspace/app");
expect(uploadFileToContainer).toHaveBeenNthCalledWith(2, "p1", "/host/b.png", "/workspace/app");
// One refresh for the batch, not one per file.
expect(listContainerFiles).toHaveBeenCalledTimes(1);
});
it("reports a failed upload but still lists whatever did land", async () => {
uploadFileToContainer.mockResolvedValueOnce(undefined);
uploadFileToContainer.mockRejectedValueOnce("File too large to upload (900 MB; limit 256 MB)");
const { result } = renderHook(() => useFileManager("p1"));
await act(async () => {
await result.current.uploadPaths(["/host/ok.txt", "/host/huge.bin"]);
});
// Inline `error` is reserved for the listing failure the user can see in
// context; a failed upload goes where it cannot scroll away.
expect(result.current.error).toBeNull();
expect(toastText()).toContain("too large");
expect(listContainerFiles).toHaveBeenCalled();
});
it("does nothing when the file picker is cancelled", async () => {
openDialog.mockResolvedValue(null);
const { result } = renderHook(() => useFileManager("p1"));
await act(async () => {
await result.current.uploadFile();
});
expect(uploadFileToContainer).not.toHaveBeenCalled();
});
});
describe("useFileManager rename and mkdir", () => {
it("sends the bare new name, never a path, and re-lists on success", async () => {
renameContainerPath.mockResolvedValue("/workspace/renamed.txt");
@@ -204,47 +151,22 @@ describe("useFileManager rename and mkdir", () => {
});
});
describe("useFileManager save to host", () => {
it("writes to the path the user picked", async () => {
save.mockResolvedValue("/host/Downloads/a.txt");
const { result } = renderHook(() => useFileManager("p1"));
await act(async () => {
await result.current.downloadFile(file("a.txt"));
});
expect(downloadContainerFile).toHaveBeenCalledWith(
"p1",
"/workspace/a.txt",
"/host/Downloads/a.txt",
);
});
it("reports a refused download — a directory is no longer written as garbage", async () => {
save.mockResolvedValue("/host/Downloads/src");
downloadContainerFile.mockRejectedValue("/workspace/src is a folder — download its files individually");
const { result } = renderHook(() => useFileManager("p1"));
await act(async () => {
await result.current.downloadFile(file("src", { is_directory: true }));
});
expect(toastText()).toContain("is a folder");
});
});
describe("useFileManager stays where the user is", () => {
it("does not drag the pane back when the user navigates away mid-upload", async () => {
it("does not drag the pane back when the user navigates away mid-operation", async () => {
// The closure captured `/workspace`; the user is in `/workspace/src` by the
// time the copy finishes. Re-listing the *captured* path is what used to
// time the rename finishes. Re-listing the *captured* path is what used to
// yank them out of the directory they had walked into.
let failUpload: (reason: unknown) => void = () => {};
let failRename: (reason: unknown) => void = () => {};
// `Once`, deliberately: `clearAllMocks` clears calls but not
// implementations, so a never-settling one would hang every test after it.
uploadFileToContainer.mockImplementationOnce(
() => new Promise((_resolve, reject) => { failUpload = reject; }),
renameContainerPath.mockImplementationOnce(
() => new Promise((_resolve, reject) => { failRename = reject; }),
);
const { result } = renderHook(() => useFileManager("p1"));
let upload!: Promise<void>;
let rename!: Promise<boolean>;
await act(async () => {
upload = result.current.uploadPaths(["/host/big.bin"]);
rename = result.current.renameEntry(file("big.bin"), "bigger.bin");
await Promise.resolve();
});
@@ -255,13 +177,13 @@ describe("useFileManager stays where the user is", () => {
listContainerFiles.mockClear();
await act(async () => {
failUpload("cp: no space left on device");
await upload;
failRename("mv: no space left on device");
await rename;
});
expect(result.current.currentPath).toBe("/workspace/src");
expect(result.current.entries.map((e) => e.name)).toEqual(["index.ts"]);
// No re-list of the directory the upload targeted…
// No re-list of the directory the rename targeted…
expect(listContainerFiles).not.toHaveBeenCalled();
// …and no failure text painted over the listing that replaced it.
expect(result.current.error).toBeNull();
@@ -269,13 +191,14 @@ describe("useFileManager stays where the user is", () => {
});
it("re-lists when the user stayed put, which is the ordinary case", async () => {
renameContainerPath.mockResolvedValue("/workspace/b.txt");
const { result } = renderHook(() => useFileManager("p1"));
await act(async () => {
await result.current.navigate("/workspace");
});
listContainerFiles.mockClear();
await act(async () => {
await result.current.uploadPaths(["/host/a.png"]);
await result.current.renameEntry(file("a.txt"), "b.txt");
});
expect(listContainerFiles).toHaveBeenCalledWith("p1", "/workspace");
});
@@ -316,248 +239,11 @@ describe("useFileManager stays where the user is", () => {
await result.current.navigate("/root");
});
listContainerFiles.mockClear();
// The pane never left /workspace, so an upload started now targets it.
// The pane never left /workspace, so a new folder made now lands there.
await act(async () => {
await result.current.uploadPaths(["/host/a.png"]);
await result.current.createFolder("new");
});
expect(uploadFileToContainer).toHaveBeenCalledWith("p1", "/host/a.png", "/workspace");
});
});
describe("useFileManager overwrite prompt", () => {
const alreadyThere = "FILE_EXISTS: /workspace/a.txt already exists";
it("asks rather than clobbering, and replaces on demand", async () => {
uploadFileToContainer.mockRejectedValueOnce(alreadyThere);
uploadFileToContainer.mockResolvedValueOnce(undefined);
const { result } = renderHook(() => useFileManager("p1"));
let upload!: Promise<void>;
await act(async () => {
upload = result.current.uploadPaths(["/host/a.txt"]);
await Promise.resolve();
});
await waitFor(() => expect(result.current.conflict?.name).toBe("a.txt"));
expect(result.current.conflict?.directory).toBe("/workspace");
// One file, so there is nothing for a blanket answer to apply to.
expect(result.current.conflict?.remaining).toBe(0);
await act(async () => {
result.current.resolveConflict("replace");
await upload;
});
expect(uploadFileToContainer).toHaveBeenNthCalledWith(2, "p1", "/host/a.txt", "/workspace", true);
expect(result.current.conflict).toBeNull();
});
it("skips without uploading anything when the user says so", async () => {
uploadFileToContainer.mockRejectedValueOnce(alreadyThere);
const { result } = renderHook(() => useFileManager("p1"));
let upload!: Promise<void>;
await act(async () => {
upload = result.current.uploadPaths(["/host/a.txt"]);
await Promise.resolve();
});
await waitFor(() => expect(result.current.conflict).not.toBeNull());
await act(async () => {
result.current.resolveConflict("skip");
await upload;
});
expect(uploadFileToContainer).toHaveBeenCalledTimes(1);
// A skip is a choice, not a failure — nothing to report.
expect(toastText()).not.toContain("could not be uploaded");
});
it("asks once for a batch when the answer is Replace all", async () => {
uploadFileToContainer.mockRejectedValueOnce(alreadyThere);
uploadFileToContainer.mockResolvedValueOnce(undefined);
uploadFileToContainer.mockRejectedValueOnce("FILE_EXISTS: /workspace/b.txt already exists");
uploadFileToContainer.mockResolvedValueOnce(undefined);
const { result } = renderHook(() => useFileManager("p1"));
let upload!: Promise<void>;
await act(async () => {
upload = result.current.uploadPaths(["/host/a.txt", "/host/b.txt"]);
await Promise.resolve();
});
await waitFor(() => expect(result.current.conflict?.remaining).toBe(1));
await act(async () => {
result.current.resolveConflict("replace-all");
await upload;
});
expect(result.current.conflict).toBeNull();
expect(uploadFileToContainer).toHaveBeenNthCalledWith(4, "p1", "/host/b.txt", "/workspace", true);
});
it("leaves an unrelated failure alone — no prompt offering a button that cannot work", async () => {
uploadFileToContainer.mockRejectedValueOnce("File too large to upload (900 MB; limit 256 MB)");
const { result } = renderHook(() => useFileManager("p1"));
await act(async () => {
await result.current.uploadPaths(["/host/huge.bin"]);
});
expect(result.current.conflict).toBeNull();
expect(toastText()).toContain("too large");
});
});
/**
* The loop, end to end. The prompt only earns its place if the *batch* survives
* it: one answer, given once, has to leave every other file in the drop exactly
* where it would have been.
*/
describe("useFileManager overwrite prompt closes the loop", () => {
const clash = (name: string) => `FILE_EXISTS: /workspace/${name} already exists`;
/**
* Start an upload and wait for it to stop at the prompt, handing back the
* still-unsettled batch.
*
* Wrapped in an object on purpose: an `async` function that returned the
* promise itself would *adopt* it, so awaiting the helper would wait for the
* whole upload — which cannot finish until the question is answered, which
* cannot happen until the helper returns. That deadlock looks exactly like
* the hang these tests exist to rule out.
*/
async function uploadUntilPrompt(
result: { current: ReturnType<typeof useFileManager> },
paths: string[],
): Promise<{ batch: Promise<void> }> {
let batch!: Promise<void>;
await act(async () => {
batch = result.current.uploadPaths(paths);
await Promise.resolve();
});
await waitFor(() => expect(result.current.conflict).not.toBeNull());
return { batch };
}
it("replaces the file that clashed and still uploads the rest of the batch", async () => {
uploadFileToContainer
.mockRejectedValueOnce(clash("a.txt")) // 1: a.txt, no overwrite
.mockResolvedValueOnce(undefined) // 2: a.txt, overwrite: true
.mockResolvedValueOnce(undefined); // 3: b.txt, no clash
const { result } = renderHook(() => useFileManager("p1"));
const { batch } = await uploadUntilPrompt(result, ["/host/a.txt", "/host/b.txt"]);
expect(result.current.conflict?.name).toBe("a.txt");
expect(result.current.conflict?.remaining).toBe(1);
await act(async () => {
result.current.resolveConflict("replace");
await batch;
});
expect(uploadFileToContainer).toHaveBeenCalledTimes(3);
// The retry is the whole point: same file, same directory, overwrite on.
expect(uploadFileToContainer).toHaveBeenNthCalledWith(2, "p1", "/host/a.txt", "/workspace", true);
// …and "Replace" answered for *that* file only, so the next one is offered
// to the backend the safe way round.
expect(uploadFileToContainer).toHaveBeenNthCalledWith(3, "p1", "/host/b.txt", "/workspace");
expect(result.current.conflict).toBeNull();
expect(result.current.completed).toContain("Uploaded 2 items");
expect(toastText()).not.toContain("could not be uploaded");
});
it("moves on to the next file on Skip rather than ending the batch", async () => {
uploadFileToContainer
.mockRejectedValueOnce(clash("a.txt"))
.mockResolvedValueOnce(undefined); // b.txt still goes
const { result } = renderHook(() => useFileManager("p1"));
const { batch } = await uploadUntilPrompt(result, ["/host/a.txt", "/host/b.txt"]);
await act(async () => {
result.current.resolveConflict("skip");
await batch;
});
expect(uploadFileToContainer).toHaveBeenCalledTimes(2);
expect(uploadFileToContainer).toHaveBeenNthCalledWith(2, "p1", "/host/b.txt", "/workspace");
// Nothing was overwritten.
expect(uploadFileToContainer.mock.calls.some((c) => c[3] === true)).toBe(false);
expect(result.current.completed).toContain("skipped 1");
});
it("dismissing the dialog is a Skip — the batch carries on", async () => {
// `OverwriteConfirmModal` maps Escape / ✕ / click-outside onto this exact
// call, so a dismissal must not hang the loop or abort the drop.
uploadFileToContainer
.mockRejectedValueOnce(clash("a.txt"))
.mockResolvedValueOnce(undefined);
const { result } = renderHook(() => useFileManager("p1"));
const { batch } = await uploadUntilPrompt(result, ["/host/a.txt", "/host/b.txt"]);
await act(async () => {
// What `Modal`'s `onClose` produces.
result.current.resolveConflict("skip");
await batch;
});
expect(uploadFileToContainer).toHaveBeenCalledTimes(2);
expect(result.current.completed).toContain("Uploaded 1 item, skipped 1");
expect(result.current.busy).toBeNull();
});
it("answers every remaining clash with Skip all, asking only once", async () => {
uploadFileToContainer
.mockRejectedValueOnce(clash("a.txt"))
.mockRejectedValueOnce(clash("b.txt"))
.mockRejectedValueOnce(clash("c.txt"));
const { result } = renderHook(() => useFileManager("p1"));
const { batch } = await uploadUntilPrompt(result, ["/host/a.txt", "/host/b.txt", "/host/c.txt"]);
expect(result.current.conflict?.remaining).toBe(2);
await act(async () => {
result.current.resolveConflict("skip-all");
await batch;
});
// Three attempts, no second prompt, nothing replaced.
expect(uploadFileToContainer).toHaveBeenCalledTimes(3);
expect(uploadFileToContainer.mock.calls.some((c) => c[3] === true)).toBe(false);
expect(result.current.conflict).toBeNull();
expect(result.current.completed).toContain("skipped 3");
});
it("puts a picked file through exactly the road a dropped one takes", async () => {
// The Upload button and the native drop listener are one routine —
// `uploadPaths` — so the prompt, the retry and the blanket answers cannot
// drift apart between them. This is that claim, from the picker end.
openDialog.mockResolvedValueOnce(["/host/a.txt", "/host/b.txt"]);
uploadFileToContainer
.mockRejectedValueOnce(clash("a.txt"))
.mockResolvedValueOnce(undefined)
.mockResolvedValueOnce(undefined);
const { result } = renderHook(() => useFileManager("p1"));
let picked!: Promise<void>;
await act(async () => {
picked = result.current.uploadFile();
await Promise.resolve();
});
await waitFor(() => expect(result.current.conflict?.name).toBe("a.txt"));
await act(async () => {
result.current.resolveConflict("replace");
await picked;
});
expect(uploadFileToContainer).toHaveBeenNthCalledWith(2, "p1", "/host/a.txt", "/workspace", true);
expect(uploadFileToContainer).toHaveBeenNthCalledWith(3, "p1", "/host/b.txt", "/workspace");
});
it("does not leave the batch waiting for an answer that can never arrive", async () => {
// The pane unmounted mid-prompt (tab closed, container stopped). The upload
// promise has to settle, or `busy` never clears and the loop leaks.
uploadFileToContainer.mockRejectedValueOnce(clash("a.txt"));
const { result, unmount } = renderHook(() => useFileManager("p1"));
const { batch } = await uploadUntilPrompt(result, ["/host/a.txt"]);
unmount();
await expect(batch).resolves.toBeUndefined();
expect(uploadFileToContainer).toHaveBeenCalledTimes(1);
expect(createContainerDirectory).toHaveBeenCalledWith("p1", "/workspace", "new");
});
});
@@ -567,8 +253,6 @@ describe("useFileManager overwrite prompt closes the loop", () => {
* reported that way is a sentence nobody reads.
*/
describe("useFileManager surfaces written refusals as prose", () => {
const hiddenFolder =
'".ssh" is a hidden folder — Triple-C will not save there. Choose a visible location.';
const outsideRoots =
"Folder path is outside the folders this panel can change (/workspace, /home/claude, /tmp): /etc";
@@ -576,10 +260,10 @@ describe("useFileManager surfaces written refusals as prose", () => {
const lastToast = () => pushToast.mock.calls.at(-1)?.[0];
it("puts the write-root refusal in the headline, not behind Details", async () => {
uploadFileToContainer.mockRejectedValueOnce(outsideRoots);
createContainerDirectory.mockRejectedValueOnce(outsideRoots);
const { result } = renderHook(() => useFileManager("p1"));
await act(async () => {
await result.current.uploadPaths(["/host/a.txt"]);
await result.current.createFolder("new");
});
expect(lastToast().message).toBe(outsideRoots);
@@ -587,39 +271,24 @@ describe("useFileManager surfaces written refusals as prose", () => {
expect(lastToast().message).not.toMatch(/^Error:/);
});
it("says it once for a whole batch that failed the same way", async () => {
// The refusal is about the target directory, so every file in the drop
// fails identically — three copies of the same sentence is not detail.
uploadFileToContainer.mockRejectedValue(outsideRoots);
it("unwraps an `Error` rather than stamping \"Error:\" on prose", async () => {
renameContainerPath.mockRejectedValueOnce(new Error(outsideRoots));
const { result } = renderHook(() => useFileManager("p1"));
await act(async () => {
await result.current.uploadPaths(["/host/a.txt", "/host/b.txt"]);
await result.current.renameEntry(file("a.txt"), "b.txt");
});
expect(lastToast().message).toBe(outsideRoots);
expect(lastToast().detail).toBeUndefined();
});
it("does the same for a refused save to the host", async () => {
save.mockResolvedValue("/home/me/.ssh/a.txt");
downloadContainerFile.mockRejectedValueOnce(new Error(hiddenFolder));
const { result } = renderHook(() => useFileManager("p1"));
await act(async () => {
await result.current.downloadFile(file("a.txt"));
});
// Unwrapped: an `Error` on the way through must not stamp "Error:" on prose.
expect(lastToast().message).toBe(hiddenFolder);
});
it("keeps the hook's own headline when the failure is not a written refusal", async () => {
uploadFileToContainer.mockRejectedValueOnce("no space left on device");
createContainerDirectory.mockRejectedValueOnce("no space left on device");
const { result } = renderHook(() => useFileManager("p1"));
await act(async () => {
await result.current.uploadPaths(["/host/a.txt"]);
await result.current.createFolder("new");
});
expect(lastToast().message).toBe("A file could not be uploaded");
expect(lastToast().message).toBe('Could not create "new"');
expect(lastToast().detail).toBe("no space left on device");
});
});
+20 -235
View File
@@ -1,36 +1,8 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { save, open as openDialog } from "@tauri-apps/plugin-dialog";
import { useCallback, useRef, useState } from "react";
import type { FileEntry } from "../lib/types";
import * as commands from "../lib/tauri-commands";
import { useAppState } from "../store/appState";
import {
errorText,
fileExistsPath,
isFileExistsError,
readableRefusal,
type OverwriteChoice,
} from "../lib/uploadErrors";
/**
* One upload waiting on the user to say whether it may replace what is there.
* `remaining` is how many files are queued behind this one, which is what
* decides whether the blanket answers are worth offering.
*/
export interface UploadConflict {
/** Host file being uploaded. */
hostPath: string;
/** Bare name, for the prompt. */
name: string;
/** Container directory it is going into. */
directory: string;
remaining: number;
}
/** `/a/b/c.txt` and `C:\a\b\c.txt` both give `c.txt`. */
function baseName(path: string): string {
const parts = path.split(/[\\/]/);
return parts[parts.length - 1] || path;
}
import { errorText, readableRefusal } from "../lib/refusalText";
/**
* ## Where failures are reported
@@ -41,22 +13,19 @@ function baseName(path: string): string {
* (empty) grid. It is on screen, it is in context, it explains why there are
* no rows, and it is not transient — it stands until the directory lists.
*
* Every **transient operation** failure — upload, rename, create folder,
* save-to-host — goes to `ToastHost` instead. Those used to land
* in the same inline `error` div, which is the first child of the *scrolling*
* list: three hundred rows down, a refused rename produced no visible change
* at all, just a rename box that stayed open for no stated reason. Worse, the
* file viewer routes its "Save to host…" through the same call, and the viewer
* is a `fixed inset-0` portal at `z-50` — so that failure reported *behind* the
* dialog that caused it. The toast host is a persistent `aria-live` region at
* `z-[60]`, i.e. the one place in the app that is above a modal and does not
* scroll away.
* Every **transient operation** failure — rename, create folder — goes to
* `ToastHost` instead. Those used to land in the same inline `error` div, which
* is the first child of the *scrolling* list: three hundred rows down, a
* refused rename produced no visible change at all, just a rename box that
* stayed open for no stated reason. The toast host is a persistent `aria-live`
* region at `z-[60]`, i.e. the one place in the app that is above a modal and
* does not scroll away.
*
* ## Where the current directory lives
*
* `currentPath` is state (the UI renders it) *and* a ref (async work reads it
* after an await). Every long operation captures the directory it targets at
* the start and compares it against the ref at the end: a 200 MB upload into
* the start and compares it against the ref at the end: a slow rename in
* `/workspace` must not drag the pane back out of `src/` because that is where
* the closure happened to be created. The ref moves at the *start* of a
* navigation rather than when the listing lands, because the question being
@@ -68,14 +37,11 @@ export function useFileManager(projectId: string) {
const [entries, setEntries] = useState<FileEntry[]>([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
/** Transient "uploading 3 files…" style note, shown beside the breadcrumb. */
const [busy, setBusy] = useState<string | null>(null);
/**
* What just finished. A live region that only ever says "uploading…" tells a
* screen reader user when to start waiting and never when to stop.
* What just finished, for the live region — a rename or a new folder is a
* change a sighted user sees in the grid and a screen reader user does not.
*/
const [completed, setCompleted] = useState<string | null>(null);
const [conflict, setConflict] = useState<UploadConflict | null>(null);
const currentPathRef = useRef(currentPath);
@@ -87,45 +53,29 @@ export function useFileManager(projectId: string) {
*/
const navGeneration = useRef(0);
const startWork = useCallback((note: string) => {
setBusy(note);
setCompleted(null);
}, []);
/**
* Report a failed operation, given the headline this hook would write and the
* raw failures behind it.
* raw failure behind it.
*
* The headline is what the *hook* knows ("Could not rename …"); it is a
* category, not an explanation. Some backend refusals are already a finished
* sentence written for the person reading it — a hidden host folder, a
* container path outside the roots this panel may change — and those used to
* sentence written for the person reading it — a container path outside the
* roots this panel may change, a name it will not create — and those used to
* arrive as the toast's `detail`, which `ToastHost` renders as collapsed
* monospace behind a "Details" button. So the sentence that said what was
* wrong and what to do about it was hidden under a headline that said
* neither. When every failure reduces to the *same* such sentence — which is
* the normal case, since these refusals are about the target directory and so
* fail identically for every file in a batch — it becomes the headline and
* there is nothing left to hide.
* neither. When there is such a sentence it becomes the headline, and there
* is nothing left to hide.
*/
const report = useCallback((message: string, ...causes: unknown[]) => {
const refusals = causes.map(readableRefusal);
const shared =
causes.length > 0 && refusals.every((r) => r !== null)
? [...new Set(refusals as string[])]
: [];
const promoted = shared.length === 1 ? shared[0] : null;
const report = useCallback((message: string, cause: unknown) => {
const promoted = readableRefusal(cause);
useAppState.getState().pushToast({
kind: "error",
message: promoted ?? message,
detail: promoted || causes.length === 0 ? undefined : causes.map(errorText).join("\n"),
detail: promoted ? undefined : errorText(cause),
});
}, []);
const confirm = useCallback((message: string) => {
useAppState.getState().pushToast({ kind: "success", message });
}, []);
const navigate = useCallback(
async (path: string) => {
const mine = ++navGeneration.current;
@@ -163,164 +113,6 @@ export function useFileManager(projectId: string) {
navigate(currentPathRef.current);
}, [navigate]);
/** Copy an entry out to a host path the user picks. */
const downloadFile = useCallback(
async (entry: FileEntry) => {
try {
const hostPath = await save({ defaultPath: entry.name });
if (!hostPath) return;
// Every sibling operation sets `busy`; this one did not, so a 200 MB
// copy was a click, then a frozen-looking pane, then nothing.
startWork(`Saving "${entry.name}" to the host…`);
try {
await commands.downloadContainerFile(projectId, entry.path, hostPath);
setCompleted(`Saved "${entry.name}" to ${hostPath}.`);
confirm(`Saved "${entry.name}" to the host.`);
} finally {
setBusy(null);
}
} catch (e) {
report(`Could not save "${entry.name}" to the host`, e);
}
},
[projectId, startWork, report, confirm],
);
/**
* The pending answer to `conflict`. Kept in a ref rather than state because
* the upload loop is `await`ing it — it needs the resolver, not a re-render.
*/
const conflictResolver = useRef<((choice: OverwriteChoice) => void) | null>(null);
const resolveConflict = useCallback((choice: OverwriteChoice) => {
const resolve = conflictResolver.current;
conflictResolver.current = null;
setConflict(null);
resolve?.(choice);
}, []);
// A pane unmounted mid-prompt (the tab was closed, the container stopped)
// would otherwise leave the upload loop awaiting an answer that can never
// come. Skipping is the safe reading of "the dialog went away".
useEffect(
() => () => {
conflictResolver.current?.("skip-all");
conflictResolver.current = null;
},
[],
);
const askOverwrite = useCallback(
(hostPath: string, directory: string, remaining: number, containerPath: string | null) =>
new Promise<OverwriteChoice>((resolve) => {
// One batch asks one question at a time — the loop awaits each answer —
// so a resolver still sitting here belongs to a *different* batch (two
// drops in flight at once, or a drop landing while the Upload button's
// batch is still copying). Installing over it would leave that batch
// awaiting an answer no dialog can ever produce: a silent hang, with
// its file neither uploaded nor skipped. Skipping it is the same
// reading of "the dialog went away" the unmount cleanup uses.
conflictResolver.current?.("skip");
conflictResolver.current = resolve;
setConflict({
hostPath,
name: baseName(containerPath ?? hostPath),
directory,
remaining,
});
}),
[],
);
/**
* Copy host files into the current directory. Shared by the Upload button and
* the native drag-drop listener, so a dropped file and a picked one take the
* same path — including the one refresh at the end rather than one per file.
*
* The backend refuses to overwrite unless asked to, so a name clash is not a
* failure here: it is a question, and the answer can be given once for the
* whole batch.
*/
const uploadPaths = useCallback(
async (hostPaths: string[]) => {
if (hostPaths.length === 0) return;
// The directory this upload is *for*. Compared against the live ref at
// the end, because the user is free to walk away while it copies.
const target = currentPathRef.current;
startWork(`Uploading ${hostPaths.length} item${hostPaths.length > 1 ? "s" : ""}`);
/** Raw failures, kept unstringified so `report` can read their shape. */
const failures: unknown[] = [];
let uploaded = 0;
let skipped = 0;
/** A "…all" answer, applied to every remaining clash without asking. */
let blanket: OverwriteChoice | null = null;
try {
for (let i = 0; i < hostPaths.length; i++) {
const hostPath = hostPaths[i];
try {
await commands.uploadFileToContainer(projectId, hostPath, target);
uploaded++;
continue;
} catch (e) {
if (!isFileExistsError(e)) {
failures.push(e);
continue;
}
const choice: OverwriteChoice =
blanket ??
(await askOverwrite(
hostPath,
target,
hostPaths.length - i - 1,
fileExistsPath(e),
));
if (choice === "replace-all" || choice === "skip-all") blanket = choice;
if (choice === "skip" || choice === "skip-all") {
skipped++;
continue;
}
}
try {
await commands.uploadFileToContainer(projectId, hostPath, target, true);
uploaded++;
} catch (e) {
failures.push(e);
}
}
} finally {
setBusy(null);
}
const summary =
`Uploaded ${uploaded} item${uploaded === 1 ? "" : "s"}` +
(skipped > 0 ? `, skipped ${skipped}` : "") +
(failures.length > 0 ? `, ${failures.length} failed` : "") +
".";
setCompleted(summary);
if (failures.length > 0) {
report(
failures.length === 1 ? "A file could not be uploaded" : `${failures.length} files could not be uploaded`,
...failures,
);
}
// Only re-list if the user is still looking at the directory this went
// into. Navigating away during a slow copy used to drag the pane back.
if (currentPathRef.current === target) await navigate(target);
},
[projectId, navigate, startWork, report, askOverwrite],
);
const uploadFile = useCallback(async () => {
try {
const selected = await openDialog({ multiple: true, directory: false });
if (!selected) return;
await uploadPaths(Array.isArray(selected) ? selected : [selected as string]);
} catch (e) {
report("Could not open the file picker", e);
}
}, [uploadPaths, report]);
/**
* Rename in place. `newName` is a bare name — Rust rejects anything with a
* `/` in it, so this can never turn into a move. Resolves true on success so
@@ -368,19 +160,12 @@ export function useFileManager(projectId: string) {
loading,
/** Inline, in-context: why the listing on screen is empty. */
error,
busy,
/** What the last operation finished doing, for the live region. */
completed,
/** An upload waiting for a Replace / Skip answer, or `null`. */
conflict,
resolveConflict,
setError,
navigate,
goUp,
refresh,
downloadFile,
uploadFile,
uploadPaths,
renameEntry,
createFolder,
};