refactor(webui): remove obsolete native workspace picker paths
This commit is contained in:
1 parent
024d181013
commit
8a795b428e
32 files changed
+186
-593
No files matched your search
+1
-1
@@ -294,7 +294,7 @@ or a result you must retain.
|
||||
Use the workspace picker to browse folders on the connected nanobot host, enter
|
||||
an absolute path, or return to recent and starred projects; favorites persist
|
||||
across gateway restarts. Tab completes paths and Shift+wheel scrolls directory
|
||||
columns. Hosts without browsing support accept manual paths in the same dialog.
|
||||
columns.
|
||||
Project paths refer to the gateway machine, not the browser's filesystem.
|
||||
|
||||
Selecting a project does not replace the configured agent workspace. The two
|
||||
|
||||
@@ -4778,7 +4778,6 @@ async def test_bootstrap_exposes_native_surface(bus: MagicMock) -> None:
|
||||
bus,
|
||||
token_issue_secret="native-secret",
|
||||
runtime_surface="native",
|
||||
runtime_capabilities_overrides={"can_pick_folder": True},
|
||||
),
|
||||
)
|
||||
|
||||
@@ -4793,7 +4792,6 @@ async def test_bootstrap_exposes_native_surface(bus: MagicMock) -> None:
|
||||
assert response.status_code == 200
|
||||
body = response.json()
|
||||
assert body["runtime_surface"] == "native"
|
||||
assert body["runtime_capabilities"]["can_pick_folder"] is True
|
||||
assert body["runtime_capabilities"]["can_restart_engine"] is True
|
||||
assert body["token"].startswith("nbwt_")
|
||||
assert body["api_token"].startswith("nbwt_")
|
||||
|
||||
@@ -3655,61 +3655,20 @@ async def test_recovery_mutation_uses_authenticated_websocket_action(bus: MagicM
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_workspace_folder_picker_is_local_authenticated_mutation(
|
||||
bus: MagicMock,
|
||||
tmp_path: Path,
|
||||
monkeypatch,
|
||||
) -> None:
|
||||
selected = tmp_path / "project"
|
||||
selected.mkdir()
|
||||
pick_folder = AsyncMock(return_value=str(selected))
|
||||
monkeypatch.setattr(
|
||||
"nanobot.webui.ws_http.native_folder_picker_available",
|
||||
lambda: True,
|
||||
)
|
||||
monkeypatch.setattr("nanobot.webui.ws_http.pick_native_folder", pick_folder)
|
||||
channel = _ch(bus)
|
||||
|
||||
response = await _webui_mutate(channel, "workspace.pick_folder")
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.json() == {"path": str(selected)}
|
||||
pick_folder.assert_awaited_once_with()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("connection", "headers", "can_use_full_access", "can_pick_folder"),
|
||||
("connection", "headers", "can_use_full_access"),
|
||||
[
|
||||
(
|
||||
_REMOTE,
|
||||
{"Host": "nas.example", "X-Forwarded-For": "203.0.113.42"},
|
||||
False,
|
||||
False,
|
||||
),
|
||||
(
|
||||
_LOCAL,
|
||||
{"Host": "nas.example", "X-Forwarded-For": "203.0.113.42"},
|
||||
False,
|
||||
False,
|
||||
),
|
||||
(_LOCAL, {"Host": "127.0.0.1:8765"}, True, True),
|
||||
(_REMOTE, {"Host": "nas.example", "X-Forwarded-For": "203.0.113.42"}, False),
|
||||
(_LOCAL, {"Host": "nas.example", "X-Forwarded-For": "203.0.113.42"}, False),
|
||||
(_LOCAL, {"Host": "127.0.0.1:8765"}, True),
|
||||
],
|
||||
)
|
||||
@pytest.mark.parametrize("native_picker_available", [True, False])
|
||||
def test_workspace_payload_separates_remote_project_selection_from_full_access(
|
||||
bus: MagicMock,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
native_picker_available: bool,
|
||||
connection: _FakeConn,
|
||||
headers: dict[str, str],
|
||||
can_use_full_access: bool,
|
||||
can_pick_folder: bool,
|
||||
) -> None:
|
||||
monkeypatch.setattr(
|
||||
"nanobot.webui.ws_http.native_folder_picker_available",
|
||||
lambda: native_picker_available,
|
||||
)
|
||||
channel = _ch(bus)
|
||||
token = channel.gateway.tokens.issue_api_token(300)
|
||||
request = _FakeReq(
|
||||
@@ -3723,63 +3682,6 @@ def test_workspace_payload_separates_remote_project_selection_from_full_access(
|
||||
controls = json.loads(response.body.decode())["controls"]
|
||||
assert controls["can_change_project"] is True
|
||||
assert controls["can_use_full_access"] is can_use_full_access
|
||||
assert controls["can_pick_folder"] is (can_pick_folder and native_picker_available)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_workspace_folder_picker_rejects_direct_http(
|
||||
bus: MagicMock,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
pick_folder = AsyncMock(return_value="/tmp")
|
||||
monkeypatch.setattr(
|
||||
"nanobot.webui.ws_http.native_folder_picker_available",
|
||||
lambda: True,
|
||||
)
|
||||
monkeypatch.setattr("nanobot.webui.ws_http.pick_native_folder", pick_folder)
|
||||
channel = _ch(bus)
|
||||
|
||||
response = await channel.gateway.http.dispatch(
|
||||
_LOCAL,
|
||||
_FakeReq(
|
||||
{"Host": "127.0.0.1:8765"},
|
||||
path="/api/workspaces/pick-folder",
|
||||
),
|
||||
)
|
||||
|
||||
assert response is not None
|
||||
assert response.status_code == 405
|
||||
assert b"authenticated WebSocket" in response.body
|
||||
pick_folder.assert_not_awaited()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize(
|
||||
("connection", "host"),
|
||||
[(_REMOTE, "127.0.0.1"), (_LOCAL, "0.0.0.0")],
|
||||
)
|
||||
async def test_workspace_folder_picker_rejects_nonlocal_surfaces(
|
||||
bus: MagicMock,
|
||||
monkeypatch,
|
||||
connection: _FakeConn,
|
||||
host: str,
|
||||
) -> None:
|
||||
pick_folder = AsyncMock(return_value="/tmp")
|
||||
monkeypatch.setattr(
|
||||
"nanobot.webui.ws_http.native_folder_picker_available",
|
||||
lambda: True,
|
||||
)
|
||||
monkeypatch.setattr("nanobot.webui.ws_http.pick_native_folder", pick_folder)
|
||||
channel = _ch(bus, host=host, token="test-token" if host == "0.0.0.0" else "")
|
||||
|
||||
response = await _webui_mutate(
|
||||
channel,
|
||||
"workspace.pick_folder",
|
||||
connection=connection,
|
||||
)
|
||||
|
||||
assert response.status_code == 403
|
||||
pick_folder.assert_not_awaited()
|
||||
|
||||
|
||||
def test_local_browser_request_requires_loopback_host_and_forwarded_origin() -> None:
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""Native path pickers used by a locally hosted WebUI; never read file contents."""
|
||||
"""Select local SSH files for the WebUI without reading their contents."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -9,7 +9,6 @@ import sys
|
||||
from contextlib import suppress
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Literal
|
||||
|
||||
_PICKER_TIMEOUT_SECONDS = 300
|
||||
_COMMON_ENV_KEYS = (
|
||||
@@ -56,8 +55,8 @@ _WINDOWS_GUI_ENV_KEYS = (
|
||||
)
|
||||
|
||||
|
||||
class NativeFolderPickerError(RuntimeError):
|
||||
"""Raised when an available native folder picker cannot complete."""
|
||||
class NativeFilePickerError(RuntimeError):
|
||||
"""Raised when a native file picker cannot complete."""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -67,8 +66,8 @@ class _PickerCommand:
|
||||
cancel_markers: tuple[str, ...] = ()
|
||||
|
||||
|
||||
def _picker_command(kind: Literal["folder", "file"] = "folder") -> _PickerCommand | None:
|
||||
title = "Select Workspace Directory" if kind == "folder" else "Select SSH key or configuration file"
|
||||
def _picker_command() -> _PickerCommand | None:
|
||||
title = "Select SSH key or configuration file"
|
||||
if sys.platform == "darwin":
|
||||
executable = shutil.which("osascript")
|
||||
if executable is None:
|
||||
@@ -77,7 +76,7 @@ def _picker_command(kind: Literal["folder", "file"] = "folder") -> _PickerComman
|
||||
argv=(
|
||||
executable,
|
||||
"-e",
|
||||
f'set selectedPath to choose {kind} with prompt "{title}"',
|
||||
f'set selectedPath to choose file with prompt "{title}"',
|
||||
"-e",
|
||||
"POSIX path of selectedPath",
|
||||
),
|
||||
@@ -89,22 +88,14 @@ def _picker_command(kind: Literal["folder", "file"] = "folder") -> _PickerComman
|
||||
executable = shutil.which("powershell.exe") or shutil.which("powershell")
|
||||
if executable is None:
|
||||
return None
|
||||
dialog = (
|
||||
"$dialog=New-Object System.Windows.Forms.FolderBrowserDialog;"
|
||||
f"$dialog.Description='{title}';"
|
||||
"$dialog.ShowNewFolderButton=$true;"
|
||||
) if kind == "folder" else (
|
||||
script = (
|
||||
"Add-Type -AssemblyName System.Windows.Forms;"
|
||||
"$dialog=New-Object System.Windows.Forms.OpenFileDialog;"
|
||||
f"$dialog.Title='{title}';"
|
||||
"$dialog.CheckFileExists=$true;$dialog.Multiselect=$false;"
|
||||
)
|
||||
selected = "SelectedPath" if kind == "folder" else "FileName"
|
||||
script = (
|
||||
"Add-Type -AssemblyName System.Windows.Forms;"
|
||||
+ dialog +
|
||||
"if($dialog.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK){"
|
||||
"[Console]::OutputEncoding=[System.Text.UTF8Encoding]::new();"
|
||||
f"[Console]::Out.Write($dialog.{selected})}}"
|
||||
"[Console]::Out.Write($dialog.FileName)}"
|
||||
)
|
||||
return _PickerCommand(
|
||||
argv=(
|
||||
@@ -127,7 +118,6 @@ def _picker_command(kind: Literal["folder", "file"] = "folder") -> _PickerComman
|
||||
argv=(
|
||||
zenity,
|
||||
"--file-selection",
|
||||
*(("--directory",) if kind == "folder" else ()),
|
||||
f"--title={title}",
|
||||
),
|
||||
cancel_codes=frozenset({1}),
|
||||
@@ -135,17 +125,12 @@ def _picker_command(kind: Literal["folder", "file"] = "folder") -> _PickerComman
|
||||
kdialog = shutil.which("kdialog")
|
||||
if kdialog is not None:
|
||||
return _PickerCommand(
|
||||
argv=(kdialog, "--getexistingdirectory" if kind == "folder" else "--getopenfilename", str(Path.home())),
|
||||
argv=(kdialog, "--getopenfilename", str(Path.home())),
|
||||
cancel_codes=frozenset({1}),
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
def native_folder_picker_available() -> bool:
|
||||
"""Return whether this host can display a native directory picker."""
|
||||
return _picker_command() is not None
|
||||
|
||||
|
||||
def _picker_environment() -> dict[str, str]:
|
||||
"""Pass only host UI/runtime variables, never provider or gateway secrets."""
|
||||
keys: list[str] = list(_COMMON_ENV_KEYS)
|
||||
@@ -175,19 +160,11 @@ async def _stop_process(process: asyncio.subprocess.Process) -> None:
|
||||
await process.wait()
|
||||
|
||||
|
||||
async def pick_native_folder() -> str | None:
|
||||
"""Open the platform directory picker and return an existing absolute path."""
|
||||
return await _pick_native_path(_picker_command(), "directory")
|
||||
|
||||
|
||||
async def pick_native_file() -> str | None:
|
||||
"""Choose an existing local file without opening, uploading or copying it."""
|
||||
return await _pick_native_path(_picker_command("file"), "file")
|
||||
|
||||
|
||||
async def _pick_native_path(command: _PickerCommand | None, kind: str) -> str | None:
|
||||
command = _picker_command()
|
||||
if command is None:
|
||||
raise NativeFolderPickerError("native folder picker is unavailable on this host")
|
||||
raise NativeFilePickerError("native file picker is unavailable on this host")
|
||||
|
||||
try:
|
||||
process = await asyncio.create_subprocess_exec(
|
||||
@@ -197,7 +174,7 @@ async def _pick_native_path(command: _PickerCommand | None, kind: str) -> str |
|
||||
stderr=asyncio.subprocess.PIPE,
|
||||
)
|
||||
except OSError as exc:
|
||||
raise NativeFolderPickerError("native folder picker failed to start") from exc
|
||||
raise NativeFilePickerError("native file picker failed to start") from exc
|
||||
try:
|
||||
stdout, stderr = await asyncio.wait_for(
|
||||
process.communicate(),
|
||||
@@ -208,7 +185,7 @@ async def _pick_native_path(command: _PickerCommand | None, kind: str) -> str |
|
||||
raise
|
||||
except TimeoutError as exc:
|
||||
await _stop_process(process)
|
||||
raise NativeFolderPickerError("native folder picker timed out") from exc
|
||||
raise NativeFilePickerError("native file picker timed out") from exc
|
||||
|
||||
error_text = stderr.decode("utf-8", errors="replace").strip()
|
||||
normalized_error = error_text.lower()
|
||||
@@ -218,12 +195,12 @@ async def _pick_native_path(command: _PickerCommand | None, kind: str) -> str |
|
||||
or any(marker in normalized_error for marker in command.cancel_markers)
|
||||
):
|
||||
return None
|
||||
raise NativeFolderPickerError("native folder picker failed")
|
||||
raise NativeFilePickerError("native file picker failed")
|
||||
|
||||
selected = stdout.decode("utf-8", errors="replace").strip()
|
||||
if not selected:
|
||||
return None
|
||||
path = Path(selected).expanduser()
|
||||
if not path.is_absolute() or not (path.is_dir() if kind == "directory" else path.is_file()):
|
||||
raise NativeFolderPickerError(f"native path picker returned an invalid {kind}")
|
||||
if not path.is_absolute() or not path.is_file():
|
||||
raise NativeFilePickerError("native file picker returned an invalid file")
|
||||
return str(path)
|
||||
@@ -212,7 +212,7 @@ class RemoteInstances:
|
||||
|
||||
async def action(self, action: str, payload: dict[str, Any]) -> dict[str, Any]:
|
||||
if action == "pick_file":
|
||||
from nanobot.webui.native_folder_picker import NativeFolderPickerError, pick_native_file
|
||||
from nanobot.webui.native_file_picker import NativeFilePickerError, pick_native_file
|
||||
|
||||
if self._closed or self._picker_lock.locked():
|
||||
raise RemoteError("file_picker_unavailable")
|
||||
@@ -221,7 +221,7 @@ class RemoteInstances:
|
||||
async with self._picker_lock:
|
||||
try:
|
||||
return {"path": await pick_native_file()}
|
||||
except NativeFolderPickerError:
|
||||
except NativeFilePickerError:
|
||||
raise RemoteError("file_picker_unavailable") from None
|
||||
if action == "discover":
|
||||
from nanobot.webui.ssh_config import discover_hosts
|
||||
|
||||
@@ -43,14 +43,12 @@ _reasoning_effort_values_for = models.reasoning_effort_values_for
|
||||
|
||||
_RUNTIME_CAPABILITIES = {
|
||||
"can_restart_engine": False,
|
||||
"can_pick_folder": False,
|
||||
"can_open_logs": False,
|
||||
"can_export_diagnostics": False,
|
||||
}
|
||||
_NATIVE_RUNTIME_CAPABILITIES = {
|
||||
**_RUNTIME_CAPABILITIES,
|
||||
"can_restart_engine": True,
|
||||
"can_pick_folder": True,
|
||||
"can_open_logs": True,
|
||||
"can_export_diagnostics": True,
|
||||
}
|
||||
|
||||
@@ -176,7 +176,6 @@ def workspaces_payload(
|
||||
default_restrict_to_workspace: bool,
|
||||
can_change_project: bool,
|
||||
can_use_full_access: bool,
|
||||
folder_picker_available: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
state = read_webui_workspace_state()
|
||||
default_access_mode = state["default_access_mode"]
|
||||
@@ -205,10 +204,6 @@ def workspaces_payload(
|
||||
"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,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -305,14 +300,12 @@ class WebUIWorkspaceController:
|
||||
*,
|
||||
can_change_project: bool,
|
||||
can_use_full_access: bool,
|
||||
folder_picker_available: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
return workspaces_payload(
|
||||
default_workspace=self._default_workspace,
|
||||
default_restrict_to_workspace=self._default_restrict_to_workspace,
|
||||
can_change_project=can_change_project,
|
||||
can_use_full_access=can_use_full_access,
|
||||
folder_picker_available=folder_picker_available,
|
||||
)
|
||||
|
||||
def resolve_project(self, path: object) -> dict[str, str]:
|
||||
|
||||
@@ -95,11 +95,6 @@ from nanobot.webui.http_utils import (
|
||||
)
|
||||
from nanobot.webui.ingress_policy import WebUIIngressPolicy
|
||||
from nanobot.webui.media_gateway import WebUIMediaGateway
|
||||
from nanobot.webui.native_folder_picker import (
|
||||
NativeFolderPickerError,
|
||||
native_folder_picker_available,
|
||||
pick_native_folder,
|
||||
)
|
||||
from nanobot.webui.session_automations import (
|
||||
all_automations_payload,
|
||||
serialize_automation_jobs,
|
||||
@@ -199,7 +194,6 @@ _WEBUI_MUTATION_PATHS = {
|
||||
"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",
|
||||
"subagent.cancel": "/api/webui/subagents/cancel",
|
||||
@@ -414,7 +408,6 @@ class GatewayHTTPHandler:
|
||||
self.subagent_manager = subagent_manager
|
||||
self.discard_session = discard_session
|
||||
self._skill_install_lock = asyncio.Lock()
|
||||
self._folder_picker_lock = asyncio.Lock()
|
||||
self.cron_service = cron_service
|
||||
self.local_trigger_store = local_trigger_store
|
||||
self.cron_pending_job_ids = cron_pending_job_ids
|
||||
@@ -473,17 +466,6 @@ class GatewayHTTPHandler:
|
||||
return False
|
||||
return _is_local_browser_request(connection, headers)
|
||||
|
||||
def workspace_folder_picker_available(
|
||||
self,
|
||||
connection: Any,
|
||||
request: WsRequest,
|
||||
) -> bool:
|
||||
return (
|
||||
_is_loopback_host(self.config.host)
|
||||
and _is_local_browser_request(connection, request.headers)
|
||||
and native_folder_picker_available()
|
||||
)
|
||||
|
||||
# -- Token management ---------------------------------------------------
|
||||
|
||||
def check_api_token(self, request: WsRequest) -> bool:
|
||||
@@ -565,7 +547,6 @@ class GatewayHTTPHandler:
|
||||
"/api/webui/star-prompt/claim",
|
||||
"/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",
|
||||
@@ -1647,8 +1628,6 @@ class GatewayHTTPHandler:
|
||||
return await self._handle_sessions_list(request)
|
||||
if got == "/api/commands":
|
||||
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":
|
||||
@@ -1704,10 +1683,6 @@ class GatewayHTTPHandler:
|
||||
connection,
|
||||
request.headers,
|
||||
),
|
||||
folder_picker_available=self.workspace_folder_picker_available(
|
||||
connection,
|
||||
request,
|
||||
),
|
||||
)
|
||||
)
|
||||
|
||||
@@ -1756,24 +1731,6 @@ class GatewayHTTPHandler:
|
||||
return _http_error(exc.status, exc.message)
|
||||
return _http_json_response(dict(payload))
|
||||
|
||||
async def _handle_workspace_folder_picker(
|
||||
self,
|
||||
connection: Any,
|
||||
request: WsRequest,
|
||||
) -> Response:
|
||||
if not self.check_api_token(request):
|
||||
return _http_error(401, "Unauthorized")
|
||||
if not self.workspace_folder_picker_available(connection, request):
|
||||
return _http_error(403, "native folder picker is unavailable for this connection")
|
||||
if self._folder_picker_lock.locked():
|
||||
return _http_error(409, "native folder picker is already open")
|
||||
try:
|
||||
async with self._folder_picker_lock:
|
||||
path = await pick_native_folder()
|
||||
except NativeFolderPickerError as exc:
|
||||
return _http_error(503, str(exc))
|
||||
return _http_json_response({"path": path})
|
||||
|
||||
def _handle_webui_skills(self, request: WsRequest) -> Response:
|
||||
if not self.check_api_token(request):
|
||||
return _http_error(401, "Unauthorized")
|
||||
|
||||
@@ -5,7 +5,7 @@ from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from nanobot.webui import native_folder_picker as picker
|
||||
from nanobot.webui import native_file_picker as picker
|
||||
|
||||
|
||||
def _picker_command(tmp_path: Path, body: str) -> picker._PickerCommand:
|
||||
@@ -15,23 +15,9 @@ def _picker_command(tmp_path: Path, body: str) -> picker._PickerCommand:
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_pick_native_folder_returns_selected_directory(tmp_path, monkeypatch) -> None:
|
||||
async def test_pick_native_file_uses_secret_free_environment(tmp_path, monkeypatch) -> None:
|
||||
selected = tmp_path / "project"
|
||||
selected.mkdir()
|
||||
command = _picker_command(tmp_path, f"print({str(selected)!r}, end='')")
|
||||
monkeypatch.setattr(
|
||||
picker,
|
||||
"_picker_command",
|
||||
lambda: command,
|
||||
)
|
||||
|
||||
assert await picker.pick_native_folder() == str(selected)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_pick_native_folder_uses_secret_free_environment(tmp_path, monkeypatch) -> None:
|
||||
selected = tmp_path / "project"
|
||||
selected.mkdir()
|
||||
selected.write_text("ssh-key")
|
||||
command = _picker_command(tmp_path, f"print({str(selected)!r}, end='')")
|
||||
monkeypatch.setattr(picker, "_picker_command", lambda: command)
|
||||
monkeypatch.setenv("HOME", str(tmp_path))
|
||||
@@ -45,7 +31,7 @@ async def test_pick_native_folder_uses_secret_free_environment(tmp_path, monkeyp
|
||||
|
||||
monkeypatch.setattr(picker.asyncio, "create_subprocess_exec", capture_spawn)
|
||||
|
||||
assert await picker.pick_native_folder() == str(selected)
|
||||
assert await picker.pick_native_file() == str(selected)
|
||||
assert captured_env["HOME"] == str(tmp_path)
|
||||
assert "OPENAI_API_KEY" not in captured_env
|
||||
|
||||
@@ -64,42 +50,15 @@ def test_picker_environment_preserves_linux_display_context(monkeypatch) -> None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_pick_native_folder_maps_dialog_cancel_to_none(tmp_path, monkeypatch) -> None:
|
||||
command = _picker_command(tmp_path, "raise SystemExit(1)")
|
||||
monkeypatch.setattr(
|
||||
picker,
|
||||
"_picker_command",
|
||||
lambda: command,
|
||||
)
|
||||
|
||||
assert await picker.pick_native_folder() is None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_pick_native_folder_rejects_non_directory_result(tmp_path, monkeypatch) -> None:
|
||||
missing = tmp_path / "missing"
|
||||
command = _picker_command(tmp_path, f"print({str(missing)!r}, end='')")
|
||||
monkeypatch.setattr(
|
||||
picker,
|
||||
"_picker_command",
|
||||
lambda: command,
|
||||
)
|
||||
|
||||
with pytest.raises(picker.NativeFolderPickerError, match="invalid directory"):
|
||||
await picker.pick_native_folder()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_pick_native_folder_reports_unavailable(monkeypatch) -> None:
|
||||
async def test_pick_native_file_reports_unavailable(monkeypatch) -> None:
|
||||
monkeypatch.setattr(picker, "_picker_command", lambda: None)
|
||||
|
||||
assert picker.native_folder_picker_available() is False
|
||||
with pytest.raises(picker.NativeFolderPickerError, match="unavailable"):
|
||||
await picker.pick_native_folder()
|
||||
with pytest.raises(picker.NativeFilePickerError, match="unavailable"):
|
||||
await picker.pick_native_file()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_pick_native_folder_wraps_process_start_failure(tmp_path, monkeypatch) -> None:
|
||||
async def test_pick_native_file_wraps_process_start_failure(tmp_path, monkeypatch) -> None:
|
||||
command = _picker_command(tmp_path, "raise AssertionError('not started')")
|
||||
monkeypatch.setattr(picker, "_picker_command", lambda: command)
|
||||
|
||||
@@ -108,8 +67,8 @@ async def test_pick_native_folder_wraps_process_start_failure(tmp_path, monkeypa
|
||||
|
||||
monkeypatch.setattr(picker.asyncio, "create_subprocess_exec", fail_spawn)
|
||||
|
||||
with pytest.raises(picker.NativeFolderPickerError, match="failed to start"):
|
||||
await picker.pick_native_folder()
|
||||
with pytest.raises(picker.NativeFilePickerError, match="failed to start"):
|
||||
await picker.pick_native_file()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("result", ["file", "directory", "cancel"])
|
||||
@@ -118,9 +77,9 @@ async def test_pick_native_file_returns_only_existing_file_path(tmp_path, monkey
|
||||
selected.write_text("must-not-be-read-or-returned")
|
||||
output = str(selected if result == "file" else tmp_path)
|
||||
command = _picker_command(tmp_path, "raise SystemExit(1)" if result == "cancel" else f"print({output!r})")
|
||||
monkeypatch.setattr(picker, "_picker_command", lambda kind: command)
|
||||
monkeypatch.setattr(picker, "_picker_command", lambda: command)
|
||||
if result == "directory":
|
||||
with pytest.raises(picker.NativeFolderPickerError, match="invalid file"):
|
||||
with pytest.raises(picker.NativeFilePickerError, match="invalid file"):
|
||||
await picker.pick_native_file()
|
||||
else:
|
||||
assert await picker.pick_native_file() == (str(selected) if result == "file" else None)
|
||||
@@ -133,7 +92,7 @@ def test_file_picker_uses_platform_file_dialog(monkeypatch, platform, marker):
|
||||
monkeypatch.setattr(picker.sys, "platform", platform)
|
||||
monkeypatch.setattr(picker.shutil, "which", lambda executable: executable)
|
||||
monkeypatch.setenv("DISPLAY", ":test")
|
||||
command = picker._picker_command("file")
|
||||
command = picker._picker_command()
|
||||
assert command is not None
|
||||
assert marker in " ".join(command.argv)
|
||||
assert "--directory" not in command.argv
|
||||
@@ -143,7 +102,7 @@ def test_file_picker_is_unavailable_on_headless_linux(monkeypatch):
|
||||
monkeypatch.setattr(picker.sys, "platform", "linux")
|
||||
monkeypatch.delenv("DISPLAY", raising=False)
|
||||
monkeypatch.delenv("WAYLAND_DISPLAY", raising=False)
|
||||
assert picker._picker_command("file") is None
|
||||
assert picker._picker_command() is None
|
||||
|
||||
|
||||
async def test_file_picker_cancellation_reaps_process(monkeypatch):
|
||||
@@ -153,7 +112,7 @@ async def test_file_picker_cancellation_reaps_process(monkeypatch):
|
||||
process = MagicMock(returncode=None)
|
||||
process.communicate = AsyncMock(side_effect=asyncio.CancelledError)
|
||||
process.wait = AsyncMock(return_value=0)
|
||||
monkeypatch.setattr(picker, "_picker_command", lambda kind: picker._PickerCommand(("picker",), frozenset()))
|
||||
monkeypatch.setattr(picker, "_picker_command", lambda: picker._PickerCommand(("picker",), frozenset()))
|
||||
monkeypatch.setattr(asyncio, "create_subprocess_exec", AsyncMock(return_value=process))
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await picker.pick_native_file()
|
||||
@@ -43,7 +43,6 @@ def test_workspace_payload_is_config_data_dir_scoped(tmp_path, monkeypatch) -> N
|
||||
assert payload["default_scope"]["access_mode"] == "full"
|
||||
assert payload["default_access_mode"] == "default"
|
||||
assert payload["controls"]["can_change_project"] is True
|
||||
assert payload["controls"]["can_pick_folder"] is False
|
||||
|
||||
|
||||
def test_workspace_payload_allows_remote_project_selection_without_full_access(
|
||||
@@ -64,7 +63,6 @@ def test_workspace_payload_allows_remote_project_selection_without_full_access(
|
||||
assert payload["default_scope"]["project_path"] == str(default.resolve())
|
||||
assert payload["controls"]["can_change_project"] is True
|
||||
assert payload["controls"]["can_use_full_access"] is False
|
||||
assert payload["controls"]["can_pick_folder"] is False
|
||||
|
||||
|
||||
def test_workspace_payload_hides_project_selection_when_unavailable(
|
||||
@@ -86,22 +84,6 @@ def test_workspace_payload_hides_project_selection_when_unavailable(
|
||||
assert payload["controls"]["can_use_full_access"] is False
|
||||
|
||||
|
||||
def test_workspace_payload_advertises_native_folder_picker(tmp_path, monkeypatch) -> None:
|
||||
monkeypatch.setattr("nanobot.webui.workspaces.get_webui_dir", lambda: tmp_path / "webui")
|
||||
default = tmp_path / "default"
|
||||
default.mkdir()
|
||||
|
||||
payload = workspaces_payload(
|
||||
default_workspace=default,
|
||||
default_restrict_to_workspace=False,
|
||||
can_change_project=True,
|
||||
can_use_full_access=True,
|
||||
folder_picker_available=True,
|
||||
)
|
||||
|
||||
assert payload["controls"]["can_pick_folder"] is True
|
||||
|
||||
|
||||
def test_workspace_payload_uses_webui_default_access_mode(tmp_path, monkeypatch) -> None:
|
||||
monkeypatch.setattr("nanobot.webui.workspaces.get_webui_dir", lambda: tmp_path / "webui")
|
||||
default = tmp_path / "default"
|
||||
@@ -442,7 +424,7 @@ def test_recent_projects_survive_controller_restart_without_changing_access(tmp_
|
||||
assert payload["recent_projects"] == [{"name": "project", "path": str(project)}]
|
||||
assert payload["default_scope"]["project_path"] == str(default)
|
||||
assert payload["default_scope"]["access_mode"] == "restricted"
|
||||
assert payload["controls"]["can_browse_directories"] is True
|
||||
assert payload["controls"]["can_change_project"] is True
|
||||
|
||||
|
||||
def test_favorites_keep_pin_order_across_restart_and_can_remove_deleted_folder(tmp_path, monkeypatch) -> None:
|
||||
|
||||
@@ -694,30 +694,30 @@ async def test_http_mutations_are_not_gettable_even_with_token(gateway, action):
|
||||
|
||||
@pytest.mark.parametrize("path", ["/local/ssh-config", None])
|
||||
async def test_file_picker_returns_path_without_saving_profile(manager, monkeypatch, path):
|
||||
from nanobot.webui import native_folder_picker
|
||||
from nanobot.webui import native_file_picker
|
||||
|
||||
choose = AsyncMock(return_value=path)
|
||||
monkeypatch.setattr(native_folder_picker, "pick_native_file", choose)
|
||||
monkeypatch.setattr(native_file_picker, "pick_native_file", choose)
|
||||
assert await manager.action("pick_file", {}) == {"path": path}
|
||||
assert not manager.path.exists()
|
||||
choose.assert_awaited_once_with()
|
||||
|
||||
|
||||
async def test_file_picker_failure_does_not_expose_native_error(manager, monkeypatch):
|
||||
from nanobot.webui import native_folder_picker
|
||||
from nanobot.webui import native_file_picker
|
||||
|
||||
monkeypatch.setattr(native_folder_picker, "pick_native_file", AsyncMock(
|
||||
side_effect=native_folder_picker.NativeFolderPickerError("private diagnostic"),
|
||||
monkeypatch.setattr(native_file_picker, "pick_native_file", AsyncMock(
|
||||
side_effect=native_file_picker.NativeFilePickerError("private diagnostic"),
|
||||
))
|
||||
with pytest.raises(RemoteError, match="^file_picker_unavailable$"):
|
||||
await manager.action("pick_file", {})
|
||||
|
||||
|
||||
async def test_file_picker_does_not_open_multiple_system_dialogs(manager, monkeypatch):
|
||||
from nanobot.webui import native_folder_picker
|
||||
from nanobot.webui import native_file_picker
|
||||
|
||||
choose = AsyncMock()
|
||||
monkeypatch.setattr(native_folder_picker, "pick_native_file", choose)
|
||||
monkeypatch.setattr(native_file_picker, "pick_native_file", choose)
|
||||
async with manager._picker_lock:
|
||||
with pytest.raises(RemoteError, match="file_picker_unavailable"):
|
||||
await manager.action("pick_file", {})
|
||||
@@ -730,10 +730,10 @@ async def test_file_picker_does_not_open_multiple_system_dialogs(manager, monkey
|
||||
("127.0.0.1", "127.0.0.1:8765", "https://evil.example"),
|
||||
])
|
||||
async def test_remote_clients_cannot_open_local_file_picker(gateway, monkeypatch, peer, host, origin):
|
||||
from nanobot.webui import native_folder_picker
|
||||
from nanobot.webui import native_file_picker
|
||||
|
||||
choose = AsyncMock()
|
||||
monkeypatch.setattr(native_folder_picker, "pick_native_file", choose)
|
||||
monkeypatch.setattr(native_file_picker, "pick_native_file", choose)
|
||||
connection = SimpleNamespace(remote_address=(peer, 10000), request=SimpleNamespace(
|
||||
headers=Headers({"Host": host, "Origin": origin}),
|
||||
))
|
||||
|
||||
@@ -1064,6 +1064,10 @@ export function ThreadComposer({
|
||||
isHero
|
||||
&& !!workspaceDefaultScope
|
||||
&& !!onWorkspaceScopeChange
|
||||
&& !!onLoadWorkspaceProjects
|
||||
&& !!onBrowseWorkspaceDirectories
|
||||
&& !!onResolveWorkspaceProject
|
||||
&& !!onFavoriteWorkspaceProject
|
||||
&& workspaceControls?.can_change_project !== false;
|
||||
const showProjectPicker = projectPickerAvailable && !workspaceControlsHidden;
|
||||
|
||||
|
||||
@@ -30,8 +30,7 @@ function WorkspaceFavoriteButton({ path, pinned, busy, onToggle }: {
|
||||
);
|
||||
}
|
||||
|
||||
type PickerOption = ProjectDirectory & { kind: "directory" | "manual" };
|
||||
type PickerColumn = { path: string; options: PickerOption[]; selectedPath: string | null; hidden: boolean };
|
||||
type PickerColumn = { path: string; options: ProjectDirectory[]; selectedPath: string | null; hidden: boolean };
|
||||
|
||||
function WorkspacePickerTooltip({ label, children }: { label: string; children: ReactElement }) {
|
||||
return (
|
||||
@@ -46,9 +45,9 @@ const DIRECTORY_ROW_HEIGHT = 44;
|
||||
const DIRECTORY_OVERSCAN = 4;
|
||||
|
||||
function WorkspaceDirectoryColumn({ options, activeIndex, renderOption, children, ...props }: {
|
||||
options: PickerOption[];
|
||||
options: ProjectDirectory[];
|
||||
activeIndex: number | null;
|
||||
renderOption: (option: PickerOption, index: number) => ReactElement;
|
||||
renderOption: (option: ProjectDirectory, index: number) => ReactElement;
|
||||
} & HTMLAttributes<HTMLDivElement>) {
|
||||
const viewportRef = useRef<HTMLDivElement>(null);
|
||||
const [firstRow, setFirstRow] = useState(0);
|
||||
@@ -84,7 +83,7 @@ function WorkspaceDirectoryColumn({ options, activeIndex, renderOption, children
|
||||
<div role="presentation" className="relative" style={{ height: options.length * DIRECTORY_ROW_HEIGHT }}>
|
||||
{options.slice(start, end).map((option, offset) => {
|
||||
const index = start + offset;
|
||||
return <div key={`${option.kind}-${option.path}`} role="presentation" className="absolute inset-x-0" style={{ top: index * DIRECTORY_ROW_HEIGHT }}>
|
||||
return <div key={option.path} role="presentation" className="absolute inset-x-0" style={{ top: index * DIRECTORY_ROW_HEIGHT }}>
|
||||
{renderOption(option, index)}
|
||||
</div>;
|
||||
})}
|
||||
@@ -142,10 +141,10 @@ export function WorkspaceProjectPicker({ isHero, disabled, scope, defaultScope,
|
||||
defaultScope: WorkspaceScopePayload | null;
|
||||
controls: WorkspacesPayload["controls"] | null;
|
||||
error?: string | null;
|
||||
onResolveProject?: (path: string) => Promise<ProjectDirectory>;
|
||||
onLoadProjects?: () => Promise<WorkspacesPayload>;
|
||||
onFavoriteProject?: (path: string, pinned: boolean) => Promise<ProjectDirectory[]>;
|
||||
onBrowseDirectories?: BrowseWorkspaceDirectories;
|
||||
onResolveProject: (path: string) => Promise<ProjectDirectory>;
|
||||
onLoadProjects: () => Promise<WorkspacesPayload>;
|
||||
onFavoriteProject: (path: string, pinned: boolean) => Promise<ProjectDirectory[]>;
|
||||
onBrowseDirectories: BrowseWorkspaceDirectories;
|
||||
onChange?: (scope: WorkspaceScopePayload) => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
@@ -183,8 +182,7 @@ export function WorkspaceProjectPicker({ isHero, disabled, scope, defaultScope,
|
||||
const displayedScope = scope ?? defaultScope;
|
||||
const projectLabel = displayedScope ? displayedScope.project_name || projectNameFromPath(displayedScope.project_path) : "";
|
||||
const visible = isHero && !!defaultScope && !!onChange && controls?.can_change_project !== false;
|
||||
const canBrowse = !!controls?.can_browse_directories && !!onBrowseDirectories;
|
||||
const directoryCache = useMemo(() => onBrowseDirectories ? createWorkspaceDirectoryCache(onBrowseDirectories) : null, [onBrowseDirectories]);
|
||||
const directoryCache = useMemo(() => createWorkspaceDirectoryCache(onBrowseDirectories), [onBrowseDirectories]);
|
||||
const absoluteDraft = isAbsoluteWorkspacePath(pathDraft);
|
||||
const requestedPath = absoluteDraft ? pathDraft.trim() : basePath;
|
||||
const folderQuery = absoluteDraft ? "" : pathDraft.trim();
|
||||
@@ -197,15 +195,15 @@ export function WorkspaceProjectPicker({ isHero, disabled, scope, defaultScope,
|
||||
setActiveColumn(0);
|
||||
setHighlightActive(false);
|
||||
const initialPath = scope?.project_path ?? defaultScope?.project_path ?? "";
|
||||
setPathDraft(canBrowse ? workspaceDirectoryPrefix(initialPath) : currentProjectScope?.project_path ?? "");
|
||||
setPathDraft(workspaceDirectoryPrefix(initialPath));
|
||||
setBasePath(initialPath);
|
||||
setDirectory(null);
|
||||
setActiveIndex(0);
|
||||
setPathError(null);
|
||||
}, [scope?.project_path, defaultScope?.project_path, open, canBrowse]);
|
||||
}, [scope?.project_path, defaultScope?.project_path, open]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open || !onLoadProjects) return;
|
||||
if (!open) return;
|
||||
let active = true;
|
||||
setCatalog(null);
|
||||
onLoadProjects().then(payload => { if (active) setCatalog(payload); }).catch((err: Error) => { if (active) setPathError(err.message); });
|
||||
@@ -213,7 +211,7 @@ export function WorkspaceProjectPicker({ isHero, disabled, scope, defaultScope,
|
||||
}, [onLoadProjects, open]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open || !canBrowse || !directoryCache) return;
|
||||
if (!open) return;
|
||||
let active = true;
|
||||
const apply = (result: WorkspaceDirectoriesPayload) => {
|
||||
if (!active) return;
|
||||
@@ -232,7 +230,7 @@ export function WorkspaceProjectPicker({ isHero, disabled, scope, defaultScope,
|
||||
});
|
||||
}, typing ? 150 : 0);
|
||||
return () => { active = false; window.clearTimeout(timer); };
|
||||
}, [open, canBrowse, directoryCache, requestedPath, folderQuery, showHidden, revision, absoluteDraft, pathDraft]);
|
||||
}, [open, directoryCache, requestedPath, folderQuery, showHidden, revision, absoluteDraft, pathDraft]);
|
||||
|
||||
useEffect(() => { if (disabled) setOpen(false); }, [disabled]);
|
||||
useEffect(() => {
|
||||
@@ -248,7 +246,7 @@ export function WorkspaceProjectPicker({ isHero, disabled, scope, defaultScope,
|
||||
|
||||
const ancestorPaths = JSON.stringify(previousColumns.filter(column => column.hidden !== showHidden).map(column => column.path));
|
||||
useEffect(() => {
|
||||
if (!open || !canBrowse || !directoryCache) return;
|
||||
if (!open) return;
|
||||
const paths: string[] = JSON.parse(ancestorPaths);
|
||||
if (!paths.length) return;
|
||||
let active = true;
|
||||
@@ -257,11 +255,11 @@ export function WorkspaceProjectPicker({ isHero, disabled, scope, defaultScope,
|
||||
setPreviousColumns(columns => columns.map(column => {
|
||||
const result = results.find(result => sameWorkspacePath(column.path, result.path));
|
||||
if (!result) return column;
|
||||
return { ...column, hidden: showHidden, options: result.entries.map(entry => ({ ...entry, kind: "directory" as const })) };
|
||||
return { ...column, hidden: showHidden, options: result.entries };
|
||||
}));
|
||||
}).catch((err: Error) => { if (active) setPathError(err.message); });
|
||||
return () => { active = false; };
|
||||
}, [open, canBrowse, directoryCache, ancestorPaths, showHidden]);
|
||||
}, [open, directoryCache, ancestorPaths, showHidden]);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const viewport = columnsElement;
|
||||
@@ -309,9 +307,9 @@ export function WorkspaceProjectPicker({ isHero, disabled, scope, defaultScope,
|
||||
completionRequest.current += 1;
|
||||
setPathDraft(value);
|
||||
const absolute = isAbsoluteWorkspacePath(value);
|
||||
const cached = directoryCache?.peek(absolute ? value.trim() : basePath, absolute ? "" : value.trim(), showHidden, true);
|
||||
const cached = directoryCache.peek(absolute ? value.trim() : basePath, absolute ? "" : value.trim(), showHidden, true);
|
||||
setDirectory(cached ?? null);
|
||||
setLoading(canBrowse && !cached);
|
||||
setLoading(!cached);
|
||||
setDirectoryError(null);
|
||||
setPathError(null);
|
||||
setActiveIndex(0);
|
||||
@@ -328,20 +326,18 @@ export function WorkspaceProjectPicker({ isHero, disabled, scope, defaultScope,
|
||||
inputRef.current?.focus();
|
||||
}
|
||||
|
||||
const applyProjectPath = useCallback((path: string, name?: string) => {
|
||||
const applyProjectPath = useCallback((path: string, name: string) => {
|
||||
const base = scope ?? defaultScope;
|
||||
const trimmed = path.trim();
|
||||
if (!base || !onChange) return;
|
||||
if (!trimmed || !isAbsoluteWorkspacePath(trimmed)) { setPathError(t("workspace.dialog.absolutePathRequired")); return; }
|
||||
const accessMode = controls?.can_use_full_access === false && !sameWorkspacePath(trimmed, base.project_path) ? "restricted" : base.access_mode;
|
||||
onChange({ ...base, project_path: trimmed, project_name: name || projectNameFromPath(trimmed), access_mode: accessMode, restrict_to_workspace: accessMode === "restricted" });
|
||||
onChange({ ...base, project_path: trimmed, project_name: name, access_mode: accessMode, restrict_to_workspace: accessMode === "restricted" });
|
||||
setPathError(null);
|
||||
setOpen(false);
|
||||
}, [controls?.can_use_full_access, defaultScope, onChange, scope, t]);
|
||||
}, [controls?.can_use_full_access, defaultScope, onChange, scope]);
|
||||
|
||||
const chooseProject = useCallback(async (path: string, name?: string) => {
|
||||
const chooseProject = useCallback(async (path: string) => {
|
||||
const session = pickerSession.current;
|
||||
if (!controls?.can_resolve_project || !onResolveProject) { applyProjectPath(path, name); return; }
|
||||
setPickingFolder(true); setPathError(null);
|
||||
try {
|
||||
const project = await onResolveProject(path);
|
||||
@@ -349,10 +345,10 @@ export function WorkspaceProjectPicker({ isHero, disabled, scope, defaultScope,
|
||||
} catch (err) {
|
||||
if (session === pickerSession.current) setPathError((err as Error).message);
|
||||
} finally { setPickingFolder(false); }
|
||||
}, [applyProjectPath, controls?.can_resolve_project, onResolveProject]);
|
||||
}, [applyProjectPath, onResolveProject]);
|
||||
|
||||
const favorites = catalog?.favorite_projects ?? [];
|
||||
const canFavorite = !!catalog?.controls.can_manage_favorites && !!onFavoriteProject;
|
||||
const canFavorite = catalog !== null;
|
||||
const isFavorite = (path: string) => favorites.some(item => sameWorkspacePath(item.path, path));
|
||||
function favoriteButton(path: string) {
|
||||
return canFavorite ? <WorkspaceFavoriteButton path={path} pinned={isFavorite(path)} busy={favoriteBusy || pickingFolder}
|
||||
@@ -360,7 +356,7 @@ export function WorkspaceProjectPicker({ isHero, disabled, scope, defaultScope,
|
||||
}
|
||||
|
||||
const toggleFavorite = async (path: string) => {
|
||||
if (!onFavoriteProject || favoriteBusy) return;
|
||||
if (favoriteBusy) return;
|
||||
const session = pickerSession.current;
|
||||
setFavoriteBusy(true); setPathError(null);
|
||||
try {
|
||||
@@ -373,15 +369,11 @@ export function WorkspaceProjectPicker({ isHero, disabled, scope, defaultScope,
|
||||
|
||||
const recentProjects = [
|
||||
...(catalog?.recent_projects ?? []),
|
||||
...(defaultScope ? [{ name: t("workspace.dialog.defaultProject"), path: defaultScope.project_path }] : []),
|
||||
...(defaultScope ? [{ name: projectNameFromPath(defaultScope.project_path), path: defaultScope.project_path }] : []),
|
||||
...(currentProjectScope ? [{ name: projectLabel, path: currentProjectScope.project_path }] : []),
|
||||
].filter((project, index, all) => all.findIndex(item => sameWorkspacePath(item.path, project.path)) === index && !isFavorite(project.path));
|
||||
const options = useMemo<PickerOption[]>(() => {
|
||||
if (directory && !loading) return directory.entries.map(entry => ({ ...entry, kind: "directory" }));
|
||||
return !canBrowse && absoluteDraft ? [{ name: projectNameFromPath(pathDraft.trim()), path: pathDraft.trim(), kind: "manual" }] : [];
|
||||
}, [directory, loading, canBrowse, absoluteDraft, pathDraft]);
|
||||
const options = useMemo(() => directory && !loading ? directory.entries : [], [directory, loading]);
|
||||
function openShortcut(project: ProjectDirectory) {
|
||||
if (!canBrowse) { void chooseProject(project.path, project.name); return; }
|
||||
setBasePath(project.path);
|
||||
changeDraft(workspaceDirectoryPrefix(project.path));
|
||||
setRevision(value => value + 1);
|
||||
@@ -390,13 +382,12 @@ export function WorkspaceProjectPicker({ isHero, disabled, scope, defaultScope,
|
||||
const columns: PickerColumn[] = [...previousColumns, { path: directory?.path ?? requestedPath, options, selectedPath: null, hidden: showHidden }];
|
||||
const activeOptions = columns[activeColumn]?.options ?? options;
|
||||
const activeOption = Math.min(activeIndex, Math.max(activeOptions.length - 1, 0));
|
||||
const selectionPath = canBrowse ? (!loading && directory && !directory.partial ? directory.path : null) : (absoluteDraft ? pathDraft.trim() : scope?.project_path ?? defaultScope?.project_path);
|
||||
const selectionPath = !loading && directory && !directory.partial ? directory.path : null;
|
||||
const displayedError = pathError ?? error ?? directoryError;
|
||||
|
||||
async function completePath() {
|
||||
const option = activeOptions[activeOption];
|
||||
if (option && option.kind !== "manual") { navigate(option.path); return; }
|
||||
if (!directoryCache || !canBrowse) return;
|
||||
if (option) { navigate(option.path); return; }
|
||||
const request = workspacePathCompletionQuery(pathDraft) ?? { path: basePath, query: pathDraft.trim() };
|
||||
const id = ++completionRequest.current;
|
||||
const session = pickerSession.current;
|
||||
@@ -411,10 +402,9 @@ export function WorkspaceProjectPicker({ isHero, disabled, scope, defaultScope,
|
||||
if (id === completionRequest.current && session === pickerSession.current) setPathError((err as Error).message);
|
||||
}
|
||||
}
|
||||
function activate(option: PickerOption, columnIndex = activeColumn) {
|
||||
function activate(option: ProjectDirectory, columnIndex = activeColumn) {
|
||||
if (pickingFolder) return;
|
||||
if (canBrowse && option.kind !== "manual") navigate(option.path, columnIndex);
|
||||
else void chooseProject(option.path, option.kind === "manual" ? undefined : option.name);
|
||||
navigate(option.path, columnIndex);
|
||||
}
|
||||
|
||||
if (!visible || !defaultScope || !onChange) return null;
|
||||
@@ -435,7 +425,7 @@ export function WorkspaceProjectPicker({ isHero, disabled, scope, defaultScope,
|
||||
<DialogDescription className="sr-only">{t("workspace.picker.description")}</DialogDescription>
|
||||
<div className="relative flex shrink-0 items-center border-b border-border/50 px-2 pb-2">
|
||||
<span className="pointer-events-none absolute left-2 top-0 flex h-10 w-9 items-center justify-center"><Search className="h-4 w-4 text-muted-foreground" /></span>
|
||||
<Input ref={inputRef} role="combobox" aria-expanded={open} aria-controls={`${optionsId}-${activeColumn}`} aria-activedescendant={activeOptions.length ? `${optionsId}-${activeColumn}-${activeOption}` : undefined} aria-autocomplete="list" aria-busy={loading} value={pathDraft} disabled={disabled || pickingFolder} onChange={event => changeDraft(event.target.value)} placeholder={t("workspace.picker.search")} aria-label={t("workspace.dialog.manual")} aria-invalid={displayedError || directoryError ? true : undefined} aria-describedby={displayedError || directoryError ? errorId : undefined} className="h-10 min-w-0 flex-1 border-0 bg-transparent pl-10 pr-3 text-[14px] shadow-none focus-visible:ring-0" onKeyDown={event => {
|
||||
<Input ref={inputRef} role="combobox" aria-expanded={open} aria-controls={`${optionsId}-${activeColumn}`} aria-activedescendant={activeOptions.length ? `${optionsId}-${activeColumn}-${activeOption}` : undefined} aria-autocomplete="list" aria-busy={loading} value={pathDraft} disabled={disabled || pickingFolder} onChange={event => changeDraft(event.target.value)} placeholder={t("workspace.picker.search")} aria-label={t("workspace.picker.search")} aria-invalid={displayedError || directoryError ? true : undefined} aria-describedby={displayedError || directoryError ? errorId : undefined} className="h-10 min-w-0 flex-1 border-0 bg-transparent pl-10 pr-3 text-[14px] shadow-none focus-visible:ring-0" onKeyDown={event => {
|
||||
if (event.nativeEvent.isComposing) return;
|
||||
if ((event.key === "ArrowDown" || event.key === "ArrowUp") && !event.altKey && activeOptions.length) {
|
||||
event.preventDefault();
|
||||
@@ -447,7 +437,7 @@ export function WorkspaceProjectPicker({ isHero, disabled, scope, defaultScope,
|
||||
setHighlightActive(true);
|
||||
setActiveColumn(activeColumn - 1);
|
||||
setActiveIndex(Math.max(0, parent.options.findIndex(option => sameWorkspacePath(option.path, parent.selectedPath))));
|
||||
} else if ((event.key === "Tab" && !event.shiftKey && !!pathDraft.trim() || event.key === "ArrowRight" && !event.shiftKey && event.currentTarget.selectionStart === pathDraft.length && event.currentTarget.selectionEnd === pathDraft.length) && canBrowse) {
|
||||
} else if (event.key === "Tab" && !event.shiftKey && !!pathDraft.trim() || event.key === "ArrowRight" && !event.shiftKey && event.currentTarget.selectionStart === pathDraft.length && event.currentTarget.selectionEnd === pathDraft.length) {
|
||||
event.preventDefault(); void completePath();
|
||||
} else if (event.key === "Enter") {
|
||||
event.preventDefault();
|
||||
@@ -486,7 +476,7 @@ export function WorkspaceProjectPicker({ isHero, disabled, scope, defaultScope,
|
||||
className={cn(floatingItemClassName, floatingItemFocusClassName, "flex min-h-11 w-full min-w-0 items-center gap-3 px-3 py-2 text-left hover:bg-foreground/[0.055] dark:hover:bg-white/[0.08] disabled:opacity-50", canFavorite && "pr-12",
|
||||
sameWorkspacePath(column.selectedPath, option.path) && "bg-primary/10 text-primary font-medium hover:bg-primary/10",
|
||||
highlightActive && columnIndex === activeColumn && index === activeOption && "ring-1 ring-inset ring-ring")}>
|
||||
{option.kind === "directory" ? <WorkspacePickerTooltip label={option.path}><span className="min-w-0 flex-1 truncate text-[13px]">{option.name}</span></WorkspacePickerTooltip> : <WorkspacePickerPath path={option.path} />}
|
||||
<WorkspacePickerTooltip label={option.path}><span className="min-w-0 flex-1 truncate text-[13px]">{option.name}</span></WorkspacePickerTooltip>
|
||||
{sameWorkspacePath(option.path, scope?.project_path ?? defaultScope.project_path) && <Check className="h-4 w-4 shrink-0 text-muted-foreground" />}
|
||||
</button>
|
||||
{favoriteButton(option.path)}
|
||||
@@ -497,9 +487,9 @@ export function WorkspaceProjectPicker({ isHero, disabled, scope, defaultScope,
|
||||
</WorkspaceDirectoryColumn>)}
|
||||
</div>
|
||||
</div>
|
||||
{canBrowse && <div className="flex shrink-0 items-center gap-2 px-2 pt-1">
|
||||
<div className="flex shrink-0 items-center gap-2 px-2 pt-1">
|
||||
<label className="flex items-center gap-2 text-[12px] text-muted-foreground"><ToggleButton checked={showHidden} onChange={setShowHidden} label={t("workspace.picker.hidden")} />{t("workspace.picker.hidden")}</label>
|
||||
</div>}
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</TooltipProvider>
|
||||
|
||||
@@ -2482,11 +2482,6 @@
|
||||
}
|
||||
},
|
||||
"workspace": {
|
||||
"dialog": {
|
||||
"defaultProject": "Default workspace",
|
||||
"manual": "Paste path",
|
||||
"absolutePathRequired": "Enter an absolute folder path on this machine."
|
||||
},
|
||||
"picker": {
|
||||
"favorites": "Favorites",
|
||||
"recent": "Recent projects",
|
||||
|
||||
@@ -2283,11 +2283,6 @@
|
||||
}
|
||||
},
|
||||
"workspace": {
|
||||
"dialog": {
|
||||
"defaultProject": "Espacio de trabajo predeterminado",
|
||||
"manual": "Pegar ruta",
|
||||
"absolutePathRequired": "Introduce una ruta absoluta de carpeta en esta máquina."
|
||||
},
|
||||
"picker": {
|
||||
"favorites": "Favoritos",
|
||||
"recent": "Proyectos recientes",
|
||||
|
||||
@@ -2282,11 +2282,6 @@
|
||||
}
|
||||
},
|
||||
"workspace": {
|
||||
"dialog": {
|
||||
"defaultProject": "Espace de travail par défaut",
|
||||
"manual": "Coller un chemin",
|
||||
"absolutePathRequired": "Saisissez un chemin absolu de dossier sur cette machine."
|
||||
},
|
||||
"picker": {
|
||||
"favorites": "Favoris",
|
||||
"recent": "Projets récents",
|
||||
|
||||
@@ -2282,11 +2282,6 @@
|
||||
}
|
||||
},
|
||||
"workspace": {
|
||||
"dialog": {
|
||||
"defaultProject": "Ruang kerja bawaan",
|
||||
"manual": "Tempel path",
|
||||
"absolutePathRequired": "Masukkan path folder absolut di mesin ini."
|
||||
},
|
||||
"picker": {
|
||||
"favorites": "Favorit",
|
||||
"recent": "Proyek terbaru",
|
||||
|
||||
@@ -2282,11 +2282,6 @@
|
||||
}
|
||||
},
|
||||
"workspace": {
|
||||
"dialog": {
|
||||
"defaultProject": "既定のワークスペース",
|
||||
"manual": "パスを貼り付け",
|
||||
"absolutePathRequired": "このマシン上の絶対フォルダーパスを入力してください。"
|
||||
},
|
||||
"picker": {
|
||||
"favorites": "お気に入り",
|
||||
"recent": "最近のプロジェクト",
|
||||
|
||||
@@ -2282,11 +2282,6 @@
|
||||
}
|
||||
},
|
||||
"workspace": {
|
||||
"dialog": {
|
||||
"defaultProject": "기본 작업공간",
|
||||
"manual": "경로 붙여넣기",
|
||||
"absolutePathRequired": "이 머신의 절대 폴더 경로를 입력하세요."
|
||||
},
|
||||
"picker": {
|
||||
"favorites": "즐겨찾기",
|
||||
"recent": "최근 프로젝트",
|
||||
|
||||
@@ -2296,11 +2296,6 @@
|
||||
}
|
||||
},
|
||||
"workspace": {
|
||||
"dialog": {
|
||||
"defaultProject": "Espaço de trabalho padrão",
|
||||
"manual": "Colar caminho",
|
||||
"absolutePathRequired": "Informe um caminho absoluto de pasta nesta máquina."
|
||||
},
|
||||
"picker": {
|
||||
"favorites": "Favoritos",
|
||||
"recent": "Projetos recentes",
|
||||
|
||||
@@ -2282,11 +2282,6 @@
|
||||
}
|
||||
},
|
||||
"workspace": {
|
||||
"dialog": {
|
||||
"defaultProject": "Không gian làm việc mặc định",
|
||||
"manual": "Dán đường dẫn",
|
||||
"absolutePathRequired": "Nhập đường dẫn thư mục tuyệt đối trên máy này."
|
||||
},
|
||||
"picker": {
|
||||
"favorites": "Yêu thích",
|
||||
"recent": "Dự án gần đây",
|
||||
|
||||
@@ -2482,11 +2482,6 @@
|
||||
}
|
||||
},
|
||||
"workspace": {
|
||||
"dialog": {
|
||||
"defaultProject": "默认工作区",
|
||||
"manual": "粘贴路径",
|
||||
"absolutePathRequired": "请输入这台机器上的绝对文件夹路径。"
|
||||
},
|
||||
"picker": {
|
||||
"favorites": "收藏",
|
||||
"recent": "最近项目",
|
||||
|
||||
@@ -2282,11 +2282,6 @@
|
||||
}
|
||||
},
|
||||
"workspace": {
|
||||
"dialog": {
|
||||
"defaultProject": "預設工作區",
|
||||
"manual": "貼上路徑",
|
||||
"absolutePathRequired": "請輸入這台機器上的絕對資料夾路徑。"
|
||||
},
|
||||
"picker": {
|
||||
"favorites": "收藏",
|
||||
"recent": "最近專案",
|
||||
|
||||
@@ -53,16 +53,6 @@ const HOST_WS_CONNECTING = 0;
|
||||
const HOST_WS_OPEN = 1;
|
||||
const HOST_WS_CLOSING = 2;
|
||||
const HOST_WS_CLOSED = 3;
|
||||
const LOOPBACK_HOST_PORT_PARAM = "nativeHostPort";
|
||||
const LOOPBACK_HOST_TOKEN_PARAM = "nativeHostToken";
|
||||
const LOOPBACK_HOST_STORAGE_KEY = "nanobot-webui.native-host";
|
||||
|
||||
interface LoopbackHostConfig {
|
||||
port: number;
|
||||
token: string;
|
||||
}
|
||||
|
||||
let hasLoopbackNativeHost = false;
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
@@ -75,20 +65,6 @@ function getHostApi(): NanobotHostApi | null {
|
||||
return window.nanobotHost ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Recognize the external native host advertised in the URL fragment.
|
||||
*
|
||||
* Consume the existing loopback bootstrap parameters so native UI behavior
|
||||
* survives refresh. The bridge token is removed from the URL and retained
|
||||
* only for the lifetime of this browser tab.
|
||||
*/
|
||||
export function initializeLoopbackRuntimeHost(): boolean {
|
||||
if (typeof window === "undefined") return false;
|
||||
const config = consumeLoopbackHostConfig() ?? loadLoopbackHostConfig();
|
||||
hasLoopbackNativeHost = config !== null;
|
||||
return hasLoopbackNativeHost;
|
||||
}
|
||||
|
||||
export function toRuntimeSurface(surface: string | null | undefined): RuntimeSurface {
|
||||
return surface === "native" ? "native" : "browser";
|
||||
}
|
||||
@@ -101,7 +77,6 @@ export function createRuntimeHost(
|
||||
const mergedCapabilities = {
|
||||
can_export_diagnostics: false,
|
||||
can_open_logs: false,
|
||||
can_pick_folder: false,
|
||||
can_restart_engine: false,
|
||||
...(capabilities ?? {}),
|
||||
};
|
||||
@@ -126,7 +101,7 @@ export function getRuntimeHost(
|
||||
}
|
||||
|
||||
export function isNativeRuntime(surface?: string | null): boolean {
|
||||
return getHostApi() !== null || hasLoopbackNativeHost || toRuntimeSurface(surface) === "native";
|
||||
return getHostApi() !== null || toRuntimeSurface(surface) === "native";
|
||||
}
|
||||
|
||||
export function createHostWebSocket(url: string): WebSocket {
|
||||
@@ -156,63 +131,6 @@ function getHostSocketBridge(): HostSocketBridge | null {
|
||||
};
|
||||
}
|
||||
|
||||
function consumeLoopbackHostConfig(): LoopbackHostConfig | null {
|
||||
const hash = window.location.hash || "";
|
||||
const queryStart = hash.indexOf("?");
|
||||
if (queryStart < 0) return null;
|
||||
|
||||
const path = hash.slice(0, queryStart) || "#/";
|
||||
const params = new URLSearchParams(hash.slice(queryStart + 1));
|
||||
const hasBridgeParams = params.has(LOOPBACK_HOST_PORT_PARAM)
|
||||
|| params.has(LOOPBACK_HOST_TOKEN_PARAM);
|
||||
if (!hasBridgeParams) return null;
|
||||
|
||||
const config = validateLoopbackHostConfig({
|
||||
port: Number(params.get(LOOPBACK_HOST_PORT_PARAM)),
|
||||
token: params.get(LOOPBACK_HOST_TOKEN_PARAM) ?? "",
|
||||
});
|
||||
params.delete(LOOPBACK_HOST_PORT_PARAM);
|
||||
params.delete(LOOPBACK_HOST_TOKEN_PARAM);
|
||||
const nextQuery = params.toString();
|
||||
const nextHash = `${path}${nextQuery ? `?${nextQuery}` : ""}`;
|
||||
window.history.replaceState(
|
||||
null,
|
||||
"",
|
||||
`${window.location.pathname}${window.location.search}${nextHash}`,
|
||||
);
|
||||
|
||||
try {
|
||||
if (config) {
|
||||
window.sessionStorage.setItem(LOOPBACK_HOST_STORAGE_KEY, JSON.stringify(config));
|
||||
} else {
|
||||
window.sessionStorage.removeItem(LOOPBACK_HOST_STORAGE_KEY);
|
||||
}
|
||||
} catch {
|
||||
// The current page can still use the bridge when session storage is unavailable.
|
||||
}
|
||||
return config;
|
||||
}
|
||||
|
||||
function loadLoopbackHostConfig(): LoopbackHostConfig | null {
|
||||
try {
|
||||
const raw = window.sessionStorage.getItem(LOOPBACK_HOST_STORAGE_KEY);
|
||||
if (!raw) return null;
|
||||
return validateLoopbackHostConfig(JSON.parse(raw) as Partial<LoopbackHostConfig>);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function validateLoopbackHostConfig(
|
||||
value: Partial<LoopbackHostConfig>,
|
||||
): LoopbackHostConfig | null {
|
||||
const port = Number(value.port);
|
||||
const token = typeof value.token === "string" ? value.token : "";
|
||||
if (!Number.isInteger(port) || port < 1 || port > 65_535) return null;
|
||||
if (!/^[A-Za-z0-9_-]{32,128}$/.test(token)) return null;
|
||||
return { port, token };
|
||||
}
|
||||
|
||||
class HostWebSocket {
|
||||
binaryType: BinaryType = "blob";
|
||||
onclose: ((this: WebSocket, ev: CloseEvent) => unknown) | null = null;
|
||||
|
||||
@@ -498,10 +498,6 @@ export interface WorkspacesPayload {
|
||||
controls: {
|
||||
can_change_project: boolean;
|
||||
can_use_full_access: boolean;
|
||||
can_pick_folder?: boolean;
|
||||
can_browse_directories?: boolean;
|
||||
can_resolve_project?: boolean;
|
||||
can_manage_favorites?: boolean;
|
||||
};
|
||||
}
|
||||
|
||||
@@ -592,7 +588,6 @@ type SettingsApplyStatus =
|
||||
|
||||
export interface RuntimeCapabilities {
|
||||
can_restart_engine: boolean;
|
||||
can_pick_folder: boolean;
|
||||
can_open_logs: boolean;
|
||||
can_export_diagnostics: boolean;
|
||||
}
|
||||
|
||||
@@ -3,7 +3,6 @@ import ReactDOM from "react-dom/client";
|
||||
import App from "./App";
|
||||
import "./globals.css";
|
||||
import { initializeI18n } from "./i18n";
|
||||
import { initializeLoopbackRuntimeHost } from "./lib/runtime";
|
||||
import { initializePairReturn } from "./lib/remote-pair-return";
|
||||
|
||||
// `crypto.randomUUID` is only defined in secure contexts (HTTPS or localhost).
|
||||
@@ -27,7 +26,6 @@ if (!root) throw new Error("root element missing");
|
||||
|
||||
initializePairReturn();
|
||||
window.addEventListener("hashchange", initializePairReturn);
|
||||
initializeLoopbackRuntimeHost();
|
||||
|
||||
async function renderWebui(container: HTMLElement) {
|
||||
await initializeI18n();
|
||||
|
||||
@@ -1141,13 +1141,20 @@ describe("App layout", () => {
|
||||
|
||||
it("preserves the first message when the gateway rejects a project", async () => {
|
||||
const consoleError = vi.spyOn(console, "error").mockImplementation(() => {});
|
||||
const projectPath = "C:\\missing-project";
|
||||
const directory = (path: string) => ({
|
||||
path, parent: null, entries: [], partial: false,
|
||||
truncated: false, host: "test-host", platform: "Windows",
|
||||
});
|
||||
const directoryUrl = (path: string) => `/api/workspaces/directories?${new URLSearchParams({ path, q: "", hidden: "0", partial: "1" })}`;
|
||||
requestMutationSpy.mockResolvedValue({ path: projectPath, name: "missing-project" });
|
||||
createChatSpy.mockRejectedValueOnce(
|
||||
new Error("workspace_scope_rejected:project_path must be an existing directory"),
|
||||
);
|
||||
mockFetchRoutes({
|
||||
"/api/workspaces": {
|
||||
schema_version: 1,
|
||||
default_access_mode: "restricted",
|
||||
default_access_mode: "default",
|
||||
default_scope: {
|
||||
project_path: "C:\\workspace",
|
||||
project_name: "workspace",
|
||||
@@ -1156,16 +1163,21 @@ describe("App layout", () => {
|
||||
},
|
||||
controls: { can_change_project: true, can_use_full_access: true },
|
||||
},
|
||||
[directoryUrl("C:\\workspace\\")]: directory("C:\\workspace"),
|
||||
[directoryUrl(projectPath)]: directory(projectPath),
|
||||
[directoryUrl(`${projectPath}\\`)]: directory(projectPath),
|
||||
});
|
||||
|
||||
render(<App />);
|
||||
|
||||
await waitFor(() => expect(connectSpy).toHaveBeenCalled());
|
||||
fireEvent.click(await screen.findByRole("button", { name: "Switch working directory" }));
|
||||
fireEvent.change(await screen.findByLabelText("Paste path"), {
|
||||
target: { value: "C:\\missing-project" },
|
||||
fireEvent.change(await screen.findByRole("combobox"), {
|
||||
target: { value: projectPath },
|
||||
});
|
||||
await waitFor(() => expect(screen.getByRole("button", { name: "Select" })).toBeEnabled());
|
||||
fireEvent.click(screen.getByRole("button", { name: "Select" }));
|
||||
await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
|
||||
|
||||
const message = screen.getByLabelText("Message input");
|
||||
fireEvent.change(message, { target: { value: "keep this first message" } });
|
||||
@@ -1179,10 +1191,10 @@ describe("App layout", () => {
|
||||
"The gateway rejected this project or access mode. Choose an existing project or a different access mode, then try again.",
|
||||
);
|
||||
fireEvent.click(projectButton);
|
||||
const projectPath = await screen.findByLabelText("Paste path");
|
||||
expect(projectPath).toHaveValue("C:\\missing-project");
|
||||
expect(projectPath).toHaveAttribute("aria-invalid", "true");
|
||||
expect(projectPath).toHaveFocus();
|
||||
const pathInput = await screen.findByRole("combobox");
|
||||
expect(pathInput).toHaveValue(`${projectPath}\\`);
|
||||
expect(pathInput).toHaveAttribute("aria-invalid", "true");
|
||||
expect(pathInput).toHaveFocus();
|
||||
expect(screen.getByRole("alert")).toHaveTextContent(
|
||||
"The gateway rejected this project or access mode. Choose an existing project or a different access mode, then try again.",
|
||||
);
|
||||
|
||||
@@ -204,8 +204,6 @@ const LOCALIZED_WORKSPACE_COPY_KEYS = [
|
||||
"thread.composer.workspace.full",
|
||||
"errors.workspaceScopeRejected.title",
|
||||
"errors.workspaceScopeRejected.body",
|
||||
"workspace.dialog.defaultProject",
|
||||
"workspace.dialog.absolutePathRequired",
|
||||
];
|
||||
const LOCALIZED_CHANNEL_SHELL_KEYS = [
|
||||
"settings.channels.advanced",
|
||||
|
||||
@@ -2,15 +2,11 @@ import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import {
|
||||
getRuntimeHost,
|
||||
initializeLoopbackRuntimeHost,
|
||||
isNativeRuntime,
|
||||
} from "@/lib/runtime";
|
||||
|
||||
afterEach(() => {
|
||||
Reflect.deleteProperty(window, "nanobotHost");
|
||||
window.sessionStorage.clear();
|
||||
window.history.replaceState(null, "", "/");
|
||||
initializeLoopbackRuntimeHost();
|
||||
});
|
||||
|
||||
describe("runtime host facade", () => {
|
||||
@@ -52,35 +48,4 @@ describe("runtime host facade", () => {
|
||||
expect(isNativeRuntime("native")).toBe(true);
|
||||
});
|
||||
|
||||
it("recognizes an external native host across refresh and consumes its URL bootstrap", () => {
|
||||
const token = "a".repeat(43);
|
||||
window.history.replaceState(
|
||||
null,
|
||||
"",
|
||||
`/#/new?bootstrapSecret=secret&nativeHostPort=43123&nativeHostToken=${token}`,
|
||||
);
|
||||
|
||||
expect(initializeLoopbackRuntimeHost()).toBe(true);
|
||||
expect(window.location.hash).toBe("#/new?bootstrapSecret=secret");
|
||||
expect(isNativeRuntime()).toBe(true);
|
||||
expect(getRuntimeHost().surface).toBe("native");
|
||||
|
||||
window.history.replaceState(null, "", "/#/new");
|
||||
expect(initializeLoopbackRuntimeHost()).toBe(true);
|
||||
expect(getRuntimeHost().surface).toBe("native");
|
||||
expect(isNativeRuntime()).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects invalid loopback bridge bootstrap values", () => {
|
||||
window.history.replaceState(
|
||||
null,
|
||||
"",
|
||||
"/#/new?nativeHostPort=70000&nativeHostToken=too-short",
|
||||
);
|
||||
|
||||
expect(initializeLoopbackRuntimeHost()).toBe(false);
|
||||
expect(window.location.hash).toBe("#/new");
|
||||
expect(getRuntimeHost().surface).toBe("browser");
|
||||
expect(isNativeRuntime()).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -335,7 +335,6 @@ describe("Settings capabilities", () => {
|
||||
runtime_surface: "native" as const,
|
||||
runtime_capabilities: {
|
||||
can_restart_engine: true,
|
||||
can_pick_folder: true,
|
||||
can_open_logs: true,
|
||||
can_export_diagnostics: true,
|
||||
},
|
||||
|
||||
@@ -8,6 +8,28 @@ import { encodeImage } from "@/lib/imageEncode";
|
||||
import { SESSION_DRAG_TYPE } from "@/lib/session-drag";
|
||||
import type { ChatSummary, CliAppInfo, McpPresetInfo, SlashCommand, WorkspaceScopePayload } from "@/lib/types";
|
||||
|
||||
function workspacePickerProps(scope: WorkspaceScopePayload) {
|
||||
const resolvePath = (path: string) => path.startsWith("~/") ? `/Users/test/${path.slice(2)}` : path;
|
||||
return {
|
||||
onLoadWorkspaceProjects: async () => ({
|
||||
schema_version: 1,
|
||||
default_access_mode: "default" as const,
|
||||
default_scope: scope,
|
||||
recent_projects: [],
|
||||
favorite_projects: [],
|
||||
controls: { can_change_project: true, can_use_full_access: true },
|
||||
}),
|
||||
onBrowseWorkspaceDirectories: async (path: string) => ({
|
||||
path: resolvePath(path), parent: null, entries: [], partial: false,
|
||||
truncated: false, host: "test-host", platform: "Linux",
|
||||
}),
|
||||
onResolveWorkspaceProject: async (path: string) => ({
|
||||
path: resolvePath(path), name: path.replace(/\\/g, "/").split("/").filter(Boolean).pop() || path,
|
||||
}),
|
||||
onFavoriteWorkspaceProject: async () => [],
|
||||
};
|
||||
}
|
||||
|
||||
vi.mock("@/lib/imageEncode", () => ({
|
||||
encodeImage: vi.fn(async (file: File) => ({
|
||||
ok: true,
|
||||
@@ -1467,6 +1489,7 @@ describe("ThreadComposer", () => {
|
||||
restrict_to_workspace: false,
|
||||
}}
|
||||
workspaceDefaultScope={defaultScope}
|
||||
{...workspacePickerProps(defaultScope)}
|
||||
workspaceControls={{ can_change_project: true, can_use_full_access: true }}
|
||||
onWorkspaceScopeChange={onWorkspaceScopeChange}
|
||||
/>,
|
||||
@@ -1477,13 +1500,14 @@ describe("ThreadComposer", () => {
|
||||
expect(await screen.findByRole("button", { name: "/Users/test/.nanobot/workspace" })).toBeInTheDocument();
|
||||
expect(screen.getByRole("dialog")).toBeInTheDocument();
|
||||
|
||||
const input = screen.getByLabelText("Paste path");
|
||||
const input = screen.getByRole("combobox");
|
||||
fireEvent.change(input, { target: { value: "relative/project" } });
|
||||
expect(screen.queryByRole("option", { name: "relative/project" })).not.toBeInTheDocument();
|
||||
expect(onWorkspaceScopeChange).not.toHaveBeenCalled();
|
||||
|
||||
fireEvent.change(input, { target: { value: "/Users/test/project-alpha" } });
|
||||
fireEvent.click(screen.getByRole("option", { name: "/Users/test/project-alpha" }));
|
||||
await waitFor(() => expect(screen.getByRole("button", { name: "Select" })).toBeEnabled());
|
||||
await user.click(screen.getByRole("button", { name: "Select" }));
|
||||
|
||||
expect(onWorkspaceScopeChange).toHaveBeenCalledWith(expect.objectContaining({
|
||||
project_path: "/Users/test/project-alpha",
|
||||
@@ -1493,12 +1517,13 @@ describe("ThreadComposer", () => {
|
||||
}));
|
||||
|
||||
await user.click(screen.getByRole("button", { name: "Switch working directory" }));
|
||||
const reopenedInput = await screen.findByLabelText("Paste path");
|
||||
const reopenedInput = await screen.findByRole("combobox");
|
||||
fireEvent.change(reopenedInput, { target: { value: "~/Pictures/Photos" } });
|
||||
fireEvent.click(screen.getByRole("option", { name: "~/Pictures/Photos" }));
|
||||
await waitFor(() => expect(screen.getByRole("button", { name: "Select" })).toBeEnabled());
|
||||
await user.click(screen.getByRole("button", { name: "Select" }));
|
||||
|
||||
expect(onWorkspaceScopeChange).toHaveBeenLastCalledWith(expect.objectContaining({
|
||||
project_path: "~/Pictures/Photos",
|
||||
project_path: "/Users/test/Pictures/Photos",
|
||||
project_name: "Photos",
|
||||
access_mode: "full",
|
||||
restrict_to_workspace: false,
|
||||
@@ -1527,6 +1552,7 @@ describe("ThreadComposer", () => {
|
||||
variant="hero"
|
||||
workspaceScope={defaultScope}
|
||||
workspaceDefaultScope={defaultScope}
|
||||
{...workspacePickerProps(defaultScope)}
|
||||
workspaceControls={{ can_change_project: true, can_use_full_access: true }}
|
||||
onWorkspaceScopeChange={onWorkspaceScopeChange}
|
||||
/>,
|
||||
@@ -1534,9 +1560,10 @@ describe("ThreadComposer", () => {
|
||||
|
||||
await user.click(screen.getByRole("button", { name: "Switch working directory" }));
|
||||
|
||||
fireEvent.change(await screen.findByLabelText("Paste path"), { target: { value: selectedPath } });
|
||||
fireEvent.keyDown(screen.getByLabelText("Paste path"), { key: "Enter" });
|
||||
expect(onWorkspaceScopeChange).toHaveBeenCalledWith(expect.objectContaining({ project_path: selectedPath }));
|
||||
fireEvent.change(await screen.findByRole("combobox"), { target: { value: selectedPath } });
|
||||
await waitFor(() => expect(screen.getByRole("button", { name: "Select" })).toBeEnabled());
|
||||
fireEvent.keyDown(screen.getByRole("combobox"), { key: "Enter" });
|
||||
await waitFor(() => expect(onWorkspaceScopeChange).toHaveBeenCalledWith(expect.objectContaining({ project_path: selectedPath })));
|
||||
});
|
||||
|
||||
it("groups the directory and access beside attachments and hides them with workspace controls", () => {
|
||||
@@ -1554,6 +1581,7 @@ describe("ThreadComposer", () => {
|
||||
workspaceControlsHidden={workspaceControlsHidden}
|
||||
workspaceScope={defaultScope}
|
||||
workspaceDefaultScope={defaultScope}
|
||||
{...workspacePickerProps(defaultScope)}
|
||||
workspaceControls={{ can_change_project: true, can_use_full_access: true }}
|
||||
onWorkspaceScopeChange={vi.fn()}
|
||||
/>
|
||||
@@ -1576,7 +1604,8 @@ describe("ThreadComposer", () => {
|
||||
vi.spyOn(HTMLFormElement.prototype, "getBoundingClientRect").mockImplementation(() => rect({ width, height: 160 }));
|
||||
const defaultScope = { project_path: "/srv/workspace", project_name: "workspace", access_mode: "full" as const };
|
||||
const { container } = render(<ThreadComposer variant="hero" onSend={vi.fn()} workspaceScope={defaultScope}
|
||||
workspaceDefaultScope={defaultScope} workspaceControls={{ can_change_project: true }} onWorkspaceScopeChange={vi.fn()} />);
|
||||
workspaceDefaultScope={defaultScope}
|
||||
{...workspacePickerProps(defaultScope)} workspaceControls={{ can_change_project: true }} onWorkspaceScopeChange={vi.fn()} />);
|
||||
const input = screen.getByRole("textbox");
|
||||
const row = container.querySelector(".thread-composer-workspace-row")!;
|
||||
const trigger = screen.getByRole("button", { name: "Switch working directory" });
|
||||
@@ -1629,12 +1658,10 @@ describe("ThreadComposer", () => {
|
||||
variant="hero"
|
||||
workspaceScope={defaultScope}
|
||||
workspaceDefaultScope={defaultScope}
|
||||
{...workspacePickerProps(defaultScope)}
|
||||
workspaceControls={{
|
||||
can_change_project: true,
|
||||
can_use_full_access: true,
|
||||
can_pick_folder: true,
|
||||
can_browse_directories: true,
|
||||
can_resolve_project: true,
|
||||
}}
|
||||
onBrowseWorkspaceDirectories={onBrowseWorkspaceDirectories}
|
||||
onResolveWorkspaceProject={onResolveWorkspaceProject}
|
||||
@@ -1658,7 +1685,7 @@ describe("ThreadComposer", () => {
|
||||
}));
|
||||
});
|
||||
|
||||
it("selects a restricted project manually when the host lacks directory browsing", async () => {
|
||||
it("selects an entered host path in Restricted mode when Full Access is unavailable", async () => {
|
||||
const user = userEvent.setup();
|
||||
const onWorkspaceScopeChange = vi.fn();
|
||||
const defaultScope = {
|
||||
@@ -1674,10 +1701,10 @@ describe("ThreadComposer", () => {
|
||||
variant="hero"
|
||||
workspaceScope={defaultScope}
|
||||
workspaceDefaultScope={defaultScope}
|
||||
{...workspacePickerProps(defaultScope)}
|
||||
workspaceControls={{
|
||||
can_change_project: true,
|
||||
can_use_full_access: false,
|
||||
can_pick_folder: false,
|
||||
}}
|
||||
onWorkspaceScopeChange={onWorkspaceScopeChange}
|
||||
/>,
|
||||
@@ -1685,12 +1712,13 @@ describe("ThreadComposer", () => {
|
||||
|
||||
await user.click(screen.getByRole("button", { name: "Switch working directory" }));
|
||||
|
||||
expect(await screen.findByLabelText("Paste path")).toBeInTheDocument();
|
||||
expect(await screen.findByRole("combobox")).toBeInTheDocument();
|
||||
|
||||
fireEvent.change(screen.getByLabelText("Paste path"), {
|
||||
fireEvent.change(screen.getByRole("combobox"), {
|
||||
target: { value: "/srv/nas-project" },
|
||||
});
|
||||
fireEvent.click(screen.getByRole("option", { name: "/srv/nas-project" }));
|
||||
await waitFor(() => expect(screen.getByRole("button", { name: "Select" })).toBeEnabled());
|
||||
await user.click(screen.getByRole("button", { name: "Select" }));
|
||||
|
||||
expect(onWorkspaceScopeChange).toHaveBeenCalledWith(expect.objectContaining({
|
||||
project_path: "/srv/nas-project",
|
||||
@@ -1699,32 +1727,6 @@ describe("ThreadComposer", () => {
|
||||
}));
|
||||
});
|
||||
|
||||
it("offers manual path entry when the host lacks directory browsing", async () => {
|
||||
const user = userEvent.setup();
|
||||
const defaultScope = {
|
||||
project_path: "/Users/test/.nanobot/workspace",
|
||||
project_name: "workspace",
|
||||
access_mode: "full" as const,
|
||||
restrict_to_workspace: false,
|
||||
};
|
||||
|
||||
render(
|
||||
<ThreadComposer
|
||||
onSend={vi.fn()}
|
||||
placeholder="Ask anything..."
|
||||
variant="hero"
|
||||
workspaceScope={defaultScope}
|
||||
workspaceDefaultScope={defaultScope}
|
||||
workspaceControls={{ can_change_project: true, can_use_full_access: true }}
|
||||
onWorkspaceScopeChange={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
|
||||
await user.click(screen.getByRole("button", { name: "Switch working directory" }));
|
||||
|
||||
expect(await screen.findByRole("button", { name: "/Users/test/.nanobot/workspace" })).toBeInTheDocument();
|
||||
expect(screen.getByLabelText("Paste path")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("closes the sustained goal through its existing drawer", () => {
|
||||
const { container, rerender } = render(
|
||||
|
||||
@@ -4,7 +4,7 @@ import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { WorkspaceProjectPicker } from "@/components/thread/WorkspaceControls";
|
||||
import type { WorkspaceDirectoriesPayload, WorkspacesPayload } from "@/lib/types";
|
||||
import type { BrowseWorkspaceDirectories } from "@/lib/workspace";
|
||||
import { projectNameFromPath, type BrowseWorkspaceDirectories } from "@/lib/workspace";
|
||||
|
||||
const scope = { project_path: "/srv/workspace", access_mode: "restricted" as const };
|
||||
const catalog: WorkspacesPayload = {
|
||||
@@ -13,19 +13,28 @@ const catalog: WorkspacesPayload = {
|
||||
default_scope: scope,
|
||||
recent_projects: [{ name: "alpha", path: "/srv/alpha" }, { name: "beta", path: "/srv/beta" }],
|
||||
host: { name: "dev-server", platform: "Linux" },
|
||||
controls: { can_change_project: true, can_use_full_access: false, can_browse_directories: true },
|
||||
controls: { can_change_project: true, can_use_full_access: false },
|
||||
};
|
||||
const directory: WorkspaceDirectoriesPayload = {
|
||||
path: "/srv/workspace", parent: "/srv", entries: [{ name: "alpha", path: "/srv/workspace/alpha" }],
|
||||
truncated: false, host: "dev-server", platform: "Linux",
|
||||
};
|
||||
|
||||
function pickerActions() {
|
||||
return {
|
||||
onLoadProjects: vi.fn().mockResolvedValue(catalog),
|
||||
onBrowseDirectories: vi.fn((path: string) => Promise.resolve({ ...directory, path, entries: [] })),
|
||||
onResolveProject: vi.fn((path: string) => Promise.resolve({ path, name: projectNameFromPath(path) })),
|
||||
onFavoriteProject: vi.fn().mockResolvedValue([]),
|
||||
};
|
||||
}
|
||||
|
||||
describe("Workspace project picker", () => {
|
||||
it("keeps saved locations separate from directory filtering", async () => {
|
||||
const user = userEvent.setup();
|
||||
const onChange = vi.fn();
|
||||
const onBrowse = vi.fn().mockResolvedValue(directory);
|
||||
render(<WorkspaceProjectPicker isHero scope={scope} defaultScope={scope} controls={catalog.controls} onLoadProjects={vi.fn().mockResolvedValue(catalog)} onBrowseDirectories={onBrowse} onChange={onChange} />);
|
||||
render(<WorkspaceProjectPicker {...pickerActions()} isHero scope={scope} defaultScope={scope} controls={catalog.controls} onLoadProjects={vi.fn().mockResolvedValue(catalog)} onBrowseDirectories={onBrowse} onChange={onChange} />);
|
||||
await user.click(screen.getByRole("button", { name: "Switch working directory" }));
|
||||
const shortcut = await screen.findByRole("button", { name: "/srv/beta" });
|
||||
await user.clear(screen.getByRole("combobox"));
|
||||
@@ -52,7 +61,7 @@ describe("Workspace project picker", () => {
|
||||
const user = userEvent.setup();
|
||||
const onBrowse = vi.fn((path: string) => Promise.resolve(path.replace(/\/$/, "") === scope.project_path
|
||||
? directory : { ...directory, path: "/srv/workspace/alpha", entries: [] }));
|
||||
render(<WorkspaceProjectPicker isHero scope={scope} defaultScope={scope} controls={catalog.controls} onBrowseDirectories={onBrowse} onChange={vi.fn()} />);
|
||||
render(<WorkspaceProjectPicker {...pickerActions()} isHero scope={scope} defaultScope={scope} controls={catalog.controls} onBrowseDirectories={onBrowse} onChange={vi.fn()} />);
|
||||
await user.click(screen.getByRole("button", { name: "Switch working directory" }));
|
||||
await user.click(await screen.findByRole("option", { name: "/srv/workspace/alpha" }));
|
||||
await waitFor(() => expect(screen.queryByRole("status")).not.toBeInTheDocument());
|
||||
@@ -72,7 +81,7 @@ describe("Workspace project picker", () => {
|
||||
const user = userEvent.setup();
|
||||
const onBrowse = vi.fn((path: string) => Promise.resolve(path.replace(/\/$/, "") === scope.project_path
|
||||
? directory : { ...directory, path: "/srv/workspace/alpha", entries: [] }));
|
||||
render(<WorkspaceProjectPicker isHero scope={scope} defaultScope={scope} controls={catalog.controls} onBrowseDirectories={onBrowse} onChange={vi.fn()} />);
|
||||
render(<WorkspaceProjectPicker {...pickerActions()} isHero scope={scope} defaultScope={scope} controls={catalog.controls} onBrowseDirectories={onBrowse} onChange={vi.fn()} />);
|
||||
await user.click(screen.getByRole("button", { name: "Switch working directory" }));
|
||||
await user.click(await screen.findByRole("option", { name: "/srv/workspace/alpha" }));
|
||||
await waitFor(() => expect(screen.queryByRole("status")).not.toBeInTheDocument());
|
||||
@@ -100,7 +109,7 @@ describe("Workspace project picker", () => {
|
||||
const path = rawPath.replace(/\/$/, "");
|
||||
return Promise.resolve({ ...directory, path, entries: path === scope.project_path ? entries : [{ name: "child", path: `${path}/child` }] });
|
||||
});
|
||||
render(<WorkspaceProjectPicker isHero scope={scope} defaultScope={scope} controls={catalog.controls} onBrowseDirectories={onBrowse} onChange={vi.fn()} />);
|
||||
render(<WorkspaceProjectPicker {...pickerActions()} isHero scope={scope} defaultScope={scope} controls={catalog.controls} onBrowseDirectories={onBrowse} onChange={vi.fn()} />);
|
||||
await user.click(screen.getByRole("button", { name: "Switch working directory" }));
|
||||
const first = await screen.findByRole("option", { name: entries[0].path });
|
||||
expect(first).toHaveAttribute("aria-setsize", "500");
|
||||
@@ -124,7 +133,7 @@ describe("Workspace project picker", () => {
|
||||
const user = userEvent.setup();
|
||||
const onChange = vi.fn();
|
||||
const onBrowse = vi.fn().mockResolvedValue(directory);
|
||||
render(<WorkspaceProjectPicker isHero scope={scope} defaultScope={scope} controls={catalog.controls} onBrowseDirectories={onBrowse} onChange={onChange} />);
|
||||
render(<WorkspaceProjectPicker {...pickerActions()} isHero scope={scope} defaultScope={scope} controls={catalog.controls} onBrowseDirectories={onBrowse} onChange={onChange} />);
|
||||
await user.click(screen.getByRole("button", { name: "Switch working directory" }));
|
||||
await screen.findByRole("option", { name: "/srv/workspace/alpha" });
|
||||
expect(onBrowse).toHaveBeenLastCalledWith("/srv/workspace/", "", false, true);
|
||||
@@ -138,15 +147,16 @@ describe("Workspace project picker", () => {
|
||||
await waitFor(() => expect(screen.getByRole("button", { name: "Switch working directory" })).not.toHaveFocus());
|
||||
});
|
||||
|
||||
it("keeps invalid paths editable and validates the project before closing", async () => {
|
||||
it("keeps the selection editable when project validation fails", async () => {
|
||||
const user = userEvent.setup();
|
||||
const onChange = vi.fn();
|
||||
const onResolve = vi.fn().mockRejectedValueOnce(new Error("project_path must be an existing directory"))
|
||||
.mockResolvedValueOnce({ name: "alpha", path: "/srv/alpha" });
|
||||
render(<WorkspaceProjectPicker isHero scope={scope} defaultScope={scope} controls={{ ...catalog.controls, can_resolve_project: true }} onResolveProject={onResolve} onChange={onChange} />);
|
||||
render(<WorkspaceProjectPicker {...pickerActions()} isHero scope={scope} defaultScope={scope} controls={catalog.controls} onResolveProject={onResolve} onChange={onChange} />);
|
||||
await user.click(screen.getByRole("button", { name: "Switch working directory" }));
|
||||
await user.clear(screen.getByRole("combobox"));
|
||||
await user.type(screen.getByRole("combobox"), "/srv/missing");
|
||||
await waitFor(() => expect(screen.getByRole("button", { name: "Select" })).toBeEnabled());
|
||||
await user.keyboard("{Enter}");
|
||||
expect(await screen.findByRole("alert")).toHaveTextContent("existing directory");
|
||||
expect(screen.getByRole("combobox")).toHaveValue("/srv/missing");
|
||||
@@ -154,33 +164,19 @@ describe("Workspace project picker", () => {
|
||||
expect(onChange).not.toHaveBeenCalled();
|
||||
await user.clear(screen.getByRole("combobox"));
|
||||
await user.type(screen.getByRole("combobox"), "/srv/alpha");
|
||||
await waitFor(() => expect(screen.getByRole("button", { name: "Select" })).toBeEnabled());
|
||||
await user.keyboard("{Enter}");
|
||||
await waitFor(() => expect(onChange).toHaveBeenCalledWith(expect.objectContaining({ project_path: "/srv/alpha" })));
|
||||
expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("uses manual paths without new requests on a host missing optional capabilities", async () => {
|
||||
const user = userEvent.setup();
|
||||
const onChange = vi.fn();
|
||||
const onBrowse = vi.fn();
|
||||
const onResolve = vi.fn();
|
||||
render(<WorkspaceProjectPicker isHero scope={scope} defaultScope={scope} controls={{ can_change_project: true, can_use_full_access: false }} onBrowseDirectories={onBrowse} onResolveProject={onResolve} onChange={onChange} />);
|
||||
await user.click(screen.getByRole("button", { name: "Switch working directory" }));
|
||||
expect(screen.queryByRole("option", { name: "Browse folders…" })).not.toBeInTheDocument();
|
||||
await user.clear(screen.getByRole("combobox"));
|
||||
await user.type(screen.getByRole("combobox"), "/srv/alpha");
|
||||
await user.keyboard("{Enter}");
|
||||
expect(onChange).toHaveBeenCalledWith(expect.objectContaining({ project_path: "/srv/alpha" }));
|
||||
expect(onBrowse).not.toHaveBeenCalled();
|
||||
expect(onResolve).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not apply a directory response after closing the dialog", async () => {
|
||||
const user = userEvent.setup();
|
||||
const onChange = vi.fn();
|
||||
let finish!: (value: WorkspaceDirectoriesPayload) => void;
|
||||
const onBrowse = vi.fn(() => new Promise<WorkspaceDirectoriesPayload>((resolve) => { finish = resolve; }));
|
||||
render(<WorkspaceProjectPicker isHero scope={scope} defaultScope={scope} controls={catalog.controls} onBrowseDirectories={onBrowse} onChange={onChange} />);
|
||||
render(<WorkspaceProjectPicker {...pickerActions()} isHero scope={scope} defaultScope={scope} controls={catalog.controls} onBrowseDirectories={onBrowse} onChange={onChange} />);
|
||||
await user.click(screen.getByRole("button", { name: "Switch working directory" }));
|
||||
await waitFor(() => expect(onBrowse).toHaveBeenCalled());
|
||||
await user.keyboard("{Escape}");
|
||||
@@ -193,7 +189,7 @@ describe("Workspace project picker", () => {
|
||||
const onChange = vi.fn();
|
||||
const favorites = [{ name: "beta", path: "/srv/beta" }];
|
||||
const onFavorite = vi.fn().mockResolvedValueOnce(favorites).mockRejectedValueOnce(new Error("disk full")).mockResolvedValueOnce([]);
|
||||
render(<WorkspaceProjectPicker isHero scope={scope} defaultScope={scope} controls={catalog.controls} onLoadProjects={vi.fn().mockResolvedValue({ ...catalog, controls: { ...catalog.controls, can_manage_favorites: true } })} onFavoriteProject={onFavorite} onChange={onChange} />);
|
||||
render(<WorkspaceProjectPicker {...pickerActions()} isHero scope={scope} defaultScope={scope} controls={catalog.controls} onLoadProjects={vi.fn().mockResolvedValue(catalog)} onFavoriteProject={onFavorite} onChange={onChange} />);
|
||||
await user.click(screen.getByRole("button", { name: "Switch working directory" }));
|
||||
await user.click(await screen.findByRole("button", { name: "Pin beta" }));
|
||||
expect(onFavorite).toHaveBeenLastCalledWith("/srv/beta", true);
|
||||
@@ -213,8 +209,8 @@ describe("Workspace project picker", () => {
|
||||
const user = userEvent.setup();
|
||||
const onChange = vi.fn();
|
||||
const onFavorite = vi.fn().mockResolvedValue([{ name: "alpha", path: "/srv/workspace/alpha" }]);
|
||||
render(<WorkspaceProjectPicker isHero scope={scope} defaultScope={scope} controls={catalog.controls}
|
||||
onLoadProjects={vi.fn().mockResolvedValue({ ...catalog, controls: { ...catalog.controls, can_manage_favorites: true } })}
|
||||
render(<WorkspaceProjectPicker {...pickerActions()} isHero scope={scope} defaultScope={scope} controls={catalog.controls}
|
||||
onLoadProjects={vi.fn().mockResolvedValue(catalog)}
|
||||
onBrowseDirectories={vi.fn().mockResolvedValue(directory)} onFavoriteProject={onFavorite} onChange={onChange} />);
|
||||
await user.click(screen.getByRole("button", { name: "Switch working directory" }));
|
||||
const option = await screen.findByRole("option", { name: "/srv/workspace/alpha" });
|
||||
@@ -237,7 +233,7 @@ describe("Workspace project picker", () => {
|
||||
const user = userEvent.setup();
|
||||
const onChange = vi.fn();
|
||||
const onBrowse = vi.fn((path: string) => Promise.resolve({ ...directory, path: completed, partial: path === draft, entries: path === draft ? [{ name: "alpha", path: completed }] : [] }));
|
||||
render(<WorkspaceProjectPicker isHero scope={scope} defaultScope={scope} controls={catalog.controls} onBrowseDirectories={onBrowse} onChange={onChange} />);
|
||||
render(<WorkspaceProjectPicker {...pickerActions()} isHero scope={scope} defaultScope={scope} controls={catalog.controls} onBrowseDirectories={onBrowse} onChange={onChange} />);
|
||||
await user.click(screen.getByRole("button", { name: "Switch working directory" }));
|
||||
const input = screen.getByRole("combobox");
|
||||
await user.clear(input);
|
||||
@@ -257,7 +253,7 @@ describe("Workspace project picker", () => {
|
||||
it("uses one list for partial paths and keyboard completion", async () => {
|
||||
const user = userEvent.setup();
|
||||
const onBrowse = vi.fn((path: string) => Promise.resolve({ ...directory, path: path === "/srv/al" ? "/srv" : path, parent: "/srv", partial: path === "/srv/al", entries: path === "/srv/al" ? [{ name: "alpha", path: "/srv/alpha" }, { name: "alpine", path: "/srv/alpine" }] : [] }));
|
||||
render(<WorkspaceProjectPicker isHero scope={scope} defaultScope={scope} controls={catalog.controls} onBrowseDirectories={onBrowse} onChange={vi.fn()} />);
|
||||
render(<WorkspaceProjectPicker {...pickerActions()} isHero scope={scope} defaultScope={scope} controls={catalog.controls} onBrowseDirectories={onBrowse} onChange={vi.fn()} />);
|
||||
await user.click(screen.getByRole("button", { name: "Switch working directory" }));
|
||||
const input = screen.getByRole("combobox");
|
||||
await user.clear(input);
|
||||
@@ -277,7 +273,7 @@ describe("Workspace project picker", () => {
|
||||
const user = userEvent.setup();
|
||||
let finish!: (value: WorkspaceDirectoriesPayload) => void;
|
||||
const onBrowse = vi.fn((path: string) => path === "/srv/al" ? new Promise<WorkspaceDirectoriesPayload>(resolve => { finish = resolve; }) : Promise.resolve({ ...directory, entries: [] }));
|
||||
render(<WorkspaceProjectPicker isHero scope={scope} defaultScope={scope} controls={catalog.controls} onBrowseDirectories={onBrowse} onChange={vi.fn()} />);
|
||||
render(<WorkspaceProjectPicker {...pickerActions()} isHero scope={scope} defaultScope={scope} controls={catalog.controls} onBrowseDirectories={onBrowse} onChange={vi.fn()} />);
|
||||
await user.click(screen.getByRole("button", { name: "Switch working directory" }));
|
||||
const input = screen.getByRole("combobox");
|
||||
await user.clear(input);
|
||||
@@ -295,7 +291,7 @@ describe("Workspace project picker", () => {
|
||||
const onBrowse = vi.fn<BrowseWorkspaceDirectories>((path: string) => path === "/srv/al"
|
||||
? new Promise<WorkspaceDirectoriesPayload>(resolve => { finish = resolve; })
|
||||
: Promise.resolve({ ...directory, path, entries: [] }));
|
||||
render(<WorkspaceProjectPicker isHero scope={scope} defaultScope={scope} controls={catalog.controls} onBrowseDirectories={onBrowse} onChange={vi.fn()} />);
|
||||
render(<WorkspaceProjectPicker {...pickerActions()} isHero scope={scope} defaultScope={scope} controls={catalog.controls} onBrowseDirectories={onBrowse} onChange={vi.fn()} />);
|
||||
await user.click(screen.getByRole("button", { name: "Switch working directory" }));
|
||||
const input = screen.getByRole("combobox");
|
||||
await user.clear(input);
|
||||
@@ -313,7 +309,7 @@ describe("Workspace project picker", () => {
|
||||
let finishOld!: (value: WorkspaceDirectoriesPayload) => void;
|
||||
const onBrowse = vi.fn((path: string) => path === "/srv/old/" ? new Promise<WorkspaceDirectoriesPayload>(resolve => { finishOld = resolve; }) : Promise.resolve({ ...directory, path, entries: [{ name: path === "/srv/new/" ? "new-child" : "initial-child", path: `${path.replace(/\/$/, "")}/child` }] }));
|
||||
const onChange = vi.fn();
|
||||
render(<WorkspaceProjectPicker isHero scope={scope} defaultScope={scope} controls={catalog.controls} onBrowseDirectories={onBrowse} onChange={onChange} />);
|
||||
render(<WorkspaceProjectPicker {...pickerActions()} isHero scope={scope} defaultScope={scope} controls={catalog.controls} onBrowseDirectories={onBrowse} onChange={onChange} />);
|
||||
await user.click(screen.getByRole("button", { name: "Switch working directory" }));
|
||||
await screen.findByRole("option", { name: "/srv/workspace/child" });
|
||||
const input = screen.getByRole("combobox");
|
||||
@@ -336,7 +332,7 @@ describe("Workspace project picker", () => {
|
||||
it("filters the current directory by name without a second browser view", async () => {
|
||||
const user = userEvent.setup();
|
||||
const onBrowse = vi.fn().mockResolvedValue(directory);
|
||||
render(<WorkspaceProjectPicker isHero scope={scope} defaultScope={scope} controls={catalog.controls} onBrowseDirectories={onBrowse} onChange={vi.fn()} />);
|
||||
render(<WorkspaceProjectPicker {...pickerActions()} isHero scope={scope} defaultScope={scope} controls={catalog.controls} onBrowseDirectories={onBrowse} onChange={vi.fn()} />);
|
||||
await user.click(screen.getByRole("button", { name: "Switch working directory" }));
|
||||
await screen.findByRole("option", { name: "/srv/workspace/alpha" });
|
||||
const input = screen.getByRole("combobox");
|
||||
@@ -357,7 +353,7 @@ describe("Workspace project picker", () => {
|
||||
if (showHidden) names.push(".hidden");
|
||||
return Promise.resolve({ ...directory, path, entries: names.map(name => ({ name, path: `${path}/${name}` })) });
|
||||
});
|
||||
render(<WorkspaceProjectPicker isHero scope={scope} defaultScope={scope} controls={catalog.controls} onBrowseDirectories={onBrowse} onChange={onChange} />);
|
||||
render(<WorkspaceProjectPicker {...pickerActions()} isHero scope={scope} defaultScope={scope} controls={catalog.controls} onBrowseDirectories={onBrowse} onChange={onChange} />);
|
||||
await user.click(screen.getByRole("button", { name: "Switch working directory" }));
|
||||
await user.click(await screen.findByRole("option", { name: "/srv/workspace/alpha" }));
|
||||
await user.click(await screen.findByRole("option", { name: "/srv/workspace/alpha/child" }));
|
||||
|
||||
Reference in new issue
Block a user