feat(webui): add a host directory picker and refine composer controls

This commit is contained in:
chengyongru authored and chengyongru committed 2026-10-08 20:33:15 +08:00
1 parent 3865bde3fe
commit 66c8d41f66
32 files changed
+1974 -464

No files matched your search

@@ -4232,3 +4232,69 @@ async def test_star_prompt_requires_authenticated_mutation_and_persists_dismissa
finally:
await channel.stop()
await server_task
@pytest.mark.asyncio
@pytest.mark.parametrize("connection", [_LOCAL, _REMOTE])
async def test_project_directory_http_read_requires_auth_and_keeps_scope(
bus: MagicMock, tmp_path: Path, connection: _FakeConn,
) -> None:
root = tmp_path / "folders"
root.mkdir()
(root / "project").mkdir()
(root / "private.txt").write_text("not returned")
channel = _ch(bus, workspace_path=tmp_path)
path = f"/api/workspaces/directories?path={root}"
response = await channel.gateway.http._dispatch_misc_routes(connection, _FakeReq({}, path=path), "/api/workspaces/directories")
assert response is not None and response.status_code == 401
token = channel.gateway.tokens.issue_api_token(300)
request = _FakeReq({"Authorization": f"Bearer {token}"}, path=path)
response = await channel.gateway.http._dispatch_misc_routes(connection, request, "/api/workspaces/directories")
assert response is not None and response.status_code == 200
assert json.loads(response.body)["entries"] == [{"name": "project", "path": str(root / "project")}]
partial_request = _FakeReq({"Authorization": f"Bearer {token}"}, path=f"/api/workspaces/directories?path={root / 'proj'}&partial=1")
partial_response = await channel.gateway.http._dispatch_misc_routes(connection, partial_request, "/api/workspaces/directories")
assert partial_response is not None and partial_response.status_code == 200
assert json.loads(partial_response.body)["partial"] is True
assert json.loads(partial_response.body)["entries"] == [{"name": "project", "path": str(root / "project")}]
assert channel.gateway.workspaces.default_scope().project_path == tmp_path
@pytest.mark.asyncio
@pytest.mark.parametrize("connection", [_LOCAL, _REMOTE])
async def test_project_selection_remembers_resolved_path_without_changing_access(
bus: MagicMock, tmp_path: Path, connection: _FakeConn,
) -> None:
project = tmp_path / "project"
project.mkdir()
channel = _ch(bus, workspace_path=tmp_path)
scope = channel.gateway.workspaces.default_scope()
response = await _webui_mutate(channel, "workspace.resolve_project", {"path": str(project)}, connection=connection)
assert response.status_code == 200
assert response.json() == {"name": "project", "path": str(project)}
assert channel.gateway.workspaces.default_scope() == scope
payload = channel.gateway.workspaces.payload(can_change_project=True, can_use_full_access=False)
assert payload["recent_projects"] == [{"name": "project", "path": str(project)}]
rejected = await _webui_mutate(channel, "workspace.resolve_project", {"path": str(tmp_path / "missing")}, connection=connection)
assert rejected.status_code == 400
assert channel.gateway.workspaces.payload(can_change_project=True, can_use_full_access=False)["recent_projects"] == payload["recent_projects"]
@pytest.mark.asyncio
@pytest.mark.parametrize("connection", [_LOCAL, _REMOTE])
async def test_project_favorites_mutation_persists_without_selecting_project(
bus: MagicMock, tmp_path: Path, connection: _FakeConn,
) -> None:
project = tmp_path / "pinned"
project.mkdir()
channel = _ch(bus, workspace_path=tmp_path)
response = await _webui_mutate(channel, "workspace.favorite", {"path": str(project), "pinned": True}, connection=connection)
assert response.status_code == 200
assert response.json() == {"favorite_projects": [{"name": "pinned", "path": str(project)}]}
payload = channel.gateway.workspaces.payload(can_change_project=True, can_use_full_access=False)
assert payload["favorite_projects"] == response.json()["favorite_projects"]
assert payload["recent_projects"] == []
assert payload["default_scope"]["project_path"] == str(tmp_path)
response = await _webui_mutate(channel, "workspace.favorite", {"path": str(project), "pinned": False}, connection=connection)
assert response.status_code == 200
assert response.json() == {"favorite_projects": []}
+87
View File
@@ -0,0 +1,87 @@
"""Directory metadata for the authenticated WebUI project selector."""
from __future__ import annotations
import heapq
import os
import platform
import socket
import stat
from pathlib import Path
from typing import TypedDict
from nanobot.security.workspace_access import WorkspaceScopeError
class ProjectDirectory(TypedDict):
name: str
path: str
class WorkspaceDirectories(TypedDict):
path: str
parent: str | None
entries: list[ProjectDirectory]
partial: bool
truncated: bool
host: str
platform: str
def browse_workspace_directories(
raw_path: str, *, default_workspace: Path, query: str = "", show_hidden: bool = False,
allow_partial: bool = False,
) -> WorkspaceDirectories:
"""List directories for project selection, independently of agent tool access.
The caller must authorize project selection. This capability discloses
directory names under a user-selected root; it never reads file contents or
changes the selected project or its read/write permissions.
"""
if "\0" in raw_path:
raise WorkspaceScopeError("path contains invalid characters")
path = Path(raw_path).expanduser() if raw_path else default_workspace
if not path.is_absolute():
raise WorkspaceScopeError("path must be absolute")
try:
prefix = ""
partial = False
if allow_partial:
try:
is_directory = stat.S_ISDIR(path.stat().st_mode)
except (FileNotFoundError, NotADirectoryError):
is_directory = False
if not is_directory:
prefix = path.name.casefold()
path = path.parent
partial = True
path = path.resolve(strict=True)
matches: list[ProjectDirectory] = []
with os.scandir(path) as entries:
for entry in entries:
if not entry.name.casefold().startswith(prefix) or query.casefold() not in entry.name.casefold():
continue
try:
if not entry.is_dir():
continue
hidden = entry.name.startswith(".") or (
os.name == "nt"
and bool(entry.stat(follow_symlinks=False).st_file_attributes & stat.FILE_ATTRIBUTE_HIDDEN)
)
if show_hidden or prefix.startswith(".") or not hidden:
matches.append({"name": entry.name, "path": entry.path})
except OSError:
continue
return {
"path": str(path),
"parent": str(path.parent) if path.parent != path else None,
"entries": heapq.nsmallest(500, matches, key=lambda item: item["name"].casefold()),
"partial": partial,
"truncated": len(matches) > 500,
"host": socket.gethostname(),
"platform": platform.system(),
}
except PermissionError as exc:
raise WorkspaceScopeError("directory is not accessible", status=403) from exc
except (OSError, RuntimeError) as exc:
raise WorkspaceScopeError("directory was not found or could not be listed") from exc
+77
View File
@@ -4,6 +4,8 @@ from __future__ import annotations
import json
import os
import platform
import socket
import time
from collections import OrderedDict
from pathlib import Path
@@ -51,6 +53,8 @@ def default_webui_workspace_state() -> dict[str, Any]:
"schema_version": WEBUI_WORKSPACE_STATE_SCHEMA_VERSION,
"default_access_mode": "default",
"updated_at": None,
"recent_projects": [],
"favorite_projects": [],
}
@@ -64,9 +68,27 @@ def normalize_webui_workspace_state(raw: Any) -> dict[str, Any]:
default_access_mode = raw.get("default_access_mode")
if default_access_mode in _DEFAULT_ACCESS_MODES:
state["default_access_mode"] = default_access_mode
for key, limit in (("recent_projects", 20), ("favorite_projects", 40)):
paths = raw.get(key)
if isinstance(paths, list):
state[key] = list(dict.fromkeys(
path for path in cast(list[object], paths)
if isinstance(path, str) and "\0" not in path and Path(path).is_absolute()
))[:limit]
return state
def remember_webui_project(path: Path) -> None:
state = read_webui_workspace_state()
recent = [str(path), *(item for item in state["recent_projects"] if item != str(path))][:20]
if recent != state["recent_projects"]:
state["recent_projects"] = recent
try:
write_webui_workspace_state(state)
except OSError:
logger.exception("failed to save recent WebUI projects")
def read_webui_workspace_state() -> dict[str, Any]:
path = webui_workspace_state_path()
if not path.is_file():
@@ -170,10 +192,22 @@ def workspaces_payload(
"schema_version": WEBUI_WORKSPACE_STATE_SCHEMA_VERSION,
"default_access_mode": default_access_mode,
"default_scope": default_scope.payload(),
"host": {"name": socket.gethostname(), "platform": platform.system()},
"favorite_projects": [
{"name": Path(path).name or path, "path": path}
for path in read_webui_workspace_state()["favorite_projects"]
],
"recent_projects": [
{"name": Path(path).name or path, "path": path}
for path in read_webui_workspace_state()["recent_projects"]
],
"controls": {
"can_change_project": can_change_project,
"can_use_full_access": can_use_full_access,
"can_pick_folder": folder_picker_available,
"can_browse_directories": can_change_project,
"can_resolve_project": can_change_project,
"can_manage_favorites": can_change_project,
},
}
@@ -280,6 +314,47 @@ class WebUIWorkspaceController:
folder_picker_available=folder_picker_available,
)
def resolve_project(self, path: object) -> dict[str, str]:
"""Validate and remember a selection without changing any chat's scope."""
if not isinstance(path, str) or not path.strip():
raise WorkspaceScopeError("project_path must be a nonempty string")
scope = validate_workspace_scope_payload(
{"project_path": path.strip(), "access_mode": "restricted"},
default_workspace=self._default_workspace,
default_restrict_to_workspace=self._default_restrict_to_workspace,
source_channel=_WEBUI_SCOPE_CHANNEL,
)
remember_webui_project(scope.project_path)
return {"path": str(scope.project_path), "name": scope.project_name}
def set_favorite_project(self, path: object, pinned: object) -> list[dict[str, str]]:
"""Pin validated folders; allow removing a favorite after it is deleted."""
if not isinstance(path, str) or not path.strip() or "\0" in path:
raise WorkspaceScopeError("path must be a nonempty directory path")
if not isinstance(pinned, bool):
raise WorkspaceScopeError("pinned must be a boolean")
path = path.strip()
if pinned:
scope = validate_workspace_scope_payload(
{"project_path": path, "access_mode": "restricted"},
default_workspace=self._default_workspace,
default_restrict_to_workspace=self._default_restrict_to_workspace,
source_channel=_WEBUI_SCOPE_CHANNEL,
)
path = str(scope.project_path)
state = read_webui_workspace_state()
favorites: list[str] = state["favorite_projects"]
existing = next((item for item in favorites if os.path.normcase(item) == os.path.normcase(path)), None)
if pinned and existing is None:
if len(favorites) >= 40:
raise WorkspaceScopeError("at most 40 favorite folders can be pinned")
favorites.append(path)
write_webui_workspace_state(state)
elif not pinned and existing is not None:
favorites.remove(existing)
write_webui_workspace_state(state)
return [{"name": Path(item).name or item, "path": item} for item in favorites]
def scope_from_envelope(
self,
envelope: dict[str, Any],
@@ -381,6 +456,7 @@ class WebUIWorkspaceController:
session.metadata[WORKSPACE_SCOPE_METADATA_KEY] = scope.metadata()
self._sessions.save(session)
self._draft_scopes.pop(session_key, None)
remember_webui_project(scope.project_path)
def stage_scope(self, chat_id: str, scope: WorkspaceScope) -> None:
"""Keep a new chat's scope transient until its first accepted message."""
@@ -391,6 +467,7 @@ class WebUIWorkspaceController:
):
self.persist_scope(chat_id, scope)
return
remember_webui_project(scope.project_path)
self._draft_scopes[session_key] = scope
self._draft_scopes.move_to_end(session_key)
while len(self._draft_scopes) > _MAX_DRAFT_SCOPES:
+57 -1
View File
@@ -32,7 +32,7 @@ from nanobot.command.builtin import builtin_command_palette
from nanobot.cron.binding import CronBindingError, binding_revision
from nanobot.cron.session_turns import is_bound_cron_job
from nanobot.cron.types import CronJob, CronSchedule
from nanobot.security.workspace_access import WorkspaceScope
from nanobot.security.workspace_access import WorkspaceScope, WorkspaceScopeError
from nanobot.session.manager import SessionManager
from nanobot.session.recovery import RecoveryActionError
from nanobot.session.session_handles import (
@@ -140,6 +140,7 @@ from nanobot.webui.transcript import (
build_webui_trace_detail_response,
webui_transcript_revision,
)
from nanobot.webui.workspace_browser import browse_workspace_directories
from nanobot.webui.workspaces import WebUIWorkspaceController
_SLOW_WEBUI_HTTP_LOG_MS = 1_000
@@ -196,6 +197,8 @@ _WEBUI_MUTATION_PATHS = {
"star_prompt.claim": "/api/webui/star-prompt/claim",
"star_prompt.dismiss": "/api/webui/star-prompt/dismiss",
"sidebar.update": "/api/webui/sidebar-state/update",
"workspace.favorite": "/api/workspaces/favorite",
"workspace.resolve_project": "/api/workspaces/resolve-project",
"workspace.pick_folder": "/api/workspaces/pick-folder",
"recovery.continue": "/api/webui/recovery/continue",
"recovery.dismiss": "/api/webui/recovery/dismiss",
@@ -563,6 +566,8 @@ class GatewayHTTPHandler:
"/api/webui/star-prompt/dismiss",
"/api/webui/sidebar-state/update",
"/api/workspaces/pick-folder",
"/api/workspaces/resolve-project",
"/api/workspaces/favorite",
"/api/webui/subagents/cancel",
}
@@ -1644,6 +1649,12 @@ class GatewayHTTPHandler:
return self._handle_commands(request)
if got == "/api/workspaces/pick-folder":
return await self._handle_workspace_folder_picker(connection, request)
if got == "/api/workspaces/favorite":
return self._handle_workspace_favorite(connection, request)
if got == "/api/workspaces/resolve-project":
return await self._handle_workspace_resolve_project(connection, request)
if got == "/api/workspaces/directories":
return await self._handle_workspace_directories(connection, request)
if got == "/api/workspaces":
return self._handle_workspaces(connection, request)
if got == "/api/webui/skills/search":
@@ -1700,6 +1711,51 @@ class GatewayHTTPHandler:
)
)
def _handle_workspace_favorite(self, connection: Any, request: WsRequest) -> Response:
if not self.check_api_token(request):
return _http_error(401, "Unauthorized")
if not self.workspace_project_selection_available(connection):
return _http_error(403, "project selection is unavailable for this connection")
payload = _mutation_payload(request) or {}
try:
favorites = self.workspaces.set_favorite_project(payload.get("path"), payload.get("pinned"))
except WorkspaceScopeError as exc:
return _http_error(exc.status, exc.message)
except OSError:
return _http_error(500, "could not save favorite folders")
return _http_json_response({"favorite_projects": favorites})
async def _handle_workspace_resolve_project(self, connection: Any, request: WsRequest) -> Response:
if not self.check_api_token(request):
return _http_error(401, "Unauthorized")
if not self.workspace_project_selection_available(connection):
return _http_error(403, "project selection is unavailable for this connection")
payload = _mutation_payload(request) or {}
try:
project = self.workspaces.resolve_project(payload.get("path"))
except WorkspaceScopeError as exc:
return _http_error(exc.status, exc.message)
return _http_json_response(project)
async def _handle_workspace_directories(self, connection: Any, request: WsRequest) -> Response:
if not self.check_api_token(request):
return _http_error(401, "Unauthorized")
if not self.workspace_project_selection_available(connection):
return _http_error(403, "project selection is unavailable for this connection")
query = _parse_query(request.path)
try:
payload = await asyncio.to_thread(
browse_workspace_directories,
_query_first(query, "path") or "",
default_workspace=self.workspaces.default_scope().project_path,
query=_query_first(query, "q") or "",
show_hidden=_query_first(query, "hidden") == "1",
allow_partial=_query_first(query, "partial") == "1",
)
except WorkspaceScopeError as exc:
return _http_error(exc.status, exc.message)
return _http_json_response(dict(payload))
async def _handle_workspace_folder_picker(
self,
connection: Any,