diff --git a/README.md b/README.md index 2293498db..238af8518 100644 --- a/README.md +++ b/README.md @@ -291,6 +291,12 @@ Open [http://127.0.0.1:3782](http://127.0.0.1:3782), configure model providers i ### Content Workspace +In a new conversation, open the workspace menu and **Choose a server folder** +to browse into a project and select it without typing a path. The same picker +is available in workspace settings. Remote deployments browse server folders; +see the [server folder picker guide](docs-for-dev/SERVER_WORKSPACE_PICKER.md) +for Docker mounts and configurable browsing roots. + The **Content Workspace** is separate from DeepTutor's private runtime home. It is the folder agents may read, with generated files under `outputs////`. Custom workspaces isolate conversations, diff --git a/deeptutor/api/routers/workspace.py b/deeptutor/api/routers/workspace.py index 77e759a3a..04cf7ea10 100644 --- a/deeptutor/api/routers/workspace.py +++ b/deeptutor/api/routers/workspace.py @@ -25,6 +25,17 @@ settings_router = APIRouter() files_router = APIRouter() +@settings_router.get("/folders") +async def list_server_folders(path: str = "") -> dict: + """Return folders available to the authenticated workspace picker.""" + from deeptutor.services.workspace.folders import browse_folders + + try: + return await asyncio.to_thread(browse_folders, get_content_workspace_service(), path) + except WorkspaceError as exc: + raise HTTPException(status_code=400, detail=str(exc)) from exc + + class WorkspacePathPayload(BaseModel): path: str | None = None diff --git a/deeptutor/services/workspace/folders.py b/deeptutor/services/workspace/folders.py new file mode 100644 index 000000000..2f161eb40 --- /dev/null +++ b/deeptutor/services/workspace/folders.py @@ -0,0 +1,72 @@ +"""Read-only server folder navigation for the workspace picker.""" + +from __future__ import annotations + +import os +from pathlib import Path + +from .models import WorkspaceError +from .service import ContentWorkspaceService + + +def browse_folders(service: ContentWorkspaceService, path: str = "") -> dict: + """List readable subfolders within the requesting user's browsing roots.""" + configured = os.environ.get("DEEPTUTOR_WORKSPACE_BROWSER_ROOTS", "").strip() + candidates = ( + [Path(value).expanduser().resolve() for value in configured.split(os.pathsep) if value] + if configured + else list(service._allowed_roots()) + ) + roots = [] + for root in candidates: + try: + service._assert_allowed_root(root) + if root.is_dir() and os.access(root, os.R_OK | os.X_OK) and root not in roots: + roots.append(root) + except (WorkspaceError, OSError): + continue + if not roots: + raise WorkspaceError("No browsable workspace folders are configured.") + try: + if "\x00" in path: + raise ValueError("Invalid path") + current = Path(path).expanduser().resolve() if path else roots[0] + except (OSError, RuntimeError, ValueError) as exc: + raise WorkspaceError("The server folder path is invalid.") from exc + # Picker confinement applies even to admins. Resolve symlinks before checking. + containing = [root for root in roots if current.is_relative_to(root)] + if not containing: + raise WorkspaceError("This folder is outside the configured browsing roots.") + root = max(containing, key=lambda item: len(item.parts)) + folders = [] + scanned = 0 + try: + with os.scandir(current) as entries: + for entry in entries: + scanned += 1 + if scanned > 10000: + break + if entry.name.startswith("."): + continue + try: + target = Path(entry.path).resolve() + if ( + entry.is_dir() + and target != current + and target.is_relative_to(root) + and os.access(target, os.R_OK | os.X_OK) + ): + folders.append({"name": entry.name, "path": str(target)}) + except (OSError, RuntimeError): + continue + except OSError as exc: + raise WorkspaceError("The selected server folder cannot be opened.") from exc + folders.sort(key=lambda entry: (entry["name"].casefold(), entry["name"])) + return { + "roots": [{"name": item.name or str(item), "path": str(item)} for item in roots], + "path": str(current), + "name": current.name or str(current), + "parent": str(current.parent) if current != root else None, + "folders": folders[:500], + "truncated": len(folders) > 500 or scanned > 10000, + } diff --git a/docs-for-dev/SERVER_WORKSPACE_PICKER.md b/docs-for-dev/SERVER_WORKSPACE_PICKER.md new file mode 100644 index 000000000..fd5911f6c --- /dev/null +++ b/docs-for-dev/SERVER_WORKSPACE_PICKER.md @@ -0,0 +1,32 @@ +# Choose a server folder as a workspace + +In a new conversation, open the workspace menu next to the composer and choose +**Choose a server folder**. Open folders until the desired project is displayed, +then choose **Select this folder**. New registrations use the folder name; +existing registrations retain their names and settings. Selecting an archived +registration restores it. Conversations with messages keep their existing binding. + +The same picker is available in **Settings → Workspaces → New workspace**, +where it fills the existing-folder path and a default workspace name. +Browsing folders is read-only. Registration continues to use the existing +workspace validation and output-directory initialization. + +## Deployment + +The picker browses the filesystem of the backend, rather than the computer +running the browser. In Docker, project folders must be bind-mounted first. +For example, mount `/srv/projects` at `/srv/projects` inside the container and +set `DEEPTUTOR_WORKSPACE_BROWSER_ROOTS=/srv/projects`. + +Multiple roots are separated by the backend platform's path separator (`:` on +Linux/macOS, `;` on Windows). Without this setting, the picker uses the roots +already provided by the content-workspace policy. Configured roots are also +checked against that policy for the requesting user; this setting does not +grant a non-admin access to additional folders. Admins remain confined to the +picker's configured browsing roots as well. + +The picker shows accessible non-hidden subdirectories and omits symlinks that +resolve outside the current root. Each directory scan is bounded to 10,000 +entries and returns at most 500 folders. Filtering applies to the displayed +directory, not recursively to the whole project tree. The API is +`GET /api/settings/workspace/folders?path=...` and inherits settings authentication. diff --git a/tests/api/test_workspace_router.py b/tests/api/test_workspace_router.py index 74fa87f53..9e359fc18 100644 --- a/tests/api/test_workspace_router.py +++ b/tests/api/test_workspace_router.py @@ -48,6 +48,26 @@ def workspace_api(tmp_path: Path, monkeypatch: pytest.MonkeyPatch): return TestClient(app), service +def test_workspace_folder_picker_browses_only_configured_server_roots( + workspace_api, tmp_path: Path, monkeypatch +) -> None: + client, _ = workspace_api + root = tmp_path / "server-projects" + (root / "oss" / "flashinfer").mkdir(parents=True) + monkeypatch.setenv("DEEPTUTOR_WORKSPACE_BROWSER_ROOTS", str(root)) + response = client.get("/api/settings/workspace/folders") + assert response.status_code == 200 + assert response.json()["folders"] == [{"name": "oss", "path": str(root / "oss")}] + nested = client.get("/api/settings/workspace/folders", params={"path": str(root / "oss")}) + assert nested.json()["parent"] == str(root) + assert nested.json()["folders"][0]["name"] == "flashinfer" + assert ( + client.get("/api/settings/workspace/folders", params={"path": str(root.parent)}).status_code + == 400 + ) + assert not (root / "outputs").exists() + + def test_workspace_settings_select_and_reset(workspace_api, tmp_path: Path) -> None: client, service = workspace_api custom = tmp_path / "learning-materials" diff --git a/tests/services/workspace/test_folder_browser.py b/tests/services/workspace/test_folder_browser.py new file mode 100644 index 000000000..b5f85d10c --- /dev/null +++ b/tests/services/workspace/test_folder_browser.py @@ -0,0 +1,111 @@ +import os +from pathlib import Path + +import pytest + +from deeptutor.multi_user.context import reset_current_user, set_current_user +from deeptutor.multi_user.models import CurrentUser, UserScope +from deeptutor.services.workspace.folders import browse_folders +from deeptutor.services.workspace.models import WorkspaceError +from deeptutor.services.workspace.service import ContentWorkspaceService + + +@pytest.fixture +def browser(monkeypatch, tmp_path): + root = tmp_path / "src" + root.mkdir() + monkeypatch.setenv("DEEPTUTOR_WORKSPACE_BROWSER_ROOTS", str(root)) + service = ContentWorkspaceService() + # Even an admin who can register arbitrary folders must stay inside the + # browser's explicitly configured roots. + monkeypatch.setattr(service, "_assert_allowed_root", lambda root: None) + return service, root + + +def test_navigate_existing_folders_without_creating_outputs(browser): + service, root = browser + (root / "oss").mkdir() + (root / "中文项目").mkdir() + (root / ".private").mkdir() + (root / "file.txt").write_text("not a folder") + listing = browse_folders(service) + assert listing["path"] == str(root) + assert listing["parent"] is None + assert [entry["name"] for entry in listing["folders"]] == ["oss", "中文项目"] + nested = browse_folders(service, str(root / "oss")) + assert nested["parent"] == str(root) + assert nested["folders"] == [] + assert not (root / "outputs").exists() + assert not (root / "oss" / "outputs").exists() + + +def test_parent_traversal_and_absolute_escape_are_rejected(browser): + service, root = browser + for path in [str(root / ".."), str(root.parent), str(root) + "/../../outside"]: + with pytest.raises(WorkspaceError, match="outside"): + browse_folders(service, path) + + +def test_symlinks_cannot_escape_the_browsing_root(browser): + service, root = browser + outside = root.parent / "private" + outside.mkdir() + try: + (root / "escape").symlink_to(outside, target_is_directory=True) + (root / "self").symlink_to(root, target_is_directory=True) + except OSError: + pytest.skip("Creating symlinks is unavailable on this Windows host") + assert browse_folders(service)["folders"] == [] + with pytest.raises(WorkspaceError, match="outside"): + browse_folders(service, str(root / "escape")) + + +def test_missing_and_invalid_paths_fail_cleanly(browser): + service, root = browser + with pytest.raises(WorkspaceError, match="cannot be opened"): + browse_folders(service, str(root / "missing")) + with pytest.raises(WorkspaceError, match="invalid"): + browse_folders(service, "\x00") + + +def test_roots_respect_existing_workspace_access_policy(browser, monkeypatch): + service, _ = browser + + def deny(root: Path): + raise WorkspaceError("denied") + + monkeypatch.setattr(service, "_assert_allowed_root", deny) + with pytest.raises(WorkspaceError, match="No browsable"): + browse_folders(service) + + +def test_multiple_roots_do_not_expand_a_normal_users_access(tmp_path, monkeypatch): + allowed, private = tmp_path / "allowed", tmp_path / "private" + allowed.mkdir() + private.mkdir() + monkeypatch.setenv( + "DEEPTUTOR_WORKSPACE_BROWSER_ROOTS", os.pathsep.join(map(str, [allowed, private])) + ) + service = ContentWorkspaceService() + monkeypatch.setattr(service, "_allowed_roots", lambda: (allowed,)) + token = set_current_user( + CurrentUser("learner", "learner", "user", UserScope("user", "learner", allowed)) + ) + try: + assert browse_folders(service)["roots"] == [{"name": "allowed", "path": str(allowed)}] + with pytest.raises(WorkspaceError, match="outside"): + browse_folders(service, str(private)) + finally: + reset_current_user(token) + + +def test_multiple_roots_are_navigable_without_parent_escape(browser, monkeypatch): + service, first = browser + second = first.parent / "other-projects" + second.mkdir() + monkeypatch.setenv( + "DEEPTUTOR_WORKSPACE_BROWSER_ROOTS", os.pathsep.join(map(str, [first, second])) + ) + listing = browse_folders(service, str(second)) + assert [row["path"] for row in listing["roots"]] == [str(first), str(second)] + assert listing["parent"] is None diff --git a/web/components/workspaces/ServerFolderPicker.tsx b/web/components/workspaces/ServerFolderPicker.tsx new file mode 100644 index 000000000..42142f41f --- /dev/null +++ b/web/components/workspaces/ServerFolderPicker.tsx @@ -0,0 +1,217 @@ +'use client' + +import { useEffect, useState } from 'react' +import { createPortal } from 'react-dom' +import { ArrowUp, ChevronRight, Folder } from 'lucide-react' +import { useTranslation } from 'react-i18next' +import { Dialog } from '@/shared/ui/Dialog' +import { + browseServerFolders, + type ServerFolder, + type ServerFolderListing, +} from '@/lib/workspaces-api' + +/** Browse the backend filesystem without requiring a manually entered path. */ +export function ServerFolderPicker({ + onClose, + onSelect, +}: { + onClose: () => void + onSelect: (folder: ServerFolder) => void | Promise +}) { + const { t } = useTranslation() + const [path, setPath] = useState('') + const [listing, setListing] = useState(null) + const [loading, setLoading] = useState(true) + const [saving, setSaving] = useState(false) + const [error, setError] = useState('') + const [filter, setFilter] = useState('') + const [attempt, setAttempt] = useState(0) + + useEffect(() => { + let active = true + browseServerFolders(path) + .then(data => { + if (active) { + setListing(data) + setLoading(false) + } + }) + .catch(err => { + if (active) { + setError(String(err.message)) + setLoading(false) + } + }) + return () => { + active = false + } + }, [path, attempt]) + + const navigate = (next: string) => { + if (next === path) return + setLoading(true) + setError('') + setFilter('') + setPath(next) + } + const choose = async () => { + if (!listing || loading || saving) return + setSaving(true) + setError('') + try { + await onSelect({ name: listing.name, path: listing.path }) + onClose() + } catch (err) { + setError(err instanceof Error ? err.message : String(err)) + } finally { + setSaving(false) + } + } + + const currentRoot = listing?.roots + .filter(root => { + const current = listing.path.replaceAll('\\', '/') + const prefix = root.path.replaceAll('\\', '/').replace(/\/$/, '') + return current === prefix || current.startsWith(prefix + '/') + }) + .sort((a, b) => b.path.length - a.path.length)[0] + + return createPortal( + + + + + } + > +
+ {listing && ( + <> +
+ +

+ {listing.path} +

+
+ {listing.roots.length > 1 && ( + + )} + + )} + setFilter(event.target.value)} + className="w-full rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 text-sm" + /> + {error && ( +
+

+ {error} +

+ +
+ )} +
+ {loading ? ( +

+ {t('Loading folders…')} +

+ ) : ( + <> + {listing?.folders + .filter(folder => + folder.name.toLocaleLowerCase().includes(filter.toLocaleLowerCase()) + ) + .map(folder => ( + + ))} + {!listing?.folders.some(folder => + folder.name.toLocaleLowerCase().includes(filter.toLocaleLowerCase()) + ) && + !error && ( +

{t('No subfolders')}

+ )} + + )} +
+ {listing?.truncated && ( +

+ {t('Showing the first 500 folders. Open a subfolder to narrow the list.')} +

+ )} +
+
, + document.body + ) +} diff --git a/web/components/workspaces/WorkspacePill.tsx b/web/components/workspaces/WorkspacePill.tsx index 141da3eac..0821e4f6f 100644 --- a/web/components/workspaces/WorkspacePill.tsx +++ b/web/components/workspaces/WorkspacePill.tsx @@ -3,6 +3,7 @@ import Tooltip from "@/shared/ui/Tooltip"; import { useEffect, useRef, useState } from "react"; import Link from "next/link"; +import dynamic from "next/dynamic"; import { Check, ChevronDown, Folder, FolderOpen, Plus } from "lucide-react"; import { useTranslation } from "react-i18next"; @@ -10,6 +11,8 @@ import { useLingerExpand } from "@/hooks/use-linger-expand"; import ToolbarLabel from "@/components/chat/home/ToolbarLabel"; import { saveWorkspace, type ChatWorkspaceRegistration } from "@/lib/workspaces-api"; +const ServerFolderPicker = dynamic(() => import("./ServerFolderPicker").then(module => module.ServerFolderPicker), { ssr: false }); + /** * Which workspace this conversation belongs to. * @@ -44,6 +47,7 @@ export function WorkspacePill({ }) { const { t } = useTranslation(); const [creating, setCreating] = useState(false); + const [browsing, setBrowsing] = useState(false); const [name, setName] = useState(""); const [saving, setSaving] = useState(false); const [createError, setCreateError] = useState(""); @@ -221,6 +225,10 @@ export function WorkspacePill({ ) : null} + {creating ? (
{ event.preventDefault(); @@ -273,6 +281,14 @@ export function WorkspacePill({ )} + {browsing && setBrowsing(false)} onSelect={async folder => { + const existing = choices.find(item => item.kind === "workspace" && item.path === folder.path); + const row = existing + ? existing.archived ? await saveWorkspace({ archived: false }, existing.workspace_id) : existing + : await saveWorkspace({ name: folder.name.slice(0, 100), path: folder.path }); + setCreated(items => [...items.filter(item => item.workspace_id !== row.workspace_id), row]); + onSelect(row.workspace_id); + }} />} ); } diff --git a/web/contracts/generated/api.ts b/web/contracts/generated/api.ts index d464f910d..2b7ebb85d 100644 --- a/web/contracts/generated/api.ts +++ b/web/contracts/generated/api.ts @@ -9585,6 +9585,26 @@ export interface paths { readonly patch?: never; readonly trace?: never; }; + readonly "/api/settings/workspace/folders": { + readonly parameters: { + readonly query?: never; + readonly header?: never; + readonly path?: never; + readonly cookie?: never; + }; + /** + * List Server Folders + * @description Return folders available to the authenticated workspace picker. + */ + readonly get: operations["list_server_folders_api_settings_workspace_folders_get"]; + readonly put?: never; + readonly post?: never; + readonly delete?: never; + readonly options?: never; + readonly head?: never; + readonly patch?: never; + readonly trace?: never; + }; readonly "/api/settings/workspace/knowledge-bases/move": { readonly parameters: { readonly query?: never; @@ -40057,6 +40077,43 @@ export interface operations { }; }; }; + readonly list_server_folders_api_settings_workspace_folders_get: { + readonly parameters: { + readonly query?: { + readonly path?: string; + }; + readonly header?: { + readonly Authorization?: string | null; + }; + readonly path?: never; + readonly cookie?: { + readonly dt_token?: string | null; + }; + }; + readonly requestBody?: never; + readonly responses: { + /** @description Successful Response */ + readonly 200: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": { + readonly [key: string]: unknown; + }; + }; + }; + /** @description Validation Error */ + readonly 422: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": components["schemas"]["HTTPValidationError"]; + }; + }; + }; + }; readonly move_knowledge_base_api_settings_workspace_knowledge_bases_move_post: { readonly parameters: { readonly query?: never; diff --git a/web/contracts/schema/openapi.json b/web/contracts/schema/openapi.json index c57215427..ee92addbd 100644 --- a/web/contracts/schema/openapi.json +++ b/web/contracts/schema/openapi.json @@ -59103,6 +59103,84 @@ ] } }, + "/api/settings/workspace/folders": { + "get": { + "description": "Return folders available to the authenticated workspace picker.", + "operationId": "list_server_folders_api_settings_workspace_folders_get", + "parameters": [ + { + "in": "query", + "name": "path", + "required": false, + "schema": { + "default": "", + "title": "Path", + "type": "string" + } + }, + { + "in": "header", + "name": "Authorization", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Authorization" + } + }, + { + "in": "cookie", + "name": "dt_token", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Dt Token" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "additionalProperties": true, + "title": "Response List Server Folders Api Settings Workspace Folders Get", + "type": "object" + } + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "List Server Folders", + "tags": [ + "workspace-settings" + ] + } + }, "/api/settings/workspace/knowledge-bases/move": { "post": { "operationId": "move_knowledge_base_api_settings_workspace_knowledge_bases_move_post", diff --git a/web/features/settings/sections/WorkspaceSettingsSection.tsx b/web/features/settings/sections/WorkspaceSettingsSection.tsx index 5d1dbe5b4..32f367ecb 100644 --- a/web/features/settings/sections/WorkspaceSettingsSection.tsx +++ b/web/features/settings/sections/WorkspaceSettingsSection.tsx @@ -3,6 +3,7 @@ import Tooltip from "@/shared/ui/Tooltip"; import { useCallback, useEffect, useState } from 'react' import Link from 'next/link' +import dynamic from 'next/dynamic' import { Archive, ArchiveRestore, FileText, Folder, FolderInput, Globe2, Pencil, Plus, Settings2 } from 'lucide-react' import { useTranslation } from 'react-i18next' import { SettingSection, SettingsPageHeader, inputClass, subPanelClass } from '@/components/settings/shared' @@ -15,6 +16,7 @@ import { } from '@/lib/workspaces-api' type RunAction = (action: () => Promise) => Promise +const ServerFolderPicker = dynamic(() => import('@/components/workspaces/ServerFolderPicker').then(module => module.ServerFolderPicker), { ssr: false }) const actionClass = 'inline-flex items-center justify-center gap-1.5 rounded-lg px-2.5 py-2 text-xs text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)] hover:text-[var(--foreground)] disabled:opacity-50' const primaryClass = 'inline-flex items-center justify-center gap-1.5 rounded-lg bg-[var(--foreground)] px-3 py-2 text-sm text-[var(--background)] disabled:opacity-50' @@ -101,6 +103,7 @@ export default function WorkspaceSettingsSection() { const [root, setRoot] = useState('') const [busy, setBusy] = useState(false) const [creating, setCreating] = useState(false) + const [browsing, setBrowsing] = useState(false) const [resources, setResources] = useState(inheritedWorkspaceResources) const [instructions, setInstructions] = useState('') const [name, setName] = useState('') @@ -145,6 +148,7 @@ export default function WorkspaceSettingsSection() { }}> +

{t('Place files in the folder for the agent to read. Generated files go into outputs/.')}

@@ -165,6 +169,10 @@ export default function WorkspaceSettingsSection() { )} + {browsing && setBrowsing(false)} onSelect={folder => { + setPath(folder.path) + if (!name.trim()) setName(folder.name.slice(0, 100)) + }} />} ) } diff --git a/web/lib/workspaces-api.ts b/web/lib/workspaces-api.ts index cfe368e7c..270ace64f 100644 --- a/web/lib/workspaces-api.ts +++ b/web/lib/workspaces-api.ts @@ -46,6 +46,22 @@ export interface ChatWorkspaceRegistration { const endpoint = '/api/settings/workspace/registrations' +export interface ServerFolder { + name: string + path: string +} + +export interface ServerFolderListing extends ServerFolder { + roots: ServerFolder[] + parent: string | null + folders: ServerFolder[] + truncated: boolean +} + +export function browseServerFolders(path = ''): Promise { + return request(`/api/settings/workspace/folders?path=${encodeURIComponent(path)}`) +} + async function request(url: string, init?: RequestInit): Promise { const response = await apiFetch(apiUrl(url), init) const payload = await response.json() diff --git a/web/locales/de/app.json b/web/locales/de/app.json index dc39cae7e..3c82841e9 100644 --- a/web/locales/de/app.json +++ b/web/locales/de/app.json @@ -6218,5 +6218,15 @@ "Could not load review strategies. Try again.": "Wiederholungsstrategien konnten nicht geladen werden. Versuche es erneut.", "Could not save review strategy. Try again.": "Die Wiederholungsstrategie konnte nicht gespeichert werden. Versuche es erneut.", "Could not duplicate review strategy. Try again.": "Die Wiederholungsstrategie konnte nicht dupliziert werden. Versuche es erneut.", - "Could not delete review strategy. Try again.": "Die Wiederholungsstrategie konnte nicht gelöscht werden. Versuche es erneut." + "Could not delete review strategy. Try again.": "Die Wiederholungsstrategie konnte nicht gelöscht werden. Versuche es erneut.", + "Choose a server folder": "Serverordner auswählen", + "Browse folders on the server and choose a project workspace.": "Durchsuche Ordner auf dem Server und wähle einen Projektarbeitsbereich.", + "Select this folder": "Diesen Ordner auswählen", + "Parent folder": "Übergeordneter Ordner", + "Current folder": "Aktueller Ordner", + "Browse root": "Stammverzeichnis", + "Filter folders": "Ordner filtern", + "Loading folders…": "Ordner werden geladen…", + "No subfolders": "Keine Unterordner", + "Showing the first 500 folders. Open a subfolder to narrow the list.": "Die ersten 500 Ordner werden angezeigt. Öffne einen Unterordner, um die Liste einzugrenzen." } diff --git a/web/locales/en/app.json b/web/locales/en/app.json index 765061ceb..29b959572 100644 --- a/web/locales/en/app.json +++ b/web/locales/en/app.json @@ -6218,5 +6218,15 @@ "Could not load review strategies. Try again.": "Could not load review strategies. Try again.", "Could not save review strategy. Try again.": "Could not save review strategy. Try again.", "Could not duplicate review strategy. Try again.": "Could not duplicate review strategy. Try again.", - "Could not delete review strategy. Try again.": "Could not delete review strategy. Try again." + "Could not delete review strategy. Try again.": "Could not delete review strategy. Try again.", + "Choose a server folder": "Choose a server folder", + "Browse folders on the server and choose a project workspace.": "Browse folders on the server and choose a project workspace.", + "Select this folder": "Select this folder", + "Parent folder": "Parent folder", + "Current folder": "Current folder", + "Browse root": "Browse root", + "Filter folders": "Filter folders", + "Loading folders…": "Loading folders…", + "No subfolders": "No subfolders", + "Showing the first 500 folders. Open a subfolder to narrow the list.": "Showing the first 500 folders. Open a subfolder to narrow the list." } diff --git a/web/locales/fr/app.json b/web/locales/fr/app.json index a1d6e8923..009cf60d1 100644 --- a/web/locales/fr/app.json +++ b/web/locales/fr/app.json @@ -6372,5 +6372,15 @@ "Could not load review strategies. Try again.": "Impossible de charger les stratégies de révision. Réessayez.", "Could not save review strategy. Try again.": "Impossible d’enregistrer la stratégie de révision. Réessayez.", "Could not duplicate review strategy. Try again.": "Impossible de dupliquer la stratégie de révision. Réessayez.", - "Could not delete review strategy. Try again.": "Impossible de supprimer la stratégie de révision. Réessayez." + "Could not delete review strategy. Try again.": "Impossible de supprimer la stratégie de révision. Réessayez.", + "Choose a server folder": "Choisir un dossier sur le serveur", + "Browse folders on the server and choose a project workspace.": "Parcourez les dossiers du serveur et choisissez un espace de travail de projet.", + "Select this folder": "Sélectionner ce dossier", + "Parent folder": "Dossier parent", + "Current folder": "Dossier actuel", + "Browse root": "Racine de navigation", + "Filter folders": "Filtrer les dossiers", + "Loading folders…": "Chargement des dossiers…", + "No subfolders": "Aucun sous-dossier", + "Showing the first 500 folders. Open a subfolder to narrow the list.": "Affichage des 500 premiers dossiers. Ouvrez un sous-dossier pour affiner la liste." } diff --git a/web/locales/pl/app.json b/web/locales/pl/app.json index ac1b2fc1f..1235c4ccf 100644 --- a/web/locales/pl/app.json +++ b/web/locales/pl/app.json @@ -6240,5 +6240,15 @@ "Could not load review strategies. Try again.": "Nie udało się wczytać strategii powtórek. Spróbuj ponownie.", "Could not save review strategy. Try again.": "Nie udało się zapisać strategii powtórek. Spróbuj ponownie.", "Could not duplicate review strategy. Try again.": "Nie udało się zduplikować strategii powtórek. Spróbuj ponownie.", - "Could not delete review strategy. Try again.": "Nie udało się usunąć strategii powtórek. Spróbuj ponownie." + "Could not delete review strategy. Try again.": "Nie udało się usunąć strategii powtórek. Spróbuj ponownie.", + "Choose a server folder": "Wybierz folder na serwerze", + "Browse folders on the server and choose a project workspace.": "Przeglądaj foldery na serwerze i wybierz obszar roboczy projektu.", + "Select this folder": "Wybierz ten folder", + "Parent folder": "Folder nadrzędny", + "Current folder": "Bieżący folder", + "Browse root": "Katalog główny", + "Filter folders": "Filtruj foldery", + "Loading folders…": "Wczytywanie folderów…", + "No subfolders": "Brak podfolderów", + "Showing the first 500 folders. Open a subfolder to narrow the list.": "Wyświetlono pierwszych 500 folderów. Otwórz podfolder, aby zawęzić listę." } diff --git a/web/locales/uk/app.json b/web/locales/uk/app.json index 7cff89341..95b221d21 100644 --- a/web/locales/uk/app.json +++ b/web/locales/uk/app.json @@ -6240,5 +6240,15 @@ "Could not load review strategies. Try again.": "Не вдалося завантажити стратегії повторень. Спробуйте ще раз.", "Could not save review strategy. Try again.": "Не вдалося зберегти стратегію повторень. Спробуйте ще раз.", "Could not duplicate review strategy. Try again.": "Не вдалося дублювати стратегію повторень. Спробуйте ще раз.", - "Could not delete review strategy. Try again.": "Не вдалося видалити стратегію повторень. Спробуйте ще раз." + "Could not delete review strategy. Try again.": "Не вдалося видалити стратегію повторень. Спробуйте ще раз.", + "Choose a server folder": "Вибрати папку на сервері", + "Browse folders on the server and choose a project workspace.": "Перегляньте папки на сервері та виберіть робочий простір проєкту.", + "Select this folder": "Вибрати цю папку", + "Parent folder": "Батьківська папка", + "Current folder": "Поточна папка", + "Browse root": "Коренева папка перегляду", + "Filter folders": "Фільтрувати папки", + "Loading folders…": "Завантаження папок…", + "No subfolders": "Немає вкладених папок", + "Showing the first 500 folders. Open a subfolder to narrow the list.": "Показано перші 500 папок. Відкрийте вкладену папку, щоб звузити список." } diff --git a/web/locales/zh/app.json b/web/locales/zh/app.json index 9eafc49ec..a346e2bf2 100644 --- a/web/locales/zh/app.json +++ b/web/locales/zh/app.json @@ -6218,5 +6218,15 @@ "Could not load review strategies. Try again.": "无法加载复习策略,请重试。", "Could not save review strategy. Try again.": "无法保存复习策略,请重试。", "Could not duplicate review strategy. Try again.": "无法复制复习策略,请重试。", - "Could not delete review strategy. Try again.": "无法删除复习策略,请重试。" + "Could not delete review strategy. Try again.": "无法删除复习策略,请重试。", + "Choose a server folder": "选择服务器文件夹", + "Browse folders on the server and choose a project workspace.": "逐层浏览服务器文件夹,选择要使用的项目工作区。", + "Select this folder": "选择此文件夹", + "Parent folder": "返回上一级", + "Current folder": "当前文件夹", + "Browse root": "浏览根目录", + "Filter folders": "筛选文件夹", + "Loading folders…": "正在加载文件夹…", + "No subfolders": "没有子文件夹", + "Showing the first 500 folders. Open a subfolder to narrow the list.": "仅显示前 500 个文件夹,请进入子文件夹继续查找。" } diff --git a/web/tests/chat-workspace-binding.spec.tsx b/web/tests/chat-workspace-binding.spec.tsx index 3bd4274cb..5bdfdc8a7 100644 --- a/web/tests/chat-workspace-binding.spec.tsx +++ b/web/tests/chat-workspace-binding.spec.tsx @@ -21,12 +21,14 @@ const fixtures = vi.hoisted(() => ({ migrate: vi.fn(), snapshot: vi.fn(), navigateWorkspace: vi.fn(), + browse: vi.fn(), })) vi.mock('@/lib/workspace-scope', () => ({ selectWorkspace: fixtures.navigateWorkspace })) vi.mock('@/features/chat/ChatStateAdapter', () => ({ useChatStateAdapter: () => ({ state: fixtures.state, configureSession: fixtures.configure }), })) vi.mock('@/lib/workspaces-api', () => ({ + browseServerFolders: fixtures.browse, inheritedWorkspaceResources: () => ({ skills: null, mcp: null, knowledge_bases: null }), getWorkspaceResources: async () => ({ skills: [], mcp: [], knowledge_bases: [] }), listWorkspaces: fixtures.list, @@ -70,6 +72,18 @@ beforeEach(() => { }) afterEach(cleanup) +it('selects an existing server directory without renaming or rewriting its resources', async () => { + fixtures.browse.mockResolvedValue({ roots: [{ name: 'materials', path: '/materials' }], + path: workspace.path, name: 'algebra', parent: '/materials', folders: [], truncated: false }) + render() + openPicker() + fireEvent.click(screen.getByRole('menuitem', { name: 'Choose a server folder' })) + await screen.findByText('No subfolders') + fireEvent.click(screen.getByRole('button', { name: 'Select this folder' })) + await waitFor(() => expect(fixtures.navigateWorkspace).toHaveBeenCalledWith('ws_a', '/chat', expect.anything())) + expect(fixtures.save).not.toHaveBeenCalled() +}) + it('binds a draft and preserves omitted versus explicit null on the wire', async () => { render() pickAlgebra() diff --git a/web/tests/server-folder-picker.spec.tsx b/web/tests/server-folder-picker.spec.tsx new file mode 100644 index 000000000..b04e424fd --- /dev/null +++ b/web/tests/server-folder-picker.spec.tsx @@ -0,0 +1,77 @@ +import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react' +import { afterEach, expect, it, vi } from 'vitest' +import { ServerFolderPicker } from '@/components/workspaces/ServerFolderPicker' + +const fixture = vi.hoisted(() => ({ browse: vi.fn() })) +vi.mock('@/lib/workspaces-api', () => ({ browseServerFolders: fixture.browse })) +vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) })) +afterEach(() => { + cleanup() + vi.resetAllMocks() +}) + +const roots = [{ name: 'src', path: '/home/user/src' }] +const page = (path: string, folders: { name: string; path: string }[]) => ({ + roots, + path, + name: path.split('/').pop(), + parent: path === roots[0].path ? null : path.slice(0, path.lastIndexOf('/')), + folders, + truncated: false, +}) + +it('opens folders, returns to the parent and selects the visible server folder without typing paths', async () => { + fixture.browse.mockImplementation(async (path: string) => + path === '/home/user/src/oss' + ? page(path, [{ name: 'flashinfer', path: '/home/user/src/oss/flashinfer' }]) + : path === '/home/user/src/oss/flashinfer' + ? page(path, []) + : page(roots[0].path, [{ name: 'oss', path: '/home/user/src/oss' }]) + ) + const select = vi.fn() + const close = vi.fn() + render() + fireEvent.click(await screen.findByRole('button', { name: 'oss' })) + fireEvent.click(await screen.findByRole('button', { name: 'flashinfer' })) + await screen.findByText('No subfolders') + expect(screen.getByLabelText('Current folder')).toHaveTextContent('/home/user/src/oss/flashinfer') + fireEvent.click(screen.getByRole('button', { name: 'Parent folder' })) + fireEvent.click(await screen.findByRole('button', { name: 'flashinfer' })) + await screen.findByText('No subfolders') + fireEvent.click(screen.getByRole('button', { name: 'Select this folder' })) + await waitFor(() => + expect(select).toHaveBeenCalledWith({ + name: 'flashinfer', + path: '/home/user/src/oss/flashinfer', + }) + ) + await waitFor(() => expect(close).toHaveBeenCalled()) +}) + +it('keeps a failed folder load unselectable and allows retry', async () => { + fixture.browse + .mockRejectedValueOnce(new Error('Cannot open folder')) + .mockResolvedValue(page(roots[0].path, [])) + render() + await screen.findByRole('alert') + expect(screen.getByRole('button', { name: 'Select this folder' })).toBeDisabled() + fireEvent.click(screen.getByRole('button', { name: 'Retry' })) + await screen.findByText('No subfolders') + expect(screen.getByRole('button', { name: 'Select this folder' })).toBeEnabled() +}) + +it('recognizes a Windows server root while navigating its child folders', async () => { + fixture.browse.mockResolvedValue({ + roots: [ + { name: 'Projects', path: 'D:\\Projects' }, + { name: 'Other', path: 'E:\\Other' }, + ], + path: 'D:\\Projects\\Example', + name: 'Example', + parent: 'D:\\Projects', + folders: [], + truncated: false, + }) + render() + expect(await screen.findByRole('combobox', { name: 'Browse root' })).toHaveValue('D:\\Projects') +})