A local-first multi-agent app development platform, built on PenguinHarness
feat(web,server): 工作区选择器支持删除空目录
lmlihenge4cd22a8a5ad
diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.tsindex c068f995..cf6fec79 100644--- a/packages/server/src/api/types.ts+++ b/packages/server/src/api/types.ts@@ -1673,6 +1673,11 @@ export interface DirCreateResponse {path: string;}+/** The answer to removing one empty folder: the absolute path (realpath) that is gone. */+export interface DirDeleteResponse {+ path: string;+}+/** One Skill found in a picked directory: metadata plus which of the two layouts it came from. */export interface DirectorySkillItem extends SkillMetadataItem {/** `.agents/skills` or `.claude/skills` — shown so the origin of an offered Skill is visible. */diff --git a/packages/server/src/http/routes/dirs.ts b/packages/server/src/http/routes/dirs.tsindex 4233ebe1..d7e6ed03 100644--- a/packages/server/src/http/routes/dirs.ts+++ b/packages/server/src/http/routes/dirs.ts@@ -18,6 +18,10 @@* POST /api/projects/:p/dirs makes one folder inside the folder being browsed, which is the* picker's "New folder": see the route for what it refuses.*+ * DELETE /api/projects/:p/dirs removes one empty folder, the picker's "Delete": see the route+ * for what it refuses. It is the picker's only destructive verb, so it takes a folder, never a+ * file, and never a whole tree: a folder with anything in it is a refusal, not a walk.+ ** POST /api/projects/:p/dirs/access is the picker's way out of that refusal in the desktop* app: see the route.*@@ -27,9 +31,11 @@ import fs from "node:fs/promises";import os from "node:os";import path from "node:path";import { Hono } from "hono";+import { projectDir } from "@prismshadow/penguin-core";import type {DirAccessResponse,DirCreateResponse,+ DirDeleteResponse,DirEntryInfo,DirListResponse,} from "../../api/types.js";@@ -38,12 +44,17 @@ import { HttpError } from "../errors.js";import { requireValidId } from "../validate.js";import { Bind, Component, Use } from "@prismshadow/penguin-core/kernel";import { directorySkillsRoutes } from "./directory-skills.js";-import type { Desktop, DesktopApi } from "../../hmr/capabilities.js";+import type { Desktop, DesktopApi, Paths } from "../../hmr/capabilities.js";import type { Access } from "../../mechanisms/projects.js";/** What this route group reaches — bound by its module (src/modules). */export interface DirsRouteDeps {access: Access;+ /**+ * The data root, which holds every Project's own directory: what the delete route refuses to+ * remove (a Project's directory, and anything above it).+ */+ root: string;/** The desktop shell's service; null when this server was not started by the desktop shell. */desktop: Pick<DesktopApi, "requestFolderAccess"> | null;}@@ -118,6 +129,72 @@ export function dirsRoutes(deps: DirsRouteDeps): Hono<AppEnv> {return c.json({ path: target } satisfies DirCreateResponse, 201);});+ /**+ * The picker's "Delete": removes ONE empty folder, the one `path` names. Removal is the only+ * destructive thing the picker can ask of a filesystem it may browse anywhere on, so the+ * route is deliberately narrow. The folder must be empty — a folder with anything in it is a+ * refusal (`dir_not_empty`), never a walk: no recursive delete exists here. A root, the+ * Project's own directory and anything above it are refused outright, and so is a path that+ * names a file: this route removes folders.+ *+ * Every decision reads the resolved path (`realpath`), so a symlink cannot name a forbidden+ * folder indirectly, and the answer names the resolved folder — which is the one that was+ * removed, and the one a picker standing on a link should re-read.+ */+ app.delete("/", async (c) => {+ const projectId = requireValidId(c, "projectId");+ deps.access.requireProjectAccess(c.var.user.userId, projectId);++ const body = (await c.req.json().catch(() => null)) as { path?: unknown } | null;+ const requested = typeof body?.path === "string" ? body.path.trim() : "";+ if (!path.isAbsolute(requested)) {+ throw new HttpError(400, "dir_not_absolute", "Directory must be an absolute path.");+ }++ let real: string;+ let isDir: boolean;+ try {+ real = await fs.realpath(requested);+ isDir = (await fs.stat(real)).isDirectory();+ } catch (err) {+ throw dirDeleteError(err, requested);+ }+ if (!isDir) throw new HttpError(400, "not_a_dir", "Not a directory.");++ // A root's own parent is itself (`/` on POSIX, `C:\` on Windows). There is nothing above a+ // root to stand in afterwards, and every path is under one: a root is never a folder to go.+ if (path.dirname(real) === real) {+ throw new HttpError(+ 403,+ "dir_root_protected",+ `The root directory cannot be deleted: ${real}.`,+ );+ }+ // The Project's own directory holds its config, its Agents and their Sessions, and every+ // folder above it holds this Project beside others: neither is the picker's to remove.+ if (isSameOrAbove(real, await resolveProjectDir(deps.root, projectId))) {+ throw new HttpError(+ 403,+ "dir_project_protected",+ `The Project's directory, or one that contains it, cannot be deleted: ${real}.`,+ );+ }++ try {+ // Emptiness is asked before the removal, so "not empty" is one answer on every platform+ // (Windows reports a folder that still holds something as a permission failure); rmdir+ // stays the operation itself, so a folder that fills up in between still fails.+ if ((await fs.readdir(real)).length > 0) {+ throw new HttpError(409, "dir_not_empty", `The folder is not empty: ${real}.`);+ }+ await fs.rmdir(real);+ } catch (err) {+ if (err instanceof HttpError) throw err;+ throw dirDeleteError(err, real);+ }+ return c.json({ path: real } satisfies DirDeleteResponse);+ });+/*** The picker's "Allow access" for a folder macOS refused: the desktop shell's main process* reads it once in the app's own name, which is what makes macOS ask the user — a read from@@ -230,6 +307,56 @@ export function dirCreateError(err: unknown, target: string): HttpError {return new HttpError(500, "dir_create_failed", `Could not create this folder: ${target}.`);}+/**+ * The HTTP answer for a `rmdir` (or the emptiness check before it) that failed on `dir`. The+ * same shape as `dirCreateError`; the one refusal a removal has of its own is a folder that+ * still holds something, which is a 409 with its own code because the user's next step differs+ * (empty it, or delete nothing at all) — never a retry of the same request.+ */+export function dirDeleteError(err: unknown, target: string): HttpError {+ const code = (err as NodeJS.ErrnoException | null)?.code;+ if (code === "ENOTEMPTY" || code === "EEXIST") {+ return new HttpError(409, "dir_not_empty", `The folder is not empty: ${target}.`);+ }+ if (code === "EACCES" || code === "EPERM") {+ return new HttpError(+ 403,+ "dir_permission_denied",+ `The server is not allowed to write here: ${path.dirname(target)}.`,+ );+ }+ if (code === "ENOENT" || code === "ENOTDIR" || code === "ELOOP") {+ return new HttpError(404, "dir_not_found", `Directory does not exist: ${target}.`);+ }+ return new HttpError(500, "dir_delete_failed", `Could not delete this folder: ${target}.`);+}++/**+ * Whether `above` is `below` itself or one of the folders holding it — what the Project+ * directory's protection is made of. Both sides are resolved first, so a trailing separator,+ * a `.`/`..` in the middle and a doubled separator all compare as the folder they name.+ */+export function isSameOrAbove(above: string, below: string): boolean {+ const a = path.resolve(above);+ const b = path.resolve(below);+ return a === b || b.startsWith(a.endsWith(path.sep) ? a : `${a}${path.sep}`);+}++/**+ * The Project's own directory, resolved where it exists. The data root itself may be reached+ * through a symlink (`/tmp` and `/var` are on macOS, and an operator may point `ADELIE_HOME`+ * at one), so comparing a caller's path against the spelling `<root>/<projectId>` alone would+ * mistake a link to that folder for somewhere else.+ */+async function resolveProjectDir(root: string, projectId: string): Promise<string> {+ const dir = projectDir(root, projectId);+ try {+ return await fs.realpath(dir);+ } catch {+ return path.resolve(dir);+ }+}+/*** `requireProjectDir` with the refusal told apart from absence. That helper folds every* failure into "does not exist or is inaccessible", which is the right answer where a path is@@ -327,10 +454,15 @@ async function driveRoots(): Promise<string[]> {export class ProjectsRoutes {@Use() private readonly access!: Access;@Use() private readonly desktop!: Desktop;+ @Use() private readonly paths!: Paths;@Bind("projects.dirs") dirsRoutes!: Hono<AppEnv>;@Bind("projects.dir-skills") dirSkillsRoutes!: Hono<AppEnv>;setup() {- this.dirsRoutes = dirsRoutes({ access: this.access, desktop: this.desktop.current() });+ this.dirsRoutes = dirsRoutes({+ access: this.access,+ root: this.paths.root,+ desktop: this.desktop.current(),+ });this.dirSkillsRoutes = directorySkillsRoutes({ access: this.access });}}diff --git a/packages/server/test/dirs.test.ts b/packages/server/test/dirs.test.tsindex 91a40630..c4fa831e 100644--- a/packages/server/test/dirs.test.ts+++ b/packages/server/test/dirs.test.ts@@ -10,11 +10,12 @@ import path from "node:path";import { afterEach, beforeEach, describe, expect, it } from "vitest";import type {DirCreateResponse,+ DirDeleteResponse,DirListResponse,ProjectCreateResponse,} from "../src/api/types.js";-import { dirReadError } from "../src/http/routes/dirs.js";-import { apiClient, createTestApp, provisionUser } from "./helpers.js";+import { dirReadError, isSameOrAbove } from "../src/http/routes/dirs.js";+import { apiClient, canCreateSymlink, createTestApp, provisionUser } from "./helpers.js";import type { TestApp } from "./helpers.js";const errno = (code: string) => Object.assign(new Error(code), { code });@@ -168,3 +169,122 @@ describe("dir create api", () => {expect(await fs.readdir(dir)).toEqual([]);});});++describe("isSameOrAbove", () => {+ it("reads a folder and every folder holding it as the same answer", () => {+ expect(isSameOrAbove("/srv/app", "/srv/app")).toBe(true);+ expect(isSameOrAbove("/srv/app", "/srv/app/sub")).toBe(true);+ expect(isSameOrAbove("/srv/app/", "/srv/app/sub/")).toBe(true);+ });++ it("keeps a sibling and a child apart from its parent", () => {+ expect(isSameOrAbove("/srv/app", "/srv/app-old")).toBe(false);+ expect(isSameOrAbove("/srv/app", "/srv")).toBe(false);+ expect(isSameOrAbove("/srv/app", "/other/app")).toBe(false);+ });+});++describe("dir delete api", () => {+ let t: TestApp;+ let owner: ReturnType<typeof apiClient>;+ let projectId: string;+ let projectDir: string;+ let dir: string;++ const deleteUrl = () => `/api/projects/${projectId}/dirs`;+ const listUrl = (p: string) => `${deleteUrl()}?path=${encodeURIComponent(p)}`;+ const remove = (p: unknown) => owner.delete(deleteUrl(), { path: p });+ const codeOf = async (res: Response) =>+ ((await res.json()) as { error: { code: string } }).error.code;++ beforeEach(async () => {+ t = await createTestApp();+ const a = await provisionUser(t.app, "owner_rmdir");+ owner = apiClient(t.app, a.cookie);+ const created = (await (+ await owner.post("/api/projects", { projectId: "owner_rmdir-dirs", name: "rmdir project" })+ ).json()) as ProjectCreateResponse;+ projectId = created.project.projectId;+ projectDir = path.join(t.root, projectId);+ dir = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), "penguin-rmdir-")));+ });++ afterEach(async () => {+ await t.cleanup();+ await fs.rm(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });+ });++ it("removes one empty folder and answers with its path", async () => {+ await fs.mkdir(path.join(dir, "gone"));+ const res = await remove(path.join(dir, "gone"));+ expect(res.status).toBe(200);+ expect(((await res.json()) as DirDeleteResponse).path).toBe(path.join(dir, "gone"));+ await expect(fs.stat(path.join(dir, "gone"))).rejects.toMatchObject({ code: "ENOENT" });+ // Gone from the picker's next listing too, since that is where the row was.+ const listing = (await (await owner.get(listUrl(dir))).json()) as DirListResponse;+ expect(listing.entries.map((e) => e.name)).not.toContain("gone");+ });++ it("refuses a folder that is not empty, and leaves it whole", async () => {+ await fs.mkdir(path.join(dir, "full"));+ await fs.writeFile(path.join(dir, "full", "notes.txt"), "x");+ await fs.mkdir(path.join(dir, "full", "sub"));+ const res = await remove(path.join(dir, "full"));+ expect([res.status, await codeOf(res)]).toEqual([409, "dir_not_empty"]);+ // Not one entry was touched: there is no recursive delete behind this.+ expect((await fs.readdir(path.join(dir, "full"))).sort()).toEqual(["notes.txt", "sub"]);+ });++ it("needs an absolute path", async () => {+ for (const bad of ["relative", "", undefined]) {+ expect((await remove(bad)).status).toBe(400);+ }+ expect(await codeOf(await remove("relative"))).toBe("dir_not_absolute");+ expect(await fs.readdir(dir)).toEqual([]);+ });++ it("refuses a file: this route removes folders", async () => {+ await fs.writeFile(path.join(dir, "notes.txt"), "x");+ const res = await remove(path.join(dir, "notes.txt"));+ expect([res.status, await codeOf(res)]).toEqual([400, "not_a_dir"]);+ expect((await fs.stat(path.join(dir, "notes.txt"))).isFile()).toBe(true);+ });++ it("refuses the root", async () => {+ const res = await remove("/");+ expect([res.status, await codeOf(res)]).toEqual([403, "dir_root_protected"]);+ expect((await fs.stat("/")).isDirectory()).toBe(true);+ });++ it("refuses the Project's own directory and anything above it", async () => {+ for (const forbidden of [projectDir, t.root]) {+ const res = await remove(forbidden);+ expect([res.status, await codeOf(res)]).toEqual([403, "dir_project_protected"]);+ expect((await fs.stat(forbidden)).isDirectory()).toBe(true);+ }+ });++ it("cannot be talked into the Project's directory through a symlink", async () => {+ if (!canCreateSymlink()) return;+ const link = path.join(dir, "shortcut");+ await fs.symlink(projectDir, link, "dir");+ const res = await remove(link);+ expect([res.status, await codeOf(res)]).toEqual([403, "dir_project_protected"]);+ expect((await fs.stat(projectDir)).isDirectory()).toBe(true);+ });++ it("keeps a folder that is already gone a 404", async () => {+ const res = await remove(path.join(dir, "never"));+ expect([res.status, await codeOf(res)]).toEqual([404, "dir_not_found"]);+ });++ it("is refused to a caller who may not see the Project", async () => {+ await fs.mkdir(path.join(dir, "keep"));+ const stranger = await provisionUser(t.app, "stranger_rmdir");+ const res = await apiClient(t.app, stranger.cookie).delete(deleteUrl(), {+ path: path.join(dir, "keep"),+ });+ expect([403, 404]).toContain(res.status);+ expect((await fs.stat(path.join(dir, "keep"))).isDirectory()).toBe(true);+ });+});diff --git a/packages/web/src/api/endpoints.ts b/packages/web/src/api/endpoints.tsindex 59504133..1f504098 100644--- a/packages/web/src/api/endpoints.ts+++ b/packages/web/src/api/endpoints.ts@@ -40,6 +40,7 @@ import type {DesktopUpdateStatusResponse,DirAccessResponse,DirCreateResponse,+ DirDeleteResponse,DirectorySkillsResponse,DirListResponse,EndpointModelListRequest,@@ -745,6 +746,18 @@ export const createDir = (projectId: string, parent: string, name: string) =>body: { parent, name },});+/**+ * Removes one EMPTY folder (the picker's "Delete"): `path` is absolute and names the folder+ * itself rather than a name inside another. The server refuses anything but an empty folder —+ * it never deletes a tree, a file, the root, or the Project's own directory and its parents —+ * and only this server can be asked, like New folder.+ */+export const deleteDir = (projectId: string, path: string) =>+ apiFetch<DirDeleteResponse>(`/api/projects/${encodeURIComponent(projectId)}/dirs`, {+ method: "DELETE",+ body: { path },+ });+/*** Asks the desktop shell to read a folder macOS refused, in the app's own name — what makes* macOS ask the user. Always this server: only the shell that started it can be asked. Thediff --git a/packages/web/src/features/chat/workspace-finder-model.ts b/packages/web/src/features/chat/workspace-finder-model.tsindex 9ba279f8..57c657c4 100644--- a/packages/web/src/features/chat/workspace-finder-model.ts+++ b/packages/web/src/features/chat/workspace-finder-model.ts@@ -354,6 +354,7 @@ export type FinderMenuItem =| "open"| "choose"| "newFolder"+ | "delete"| "addToQuickAccess"| "removeFromQuickAccess"| "copyPath"@@ -361,19 +362,27 @@ export type FinderMenuItem =/*** The context menu's rows, the way Explorer orders them: what opening the thing does first,- * then choosing it, then Quick access, then copying its path. A file row only copies (files- * are listed for context and cannot be picked); the empty space acts on the open folder, and- * adds New folder and Refresh as Explorer's background menu does.+ * then choosing it, then the folder's own housekeeping (making one inside the folder on screen,+ * removing the one a row stands for), then Quick access, then copying its path. A file row only+ * copies (files are listed for context and cannot be picked); the empty space acts on the open+ * folder, and adds New folder, Delete and Refresh as Explorer's background menu does.+ *+ * `local` says the target is on this server's own filesystem. The two rows that change it — New+ * folder and Delete — are dropped for anything else: a machine browsed over ssh lists folders+ * and cannot be asked to make or remove one.*/export function finderMenuItems(target: FinderMenuTarget,inQuickAccess: boolean,+ local = true,): FinderMenuItem[] {if (target.kind === "file") return ["copyPath"];const quick = inQuickAccess ? "removeFromQuickAccess" : "addToQuickAccess";- return target.kind === "here"- ? ["choose", "newFolder", quick, "copyPath", "refresh"]- : ["open", "choose", quick, "copyPath"];+ const items: FinderMenuItem[] =+ target.kind === "here"+ ? ["choose", "newFolder", "delete", quick, "copyPath", "refresh"]+ : ["open", "choose", "delete", quick, "copyPath"];+ return local ? items : items.filter((item) => item !== "newFolder" && item !== "delete");}/** A Workspace recently used in this Project, and the machine it is on (null: this server). */diff --git a/packages/web/src/features/chat/workspace-finder.tsx b/packages/web/src/features/chat/workspace-finder.tsxindex bfc59fbe..cd62a37f 100644--- a/packages/web/src/features/chat/workspace-finder.tsx+++ b/packages/web/src/features/chat/workspace-finder.tsx@@ -15,6 +15,12 @@* The component stays mounted while closed, so it reopens where it was browsing when the host* has no Workspace set yet (the sidebar's new-workspace button picks one after another from the* same place); with one set, it reopens revealing that folder in its parent.+ *+ * It changes the folder it shows in exactly two ways, both on this server's own filesystem: New+ * folder makes one inside the folder being browsed, and Delete removes one — never a folder+ * with anything in it, never the root or the Project's own directory, and only after the+ * confirmation card says so (features/chat/workspace-finder-model.ts decides what either menu+ * offers).*/import { useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from "react";import type {@@ -27,6 +33,7 @@ import type { DesktopPrivacyPane, DirListResponse } from "@prismshadow/penguin-simport {Button,CloseIcon,+ ConfirmModal,Dropdown,GlyphIcon,ICONS,@@ -120,6 +127,7 @@ const MENU_ICON: Record<FinderMenuItem, string> = {open: ICONS.folderOpen,choose: CHECK_ICON,newFolder: ICONS.folderPlus,+ delete: ICONS.trash,addToQuickAccess: ICONS.pin,removeFromQuickAccess: ICONS.pin,copyPath: STAT_ICONS.copy,@@ -222,6 +230,14 @@ export function WorkspaceFinder({const [newFolderName, setNewFolderName] = useState("");const [creating, setCreating] = useState(false);const newFolderRef = useRef<HTMLInputElement>(null);+ /**+ * The folder the Delete confirmation is about (null: nothing is being removed), and whether+ * the request is in flight. Removal is the finder's one irreversible action, so it never+ * happens on the row that was clicked: that row opens the card, and only the card's own+ * button sends it.+ */+ const [deleteTarget, setDeleteTarget] = useState<string | null>(null);+ const [deleting, setDeleting] = useState(false);/** The address bar is a path field (clicked, or ⌘⇧G) rather than breadcrumbs; the draft is what it holds. */const [addressEditing, setAddressEditing] = useState(false);const [addressDraft, setAddressDraft] = useState("");@@ -427,6 +443,15 @@ export function WorkspaceFinder({const crumbs = splitBreadcrumbs(view.path);/** "New folder" is offered only where it can be honoured: this server's own filesystem. */const canCreateFolder = machine === null && view.error === null && view.listing !== null;+ /**+ * What a toolbar Delete would remove: the row picked, when it is a folder on this server.+ * The folder on screen is deleted from the list's own menu instead (its empty space), so the+ * toolbar has one unambiguous subject — the selection the user is looking at.+ */+ const deletableSelection =+ canCreateFolder && selectedEntry !== null && isFolder(selectedEntry)+ ? selectedEntry.path+ : null;// Opening the box puts the caret in it, selected, so a name is typed straight over any// suggestion the browser made. Keyed on the box alone: re-running per keystroke would fight@@ -525,6 +550,45 @@ export function WorkspaceFinder({.finally(() => setCreating(false));};+ /**+ * Asks before removing `path`: the card is the whole transaction, and it carries the one+ * rule that makes the answer safe to expect — only an empty folder can go. A target on+ * another machine is not ours to change, exactly as for New folder (a machine browsed over+ * ssh lists folders and cannot be asked to remove one), so nothing is asked there.+ */+ const askDelete = (path: string, onMachine: string | null) => {+ if (onMachine !== null) return;+ setDeleteTarget(path);+ };++ /**+ * Removes the empty folder the card named. A folder that is not empty — the case the card+ * warned about — comes back as its own refusal, shown as a toast: unlike a folder name there+ * is nothing in the dialog to change, so the card closes on the reason rather than staying+ * open on it. Afterwards the list is read again, since a folder that is gone must not stay on+ * screen; when the folder removed was the one being browsed, the finder stands in its parent.+ */+ const deleteFolder = () => {+ const target = deleteTarget;+ if (target === null || deleting) return;+ setDeleting(true);+ api+ .deleteDir(projectId, target)+ .then((res) => {+ const removedHere = res.path === view.listing?.path;+ const parent = removedHere ? parentOf(res.path) : null;+ setDeleteTarget(null);+ toastSuccess(f.folderDeleted(baseName(res.path)));+ if (parent !== null) load(parent, { record: false });+ else refresh();+ })+ .catch((err: unknown) => {+ setDeleteTarget(null);+ toastError(apiErrorText(err));+ })+ .finally(() => setDeleting(false));+ };+/*** "Allow access": the shell reads the refused folder in the app's own name, which is what* makes macOS ask. Granted, the folder is read again — unless the finder has moved on while@@ -630,6 +694,11 @@ export function WorkspaceFinder({// panel's item filter), so there is nothing to re-root: the box opens where we stand.startNewFolder();break;+ case "delete":+ // Likewise this server's own folders only; what goes is the row the menu stands on —+ // the folder itself, or the folder on screen when the menu came from empty space.+ askDelete(target.path, target.machine);+ break;case "addToQuickAccess":case "removeFromQuickAccess":editQuickAccess(target.path, target.machine, item === "addToQuickAccess");@@ -655,6 +724,8 @@ export function WorkspaceFinder({return target.kind === "here" ? f.chooseCurrent : f.chooseThis;case "newFolder":return f.newFolder;+ case "delete":+ return f.deleteFolder;case "addToQuickAccess":return f.addToQuickAccess;case "removeFromQuickAccess":@@ -1229,6 +1300,20 @@ export function WorkspaceFinder({<GlyphIcon d={ICONS.folderPlus} size={ICON_SIZE.iconButton} /></button>)}+ {/* Delete sits beside it — the same filesystem work, on the row that is picked rather+ than on the folder on screen — and a phone reaches both from the list's context+ menu, where the toolbar keeps only the navigation. */}+ {deletableSelection !== null && (+ <button+ type="button"+ className={`${navButtonClass} hidden sm:block`}+ data-tooltip={f.deleteFolder}+ aria-label={f.deleteFolder}+ onClick={() => askDelete(deletableSelection, machine)}+ >+ <GlyphIcon d={ICONS.trash} size={ICON_SIZE.iconButton} />+ </button>+ )}</div>{addressBar}<label className="relative flex shrink-0 items-center">@@ -1548,21 +1633,43 @@ export function WorkspaceFinder({button={null}><Menu density="sm">- {finderMenuItems(menuTarget, inQuickAccess(menuTarget.path, menuTarget.machine))- // Making a folder is this server's own filesystem work: a machine browsed over ssh- // lists folders and cannot be asked to make one, so the row is not offered there.- .filter((item) => item !== "newFolder" || menuTarget.machine === null)- .map((item) => (- <MenuItem- key={item}- glyph={MENU_ICON[item]}- label={menuLabel(item, menuTarget)}- onSelect={() => runMenuItem(item, menuTarget)}- />- ))}+ {finderMenuItems(+ menuTarget,+ inQuickAccess(menuTarget.path, menuTarget.machine),+ // Making and removing a folder are this server's own filesystem work, so both+ // rows are dropped for a target on another machine (one browsed over ssh lists+ // folders and cannot be asked to change them).+ menuTarget.machine === null,+ ).map((item) => (+ <MenuItem+ key={item}+ glyph={MENU_ICON[item]}+ label={menuLabel(item, menuTarget)}+ onSelect={() => runMenuItem(item, menuTarget)}+ />+ ))}</Menu></Dropdown>)}+ {/* Removing a folder is the finder's one irreversible action, so it is asked for and never+ assumed: the card names the folder, says the rule the server enforces (only an empty+ folder can go) and waits. It stacks over this dialog of its own accord — Modals are+ portaled to body and share one Escape stack — so one Escape closes the card and leaves+ the finder where it was browsing. */}+ <ConfirmModal+ open={deleteTarget !== null}+ title={f.deleteFolderTitle}+ tone="danger"+ confirmLabel={S.common.delete}+ cancelLabel={S.common.cancel}+ busy={deleting}+ onClose={() => setDeleteTarget(null)}+ onConfirm={deleteFolder}+ >+ <p className="break-all text-sm text-gray-600 dark:text-gray-300">+ {deleteTarget !== null ? f.deleteFolderConfirm(baseName(deleteTarget)) : ""}+ </p>+ </ConfirmModal></Modal>);}diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.tsindex cd62a3e8..424b88c1 100644--- a/packages/web/src/lib/strings-en.ts+++ b/packages/web/src/lib/strings-en.ts@@ -2478,6 +2478,18 @@ export const en: Strings = {newFolder: "New folder",newFolderName: "Folder name",newFolderHint: "Type a name and press Enter to create it, Escape to cancel",+ /** The context-menu row that removes one folder on this server. */+ deleteFolder: "Delete folder",+ /** Names the delete confirmation for assistive tech (the card itself has no title bar). */+ deleteFolderTitle: "Delete folder",+ /**+ * The delete confirmation: what goes, and the rule the server enforces — only an empty+ * folder can be removed, and there is no undo (nothing is moved to a trash).+ */+ deleteFolderConfirm: (name: string): string =>+ `Delete the folder "${name}"? Only an empty folder can be deleted — the server refuses one that still holds anything — and a deleted folder cannot be recovered.`,+ /** The toast after one was removed. */+ folderDeleted: (name: string): string => `Deleted the folder "${name}"`,chooseThis: "Choose this folder",chooseCurrent: "Choose the current folder",copyPath: "Copy path",@@ -4963,12 +4975,17 @@ Scenarios:image_too_large: "The image is too large to send inline.",dir_not_absolute: "The directory must be an absolute path.",dir_not_found: "That directory does not exist or is inaccessible.",- dir_permission_denied: "Reading that directory is not allowed.",+ dir_permission_denied: "The server is not allowed to access that directory.",dir_name_empty: "Enter a folder name.",dir_name_invalid:"A folder name cannot be a path, `.` or `..`, nor contain characters the system refuses.",dir_exists: "That name is already taken.",dir_create_failed: "Could not create that folder.",+ dir_not_empty: "That folder is not empty — only an empty folder can be deleted.",+ dir_root_protected: "The root directory cannot be deleted.",+ dir_project_protected:+ "The Project's own directory, or a directory that contains it, cannot be deleted.",+ dir_delete_failed: "Could not delete that folder.",not_a_dir: "That path is not a directory.",path_not_found: "That path does not exist.",reveal_failed: "Could not open the folder.",diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.tsindex e822d622..3182e707 100644--- a/packages/web/src/lib/strings.ts+++ b/packages/web/src/lib/strings.ts@@ -2528,6 +2528,18 @@ export const zh = {newFolderName: "文件夹名称",/** The name box's accessible name and tooltip: Enter makes it, Escape cancels. */newFolderHint: "输入名称后按 Enter 创建,按 Esc 取消",+ /** The context-menu row that removes one folder on this server. */+ deleteFolder: "删除文件夹",+ /** Names the delete confirmation for assistive tech (the card itself has no title bar). */+ deleteFolderTitle: "删除文件夹",+ /**+ * The delete confirmation: what goes, and the rule the server enforces — only an empty+ * folder can be removed, and there is no undo (nothing is moved to a trash).+ */+ deleteFolderConfirm: (name: string): string =>+ `删除文件夹「${name}」?只能删除空文件夹,里面还有内容时服务端会拒绝,且删除不可恢复。`,+ /** The toast after one was removed. */+ folderDeleted: (name: string): string => `已删除文件夹「${name}」`,chooseThis: "选择此文件夹",chooseCurrent: "选择当前文件夹",copyPath: "复制路径",@@ -4984,11 +4996,15 @@ Benchmark:image_too_large: "图片过大,无法随对话发送。",dir_not_absolute: "目录必须是绝对路径。",dir_not_found: "该目录不存在或不可访问。",- dir_permission_denied: "没有读取该目录的权限。",+ dir_permission_denied: "没有访问该目录的权限。",dir_name_empty: "请输入文件夹名称。",dir_name_invalid: "文件夹名称不能是路径、`.` 或 `..`,也不能含有系统不接受的字符。",dir_exists: "这个名称已被占用。",dir_create_failed: "无法创建该文件夹。",+ dir_not_empty: "该文件夹不是空的,只能删除空文件夹。",+ dir_root_protected: "不能删除根目录。",+ dir_project_protected: "不能删除项目目录,或包含项目目录的上级目录。",+ dir_delete_failed: "无法删除该文件夹。",not_a_dir: "该路径不是目录。",path_not_found: "该路径不存在。",reveal_failed: "无法打开文件夹。",diff --git a/packages/web/test/workspace-finder.test.ts b/packages/web/test/workspace-finder.test.tsindex 23e86b29..2261e5c3 100644--- a/packages/web/test/workspace-finder.test.ts+++ b/packages/web/test/workspace-finder.test.ts@@ -12,8 +12,10 @@* - Quick access offers each platform's standard folders that exist there (Windows names* ignoring case), keeps Windows drives apart, takes the user's additions and removals (a* default included), and stores them per machine, reading anything unreadable as none.- * - The context menu offers open, choose, Quick access and copy on a folder, copy only on a- * file, and acts on the open folder (with Refresh) from the list's empty space.+ * - The context menu offers open, choose, Delete, Quick access and copy on a folder, copy only+ * on a file, and acts on the open folder (with New folder, Delete and Refresh) from the+ * list's empty space — while a target on another machine carries neither of the two rows that+ * would change that machine's filesystem.* - Recent folds the newest Session per Workspace across Agents, leaving temporary ones out;* "go to" resolves ~ against the machine's home.* - A folder the server may not read gets a box of its own: the desktop app's access request@@ -274,11 +276,12 @@ describe("quick access", () => {});describe("the context menu", () => {- it("offers a folder open, choose, Quick access and copy; a file only copy", () => {+ it("offers a folder open, choose, Delete, Quick access and copy; a file only copy", () => {const folder = { kind: "folder" as const, path: "/p/a", machine: null };expect(finderMenuItems(folder, false)).toEqual(["open","choose",+ "delete","addToQuickAccess","copyPath",]);@@ -286,10 +289,11 @@ describe("the context menu", () => {expect(finderMenuItems({ ...folder, kind: "file" }, false)).toEqual(["copyPath"]);});- it("acts on the open folder from the list's empty space, with New folder and Refresh", () => {+ it("acts on the open folder from the list's empty space, with New folder, Delete and Refresh", () => {expect(finderMenuItems({ kind: "here", path: "/p", machine: null }, false)).toEqual(["choose","newFolder",+ "delete","addToQuickAccess","copyPath","refresh",@@ -301,6 +305,35 @@ describe("the context menu", () => {expect(finderMenuItems(folder, false)).not.toContain("newFolder");expect(finderMenuItems({ ...folder, kind: "file" }, false)).not.toContain("newFolder");});++ it("never offers Delete for a file: this is the folder picker's own action", () => {+ const file = { kind: "file" as const, path: "/p/a.txt", machine: null };+ expect(finderMenuItems(file, false)).not.toContain("delete");+ });++ it("drops New folder and Delete for a target that is not this server's", () => {+ // Another machine lists folders over ssh and cannot be asked to make or remove one; the+ // two rows that would change its filesystem are the ones that go.+ const here = { kind: "here" as const, path: "/p", machine: "far" };+ const row = { kind: "folder" as const, path: "/p/a", machine: "far" };+ expect(finderMenuItems(here, false, false)).toEqual([+ "choose",+ "addToQuickAccess",+ "copyPath",+ "refresh",+ ]);+ expect(finderMenuItems(row, false, false)).toEqual([+ "open",+ "choose",+ "addToQuickAccess",+ "copyPath",+ ]);+ // This server's own folders keep both: New folder on the folder on screen, Delete on either.+ expect(finderMenuItems({ ...here, machine: null }, false, true)).toContain("newFolder");+ expect(finderMenuItems({ kind: "folder", path: "/p/a", machine: null }, false, true)).toContain(+ "delete",+ );+ });});describe("recent and go to folder", () => {