feat(webui): add a host directory picker and refine composer controls
This commit is contained in:
1 parent
3865bde3fe
commit
66c8d41f66
32 files changed
+1974
-464
No files matched your search
+56
-6
@@ -291,11 +291,57 @@ or a result you must retain.
|
||||
|
||||
## Workspace and Access
|
||||
|
||||
Use the workspace picker before starting project-specific work. This gives the
|
||||
agent the right project context for file paths, shell commands, and topic
|
||||
metadata. A locally hosted WebUI opens the operating system's folder chooser
|
||||
when one is available; remote deployments use a manual absolute path on the
|
||||
nanobot host. The browser's local filesystem is never used for project selection.
|
||||
The folder label shows the current working directory in the composer toolbar.
|
||||
On narrow screens, it sits below the input on the left, opposite the access
|
||||
control.
|
||||
Hover it to see the full path, or click it to switch directories before starting
|
||||
project-specific work. This gives the agent the right project context for file paths, shell commands, and topic
|
||||
metadata. The picker opens one dialog with a saved-locations sidebar and a
|
||||
directory browser. Favorites and recent projects remain in the sidebar while
|
||||
you navigate. Right-click a folder to pin or unpin it without selecting it.
|
||||
Right-click a column's empty area to pin its directory. Favorites keep their
|
||||
pin order, are saved by the connected gateway, and remain available after a
|
||||
restart. A deleted folder can still be unpinned.
|
||||
|
||||
Typing a name filters the current directory only; typing an absolute host path
|
||||
lists its directories as you edit. An unfinished folder name filters its parent
|
||||
directory by prefix. Use the arrow keys to highlight a result, then Tab to
|
||||
complete its path or Enter to enter the directory. Opening a folder preserves
|
||||
its column and displays its subdirectories in a new column to the right.
|
||||
Column widths stay stable as you navigate; deeper levels scroll horizontally.
|
||||
Hold Shift while using the mouse wheel over directory columns to scroll
|
||||
horizontally. Ordinary wheel scrolling remains vertical.
|
||||
The picker caches up to 64 directory listings for 30 seconds, reuses in-flight
|
||||
requests, and displays cached listings immediately. Only typed queries are
|
||||
debounced; entering a folder starts its request immediately.
|
||||
Selecting a different folder in an earlier column replaces the columns to its
|
||||
right. Clicking a saved location starts a new directory trail. Expanded branches
|
||||
have a persistent selection fill; pointer hover and keyboard focus remain
|
||||
visually distinct. Directory columns show folder names; the input and hover
|
||||
hints retain full paths. Favorites and recent projects show full paths to
|
||||
distinguish folders with the same name. On narrow screens, saved locations move
|
||||
into a compact area above the directory columns.
|
||||
|
||||
Use **Select** to confirm the directory being browsed. Only a fully
|
||||
resolved directory can be selected or pinned. **Show hidden folders** includes
|
||||
hidden entries.
|
||||
Escape or clicking outside closes the dialog. Shift+Tab moves focus back.
|
||||
|
||||
The dialog is centered within the message thread and keeps a fixed height
|
||||
within the available space, so changing results cannot move the input field.
|
||||
Loading, errors, and completion candidates appear in the active column. Each column scrolls vertically, and deeper paths scroll
|
||||
the columns horizontally. Up to three columns
|
||||
fit on desktop; narrower windows show fewer columns.
|
||||
|
||||
The directory browser works on Windows,
|
||||
Linux, and macOS hosts, including remote gateways and environments without a
|
||||
desktop. It lists directory names without reading file contents or changing the
|
||||
agent's access mode. Windows drive paths and UNC paths can be entered directly.
|
||||
|
||||
A locally hosted WebUI also offers the operating system's folder chooser when
|
||||
available. You can enter an absolute host path in the search field; gateways
|
||||
without directory browsing support retain this option. The browser's local
|
||||
filesystem is never used for project selection.
|
||||
|
||||
Selecting a project does not replace the configured agent workspace. The two
|
||||
paths have different responsibilities:
|
||||
@@ -325,12 +371,16 @@ selected project. These tool exceptions do not broaden the browser's file
|
||||
preview boundary.
|
||||
|
||||
Remote WebUI connections may reduce access for the current workspace and may
|
||||
select a different workspace by entering its server-side path. A remote project
|
||||
select a different workspace by browsing directories or entering its server-side path. A remote project
|
||||
change must use Restricted mode; enabling Full Access remains limited to local
|
||||
and native clients.
|
||||
|
||||
## Composer
|
||||
|
||||
The rightmost composer button starts voice input while the draft is empty and
|
||||
switches to Send when text or an attachment is present. Recorded speech is
|
||||
transcribed into the draft for confirmation before sending.
|
||||
|
||||
The composer supports plain messages, image attachments, voice input when
|
||||
transcription is configured, slash commands, and `@` mentions for installed Apps,
|
||||
MCP presets, or persisted topics. Topics have short, pronounceable handles such as
|
||||
|
||||
@@ -4232,3 +4232,69 @@ async def test_star_prompt_requires_authenticated_mutation_and_persists_dismissa
|
||||
finally:
|
||||
await channel.stop()
|
||||
await server_task
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("connection", [_LOCAL, _REMOTE])
|
||||
async def test_project_directory_http_read_requires_auth_and_keeps_scope(
|
||||
bus: MagicMock, tmp_path: Path, connection: _FakeConn,
|
||||
) -> None:
|
||||
root = tmp_path / "folders"
|
||||
root.mkdir()
|
||||
(root / "project").mkdir()
|
||||
(root / "private.txt").write_text("not returned")
|
||||
channel = _ch(bus, workspace_path=tmp_path)
|
||||
path = f"/api/workspaces/directories?path={root}"
|
||||
response = await channel.gateway.http._dispatch_misc_routes(connection, _FakeReq({}, path=path), "/api/workspaces/directories")
|
||||
assert response is not None and response.status_code == 401
|
||||
token = channel.gateway.tokens.issue_api_token(300)
|
||||
request = _FakeReq({"Authorization": f"Bearer {token}"}, path=path)
|
||||
response = await channel.gateway.http._dispatch_misc_routes(connection, request, "/api/workspaces/directories")
|
||||
assert response is not None and response.status_code == 200
|
||||
assert json.loads(response.body)["entries"] == [{"name": "project", "path": str(root / "project")}]
|
||||
partial_request = _FakeReq({"Authorization": f"Bearer {token}"}, path=f"/api/workspaces/directories?path={root / 'proj'}&partial=1")
|
||||
partial_response = await channel.gateway.http._dispatch_misc_routes(connection, partial_request, "/api/workspaces/directories")
|
||||
assert partial_response is not None and partial_response.status_code == 200
|
||||
assert json.loads(partial_response.body)["partial"] is True
|
||||
assert json.loads(partial_response.body)["entries"] == [{"name": "project", "path": str(root / "project")}]
|
||||
assert channel.gateway.workspaces.default_scope().project_path == tmp_path
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("connection", [_LOCAL, _REMOTE])
|
||||
async def test_project_selection_remembers_resolved_path_without_changing_access(
|
||||
bus: MagicMock, tmp_path: Path, connection: _FakeConn,
|
||||
) -> None:
|
||||
project = tmp_path / "project"
|
||||
project.mkdir()
|
||||
channel = _ch(bus, workspace_path=tmp_path)
|
||||
scope = channel.gateway.workspaces.default_scope()
|
||||
response = await _webui_mutate(channel, "workspace.resolve_project", {"path": str(project)}, connection=connection)
|
||||
assert response.status_code == 200
|
||||
assert response.json() == {"name": "project", "path": str(project)}
|
||||
assert channel.gateway.workspaces.default_scope() == scope
|
||||
payload = channel.gateway.workspaces.payload(can_change_project=True, can_use_full_access=False)
|
||||
assert payload["recent_projects"] == [{"name": "project", "path": str(project)}]
|
||||
rejected = await _webui_mutate(channel, "workspace.resolve_project", {"path": str(tmp_path / "missing")}, connection=connection)
|
||||
assert rejected.status_code == 400
|
||||
assert channel.gateway.workspaces.payload(can_change_project=True, can_use_full_access=False)["recent_projects"] == payload["recent_projects"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("connection", [_LOCAL, _REMOTE])
|
||||
async def test_project_favorites_mutation_persists_without_selecting_project(
|
||||
bus: MagicMock, tmp_path: Path, connection: _FakeConn,
|
||||
) -> None:
|
||||
project = tmp_path / "pinned"
|
||||
project.mkdir()
|
||||
channel = _ch(bus, workspace_path=tmp_path)
|
||||
response = await _webui_mutate(channel, "workspace.favorite", {"path": str(project), "pinned": True}, connection=connection)
|
||||
assert response.status_code == 200
|
||||
assert response.json() == {"favorite_projects": [{"name": "pinned", "path": str(project)}]}
|
||||
payload = channel.gateway.workspaces.payload(can_change_project=True, can_use_full_access=False)
|
||||
assert payload["favorite_projects"] == response.json()["favorite_projects"]
|
||||
assert payload["recent_projects"] == []
|
||||
assert payload["default_scope"]["project_path"] == str(tmp_path)
|
||||
response = await _webui_mutate(channel, "workspace.favorite", {"path": str(project), "pinned": False}, connection=connection)
|
||||
assert response.status_code == 200
|
||||
assert response.json() == {"favorite_projects": []}
|
||||
@@ -0,0 +1,87 @@
|
||||
"""Directory metadata for the authenticated WebUI project selector."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import heapq
|
||||
import os
|
||||
import platform
|
||||
import socket
|
||||
import stat
|
||||
from pathlib import Path
|
||||
from typing import TypedDict
|
||||
|
||||
from nanobot.security.workspace_access import WorkspaceScopeError
|
||||
|
||||
|
||||
class ProjectDirectory(TypedDict):
|
||||
name: str
|
||||
path: str
|
||||
|
||||
|
||||
class WorkspaceDirectories(TypedDict):
|
||||
path: str
|
||||
parent: str | None
|
||||
entries: list[ProjectDirectory]
|
||||
partial: bool
|
||||
truncated: bool
|
||||
host: str
|
||||
platform: str
|
||||
|
||||
|
||||
def browse_workspace_directories(
|
||||
raw_path: str, *, default_workspace: Path, query: str = "", show_hidden: bool = False,
|
||||
allow_partial: bool = False,
|
||||
) -> WorkspaceDirectories:
|
||||
"""List directories for project selection, independently of agent tool access.
|
||||
|
||||
The caller must authorize project selection. This capability discloses
|
||||
directory names under a user-selected root; it never reads file contents or
|
||||
changes the selected project or its read/write permissions.
|
||||
"""
|
||||
if "\0" in raw_path:
|
||||
raise WorkspaceScopeError("path contains invalid characters")
|
||||
path = Path(raw_path).expanduser() if raw_path else default_workspace
|
||||
if not path.is_absolute():
|
||||
raise WorkspaceScopeError("path must be absolute")
|
||||
try:
|
||||
prefix = ""
|
||||
partial = False
|
||||
if allow_partial:
|
||||
try:
|
||||
is_directory = stat.S_ISDIR(path.stat().st_mode)
|
||||
except (FileNotFoundError, NotADirectoryError):
|
||||
is_directory = False
|
||||
if not is_directory:
|
||||
prefix = path.name.casefold()
|
||||
path = path.parent
|
||||
partial = True
|
||||
path = path.resolve(strict=True)
|
||||
matches: list[ProjectDirectory] = []
|
||||
with os.scandir(path) as entries:
|
||||
for entry in entries:
|
||||
if not entry.name.casefold().startswith(prefix) or query.casefold() not in entry.name.casefold():
|
||||
continue
|
||||
try:
|
||||
if not entry.is_dir():
|
||||
continue
|
||||
hidden = entry.name.startswith(".") or (
|
||||
os.name == "nt"
|
||||
and bool(entry.stat(follow_symlinks=False).st_file_attributes & stat.FILE_ATTRIBUTE_HIDDEN)
|
||||
)
|
||||
if show_hidden or prefix.startswith(".") or not hidden:
|
||||
matches.append({"name": entry.name, "path": entry.path})
|
||||
except OSError:
|
||||
continue
|
||||
return {
|
||||
"path": str(path),
|
||||
"parent": str(path.parent) if path.parent != path else None,
|
||||
"entries": heapq.nsmallest(500, matches, key=lambda item: item["name"].casefold()),
|
||||
"partial": partial,
|
||||
"truncated": len(matches) > 500,
|
||||
"host": socket.gethostname(),
|
||||
"platform": platform.system(),
|
||||
}
|
||||
except PermissionError as exc:
|
||||
raise WorkspaceScopeError("directory is not accessible", status=403) from exc
|
||||
except (OSError, RuntimeError) as exc:
|
||||
raise WorkspaceScopeError("directory was not found or could not be listed") from exc
|
||||
@@ -4,6 +4,8 @@ from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import platform
|
||||
import socket
|
||||
import time
|
||||
from collections import OrderedDict
|
||||
from pathlib import Path
|
||||
@@ -51,6 +53,8 @@ def default_webui_workspace_state() -> dict[str, Any]:
|
||||
"schema_version": WEBUI_WORKSPACE_STATE_SCHEMA_VERSION,
|
||||
"default_access_mode": "default",
|
||||
"updated_at": None,
|
||||
"recent_projects": [],
|
||||
"favorite_projects": [],
|
||||
}
|
||||
|
||||
|
||||
@@ -64,9 +68,27 @@ def normalize_webui_workspace_state(raw: Any) -> dict[str, Any]:
|
||||
default_access_mode = raw.get("default_access_mode")
|
||||
if default_access_mode in _DEFAULT_ACCESS_MODES:
|
||||
state["default_access_mode"] = default_access_mode
|
||||
for key, limit in (("recent_projects", 20), ("favorite_projects", 40)):
|
||||
paths = raw.get(key)
|
||||
if isinstance(paths, list):
|
||||
state[key] = list(dict.fromkeys(
|
||||
path for path in cast(list[object], paths)
|
||||
if isinstance(path, str) and "\0" not in path and Path(path).is_absolute()
|
||||
))[:limit]
|
||||
return state
|
||||
|
||||
|
||||
def remember_webui_project(path: Path) -> None:
|
||||
state = read_webui_workspace_state()
|
||||
recent = [str(path), *(item for item in state["recent_projects"] if item != str(path))][:20]
|
||||
if recent != state["recent_projects"]:
|
||||
state["recent_projects"] = recent
|
||||
try:
|
||||
write_webui_workspace_state(state)
|
||||
except OSError:
|
||||
logger.exception("failed to save recent WebUI projects")
|
||||
|
||||
|
||||
def read_webui_workspace_state() -> dict[str, Any]:
|
||||
path = webui_workspace_state_path()
|
||||
if not path.is_file():
|
||||
@@ -170,10 +192,22 @@ def workspaces_payload(
|
||||
"schema_version": WEBUI_WORKSPACE_STATE_SCHEMA_VERSION,
|
||||
"default_access_mode": default_access_mode,
|
||||
"default_scope": default_scope.payload(),
|
||||
"host": {"name": socket.gethostname(), "platform": platform.system()},
|
||||
"favorite_projects": [
|
||||
{"name": Path(path).name or path, "path": path}
|
||||
for path in read_webui_workspace_state()["favorite_projects"]
|
||||
],
|
||||
"recent_projects": [
|
||||
{"name": Path(path).name or path, "path": path}
|
||||
for path in read_webui_workspace_state()["recent_projects"]
|
||||
],
|
||||
"controls": {
|
||||
"can_change_project": can_change_project,
|
||||
"can_use_full_access": can_use_full_access,
|
||||
"can_pick_folder": folder_picker_available,
|
||||
"can_browse_directories": can_change_project,
|
||||
"can_resolve_project": can_change_project,
|
||||
"can_manage_favorites": can_change_project,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -280,6 +314,47 @@ class WebUIWorkspaceController:
|
||||
folder_picker_available=folder_picker_available,
|
||||
)
|
||||
|
||||
def resolve_project(self, path: object) -> dict[str, str]:
|
||||
"""Validate and remember a selection without changing any chat's scope."""
|
||||
if not isinstance(path, str) or not path.strip():
|
||||
raise WorkspaceScopeError("project_path must be a nonempty string")
|
||||
scope = validate_workspace_scope_payload(
|
||||
{"project_path": path.strip(), "access_mode": "restricted"},
|
||||
default_workspace=self._default_workspace,
|
||||
default_restrict_to_workspace=self._default_restrict_to_workspace,
|
||||
source_channel=_WEBUI_SCOPE_CHANNEL,
|
||||
)
|
||||
remember_webui_project(scope.project_path)
|
||||
return {"path": str(scope.project_path), "name": scope.project_name}
|
||||
|
||||
def set_favorite_project(self, path: object, pinned: object) -> list[dict[str, str]]:
|
||||
"""Pin validated folders; allow removing a favorite after it is deleted."""
|
||||
if not isinstance(path, str) or not path.strip() or "\0" in path:
|
||||
raise WorkspaceScopeError("path must be a nonempty directory path")
|
||||
if not isinstance(pinned, bool):
|
||||
raise WorkspaceScopeError("pinned must be a boolean")
|
||||
path = path.strip()
|
||||
if pinned:
|
||||
scope = validate_workspace_scope_payload(
|
||||
{"project_path": path, "access_mode": "restricted"},
|
||||
default_workspace=self._default_workspace,
|
||||
default_restrict_to_workspace=self._default_restrict_to_workspace,
|
||||
source_channel=_WEBUI_SCOPE_CHANNEL,
|
||||
)
|
||||
path = str(scope.project_path)
|
||||
state = read_webui_workspace_state()
|
||||
favorites: list[str] = state["favorite_projects"]
|
||||
existing = next((item for item in favorites if os.path.normcase(item) == os.path.normcase(path)), None)
|
||||
if pinned and existing is None:
|
||||
if len(favorites) >= 40:
|
||||
raise WorkspaceScopeError("at most 40 favorite folders can be pinned")
|
||||
favorites.append(path)
|
||||
write_webui_workspace_state(state)
|
||||
elif not pinned and existing is not None:
|
||||
favorites.remove(existing)
|
||||
write_webui_workspace_state(state)
|
||||
return [{"name": Path(item).name or item, "path": item} for item in favorites]
|
||||
|
||||
def scope_from_envelope(
|
||||
self,
|
||||
envelope: dict[str, Any],
|
||||
@@ -381,6 +456,7 @@ class WebUIWorkspaceController:
|
||||
session.metadata[WORKSPACE_SCOPE_METADATA_KEY] = scope.metadata()
|
||||
self._sessions.save(session)
|
||||
self._draft_scopes.pop(session_key, None)
|
||||
remember_webui_project(scope.project_path)
|
||||
|
||||
def stage_scope(self, chat_id: str, scope: WorkspaceScope) -> None:
|
||||
"""Keep a new chat's scope transient until its first accepted message."""
|
||||
@@ -391,6 +467,7 @@ class WebUIWorkspaceController:
|
||||
):
|
||||
self.persist_scope(chat_id, scope)
|
||||
return
|
||||
remember_webui_project(scope.project_path)
|
||||
self._draft_scopes[session_key] = scope
|
||||
self._draft_scopes.move_to_end(session_key)
|
||||
while len(self._draft_scopes) > _MAX_DRAFT_SCOPES:
|
||||
|
||||
@@ -32,7 +32,7 @@ from nanobot.command.builtin import builtin_command_palette
|
||||
from nanobot.cron.binding import CronBindingError, binding_revision
|
||||
from nanobot.cron.session_turns import is_bound_cron_job
|
||||
from nanobot.cron.types import CronJob, CronSchedule
|
||||
from nanobot.security.workspace_access import WorkspaceScope
|
||||
from nanobot.security.workspace_access import WorkspaceScope, WorkspaceScopeError
|
||||
from nanobot.session.manager import SessionManager
|
||||
from nanobot.session.recovery import RecoveryActionError
|
||||
from nanobot.session.session_handles import (
|
||||
@@ -140,6 +140,7 @@ from nanobot.webui.transcript import (
|
||||
build_webui_trace_detail_response,
|
||||
webui_transcript_revision,
|
||||
)
|
||||
from nanobot.webui.workspace_browser import browse_workspace_directories
|
||||
from nanobot.webui.workspaces import WebUIWorkspaceController
|
||||
|
||||
_SLOW_WEBUI_HTTP_LOG_MS = 1_000
|
||||
@@ -196,6 +197,8 @@ _WEBUI_MUTATION_PATHS = {
|
||||
"star_prompt.claim": "/api/webui/star-prompt/claim",
|
||||
"star_prompt.dismiss": "/api/webui/star-prompt/dismiss",
|
||||
"sidebar.update": "/api/webui/sidebar-state/update",
|
||||
"workspace.favorite": "/api/workspaces/favorite",
|
||||
"workspace.resolve_project": "/api/workspaces/resolve-project",
|
||||
"workspace.pick_folder": "/api/workspaces/pick-folder",
|
||||
"recovery.continue": "/api/webui/recovery/continue",
|
||||
"recovery.dismiss": "/api/webui/recovery/dismiss",
|
||||
@@ -563,6 +566,8 @@ class GatewayHTTPHandler:
|
||||
"/api/webui/star-prompt/dismiss",
|
||||
"/api/webui/sidebar-state/update",
|
||||
"/api/workspaces/pick-folder",
|
||||
"/api/workspaces/resolve-project",
|
||||
"/api/workspaces/favorite",
|
||||
"/api/webui/subagents/cancel",
|
||||
}
|
||||
|
||||
@@ -1644,6 +1649,12 @@ class GatewayHTTPHandler:
|
||||
return self._handle_commands(request)
|
||||
if got == "/api/workspaces/pick-folder":
|
||||
return await self._handle_workspace_folder_picker(connection, request)
|
||||
if got == "/api/workspaces/favorite":
|
||||
return self._handle_workspace_favorite(connection, request)
|
||||
if got == "/api/workspaces/resolve-project":
|
||||
return await self._handle_workspace_resolve_project(connection, request)
|
||||
if got == "/api/workspaces/directories":
|
||||
return await self._handle_workspace_directories(connection, request)
|
||||
if got == "/api/workspaces":
|
||||
return self._handle_workspaces(connection, request)
|
||||
if got == "/api/webui/skills/search":
|
||||
@@ -1700,6 +1711,51 @@ class GatewayHTTPHandler:
|
||||
)
|
||||
)
|
||||
|
||||
def _handle_workspace_favorite(self, connection: Any, request: WsRequest) -> Response:
|
||||
if not self.check_api_token(request):
|
||||
return _http_error(401, "Unauthorized")
|
||||
if not self.workspace_project_selection_available(connection):
|
||||
return _http_error(403, "project selection is unavailable for this connection")
|
||||
payload = _mutation_payload(request) or {}
|
||||
try:
|
||||
favorites = self.workspaces.set_favorite_project(payload.get("path"), payload.get("pinned"))
|
||||
except WorkspaceScopeError as exc:
|
||||
return _http_error(exc.status, exc.message)
|
||||
except OSError:
|
||||
return _http_error(500, "could not save favorite folders")
|
||||
return _http_json_response({"favorite_projects": favorites})
|
||||
|
||||
async def _handle_workspace_resolve_project(self, connection: Any, request: WsRequest) -> Response:
|
||||
if not self.check_api_token(request):
|
||||
return _http_error(401, "Unauthorized")
|
||||
if not self.workspace_project_selection_available(connection):
|
||||
return _http_error(403, "project selection is unavailable for this connection")
|
||||
payload = _mutation_payload(request) or {}
|
||||
try:
|
||||
project = self.workspaces.resolve_project(payload.get("path"))
|
||||
except WorkspaceScopeError as exc:
|
||||
return _http_error(exc.status, exc.message)
|
||||
return _http_json_response(project)
|
||||
|
||||
async def _handle_workspace_directories(self, connection: Any, request: WsRequest) -> Response:
|
||||
if not self.check_api_token(request):
|
||||
return _http_error(401, "Unauthorized")
|
||||
if not self.workspace_project_selection_available(connection):
|
||||
return _http_error(403, "project selection is unavailable for this connection")
|
||||
query = _parse_query(request.path)
|
||||
try:
|
||||
payload = await asyncio.to_thread(
|
||||
browse_workspace_directories,
|
||||
_query_first(query, "path") or "",
|
||||
default_workspace=self.workspaces.default_scope().project_path,
|
||||
query=_query_first(query, "q") or "",
|
||||
show_hidden=_query_first(query, "hidden") == "1",
|
||||
allow_partial=_query_first(query, "partial") == "1",
|
||||
)
|
||||
except WorkspaceScopeError as exc:
|
||||
return _http_error(exc.status, exc.message)
|
||||
return _http_json_response(dict(payload))
|
||||
|
||||
async def _handle_workspace_folder_picker(
|
||||
self,
|
||||
connection: Any,
|
||||
|
||||
@@ -418,3 +418,54 @@ def test_project_selection_can_remain_disabled_for_untrusted_connections(
|
||||
can_change_project=False,
|
||||
can_use_full_access=False,
|
||||
)
|
||||
|
||||
|
||||
def test_recent_projects_survive_controller_restart_without_changing_access(tmp_path, monkeypatch) -> None:
|
||||
monkeypatch.setattr("nanobot.webui.workspaces.get_webui_dir", lambda: tmp_path / "webui")
|
||||
default = tmp_path / "default"
|
||||
project = tmp_path / "project"
|
||||
default.mkdir()
|
||||
project.mkdir()
|
||||
controller = WebUIWorkspaceController(
|
||||
session_manager=None, default_workspace=default, default_restrict_to_workspace=True,
|
||||
)
|
||||
scope = controller.scope_for_new_chat(
|
||||
{WORKSPACE_SCOPE_METADATA_KEY: {"project_path": str(project), "access_mode": "restricted"}},
|
||||
can_change_project=True, can_use_full_access=False,
|
||||
)
|
||||
controller.stage_scope("first", scope)
|
||||
controller.stage_scope("second", scope)
|
||||
restarted = WebUIWorkspaceController(
|
||||
session_manager=None, default_workspace=default, default_restrict_to_workspace=True,
|
||||
)
|
||||
payload = restarted.payload(can_change_project=True, can_use_full_access=False)
|
||||
assert payload["recent_projects"] == [{"name": "project", "path": str(project)}]
|
||||
assert payload["default_scope"]["project_path"] == str(default)
|
||||
assert payload["default_scope"]["access_mode"] == "restricted"
|
||||
assert payload["controls"]["can_browse_directories"] is True
|
||||
|
||||
|
||||
def test_favorites_keep_pin_order_across_restart_and_can_remove_deleted_folder(tmp_path, monkeypatch) -> None:
|
||||
monkeypatch.setattr("nanobot.webui.workspaces.get_webui_dir", lambda: tmp_path / "webui")
|
||||
default, alpha, beta = (tmp_path / name for name in ("default", "alpha", "beta"))
|
||||
for folder in (default, alpha, beta):
|
||||
folder.mkdir()
|
||||
controller = WebUIWorkspaceController(
|
||||
session_manager=None, default_workspace=default, default_restrict_to_workspace=True,
|
||||
)
|
||||
controller.set_favorite_project(str(beta), True)
|
||||
controller.set_favorite_project(str(alpha), True)
|
||||
controller.set_favorite_project(str(beta), True)
|
||||
controller.resolve_project(str(alpha))
|
||||
restarted = WebUIWorkspaceController(
|
||||
session_manager=None, default_workspace=default, default_restrict_to_workspace=True,
|
||||
)
|
||||
payload = restarted.payload(can_change_project=True, can_use_full_access=False)
|
||||
assert [item["path"] for item in payload["favorite_projects"]] == [str(beta), str(alpha)]
|
||||
assert [item["path"] for item in payload["recent_projects"]] == [str(alpha)]
|
||||
assert payload["default_scope"]["project_path"] == str(default)
|
||||
assert payload["default_scope"]["access_mode"] == "restricted"
|
||||
beta.rmdir()
|
||||
assert restarted.set_favorite_project(str(beta), False) == [{"name": "alpha", "path": str(alpha)}]
|
||||
with pytest.raises(WorkspaceScopeError, match="existing directory"):
|
||||
restarted.set_favorite_project(str(beta), True)
|
||||
@@ -0,0 +1,69 @@
|
||||
"""Project selection directory metadata contracts."""
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from nanobot.security.workspace_access import WorkspaceScopeError
|
||||
from nanobot.webui.workspace_browser import browse_workspace_directories
|
||||
|
||||
|
||||
def test_directory_browser_filters_folders_and_exposes_navigation(tmp_path: Path) -> None:
|
||||
(tmp_path / "Beta").mkdir()
|
||||
(tmp_path / "alpha").mkdir()
|
||||
(tmp_path / ".hidden").mkdir()
|
||||
(tmp_path / "secret.txt").write_text("file contents")
|
||||
result = browse_workspace_directories(str(tmp_path), default_workspace=tmp_path)
|
||||
assert [entry["name"] for entry in result["entries"]] == ["alpha", "Beta"]
|
||||
assert result["path"] == str(tmp_path)
|
||||
assert result["parent"] == str(tmp_path.parent)
|
||||
hidden = browse_workspace_directories(str(tmp_path), default_workspace=tmp_path, show_hidden=True, query="HID")
|
||||
assert hidden["entries"] == [{"name": ".hidden", "path": str(tmp_path / ".hidden")}]
|
||||
|
||||
|
||||
def test_directory_filter_reaches_folders_beyond_display_limit(tmp_path: Path) -> None:
|
||||
for index in range(501):
|
||||
(tmp_path / f"project-{index:03}").mkdir()
|
||||
result = browse_workspace_directories(str(tmp_path), default_workspace=tmp_path)
|
||||
assert len(result["entries"]) == 500
|
||||
assert result["truncated"] is True
|
||||
filtered = browse_workspace_directories(str(tmp_path), default_workspace=tmp_path, query="500")
|
||||
assert filtered["entries"] == [{"name": "project-500", "path": str(tmp_path / "project-500")}]
|
||||
assert filtered["truncated"] is False
|
||||
|
||||
|
||||
@pytest.mark.parametrize("path", ["relative/project", "invalid\0path"])
|
||||
def test_directory_browser_rejects_invalid_user_paths(tmp_path: Path, path: str) -> None:
|
||||
with pytest.raises(WorkspaceScopeError):
|
||||
browse_workspace_directories(path, default_workspace=tmp_path)
|
||||
|
||||
|
||||
def test_partial_address_lists_matching_parent_folders_and_exact_address_lists_children(tmp_path: Path) -> None:
|
||||
for name in ("workspace", "workspace-two", "other"):
|
||||
(tmp_path / name).mkdir()
|
||||
(tmp_path / "workspace" / "src").mkdir()
|
||||
(tmp_path / "worksp-file").write_text("not a folder")
|
||||
partial = browse_workspace_directories(str(tmp_path / "worksp"), default_workspace=tmp_path, allow_partial=True)
|
||||
assert partial["path"] == str(tmp_path)
|
||||
assert partial["partial"] is True
|
||||
assert [entry["name"] for entry in partial["entries"]] == ["workspace", "workspace-two"]
|
||||
exact = browse_workspace_directories(str(tmp_path / "workspace"), default_workspace=tmp_path, allow_partial=True)
|
||||
assert exact["partial"] is False
|
||||
assert exact["entries"] == [{"name": "src", "path": str(tmp_path / "workspace" / "src")}]
|
||||
missing = browse_workspace_directories(str(tmp_path / "missing"), default_workspace=tmp_path, allow_partial=True)
|
||||
assert missing["partial"] is True
|
||||
assert missing["entries"] == []
|
||||
with pytest.raises(WorkspaceScopeError):
|
||||
browse_workspace_directories(str(tmp_path / "worksp"), default_workspace=tmp_path)
|
||||
|
||||
|
||||
def test_partial_address_matches_before_display_limit_and_explicit_hidden_prefix(tmp_path: Path) -> None:
|
||||
for index in range(501):
|
||||
(tmp_path / f"a-workspace-{index:03}").mkdir()
|
||||
(tmp_path / "workspace").mkdir()
|
||||
(tmp_path / ".private").mkdir()
|
||||
result = browse_workspace_directories(str(tmp_path / "worksp"), default_workspace=tmp_path, allow_partial=True)
|
||||
assert result["entries"] == [{"name": "workspace", "path": str(tmp_path / "workspace")}]
|
||||
assert result["truncated"] is False
|
||||
hidden = browse_workspace_directories(str(tmp_path / ".priv"), default_workspace=tmp_path, allow_partial=True)
|
||||
assert hidden["entries"] == [{"name": ".private", "path": str(tmp_path / ".private")}]
|
||||
@@ -115,6 +115,8 @@ import type {
|
||||
WebUIIngressLimits,
|
||||
WorkspaceScopePayload,
|
||||
WorkspacesPayload,
|
||||
ProjectDirectory,
|
||||
WorkspaceDirectoriesPayload,
|
||||
} from "@/lib/types";
|
||||
import {
|
||||
logoFallbackUrls,
|
||||
@@ -236,11 +238,16 @@ interface ThreadComposerProps {
|
||||
goalState?: GoalStateWsPayload;
|
||||
workspaceScope?: WorkspaceScopePayload | null;
|
||||
workspaceControlsHidden?: boolean;
|
||||
workspacePickerLayoutAnchor?: HTMLElement | null;
|
||||
workspaceDefaultScope?: WorkspaceScopePayload | null;
|
||||
workspaceControls?: WorkspacesPayload["controls"] | null;
|
||||
workspaceScopeDisabled?: boolean;
|
||||
workspaceError?: string | null;
|
||||
onPickWorkspaceFolder?: () => Promise<string | null>;
|
||||
onFavoriteWorkspaceProject?: (path: string, pinned: boolean) => Promise<ProjectDirectory[]>;
|
||||
onResolveWorkspaceProject?: (path: string) => Promise<ProjectDirectory>;
|
||||
onLoadWorkspaceProjects?: () => Promise<WorkspacesPayload>;
|
||||
onBrowseWorkspaceDirectories?: (path: string, query: string, showHidden: boolean) => Promise<WorkspaceDirectoriesPayload>;
|
||||
onWorkspaceScopeChange?: (scope: WorkspaceScopePayload) => void;
|
||||
pendingQueueKey?: string | null;
|
||||
draftKey?: string;
|
||||
@@ -958,11 +965,16 @@ export function ThreadComposer({
|
||||
goalState,
|
||||
workspaceScope = null,
|
||||
workspaceControlsHidden = false,
|
||||
workspacePickerLayoutAnchor,
|
||||
workspaceDefaultScope = null,
|
||||
workspaceControls = null,
|
||||
workspaceScopeDisabled = false,
|
||||
workspaceError = null,
|
||||
onPickWorkspaceFolder,
|
||||
onLoadWorkspaceProjects,
|
||||
onResolveWorkspaceProject,
|
||||
onFavoriteWorkspaceProject,
|
||||
onBrowseWorkspaceDirectories,
|
||||
onWorkspaceScopeChange,
|
||||
pendingQueueKey = null,
|
||||
draftKey,
|
||||
@@ -2315,7 +2327,10 @@ export function ThreadComposer({
|
||||
);
|
||||
|
||||
const attachButtonDisabled = interactionDisabled || full;
|
||||
const showVoiceButton = Boolean(onTranscribeAudio);
|
||||
const showVoiceButton = Boolean(onTranscribeAudio) && (
|
||||
voiceRecorder.state !== "idle"
|
||||
|| (!hasComposerContent && images.length === 0 && !isStreaming && !modelNeedsSetup)
|
||||
);
|
||||
const voiceRecordingStatusLabel = t("thread.composer.voice.recordingStatus", {
|
||||
time: voiceRecorder.elapsedLabel,
|
||||
defaultValue: `Recording ${voiceRecorder.elapsedLabel}`,
|
||||
@@ -2369,6 +2384,23 @@ export function ThreadComposer({
|
||||
onChange={onWorkspaceScopeChange}
|
||||
/>
|
||||
) : null;
|
||||
const workspaceControl = showProjectPicker ? (
|
||||
<WorkspaceProjectPicker
|
||||
layoutAnchor={workspacePickerLayoutAnchor}
|
||||
isHero={isHero}
|
||||
disabled={interactionDisabled || workspaceScopeDisabled}
|
||||
scope={workspaceScope}
|
||||
defaultScope={workspaceDefaultScope}
|
||||
controls={workspaceControls}
|
||||
error={workspaceError}
|
||||
onPickFolder={onPickWorkspaceFolder}
|
||||
onFavoriteProject={onFavoriteWorkspaceProject}
|
||||
onResolveProject={onResolveWorkspaceProject}
|
||||
onLoadProjects={onLoadWorkspaceProjects}
|
||||
onBrowseDirectories={onBrowseWorkspaceDirectories}
|
||||
onChange={onWorkspaceScopeChange}
|
||||
/>
|
||||
) : null;
|
||||
const modelControl = modelLabel && !voiceRecorder.isRecording ? (
|
||||
<ModelPresetBadge
|
||||
label={modelLabel}
|
||||
@@ -2633,7 +2665,7 @@ export function ThreadComposer({
|
||||
isHero
|
||||
? cn(
|
||||
"gap-x-1.5 px-3 sm:px-4",
|
||||
showProjectPicker ? "pb-1.5" : "pb-3.5",
|
||||
showProjectPicker && compactControls ? "pb-1.5" : "pb-3.5",
|
||||
)
|
||||
: "gap-x-2 px-2.5 pb-2 sm:px-3",
|
||||
)}
|
||||
@@ -2660,13 +2692,13 @@ export function ThreadComposer({
|
||||
aria-label={t("thread.composer.attachImage")}
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
className={cn(
|
||||
"thread-composer-action thread-composer-round-action touch-target rounded-xl text-muted-foreground hover:text-foreground",
|
||||
"thread-composer-action thread-composer-round-action touch-target shrink-0 rounded-xl text-muted-foreground hover:text-foreground",
|
||||
isHero
|
||||
? "h-8 w-8"
|
||||
: "h-9 w-9",
|
||||
)}
|
||||
>
|
||||
<AttachIcon className={cn(isHero ? "h-[18px] w-[18px]" : "h-4 w-4")} />
|
||||
<AttachIcon className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
{voiceRecorder.isRecording ? (
|
||||
<VoiceRecordingMeter
|
||||
@@ -2676,7 +2708,12 @@ export function ThreadComposer({
|
||||
isHero={isHero}
|
||||
levels={voiceRecorder.levels}
|
||||
/>
|
||||
) : compactControls ? modelControl : accessControl}
|
||||
) : compactControls ? modelControl : (
|
||||
<div className="thread-composer-workspace-group flex min-w-0 items-center gap-0.5">
|
||||
{workspaceControl}
|
||||
{accessControl}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div
|
||||
className={cn(
|
||||
@@ -2686,37 +2723,61 @@ export function ThreadComposer({
|
||||
>
|
||||
{!compactControls ? modelControl : null}
|
||||
{!compactControls ? usageControl : null}
|
||||
{showVoiceButton ? (
|
||||
<TooltipProvider>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
type="button"
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
disabled={voiceRecorder.buttonDisabled}
|
||||
aria-label={voiceButtonLabel}
|
||||
aria-keyshortcuts={VOICE_SHORTCUT_ARIA}
|
||||
onPointerDown={voiceRecorder.beginPress}
|
||||
onPointerUp={voiceRecorder.endPress}
|
||||
onPointerCancel={voiceRecorder.endPress}
|
||||
onClick={voiceRecorder.handleClick}
|
||||
className={cn(
|
||||
"thread-composer-action touch-target rounded-xl border border-transparent text-muted-foreground hover:text-foreground",
|
||||
isHero ? "h-8 w-8" : "h-9 w-9",
|
||||
voiceRecorder.isRecording &&
|
||||
"bg-red-500 text-white hover:text-white",
|
||||
)}
|
||||
>
|
||||
{voiceRecorder.state === "transcribing" ? (
|
||||
<Loader2 className={cn(isHero ? "h-4 w-4" : "h-4 w-4", "animate-spin")} />
|
||||
<TooltipProvider>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
type={showVoiceButton || showStopButton || modelNeedsSetup ? "button" : "submit"}
|
||||
size="icon"
|
||||
disabled={showVoiceButton ? voiceRecorder.buttonDisabled : showStopButton ? interactionDisabled : !canSend && !canOpenModelSettings}
|
||||
aria-label={
|
||||
showVoiceButton
|
||||
? voiceButtonLabel
|
||||
: showStopButton
|
||||
? t("thread.composer.stop")
|
||||
: modelNeedsSetup
|
||||
? t("thread.composer.configureModel", { defaultValue: "Configure model" })
|
||||
: t("thread.composer.send")
|
||||
}
|
||||
aria-keyshortcuts={showVoiceButton ? VOICE_SHORTCUT_ARIA : undefined}
|
||||
onPointerDown={showVoiceButton ? voiceRecorder.beginPress : undefined}
|
||||
onPointerUp={showVoiceButton ? voiceRecorder.endPress : undefined}
|
||||
onPointerCancel={showVoiceButton ? voiceRecorder.endPress : undefined}
|
||||
onClickCapture={event => {
|
||||
if (!voiceRecorder.consumeSuppressedClick()) return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
}}
|
||||
onClick={showVoiceButton ? voiceRecorder.handleClick : showStopButton ? handleStop : modelNeedsSetup ? onModelBadgeClick : undefined}
|
||||
className={cn(
|
||||
"thread-composer-action thread-composer-round-action touch-target rounded-full",
|
||||
showStopButton && !showVoiceButton
|
||||
? "border border-border/70 bg-card text-foreground/85 hover:text-foreground disabled:text-muted-foreground/50"
|
||||
: "border border-foreground bg-foreground text-background disabled:border-foreground disabled:bg-foreground disabled:text-background",
|
||||
showVoiceButton && voiceRecorder.isRecording && "border-red-500 bg-red-500 text-white hover:bg-red-500 hover:text-white",
|
||||
isHero ? "h-8 w-8" : "h-9 w-9",
|
||||
)}
|
||||
>
|
||||
{showVoiceButton ? (
|
||||
voiceRecorder.state === "transcribing" ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
) : voiceRecorder.isRecording ? (
|
||||
<StopIcon className={cn(isHero ? "h-3.5 w-3.5" : "h-3.5 w-3.5")} fill="currentColor" />
|
||||
<StopIcon className="h-3.5 w-3.5" fill="currentColor" />
|
||||
) : (
|
||||
<VoiceIcon className={cn(isHero ? "h-4 w-4" : "h-4 w-4")} />
|
||||
)}
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<VoiceIcon className="h-4 w-4" />
|
||||
)
|
||||
) : showStopButton ? (
|
||||
<StopIcon className={cn("fill-current stroke-current", isHero ? "h-3 w-3" : "h-3.5 w-3.5")} />
|
||||
) : modelNeedsSetup ? (
|
||||
<ModelsIcon className="h-4 w-4" />
|
||||
) : canSend || !isStreaming ? (
|
||||
<ArrowUp className="h-4 w-4" />
|
||||
) : (
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
)}
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
{showVoiceButton ? (
|
||||
<TooltipContent
|
||||
side="top"
|
||||
align="center"
|
||||
@@ -2724,49 +2785,17 @@ export function ThreadComposer({
|
||||
>
|
||||
<span>{voiceButtonTooltip}</span>
|
||||
{voiceRecorder.state === "idle" ? (
|
||||
<kbd className="rounded-full bg-muted px-2 py-0.5 font-sans text-[12px] font-semibold leading-none text-muted-foreground dark:bg-white/10 dark:text-white/80">
|
||||
<kbd className="rounded-full bg-muted px-2 py-0.5 font-sans text-[12px] font-semibold leading-none text-muted-foreground dark:bg-white/10">
|
||||
{voiceShortcutLabel}
|
||||
</kbd>
|
||||
) : null}
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
) : null}
|
||||
<Button
|
||||
type={showStopButton || modelNeedsSetup ? "button" : "submit"}
|
||||
size="icon"
|
||||
disabled={showStopButton ? interactionDisabled : !canSend && !canOpenModelSettings}
|
||||
aria-label={
|
||||
showStopButton
|
||||
? t("thread.composer.stop")
|
||||
: modelNeedsSetup
|
||||
? t("thread.composer.configureModel", { defaultValue: "Configure model" })
|
||||
: t("thread.composer.send")
|
||||
}
|
||||
onClick={showStopButton ? handleStop : modelNeedsSetup ? onModelBadgeClick : undefined}
|
||||
className={cn(
|
||||
"thread-composer-action thread-composer-round-action touch-target rounded-full",
|
||||
showStopButton
|
||||
? "border border-border/70 bg-card text-foreground/85 hover:text-foreground disabled:text-muted-foreground/50"
|
||||
: isHero
|
||||
? "border border-foreground bg-foreground text-background disabled:border-foreground disabled:bg-foreground disabled:text-background"
|
||||
: "border border-foreground bg-foreground text-background disabled:border-foreground disabled:bg-foreground disabled:text-background",
|
||||
isHero ? "h-8 w-8" : "h-9 w-9",
|
||||
)}
|
||||
>
|
||||
{showStopButton ? (
|
||||
<StopIcon className={cn("fill-current stroke-current", isHero ? "h-3 w-3" : "h-3.5 w-3.5")} />
|
||||
) : modelNeedsSetup ? (
|
||||
<ModelsIcon className="h-4 w-4" />
|
||||
) : canSend || !isStreaming ? (
|
||||
<ArrowUp className={cn(isHero ? "h-4 w-4" : "h-4 w-4")} />
|
||||
) : (
|
||||
<Loader2 className={cn(isHero ? "h-4 w-4" : "h-4 w-4", "animate-spin")} />
|
||||
)}
|
||||
</Button>
|
||||
) : null}
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
</div>
|
||||
</div>
|
||||
{projectPickerAvailable ? (
|
||||
{compactControls && projectPickerAvailable ? (
|
||||
<div
|
||||
className="inline-disclosure"
|
||||
data-composer-workspace-drawer=""
|
||||
@@ -2774,25 +2803,17 @@ export function ThreadComposer({
|
||||
aria-hidden={showProjectPicker ? undefined : true}
|
||||
>
|
||||
<div className="inline-disclosure-clip">
|
||||
<div className="inline-disclosure-content">
|
||||
<WorkspaceProjectPicker
|
||||
isHero={isHero}
|
||||
disabled={interactionDisabled || workspaceScopeDisabled || !showProjectPicker}
|
||||
scope={workspaceScope}
|
||||
defaultScope={workspaceDefaultScope}
|
||||
controls={workspaceControls}
|
||||
error={workspaceError}
|
||||
onPickFolder={onPickWorkspaceFolder}
|
||||
onChange={onWorkspaceScopeChange}
|
||||
/>
|
||||
<div className="inline-disclosure-content thread-composer-workspace-row flex min-w-0 items-center justify-between gap-2 rounded-b-[28px] bg-muted/45 px-3 py-1.5 dark:bg-white/[0.045] sm:px-4">
|
||||
{workspaceControl}
|
||||
<div className="ml-auto flex min-w-0 justify-end">{accessControl}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
{compactControls ? (
|
||||
<div className="thread-composer-meta mx-auto flex w-full max-w-[58rem] items-center justify-between gap-2 px-2">
|
||||
{accessControl}
|
||||
{compactControls && (!projectPickerAvailable || usageControl) ? (
|
||||
<div className="thread-composer-meta mx-auto flex w-full max-w-[58rem] items-center justify-between gap-2 px-3">
|
||||
{!projectPickerAvailable ? accessControl : null}
|
||||
<div className="ml-auto">{usageControl}</div>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
@@ -41,6 +41,8 @@ import {
|
||||
fetchInstalledCliApps,
|
||||
fetchMcpPresets,
|
||||
fetchSettings,
|
||||
fetchWorkspaces,
|
||||
fetchWorkspaceDirectories,
|
||||
fetchWebuiThreadTraceDetail,
|
||||
listSlashCommands,
|
||||
} from "@/lib/api";
|
||||
@@ -66,6 +68,7 @@ import type {
|
||||
UIMessage,
|
||||
WorkspaceScopePayload,
|
||||
WorkspacesPayload,
|
||||
ProjectDirectory,
|
||||
} from "@/lib/types";
|
||||
import { projectThreadEvents } from "@/lib/thread-event-projection";
|
||||
import { projectWebuiThreadMessages } from "@/lib/thread-display-projection";
|
||||
@@ -707,6 +710,23 @@ export function ThreadShell({
|
||||
);
|
||||
return typeof response.path === "string" ? response.path : null;
|
||||
}, [client]);
|
||||
const favoriteWorkspaceProject = useCallback(
|
||||
async (path: string, pinned: boolean) => {
|
||||
const response = await client.requestMutation<{ favorite_projects: ProjectDirectory[] }>("workspace.favorite", { path, pinned });
|
||||
return response.favorite_projects;
|
||||
},
|
||||
[client],
|
||||
);
|
||||
const resolveWorkspaceProject = useCallback(
|
||||
(path: string) => client.requestMutation<ProjectDirectory>("workspace.resolve_project", { path }),
|
||||
[client],
|
||||
);
|
||||
const loadWorkspaceProjects = useCallback(() => fetchWorkspaces(getToken()), [getToken]);
|
||||
const browseWorkspaceDirectories = useCallback(
|
||||
(path: string, query: string, showHidden: boolean, allowPartial = false) =>
|
||||
fetchWorkspaceDirectories(getToken(), path, query, showHidden, allowPartial),
|
||||
[getToken],
|
||||
);
|
||||
const [booting, setBooting] = useState(false);
|
||||
const [slashCommands, setSlashCommands] = useState<SlashCommand[]>([]);
|
||||
const [mentionCatalogRequestCount, setMentionCatalogRequestCount] = useState(0);
|
||||
@@ -756,6 +776,7 @@ export function ThreadShell({
|
||||
}, [draftKey]);
|
||||
const [composerFocusSignal, setComposerFocusSignal] = useState(0);
|
||||
const shellRef = useRef<HTMLElement | null>(null);
|
||||
const [conversationElement, setConversationElement] = useState<HTMLDivElement | null>(null);
|
||||
const composerSurfaceRef = useRef<HTMLDivElement | null>(null);
|
||||
const filePreviewWidthRef = useRef(FILE_PREVIEW_DEFAULT_WIDTH);
|
||||
const filePreviewCloseTimerRef = useRef<number | null>(null);
|
||||
@@ -1770,6 +1791,11 @@ export function ThreadShell({
|
||||
onStop={stop}
|
||||
onTranscribeAudio={transcribeAudio}
|
||||
goalState={currentGoalState}
|
||||
onFavoriteWorkspaceProject={favoriteWorkspaceProject}
|
||||
onResolveWorkspaceProject={resolveWorkspaceProject}
|
||||
onLoadWorkspaceProjects={loadWorkspaceProjects}
|
||||
workspacePickerLayoutAnchor={conversationElement}
|
||||
onBrowseWorkspaceDirectories={browseWorkspaceDirectories}
|
||||
workspaceScope={workspaceScope}
|
||||
workspaceControlsHidden={temporary}
|
||||
workspaceDefaultScope={workspaceDefaultScope}
|
||||
@@ -1824,6 +1850,11 @@ export function ThreadShell({
|
||||
surfaceRef={composerSurfaceRef}
|
||||
onTranscribeAudio={transcribeAudio}
|
||||
goalState={currentGoalState}
|
||||
onFavoriteWorkspaceProject={favoriteWorkspaceProject}
|
||||
onResolveWorkspaceProject={resolveWorkspaceProject}
|
||||
onLoadWorkspaceProjects={loadWorkspaceProjects}
|
||||
workspacePickerLayoutAnchor={conversationElement}
|
||||
onBrowseWorkspaceDirectories={browseWorkspaceDirectories}
|
||||
workspaceScope={workspaceScope}
|
||||
workspaceControlsHidden={temporary}
|
||||
workspaceDefaultScope={workspaceDefaultScope}
|
||||
@@ -1893,7 +1924,7 @@ export function ThreadShell({
|
||||
active={composerActive}
|
||||
enabled={!temporary && !!session?.key.startsWith("websocket:") && webuiCapabilities.includes("webui.subagents.v1")}>
|
||||
<section ref={shellRef} data-preview-open={previewOpen || undefined} className="thread-preview-layout relative flex min-h-0 flex-1 overflow-hidden">
|
||||
<div className={cn(
|
||||
<div ref={setConversationElement} className={cn(
|
||||
"thread-conversation relative flex min-w-0 flex-1 flex-col overflow-hidden",
|
||||
headerPortalTarget === undefined && !hideHeader && "thread-workspace",
|
||||
)}>
|
||||
|
||||
@@ -1,60 +1,113 @@
|
||||
import {
|
||||
FullAccessIcon,
|
||||
WorkspaceIcon,
|
||||
RestrictedAccessIcon,
|
||||
} from "@/components/icons/product-icons";
|
||||
import { useCallback, useEffect, useId, useRef, useState } from "react";
|
||||
import { Check, ChevronDown } from "lucide-react";
|
||||
import { FullAccessIcon, WorkspaceIcon, RestrictedAccessIcon } from "@/components/icons/product-icons";
|
||||
import * as Menu from "@radix-ui/react-menu";
|
||||
import { useFloatingPortal } from "@/components/ui/floating-portal";
|
||||
import type { ReactElement } from "react";
|
||||
import { useCallback, useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from "react";
|
||||
import { Check, FolderOpen, Search } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { ToggleButton } from "@/components/settings/ToggleButton";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
floatingItemClassName,
|
||||
floatingItemFocusClassName,
|
||||
} from "@/components/ui/floating-surface";
|
||||
import { floatingItemClassName, floatingItemFocusClassName, floatingSurfaceClassName, floatingSurfaceMotionClassName } from "@/components/ui/floating-surface";
|
||||
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import {
|
||||
Popover,
|
||||
PopoverContent,
|
||||
PopoverTrigger,
|
||||
} from "@/components/ui/popover";
|
||||
import type {
|
||||
WorkspaceScopePayload,
|
||||
WorkspacesPayload,
|
||||
} from "@/lib/types";
|
||||
import { Dialog, DialogContent, DialogTrigger, DialogTitle, DialogDescription } from "@/components/ui/dialog";
|
||||
import type { WorkspaceScopePayload, ProjectDirectory, WorkspaceDirectoriesPayload, WorkspacesPayload } from "@/lib/types";
|
||||
import { createWorkspaceDirectoryCache } from "@/lib/workspace-directory-cache";
|
||||
import { getRuntimeHost } from "@/lib/runtime";
|
||||
import { cn } from "@/lib/utils";
|
||||
import {
|
||||
isAbsoluteWorkspacePath,
|
||||
projectNameFromPath,
|
||||
sameWorkspacePath,
|
||||
scopeWithAccessMode,
|
||||
selectedProjectScope,
|
||||
shortWorkspacePath,
|
||||
} from "@/lib/workspace";
|
||||
import { isAbsoluteWorkspacePath, projectNameFromPath, sameWorkspacePath, scopeWithAccessMode, workspacePathCompletionQuery, workspaceDirectoryPrefix, selectedProjectScope, type BrowseWorkspaceDirectories } from "@/lib/workspace";
|
||||
|
||||
function workspacePathPlaceholder(defaultWorkspacePath: string, macPlaceholder: string): string {
|
||||
const normalized = defaultWorkspacePath.trim().replace(/\\/g, "/");
|
||||
const windowsDrive = normalized.match(/^([A-Za-z]):\//)?.[1];
|
||||
if (windowsDrive) return `${windowsDrive.toUpperCase()}:\\path\\to\\project`;
|
||||
if (normalized.startsWith("/Users/")) return macPlaceholder;
|
||||
return "/home/name/project";
|
||||
function WorkspaceFolderMenu({ path, pinned, busy, onToggle, onRequestFocus, children }: {
|
||||
path: string; pinned: boolean; busy: boolean;
|
||||
onToggle: () => void; onRequestFocus: () => void; children: ReactElement;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const portal = useFloatingPortal();
|
||||
const [open, setOpen] = useState(false);
|
||||
const point = useRef({ x: 0, y: 0 });
|
||||
const anchor = useRef({ getBoundingClientRect: () => new DOMRect(point.current.x, point.current.y, 0, 0) });
|
||||
return (
|
||||
<Menu.Root open={open} onOpenChange={setOpen}>
|
||||
<Menu.Anchor virtualRef={anchor} />
|
||||
<div className="contents" onContextMenu={event => {
|
||||
event.preventDefault(); event.stopPropagation();
|
||||
point.current = { x: event.clientX, y: event.clientY }; setOpen(true);
|
||||
}} onKeyDown={event => {
|
||||
if (event.key !== "ContextMenu" && !(event.key === "F10" && event.shiftKey)) return;
|
||||
event.preventDefault(); event.stopPropagation();
|
||||
const bounds = (event.target as HTMLElement).getBoundingClientRect();
|
||||
point.current = { x: bounds.left, y: bounds.bottom }; setOpen(true);
|
||||
}}>{children}</div>
|
||||
<Menu.Portal container={portal ?? undefined}>
|
||||
<Menu.Content align="start" sideOffset={4} collisionPadding={12}
|
||||
className={cn(floatingSurfaceClassName, floatingSurfaceMotionClassName, "min-w-40 rounded-control p-1")}
|
||||
onContextMenu={event => { event.preventDefault(); event.stopPropagation(); }}
|
||||
onCloseAutoFocus={event => { event.preventDefault(); onRequestFocus(); }}>
|
||||
<Menu.Item disabled={busy} onSelect={onToggle}
|
||||
className={cn(floatingItemClassName, floatingItemFocusClassName, "cursor-default data-[disabled]:pointer-events-none data-[disabled]:opacity-50")}>
|
||||
{t(pinned ? "workspace.picker.unpin" : "workspace.picker.pin", { name: projectNameFromPath(path) })}
|
||||
</Menu.Item>
|
||||
</Menu.Content>
|
||||
</Menu.Portal>
|
||||
</Menu.Root>
|
||||
);
|
||||
}
|
||||
|
||||
export function WorkspaceProjectPicker({
|
||||
isHero,
|
||||
compact = false,
|
||||
connected = false,
|
||||
disabled,
|
||||
scope,
|
||||
defaultScope,
|
||||
controls,
|
||||
error,
|
||||
onPickFolder,
|
||||
onChange,
|
||||
}: {
|
||||
type PickerOption = ProjectDirectory & { kind: "directory" | "manual"; group: string };
|
||||
type PickerColumn = { path: string; options: PickerOption[]; selectedPath: string | null; hidden: boolean };
|
||||
|
||||
function WorkspacePickerTooltip({ label, children }: { label: string; children: ReactElement }) {
|
||||
return (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>{children}</TooltipTrigger>
|
||||
<TooltipContent className="max-w-[min(28rem,calc(100vw-2rem))] whitespace-pre-line break-all">{label}</TooltipContent>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
|
||||
function WorkspaceDirectorySkeleton() {
|
||||
const { t } = useTranslation();
|
||||
const viewportRef = useRef<HTMLDivElement>(null);
|
||||
const [rows, setRows] = useState(1);
|
||||
useLayoutEffect(() => {
|
||||
const viewport = viewportRef.current;
|
||||
if (!viewport) return;
|
||||
const measure = () => setRows(Math.max(1, Math.ceil(viewport.clientHeight / 44)));
|
||||
measure();
|
||||
const observer = new ResizeObserver(measure);
|
||||
observer.observe(viewport);
|
||||
return () => observer.disconnect();
|
||||
}, []);
|
||||
const widths = ["64%", "78%", "52%", "70%", "60%", "74%"];
|
||||
return (
|
||||
<div ref={viewportRef} role="status" aria-label={t("workspace.picker.loading")} className="workspace-directory-loading h-full">
|
||||
<span className="sr-only">{t("workspace.picker.loading")}</span>
|
||||
<div aria-hidden="true">
|
||||
{Array.from({ length: rows }, (_, index) => (
|
||||
<div key={index} className="flex h-11 items-center px-3 py-2">
|
||||
<span className="h-3.5 rounded-control bg-foreground/[0.055]" style={{ width: widths[index % widths.length] }} />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function WorkspacePickerPath({ path }: { path: string }) {
|
||||
const parts = workspacePathCompletionQuery(path);
|
||||
return (
|
||||
<WorkspacePickerTooltip label={path}>
|
||||
<span className="flex min-w-0 flex-1 text-[13px]">
|
||||
<span className="min-w-0 truncate">{parts?.path ?? path}</span>
|
||||
{parts?.query && <span className="max-w-[65%] shrink-0 truncate">{parts.query}</span>}
|
||||
</span>
|
||||
</WorkspacePickerTooltip>
|
||||
);
|
||||
}
|
||||
|
||||
export function WorkspaceProjectPicker({ isHero, connected = false, disabled, scope, defaultScope, controls, error, onPickFolder, onLoadProjects, onResolveProject, onFavoriteProject, onBrowseDirectories, layoutAnchor, onChange }: {
|
||||
layoutAnchor?: HTMLElement | null;
|
||||
isHero: boolean;
|
||||
compact?: boolean;
|
||||
connected?: boolean;
|
||||
disabled?: boolean;
|
||||
scope: WorkspaceScopePayload | null;
|
||||
@@ -62,236 +115,369 @@ export function WorkspaceProjectPicker({
|
||||
controls: WorkspacesPayload["controls"] | null;
|
||||
error?: string | null;
|
||||
onPickFolder?: () => Promise<string | null>;
|
||||
onResolveProject?: (path: string) => Promise<ProjectDirectory>;
|
||||
onLoadProjects?: () => Promise<WorkspacesPayload>;
|
||||
onFavoriteProject?: (path: string, pinned: boolean) => Promise<ProjectDirectory[]>;
|
||||
onBrowseDirectories?: BrowseWorkspaceDirectories;
|
||||
onChange?: (scope: WorkspaceScopePayload) => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [pathDraft, setPathDraft] = useState("");
|
||||
const [basePath, setBasePath] = useState(scope?.project_path ?? defaultScope?.project_path ?? "");
|
||||
const [catalog, setCatalog] = useState<WorkspacesPayload | null>(null);
|
||||
const [directory, setDirectory] = useState<WorkspaceDirectoriesPayload | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [showHidden, setShowHidden] = useState(false);
|
||||
const [revision, setRevision] = useState(0);
|
||||
const [directoryError, setDirectoryError] = useState<string | null>(null);
|
||||
const [pathError, setPathError] = useState<string | null>(null);
|
||||
const [pickingFolder, setPickingFolder] = useState(false);
|
||||
const [favoriteBusy, setFavoriteBusy] = useState(false);
|
||||
const [activeIndex, setActiveIndex] = useState(0);
|
||||
const [activeColumn, setActiveColumn] = useState(0);
|
||||
const [highlightActive, setHighlightActive] = useState(false);
|
||||
const [previousColumns, setPreviousColumns] = useState<PickerColumn[]>([]);
|
||||
const columnsRef = useRef<HTMLDivElement | null>(null);
|
||||
const [columnsElement, setColumnsElement] = useState<HTMLDivElement | null>(null);
|
||||
const attachColumns = useCallback((element: HTMLDivElement | null) => {
|
||||
columnsRef.current = element;
|
||||
setColumnsElement(element);
|
||||
}, []);
|
||||
const [columnCapacity, setColumnCapacity] = useState(3);
|
||||
const visibleColumns = columnCapacity;
|
||||
const pickerSession = useRef(0);
|
||||
const completionRequest = useRef(0);
|
||||
const triggerRef = useRef<HTMLButtonElement>(null);
|
||||
const pathInputRef = useRef<HTMLInputElement>(null);
|
||||
const pathErrorId = useId();
|
||||
const keyboardInteraction = useRef(false);
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
const optionsId = useId();
|
||||
const errorId = useId();
|
||||
const currentProjectScope = selectedProjectScope(scope, defaultScope);
|
||||
const projectLabel = currentProjectScope
|
||||
? currentProjectScope.project_name || projectNameFromPath(currentProjectScope.project_path)
|
||||
: t("thread.composer.workspace.projectPlaceholder");
|
||||
const visible = isHero
|
||||
&& !!defaultScope
|
||||
&& !!onChange
|
||||
&& controls?.can_change_project !== false;
|
||||
const pickFolder = controls?.can_pick_folder
|
||||
? getRuntimeHost().pickFolder ?? onPickFolder
|
||||
: undefined;
|
||||
const nativeProjectPicker = !!pickFolder;
|
||||
const displayedScope = scope ?? defaultScope;
|
||||
const projectLabel = displayedScope?.project_name || (displayedScope ? projectNameFromPath(displayedScope.project_path) : t("thread.composer.workspace.projectPlaceholder"));
|
||||
const visible = isHero && !!defaultScope && !!onChange && controls?.can_change_project !== false;
|
||||
const canBrowse = !!controls?.can_browse_directories && !!onBrowseDirectories;
|
||||
const directoryCache = useMemo(() => onBrowseDirectories ? createWorkspaceDirectoryCache(onBrowseDirectories) : null, [onBrowseDirectories, connected]);
|
||||
const pickFolder = controls?.can_pick_folder ? getRuntimeHost().pickFolder ?? onPickFolder : undefined;
|
||||
const absoluteDraft = isAbsoluteWorkspacePath(pathDraft);
|
||||
const requestedPath = absoluteDraft ? pathDraft.trim() : basePath;
|
||||
const folderQuery = absoluteDraft ? "" : pathDraft.trim();
|
||||
|
||||
useEffect(() => {
|
||||
pickerSession.current += 1;
|
||||
completionRequest.current += 1;
|
||||
if (!open) return;
|
||||
setPathDraft(currentProjectScope?.project_path ?? "");
|
||||
setPreviousColumns([]);
|
||||
setActiveColumn(0);
|
||||
setHighlightActive(false);
|
||||
const initialPath = scope?.project_path ?? defaultScope?.project_path ?? "";
|
||||
setPathDraft(canBrowse ? workspaceDirectoryPrefix(initialPath) : currentProjectScope?.project_path ?? "");
|
||||
setBasePath(initialPath);
|
||||
setDirectory(null);
|
||||
setActiveIndex(0);
|
||||
setPathError(null);
|
||||
}, [currentProjectScope?.project_path, open]);
|
||||
}, [scope?.project_path, defaultScope?.project_path, open, canBrowse]);
|
||||
|
||||
useEffect(() => {
|
||||
if (disabled) setOpen(false);
|
||||
}, [disabled]);
|
||||
if (!open || !onLoadProjects) return;
|
||||
let active = true;
|
||||
setCatalog(null);
|
||||
onLoadProjects().then(payload => { if (active) setCatalog(payload); }).catch((err: Error) => { if (active) setPathError(err.message); });
|
||||
return () => { active = false; };
|
||||
}, [onLoadProjects, open]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open || !canBrowse || !directoryCache) return;
|
||||
let active = true;
|
||||
const apply = (result: WorkspaceDirectoriesPayload) => {
|
||||
if (!active) return;
|
||||
setDirectory(result); setLoading(false);
|
||||
if (absoluteDraft) setBasePath(result.path);
|
||||
};
|
||||
setDirectoryError(null);
|
||||
const cached = directoryCache.peek(requestedPath, folderQuery, showHidden, true);
|
||||
if (cached) { apply(cached); return; }
|
||||
setLoading(true);
|
||||
setDirectory(null);
|
||||
const typing = !!folderQuery || absoluteDraft && !/[\\/]$/.test(pathDraft);
|
||||
const timer = window.setTimeout(() => {
|
||||
directoryCache.load(requestedPath, folderQuery, showHidden, true).then(apply).catch((err: Error) => {
|
||||
if (active) { setDirectoryError(err.message); setLoading(false); }
|
||||
});
|
||||
}, typing ? 150 : 0);
|
||||
return () => { active = false; window.clearTimeout(timer); };
|
||||
}, [open, canBrowse, directoryCache, requestedPath, folderQuery, showHidden, revision, absoluteDraft, pathDraft]);
|
||||
|
||||
useEffect(() => { if (disabled) setOpen(false); }, [disabled]);
|
||||
useEffect(() => {
|
||||
if (!error || !visible || disabled) return;
|
||||
const frame = window.requestAnimationFrame(() => triggerRef.current?.focus());
|
||||
return () => window.cancelAnimationFrame(frame);
|
||||
}, [disabled, error, visible]);
|
||||
useEffect(() => {
|
||||
if (!open || pickingFolder) return;
|
||||
const frame = window.requestAnimationFrame(() => inputRef.current?.focus());
|
||||
return () => window.cancelAnimationFrame(frame);
|
||||
}, [open, pickingFolder, pathError]);
|
||||
|
||||
const ancestorPaths = JSON.stringify(previousColumns.filter(column => column.hidden !== showHidden).map(column => column.path));
|
||||
const directoryGroup = t("workspace.picker.directories");
|
||||
useEffect(() => {
|
||||
if (!open || !canBrowse || !directoryCache) return;
|
||||
const paths: string[] = JSON.parse(ancestorPaths);
|
||||
if (!paths.length) return;
|
||||
let active = true;
|
||||
Promise.all(paths.map(path => directoryCache.load(path, "", showHidden, true))).then(results => {
|
||||
if (!active) return;
|
||||
setPreviousColumns(columns => columns.map(column => {
|
||||
const result = results.find(result => sameWorkspacePath(column.path, result.path));
|
||||
if (!result || !sameWorkspacePath(column.path, result.path)) return column;
|
||||
return { ...column, hidden: showHidden, options: result.entries.map(entry => ({ ...entry, kind: "directory" as const, group: directoryGroup })) };
|
||||
}));
|
||||
}).catch((err: Error) => { if (active) setPathError(err.message); });
|
||||
return () => { active = false; };
|
||||
}, [open, canBrowse, directoryCache, ancestorPaths, showHidden, directoryGroup]);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const viewport = columnsElement;
|
||||
if (!open || !viewport) return;
|
||||
const measure = () => setColumnCapacity(Math.max(1, Math.min(3, Math.floor(viewport.clientWidth / 240))));
|
||||
measure();
|
||||
const observer = new ResizeObserver(measure);
|
||||
observer.observe(viewport);
|
||||
return () => observer.disconnect();
|
||||
}, [open, columnsElement]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open || !error) return;
|
||||
const frame = window.requestAnimationFrame(() => pathInputRef.current?.focus());
|
||||
return () => window.cancelAnimationFrame(frame);
|
||||
}, [error, open]);
|
||||
const viewport = columnsElement;
|
||||
if (!open || !viewport) return;
|
||||
const onWheel = (event: WheelEvent) => {
|
||||
if (!event.shiftKey || event.ctrlKey || event.metaKey || viewport.scrollWidth <= viewport.clientWidth) return;
|
||||
const delta = event.deltaX || event.deltaY;
|
||||
if (!delta) return;
|
||||
event.preventDefault();
|
||||
const unit = event.deltaMode === 1 ? 16 : event.deltaMode === 2 ? viewport.clientWidth : 1;
|
||||
viewport.scrollLeft = Math.max(0, Math.min(viewport.scrollWidth - viewport.clientWidth, viewport.scrollLeft + delta * unit));
|
||||
};
|
||||
viewport.addEventListener("wheel", onWheel, { passive: false });
|
||||
return () => viewport.removeEventListener("wheel", onWheel);
|
||||
}, [open, columnsElement]);
|
||||
|
||||
const applyProjectPath = useCallback(
|
||||
(projectPath: string, projectName?: string) => {
|
||||
const base = scope ?? defaultScope;
|
||||
const trimmed = projectPath.trim();
|
||||
if (!base || !onChange) return;
|
||||
if (!trimmed || !isAbsoluteWorkspacePath(trimmed)) {
|
||||
setPathError(t("workspace.dialog.absolutePathRequired"));
|
||||
return;
|
||||
}
|
||||
const accessMode =
|
||||
controls?.can_use_full_access === false
|
||||
&& !sameWorkspacePath(trimmed, base.project_path)
|
||||
? "restricted"
|
||||
: base.access_mode;
|
||||
onChange({
|
||||
...base,
|
||||
project_path: trimmed,
|
||||
project_name: projectName || projectNameFromPath(trimmed),
|
||||
access_mode: accessMode,
|
||||
restrict_to_workspace: accessMode === "restricted",
|
||||
});
|
||||
setPathError(null);
|
||||
setOpen(false);
|
||||
},
|
||||
[controls?.can_use_full_access, defaultScope, onChange, scope, t],
|
||||
);
|
||||
useLayoutEffect(() => {
|
||||
const viewport = columnsRef.current;
|
||||
if (viewport) viewport.scrollLeft = viewport.clientWidth * Math.max(0, previousColumns.length + 1 - visibleColumns) / visibleColumns;
|
||||
}, [previousColumns.length, visibleColumns]);
|
||||
|
||||
const pickNativeFolder = useCallback(async () => {
|
||||
if (!pickFolder || disabled) return;
|
||||
setPickingFolder(true);
|
||||
try {
|
||||
const picked = await pickFolder();
|
||||
if (picked) applyProjectPath(picked);
|
||||
} catch (err) {
|
||||
setPathError((err as Error).message);
|
||||
} finally {
|
||||
setPickingFolder(false);
|
||||
}
|
||||
}, [applyProjectPath, disabled, pickFolder]);
|
||||
|
||||
if (!visible || !defaultScope || !onChange) return null;
|
||||
|
||||
if (nativeProjectPicker) {
|
||||
return (
|
||||
<div className={cn(
|
||||
compact
|
||||
? "inline-flex"
|
||||
: "flex min-w-0 items-center rounded-b-[28px] bg-muted/45 px-3 py-1.5 dark:bg-white/[0.045] sm:px-4",
|
||||
)}>
|
||||
<button
|
||||
ref={triggerRef}
|
||||
type="button"
|
||||
disabled={disabled || pickingFolder}
|
||||
aria-label={t("thread.composer.workspace.projectAria")}
|
||||
title={currentProjectScope?.project_path}
|
||||
onClick={() => void pickNativeFolder()}
|
||||
className={cn(
|
||||
compact
|
||||
? "thread-composer-action touch-target inline-flex h-8 w-8 items-center justify-center rounded-full border border-transparent"
|
||||
: "inline-flex h-7 max-w-full items-center gap-2 rounded-full px-2.5 sm:max-w-[18rem]",
|
||||
"text-[12px] font-medium text-muted-foreground/90 transition-colors hover:text-foreground disabled:pointer-events-none disabled:opacity-55",
|
||||
compact ? "hover:bg-muted/65" : "hover:bg-background/70",
|
||||
(connected || currentProjectScope) && "text-primary",
|
||||
)}
|
||||
>
|
||||
<WorkspaceIcon className={cn("shrink-0", compact ? "h-4 w-4" : "h-3.5 w-3.5")} />
|
||||
<span className={compact ? "sr-only" : "truncate"}>{projectLabel}</span>
|
||||
</button>
|
||||
{!compact && (pathError || error) ? (
|
||||
<span role="alert" className="ml-2 min-w-0 truncate text-[11.5px] font-medium text-destructive">
|
||||
{pathError ?? error}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
function changeDraft(value: string, resetColumns = true) {
|
||||
setHighlightActive(false);
|
||||
if (resetColumns) { setPreviousColumns([]); setActiveColumn(0); }
|
||||
completionRequest.current += 1;
|
||||
setPathDraft(value);
|
||||
const absolute = isAbsoluteWorkspacePath(value);
|
||||
const cached = directoryCache?.peek(absolute ? value.trim() : basePath, absolute ? "" : value.trim(), showHidden, true);
|
||||
setDirectory(cached ?? null);
|
||||
setLoading(canBrowse && !cached);
|
||||
setDirectoryError(null);
|
||||
setPathError(null);
|
||||
setActiveIndex(0);
|
||||
}
|
||||
function navigate(path: string, columnIndex = activeColumn) {
|
||||
const source = columns[columnIndex];
|
||||
const ancestors = columns.slice(0, columnIndex);
|
||||
if (source?.options.length) ancestors.push({ ...source, selectedPath: path });
|
||||
setPreviousColumns(ancestors);
|
||||
setActiveColumn(ancestors.length);
|
||||
setBasePath(path);
|
||||
changeDraft(workspaceDirectoryPrefix(path), false);
|
||||
setRevision(value => value + 1);
|
||||
inputRef.current?.focus();
|
||||
}
|
||||
|
||||
const applyProjectPath = useCallback((path: string, name?: string) => {
|
||||
const base = scope ?? defaultScope;
|
||||
const trimmed = path.trim();
|
||||
if (!base || !onChange) return;
|
||||
if (!trimmed || !isAbsoluteWorkspacePath(trimmed)) { setPathError(t("workspace.dialog.absolutePathRequired")); return; }
|
||||
const accessMode = controls?.can_use_full_access === false && !sameWorkspacePath(trimmed, base.project_path) ? "restricted" : base.access_mode;
|
||||
onChange({ ...base, project_path: trimmed, project_name: name || projectNameFromPath(trimmed), access_mode: accessMode, restrict_to_workspace: accessMode === "restricted" });
|
||||
setPathError(null);
|
||||
setOpen(false);
|
||||
}, [controls?.can_use_full_access, defaultScope, onChange, scope, t]);
|
||||
|
||||
const chooseProject = useCallback(async (path: string, name?: string) => {
|
||||
const session = pickerSession.current;
|
||||
if (!controls?.can_resolve_project || !onResolveProject) { applyProjectPath(path, name); return; }
|
||||
setPickingFolder(true); setPathError(null);
|
||||
try {
|
||||
const project = await onResolveProject(path);
|
||||
if (session === pickerSession.current) applyProjectPath(project.path, project.name);
|
||||
} catch (err) {
|
||||
if (session === pickerSession.current) setPathError((err as Error).message);
|
||||
} finally { setPickingFolder(false); }
|
||||
}, [applyProjectPath, controls?.can_resolve_project, onResolveProject]);
|
||||
|
||||
const pickNativeFolder = async () => {
|
||||
if (!pickFolder || disabled) return;
|
||||
const session = pickerSession.current;
|
||||
setPickingFolder(true);
|
||||
try {
|
||||
const path = await pickFolder();
|
||||
if (path && session === pickerSession.current) await chooseProject(path);
|
||||
} catch (err) {
|
||||
if (session === pickerSession.current) setPathError((err as Error).message);
|
||||
} finally { setPickingFolder(false); }
|
||||
};
|
||||
|
||||
const favorites = catalog?.favorite_projects ?? [];
|
||||
const canFavorite = !!catalog?.controls.can_manage_favorites && !!onFavoriteProject;
|
||||
const isFavorite = (path: string) => favorites.some(item => sameWorkspacePath(item.path, path));
|
||||
function folderMenu(path: string, children: ReactElement, enabled = true) {
|
||||
return canFavorite && enabled ? <WorkspaceFolderMenu path={path} pinned={isFavorite(path)} busy={favoriteBusy || pickingFolder}
|
||||
onToggle={() => void toggleFavorite(path)} onRequestFocus={() => inputRef.current?.focus()}>{children}</WorkspaceFolderMenu> : children;
|
||||
}
|
||||
|
||||
const toggleFavorite = async (path: string) => {
|
||||
if (!onFavoriteProject || favoriteBusy) return;
|
||||
const session = pickerSession.current;
|
||||
setFavoriteBusy(true); setPathError(null);
|
||||
try {
|
||||
const favorites = await onFavoriteProject(path, !isFavorite(path));
|
||||
if (session === pickerSession.current) setCatalog(current => current ? { ...current, favorite_projects: favorites } : current);
|
||||
} catch (err) {
|
||||
if (session === pickerSession.current) setPathError((err as Error).message);
|
||||
} finally { setFavoriteBusy(false); }
|
||||
};
|
||||
|
||||
const recentProjects = [
|
||||
...(catalog?.recent_projects ?? []),
|
||||
...(defaultScope ? [{ name: t("workspace.dialog.defaultProject"), path: defaultScope.project_path }] : []),
|
||||
...(currentProjectScope ? [{ name: projectLabel, path: currentProjectScope.project_path }] : []),
|
||||
].filter((project, index, all) => all.findIndex(item => sameWorkspacePath(item.path, project.path)) === index && !isFavorite(project.path));
|
||||
const options: PickerOption[] = directory && !loading
|
||||
? directory.entries.map(entry => ({ ...entry, kind: "directory", group: directoryGroup })) : [];
|
||||
if (!canBrowse && absoluteDraft) options.push({ name: t("workspace.dialog.usePath"), path: pathDraft.trim(), kind: "manual", group: directoryGroup });
|
||||
function openShortcut(project: ProjectDirectory) {
|
||||
if (!canBrowse) { void chooseProject(project.path, project.name); return; }
|
||||
setBasePath(project.path);
|
||||
changeDraft(workspaceDirectoryPrefix(project.path));
|
||||
setRevision(value => value + 1);
|
||||
inputRef.current?.focus();
|
||||
}
|
||||
const columns: PickerColumn[] = [...previousColumns, { path: directory?.path ?? requestedPath, options, selectedPath: null, hidden: showHidden }];
|
||||
const activeOptions = columns[activeColumn]?.options ?? options;
|
||||
const activeOption = Math.min(activeIndex, Math.max(activeOptions.length - 1, 0));
|
||||
const selectionPath = canBrowse ? (!loading && directory && !directory.partial ? directory.path : null) : (absoluteDraft ? pathDraft.trim() : scope?.project_path ?? defaultScope?.project_path);
|
||||
const displayedError = pathError ?? error ?? directoryError;
|
||||
|
||||
async function completePath() {
|
||||
const option = activeOptions[activeOption];
|
||||
if (option && option.kind !== "manual") { navigate(option.path); return; }
|
||||
if (!directoryCache || !canBrowse) return;
|
||||
const request = workspacePathCompletionQuery(pathDraft) ?? { path: basePath, query: pathDraft.trim() };
|
||||
const id = ++completionRequest.current;
|
||||
const session = pickerSession.current;
|
||||
try {
|
||||
const result = await directoryCache.load(request.path, request.query, showHidden || request.query.startsWith("."));
|
||||
if (id !== completionRequest.current || session !== pickerSession.current) return;
|
||||
const first = result.entries.find(entry => entry.name.toLocaleLowerCase().startsWith(request.query.toLocaleLowerCase()));
|
||||
if (first) navigate(first.path);
|
||||
} catch (err) {
|
||||
if (id === completionRequest.current && session === pickerSession.current) setPathError((err as Error).message);
|
||||
}
|
||||
}
|
||||
function activate(option: PickerOption, columnIndex = activeColumn) {
|
||||
if (pickingFolder) return;
|
||||
if (canBrowse && option.kind !== "manual") navigate(option.path, columnIndex);
|
||||
else void chooseProject(option.path, option.kind === "manual" ? undefined : option.name);
|
||||
}
|
||||
|
||||
if (!visible || !defaultScope || !onChange) return null;
|
||||
return (
|
||||
<div className={cn(
|
||||
compact
|
||||
? "inline-flex"
|
||||
: "flex min-w-0 items-center rounded-b-[28px] bg-muted/45 px-3 py-1.5 dark:bg-white/[0.045] sm:px-4",
|
||||
)}>
|
||||
<Popover open={open} onOpenChange={setOpen}>
|
||||
<PopoverTrigger asChild>
|
||||
<button
|
||||
ref={triggerRef}
|
||||
type="button"
|
||||
disabled={disabled}
|
||||
aria-label={t("thread.composer.workspace.projectAria")}
|
||||
className={cn(
|
||||
compact
|
||||
? "thread-composer-action touch-target inline-flex h-8 w-8 items-center justify-center rounded-full border border-transparent"
|
||||
: "inline-flex h-7 max-w-full items-center gap-2 rounded-full px-2.5 sm:max-w-[18rem]",
|
||||
"text-[12px] font-medium text-muted-foreground/90 transition-colors hover:text-foreground disabled:pointer-events-none disabled:opacity-55",
|
||||
compact ? "hover:bg-muted/65" : "hover:bg-background/70",
|
||||
(connected || currentProjectScope) && "text-primary",
|
||||
)}
|
||||
>
|
||||
<WorkspaceIcon className={cn("shrink-0", compact ? "h-4 w-4" : "h-3.5 w-3.5")} />
|
||||
<span className={compact ? "sr-only" : "truncate"}>{projectLabel}</span>
|
||||
{!compact ? (
|
||||
<ChevronDown className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
|
||||
) : null}
|
||||
</button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent
|
||||
align="start"
|
||||
side="bottom"
|
||||
sideOffset={8}
|
||||
className="w-[min(25rem,calc(100vw-2rem))]"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => applyProjectPath(defaultScope.project_path, defaultScope.project_name)}
|
||||
className={cn(
|
||||
floatingItemClassName,
|
||||
floatingItemFocusClassName,
|
||||
"flex min-h-[48px] w-full cursor-default gap-3 px-3 py-2.5 focus:bg-muted/55",
|
||||
)}
|
||||
>
|
||||
<span className="grid h-8 w-8 shrink-0 place-items-center rounded-control bg-muted text-foreground/80">
|
||||
<WorkspaceIcon className="h-4 w-4" />
|
||||
</span>
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="block truncate text-[13px] font-semibold text-foreground">
|
||||
{t("workspace.dialog.defaultProject")}
|
||||
</span>
|
||||
<span className="block truncate text-[11.5px] text-muted-foreground">
|
||||
{shortWorkspacePath(defaultScope.project_path)}
|
||||
</span>
|
||||
</span>
|
||||
{!currentProjectScope ? <Check className="h-4 w-4 text-foreground/80" /> : null}
|
||||
</button>
|
||||
<div className="my-1 h-px bg-border/45" />
|
||||
<div className="space-y-1.5 px-1.5 py-1.5">
|
||||
<form
|
||||
className="flex items-center gap-2"
|
||||
onSubmit={(event) => {
|
||||
<div className="inline-flex min-w-0 max-w-[11rem] shrink items-center">
|
||||
<TooltipProvider>
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<WorkspacePickerTooltip label={`${t("workspace.picker.switchDirectory")}\n${displayedScope?.project_path ?? ""}`}>
|
||||
<DialogTrigger asChild>
|
||||
<button ref={triggerRef} onPointerDown={() => { keyboardInteraction.current = false; }} onKeyDown={() => { keyboardInteraction.current = true; }} type="button" disabled={disabled} aria-label={t("workspace.picker.switchDirectory")} className="thread-composer-workspace touch-target inline-flex h-8 min-w-0 max-w-full items-center gap-1.5 rounded-control px-2 text-[12px] font-medium text-muted-foreground outline-none transition-colors hover:bg-foreground/[0.055] hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-55">
|
||||
<WorkspaceIcon className="h-3.5 w-3.5 shrink-0" />
|
||||
<span className="min-w-0 truncate">{projectLabel}</span>
|
||||
</button>
|
||||
</DialogTrigger>
|
||||
</WorkspacePickerTooltip>
|
||||
<DialogContent showCloseButton={false} layoutAnchor={layoutAnchor} centerInLayoutAnchor className="flex h-[min(34rem,calc(100%-2rem))] max-w-5xl flex-col gap-2 p-3" onOpenAutoFocus={event => { event.preventDefault(); inputRef.current?.focus(); }} onPointerDownCapture={() => { keyboardInteraction.current = false; }} onKeyDownCapture={() => { keyboardInteraction.current = true; }} onCloseAutoFocus={event => { if (!keyboardInteraction.current) event.preventDefault(); }}>
|
||||
<DialogTitle className="sr-only">{t("thread.composer.workspace.projectAria")}</DialogTitle>
|
||||
<DialogDescription className="sr-only">{t("workspace.picker.description")}</DialogDescription>
|
||||
<div className="relative flex shrink-0 items-center border-b border-border/50 px-2 pb-2">
|
||||
<span className="pointer-events-none absolute left-2 top-0 flex h-10 w-9 items-center justify-center"><Search className="h-4 w-4 text-muted-foreground" /></span>
|
||||
<Input ref={inputRef} role="combobox" aria-expanded={open} aria-controls={`${optionsId}-${activeColumn}`} aria-activedescendant={activeOptions.length ? `${optionsId}-${activeColumn}-${activeOption}` : undefined} aria-autocomplete="list" aria-busy={loading} value={pathDraft} disabled={disabled || pickingFolder} onChange={event => changeDraft(event.target.value)} placeholder={t("workspace.picker.search")} aria-label={t("workspace.dialog.manual")} aria-invalid={displayedError || directoryError ? true : undefined} aria-describedby={displayedError || directoryError ? errorId : undefined} className="h-10 min-w-0 flex-1 border-0 bg-transparent pl-10 pr-3 text-[14px] shadow-none focus-visible:ring-0" onKeyDown={event => {
|
||||
if (event.nativeEvent.isComposing) return;
|
||||
if ((event.key === "ArrowDown" || event.key === "ArrowUp") && !event.altKey && activeOptions.length) {
|
||||
event.preventDefault();
|
||||
applyProjectPath(pathDraft);
|
||||
}}
|
||||
>
|
||||
<Input
|
||||
ref={pathInputRef}
|
||||
value={pathDraft}
|
||||
disabled={disabled}
|
||||
onChange={(event) => {
|
||||
setPathDraft(event.target.value);
|
||||
setPathError(null);
|
||||
}}
|
||||
placeholder={workspacePathPlaceholder(
|
||||
defaultScope.project_path,
|
||||
t("workspace.dialog.manualPlaceholder"),
|
||||
)}
|
||||
aria-label={t("workspace.dialog.manual")}
|
||||
aria-invalid={pathError || error ? true : undefined}
|
||||
aria-describedby={pathError || error ? pathErrorId : undefined}
|
||||
className="h-9 rounded-full border-border/55 bg-background/80 px-3 text-[12.5px]"
|
||||
/>
|
||||
<Button
|
||||
type="submit"
|
||||
disabled={disabled || !pathDraft.trim()}
|
||||
className="h-9 shrink-0 rounded-full px-3 text-[12px]"
|
||||
>
|
||||
{t("workspace.dialog.usePath")}
|
||||
</Button>
|
||||
</form>
|
||||
{pathError || error ? (
|
||||
<p
|
||||
id={pathErrorId}
|
||||
role="alert"
|
||||
className="px-1 text-[11.5px] font-medium text-destructive"
|
||||
>
|
||||
{pathError ?? error}
|
||||
</p>
|
||||
) : null}
|
||||
const next = (activeOption + (event.key === "ArrowDown" ? 1 : -1) + activeOptions.length) % activeOptions.length;
|
||||
setHighlightActive(true); setActiveIndex(next); document.getElementById(`${optionsId}-${activeColumn}-${next}`)?.scrollIntoView({ block: "nearest" });
|
||||
} else if (event.key === "ArrowLeft" && activeColumn > 0 && event.currentTarget.selectionStart === 0 && event.currentTarget.selectionEnd === 0) {
|
||||
event.preventDefault();
|
||||
const parent = columns[activeColumn - 1];
|
||||
setHighlightActive(true);
|
||||
setActiveColumn(activeColumn - 1);
|
||||
setActiveIndex(Math.max(0, parent.options.findIndex(option => sameWorkspacePath(option.path, parent.selectedPath))));
|
||||
} else if ((event.key === "Tab" && !event.shiftKey && !!pathDraft.trim() || event.key === "ArrowRight" && !event.shiftKey && event.currentTarget.selectionStart === pathDraft.length && event.currentTarget.selectionEnd === pathDraft.length) && canBrowse) {
|
||||
event.preventDefault(); void completePath();
|
||||
} else if (event.key === "Enter") {
|
||||
event.preventDefault();
|
||||
if ((event.ctrlKey || event.metaKey) && selectionPath) void chooseProject(selectionPath);
|
||||
else if (activeOptions[activeOption]) activate(activeOptions[activeOption]);
|
||||
else if (selectionPath) void chooseProject(selectionPath);
|
||||
}
|
||||
}} />
|
||||
<Button size="sm" className="ml-2 shrink-0" disabled={!selectionPath || pickingFolder} onClick={() => selectionPath && void chooseProject(selectionPath)}>{t("workspace.picker.select")}</Button>
|
||||
</div>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
{!compact && error && !open ? (
|
||||
<span role="alert" className="ml-2 min-w-0 truncate text-[11.5px] font-medium text-destructive">
|
||||
{error}
|
||||
</span>
|
||||
) : null}
|
||||
<div className="flex min-h-0 flex-1 flex-col gap-2 sm:flex-row sm:gap-0">
|
||||
<nav aria-label={t("workspace.picker.shortcuts")} className="flex h-28 shrink-0 gap-2 overflow-auto border-b border-border/50 pb-2 sm:h-auto sm:w-48 sm:flex-col sm:gap-4 sm:border-b-0 sm:border-r sm:pr-2 sm:pb-0">
|
||||
{[{ label: t("workspace.picker.favorites"), projects: favorites, favorite: true }, { label: t("workspace.picker.recent"), projects: recentProjects, favorite: false }].map(section => (
|
||||
<section key={section.label} className="min-w-0 shrink-0 w-48 sm:w-auto">
|
||||
<h3 className="px-3 py-2 text-[11px] font-medium text-muted-foreground">{section.label}</h3>
|
||||
{section.projects.map(project => <div key={project.path}>{folderMenu(project.path,
|
||||
<button type="button" aria-label={project.path} aria-current={sameWorkspacePath(basePath, project.path) ? "location" : undefined}
|
||||
disabled={pickingFolder} onMouseDown={event => event.preventDefault()} onClick={() => openShortcut(project)}
|
||||
className={cn(floatingItemClassName, floatingItemFocusClassName, "flex min-h-11 w-full min-w-0 items-center gap-2 px-3 py-2 text-left hover:bg-foreground/[0.055] dark:hover:bg-white/[0.08]", sameWorkspacePath(basePath, project.path) && "bg-primary/10 text-primary")}>
|
||||
<WorkspacePickerPath path={project.path} />
|
||||
{sameWorkspacePath(project.path, scope?.project_path ?? defaultScope.project_path) && <Check className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />}
|
||||
</button>)}</div>)}
|
||||
{section.favorite && !favorites.length && canFavorite && <p className="px-3 text-[11px] leading-relaxed text-muted-foreground">{t("workspace.picker.favoriteHint")}</p>}
|
||||
</section>
|
||||
))}
|
||||
</nav>
|
||||
<div ref={attachColumns} data-workspace-columns className="flex flex-1 min-h-0 min-w-0 overflow-x-auto overscroll-x-contain">
|
||||
{columns.map((column, columnIndex) => <div key={columnIndex} className="contents">{folderMenu(column.path, <div id={`${optionsId}-${columnIndex}`} role="listbox" aria-label={column.path || t("thread.composer.workspace.projectAria")} aria-busy={columnIndex === previousColumns.length && loading} style={{ width: `${100 / visibleColumns}%` }} className={cn("min-w-0 shrink-0 overflow-x-hidden overflow-y-auto border-r border-transparent px-1 py-1", !!columns[columnIndex + 1]?.options.length && "border-border/50")}>
|
||||
{column.options.map((option, index) => <div key={`${option.kind}-${option.path}`} role="presentation">
|
||||
{folderMenu(option.path, <button id={`${optionsId}-${columnIndex}-${index}`} type="button" role="option" aria-label={option.path} aria-selected={sameWorkspacePath(column.selectedPath, option.path)} disabled={pickingFolder}
|
||||
onPointerMove={() => { setHighlightActive(false); setActiveColumn(columnIndex); setActiveIndex(index); }}
|
||||
onMouseDown={event => event.preventDefault()} onClick={() => activate(option, columnIndex)}
|
||||
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",
|
||||
sameWorkspacePath(column.selectedPath, option.path) && "bg-primary/10 text-primary font-medium hover:bg-primary/10",
|
||||
highlightActive && columnIndex === activeColumn && index === activeOption && "ring-1 ring-inset ring-ring")}>
|
||||
{option.kind === "directory" ? <WorkspacePickerTooltip label={option.path}><span className="min-w-0 flex-1 truncate text-[13px]">{option.name}</span></WorkspacePickerTooltip> : <WorkspacePickerPath path={option.path} />}
|
||||
{sameWorkspacePath(option.path, scope?.project_path ?? defaultScope.project_path) && <Check className="h-4 w-4 shrink-0 text-muted-foreground" />}
|
||||
</button>)}
|
||||
</div>)}
|
||||
{columnIndex === previousColumns.length && loading && <WorkspaceDirectorySkeleton />}
|
||||
{columnIndex === previousColumns.length && directory?.truncated && <p className="px-3 py-2 text-[11px] text-muted-foreground">{t("workspace.picker.truncated")}</p>}
|
||||
{columnIndex === previousColumns.length && displayedError && <p id={errorId} role="alert" className="px-3 py-2 text-[11.5px] text-destructive">{displayedError}</p>}
|
||||
</div>, columnIndex !== previousColumns.length || !!selectionPath)}</div>)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex shrink-0 items-center justify-between gap-2 px-2 pt-1">
|
||||
<div className="flex min-w-0 items-center gap-1">
|
||||
{canBrowse && <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>}
|
||||
{pickFolder && <WorkspacePickerTooltip label={t("workspace.picker.native")}><Button type="button" variant="ghost" size="icon" aria-label={t("workspace.picker.native")} disabled={pickingFolder} onClick={() => void pickNativeFolder()}><FolderOpen className="h-4 w-4" /></Button></WorkspacePickerTooltip>}
|
||||
</div>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</TooltipProvider>
|
||||
{error && !open && <span role="alert" className="ml-2 min-w-0 truncate text-[11.5px] font-medium text-destructive">{error}</span>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -321,32 +507,41 @@ export function WorkspaceAccessToggle({
|
||||
const accessAriaLabel = `${t("thread.composer.workspace.accessAria")}: ${accessLabel}`;
|
||||
|
||||
return (
|
||||
<Button
|
||||
type="button"
|
||||
variant={null}
|
||||
aria-label={accessAriaLabel}
|
||||
aria-pressed={isFull}
|
||||
disabled={disabled || !onChange || (!isFull && !canUseFullAccess)}
|
||||
onClick={() => onChange?.(scopeWithAccessMode(scope, isFull ? "restricted" : "full"))}
|
||||
className={cn(
|
||||
"settings-hover thread-composer-access touch-target min-w-0 max-w-[min(12.5rem,42vw)] whitespace-nowrap rounded-control border border-transparent font-semibold shadow-none",
|
||||
isHero ? "h-8 px-2.5 text-[12px]" : "h-9 px-3 text-[12.5px]",
|
||||
isFull
|
||||
? "bg-transparent text-orange-600 hover:text-orange-600 dark:text-orange-300 dark:hover:text-orange-300"
|
||||
: "bg-transparent text-muted-foreground hover:text-foreground",
|
||||
)}
|
||||
>
|
||||
{isFull ? (
|
||||
<FullAccessIcon className={cn("thread-composer-access-icon mr-1.5 shrink-0", isHero ? "h-3.5 w-3.5" : "h-3.5 w-3.5")} />
|
||||
) : (
|
||||
<RestrictedAccessIcon className={cn("thread-composer-access-icon mr-1.5 shrink-0", isHero ? "h-3.5 w-3.5" : "h-3.5 w-3.5")} />
|
||||
)}
|
||||
<span aria-hidden className="thread-composer-access-label-full min-w-0 truncate">
|
||||
{accessLabel}
|
||||
</span>
|
||||
<span aria-hidden className="thread-composer-access-label-short hidden min-w-0 truncate">
|
||||
{shortAccessLabel}
|
||||
</span>
|
||||
</Button>
|
||||
<TooltipProvider>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
type="button"
|
||||
variant={null}
|
||||
aria-label={accessAriaLabel}
|
||||
aria-pressed={isFull}
|
||||
disabled={disabled || !onChange || (!isFull && !canUseFullAccess)}
|
||||
onClick={() => onChange?.(scopeWithAccessMode(scope, isFull ? "restricted" : "full"))}
|
||||
className={cn(
|
||||
"settings-hover thread-composer-access touch-target min-w-0 max-w-[min(12.5rem,42vw)] whitespace-nowrap rounded-control border border-transparent font-semibold shadow-none",
|
||||
isHero ? "h-8 px-2.5 text-[12px]" : "h-9 px-3 text-[12.5px]",
|
||||
isFull
|
||||
? "bg-transparent text-orange-600 hover:text-orange-600 dark:text-orange-300 dark:hover:text-orange-300"
|
||||
: "bg-transparent text-muted-foreground hover:text-foreground",
|
||||
)}
|
||||
>
|
||||
{isFull ? (
|
||||
<FullAccessIcon className={cn("thread-composer-access-icon mr-1.5 shrink-0", isHero ? "h-3.5 w-3.5" : "h-3.5 w-3.5")} />
|
||||
) : (
|
||||
<RestrictedAccessIcon className={cn("thread-composer-access-icon mr-1.5 shrink-0", isHero ? "h-3.5 w-3.5" : "h-3.5 w-3.5")} />
|
||||
)}
|
||||
<span aria-hidden className="thread-composer-access-label-full min-w-0 truncate">
|
||||
{accessLabel}
|
||||
</span>
|
||||
<span aria-hidden className="thread-composer-access-label-short hidden min-w-0 truncate">
|
||||
{shortAccessLabel}
|
||||
</span>
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="top" className="w-max max-w-[calc(100vw-2rem)] text-left leading-relaxed">
|
||||
{t(isFull ? "thread.composer.workspace.fullDescription" : "thread.composer.workspace.defaultDescription")}
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
);
|
||||
}
|
||||
@@ -63,17 +63,20 @@ interface DialogContentProps
|
||||
extends React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content> {
|
||||
showCloseButton?: boolean;
|
||||
overlayClassName?: string;
|
||||
layoutAnchor?: HTMLElement | null;
|
||||
centerInLayoutAnchor?: boolean;
|
||||
placement?: "center" | "bottom";
|
||||
}
|
||||
|
||||
const DialogContent = React.forwardRef<
|
||||
React.ElementRef<typeof DialogPrimitive.Content>,
|
||||
DialogContentProps
|
||||
>(({ className, children, showCloseButton = true, overlayClassName, placement = "center", onOpenAutoFocus, ...props }, ref) => {
|
||||
>(({ className, children, showCloseButton = true, overlayClassName, placement = "center", layoutAnchor: explicitLayoutAnchor, centerInLayoutAnchor = false, onOpenAutoFocus, ...props }, ref) => {
|
||||
const { t } = useTranslation();
|
||||
const [container, setContainer] = React.useState<HTMLDivElement | null>(null);
|
||||
const contentNode = React.useRef<HTMLDivElement | null>(null);
|
||||
const layoutAnchor = React.useContext(DialogLayoutContext);
|
||||
const inheritedLayoutAnchor = React.useContext(DialogLayoutContext);
|
||||
const layoutAnchor = explicitLayoutAnchor ?? inheritedLayoutAnchor;
|
||||
const [layout, setLayout] = React.useState<React.CSSProperties>();
|
||||
React.useLayoutEffect(() => {
|
||||
if (!layoutAnchor || placement === "bottom") {
|
||||
@@ -85,17 +88,30 @@ const DialogContent = React.forwardRef<
|
||||
const style = getComputedStyle(layoutAnchor);
|
||||
const start = parseFloat(style.paddingLeft) || 0;
|
||||
const end = parseFloat(style.paddingRight) || 0;
|
||||
if (rect.width > 0) setLayout({ left: rect.left + start, right: "auto", width: rect.width - start - end, paddingInline: 0 });
|
||||
if (rect.width > 0) {
|
||||
const viewport = window.visualViewport;
|
||||
const top = Math.max(rect.top, viewport?.offsetTop ?? 0);
|
||||
const bottom = Math.min(rect.bottom, (viewport?.offsetTop ?? 0) + (viewport?.height ?? window.innerHeight));
|
||||
setLayout({
|
||||
left: rect.left + start, right: "auto", width: rect.width - start - end,
|
||||
paddingInline: centerInLayoutAnchor ? 16 : 0,
|
||||
...(centerInLayoutAnchor ? { top, height: Math.max(0, bottom - top) } : {}),
|
||||
});
|
||||
}
|
||||
};
|
||||
update();
|
||||
const observer = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(update);
|
||||
observer?.observe(layoutAnchor);
|
||||
window.addEventListener("resize", update);
|
||||
window.visualViewport?.addEventListener("resize", update);
|
||||
window.visualViewport?.addEventListener("scroll", update);
|
||||
return () => {
|
||||
observer?.disconnect();
|
||||
window.removeEventListener("resize", update);
|
||||
window.visualViewport?.removeEventListener("resize", update);
|
||||
window.visualViewport?.removeEventListener("scroll", update);
|
||||
};
|
||||
}, [layoutAnchor, placement]);
|
||||
}, [layoutAnchor, placement, centerInLayoutAnchor]);
|
||||
const contentRef = React.useCallback((node: HTMLDivElement | null) => {
|
||||
contentNode.current = node;
|
||||
setContainer(node);
|
||||
|
||||
+40
-1
@@ -1151,8 +1151,26 @@
|
||||
|
||||
.thread-composer-meta .thread-composer-access {
|
||||
max-width: 100%;
|
||||
padding-inline: 0.5rem;
|
||||
padding-inline: 0.625rem 0.5rem;
|
||||
}
|
||||
|
||||
.thread-composer-workspace-row {
|
||||
padding-inline: 0.75rem;
|
||||
}
|
||||
|
||||
.thread-composer-workspace-row .touch-target {
|
||||
min-height: 2.75rem;
|
||||
min-width: 2.75rem;
|
||||
}
|
||||
|
||||
.thread-composer-workspace-row .thread-composer-access {
|
||||
padding-inline-end: 0;
|
||||
}
|
||||
|
||||
.thread-composer-workspace-row .thread-composer-workspace {
|
||||
padding-inline-start: 0.6875rem;
|
||||
}
|
||||
|
||||
@media (forced-colors: active) {
|
||||
[data-workbench-move-handle]:focus-visible {
|
||||
outline: 2px solid CanvasText;
|
||||
@@ -1549,3 +1567,24 @@
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.sidebar-scrollbar::-webkit-scrollbar-thumb { transition: none; }
|
||||
}
|
||||
|
||||
.workspace-directory-loading {
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: no-preference) {
|
||||
.workspace-directory-loading::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
pointer-events: none;
|
||||
background: linear-gradient(90deg, transparent, hsl(var(--foreground) / 0.045), transparent);
|
||||
transform: translateX(-100%);
|
||||
animation: workspace-directory-shimmer 1.6s ease-in-out infinite;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes workspace-directory-shimmer {
|
||||
to { transform: translateX(100%); }
|
||||
}
|
||||
@@ -266,15 +266,18 @@ export function useVoiceRecorder({
|
||||
stopRecordingWhenReady();
|
||||
}, [stopRecordingWhenReady, suppressNextClick]);
|
||||
|
||||
const consumeSuppressedClick = useCallback(() => {
|
||||
if (!suppressClickRef.current) return false;
|
||||
clearSuppressClickTimer();
|
||||
suppressClickRef.current = false;
|
||||
return true;
|
||||
}, [clearSuppressClickTimer]);
|
||||
|
||||
const handleClick = useCallback(() => {
|
||||
if (suppressClickRef.current) {
|
||||
clearSuppressClickTimer();
|
||||
suppressClickRef.current = false;
|
||||
return;
|
||||
}
|
||||
if (consumeSuppressedClick()) return;
|
||||
if (state === "recording") stopRecording();
|
||||
else void startRecording();
|
||||
}, [clearSuppressClickTimer, startRecording, state, stopRecording]);
|
||||
}, [consumeSuppressedClick, startRecording, state, stopRecording]);
|
||||
|
||||
const beginShortcutHold = useCallback(() => {
|
||||
if (!onTranscribeAudio || disabled || state !== "idle" || shortcutActiveRef.current) return;
|
||||
@@ -308,6 +311,7 @@ export function useVoiceRecorder({
|
||||
beginShortcutHold,
|
||||
beginPress,
|
||||
buttonDisabled: disabled || state === "transcribing",
|
||||
consumeSuppressedClick,
|
||||
elapsedLabel: formatVoiceElapsed(elapsedMs),
|
||||
endShortcutHold,
|
||||
endPress,
|
||||
|
||||
@@ -1922,7 +1922,7 @@
|
||||
},
|
||||
"composer": {
|
||||
"placeholderThread": "Type your message…",
|
||||
"placeholderHero": "Ask anything...",
|
||||
"placeholderHero": "Describe what you’d like to do",
|
||||
"placeholderOpening": "Opening a new topic…",
|
||||
"placeholderStreaming": "Model is responding…",
|
||||
"inputAria": "Message input",
|
||||
@@ -2119,7 +2119,9 @@
|
||||
"default": "Default Permission",
|
||||
"defaultShort": "Default",
|
||||
"full": "Full Access",
|
||||
"fullShort": "Full"
|
||||
"fullShort": "Full",
|
||||
"defaultDescription": "File access and command execution are restricted to the current working directory.",
|
||||
"fullDescription": "Allows file access and command execution outside the current working directory."
|
||||
}
|
||||
},
|
||||
"scrollToBottom": "Scroll to bottom",
|
||||
@@ -2487,6 +2489,27 @@
|
||||
"manualPlaceholder": "/Users/name/project",
|
||||
"usePath": "Use Path",
|
||||
"absolutePathRequired": "Enter an absolute folder path on this machine."
|
||||
},
|
||||
"picker": {
|
||||
"favorites": "Favorites",
|
||||
"recent": "Recent projects",
|
||||
"directories": "Folders",
|
||||
"pin": "Pin {{name}}",
|
||||
"unpin": "Unpin {{name}}",
|
||||
"description": "Search recent projects or choose a folder on the connected host.",
|
||||
"emptyProjects": "No matching projects",
|
||||
"search": "Enter a path or filter this folder…",
|
||||
"shortcuts": "Saved locations",
|
||||
"favoriteHint": "Right-click a folder to add it here.",
|
||||
"native": "Use system folder picker…",
|
||||
"up": "Parent directory",
|
||||
"loading": "Loading folders…",
|
||||
"emptyDirectories": "No matching folders",
|
||||
"truncated": "Showing 500 folders. Continue typing the path to narrow the list.",
|
||||
"hidden": "Show hidden folders",
|
||||
"select": "Select",
|
||||
"switchDirectory": "Switch working directory",
|
||||
"selectDirectory": "Select this folder"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1723,7 +1723,7 @@
|
||||
},
|
||||
"composer": {
|
||||
"placeholderThread": "Escribe tu mensaje…",
|
||||
"placeholderHero": "¿Qué tienes en mente?",
|
||||
"placeholderHero": "Describe lo que quieres hacer",
|
||||
"placeholderOpening": "Abriendo un nuevo tema…",
|
||||
"placeholderStreaming": "El modelo está respondiendo…",
|
||||
"inputAria": "Entrada de mensaje",
|
||||
@@ -1920,7 +1920,9 @@
|
||||
"default": "Permiso predeterminado",
|
||||
"defaultShort": "Predeterm.",
|
||||
"full": "Acceso completo",
|
||||
"fullShort": "Completo"
|
||||
"fullShort": "Completo",
|
||||
"defaultDescription": "El acceso a archivos y la ejecución de comandos se limitan al directorio de trabajo actual.",
|
||||
"fullDescription": "Permite acceder a archivos y ejecutar comandos fuera del directorio de trabajo actual."
|
||||
}
|
||||
},
|
||||
"scrollToBottom": "Desplazarse al final",
|
||||
@@ -2288,6 +2290,27 @@
|
||||
"manualPlaceholder": "/Users/name/project",
|
||||
"usePath": "Usar ruta",
|
||||
"absolutePathRequired": "Introduce una ruta absoluta de carpeta en esta máquina."
|
||||
},
|
||||
"picker": {
|
||||
"favorites": "Favoritos",
|
||||
"recent": "Proyectos recientes",
|
||||
"directories": "Carpetas",
|
||||
"pin": "Fijar {{name}}",
|
||||
"unpin": "Desfijar {{name}}",
|
||||
"description": "Busca proyectos recientes o elige una carpeta en el equipo conectado.",
|
||||
"emptyProjects": "No hay proyectos coincidentes",
|
||||
"search": "Introduce una ruta o filtra esta carpeta…",
|
||||
"shortcuts": "Ubicaciones guardadas",
|
||||
"favoriteHint": "Haz clic derecho en una carpeta para añadirla aquí.",
|
||||
"native": "Usar el selector de carpetas del sistema…",
|
||||
"up": "Carpeta superior",
|
||||
"loading": "Cargando carpetas…",
|
||||
"emptyDirectories": "No hay carpetas coincidentes",
|
||||
"truncated": "Se muestran 500 carpetas. Sigue escribiendo la ruta para reducir la lista.",
|
||||
"hidden": "Mostrar carpetas ocultas",
|
||||
"select": "Seleccionar",
|
||||
"switchDirectory": "Cambiar directorio de trabajo",
|
||||
"selectDirectory": "Seleccionar esta carpeta"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1722,7 +1722,7 @@
|
||||
},
|
||||
"composer": {
|
||||
"placeholderThread": "Saisissez votre message…",
|
||||
"placeholderHero": "Qu’avez-vous en tête ?",
|
||||
"placeholderHero": "Décrivez ce que vous souhaitez faire",
|
||||
"placeholderOpening": "Ouverture d’un nouveau sujet…",
|
||||
"placeholderStreaming": "Le modèle est en train de répondre…",
|
||||
"inputAria": "Champ de message",
|
||||
@@ -1919,7 +1919,9 @@
|
||||
"default": "Autorisation par défaut",
|
||||
"defaultShort": "Par défaut",
|
||||
"full": "Accès complet",
|
||||
"fullShort": "Complet"
|
||||
"fullShort": "Complet",
|
||||
"defaultDescription": "L’accès aux fichiers et l’exécution des commandes sont limités au dossier de travail actuel.",
|
||||
"fullDescription": "Autorise l’accès aux fichiers et l’exécution des commandes hors du dossier de travail actuel."
|
||||
}
|
||||
},
|
||||
"scrollToBottom": "Faire défiler vers le bas",
|
||||
@@ -2287,6 +2289,27 @@
|
||||
"manualPlaceholder": "/Users/name/project",
|
||||
"usePath": "Utiliser le chemin",
|
||||
"absolutePathRequired": "Saisissez un chemin absolu de dossier sur cette machine."
|
||||
},
|
||||
"picker": {
|
||||
"favorites": "Favoris",
|
||||
"recent": "Projets récents",
|
||||
"directories": "Dossiers",
|
||||
"pin": "Épingler {{name}}",
|
||||
"unpin": "Désépingler {{name}}",
|
||||
"description": "Recherchez un projet récent ou choisissez un dossier sur l’hôte connecté.",
|
||||
"emptyProjects": "Aucun projet correspondant",
|
||||
"search": "Saisir un chemin ou filtrer ce dossier…",
|
||||
"shortcuts": "Emplacements enregistrés",
|
||||
"favoriteHint": "Faites un clic droit sur un dossier pour l’ajouter ici.",
|
||||
"native": "Utiliser le sélecteur de dossiers du système…",
|
||||
"up": "Dossier parent",
|
||||
"loading": "Chargement des dossiers…",
|
||||
"emptyDirectories": "Aucun dossier correspondant",
|
||||
"truncated": "500 dossiers affichés. Continuez à saisir le chemin pour réduire la liste.",
|
||||
"hidden": "Afficher les dossiers cachés",
|
||||
"select": "Choisir",
|
||||
"switchDirectory": "Changer de dossier de travail",
|
||||
"selectDirectory": "Sélectionner ce dossier"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1722,7 +1722,7 @@
|
||||
},
|
||||
"composer": {
|
||||
"placeholderThread": "Ketik pesan Anda…",
|
||||
"placeholderHero": "Apa yang sedang Anda pikirkan?",
|
||||
"placeholderHero": "Jelaskan apa yang ingin Anda lakukan",
|
||||
"placeholderOpening": "Membuka topik baru…",
|
||||
"placeholderStreaming": "Model sedang merespons…",
|
||||
"inputAria": "Input pesan",
|
||||
@@ -1919,7 +1919,9 @@
|
||||
"default": "Izin bawaan",
|
||||
"defaultShort": "Bawaan",
|
||||
"full": "Akses penuh",
|
||||
"fullShort": "Penuh"
|
||||
"fullShort": "Penuh",
|
||||
"defaultDescription": "Akses file dan eksekusi perintah dibatasi pada direktori kerja saat ini.",
|
||||
"fullDescription": "Mengizinkan akses file dan eksekusi perintah di luar direktori kerja saat ini."
|
||||
}
|
||||
},
|
||||
"scrollToBottom": "Gulir ke bawah",
|
||||
@@ -2287,6 +2289,27 @@
|
||||
"manualPlaceholder": "/Users/name/project",
|
||||
"usePath": "Gunakan path",
|
||||
"absolutePathRequired": "Masukkan path folder absolut di mesin ini."
|
||||
},
|
||||
"picker": {
|
||||
"favorites": "Favorit",
|
||||
"recent": "Proyek terbaru",
|
||||
"directories": "Folder",
|
||||
"pin": "Sematkan {{name}}",
|
||||
"unpin": "Lepas {{name}}",
|
||||
"description": "Cari proyek terbaru atau pilih folder di host yang terhubung.",
|
||||
"emptyProjects": "Tidak ada proyek yang cocok",
|
||||
"search": "Masukkan jalur atau filter folder ini…",
|
||||
"shortcuts": "Lokasi tersimpan",
|
||||
"favoriteHint": "Klik kanan folder untuk menambahkannya di sini.",
|
||||
"native": "Gunakan pemilih folder sistem…",
|
||||
"up": "Direktori induk",
|
||||
"loading": "Memuat folder…",
|
||||
"emptyDirectories": "Tidak ada folder yang cocok",
|
||||
"truncated": "Menampilkan 500 folder. Lanjutkan mengetik jalur untuk mempersempit daftar.",
|
||||
"hidden": "Tampilkan folder tersembunyi",
|
||||
"select": "Pilih",
|
||||
"switchDirectory": "Ganti direktori kerja",
|
||||
"selectDirectory": "Pilih folder ini"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1722,7 +1722,7 @@
|
||||
},
|
||||
"composer": {
|
||||
"placeholderThread": "メッセージを入力…",
|
||||
"placeholderHero": "何を考えていますか?",
|
||||
"placeholderHero": "やりたいことを入力",
|
||||
"placeholderOpening": "新しいトピックを開いています…",
|
||||
"placeholderStreaming": "モデルが応答しています…",
|
||||
"inputAria": "メッセージ入力欄",
|
||||
@@ -1919,7 +1919,9 @@
|
||||
"default": "既定の権限",
|
||||
"defaultShort": "既定",
|
||||
"full": "フルアクセス",
|
||||
"fullShort": "フル"
|
||||
"fullShort": "フル",
|
||||
"defaultDescription": "ファイルへのアクセスとコマンド実行は現在の作業ディレクトリ内に制限されます。",
|
||||
"fullDescription": "現在の作業ディレクトリ外でのファイルへのアクセスとコマンド実行を許可します。"
|
||||
}
|
||||
},
|
||||
"scrollToBottom": "一番下へスクロール",
|
||||
@@ -2287,6 +2289,27 @@
|
||||
"manualPlaceholder": "/Users/name/project",
|
||||
"usePath": "パスを使用",
|
||||
"absolutePathRequired": "このマシン上の絶対フォルダーパスを入力してください。"
|
||||
},
|
||||
"picker": {
|
||||
"favorites": "お気に入り",
|
||||
"recent": "最近のプロジェクト",
|
||||
"directories": "フォルダー",
|
||||
"pin": "{{name}} を固定",
|
||||
"unpin": "{{name}} の固定を解除",
|
||||
"description": "最近のプロジェクトを検索するか、接続先ホストのフォルダーを選択します。",
|
||||
"emptyProjects": "一致するプロジェクトはありません",
|
||||
"search": "パスを入力、または現在のフォルダを絞り込む…",
|
||||
"shortcuts": "保存した場所",
|
||||
"favoriteHint": "フォルダを右クリックして、お気に入りに追加します。",
|
||||
"native": "システムのフォルダー選択を使用…",
|
||||
"up": "親ディレクトリ",
|
||||
"loading": "フォルダーを読み込み中…",
|
||||
"emptyDirectories": "一致するフォルダーはありません",
|
||||
"truncated": "500 個のフォルダーを表示しています。パスの入力を続けて絞り込んでください。",
|
||||
"hidden": "隠しフォルダーを表示",
|
||||
"select": "選択",
|
||||
"switchDirectory": "作業ディレクトリを切り替える",
|
||||
"selectDirectory": "このフォルダーを選択"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1722,7 +1722,7 @@
|
||||
},
|
||||
"composer": {
|
||||
"placeholderThread": "메시지를 입력하세요…",
|
||||
"placeholderHero": "무슨 생각을 하고 있나요?",
|
||||
"placeholderHero": "하고 싶은 일을 알려 주세요",
|
||||
"placeholderOpening": "새 주제를 여는 중…",
|
||||
"placeholderStreaming": "모델이 응답 중입니다…",
|
||||
"inputAria": "메시지 입력",
|
||||
@@ -1919,7 +1919,9 @@
|
||||
"default": "기본 권한",
|
||||
"defaultShort": "기본",
|
||||
"full": "전체 접근 권한",
|
||||
"fullShort": "전체"
|
||||
"fullShort": "전체",
|
||||
"defaultDescription": "파일 접근과 명령 실행이 현재 작업 디렉터리 안으로 제한됩니다.",
|
||||
"fullDescription": "현재 작업 디렉터리 밖의 파일 접근과 명령 실행을 허용합니다."
|
||||
}
|
||||
},
|
||||
"scrollToBottom": "맨 아래로 스크롤",
|
||||
@@ -2287,6 +2289,27 @@
|
||||
"manualPlaceholder": "/Users/name/project",
|
||||
"usePath": "경로 사용",
|
||||
"absolutePathRequired": "이 머신의 절대 폴더 경로를 입력하세요."
|
||||
},
|
||||
"picker": {
|
||||
"favorites": "즐겨찾기",
|
||||
"recent": "최근 프로젝트",
|
||||
"directories": "폴더",
|
||||
"pin": "{{name}} 고정",
|
||||
"unpin": "{{name}} 고정 해제",
|
||||
"description": "최근 프로젝트를 검색하거나 연결된 호스트의 폴더를 선택하세요.",
|
||||
"emptyProjects": "일치하는 프로젝트가 없습니다",
|
||||
"search": "경로 입력 또는 현재 폴더 필터링…",
|
||||
"shortcuts": "저장된 위치",
|
||||
"favoriteHint": "폴더를 마우스 오른쪽 버튼으로 클릭하여 즐겨찾기에 추가하세요.",
|
||||
"native": "시스템 폴더 선택기 사용…",
|
||||
"up": "상위 디렉터리",
|
||||
"loading": "폴더 불러오는 중…",
|
||||
"emptyDirectories": "일치하는 폴더가 없습니다",
|
||||
"truncated": "폴더 500개를 표시합니다. 경로를 계속 입력하여 목록을 좁히세요.",
|
||||
"hidden": "숨김 폴더 표시",
|
||||
"select": "선택",
|
||||
"switchDirectory": "작업 디렉터리 변경",
|
||||
"selectDirectory": "이 폴더 선택"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1736,7 +1736,7 @@
|
||||
},
|
||||
"composer": {
|
||||
"placeholderThread": "Digite sua mensagem…",
|
||||
"placeholderHero": "Pergunte qualquer coisa...",
|
||||
"placeholderHero": "Descreva o que você quer fazer",
|
||||
"placeholderOpening": "Abrindo um novo tópico…",
|
||||
"placeholderStreaming": "O modelo está respondendo…",
|
||||
"inputAria": "Campo de mensagem",
|
||||
@@ -1933,7 +1933,9 @@
|
||||
"default": "Permissão padrão",
|
||||
"defaultShort": "Padrão",
|
||||
"full": "Acesso total",
|
||||
"fullShort": "Total"
|
||||
"fullShort": "Total",
|
||||
"defaultDescription": "O acesso a arquivos e a execução de comandos ficam restritos ao diretório de trabalho atual.",
|
||||
"fullDescription": "Permite acessar arquivos e executar comandos fora do diretório de trabalho atual."
|
||||
}
|
||||
},
|
||||
"scrollToBottom": "Rolar para o final",
|
||||
@@ -2301,6 +2303,27 @@
|
||||
"manualPlaceholder": "/Users/nome/projeto",
|
||||
"usePath": "Usar caminho",
|
||||
"absolutePathRequired": "Informe um caminho absoluto de pasta nesta máquina."
|
||||
},
|
||||
"picker": {
|
||||
"favorites": "Favoritos",
|
||||
"recent": "Projetos recentes",
|
||||
"directories": "Pastas",
|
||||
"pin": "Fixar {{name}}",
|
||||
"unpin": "Desafixar {{name}}",
|
||||
"description": "Pesquise projetos recentes ou escolha uma pasta no host conectado.",
|
||||
"emptyProjects": "Nenhum projeto correspondente",
|
||||
"search": "Digite um caminho ou filtre esta pasta…",
|
||||
"shortcuts": "Locais salvos",
|
||||
"favoriteHint": "Clique com o botão direito em uma pasta para adicioná-la aqui.",
|
||||
"native": "Usar o seletor de pastas do sistema…",
|
||||
"up": "Pasta superior",
|
||||
"loading": "Carregando pastas…",
|
||||
"emptyDirectories": "Nenhuma pasta correspondente",
|
||||
"truncated": "Exibindo 500 pastas. Continue digitando o caminho para reduzir a lista.",
|
||||
"hidden": "Mostrar pastas ocultas",
|
||||
"select": "Selecionar",
|
||||
"switchDirectory": "Alterar diretório de trabalho",
|
||||
"selectDirectory": "Selecionar esta pasta"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1722,7 +1722,7 @@
|
||||
},
|
||||
"composer": {
|
||||
"placeholderThread": "Nhập tin nhắn…",
|
||||
"placeholderHero": "Bạn đang nghĩ gì?",
|
||||
"placeholderHero": "Mô tả điều bạn muốn làm",
|
||||
"placeholderOpening": "Đang mở chủ đề mới…",
|
||||
"placeholderStreaming": "Mô hình đang trả lời…",
|
||||
"inputAria": "Ô nhập tin nhắn",
|
||||
@@ -1919,7 +1919,9 @@
|
||||
"default": "Quyền mặc định",
|
||||
"defaultShort": "Mặc định",
|
||||
"full": "Toàn quyền truy cập",
|
||||
"fullShort": "Toàn quyền"
|
||||
"fullShort": "Toàn quyền",
|
||||
"defaultDescription": "Quyền truy cập tệp và chạy lệnh bị giới hạn trong thư mục làm việc hiện tại.",
|
||||
"fullDescription": "Cho phép truy cập tệp và chạy lệnh ngoài thư mục làm việc hiện tại."
|
||||
}
|
||||
},
|
||||
"scrollToBottom": "Cuộn xuống cuối",
|
||||
@@ -2287,6 +2289,27 @@
|
||||
"manualPlaceholder": "/Users/name/project",
|
||||
"usePath": "Dùng đường dẫn",
|
||||
"absolutePathRequired": "Nhập đường dẫn thư mục tuyệt đối trên máy này."
|
||||
},
|
||||
"picker": {
|
||||
"favorites": "Yêu thích",
|
||||
"recent": "Dự án gần đây",
|
||||
"directories": "Thư mục",
|
||||
"pin": "Ghim {{name}}",
|
||||
"unpin": "Bỏ ghim {{name}}",
|
||||
"description": "Tìm dự án gần đây hoặc chọn thư mục trên máy chủ đang kết nối.",
|
||||
"emptyProjects": "Không có dự án phù hợp",
|
||||
"search": "Nhập đường dẫn hoặc lọc thư mục này…",
|
||||
"shortcuts": "Vị trí đã lưu",
|
||||
"favoriteHint": "Nhấp chuột phải vào thư mục để thêm vào đây.",
|
||||
"native": "Dùng bộ chọn thư mục hệ thống…",
|
||||
"up": "Thư mục cha",
|
||||
"loading": "Đang tải thư mục…",
|
||||
"emptyDirectories": "Không có thư mục phù hợp",
|
||||
"truncated": "Hiển thị 500 thư mục. Tiếp tục nhập đường dẫn để thu hẹp danh sách.",
|
||||
"hidden": "Hiện thư mục ẩn",
|
||||
"select": "Chọn",
|
||||
"switchDirectory": "Đổi thư mục làm việc",
|
||||
"selectDirectory": "Chọn thư mục này"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1922,7 +1922,7 @@
|
||||
},
|
||||
"composer": {
|
||||
"placeholderThread": "输入消息…",
|
||||
"placeholderHero": "问任何问题...",
|
||||
"placeholderHero": "描述你想做的事",
|
||||
"placeholderOpening": "正在打开新话题…",
|
||||
"placeholderStreaming": "模型正在回复…",
|
||||
"inputAria": "消息输入框",
|
||||
@@ -2118,8 +2118,10 @@
|
||||
"projectPlaceholder": "选择项目",
|
||||
"default": "默认权限",
|
||||
"defaultShort": "默认",
|
||||
"full": "完全访问权限",
|
||||
"fullShort": "完全"
|
||||
"full": "完全访问",
|
||||
"fullShort": "完全",
|
||||
"defaultDescription": "文件访问和命令执行限制在当前工作目录内。",
|
||||
"fullDescription": "允许访问当前工作目录外的文件,并在目录外执行命令。"
|
||||
}
|
||||
},
|
||||
"scrollToBottom": "滚动到底部",
|
||||
@@ -2487,6 +2489,27 @@
|
||||
"manualPlaceholder": "/Users/name/project",
|
||||
"usePath": "使用路径",
|
||||
"absolutePathRequired": "请输入这台机器上的绝对文件夹路径。"
|
||||
},
|
||||
"picker": {
|
||||
"favorites": "收藏",
|
||||
"recent": "最近项目",
|
||||
"directories": "文件夹",
|
||||
"pin": "收藏 {{name}}",
|
||||
"unpin": "取消收藏 {{name}}",
|
||||
"description": "搜索最近项目,或选择当前连接主机上的文件夹。",
|
||||
"emptyProjects": "没有匹配的项目",
|
||||
"search": "输入路径或筛选当前目录…",
|
||||
"shortcuts": "快捷位置",
|
||||
"favoriteHint": "右键点击文件夹,将它加入收藏。",
|
||||
"native": "使用系统文件夹选择器…",
|
||||
"up": "返回上级目录",
|
||||
"loading": "正在加载文件夹…",
|
||||
"emptyDirectories": "没有匹配的文件夹",
|
||||
"truncated": "已显示 500 个文件夹,继续输入路径以缩小范围。",
|
||||
"hidden": "显示隐藏文件夹",
|
||||
"select": "选择",
|
||||
"switchDirectory": "切换工作目录",
|
||||
"selectDirectory": "选择此文件夹"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1722,7 +1722,7 @@
|
||||
},
|
||||
"composer": {
|
||||
"placeholderThread": "輸入訊息…",
|
||||
"placeholderHero": "任何問題都可以問…",
|
||||
"placeholderHero": "描述你想做的事",
|
||||
"placeholderOpening": "正在開啟新話題…",
|
||||
"placeholderStreaming": "模型正在回覆…",
|
||||
"inputAria": "訊息輸入框",
|
||||
@@ -1919,7 +1919,9 @@
|
||||
"default": "預設權限",
|
||||
"defaultShort": "預設",
|
||||
"full": "完整存取權",
|
||||
"fullShort": "完整"
|
||||
"fullShort": "完整",
|
||||
"defaultDescription": "檔案存取與命令執行限制在目前工作目錄內。",
|
||||
"fullDescription": "允許存取目前工作目錄外的檔案,並在目錄外執行命令。"
|
||||
}
|
||||
},
|
||||
"scrollToBottom": "捲動到底部",
|
||||
@@ -2287,6 +2289,27 @@
|
||||
"manualPlaceholder": "/Users/name/project",
|
||||
"usePath": "使用路徑",
|
||||
"absolutePathRequired": "請輸入這台機器上的絕對資料夾路徑。"
|
||||
},
|
||||
"picker": {
|
||||
"favorites": "收藏",
|
||||
"recent": "最近專案",
|
||||
"directories": "資料夾",
|
||||
"pin": "收藏 {{name}}",
|
||||
"unpin": "取消收藏 {{name}}",
|
||||
"description": "搜尋最近專案,或選擇目前連線主機上的資料夾。",
|
||||
"emptyProjects": "沒有符合的專案",
|
||||
"search": "輸入路徑或篩選目前目錄…",
|
||||
"shortcuts": "快捷位置",
|
||||
"favoriteHint": "右鍵點擊資料夾,將它加入收藏。",
|
||||
"native": "使用系統資料夾選擇器…",
|
||||
"up": "返回上層目錄",
|
||||
"loading": "正在載入資料夾…",
|
||||
"emptyDirectories": "沒有符合的資料夾",
|
||||
"truncated": "已顯示 500 個資料夾,繼續輸入路徑以縮小範圍。",
|
||||
"hidden": "顯示隱藏資料夾",
|
||||
"select": "選擇",
|
||||
"switchDirectory": "切換工作目錄",
|
||||
"selectDirectory": "選擇此資料夾"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -46,6 +46,7 @@ import type {
|
||||
ThreadProjectionEvent,
|
||||
WebSearchSettingsUpdate,
|
||||
WorkspacesPayload,
|
||||
WorkspaceDirectoriesPayload,
|
||||
WebuiThreadPersistedPayload,
|
||||
WebuiThreadTraceDetailPayload,
|
||||
WorkspaceScopePayload,
|
||||
@@ -762,6 +763,22 @@ export async function fetchWorkspaces(
|
||||
);
|
||||
}
|
||||
|
||||
export async function fetchWorkspaceDirectories(
|
||||
token: string,
|
||||
path: string,
|
||||
query: string,
|
||||
showHidden: boolean,
|
||||
allowPartial = false,
|
||||
): Promise<WorkspaceDirectoriesPayload> {
|
||||
const params = new URLSearchParams({ path, q: query, hidden: showHidden ? "1" : "0", partial: allowPartial ? "1" : "0" });
|
||||
return request<WorkspaceDirectoriesPayload>(
|
||||
`/api/workspaces/directories?${params}`,
|
||||
token,
|
||||
undefined,
|
||||
API_READ_TIMEOUT_MS,
|
||||
);
|
||||
}
|
||||
|
||||
export async function fetchCliApps(
|
||||
token: string,
|
||||
base: string = "",
|
||||
|
||||
@@ -473,14 +473,35 @@ export interface WorkspaceScopePayload {
|
||||
};
|
||||
}
|
||||
|
||||
export interface ProjectDirectory {
|
||||
name: string;
|
||||
path: string;
|
||||
}
|
||||
|
||||
export interface WorkspaceDirectoriesPayload {
|
||||
partial?: boolean;
|
||||
path: string;
|
||||
parent: string | null;
|
||||
entries: ProjectDirectory[];
|
||||
truncated: boolean;
|
||||
host: string;
|
||||
platform: string;
|
||||
}
|
||||
|
||||
export interface WorkspacesPayload {
|
||||
schema_version: number;
|
||||
default_access_mode: WebuiDefaultAccessMode;
|
||||
default_scope: WorkspaceScopePayload;
|
||||
recent_projects?: ProjectDirectory[];
|
||||
favorite_projects?: ProjectDirectory[];
|
||||
host?: { name: string; platform: string };
|
||||
controls: {
|
||||
can_change_project: boolean;
|
||||
can_use_full_access: boolean;
|
||||
can_pick_folder?: boolean;
|
||||
can_browse_directories?: boolean;
|
||||
can_resolve_project?: boolean;
|
||||
can_manage_favorites?: boolean;
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import type { WorkspaceDirectoriesPayload } from "@/lib/types";
|
||||
import { normalizeWorkspacePath, type BrowseWorkspaceDirectories } from "@/lib/workspace";
|
||||
|
||||
const MAX_DIRECTORIES = 64;
|
||||
const DIRECTORY_TTL_MS = 30_000;
|
||||
|
||||
export function createWorkspaceDirectoryCache(browse: BrowseWorkspaceDirectories) {
|
||||
const entries = new Map<string, { result: WorkspaceDirectoriesPayload; expires: number }>();
|
||||
const pending = new Map<string, Promise<WorkspaceDirectoriesPayload>>();
|
||||
const keyFor = (path: string, query: string, hidden: boolean, partial = false) =>
|
||||
JSON.stringify([normalizeWorkspacePath(path.trim()), query, hidden, partial]);
|
||||
|
||||
function peek(path: string, query: string, hidden: boolean, partial = false) {
|
||||
const key = keyFor(path, query, hidden, partial);
|
||||
const entry = entries.get(key);
|
||||
if (!entry) return undefined;
|
||||
entries.delete(key);
|
||||
if (entry.expires <= Date.now()) return undefined;
|
||||
entries.set(key, entry);
|
||||
return entry.result;
|
||||
}
|
||||
|
||||
function load(path: string, query: string, hidden: boolean, partial = false) {
|
||||
const cached = peek(path, query, hidden, partial);
|
||||
if (cached) return Promise.resolve(cached);
|
||||
const key = keyFor(path, query, hidden, partial);
|
||||
const existing = pending.get(key);
|
||||
if (existing) return existing;
|
||||
const request = browse(path, query, hidden, partial).then(result => {
|
||||
entries.delete(key);
|
||||
entries.set(key, { result, expires: Date.now() + DIRECTORY_TTL_MS });
|
||||
if (entries.size > MAX_DIRECTORIES) entries.delete(entries.keys().next().value!);
|
||||
return result;
|
||||
}).finally(() => pending.delete(key));
|
||||
pending.set(key, request);
|
||||
return request;
|
||||
}
|
||||
|
||||
return { peek, load };
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { WorkspaceAccessMode, WorkspaceScopePayload } from "@/lib/types";
|
||||
import type { WorkspaceAccessMode, WorkspaceScopePayload, WorkspaceDirectoriesPayload } from "@/lib/types";
|
||||
|
||||
export function scopeWithAccessMode(
|
||||
scope: WorkspaceScopePayload,
|
||||
@@ -30,6 +30,7 @@ export function isAbsoluteWorkspacePath(path: string): boolean {
|
||||
|| trimmed.startsWith("~/")
|
||||
|| trimmed.startsWith("~\\")
|
||||
|| trimmed.startsWith("/")
|
||||
|| trimmed.startsWith("\\\\")
|
||||
|| /^[A-Za-z]:[\\/]/.test(trimmed)
|
||||
);
|
||||
}
|
||||
@@ -54,3 +55,18 @@ export function sameWorkspacePath(
|
||||
if (!a || !b) return false;
|
||||
return normalizeWorkspacePath(a) === normalizeWorkspacePath(b);
|
||||
}
|
||||
|
||||
export function workspacePathCompletionQuery(path: string): { path: string; query: string } | null {
|
||||
const draft = path.trim();
|
||||
if (!isAbsoluteWorkspacePath(draft)) return null;
|
||||
if (draft === "~") return { path: "~", query: "" };
|
||||
const parts = /^(.*[\\/])([^\\/]*)$/.exec(draft);
|
||||
return parts ? { path: parts[1], query: parts[2] } : null;
|
||||
}
|
||||
|
||||
export function workspaceDirectoryPrefix(path: string): string {
|
||||
const separator = path.includes("\\") ? "\\" : "/";
|
||||
return path.replace(/[\\/]+$/, "") + separator;
|
||||
}
|
||||
|
||||
export type BrowseWorkspaceDirectories = (path: string, query: string, showHidden: boolean, allowPartial?: boolean) => Promise<WorkspaceDirectoriesPayload>;
|
||||
@@ -1088,7 +1088,7 @@ describe("App layout", () => {
|
||||
expect(window.location.hash).toBe("#/new");
|
||||
// Let queued browser navigation events settle before sending the first message.
|
||||
await act(async () => { await new Promise((resolve) => setTimeout(resolve, 50)); });
|
||||
expect(await screen.findByRole("button", { name: "Choose project" })).toHaveTextContent("selected-project");
|
||||
expect(await screen.findByRole("button", { name: "Switch working directory" })).toHaveTextContent("selected-project");
|
||||
fireEvent.change(screen.getByLabelText("Message input"), {
|
||||
target: { value: "project topic" },
|
||||
});
|
||||
@@ -1113,7 +1113,7 @@ describe("App layout", () => {
|
||||
render(<App />);
|
||||
|
||||
await waitFor(() => expect(connectSpy).toHaveBeenCalled());
|
||||
expect(await screen.findByRole("button", { name: "Choose project" })).toBeInTheDocument();
|
||||
expect(await screen.findByRole("button", { name: "Switch working directory" })).toBeInTheDocument();
|
||||
act(() => {
|
||||
sessionUpdateHandlers.forEach((handler) => handler("selected-chat", "metadata", {
|
||||
project_path: "/tmp/selected-project",
|
||||
@@ -1124,7 +1124,7 @@ describe("App layout", () => {
|
||||
});
|
||||
fireEvent.click(screen.getByRole("button", { name: "Temporary chat" }));
|
||||
|
||||
expect(screen.queryByRole("button", { name: "Choose project" })).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole("button", { name: "Switch working directory" })).not.toBeInTheDocument();
|
||||
expect(screen.queryByText("Full Access")).not.toBeInTheDocument();
|
||||
fireEvent.change(screen.getByLabelText("Message input"), {
|
||||
target: { value: "temporary project check" },
|
||||
@@ -1161,11 +1161,11 @@ describe("App layout", () => {
|
||||
render(<App />);
|
||||
|
||||
await waitFor(() => expect(connectSpy).toHaveBeenCalled());
|
||||
fireEvent.click(await screen.findByRole("button", { name: "Choose project" }));
|
||||
fireEvent.click(await screen.findByRole("button", { name: "Switch working directory" }));
|
||||
fireEvent.change(await screen.findByLabelText("Paste path"), {
|
||||
target: { value: "C:\\missing-project" },
|
||||
});
|
||||
fireEvent.click(screen.getByRole("button", { name: "Use Path" }));
|
||||
fireEvent.click(screen.getByRole("button", { name: "Select" }));
|
||||
|
||||
const message = screen.getByLabelText("Message input");
|
||||
fireEvent.change(message, { target: { value: "keep this first message" } });
|
||||
@@ -1173,7 +1173,7 @@ describe("App layout", () => {
|
||||
|
||||
await waitFor(() => expect(createChatSpy).toHaveBeenCalledTimes(1));
|
||||
expect(message).toHaveValue("keep this first message");
|
||||
const projectButton = screen.getByRole("button", { name: "Choose project" });
|
||||
const projectButton = screen.getByRole("button", { name: "Switch working directory" });
|
||||
await waitFor(() => expect(projectButton).toHaveFocus());
|
||||
expect(screen.getByRole("alert")).toHaveTextContent(
|
||||
"The gateway rejected this project or access mode. Choose an existing project or a different access mode, then try again.",
|
||||
|
||||
@@ -866,6 +866,34 @@ describe("ThreadComposer", () => {
|
||||
expect(onPresetChange).toHaveBeenCalledWith("dflash");
|
||||
});
|
||||
|
||||
it("switches the same primary button between voice and send as the draft changes", () => {
|
||||
const onSend = vi.fn();
|
||||
render(<ThreadComposer onSend={onSend} onTranscribeAudio={vi.fn(async () => "voice")} />);
|
||||
const input = screen.getByRole("textbox");
|
||||
const action = screen.getByRole("button", { name: "Voice input" });
|
||||
expect(screen.queryByRole("button", { name: "Send message" })).not.toBeInTheDocument();
|
||||
fireEvent.change(input, { target: { value: " " } });
|
||||
expect(screen.getByRole("button", { name: "Voice input" })).toBe(action);
|
||||
fireEvent.change(input, { target: { value: "send this" } });
|
||||
expect(screen.getByRole("button", { name: "Send message" })).toBe(action);
|
||||
expect(screen.queryByRole("button", { name: "Voice input" })).not.toBeInTheDocument();
|
||||
fireEvent.click(action);
|
||||
expect(onSend).toHaveBeenCalledWith("send this", undefined, undefined);
|
||||
expect(screen.getByRole("button", { name: "Voice input" })).toBe(action);
|
||||
});
|
||||
|
||||
it("uses send for an attachment-only draft and restores voice after removal", async () => {
|
||||
mockBlobUrls();
|
||||
const { container } = render(<ThreadComposer onSend={vi.fn()} onTranscribeAudio={vi.fn(async () => "voice")} />);
|
||||
fireEvent.change(container.querySelector('input[type="file"]')!, {
|
||||
target: { files: [new File(["image"], "photo.png", { type: "image/png" })] },
|
||||
});
|
||||
await waitFor(() => expect(screen.getByRole("button", { name: "Send message" })).toBeEnabled());
|
||||
expect(screen.queryByRole("button", { name: "Voice input" })).not.toBeInTheDocument();
|
||||
fireEvent.click(screen.getByRole("button", { name: "Remove attachment" }));
|
||||
expect(screen.getByRole("button", { name: "Voice input" })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("transcribes voice input into the composer without sending", async () => {
|
||||
mockVoiceRecorder();
|
||||
const onSend = vi.fn();
|
||||
@@ -1106,10 +1134,11 @@ describe("ThreadComposer", () => {
|
||||
|
||||
it("ignores the delayed click emitted after a long-press voice recording", async () => {
|
||||
const { getUserMedia } = mockVoiceRecorder();
|
||||
const onSend = vi.fn();
|
||||
const onTranscribeAudio = vi.fn(async () => "held once");
|
||||
render(
|
||||
<ThreadComposer
|
||||
onSend={vi.fn()}
|
||||
onSend={onSend}
|
||||
onTranscribeAudio={onTranscribeAudio}
|
||||
placeholder="Type your message..."
|
||||
/>,
|
||||
@@ -1131,8 +1160,9 @@ describe("ThreadComposer", () => {
|
||||
await act(async () => {
|
||||
await new Promise((resolve) => setTimeout(resolve, 20));
|
||||
});
|
||||
fireEvent.click(screen.getByRole("button", { name: "Voice input" }));
|
||||
fireEvent.click(screen.getByRole("button", { name: "Send message" }));
|
||||
|
||||
expect(onSend).not.toHaveBeenCalled();
|
||||
expect(getUserMedia).toHaveBeenCalledTimes(1);
|
||||
expect(onTranscribeAudio).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
@@ -1153,7 +1183,8 @@ describe("ThreadComposer", () => {
|
||||
|
||||
const input = screen.getByLabelText("Message input");
|
||||
fireEvent.change(input, { target: { value: "draft" } });
|
||||
fireEvent.click(screen.getByRole("button", { name: "Voice input" }));
|
||||
fireEvent.keyDown(window, { key: "D", code: "KeyD", ctrlKey: true, shiftKey: true });
|
||||
expect(await screen.findByLabelText("Recording 0:00")).toBeInTheDocument();
|
||||
await waitForVoiceCapture();
|
||||
fireEvent.click(await screen.findByRole("button", { name: "Stop recording" }));
|
||||
|
||||
@@ -1342,6 +1373,19 @@ describe("ThreadComposer", () => {
|
||||
expect(screen.getByRole("progressbar", { name: "Context 50%" })).toBeVisible();
|
||||
});
|
||||
|
||||
it.each([
|
||||
["restricted", "Default Permission", "File access and command execution are restricted to the current working directory."],
|
||||
["full", "Full Access", "Allows file access and command execution outside the current working directory."],
|
||||
] as const)("explains %s workspace access on hover", async (mode, label, explanation) => {
|
||||
const user = userEvent.setup();
|
||||
render(<ThreadComposer onSend={vi.fn()} workspaceScope={{ project_path: "/tmp/project", project_name: "project", access_mode: mode, restrict_to_workspace: mode === "restricted" }} onWorkspaceScopeChange={vi.fn()} />);
|
||||
const access = screen.getByRole("button", { name: `Workspace access mode: ${label}` });
|
||||
expect(access).not.toHaveAttribute("title");
|
||||
await user.hover(access);
|
||||
expect(await screen.findByRole("tooltip")).toHaveTextContent(explanation);
|
||||
expect(access).toHaveAttribute("aria-describedby");
|
||||
});
|
||||
|
||||
it("toggles workspace access directly by click and keyboard", async () => {
|
||||
const user = userEvent.setup();
|
||||
const onWorkspaceScopeChange = vi.fn();
|
||||
@@ -1403,7 +1447,7 @@ describe("ThreadComposer", () => {
|
||||
expect(shortLabel).toHaveClass("hidden");
|
||||
});
|
||||
|
||||
it("keeps project selection as a compact composer dropdown", async () => {
|
||||
it("opens project selection in a searchable dialog", async () => {
|
||||
const user = userEvent.setup();
|
||||
const onWorkspaceScopeChange = vi.fn();
|
||||
const defaultScope = {
|
||||
@@ -1428,22 +1472,18 @@ describe("ThreadComposer", () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
await user.click(screen.getByRole("button", { name: "Choose project" }));
|
||||
await user.click(screen.getByRole("button", { name: "Switch working directory" }));
|
||||
|
||||
expect(await screen.findByRole("button", { name: /Default workspace/ })).toBeInTheDocument();
|
||||
expect(await screen.findByRole("button", { name: "/Users/test/.nanobot/workspace" })).toBeInTheDocument();
|
||||
expect(screen.getByRole("dialog")).toBeInTheDocument();
|
||||
|
||||
const input = screen.getByLabelText("Paste path");
|
||||
fireEvent.change(input, { target: { value: "relative/project" } });
|
||||
fireEvent.click(screen.getByRole("button", { name: "Use Path" }));
|
||||
|
||||
expect(screen.getByRole("alert")).toHaveTextContent(
|
||||
"Enter an absolute folder path on this machine.",
|
||||
);
|
||||
expect(screen.queryByRole("option", { name: "relative/project" })).not.toBeInTheDocument();
|
||||
expect(onWorkspaceScopeChange).not.toHaveBeenCalled();
|
||||
|
||||
fireEvent.change(input, { target: { value: "/Users/test/project-alpha" } });
|
||||
fireEvent.click(screen.getByRole("button", { name: "Use Path" }));
|
||||
fireEvent.click(screen.getByRole("option", { name: "/Users/test/project-alpha" }));
|
||||
|
||||
expect(onWorkspaceScopeChange).toHaveBeenCalledWith(expect.objectContaining({
|
||||
project_path: "/Users/test/project-alpha",
|
||||
@@ -1452,10 +1492,10 @@ describe("ThreadComposer", () => {
|
||||
restrict_to_workspace: false,
|
||||
}));
|
||||
|
||||
await user.click(screen.getByRole("button", { name: "Choose project" }));
|
||||
await user.click(screen.getByRole("button", { name: "Switch working directory" }));
|
||||
const reopenedInput = await screen.findByLabelText("Paste path");
|
||||
fireEvent.change(reopenedInput, { target: { value: "~/Pictures/Photos" } });
|
||||
fireEvent.click(screen.getByRole("button", { name: "Use Path" }));
|
||||
fireEvent.click(screen.getByRole("option", { name: "~/Pictures/Photos" }));
|
||||
|
||||
expect(onWorkspaceScopeChange).toHaveBeenLastCalledWith(expect.objectContaining({
|
||||
project_path: "~/Pictures/Photos",
|
||||
@@ -1467,10 +1507,12 @@ describe("ThreadComposer", () => {
|
||||
|
||||
it.each([
|
||||
["Windows", "D:\\Users\\test\\.nanobot\\workspace", "D:\\path\\to\\project"],
|
||||
["Windows UNC", "\\\\server\\share\\workspace", "\\\\server\\share\\project"],
|
||||
["macOS", "/Users/test/.nanobot/workspace", "/Users/name/project"],
|
||||
["Linux", "/home/test/.nanobot/workspace", "/home/name/project"],
|
||||
])("uses a %s path example for the project picker", async (_, projectPath, placeholder) => {
|
||||
])("accepts a %s project path", async (_, projectPath, selectedPath) => {
|
||||
const user = userEvent.setup();
|
||||
const onWorkspaceScopeChange = vi.fn();
|
||||
const defaultScope = {
|
||||
project_path: projectPath,
|
||||
project_name: "workspace",
|
||||
@@ -1486,16 +1528,18 @@ describe("ThreadComposer", () => {
|
||||
workspaceScope={defaultScope}
|
||||
workspaceDefaultScope={defaultScope}
|
||||
workspaceControls={{ can_change_project: true, can_use_full_access: true }}
|
||||
onWorkspaceScopeChange={vi.fn()}
|
||||
onWorkspaceScopeChange={onWorkspaceScopeChange}
|
||||
/>,
|
||||
);
|
||||
|
||||
await user.click(screen.getByRole("button", { name: "Choose project" }));
|
||||
await user.click(screen.getByRole("button", { name: "Switch working directory" }));
|
||||
|
||||
expect(await screen.findByLabelText("Paste path")).toHaveAttribute("placeholder", placeholder);
|
||||
fireEvent.change(await screen.findByLabelText("Paste path"), { target: { value: selectedPath } });
|
||||
fireEvent.keyDown(screen.getByLabelText("Paste path"), { key: "Enter" });
|
||||
expect(onWorkspaceScopeChange).toHaveBeenCalledWith(expect.objectContaining({ project_path: selectedPath }));
|
||||
});
|
||||
|
||||
it("slides project controls closed without offering a compact replacement", () => {
|
||||
it("groups the directory and access beside attachments and hides them with workspace controls", () => {
|
||||
const defaultScope = {
|
||||
project_path: "/Users/test/.nanobot/workspace",
|
||||
project_name: "workspace",
|
||||
@@ -1515,36 +1559,38 @@ describe("ThreadComposer", () => {
|
||||
/>
|
||||
);
|
||||
const { container, rerender } = render(composer(false));
|
||||
const drawer = container.querySelector("[data-composer-workspace-drawer]");
|
||||
|
||||
expect(drawer).toHaveClass("inline-disclosure");
|
||||
expect(drawer?.firstElementChild).toHaveClass("inline-disclosure-clip");
|
||||
expect(drawer?.firstElementChild?.firstElementChild).toHaveClass("inline-disclosure-content");
|
||||
expect(drawer).toHaveAttribute("data-state", "open");
|
||||
expect(drawer).not.toHaveAttribute("aria-hidden");
|
||||
expect(container.querySelector("[data-composer-workspace-compact]")).not.toBeInTheDocument();
|
||||
|
||||
const trigger = screen.getByRole("button", { name: "Switch working directory" });
|
||||
expect(trigger).toHaveTextContent("workspace");
|
||||
expect(trigger.closest(".thread-composer-footer-primary")).not.toBeNull();
|
||||
expect(trigger.closest(".thread-composer-workspace-group")).toContainElement(screen.getByRole("button", { name: "Workspace access mode: Full Access" }));
|
||||
expect(container.querySelector("[data-composer-workspace-drawer]")).not.toBeInTheDocument();
|
||||
rerender(composer(true));
|
||||
|
||||
expect(container.querySelector("[data-composer-workspace-drawer]")).toBe(drawer);
|
||||
expect(drawer).toHaveAttribute("data-state", "closed");
|
||||
expect(drawer).toHaveAttribute("aria-hidden", "true");
|
||||
expect(within(drawer as HTMLElement).getByRole("button", {
|
||||
hidden: true,
|
||||
name: "Choose project",
|
||||
})).toBeDisabled();
|
||||
expect(screen.queryByRole("button", { name: "Choose project" })).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole("button", {
|
||||
name: "Workspace access mode: Full Access",
|
||||
})).not.toBeInTheDocument();
|
||||
|
||||
expect(screen.queryByRole("button", { name: "Switch working directory" })).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole("button", { name: "Workspace access mode: Full Access" })).not.toBeInTheDocument();
|
||||
rerender(composer(false));
|
||||
expect(screen.getByRole("button", { name: "Switch working directory" })).toBeEnabled();
|
||||
});
|
||||
|
||||
expect(container.querySelector("[data-composer-workspace-drawer]")).toBe(drawer);
|
||||
expect(drawer).toHaveAttribute("data-state", "open");
|
||||
expect(within(drawer as HTMLElement).getByRole("button", {
|
||||
name: "Choose project",
|
||||
})).toBeEnabled();
|
||||
it("places the directory left and access right on narrow composers, moving them into the toolbar on desktop", () => {
|
||||
let width = 390;
|
||||
vi.spyOn(HTMLFormElement.prototype, "getBoundingClientRect").mockImplementation(() => rect({ width, height: 160 }));
|
||||
const defaultScope = { project_path: "/srv/workspace", project_name: "workspace", access_mode: "full" as const };
|
||||
const { container } = render(<ThreadComposer variant="hero" onSend={vi.fn()} workspaceScope={defaultScope}
|
||||
workspaceDefaultScope={defaultScope} workspaceControls={{ can_change_project: true }} onWorkspaceScopeChange={vi.fn()} />);
|
||||
const input = screen.getByRole("textbox");
|
||||
const row = container.querySelector(".thread-composer-workspace-row")!;
|
||||
const trigger = screen.getByRole("button", { name: "Switch working directory" });
|
||||
expect(row).toContainElement(trigger);
|
||||
expect(trigger.closest(".ml-auto")).toBeNull();
|
||||
const access = screen.getByRole("button", { name: "Workspace access mode: Full Access" });
|
||||
expect(row).toContainElement(access);
|
||||
expect(access.closest(".ml-auto")).not.toBeNull();
|
||||
width = 800;
|
||||
fireEvent(window, new Event("resize"));
|
||||
expect(screen.getByRole("button", { name: "Switch working directory" }).closest(".thread-composer-footer-primary")).not.toBeNull();
|
||||
expect(container.querySelector("[data-composer-workspace-drawer]")).not.toBeInTheDocument();
|
||||
expect(screen.getByRole("textbox")).toBe(input);
|
||||
expect(screen.getAllByRole("button", { name: "Switch working directory" })).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("uses the native folder picker for project selection on native host", async () => {
|
||||
@@ -1583,10 +1629,12 @@ describe("ThreadComposer", () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "Choose project" }));
|
||||
fireEvent.click(screen.getByRole("button", { name: "Switch working directory" }));
|
||||
|
||||
expect(screen.getByRole("dialog", { name: "Choose project" })).toBeInTheDocument();
|
||||
fireEvent.click(screen.getByRole("button", { name: "Use system folder picker…" }));
|
||||
await waitFor(() => expect(pickFolder).toHaveBeenCalled());
|
||||
expect(screen.queryByRole("button", { name: /Default workspace/ })).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole("dialog", { name: "Choose project" })).not.toBeInTheDocument();
|
||||
expect(onWorkspaceScopeChange).toHaveBeenCalledWith(expect.objectContaining({
|
||||
project_path: "/Users/test/native-project",
|
||||
project_name: "native-project",
|
||||
@@ -1628,7 +1676,7 @@ describe("ThreadComposer", () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
await user.click(screen.getByRole("button", { name: "Choose project" }));
|
||||
await user.click(screen.getByRole("button", { name: "Switch working directory" }));
|
||||
|
||||
expect(await screen.findByLabelText("Paste path")).toBeInTheDocument();
|
||||
expect(pickFolder).not.toHaveBeenCalled();
|
||||
@@ -1637,7 +1685,7 @@ describe("ThreadComposer", () => {
|
||||
fireEvent.change(screen.getByLabelText("Paste path"), {
|
||||
target: { value: "/srv/nas-project" },
|
||||
});
|
||||
fireEvent.click(screen.getByRole("button", { name: "Use Path" }));
|
||||
fireEvent.click(screen.getByRole("option", { name: "/srv/nas-project" }));
|
||||
|
||||
expect(onWorkspaceScopeChange).toHaveBeenCalledWith(expect.objectContaining({
|
||||
project_path: "/srv/nas-project",
|
||||
@@ -1673,8 +1721,10 @@ describe("ThreadComposer", () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "Choose project" }));
|
||||
fireEvent.click(screen.getByRole("button", { name: "Switch working directory" }));
|
||||
|
||||
expect(screen.getByRole("dialog", { name: "Choose project" })).toBeInTheDocument();
|
||||
fireEvent.click(screen.getByRole("button", { name: "Use system folder picker…" }));
|
||||
await waitFor(() => expect(pickFolder).toHaveBeenCalled());
|
||||
expect(screen.queryByLabelText("Paste path")).not.toBeInTheDocument();
|
||||
expect(onWorkspaceScopeChange).toHaveBeenCalledWith(expect.objectContaining({
|
||||
@@ -1706,9 +1756,9 @@ describe("ThreadComposer", () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
await user.click(screen.getByRole("button", { name: "Choose project" }));
|
||||
await user.click(screen.getByRole("button", { name: "Switch working directory" }));
|
||||
|
||||
expect(await screen.findByRole("button", { name: /Default workspace/ })).toBeInTheDocument();
|
||||
expect(await screen.findByRole("button", { name: "/Users/test/.nanobot/workspace" })).toBeInTheDocument();
|
||||
expect(screen.getByLabelText("Paste path")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
|
||||
@@ -1775,7 +1775,7 @@ describe("ThreadShell", () => {
|
||||
await waitFor(() => {
|
||||
expect(screen.queryByText("delete me cleanly")).not.toBeInTheDocument();
|
||||
});
|
||||
expect(screen.getByPlaceholderText("Ask anything...")).toBeInTheDocument();
|
||||
expect(screen.getByRole("textbox")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("creates a chat only when the blank landing sends a first message", async () => {
|
||||
@@ -2131,7 +2131,7 @@ describe("ThreadShell", () => {
|
||||
const greeting = screen.getByRole("heading", { level: 1, name: HERO_GREETING_PATTERN });
|
||||
expect(greeting).toHaveAttribute("data-testid", "hero-greeting");
|
||||
expect(greeting).toHaveClass("select-none", "whitespace-nowrap");
|
||||
expect(screen.getByPlaceholderText("Ask anything...")).toBeInTheDocument();
|
||||
expect(screen.getByRole("textbox")).toBeInTheDocument();
|
||||
expect(screen.queryByRole("button", { name: "Write code" })).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole("button", { name: "Create a project plan" })).not.toBeInTheDocument();
|
||||
});
|
||||
@@ -2191,9 +2191,10 @@ describe("ThreadShell", () => {
|
||||
|
||||
expect(screen.queryByText("old answer")).not.toBeInTheDocument();
|
||||
await waitFor(() =>
|
||||
expect(screen.getByPlaceholderText("Ask anything...")).toBeInTheDocument(),
|
||||
expect(screen.getByRole("textbox")).toBeInTheDocument(),
|
||||
);
|
||||
const input = screen.getByPlaceholderText("Ask anything...");
|
||||
const input = screen.getByRole("textbox");
|
||||
expect(input).toHaveAttribute("placeholder", "Describe what you’d like to do");
|
||||
expect(input.className).toContain("min-h-[78px]");
|
||||
expect(screen.queryByText("old answer")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { createWorkspaceDirectoryCache } from "@/lib/workspace-directory-cache";
|
||||
import type { WorkspaceDirectoriesPayload } from "@/lib/types";
|
||||
|
||||
const directory: WorkspaceDirectoriesPayload = {
|
||||
path: "/srv/workspace", parent: "/srv", entries: [], truncated: false,
|
||||
host: "dev-server", platform: "Linux",
|
||||
};
|
||||
|
||||
describe("workspace directory cache", () => {
|
||||
it("reuses revisited directories while separating filters and hidden-folder modes", async () => {
|
||||
const browse = vi.fn().mockResolvedValue(directory);
|
||||
const cache = createWorkspaceDirectoryCache(browse);
|
||||
await cache.load("/srv/workspace/", "", false, true);
|
||||
expect(cache.peek("/srv/workspace", "", false, true)).toBe(directory);
|
||||
await cache.load("/srv/workspace", "", false, true);
|
||||
expect(browse).toHaveBeenCalledTimes(1);
|
||||
await cache.load("/srv/workspace", "alpha", false, true);
|
||||
await cache.load("/srv/workspace", "", true, true);
|
||||
await cache.load("/srv/workspace", "", false, false);
|
||||
expect(browse).toHaveBeenCalledTimes(4);
|
||||
});
|
||||
|
||||
it("evicts least recently used results and refreshes expired directory listings", async () => {
|
||||
const clock = vi.spyOn(Date, "now").mockReturnValue(1000);
|
||||
try {
|
||||
const browse = vi.fn().mockResolvedValue(directory);
|
||||
const cache = createWorkspaceDirectoryCache(browse);
|
||||
for (let i = 0; i < 64; i++) await cache.load(`/srv/${i}`, "", false);
|
||||
expect(cache.peek("/srv/0", "", false)).toBe(directory);
|
||||
await cache.load("/srv/64", "", false);
|
||||
expect(cache.peek("/srv/1", "", false)).toBeUndefined();
|
||||
expect(cache.peek("/srv/0", "", false)).toBe(directory);
|
||||
clock.mockReturnValue(31_001);
|
||||
expect(cache.peek("/srv/0", "", false)).toBeUndefined();
|
||||
await cache.load("/srv/0", "", false);
|
||||
expect(browse).toHaveBeenCalledTimes(66);
|
||||
} finally { clock.mockRestore(); }
|
||||
});
|
||||
|
||||
it("shares simultaneous requests and lets failed requests be retried", async () => {
|
||||
let reject!: (reason: Error) => void;
|
||||
const browse = vi.fn().mockImplementationOnce(() => new Promise<WorkspaceDirectoriesPayload>((_resolve, fail) => { reject = fail; }))
|
||||
.mockResolvedValue(directory);
|
||||
const cache = createWorkspaceDirectoryCache(browse);
|
||||
const first = cache.load("/srv/workspace", "", false);
|
||||
expect(cache.load("/srv/workspace", "", false)).toBe(first);
|
||||
const failed = expect(first).rejects.toThrow("permission denied");
|
||||
reject(new Error("permission denied"));
|
||||
await failed;
|
||||
expect(cache.peek("/srv/workspace", "", false)).toBeUndefined();
|
||||
await expect(cache.load("/srv/workspace", "", false)).resolves.toBe(directory);
|
||||
expect(browse).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,318 @@
|
||||
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { WorkspaceProjectPicker } from "@/components/thread/WorkspaceControls";
|
||||
import type { WorkspaceDirectoriesPayload, WorkspacesPayload } from "@/lib/types";
|
||||
|
||||
const scope = { project_path: "/srv/workspace", access_mode: "restricted" as const };
|
||||
const catalog: WorkspacesPayload = {
|
||||
schema_version: 1,
|
||||
default_access_mode: "default",
|
||||
default_scope: scope,
|
||||
recent_projects: [{ name: "alpha", path: "/srv/alpha" }, { name: "beta", path: "/srv/beta" }],
|
||||
host: { name: "dev-server", platform: "Linux" },
|
||||
controls: { can_change_project: true, can_use_full_access: false, can_browse_directories: true },
|
||||
};
|
||||
const directory: WorkspaceDirectoriesPayload = {
|
||||
path: "/srv/workspace", parent: "/srv", entries: [{ name: "alpha", path: "/srv/workspace/alpha" }],
|
||||
truncated: false, host: "dev-server", platform: "Linux",
|
||||
};
|
||||
|
||||
describe("Workspace project picker", () => {
|
||||
it("keeps saved locations separate from directory filtering", async () => {
|
||||
const user = userEvent.setup();
|
||||
const onChange = vi.fn();
|
||||
const onBrowse = vi.fn().mockResolvedValue(directory);
|
||||
render(<WorkspaceProjectPicker isHero scope={scope} defaultScope={scope} controls={catalog.controls} onLoadProjects={vi.fn().mockResolvedValue(catalog)} onBrowseDirectories={onBrowse} onChange={onChange} />);
|
||||
await user.click(screen.getByRole("button", { name: "Switch working directory" }));
|
||||
const shortcut = await screen.findByRole("button", { name: "/srv/beta" });
|
||||
await user.clear(screen.getByRole("combobox"));
|
||||
await user.type(screen.getByRole("combobox"), "al");
|
||||
await waitFor(() => expect(onBrowse).toHaveBeenLastCalledWith("/srv/workspace", "al", false, true));
|
||||
expect(shortcut).toBeInTheDocument();
|
||||
expect(screen.getAllByRole("listbox")).toHaveLength(1);
|
||||
onBrowse.mockResolvedValue({ ...directory, path: "/srv/beta", entries: [] });
|
||||
await user.click(shortcut);
|
||||
await waitFor(() => expect(screen.getByRole("button", { name: "Select" })).toBeEnabled());
|
||||
expect(screen.getAllByRole("listbox")).toHaveLength(1);
|
||||
expect(screen.getByRole("combobox")).toHaveValue("/srv/beta/");
|
||||
expect(onChange).not.toHaveBeenCalled();
|
||||
await user.clear(screen.getByRole("combobox"));
|
||||
await user.type(screen.getByRole("combobox"), "oth");
|
||||
await waitFor(() => expect(onBrowse).toHaveBeenLastCalledWith("/srv/beta", "oth", false, true));
|
||||
expect(shortcut).toBeInTheDocument();
|
||||
await waitFor(() => expect(screen.getByRole("button", { name: "Select" })).toBeEnabled());
|
||||
await user.click(screen.getByRole("button", { name: "Select" }));
|
||||
expect(onChange).toHaveBeenCalledWith(expect.objectContaining({ project_path: "/srv/beta", access_mode: "restricted" }));
|
||||
});
|
||||
|
||||
it("shows cached directories without loading again when revisiting or reopening", async () => {
|
||||
const user = userEvent.setup();
|
||||
const onBrowse = vi.fn((path: string) => Promise.resolve(path.replace(/\/$/, "") === scope.project_path
|
||||
? directory : { ...directory, path: "/srv/workspace/alpha", entries: [] }));
|
||||
render(<WorkspaceProjectPicker isHero scope={scope} defaultScope={scope} controls={catalog.controls} onBrowseDirectories={onBrowse} onChange={vi.fn()} />);
|
||||
await user.click(screen.getByRole("button", { name: "Switch working directory" }));
|
||||
await user.click(await screen.findByRole("option", { name: "/srv/workspace/alpha" }));
|
||||
await waitFor(() => expect(screen.queryByRole("status")).not.toBeInTheDocument());
|
||||
expect(onBrowse).toHaveBeenCalledTimes(2);
|
||||
await user.click(screen.getByRole("button", { name: "/srv/workspace" }));
|
||||
expect(screen.getByRole("option", { name: "/srv/workspace/alpha" })).toBeInTheDocument();
|
||||
expect(screen.queryByRole("status")).not.toBeInTheDocument();
|
||||
expect(onBrowse).toHaveBeenCalledTimes(2);
|
||||
await user.keyboard("{Escape}");
|
||||
await user.click(screen.getByRole("button", { name: "Switch working directory" }));
|
||||
expect(screen.getByRole("option", { name: "/srv/workspace/alpha" })).toBeInTheDocument();
|
||||
expect(screen.queryByRole("status")).not.toBeInTheDocument();
|
||||
expect(onBrowse).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("scrolls deep directory columns horizontally with Shift and preserves ordinary wheel events", async () => {
|
||||
const user = userEvent.setup();
|
||||
const onBrowse = vi.fn((path: string) => Promise.resolve(path.replace(/\/$/, "") === scope.project_path
|
||||
? directory : { ...directory, path: "/srv/workspace/alpha", entries: [] }));
|
||||
render(<WorkspaceProjectPicker isHero scope={scope} defaultScope={scope} controls={catalog.controls} onBrowseDirectories={onBrowse} onChange={vi.fn()} />);
|
||||
await user.click(screen.getByRole("button", { name: "Switch working directory" }));
|
||||
await user.click(await screen.findByRole("option", { name: "/srv/workspace/alpha" }));
|
||||
await waitFor(() => expect(screen.queryByRole("status")).not.toBeInTheDocument());
|
||||
const viewport = screen.getAllByRole("listbox")[0].closest("[data-workspace-columns]") as HTMLElement;
|
||||
Object.defineProperties(viewport, { clientWidth: { value: 300 }, scrollWidth: { value: 600 } });
|
||||
viewport.scrollLeft = 0;
|
||||
const wheel = (options: WheelEventInit) => fireEvent(viewport, Object.assign(
|
||||
new Event("wheel", { bubbles: true, cancelable: true }),
|
||||
{ deltaX: 0, deltaY: 0, deltaMode: 0, shiftKey: false, ctrlKey: false, metaKey: false, ...options },
|
||||
));
|
||||
expect(wheel({ deltaY: 120, shiftKey: true })).toBe(false);
|
||||
expect(viewport.scrollLeft).toBe(120);
|
||||
expect(wheel({ deltaY: -2, deltaMode: 1, shiftKey: true })).toBe(false);
|
||||
expect(viewport.scrollLeft).toBe(88);
|
||||
wheel({ deltaY: 120 });
|
||||
expect(viewport.scrollLeft).toBe(88);
|
||||
wheel({ deltaY: 120, shiftKey: true, ctrlKey: true });
|
||||
expect(viewport.scrollLeft).toBe(88);
|
||||
});
|
||||
|
||||
it("browses folders immediately, toggles hidden entries, and selects the resolved directory", async () => {
|
||||
const user = userEvent.setup();
|
||||
const onChange = vi.fn();
|
||||
const onBrowse = vi.fn().mockResolvedValue(directory);
|
||||
render(<WorkspaceProjectPicker isHero scope={scope} defaultScope={scope} controls={catalog.controls} onBrowseDirectories={onBrowse} onChange={onChange} />);
|
||||
await user.click(screen.getByRole("button", { name: "Switch working directory" }));
|
||||
await screen.findByRole("option", { name: "/srv/workspace/alpha" });
|
||||
expect(onBrowse).toHaveBeenLastCalledWith("/srv/workspace/", "", false, true);
|
||||
await user.click(screen.getByRole("switch", { name: "Show hidden folders" }));
|
||||
await waitFor(() => expect(onBrowse).toHaveBeenLastCalledWith("/srv/workspace/", "", true, true));
|
||||
onBrowse.mockResolvedValue({ ...directory, path: "/srv/workspace/alpha", entries: [] });
|
||||
await user.click(screen.getByRole("option", { name: "/srv/workspace/alpha" }));
|
||||
await waitFor(() => expect(screen.getByRole("button", { name: "Select" })).toBeEnabled());
|
||||
await user.click(screen.getByRole("button", { name: "Select" }));
|
||||
expect(onChange).toHaveBeenCalledWith(expect.objectContaining({ project_path: "/srv/workspace/alpha" }));
|
||||
await waitFor(() => expect(screen.getByRole("button", { name: "Switch working directory" })).not.toHaveFocus());
|
||||
});
|
||||
|
||||
it("keeps invalid paths editable and validates the project before closing", async () => {
|
||||
const user = userEvent.setup();
|
||||
const onChange = vi.fn();
|
||||
const onResolve = vi.fn().mockRejectedValueOnce(new Error("project_path must be an existing directory"))
|
||||
.mockResolvedValueOnce({ name: "alpha", path: "/srv/alpha" });
|
||||
render(<WorkspaceProjectPicker isHero scope={scope} defaultScope={scope} controls={{ ...catalog.controls, can_resolve_project: true }} onResolveProject={onResolve} onChange={onChange} />);
|
||||
await user.click(screen.getByRole("button", { name: "Switch working directory" }));
|
||||
await user.clear(screen.getByRole("combobox"));
|
||||
await user.type(screen.getByRole("combobox"), "/srv/missing");
|
||||
await user.keyboard("{Enter}");
|
||||
expect(await screen.findByRole("alert")).toHaveTextContent("existing directory");
|
||||
expect(screen.getByRole("combobox")).toHaveValue("/srv/missing");
|
||||
await waitFor(() => expect(screen.getByRole("combobox")).toHaveFocus());
|
||||
expect(onChange).not.toHaveBeenCalled();
|
||||
await user.clear(screen.getByRole("combobox"));
|
||||
await user.type(screen.getByRole("combobox"), "/srv/alpha");
|
||||
await user.keyboard("{Enter}");
|
||||
await waitFor(() => expect(onChange).toHaveBeenCalledWith(expect.objectContaining({ project_path: "/srv/alpha" })));
|
||||
expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("uses manual paths without new requests on a host missing optional capabilities", async () => {
|
||||
const user = userEvent.setup();
|
||||
const onChange = vi.fn();
|
||||
const onBrowse = vi.fn();
|
||||
const onResolve = vi.fn();
|
||||
render(<WorkspaceProjectPicker isHero scope={scope} defaultScope={scope} controls={{ can_change_project: true, can_use_full_access: false }} onBrowseDirectories={onBrowse} onResolveProject={onResolve} onChange={onChange} />);
|
||||
await user.click(screen.getByRole("button", { name: "Switch working directory" }));
|
||||
expect(screen.queryByRole("option", { name: "Browse folders…" })).not.toBeInTheDocument();
|
||||
await user.clear(screen.getByRole("combobox"));
|
||||
await user.type(screen.getByRole("combobox"), "/srv/alpha");
|
||||
await user.keyboard("{Enter}");
|
||||
expect(onChange).toHaveBeenCalledWith(expect.objectContaining({ project_path: "/srv/alpha" }));
|
||||
expect(onBrowse).not.toHaveBeenCalled();
|
||||
expect(onResolve).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not apply a directory response after closing the dialog", async () => {
|
||||
const user = userEvent.setup();
|
||||
const onChange = vi.fn();
|
||||
let finish!: (value: WorkspaceDirectoriesPayload) => void;
|
||||
const onBrowse = vi.fn(() => new Promise<WorkspaceDirectoriesPayload>((resolve) => { finish = resolve; }));
|
||||
render(<WorkspaceProjectPicker isHero scope={scope} defaultScope={scope} controls={catalog.controls} onBrowseDirectories={onBrowse} onChange={onChange} />);
|
||||
await user.click(screen.getByRole("button", { name: "Switch working directory" }));
|
||||
await waitFor(() => expect(onBrowse).toHaveBeenCalled());
|
||||
await user.keyboard("{Escape}");
|
||||
finish(directory);
|
||||
expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
|
||||
expect(onChange).not.toHaveBeenCalled();
|
||||
});
|
||||
it("pins folders without selecting and keeps favorites ahead of recent projects", async () => {
|
||||
const user = userEvent.setup();
|
||||
const onChange = vi.fn();
|
||||
const favorites = [{ name: "beta", path: "/srv/beta" }];
|
||||
const onFavorite = vi.fn().mockResolvedValueOnce(favorites).mockRejectedValueOnce(new Error("disk full")).mockResolvedValueOnce([]);
|
||||
render(<WorkspaceProjectPicker isHero scope={scope} defaultScope={scope} controls={catalog.controls} onLoadProjects={vi.fn().mockResolvedValue({ ...catalog, controls: { ...catalog.controls, can_manage_favorites: true } })} onFavoriteProject={onFavorite} onChange={onChange} />);
|
||||
await user.click(screen.getByRole("button", { name: "Switch working directory" }));
|
||||
async function openFavoriteMenu(name: string) {
|
||||
fireEvent.contextMenu(await screen.findByRole("button", { name: "/srv/beta" }), { clientX: 100, clientY: 100 });
|
||||
return screen.findByRole("menuitem", { name });
|
||||
}
|
||||
await user.click(await openFavoriteMenu("Pin beta"));
|
||||
expect(onFavorite).toHaveBeenLastCalledWith("/srv/beta", true);
|
||||
await waitFor(() => expect(screen.queryByRole("menu")).not.toBeInTheDocument());
|
||||
expect(screen.getByRole("navigation")).toHaveTextContent("Favorites/srv/betaRecent projects");
|
||||
expect(screen.getByRole("combobox")).toHaveFocus();
|
||||
expect(onChange).not.toHaveBeenCalled();
|
||||
await user.click(await openFavoriteMenu("Unpin beta"));
|
||||
expect(await screen.findByRole("alert")).toHaveTextContent("disk full");
|
||||
await user.click(await openFavoriteMenu("Unpin beta"));
|
||||
await waitFor(() => expect(screen.queryByRole("menu")).not.toBeInTheDocument());
|
||||
expect(await openFavoriteMenu("Pin beta")).toBeInTheDocument();
|
||||
expect(onFavorite).toHaveBeenLastCalledWith("/srv/beta", false);
|
||||
expect(onChange).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([
|
||||
["/srv/al", "/srv/alpha", "/srv/alpha/"],
|
||||
["C:\\Projects\\al", "C:\\Projects\\alpha", "C:\\Projects\\alpha\\"],
|
||||
["\\\\server\\share\\al", "\\\\server\\share\\alpha", "\\\\server\\share\\alpha\\"],
|
||||
])("completes paths in the same input: %s", async (draft, completed, expected) => {
|
||||
const user = userEvent.setup();
|
||||
const onChange = vi.fn();
|
||||
const onBrowse = vi.fn((path: string) => Promise.resolve({ ...directory, path: completed, partial: path === draft, entries: path === draft ? [{ name: "alpha", path: completed }] : [] }));
|
||||
render(<WorkspaceProjectPicker isHero scope={scope} defaultScope={scope} controls={catalog.controls} onBrowseDirectories={onBrowse} onChange={onChange} />);
|
||||
await user.click(screen.getByRole("button", { name: "Switch working directory" }));
|
||||
const input = screen.getByRole("combobox");
|
||||
await user.clear(input);
|
||||
await user.type(input, draft);
|
||||
await screen.findByRole("option", { name: completed });
|
||||
await user.keyboard("{Tab}");
|
||||
expect(input).toHaveValue(expected);
|
||||
expect(input).toHaveFocus();
|
||||
expect(screen.getByRole("combobox")).toBe(input);
|
||||
expect(onChange).not.toHaveBeenCalled();
|
||||
await waitFor(() => expect(screen.getByRole("button", { name: "Select" })).toBeEnabled());
|
||||
expect(fireEvent.keyDown(input, { key: "Tab", shiftKey: true })).toBe(true);
|
||||
await user.click(screen.getByRole("button", { name: "Select" }));
|
||||
expect(onChange).toHaveBeenCalledWith(expect.objectContaining({ project_path: completed }));
|
||||
});
|
||||
|
||||
it("uses one list for partial paths and keyboard completion", async () => {
|
||||
const user = userEvent.setup();
|
||||
const onBrowse = vi.fn((path: string) => Promise.resolve({ ...directory, path: path === "/srv/al" ? "/srv" : path, parent: "/srv", partial: path === "/srv/al", entries: path === "/srv/al" ? [{ name: "alpha", path: "/srv/alpha" }, { name: "alpine", path: "/srv/alpine" }] : [] }));
|
||||
render(<WorkspaceProjectPicker isHero scope={scope} defaultScope={scope} controls={catalog.controls} onBrowseDirectories={onBrowse} onChange={vi.fn()} />);
|
||||
await user.click(screen.getByRole("button", { name: "Switch working directory" }));
|
||||
const input = screen.getByRole("combobox");
|
||||
await user.clear(input);
|
||||
await user.type(input, "/srv/al");
|
||||
await screen.findByRole("option", { name: "/srv/alpine" });
|
||||
expect(screen.getByRole("button", { name: "Select" })).toBeDisabled();
|
||||
expect(screen.queryByRole("alert")).not.toBeInTheDocument();
|
||||
await user.keyboard("{ArrowDown}{Tab}");
|
||||
expect(input).toHaveValue("/srv/alpine/");
|
||||
expect(screen.getAllByRole("combobox")).toHaveLength(1);
|
||||
expect(screen.getAllByRole("listbox")).toHaveLength(2);
|
||||
await waitFor(() => expect(screen.getByRole("button", { name: "Select" })).toBeEnabled());
|
||||
expect(input).toHaveFocus();
|
||||
});
|
||||
|
||||
it("ignores a Tab completion after the user changes the path", async () => {
|
||||
const user = userEvent.setup();
|
||||
let finish!: (value: WorkspaceDirectoriesPayload) => void;
|
||||
const onBrowse = vi.fn((_path: string, query: string) => query ? 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()} />);
|
||||
await user.click(screen.getByRole("button", { name: "Switch working directory" }));
|
||||
const input = screen.getByRole("combobox");
|
||||
await user.clear(input);
|
||||
await user.type(input, "/srv/al");
|
||||
await user.keyboard("{Tab}");
|
||||
await user.type(input, "ternative");
|
||||
finish({ ...directory, entries: [{ name: "alpha", path: "/srv/alpha" }] });
|
||||
await waitFor(() => expect(input).toHaveValue("/srv/alternative"));
|
||||
expect(input).toHaveFocus();
|
||||
});
|
||||
|
||||
it("updates folders while typing and ignores results from older paths", async () => {
|
||||
const user = userEvent.setup();
|
||||
let finishOld!: (value: WorkspaceDirectoriesPayload) => void;
|
||||
const onBrowse = vi.fn((path: string) => path === "/srv/old/" ? new Promise<WorkspaceDirectoriesPayload>(resolve => { finishOld = resolve; }) : Promise.resolve({ ...directory, path, entries: [{ name: path === "/srv/new/" ? "new-child" : "initial-child", path: `${path.replace(/\/$/, "")}/child` }] }));
|
||||
const onChange = vi.fn();
|
||||
render(<WorkspaceProjectPicker isHero scope={scope} defaultScope={scope} controls={catalog.controls} onBrowseDirectories={onBrowse} onChange={onChange} />);
|
||||
await user.click(screen.getByRole("button", { name: "Switch working directory" }));
|
||||
await screen.findByRole("option", { name: "/srv/workspace/child" });
|
||||
const input = screen.getByRole("combobox");
|
||||
await user.clear(input);
|
||||
await user.type(input, "/srv/old/");
|
||||
expect(screen.queryByRole("option", { name: "/srv/workspace/child" })).not.toBeInTheDocument();
|
||||
expect(screen.getByRole("button", { name: "Select" })).toBeDisabled();
|
||||
await waitFor(() => expect(onBrowse).toHaveBeenCalledWith("/srv/old/", "", false, true));
|
||||
await user.clear(input);
|
||||
await user.type(input, "/srv/new/");
|
||||
await screen.findByRole("option", { name: "/srv/new/child" });
|
||||
finishOld({ ...directory, path: "/srv/old/", entries: [{ name: "stale-child", path: "/srv/old/child" }] });
|
||||
await waitFor(() => expect(screen.queryByRole("option", { name: "/srv/old/child" })).not.toBeInTheDocument());
|
||||
expect(screen.getByRole("combobox")).toBe(input);
|
||||
expect(input).toHaveFocus();
|
||||
await user.click(screen.getByRole("button", { name: "Select" }));
|
||||
expect(onChange).toHaveBeenCalledWith(expect.objectContaining({ project_path: "/srv/new/" }));
|
||||
});
|
||||
|
||||
it("filters the current directory by name without a second browser view", async () => {
|
||||
const user = userEvent.setup();
|
||||
const onBrowse = vi.fn().mockResolvedValue(directory);
|
||||
render(<WorkspaceProjectPicker isHero scope={scope} defaultScope={scope} controls={catalog.controls} onBrowseDirectories={onBrowse} onChange={vi.fn()} />);
|
||||
await user.click(screen.getByRole("button", { name: "Switch working directory" }));
|
||||
await screen.findByRole("option", { name: "/srv/workspace/alpha" });
|
||||
const input = screen.getByRole("combobox");
|
||||
await user.clear(input);
|
||||
await user.type(input, "alp");
|
||||
await waitFor(() => expect(onBrowse).toHaveBeenLastCalledWith("/srv/workspace", "alp", false, true));
|
||||
expect(screen.getAllByRole("combobox")).toHaveLength(1);
|
||||
expect(screen.queryByText("Browse folders…")).not.toBeInTheDocument();
|
||||
expect(screen.queryByPlaceholderText("Filter folders…")).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole("button", { name: "Close" })).not.toBeInTheDocument();
|
||||
});
|
||||
it("keeps ancestor columns and replaces descendants when another folder is opened", async () => {
|
||||
const user = userEvent.setup();
|
||||
const onChange = vi.fn();
|
||||
const onBrowse = vi.fn((rawPath: string, _query: string, showHidden: boolean) => {
|
||||
const path = rawPath.replace(/\/$/, "");
|
||||
const names = path === scope.project_path ? ["alpha", "beta"] : path.endsWith("/alpha") ? ["child"] : path.endsWith("/beta") ? ["other"] : [];
|
||||
if (showHidden) names.push(".hidden");
|
||||
return Promise.resolve({ ...directory, path, entries: names.map(name => ({ name, path: `${path}/${name}` })) });
|
||||
});
|
||||
render(<WorkspaceProjectPicker isHero scope={scope} defaultScope={scope} controls={catalog.controls} onBrowseDirectories={onBrowse} onChange={onChange} />);
|
||||
await user.click(screen.getByRole("button", { name: "Switch working directory" }));
|
||||
await user.click(await screen.findByRole("option", { name: "/srv/workspace/alpha" }));
|
||||
await user.click(await screen.findByRole("option", { name: "/srv/workspace/alpha/child" }));
|
||||
expect(screen.getAllByRole("listbox")).toHaveLength(3);
|
||||
expect(screen.getByRole("option", { name: "/srv/workspace/alpha" })).toHaveAttribute("aria-selected", "true");
|
||||
expect(onChange).not.toHaveBeenCalled();
|
||||
expect(onBrowse.mock.calls.filter(call => call[0].replace(/\/$/, "") === scope.project_path)).toHaveLength(1);
|
||||
await user.click(screen.getByRole("switch", { name: "Show hidden folders" }));
|
||||
await screen.findByRole("option", { name: "/srv/workspace/.hidden" });
|
||||
await screen.findByRole("option", { name: "/srv/workspace/alpha/.hidden" });
|
||||
await screen.findByRole("option", { name: "/srv/workspace/alpha/child/.hidden" });
|
||||
await user.click(screen.getByRole("option", { name: "/srv/workspace/beta" }));
|
||||
await screen.findByRole("option", { name: "/srv/workspace/beta/other" });
|
||||
expect(screen.getAllByRole("listbox")).toHaveLength(2);
|
||||
expect(screen.queryByRole("option", { name: "/srv/workspace/alpha/child" })).not.toBeInTheDocument();
|
||||
await user.click(screen.getByRole("button", { name: "Select" }));
|
||||
expect(onChange).toHaveBeenCalledWith(expect.objectContaining({ project_path: "/srv/workspace/beta" }));
|
||||
});
|
||||
|
||||
});
|
||||
Reference in new issue
Block a user