refactor(webui): remove obsolete native workspace picker paths

This commit is contained in:
chengyongru authored and chengyongru committed 2026-10-08 20:33:15 +08:00
1 parent 024d181013
commit 8a795b428e
32 files changed
+186 -593

No files matched your search

+1 -1
View File
@@ -294,7 +294,7 @@ or a result you must retain.
Use the workspace picker to browse folders on the connected nanobot host, enter 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 an absolute path, or return to recent and starred projects; favorites persist
across gateway restarts. Tab completes paths and Shift+wheel scrolls directory 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. Project paths refer to the gateway machine, not the browser's filesystem.
Selecting a project does not replace the configured agent workspace. The two 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, bus,
token_issue_secret="native-secret", token_issue_secret="native-secret",
runtime_surface="native", 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 assert response.status_code == 200
body = response.json() body = response.json()
assert body["runtime_surface"] == "native" 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["runtime_capabilities"]["can_restart_engine"] is True
assert body["token"].startswith("nbwt_") assert body["token"].startswith("nbwt_")
assert body["api_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( @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),
_REMOTE, (_LOCAL, {"Host": "nas.example", "X-Forwarded-For": "203.0.113.42"}, False),
{"Host": "nas.example", "X-Forwarded-For": "203.0.113.42"}, (_LOCAL, {"Host": "127.0.0.1:8765"}, True),
False,
False,
),
(
_LOCAL,
{"Host": "nas.example", "X-Forwarded-For": "203.0.113.42"},
False,
False,
),
(_LOCAL, {"Host": "127.0.0.1:8765"}, True, True),
], ],
) )
@pytest.mark.parametrize("native_picker_available", [True, False])
def test_workspace_payload_separates_remote_project_selection_from_full_access( def test_workspace_payload_separates_remote_project_selection_from_full_access(
bus: MagicMock, bus: MagicMock,
monkeypatch: pytest.MonkeyPatch,
native_picker_available: bool,
connection: _FakeConn, connection: _FakeConn,
headers: dict[str, str], headers: dict[str, str],
can_use_full_access: bool, can_use_full_access: bool,
can_pick_folder: bool,
) -> None: ) -> None:
monkeypatch.setattr(
"nanobot.webui.ws_http.native_folder_picker_available",
lambda: native_picker_available,
)
channel = _ch(bus) channel = _ch(bus)
token = channel.gateway.tokens.issue_api_token(300) token = channel.gateway.tokens.issue_api_token(300)
request = _FakeReq( request = _FakeReq(
@@ -3723,63 +3682,6 @@ def test_workspace_payload_separates_remote_project_selection_from_full_access(
controls = json.loads(response.body.decode())["controls"] controls = json.loads(response.body.decode())["controls"]
assert controls["can_change_project"] is True assert controls["can_change_project"] is True
assert controls["can_use_full_access"] is can_use_full_access 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: 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 from __future__ import annotations
@@ -9,7 +9,6 @@ import sys
from contextlib import suppress from contextlib import suppress
from dataclasses import dataclass from dataclasses import dataclass
from pathlib import Path from pathlib import Path
from typing import Literal
_PICKER_TIMEOUT_SECONDS = 300 _PICKER_TIMEOUT_SECONDS = 300
_COMMON_ENV_KEYS = ( _COMMON_ENV_KEYS = (
@@ -56,8 +55,8 @@ _WINDOWS_GUI_ENV_KEYS = (
) )
class NativeFolderPickerError(RuntimeError): class NativeFilePickerError(RuntimeError):
"""Raised when an available native folder picker cannot complete.""" """Raised when a native file picker cannot complete."""
@dataclass(frozen=True) @dataclass(frozen=True)
@@ -67,8 +66,8 @@ class _PickerCommand:
cancel_markers: tuple[str, ...] = () cancel_markers: tuple[str, ...] = ()
def _picker_command(kind: Literal["folder", "file"] = "folder") -> _PickerCommand | None: def _picker_command() -> _PickerCommand | None:
title = "Select Workspace Directory" if kind == "folder" else "Select SSH key or configuration file" title = "Select SSH key or configuration file"
if sys.platform == "darwin": if sys.platform == "darwin":
executable = shutil.which("osascript") executable = shutil.which("osascript")
if executable is None: if executable is None:
@@ -77,7 +76,7 @@ def _picker_command(kind: Literal["folder", "file"] = "folder") -> _PickerComman
argv=( argv=(
executable, executable,
"-e", "-e",
f'set selectedPath to choose {kind} with prompt "{title}"', f'set selectedPath to choose file with prompt "{title}"',
"-e", "-e",
"POSIX path of selectedPath", "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") executable = shutil.which("powershell.exe") or shutil.which("powershell")
if executable is None: if executable is None:
return None return None
dialog = ( script = (
"$dialog=New-Object System.Windows.Forms.FolderBrowserDialog;" "Add-Type -AssemblyName System.Windows.Forms;"
f"$dialog.Description='{title}';"
"$dialog.ShowNewFolderButton=$true;"
) if kind == "folder" else (
"$dialog=New-Object System.Windows.Forms.OpenFileDialog;" "$dialog=New-Object System.Windows.Forms.OpenFileDialog;"
f"$dialog.Title='{title}';" f"$dialog.Title='{title}';"
"$dialog.CheckFileExists=$true;$dialog.Multiselect=$false;" "$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){" "if($dialog.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK){"
"[Console]::OutputEncoding=[System.Text.UTF8Encoding]::new();" "[Console]::OutputEncoding=[System.Text.UTF8Encoding]::new();"
f"[Console]::Out.Write($dialog.{selected})}}" "[Console]::Out.Write($dialog.FileName)}"
) )
return _PickerCommand( return _PickerCommand(
argv=( argv=(
@@ -127,7 +118,6 @@ def _picker_command(kind: Literal["folder", "file"] = "folder") -> _PickerComman
argv=( argv=(
zenity, zenity,
"--file-selection", "--file-selection",
*(("--directory",) if kind == "folder" else ()),
f"--title={title}", f"--title={title}",
), ),
cancel_codes=frozenset({1}), cancel_codes=frozenset({1}),
@@ -135,17 +125,12 @@ def _picker_command(kind: Literal["folder", "file"] = "folder") -> _PickerComman
kdialog = shutil.which("kdialog") kdialog = shutil.which("kdialog")
if kdialog is not None: if kdialog is not None:
return _PickerCommand( return _PickerCommand(
argv=(kdialog, "--getexistingdirectory" if kind == "folder" else "--getopenfilename", str(Path.home())), argv=(kdialog, "--getopenfilename", str(Path.home())),
cancel_codes=frozenset({1}), cancel_codes=frozenset({1}),
) )
return None 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]: def _picker_environment() -> dict[str, str]:
"""Pass only host UI/runtime variables, never provider or gateway secrets.""" """Pass only host UI/runtime variables, never provider or gateway secrets."""
keys: list[str] = list(_COMMON_ENV_KEYS) keys: list[str] = list(_COMMON_ENV_KEYS)
@@ -175,19 +160,11 @@ async def _stop_process(process: asyncio.subprocess.Process) -> None:
await process.wait() 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: async def pick_native_file() -> str | None:
"""Choose an existing local file without opening, uploading or copying it.""" """Choose an existing local file without opening, uploading or copying it."""
return await _pick_native_path(_picker_command("file"), "file") command = _picker_command()
async def _pick_native_path(command: _PickerCommand | None, kind: str) -> str | None:
if command is None: 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: try:
process = await asyncio.create_subprocess_exec( 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, stderr=asyncio.subprocess.PIPE,
) )
except OSError as exc: 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: try:
stdout, stderr = await asyncio.wait_for( stdout, stderr = await asyncio.wait_for(
process.communicate(), process.communicate(),
@@ -208,7 +185,7 @@ async def _pick_native_path(command: _PickerCommand | None, kind: str) -> str |
raise raise
except TimeoutError as exc: except TimeoutError as exc:
await _stop_process(process) 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() error_text = stderr.decode("utf-8", errors="replace").strip()
normalized_error = error_text.lower() 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) or any(marker in normalized_error for marker in command.cancel_markers)
): ):
return None return None
raise NativeFolderPickerError("native folder picker failed") raise NativeFilePickerError("native file picker failed")
selected = stdout.decode("utf-8", errors="replace").strip() selected = stdout.decode("utf-8", errors="replace").strip()
if not selected: if not selected:
return None return None
path = Path(selected).expanduser() path = Path(selected).expanduser()
if not path.is_absolute() or not (path.is_dir() if kind == "directory" else path.is_file()): if not path.is_absolute() or not path.is_file():
raise NativeFolderPickerError(f"native path picker returned an invalid {kind}") raise NativeFilePickerError("native file picker returned an invalid file")
return str(path) return str(path)
+2 -2
View File
@@ -212,7 +212,7 @@ class RemoteInstances:
async def action(self, action: str, payload: dict[str, Any]) -> dict[str, Any]: async def action(self, action: str, payload: dict[str, Any]) -> dict[str, Any]:
if action == "pick_file": 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(): if self._closed or self._picker_lock.locked():
raise RemoteError("file_picker_unavailable") raise RemoteError("file_picker_unavailable")
@@ -221,7 +221,7 @@ class RemoteInstances:
async with self._picker_lock: async with self._picker_lock:
try: try:
return {"path": await pick_native_file()} return {"path": await pick_native_file()}
except NativeFolderPickerError: except NativeFilePickerError:
raise RemoteError("file_picker_unavailable") from None raise RemoteError("file_picker_unavailable") from None
if action == "discover": if action == "discover":
from nanobot.webui.ssh_config import discover_hosts from nanobot.webui.ssh_config import discover_hosts
-2
View File
@@ -43,14 +43,12 @@ _reasoning_effort_values_for = models.reasoning_effort_values_for
_RUNTIME_CAPABILITIES = { _RUNTIME_CAPABILITIES = {
"can_restart_engine": False, "can_restart_engine": False,
"can_pick_folder": False,
"can_open_logs": False, "can_open_logs": False,
"can_export_diagnostics": False, "can_export_diagnostics": False,
} }
_NATIVE_RUNTIME_CAPABILITIES = { _NATIVE_RUNTIME_CAPABILITIES = {
**_RUNTIME_CAPABILITIES, **_RUNTIME_CAPABILITIES,
"can_restart_engine": True, "can_restart_engine": True,
"can_pick_folder": True,
"can_open_logs": True, "can_open_logs": True,
"can_export_diagnostics": True, "can_export_diagnostics": True,
} }
-7
View File
@@ -176,7 +176,6 @@ def workspaces_payload(
default_restrict_to_workspace: bool, default_restrict_to_workspace: bool,
can_change_project: bool, can_change_project: bool,
can_use_full_access: bool, can_use_full_access: bool,
folder_picker_available: bool = False,
) -> dict[str, Any]: ) -> dict[str, Any]:
state = read_webui_workspace_state() state = read_webui_workspace_state()
default_access_mode = state["default_access_mode"] default_access_mode = state["default_access_mode"]
@@ -205,10 +204,6 @@ def workspaces_payload(
"controls": { "controls": {
"can_change_project": can_change_project, "can_change_project": can_change_project,
"can_use_full_access": can_use_full_access, "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_change_project: bool,
can_use_full_access: bool, can_use_full_access: bool,
folder_picker_available: bool = False,
) -> dict[str, Any]: ) -> dict[str, Any]:
return workspaces_payload( return workspaces_payload(
default_workspace=self._default_workspace, default_workspace=self._default_workspace,
default_restrict_to_workspace=self._default_restrict_to_workspace, default_restrict_to_workspace=self._default_restrict_to_workspace,
can_change_project=can_change_project, can_change_project=can_change_project,
can_use_full_access=can_use_full_access, can_use_full_access=can_use_full_access,
folder_picker_available=folder_picker_available,
) )
def resolve_project(self, path: object) -> dict[str, str]: def resolve_project(self, path: object) -> dict[str, str]:
-43
View File
@@ -95,11 +95,6 @@ from nanobot.webui.http_utils import (
) )
from nanobot.webui.ingress_policy import WebUIIngressPolicy from nanobot.webui.ingress_policy import WebUIIngressPolicy
from nanobot.webui.media_gateway import WebUIMediaGateway 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 ( from nanobot.webui.session_automations import (
all_automations_payload, all_automations_payload,
serialize_automation_jobs, serialize_automation_jobs,
@@ -199,7 +194,6 @@ _WEBUI_MUTATION_PATHS = {
"sidebar.update": "/api/webui/sidebar-state/update", "sidebar.update": "/api/webui/sidebar-state/update",
"workspace.favorite": "/api/workspaces/favorite", "workspace.favorite": "/api/workspaces/favorite",
"workspace.resolve_project": "/api/workspaces/resolve-project", "workspace.resolve_project": "/api/workspaces/resolve-project",
"workspace.pick_folder": "/api/workspaces/pick-folder",
"recovery.continue": "/api/webui/recovery/continue", "recovery.continue": "/api/webui/recovery/continue",
"recovery.dismiss": "/api/webui/recovery/dismiss", "recovery.dismiss": "/api/webui/recovery/dismiss",
"subagent.cancel": "/api/webui/subagents/cancel", "subagent.cancel": "/api/webui/subagents/cancel",
@@ -414,7 +408,6 @@ class GatewayHTTPHandler:
self.subagent_manager = subagent_manager self.subagent_manager = subagent_manager
self.discard_session = discard_session self.discard_session = discard_session
self._skill_install_lock = asyncio.Lock() self._skill_install_lock = asyncio.Lock()
self._folder_picker_lock = asyncio.Lock()
self.cron_service = cron_service self.cron_service = cron_service
self.local_trigger_store = local_trigger_store self.local_trigger_store = local_trigger_store
self.cron_pending_job_ids = cron_pending_job_ids self.cron_pending_job_ids = cron_pending_job_ids
@@ -473,17 +466,6 @@ class GatewayHTTPHandler:
return False return False
return _is_local_browser_request(connection, headers) 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 --------------------------------------------------- # -- Token management ---------------------------------------------------
def check_api_token(self, request: WsRequest) -> bool: def check_api_token(self, request: WsRequest) -> bool:
@@ -565,7 +547,6 @@ class GatewayHTTPHandler:
"/api/webui/star-prompt/claim", "/api/webui/star-prompt/claim",
"/api/webui/star-prompt/dismiss", "/api/webui/star-prompt/dismiss",
"/api/webui/sidebar-state/update", "/api/webui/sidebar-state/update",
"/api/workspaces/pick-folder",
"/api/workspaces/resolve-project", "/api/workspaces/resolve-project",
"/api/workspaces/favorite", "/api/workspaces/favorite",
"/api/webui/subagents/cancel", "/api/webui/subagents/cancel",
@@ -1647,8 +1628,6 @@ class GatewayHTTPHandler:
return await self._handle_sessions_list(request) return await self._handle_sessions_list(request)
if got == "/api/commands": if got == "/api/commands":
return self._handle_commands(request) 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": if got == "/api/workspaces/favorite":
return self._handle_workspace_favorite(connection, request) return self._handle_workspace_favorite(connection, request)
if got == "/api/workspaces/resolve-project": if got == "/api/workspaces/resolve-project":
@@ -1704,10 +1683,6 @@ class GatewayHTTPHandler:
connection, connection,
request.headers, 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_error(exc.status, exc.message)
return _http_json_response(dict(payload)) 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: def _handle_webui_skills(self, request: WsRequest) -> Response:
if not self.check_api_token(request): if not self.check_api_token(request):
return _http_error(401, "Unauthorized") return _http_error(401, "Unauthorized")
@@ -5,7 +5,7 @@ from pathlib import Path
import pytest 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: 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 @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 = 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,
)
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()
command = _picker_command(tmp_path, f"print({str(selected)!r}, end='')") command = _picker_command(tmp_path, f"print({str(selected)!r}, end='')")
monkeypatch.setattr(picker, "_picker_command", lambda: command) monkeypatch.setattr(picker, "_picker_command", lambda: command)
monkeypatch.setenv("HOME", str(tmp_path)) 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) 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 captured_env["HOME"] == str(tmp_path)
assert "OPENAI_API_KEY" not in captured_env 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 @pytest.mark.asyncio
async def test_pick_native_folder_maps_dialog_cancel_to_none(tmp_path, monkeypatch) -> None: async def test_pick_native_file_reports_unavailable(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:
monkeypatch.setattr(picker, "_picker_command", lambda: None) monkeypatch.setattr(picker, "_picker_command", lambda: None)
assert picker.native_folder_picker_available() is False with pytest.raises(picker.NativeFilePickerError, match="unavailable"):
with pytest.raises(picker.NativeFolderPickerError, match="unavailable"): await picker.pick_native_file()
await picker.pick_native_folder()
@pytest.mark.asyncio @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')") command = _picker_command(tmp_path, "raise AssertionError('not started')")
monkeypatch.setattr(picker, "_picker_command", lambda: command) 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) monkeypatch.setattr(picker.asyncio, "create_subprocess_exec", fail_spawn)
with pytest.raises(picker.NativeFolderPickerError, match="failed to start"): with pytest.raises(picker.NativeFilePickerError, match="failed to start"):
await picker.pick_native_folder() await picker.pick_native_file()
@pytest.mark.parametrize("result", ["file", "directory", "cancel"]) @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") selected.write_text("must-not-be-read-or-returned")
output = str(selected if result == "file" else tmp_path) 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})") 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": if result == "directory":
with pytest.raises(picker.NativeFolderPickerError, match="invalid file"): with pytest.raises(picker.NativeFilePickerError, match="invalid file"):
await picker.pick_native_file() await picker.pick_native_file()
else: else:
assert await picker.pick_native_file() == (str(selected) if result == "file" else None) 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.sys, "platform", platform)
monkeypatch.setattr(picker.shutil, "which", lambda executable: executable) monkeypatch.setattr(picker.shutil, "which", lambda executable: executable)
monkeypatch.setenv("DISPLAY", ":test") monkeypatch.setenv("DISPLAY", ":test")
command = picker._picker_command("file") command = picker._picker_command()
assert command is not None assert command is not None
assert marker in " ".join(command.argv) assert marker in " ".join(command.argv)
assert "--directory" not in 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.setattr(picker.sys, "platform", "linux")
monkeypatch.delenv("DISPLAY", raising=False) monkeypatch.delenv("DISPLAY", raising=False)
monkeypatch.delenv("WAYLAND_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): 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 = MagicMock(returncode=None)
process.communicate = AsyncMock(side_effect=asyncio.CancelledError) process.communicate = AsyncMock(side_effect=asyncio.CancelledError)
process.wait = AsyncMock(return_value=0) 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)) monkeypatch.setattr(asyncio, "create_subprocess_exec", AsyncMock(return_value=process))
with pytest.raises(asyncio.CancelledError): with pytest.raises(asyncio.CancelledError):
await picker.pick_native_file() await picker.pick_native_file()
+1 -19
View 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_scope"]["access_mode"] == "full"
assert payload["default_access_mode"] == "default" assert payload["default_access_mode"] == "default"
assert payload["controls"]["can_change_project"] is True 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( 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["default_scope"]["project_path"] == str(default.resolve())
assert payload["controls"]["can_change_project"] is True assert payload["controls"]["can_change_project"] is True
assert payload["controls"]["can_use_full_access"] is False 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( 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 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: 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") monkeypatch.setattr("nanobot.webui.workspaces.get_webui_dir", lambda: tmp_path / "webui")
default = tmp_path / "default" 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["recent_projects"] == [{"name": "project", "path": str(project)}]
assert payload["default_scope"]["project_path"] == str(default) assert payload["default_scope"]["project_path"] == str(default)
assert payload["default_scope"]["access_mode"] == "restricted" 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: def test_favorites_keep_pin_order_across_restart_and_can_remove_deleted_folder(tmp_path, monkeypatch) -> None:
+9 -9
View File
@@ -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]) @pytest.mark.parametrize("path", ["/local/ssh-config", None])
async def test_file_picker_returns_path_without_saving_profile(manager, monkeypatch, path): 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) 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 await manager.action("pick_file", {}) == {"path": path}
assert not manager.path.exists() assert not manager.path.exists()
choose.assert_awaited_once_with() choose.assert_awaited_once_with()
async def test_file_picker_failure_does_not_expose_native_error(manager, monkeypatch): 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( monkeypatch.setattr(native_file_picker, "pick_native_file", AsyncMock(
side_effect=native_folder_picker.NativeFolderPickerError("private diagnostic"), side_effect=native_file_picker.NativeFilePickerError("private diagnostic"),
)) ))
with pytest.raises(RemoteError, match="^file_picker_unavailable$"): with pytest.raises(RemoteError, match="^file_picker_unavailable$"):
await manager.action("pick_file", {}) await manager.action("pick_file", {})
async def test_file_picker_does_not_open_multiple_system_dialogs(manager, monkeypatch): 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() 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: async with manager._picker_lock:
with pytest.raises(RemoteError, match="file_picker_unavailable"): with pytest.raises(RemoteError, match="file_picker_unavailable"):
await manager.action("pick_file", {}) 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"), ("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): 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() 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( connection = SimpleNamespace(remote_address=(peer, 10000), request=SimpleNamespace(
headers=Headers({"Host": host, "Origin": origin}), headers=Headers({"Host": host, "Origin": origin}),
)) ))
@@ -1064,6 +1064,10 @@ export function ThreadComposer({
isHero isHero
&& !!workspaceDefaultScope && !!workspaceDefaultScope
&& !!onWorkspaceScopeChange && !!onWorkspaceScopeChange
&& !!onLoadWorkspaceProjects
&& !!onBrowseWorkspaceDirectories
&& !!onResolveWorkspaceProject
&& !!onFavoriteWorkspaceProject
&& workspaceControls?.can_change_project !== false; && workspaceControls?.can_change_project !== false;
const showProjectPicker = projectPickerAvailable && !workspaceControlsHidden; 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: ProjectDirectory[]; selectedPath: string | null; hidden: boolean };
type PickerColumn = { path: string; options: PickerOption[]; selectedPath: string | null; hidden: boolean };
function WorkspacePickerTooltip({ label, children }: { label: string; children: ReactElement }) { function WorkspacePickerTooltip({ label, children }: { label: string; children: ReactElement }) {
return ( return (
@@ -46,9 +45,9 @@ const DIRECTORY_ROW_HEIGHT = 44;
const DIRECTORY_OVERSCAN = 4; const DIRECTORY_OVERSCAN = 4;
function WorkspaceDirectoryColumn({ options, activeIndex, renderOption, children, ...props }: { function WorkspaceDirectoryColumn({ options, activeIndex, renderOption, children, ...props }: {
options: PickerOption[]; options: ProjectDirectory[];
activeIndex: number | null; activeIndex: number | null;
renderOption: (option: PickerOption, index: number) => ReactElement; renderOption: (option: ProjectDirectory, index: number) => ReactElement;
} & HTMLAttributes<HTMLDivElement>) { } & HTMLAttributes<HTMLDivElement>) {
const viewportRef = useRef<HTMLDivElement>(null); const viewportRef = useRef<HTMLDivElement>(null);
const [firstRow, setFirstRow] = useState(0); 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 }}> <div role="presentation" className="relative" style={{ height: options.length * DIRECTORY_ROW_HEIGHT }}>
{options.slice(start, end).map((option, offset) => { {options.slice(start, end).map((option, offset) => {
const index = start + 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)} {renderOption(option, index)}
</div>; </div>;
})} })}
@@ -142,10 +141,10 @@ export function WorkspaceProjectPicker({ isHero, disabled, scope, defaultScope,
defaultScope: WorkspaceScopePayload | null; defaultScope: WorkspaceScopePayload | null;
controls: WorkspacesPayload["controls"] | null; controls: WorkspacesPayload["controls"] | null;
error?: string | null; error?: string | null;
onResolveProject?: (path: string) => Promise<ProjectDirectory>; onResolveProject: (path: string) => Promise<ProjectDirectory>;
onLoadProjects?: () => Promise<WorkspacesPayload>; onLoadProjects: () => Promise<WorkspacesPayload>;
onFavoriteProject?: (path: string, pinned: boolean) => Promise<ProjectDirectory[]>; onFavoriteProject: (path: string, pinned: boolean) => Promise<ProjectDirectory[]>;
onBrowseDirectories?: BrowseWorkspaceDirectories; onBrowseDirectories: BrowseWorkspaceDirectories;
onChange?: (scope: WorkspaceScopePayload) => void; onChange?: (scope: WorkspaceScopePayload) => void;
}) { }) {
const { t } = useTranslation(); const { t } = useTranslation();
@@ -183,8 +182,7 @@ export function WorkspaceProjectPicker({ isHero, disabled, scope, defaultScope,
const displayedScope = scope ?? defaultScope; const displayedScope = scope ?? defaultScope;
const projectLabel = displayedScope ? displayedScope.project_name || projectNameFromPath(displayedScope.project_path) : ""; const projectLabel = displayedScope ? displayedScope.project_name || projectNameFromPath(displayedScope.project_path) : "";
const visible = isHero && !!defaultScope && !!onChange && controls?.can_change_project !== false; const visible = isHero && !!defaultScope && !!onChange && controls?.can_change_project !== false;
const canBrowse = !!controls?.can_browse_directories && !!onBrowseDirectories; const directoryCache = useMemo(() => createWorkspaceDirectoryCache(onBrowseDirectories), [onBrowseDirectories]);
const directoryCache = useMemo(() => onBrowseDirectories ? createWorkspaceDirectoryCache(onBrowseDirectories) : null, [onBrowseDirectories]);
const absoluteDraft = isAbsoluteWorkspacePath(pathDraft); const absoluteDraft = isAbsoluteWorkspacePath(pathDraft);
const requestedPath = absoluteDraft ? pathDraft.trim() : basePath; const requestedPath = absoluteDraft ? pathDraft.trim() : basePath;
const folderQuery = absoluteDraft ? "" : pathDraft.trim(); const folderQuery = absoluteDraft ? "" : pathDraft.trim();
@@ -197,15 +195,15 @@ export function WorkspaceProjectPicker({ isHero, disabled, scope, defaultScope,
setActiveColumn(0); setActiveColumn(0);
setHighlightActive(false); setHighlightActive(false);
const initialPath = scope?.project_path ?? defaultScope?.project_path ?? ""; const initialPath = scope?.project_path ?? defaultScope?.project_path ?? "";
setPathDraft(canBrowse ? workspaceDirectoryPrefix(initialPath) : currentProjectScope?.project_path ?? ""); setPathDraft(workspaceDirectoryPrefix(initialPath));
setBasePath(initialPath); setBasePath(initialPath);
setDirectory(null); setDirectory(null);
setActiveIndex(0); setActiveIndex(0);
setPathError(null); setPathError(null);
}, [scope?.project_path, defaultScope?.project_path, open, canBrowse]); }, [scope?.project_path, defaultScope?.project_path, open]);
useEffect(() => { useEffect(() => {
if (!open || !onLoadProjects) return; if (!open) return;
let active = true; let active = true;
setCatalog(null); setCatalog(null);
onLoadProjects().then(payload => { if (active) setCatalog(payload); }).catch((err: Error) => { if (active) setPathError(err.message); }); 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]); }, [onLoadProjects, open]);
useEffect(() => { useEffect(() => {
if (!open || !canBrowse || !directoryCache) return; if (!open) return;
let active = true; let active = true;
const apply = (result: WorkspaceDirectoriesPayload) => { const apply = (result: WorkspaceDirectoriesPayload) => {
if (!active) return; if (!active) return;
@@ -232,7 +230,7 @@ export function WorkspaceProjectPicker({ isHero, disabled, scope, defaultScope,
}); });
}, typing ? 150 : 0); }, typing ? 150 : 0);
return () => { active = false; window.clearTimeout(timer); }; 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(() => { if (disabled) setOpen(false); }, [disabled]);
useEffect(() => { 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)); const ancestorPaths = JSON.stringify(previousColumns.filter(column => column.hidden !== showHidden).map(column => column.path));
useEffect(() => { useEffect(() => {
if (!open || !canBrowse || !directoryCache) return; if (!open) return;
const paths: string[] = JSON.parse(ancestorPaths); const paths: string[] = JSON.parse(ancestorPaths);
if (!paths.length) return; if (!paths.length) return;
let active = true; let active = true;
@@ -257,11 +255,11 @@ export function WorkspaceProjectPicker({ isHero, disabled, scope, defaultScope,
setPreviousColumns(columns => columns.map(column => { setPreviousColumns(columns => columns.map(column => {
const result = results.find(result => sameWorkspacePath(column.path, result.path)); const result = results.find(result => sameWorkspacePath(column.path, result.path));
if (!result) return column; 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); }); }).catch((err: Error) => { if (active) setPathError(err.message); });
return () => { active = false; }; return () => { active = false; };
}, [open, canBrowse, directoryCache, ancestorPaths, showHidden]); }, [open, directoryCache, ancestorPaths, showHidden]);
useLayoutEffect(() => { useLayoutEffect(() => {
const viewport = columnsElement; const viewport = columnsElement;
@@ -309,9 +307,9 @@ export function WorkspaceProjectPicker({ isHero, disabled, scope, defaultScope,
completionRequest.current += 1; completionRequest.current += 1;
setPathDraft(value); setPathDraft(value);
const absolute = isAbsoluteWorkspacePath(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); setDirectory(cached ?? null);
setLoading(canBrowse && !cached); setLoading(!cached);
setDirectoryError(null); setDirectoryError(null);
setPathError(null); setPathError(null);
setActiveIndex(0); setActiveIndex(0);
@@ -328,20 +326,18 @@ export function WorkspaceProjectPicker({ isHero, disabled, scope, defaultScope,
inputRef.current?.focus(); inputRef.current?.focus();
} }
const applyProjectPath = useCallback((path: string, name?: string) => { const applyProjectPath = useCallback((path: string, name: string) => {
const base = scope ?? defaultScope; const base = scope ?? defaultScope;
const trimmed = path.trim(); const trimmed = path.trim();
if (!base || !onChange) return; 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; 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); setPathError(null);
setOpen(false); 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; const session = pickerSession.current;
if (!controls?.can_resolve_project || !onResolveProject) { applyProjectPath(path, name); return; }
setPickingFolder(true); setPathError(null); setPickingFolder(true); setPathError(null);
try { try {
const project = await onResolveProject(path); const project = await onResolveProject(path);
@@ -349,10 +345,10 @@ export function WorkspaceProjectPicker({ isHero, disabled, scope, defaultScope,
} catch (err) { } catch (err) {
if (session === pickerSession.current) setPathError((err as Error).message); if (session === pickerSession.current) setPathError((err as Error).message);
} finally { setPickingFolder(false); } } finally { setPickingFolder(false); }
}, [applyProjectPath, controls?.can_resolve_project, onResolveProject]); }, [applyProjectPath, onResolveProject]);
const favorites = catalog?.favorite_projects ?? []; 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)); const isFavorite = (path: string) => favorites.some(item => sameWorkspacePath(item.path, path));
function favoriteButton(path: string) { function favoriteButton(path: string) {
return canFavorite ? <WorkspaceFavoriteButton path={path} pinned={isFavorite(path)} busy={favoriteBusy || pickingFolder} 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) => { const toggleFavorite = async (path: string) => {
if (!onFavoriteProject || favoriteBusy) return; if (favoriteBusy) return;
const session = pickerSession.current; const session = pickerSession.current;
setFavoriteBusy(true); setPathError(null); setFavoriteBusy(true); setPathError(null);
try { try {
@@ -373,15 +369,11 @@ export function WorkspaceProjectPicker({ isHero, disabled, scope, defaultScope,
const recentProjects = [ const recentProjects = [
...(catalog?.recent_projects ?? []), ...(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 }] : []), ...(currentProjectScope ? [{ name: projectLabel, path: currentProjectScope.project_path }] : []),
].filter((project, index, all) => all.findIndex(item => sameWorkspacePath(item.path, project.path)) === index && !isFavorite(project.path)); ].filter((project, index, all) => all.findIndex(item => sameWorkspacePath(item.path, project.path)) === index && !isFavorite(project.path));
const options = useMemo<PickerOption[]>(() => { const options = useMemo(() => directory && !loading ? directory.entries : [], [directory, loading]);
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]);
function openShortcut(project: ProjectDirectory) { function openShortcut(project: ProjectDirectory) {
if (!canBrowse) { void chooseProject(project.path, project.name); return; }
setBasePath(project.path); setBasePath(project.path);
changeDraft(workspaceDirectoryPrefix(project.path)); changeDraft(workspaceDirectoryPrefix(project.path));
setRevision(value => value + 1); 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 columns: PickerColumn[] = [...previousColumns, { path: directory?.path ?? requestedPath, options, selectedPath: null, hidden: showHidden }];
const activeOptions = columns[activeColumn]?.options ?? options; const activeOptions = columns[activeColumn]?.options ?? options;
const activeOption = Math.min(activeIndex, Math.max(activeOptions.length - 1, 0)); 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; const displayedError = pathError ?? error ?? directoryError;
async function completePath() { async function completePath() {
const option = activeOptions[activeOption]; const option = activeOptions[activeOption];
if (option && option.kind !== "manual") { navigate(option.path); return; } if (option) { navigate(option.path); return; }
if (!directoryCache || !canBrowse) return;
const request = workspacePathCompletionQuery(pathDraft) ?? { path: basePath, query: pathDraft.trim() }; const request = workspacePathCompletionQuery(pathDraft) ?? { path: basePath, query: pathDraft.trim() };
const id = ++completionRequest.current; const id = ++completionRequest.current;
const session = pickerSession.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); 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 (pickingFolder) return;
if (canBrowse && option.kind !== "manual") navigate(option.path, columnIndex); navigate(option.path, columnIndex);
else void chooseProject(option.path, option.kind === "manual" ? undefined : option.name);
} }
if (!visible || !defaultScope || !onChange) return null; 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> <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"> <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> <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.nativeEvent.isComposing) return;
if ((event.key === "ArrowDown" || event.key === "ArrowUp") && !event.altKey && activeOptions.length) { if ((event.key === "ArrowDown" || event.key === "ArrowUp") && !event.altKey && activeOptions.length) {
event.preventDefault(); event.preventDefault();
@@ -447,7 +437,7 @@ export function WorkspaceProjectPicker({ isHero, disabled, scope, defaultScope,
setHighlightActive(true); setHighlightActive(true);
setActiveColumn(activeColumn - 1); setActiveColumn(activeColumn - 1);
setActiveIndex(Math.max(0, parent.options.findIndex(option => sameWorkspacePath(option.path, parent.selectedPath)))); 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(); event.preventDefault(); void completePath();
} else if (event.key === "Enter") { } else if (event.key === "Enter") {
event.preventDefault(); 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", 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", 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")}> 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" />} {sameWorkspacePath(option.path, scope?.project_path ?? defaultScope.project_path) && <Check className="h-4 w-4 shrink-0 text-muted-foreground" />}
</button> </button>
{favoriteButton(option.path)} {favoriteButton(option.path)}
@@ -497,9 +487,9 @@ export function WorkspaceProjectPicker({ isHero, disabled, scope, defaultScope,
</WorkspaceDirectoryColumn>)} </WorkspaceDirectoryColumn>)}
</div> </div>
</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> <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> </DialogContent>
</Dialog> </Dialog>
</TooltipProvider> </TooltipProvider>
-5
View File
@@ -2482,11 +2482,6 @@
} }
}, },
"workspace": { "workspace": {
"dialog": {
"defaultProject": "Default workspace",
"manual": "Paste path",
"absolutePathRequired": "Enter an absolute folder path on this machine."
},
"picker": { "picker": {
"favorites": "Favorites", "favorites": "Favorites",
"recent": "Recent projects", "recent": "Recent projects",
-5
View File
@@ -2283,11 +2283,6 @@
} }
}, },
"workspace": { "workspace": {
"dialog": {
"defaultProject": "Espacio de trabajo predeterminado",
"manual": "Pegar ruta",
"absolutePathRequired": "Introduce una ruta absoluta de carpeta en esta máquina."
},
"picker": { "picker": {
"favorites": "Favoritos", "favorites": "Favoritos",
"recent": "Proyectos recientes", "recent": "Proyectos recientes",
-5
View File
@@ -2282,11 +2282,6 @@
} }
}, },
"workspace": { "workspace": {
"dialog": {
"defaultProject": "Espace de travail par défaut",
"manual": "Coller un chemin",
"absolutePathRequired": "Saisissez un chemin absolu de dossier sur cette machine."
},
"picker": { "picker": {
"favorites": "Favoris", "favorites": "Favoris",
"recent": "Projets récents", "recent": "Projets récents",
-5
View File
@@ -2282,11 +2282,6 @@
} }
}, },
"workspace": { "workspace": {
"dialog": {
"defaultProject": "Ruang kerja bawaan",
"manual": "Tempel path",
"absolutePathRequired": "Masukkan path folder absolut di mesin ini."
},
"picker": { "picker": {
"favorites": "Favorit", "favorites": "Favorit",
"recent": "Proyek terbaru", "recent": "Proyek terbaru",
-5
View File
@@ -2282,11 +2282,6 @@
} }
}, },
"workspace": { "workspace": {
"dialog": {
"defaultProject": "既定のワークスペース",
"manual": "パスを貼り付け",
"absolutePathRequired": "このマシン上の絶対フォルダーパスを入力してください。"
},
"picker": { "picker": {
"favorites": "お気に入り", "favorites": "お気に入り",
"recent": "最近のプロジェクト", "recent": "最近のプロジェクト",
-5
View File
@@ -2282,11 +2282,6 @@
} }
}, },
"workspace": { "workspace": {
"dialog": {
"defaultProject": "기본 작업공간",
"manual": "경로 붙여넣기",
"absolutePathRequired": "이 머신의 절대 폴더 경로를 입력하세요."
},
"picker": { "picker": {
"favorites": "즐겨찾기", "favorites": "즐겨찾기",
"recent": "최근 프로젝트", "recent": "최근 프로젝트",
-5
View File
@@ -2296,11 +2296,6 @@
} }
}, },
"workspace": { "workspace": {
"dialog": {
"defaultProject": "Espaço de trabalho padrão",
"manual": "Colar caminho",
"absolutePathRequired": "Informe um caminho absoluto de pasta nesta máquina."
},
"picker": { "picker": {
"favorites": "Favoritos", "favorites": "Favoritos",
"recent": "Projetos recentes", "recent": "Projetos recentes",
-5
View File
@@ -2282,11 +2282,6 @@
} }
}, },
"workspace": { "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": { "picker": {
"favorites": "Yêu thích", "favorites": "Yêu thích",
"recent": "Dự án gần đây", "recent": "Dự án gần đây",
-5
View File
@@ -2482,11 +2482,6 @@
} }
}, },
"workspace": { "workspace": {
"dialog": {
"defaultProject": "默认工作区",
"manual": "粘贴路径",
"absolutePathRequired": "请输入这台机器上的绝对文件夹路径。"
},
"picker": { "picker": {
"favorites": "收藏", "favorites": "收藏",
"recent": "最近项目", "recent": "最近项目",
-5
View File
@@ -2282,11 +2282,6 @@
} }
}, },
"workspace": { "workspace": {
"dialog": {
"defaultProject": "預設工作區",
"manual": "貼上路徑",
"absolutePathRequired": "請輸入這台機器上的絕對資料夾路徑。"
},
"picker": { "picker": {
"favorites": "收藏", "favorites": "收藏",
"recent": "最近專案", "recent": "最近專案",
+1 -83
View File
@@ -53,16 +53,6 @@ const HOST_WS_CONNECTING = 0;
const HOST_WS_OPEN = 1; const HOST_WS_OPEN = 1;
const HOST_WS_CLOSING = 2; const HOST_WS_CLOSING = 2;
const HOST_WS_CLOSED = 3; 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 { declare global {
interface Window { interface Window {
@@ -75,20 +65,6 @@ function getHostApi(): NanobotHostApi | null {
return window.nanobotHost ?? 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 { export function toRuntimeSurface(surface: string | null | undefined): RuntimeSurface {
return surface === "native" ? "native" : "browser"; return surface === "native" ? "native" : "browser";
} }
@@ -101,7 +77,6 @@ export function createRuntimeHost(
const mergedCapabilities = { const mergedCapabilities = {
can_export_diagnostics: false, can_export_diagnostics: false,
can_open_logs: false, can_open_logs: false,
can_pick_folder: false,
can_restart_engine: false, can_restart_engine: false,
...(capabilities ?? {}), ...(capabilities ?? {}),
}; };
@@ -126,7 +101,7 @@ export function getRuntimeHost(
} }
export function isNativeRuntime(surface?: string | null): boolean { 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 { 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 { class HostWebSocket {
binaryType: BinaryType = "blob"; binaryType: BinaryType = "blob";
onclose: ((this: WebSocket, ev: CloseEvent) => unknown) | null = null; onclose: ((this: WebSocket, ev: CloseEvent) => unknown) | null = null;
-5
View File
@@ -498,10 +498,6 @@ export interface WorkspacesPayload {
controls: { controls: {
can_change_project: boolean; can_change_project: boolean;
can_use_full_access: 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 { export interface RuntimeCapabilities {
can_restart_engine: boolean; can_restart_engine: boolean;
can_pick_folder: boolean;
can_open_logs: boolean; can_open_logs: boolean;
can_export_diagnostics: boolean; can_export_diagnostics: boolean;
} }
-2
View File
@@ -3,7 +3,6 @@ import ReactDOM from "react-dom/client";
import App from "./App"; import App from "./App";
import "./globals.css"; import "./globals.css";
import { initializeI18n } from "./i18n"; import { initializeI18n } from "./i18n";
import { initializeLoopbackRuntimeHost } from "./lib/runtime";
import { initializePairReturn } from "./lib/remote-pair-return"; import { initializePairReturn } from "./lib/remote-pair-return";
// `crypto.randomUUID` is only defined in secure contexts (HTTPS or localhost). // `crypto.randomUUID` is only defined in secure contexts (HTTPS or localhost).
@@ -27,7 +26,6 @@ if (!root) throw new Error("root element missing");
initializePairReturn(); initializePairReturn();
window.addEventListener("hashchange", initializePairReturn); window.addEventListener("hashchange", initializePairReturn);
initializeLoopbackRuntimeHost();
async function renderWebui(container: HTMLElement) { async function renderWebui(container: HTMLElement) {
await initializeI18n(); await initializeI18n();
+19 -7
View File
@@ -1141,13 +1141,20 @@ describe("App layout", () => {
it("preserves the first message when the gateway rejects a project", async () => { it("preserves the first message when the gateway rejects a project", async () => {
const consoleError = vi.spyOn(console, "error").mockImplementation(() => {}); 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( createChatSpy.mockRejectedValueOnce(
new Error("workspace_scope_rejected:project_path must be an existing directory"), new Error("workspace_scope_rejected:project_path must be an existing directory"),
); );
mockFetchRoutes({ mockFetchRoutes({
"/api/workspaces": { "/api/workspaces": {
schema_version: 1, schema_version: 1,
default_access_mode: "restricted", default_access_mode: "default",
default_scope: { default_scope: {
project_path: "C:\\workspace", project_path: "C:\\workspace",
project_name: "workspace", project_name: "workspace",
@@ -1156,16 +1163,21 @@ describe("App layout", () => {
}, },
controls: { can_change_project: true, can_use_full_access: true }, 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 />); render(<App />);
await waitFor(() => expect(connectSpy).toHaveBeenCalled()); await waitFor(() => expect(connectSpy).toHaveBeenCalled());
fireEvent.click(await screen.findByRole("button", { name: "Switch working directory" })); fireEvent.click(await screen.findByRole("button", { name: "Switch working directory" }));
fireEvent.change(await screen.findByLabelText("Paste path"), { fireEvent.change(await screen.findByRole("combobox"), {
target: { value: "C:\\missing-project" }, target: { value: projectPath },
}); });
await waitFor(() => expect(screen.getByRole("button", { name: "Select" })).toBeEnabled());
fireEvent.click(screen.getByRole("button", { name: "Select" })); fireEvent.click(screen.getByRole("button", { name: "Select" }));
await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
const message = screen.getByLabelText("Message input"); const message = screen.getByLabelText("Message input");
fireEvent.change(message, { target: { value: "keep this first message" } }); 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.", "The gateway rejected this project or access mode. Choose an existing project or a different access mode, then try again.",
); );
fireEvent.click(projectButton); fireEvent.click(projectButton);
const projectPath = await screen.findByLabelText("Paste path"); const pathInput = await screen.findByRole("combobox");
expect(projectPath).toHaveValue("C:\\missing-project"); expect(pathInput).toHaveValue(`${projectPath}\\`);
expect(projectPath).toHaveAttribute("aria-invalid", "true"); expect(pathInput).toHaveAttribute("aria-invalid", "true");
expect(projectPath).toHaveFocus(); expect(pathInput).toHaveFocus();
expect(screen.getByRole("alert")).toHaveTextContent( 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.", "The gateway rejected this project or access mode. Choose an existing project or a different access mode, then try again.",
); );
-2
View File
@@ -204,8 +204,6 @@ const LOCALIZED_WORKSPACE_COPY_KEYS = [
"thread.composer.workspace.full", "thread.composer.workspace.full",
"errors.workspaceScopeRejected.title", "errors.workspaceScopeRejected.title",
"errors.workspaceScopeRejected.body", "errors.workspaceScopeRejected.body",
"workspace.dialog.defaultProject",
"workspace.dialog.absolutePathRequired",
]; ];
const LOCALIZED_CHANNEL_SHELL_KEYS = [ const LOCALIZED_CHANNEL_SHELL_KEYS = [
"settings.channels.advanced", "settings.channels.advanced",
-35
View File
@@ -2,15 +2,11 @@ import { afterEach, describe, expect, it, vi } from "vitest";
import { import {
getRuntimeHost, getRuntimeHost,
initializeLoopbackRuntimeHost,
isNativeRuntime, isNativeRuntime,
} from "@/lib/runtime"; } from "@/lib/runtime";
afterEach(() => { afterEach(() => {
Reflect.deleteProperty(window, "nanobotHost"); Reflect.deleteProperty(window, "nanobotHost");
window.sessionStorage.clear();
window.history.replaceState(null, "", "/");
initializeLoopbackRuntimeHost();
}); });
describe("runtime host facade", () => { describe("runtime host facade", () => {
@@ -52,35 +48,4 @@ describe("runtime host facade", () => {
expect(isNativeRuntime("native")).toBe(true); 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_surface: "native" as const,
runtime_capabilities: { runtime_capabilities: {
can_restart_engine: true, can_restart_engine: true,
can_pick_folder: true,
can_open_logs: true, can_open_logs: true,
can_export_diagnostics: true, can_export_diagnostics: true,
}, },
+45 -43
View File
@@ -8,6 +8,28 @@ import { encodeImage } from "@/lib/imageEncode";
import { SESSION_DRAG_TYPE } from "@/lib/session-drag"; import { SESSION_DRAG_TYPE } from "@/lib/session-drag";
import type { ChatSummary, CliAppInfo, McpPresetInfo, SlashCommand, WorkspaceScopePayload } from "@/lib/types"; 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", () => ({ vi.mock("@/lib/imageEncode", () => ({
encodeImage: vi.fn(async (file: File) => ({ encodeImage: vi.fn(async (file: File) => ({
ok: true, ok: true,
@@ -1467,6 +1489,7 @@ describe("ThreadComposer", () => {
restrict_to_workspace: false, restrict_to_workspace: false,
}} }}
workspaceDefaultScope={defaultScope} workspaceDefaultScope={defaultScope}
{...workspacePickerProps(defaultScope)}
workspaceControls={{ can_change_project: true, can_use_full_access: true }} workspaceControls={{ can_change_project: true, can_use_full_access: true }}
onWorkspaceScopeChange={onWorkspaceScopeChange} onWorkspaceScopeChange={onWorkspaceScopeChange}
/>, />,
@@ -1477,13 +1500,14 @@ describe("ThreadComposer", () => {
expect(await screen.findByRole("button", { name: "/Users/test/.nanobot/workspace" })).toBeInTheDocument(); expect(await screen.findByRole("button", { name: "/Users/test/.nanobot/workspace" })).toBeInTheDocument();
expect(screen.getByRole("dialog")).toBeInTheDocument(); expect(screen.getByRole("dialog")).toBeInTheDocument();
const input = screen.getByLabelText("Paste path"); const input = screen.getByRole("combobox");
fireEvent.change(input, { target: { value: "relative/project" } }); fireEvent.change(input, { target: { value: "relative/project" } });
expect(screen.queryByRole("option", { name: "relative/project" })).not.toBeInTheDocument(); expect(screen.queryByRole("option", { name: "relative/project" })).not.toBeInTheDocument();
expect(onWorkspaceScopeChange).not.toHaveBeenCalled(); expect(onWorkspaceScopeChange).not.toHaveBeenCalled();
fireEvent.change(input, { target: { value: "/Users/test/project-alpha" } }); 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({ expect(onWorkspaceScopeChange).toHaveBeenCalledWith(expect.objectContaining({
project_path: "/Users/test/project-alpha", project_path: "/Users/test/project-alpha",
@@ -1493,12 +1517,13 @@ describe("ThreadComposer", () => {
})); }));
await user.click(screen.getByRole("button", { name: "Switch working directory" })); 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.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({ expect(onWorkspaceScopeChange).toHaveBeenLastCalledWith(expect.objectContaining({
project_path: "~/Pictures/Photos", project_path: "/Users/test/Pictures/Photos",
project_name: "Photos", project_name: "Photos",
access_mode: "full", access_mode: "full",
restrict_to_workspace: false, restrict_to_workspace: false,
@@ -1527,6 +1552,7 @@ describe("ThreadComposer", () => {
variant="hero" variant="hero"
workspaceScope={defaultScope} workspaceScope={defaultScope}
workspaceDefaultScope={defaultScope} workspaceDefaultScope={defaultScope}
{...workspacePickerProps(defaultScope)}
workspaceControls={{ can_change_project: true, can_use_full_access: true }} workspaceControls={{ can_change_project: true, can_use_full_access: true }}
onWorkspaceScopeChange={onWorkspaceScopeChange} onWorkspaceScopeChange={onWorkspaceScopeChange}
/>, />,
@@ -1534,9 +1560,10 @@ describe("ThreadComposer", () => {
await user.click(screen.getByRole("button", { name: "Switch working directory" })); await user.click(screen.getByRole("button", { name: "Switch working directory" }));
fireEvent.change(await screen.findByLabelText("Paste path"), { target: { value: selectedPath } }); fireEvent.change(await screen.findByRole("combobox"), { target: { value: selectedPath } });
fireEvent.keyDown(screen.getByLabelText("Paste path"), { key: "Enter" }); await waitFor(() => expect(screen.getByRole("button", { name: "Select" })).toBeEnabled());
expect(onWorkspaceScopeChange).toHaveBeenCalledWith(expect.objectContaining({ project_path: selectedPath })); 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", () => { it("groups the directory and access beside attachments and hides them with workspace controls", () => {
@@ -1554,6 +1581,7 @@ describe("ThreadComposer", () => {
workspaceControlsHidden={workspaceControlsHidden} workspaceControlsHidden={workspaceControlsHidden}
workspaceScope={defaultScope} workspaceScope={defaultScope}
workspaceDefaultScope={defaultScope} workspaceDefaultScope={defaultScope}
{...workspacePickerProps(defaultScope)}
workspaceControls={{ can_change_project: true, can_use_full_access: true }} workspaceControls={{ can_change_project: true, can_use_full_access: true }}
onWorkspaceScopeChange={vi.fn()} onWorkspaceScopeChange={vi.fn()}
/> />
@@ -1576,7 +1604,8 @@ describe("ThreadComposer", () => {
vi.spyOn(HTMLFormElement.prototype, "getBoundingClientRect").mockImplementation(() => rect({ width, height: 160 })); 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 defaultScope = { project_path: "/srv/workspace", project_name: "workspace", access_mode: "full" as const };
const { container } = render(<ThreadComposer variant="hero" onSend={vi.fn()} workspaceScope={defaultScope} 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 input = screen.getByRole("textbox");
const row = container.querySelector(".thread-composer-workspace-row")!; const row = container.querySelector(".thread-composer-workspace-row")!;
const trigger = screen.getByRole("button", { name: "Switch working directory" }); const trigger = screen.getByRole("button", { name: "Switch working directory" });
@@ -1629,12 +1658,10 @@ describe("ThreadComposer", () => {
variant="hero" variant="hero"
workspaceScope={defaultScope} workspaceScope={defaultScope}
workspaceDefaultScope={defaultScope} workspaceDefaultScope={defaultScope}
{...workspacePickerProps(defaultScope)}
workspaceControls={{ workspaceControls={{
can_change_project: true, can_change_project: true,
can_use_full_access: true, can_use_full_access: true,
can_pick_folder: true,
can_browse_directories: true,
can_resolve_project: true,
}} }}
onBrowseWorkspaceDirectories={onBrowseWorkspaceDirectories} onBrowseWorkspaceDirectories={onBrowseWorkspaceDirectories}
onResolveWorkspaceProject={onResolveWorkspaceProject} 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 user = userEvent.setup();
const onWorkspaceScopeChange = vi.fn(); const onWorkspaceScopeChange = vi.fn();
const defaultScope = { const defaultScope = {
@@ -1674,10 +1701,10 @@ describe("ThreadComposer", () => {
variant="hero" variant="hero"
workspaceScope={defaultScope} workspaceScope={defaultScope}
workspaceDefaultScope={defaultScope} workspaceDefaultScope={defaultScope}
{...workspacePickerProps(defaultScope)}
workspaceControls={{ workspaceControls={{
can_change_project: true, can_change_project: true,
can_use_full_access: false, can_use_full_access: false,
can_pick_folder: false,
}} }}
onWorkspaceScopeChange={onWorkspaceScopeChange} onWorkspaceScopeChange={onWorkspaceScopeChange}
/>, />,
@@ -1685,12 +1712,13 @@ describe("ThreadComposer", () => {
await user.click(screen.getByRole("button", { name: "Switch working directory" })); 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" }, 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({ expect(onWorkspaceScopeChange).toHaveBeenCalledWith(expect.objectContaining({
project_path: "/srv/nas-project", 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", () => { it("closes the sustained goal through its existing drawer", () => {
const { container, rerender } = render( const { container, rerender } = render(
+31 -35
View File
@@ -4,7 +4,7 @@ import { describe, expect, it, vi } from "vitest";
import { WorkspaceProjectPicker } from "@/components/thread/WorkspaceControls"; import { WorkspaceProjectPicker } from "@/components/thread/WorkspaceControls";
import type { WorkspaceDirectoriesPayload, WorkspacesPayload } from "@/lib/types"; 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 scope = { project_path: "/srv/workspace", access_mode: "restricted" as const };
const catalog: WorkspacesPayload = { const catalog: WorkspacesPayload = {
@@ -13,19 +13,28 @@ const catalog: WorkspacesPayload = {
default_scope: scope, default_scope: scope,
recent_projects: [{ name: "alpha", path: "/srv/alpha" }, { name: "beta", path: "/srv/beta" }], recent_projects: [{ name: "alpha", path: "/srv/alpha" }, { name: "beta", path: "/srv/beta" }],
host: { name: "dev-server", platform: "Linux" }, 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 = { const directory: WorkspaceDirectoriesPayload = {
path: "/srv/workspace", parent: "/srv", entries: [{ name: "alpha", path: "/srv/workspace/alpha" }], path: "/srv/workspace", parent: "/srv", entries: [{ name: "alpha", path: "/srv/workspace/alpha" }],
truncated: false, host: "dev-server", platform: "Linux", 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", () => { describe("Workspace project picker", () => {
it("keeps saved locations separate from directory filtering", async () => { it("keeps saved locations separate from directory filtering", async () => {
const user = userEvent.setup(); const user = userEvent.setup();
const onChange = vi.fn(); const onChange = vi.fn();
const onBrowse = vi.fn().mockResolvedValue(directory); 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" })); await user.click(screen.getByRole("button", { name: "Switch working directory" }));
const shortcut = await screen.findByRole("button", { name: "/srv/beta" }); const shortcut = await screen.findByRole("button", { name: "/srv/beta" });
await user.clear(screen.getByRole("combobox")); await user.clear(screen.getByRole("combobox"));
@@ -52,7 +61,7 @@ describe("Workspace project picker", () => {
const user = userEvent.setup(); const user = userEvent.setup();
const onBrowse = vi.fn((path: string) => Promise.resolve(path.replace(/\/$/, "") === scope.project_path const onBrowse = vi.fn((path: string) => Promise.resolve(path.replace(/\/$/, "") === scope.project_path
? directory : { ...directory, path: "/srv/workspace/alpha", entries: [] })); ? 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(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" }));
await waitFor(() => expect(screen.queryByRole("status")).not.toBeInTheDocument()); await waitFor(() => expect(screen.queryByRole("status")).not.toBeInTheDocument());
@@ -72,7 +81,7 @@ describe("Workspace project picker", () => {
const user = userEvent.setup(); const user = userEvent.setup();
const onBrowse = vi.fn((path: string) => Promise.resolve(path.replace(/\/$/, "") === scope.project_path const onBrowse = vi.fn((path: string) => Promise.resolve(path.replace(/\/$/, "") === scope.project_path
? directory : { ...directory, path: "/srv/workspace/alpha", entries: [] })); ? 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(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" }));
await waitFor(() => expect(screen.queryByRole("status")).not.toBeInTheDocument()); await waitFor(() => expect(screen.queryByRole("status")).not.toBeInTheDocument());
@@ -100,7 +109,7 @@ describe("Workspace project picker", () => {
const path = rawPath.replace(/\/$/, ""); const path = rawPath.replace(/\/$/, "");
return Promise.resolve({ ...directory, path, entries: path === scope.project_path ? entries : [{ name: "child", path: `${path}/child` }] }); 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" })); await user.click(screen.getByRole("button", { name: "Switch working directory" }));
const first = await screen.findByRole("option", { name: entries[0].path }); const first = await screen.findByRole("option", { name: entries[0].path });
expect(first).toHaveAttribute("aria-setsize", "500"); expect(first).toHaveAttribute("aria-setsize", "500");
@@ -124,7 +133,7 @@ describe("Workspace project picker", () => {
const user = userEvent.setup(); const user = userEvent.setup();
const onChange = vi.fn(); const onChange = vi.fn();
const onBrowse = vi.fn().mockResolvedValue(directory); 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 user.click(screen.getByRole("button", { name: "Switch working directory" }));
await screen.findByRole("option", { name: "/srv/workspace/alpha" }); await screen.findByRole("option", { name: "/srv/workspace/alpha" });
expect(onBrowse).toHaveBeenLastCalledWith("/srv/workspace/", "", false, true); 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()); 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 user = userEvent.setup();
const onChange = vi.fn(); const onChange = vi.fn();
const onResolve = vi.fn().mockRejectedValueOnce(new Error("project_path must be an existing directory")) const onResolve = vi.fn().mockRejectedValueOnce(new Error("project_path must be an existing directory"))
.mockResolvedValueOnce({ name: "alpha", path: "/srv/alpha" }); .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.click(screen.getByRole("button", { name: "Switch working directory" }));
await user.clear(screen.getByRole("combobox")); await user.clear(screen.getByRole("combobox"));
await user.type(screen.getByRole("combobox"), "/srv/missing"); await user.type(screen.getByRole("combobox"), "/srv/missing");
await waitFor(() => expect(screen.getByRole("button", { name: "Select" })).toBeEnabled());
await user.keyboard("{Enter}"); await user.keyboard("{Enter}");
expect(await screen.findByRole("alert")).toHaveTextContent("existing directory"); expect(await screen.findByRole("alert")).toHaveTextContent("existing directory");
expect(screen.getByRole("combobox")).toHaveValue("/srv/missing"); expect(screen.getByRole("combobox")).toHaveValue("/srv/missing");
@@ -154,33 +164,19 @@ describe("Workspace project picker", () => {
expect(onChange).not.toHaveBeenCalled(); expect(onChange).not.toHaveBeenCalled();
await user.clear(screen.getByRole("combobox")); await user.clear(screen.getByRole("combobox"));
await user.type(screen.getByRole("combobox"), "/srv/alpha"); await user.type(screen.getByRole("combobox"), "/srv/alpha");
await waitFor(() => expect(screen.getByRole("button", { name: "Select" })).toBeEnabled());
await user.keyboard("{Enter}"); await user.keyboard("{Enter}");
await waitFor(() => expect(onChange).toHaveBeenCalledWith(expect.objectContaining({ project_path: "/srv/alpha" }))); await waitFor(() => expect(onChange).toHaveBeenCalledWith(expect.objectContaining({ project_path: "/srv/alpha" })));
expect(screen.queryByRole("dialog")).not.toBeInTheDocument(); 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 () => { it("does not apply a directory response after closing the dialog", async () => {
const user = userEvent.setup(); const user = userEvent.setup();
const onChange = vi.fn(); const onChange = vi.fn();
let finish!: (value: WorkspaceDirectoriesPayload) => void; let finish!: (value: WorkspaceDirectoriesPayload) => void;
const onBrowse = vi.fn(() => new Promise<WorkspaceDirectoriesPayload>((resolve) => { finish = resolve; })); 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 user.click(screen.getByRole("button", { name: "Switch working directory" }));
await waitFor(() => expect(onBrowse).toHaveBeenCalled()); await waitFor(() => expect(onBrowse).toHaveBeenCalled());
await user.keyboard("{Escape}"); await user.keyboard("{Escape}");
@@ -193,7 +189,7 @@ describe("Workspace project picker", () => {
const onChange = vi.fn(); const onChange = vi.fn();
const favorites = [{ name: "beta", path: "/srv/beta" }]; const favorites = [{ name: "beta", path: "/srv/beta" }];
const onFavorite = vi.fn().mockResolvedValueOnce(favorites).mockRejectedValueOnce(new Error("disk full")).mockResolvedValueOnce([]); 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(screen.getByRole("button", { name: "Switch working directory" }));
await user.click(await screen.findByRole("button", { name: "Pin beta" })); await user.click(await screen.findByRole("button", { name: "Pin beta" }));
expect(onFavorite).toHaveBeenLastCalledWith("/srv/beta", true); expect(onFavorite).toHaveBeenLastCalledWith("/srv/beta", true);
@@ -213,8 +209,8 @@ describe("Workspace project picker", () => {
const user = userEvent.setup(); const user = userEvent.setup();
const onChange = vi.fn(); const onChange = vi.fn();
const onFavorite = vi.fn().mockResolvedValue([{ name: "alpha", path: "/srv/workspace/alpha" }]); const onFavorite = vi.fn().mockResolvedValue([{ name: "alpha", path: "/srv/workspace/alpha" }]);
render(<WorkspaceProjectPicker isHero scope={scope} defaultScope={scope} controls={catalog.controls} render(<WorkspaceProjectPicker {...pickerActions()} isHero scope={scope} defaultScope={scope} controls={catalog.controls}
onLoadProjects={vi.fn().mockResolvedValue({ ...catalog, controls: { ...catalog.controls, can_manage_favorites: true } })} onLoadProjects={vi.fn().mockResolvedValue(catalog)}
onBrowseDirectories={vi.fn().mockResolvedValue(directory)} onFavoriteProject={onFavorite} onChange={onChange} />); onBrowseDirectories={vi.fn().mockResolvedValue(directory)} onFavoriteProject={onFavorite} onChange={onChange} />);
await user.click(screen.getByRole("button", { name: "Switch working directory" })); await user.click(screen.getByRole("button", { name: "Switch working directory" }));
const option = await screen.findByRole("option", { name: "/srv/workspace/alpha" }); const option = await screen.findByRole("option", { name: "/srv/workspace/alpha" });
@@ -237,7 +233,7 @@ describe("Workspace project picker", () => {
const user = userEvent.setup(); const user = userEvent.setup();
const onChange = vi.fn(); 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 }] : [] })); 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" })); await user.click(screen.getByRole("button", { name: "Switch working directory" }));
const input = screen.getByRole("combobox"); const input = screen.getByRole("combobox");
await user.clear(input); await user.clear(input);
@@ -257,7 +253,7 @@ describe("Workspace project picker", () => {
it("uses one list for partial paths and keyboard completion", async () => { it("uses one list for partial paths and keyboard completion", async () => {
const user = userEvent.setup(); 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" }] : [] })); 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" })); await user.click(screen.getByRole("button", { name: "Switch working directory" }));
const input = screen.getByRole("combobox"); const input = screen.getByRole("combobox");
await user.clear(input); await user.clear(input);
@@ -277,7 +273,7 @@ describe("Workspace project picker", () => {
const user = userEvent.setup(); const user = userEvent.setup();
let finish!: (value: WorkspaceDirectoriesPayload) => void; let finish!: (value: WorkspaceDirectoriesPayload) => void;
const onBrowse = vi.fn((path: string) => path === "/srv/al" ? new Promise<WorkspaceDirectoriesPayload>(resolve => { finish = resolve; }) : Promise.resolve({ ...directory, entries: [] })); 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" })); await user.click(screen.getByRole("button", { name: "Switch working directory" }));
const input = screen.getByRole("combobox"); const input = screen.getByRole("combobox");
await user.clear(input); await user.clear(input);
@@ -295,7 +291,7 @@ describe("Workspace project picker", () => {
const onBrowse = vi.fn<BrowseWorkspaceDirectories>((path: string) => path === "/srv/al" const onBrowse = vi.fn<BrowseWorkspaceDirectories>((path: string) => path === "/srv/al"
? new Promise<WorkspaceDirectoriesPayload>(resolve => { finish = resolve; }) ? new Promise<WorkspaceDirectoriesPayload>(resolve => { finish = resolve; })
: Promise.resolve({ ...directory, path, entries: [] })); : 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" })); await user.click(screen.getByRole("button", { name: "Switch working directory" }));
const input = screen.getByRole("combobox"); const input = screen.getByRole("combobox");
await user.clear(input); await user.clear(input);
@@ -313,7 +309,7 @@ describe("Workspace project picker", () => {
let finishOld!: (value: WorkspaceDirectoriesPayload) => void; 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 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(); 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 user.click(screen.getByRole("button", { name: "Switch working directory" }));
await screen.findByRole("option", { name: "/srv/workspace/child" }); await screen.findByRole("option", { name: "/srv/workspace/child" });
const input = screen.getByRole("combobox"); 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 () => { it("filters the current directory by name without a second browser view", async () => {
const user = userEvent.setup(); const user = userEvent.setup();
const onBrowse = vi.fn().mockResolvedValue(directory); 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 user.click(screen.getByRole("button", { name: "Switch working directory" }));
await screen.findByRole("option", { name: "/srv/workspace/alpha" }); await screen.findByRole("option", { name: "/srv/workspace/alpha" });
const input = screen.getByRole("combobox"); const input = screen.getByRole("combobox");
@@ -357,7 +353,7 @@ describe("Workspace project picker", () => {
if (showHidden) names.push(".hidden"); if (showHidden) names.push(".hidden");
return Promise.resolve({ ...directory, path, entries: names.map(name => ({ name, path: `${path}/${name}` })) }); 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(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" }));
await user.click(await screen.findByRole("option", { name: "/srv/workspace/alpha/child" })); await user.click(await screen.findByRole("option", { name: "/srv/workspace/alpha/child" }));