Skip to content

Commit a2a129f

Browse files
authored
feat: create a folder from the project picker's browse tab (#31644)
The project picker's Browse tab can list the gateway host's folders and select one, but not make one, so starting a project in a new folder meant leaving the dashboard for a shell on the gateway host. Add a New folder control beside "Add ... to favorites". It opens a name field; Enter or Create makes the folder in the directory on screen and lists it, so Select makes it the project. Escape closes only the field, and a refusal is explained under it with the typed name kept. The server side is one owner-only route, POST /api/browse-dirs/create, that makes exactly one folder level. It refuses an existing name, a name with a slash, a protected location (the sensitive-path floor is checked on the new path before anything is created) and a parent it cannot write to, and audits each outcome. Builds on #26007 by @alparamonov. Closes #26005
1 parent 20764b5 commit a2a129f

30 files changed

Lines changed: 1005 additions & 45 deletions

‎docs/feature-map/README.md‎

Lines changed: 1 addition & 0 deletions
Large diffs are not rendered by default.

‎docs/system-specs/modules/learn-cron-dashboard.md‎

Lines changed: 3 additions & 3 deletions
Large diffs are not rendered by default.

‎src/kiro_crew/dashboard/file_api/browse.py‎

Lines changed: 145 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,28 @@
1-
"""Listings behind the directory pickers ``/api/browse-dirs`` and ``/api/browse-files``."""
1+
"""Listings behind the directory pickers ``/api/browse-dirs`` and ``/api/browse-files``,
2+
and the project picker's folder create, ``POST /api/browse-dirs/create``."""
23

34
from __future__ import annotations
45

6+
import errno
7+
import ntpath
58
import os
69
from typing import TYPE_CHECKING
710

11+
from aiohttp import web
12+
813
if TYPE_CHECKING:
914
from kiro_crew.dashboard.handlers.files import (
1015
_WIN_DRIVE_ROOT_RE,
16+
_PathProbeBusy,
17+
_probe_busy_response,
18+
_run_path_probe,
19+
_sel,
1120
is_sensitive_canonical_path,
21+
logger,
22+
pinned_fs,
1223
platform_compat,
24+
read_bounded_json,
25+
require_owner_dashboard_request,
1326
)
1427

1528

@@ -138,3 +151,134 @@ def _browse_parent(base: str) -> str:
138151
if _is_windows_drive_root(base):
139152
return ""
140153
return os.path.dirname(base)
154+
155+
156+
def _create_browse_dir_sync(parent: str, name: str) -> tuple[str, str]:
157+
"""Make folder *name* inside directory *parent*: ``(outcome, path)``.
158+
159+
Blocking (``realpath`` then ``mkdir``); the route runs it on the probe pool.
160+
The target is spelled the way the OS will create it (``abspath``: on Windows
161+
``C:x`` leaves *parent* and a trailing dot is dropped) and must sit directly
162+
in *parent*. It then meets the sensitive-path floor before anything is
163+
created, so the picker cannot make a protected folder (``~/.aws`` in a home
164+
without one); a path inside a protected one is protected too, so this also
165+
refuses a protected *parent*. Outcomes: ``created``, ``sensitive``,
166+
``exists``, ``not_found`` (the parent is gone or is not a directory),
167+
``parent_changed``, ``permission_denied``, ``invalid_name`` and ``failed``.
168+
169+
The checked *parent* is pinned before the create, the way uploads pin theirs,
170+
so an ancestor swapped for a link after the check cannot redirect the folder
171+
into a protected place: on POSIX the leaf is made relative to a descriptor
172+
walked with ``O_NOFOLLOW`` (``pinned_fs.pin_parent``); on Windows a handle
173+
without delete sharing locks the chain against renames while ``mkdir`` runs,
174+
once its final path is confirmed to be *parent*. A swap is ``parent_changed``.
175+
"""
176+
base = os.path.realpath(os.path.expanduser(parent))
177+
target = os.path.abspath(os.path.join(base, name))
178+
if os.path.normcase(os.path.dirname(target)) != os.path.normcase(base):
179+
return "invalid_name", target
180+
if is_sensitive_canonical_path(target):
181+
return "sensitive", target
182+
guard_fd: int | None = None
183+
try:
184+
if pinned_fs.supports_pinned_walk() and os.mkdir in os.supports_dir_fd:
185+
guard_fd = pinned_fs.pin_parent(base, what="new folder's parent")
186+
os.mkdir(os.path.basename(target), dir_fd=guard_fd)
187+
elif platform_compat.IS_WINDOWS:
188+
guard_fd = platform_compat.pin_directory(base, links_only=True)
189+
pinned = pinned_fs.fd_real_path(guard_fd)
190+
if pinned is None or ntpath.normcase(ntpath.normpath(pinned)) != ntpath.normcase(
191+
ntpath.normpath(base)
192+
):
193+
return "parent_changed", target
194+
os.mkdir(target)
195+
else:
196+
# Neither pin exists here (unreachable on Linux, macOS and Windows):
197+
# a by-name mkdir would be the unguarded swap window, so refuse.
198+
return "failed", target
199+
except (pinned_fs.PinnedPathRefusal, NotADirectoryError):
200+
# The POSIX walk and the Windows pin refuse a link and a non-directory alike;
201+
# a parent that is no directory at all is the plain "gone" case, anything
202+
# else was swapped.
203+
return ("parent_changed" if os.path.isdir(base) else "not_found"), target
204+
except FileExistsError:
205+
return "exists", target
206+
except FileNotFoundError:
207+
# With the parent still there it was the name: Windows reports an overlong
208+
# one as a missing path.
209+
return ("invalid_name" if os.path.isdir(base) else "not_found"), target
210+
except PermissionError:
211+
return "permission_denied", target
212+
except ValueError: # a NUL or an unencodable character in the name
213+
return "invalid_name", target
214+
except OSError as exc:
215+
if exc.errno == errno.EROFS:
216+
return "permission_denied", target
217+
if exc.errno in (errno.ENAMETOOLONG, errno.EINVAL):
218+
return "invalid_name", target
219+
if exc.errno == errno.ELOOP:
220+
return "parent_changed", target
221+
logger.warning("browse_create_dir failed for %s: errno %s", target, exc.errno)
222+
return "failed", target
223+
finally:
224+
if guard_fd is not None:
225+
os.close(guard_fd)
226+
return "created", target
227+
228+
229+
async def api_browse_create_dir(request: web.Request) -> web.Response:
230+
"""POST /api/browse-dirs/create -- make one folder in the directory the picker shows.
231+
232+
Body ``{"parent": <directory>, "name": <folder name>}``; answers 201
233+
``{"path"}`` with the new folder's path so the picker can list it. Owner-only,
234+
checked before the body is read, like ``/api/file-write``: it writes to the
235+
gateway host's filesystem. *name* is one path component, so the route makes
236+
exactly one folder level. Every refusal carries a ``code`` for the picker.
237+
"""
238+
owner_denied = await require_owner_dashboard_request(request, "browse_create_dir")
239+
if owner_denied is not None:
240+
return owner_denied
241+
caller = request.get("user", "dashboard")
242+
body, body_err = await read_bounded_json(request)
243+
if body_err is not None:
244+
return body_err
245+
assert body is not None # read_bounded_json returns (dict, None) on success
246+
parent, name = body.get("parent"), body.get("name")
247+
if not isinstance(parent, str) or not parent.strip():
248+
return web.json_response(
249+
{"error": "A parent directory is required", "code": "parent_required"}, status=400
250+
)
251+
if not isinstance(name, str) or name in ("", ".", "..") or "/" in name or "\\" in name:
252+
return web.json_response(
253+
{"error": "Not a valid folder name", "code": "invalid_name"}, status=400
254+
)
255+
try:
256+
outcome, target = await _run_path_probe(_create_browse_dir_sync, parent.strip(), name)
257+
except _PathProbeBusy:
258+
return _probe_busy_response(resource=parent, operation="browse_create_dir", caller=caller)
259+
if outcome == "created":
260+
_sel().log_api_access(
261+
caller=caller, operation="browse_create_dir", outcome="allowed", resources=target
262+
)
263+
return web.json_response({"path": target}, status=201)
264+
status, code, message = {
265+
"sensitive": (403, "access_denied", "Access denied"),
266+
"exists": (409, "already_exists", "A file or folder with that name already exists"),
267+
"not_found": (404, "not_found", "The parent directory no longer exists"),
268+
"parent_changed": (
269+
409,
270+
"parent_changed",
271+
"The parent directory changed while the folder was being created",
272+
),
273+
"permission_denied": (403, "permission_denied", "No permission to create a folder here"),
274+
"invalid_name": (400, "invalid_name", "Not a valid folder name"),
275+
"failed": (500, "create_failed", "Could not create the folder"),
276+
}[outcome]
277+
_sel().log_api_access(
278+
caller=caller,
279+
operation="browse_create_dir",
280+
outcome="denied" if status < 500 else "failure",
281+
resources=target,
282+
error=code,
283+
)
284+
return web.json_response({"error": message, "code": code}, status=status)

‎src/kiro_crew/dashboard/handlers/__init__.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -177,6 +177,7 @@ def sel():
177177
from kiro_crew.dashboard.handlers.files import ( # noqa: E402, F401
178178
_validate_dashboard_path,
179179
_write_file_restricted,
180+
api_browse_create_dir,
180181
api_browse_dirs,
181182
api_browse_files,
182183
api_channel_upload_file,

‎src/kiro_crew/dashboard/handlers/files.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -120,7 +120,9 @@
120120
_browse_entry_is_dir,
121121
_browse_files_sync,
122122
_browse_parent,
123+
_create_browse_dir_sync,
123124
_is_windows_drive_root,
125+
api_browse_create_dir,
124126
)
125127
from kiro_crew.dashboard.file_api.channel_upload import ( # noqa: F401
126128
_gate_upload_file,

‎src/kiro_crew/dashboard/routes/taskrunner.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,7 @@ def register(app: web.Application) -> None:
6565
app.router.add_post("/api/file-grep", handlers.api_file_grep)
6666
app.router.add_get("/api/file-sheet", handlers.api_file_sheet)
6767
app.router.add_get("/api/browse-dirs", handlers.api_browse_dirs)
68+
app.router.add_post("/api/browse-dirs/create", handlers.api_browse_create_dir)
6869
app.router.add_get("/api/browse-files", handlers.api_browse_files)
6970
app.router.add_get("/api/project/git", _local_files(handlers.api_project_git))
7071
app.router.add_get("/api/project/git/status", _local_files(handlers.api_project_git_status))

0 commit comments

Comments
 (0)