Merge pull request #2086: server folder picker with all supported locales

This commit is contained in:
Bingxi Zhao (Frank)
2026-10-29 01:10:00 +08:00
20 changed files with 801 additions and 6 deletions
+6
View File
@@ -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/<capability>/<session>/<turn>/`. Custom workspaces isolate conversations,
+11
View File
@@ -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
+72
View File
@@ -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,
}
+32
View File
@@ -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.
+20
View File
@@ -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"
@@ -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
@@ -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<void>
}) {
const { t } = useTranslation()
const [path, setPath] = useState('')
const [listing, setListing] = useState<ServerFolderListing | null>(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(
<Dialog
open
title={t('Choose a server folder')}
onClose={onClose}
busy={saving}
closeLabel={t('Close')}
size="lg"
description={t('Browse folders on the server and choose a project workspace.')}
footer={
<>
<button
type="button"
disabled={saving}
onClick={onClose}
className="rounded-lg px-3 py-2 text-sm hover:bg-[var(--muted)]"
>
{t('Cancel')}
</button>
<button
type="button"
disabled={loading || saving || !listing || !!error}
onClick={() => void choose()}
className="rounded-lg bg-[var(--foreground)] px-3 py-2 text-sm text-[var(--background)] disabled:opacity-50"
>
{t('Select this folder')}
</button>
</>
}
>
<div className="space-y-3">
{listing && (
<>
<div className="flex items-center gap-2">
<button
type="button"
aria-label={t('Parent folder')}
disabled={!listing.parent || loading || saving}
onClick={() => listing.parent && navigate(listing.parent)}
className="rounded-lg border border-[var(--border)] p-2 disabled:opacity-40"
>
<ArrowUp size={16} />
</button>
<p
aria-label={t('Current folder')}
className="min-w-0 flex-1 select-all break-all font-mono text-xs"
>
{listing.path}
</p>
</div>
{listing.roots.length > 1 && (
<select
aria-label={t('Browse root')}
disabled={saving || loading}
value={currentRoot?.path ?? ''}
onChange={event => navigate(event.target.value)}
className="w-full rounded-lg border border-[var(--border)] bg-[var(--background)] p-2 text-sm"
>
{listing.roots.map(root => (
<option key={root.path} value={root.path}>
{root.path}
</option>
))}
</select>
)}
</>
)}
<input
aria-label={t('Filter folders')}
placeholder={t('Filter folders')}
value={filter}
onChange={event => setFilter(event.target.value)}
className="w-full rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 text-sm"
/>
{error && (
<div className="flex items-center gap-3">
<p role="alert" className="text-sm text-[var(--destructive)]">
{error}
</p>
<button
type="button"
onClick={() => {
setLoading(true)
setError('')
setAttempt(value => value + 1)
}}
className="text-sm underline"
>
{t('Retry')}
</button>
</div>
)}
<div
aria-busy={loading}
className="h-64 overflow-y-auto rounded-lg border border-[var(--border)]"
>
{loading ? (
<p role="status" className="p-4 text-sm text-[var(--muted-foreground)]">
{t('Loading folders…')}
</p>
) : (
<>
{listing?.folders
.filter(folder =>
folder.name.toLocaleLowerCase().includes(filter.toLocaleLowerCase())
)
.map(folder => (
<button
type="button"
key={folder.path}
disabled={saving}
onClick={() => navigate(folder.path)}
className="flex w-full items-center gap-3 px-3 py-2.5 text-left text-sm hover:bg-[var(--muted)]"
>
<Folder size={17} className="shrink-0 text-[var(--muted-foreground)]" />
<span className="min-w-0 flex-1 break-words">{folder.name}</span>
<ChevronRight size={15} className="shrink-0" />
</button>
))}
{!listing?.folders.some(folder =>
folder.name.toLocaleLowerCase().includes(filter.toLocaleLowerCase())
) &&
!error && (
<p className="p-4 text-sm text-[var(--muted-foreground)]">{t('No subfolders')}</p>
)}
</>
)}
</div>
{listing?.truncated && (
<p className="text-xs text-[var(--muted-foreground)]">
{t('Showing the first 500 folders. Open a subfolder to narrow the list.')}
</p>
)}
</div>
</Dialog>,
document.body
)
}
@@ -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({
</button>
) : null}
<button type="button" role="menuitem" onClick={() => { setOpen(false); setBrowsing(true); }}
className="flex w-full items-center gap-2 border-t border-[var(--border)] px-3 py-2 text-left text-xs hover:bg-[var(--muted)]">
<FolderOpen size={15} />{t("Choose a server folder")}
</button>
{creating ? (
<form className="space-y-2 border-t border-[var(--border)] p-3" onSubmit={async event => {
event.preventDefault();
@@ -273,6 +281,14 @@ export function WorkspacePill({
</div>
</div>
)}
{browsing && <ServerFolderPicker onClose={() => 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);
}} />}
</div>
);
}
+57
View File
@@ -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;
+78
View File
@@ -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",
@@ -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<unknown>) => Promise<boolean>
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() {
}}>
<label className="block text-sm">{t('Workspace name')}<input autoFocus className={`${inputClass} mt-1`} value={name} onChange={event => setName(event.target.value)} required maxLength={100} placeholder={t('e.g. Probability')} /></label>
<label className="block text-sm">{t('Existing folder path (optional)')}<input className={`${inputClass} mt-1 font-mono`} value={path} onChange={event => setPath(event.target.value)} placeholder={t('Leave empty to create under root')} /></label>
<button type="button" className={actionClass} onClick={() => setBrowsing(true)}><Folder size={15} />{t('Choose a server folder')}</button>
<p className="text-xs leading-relaxed text-[var(--muted-foreground)]">{t('Place files in the folder for the agent to read. Generated files go into outputs/.')}</p>
<WorkspaceInstructionsField value={instructions} onChange={setInstructions} />
<WorkspaceResourcePicker value={resources} onChange={setResources} />
@@ -165,6 +169,10 @@ export default function WorkspaceSettingsSection() {
</SettingSection>
</fieldset>
)}
{browsing && <ServerFolderPicker onClose={() => setBrowsing(false)} onSelect={folder => {
setPath(folder.path)
if (!name.trim()) setName(folder.name.slice(0, 100))
}} />}
</div>
)
}
+16
View File
@@ -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<ServerFolderListing> {
return request(`/api/settings/workspace/folders?path=${encodeURIComponent(path)}`)
}
async function request<T>(url: string, init?: RequestInit): Promise<T> {
const response = await apiFetch(apiUrl(url), init)
const payload = await response.json()
+11 -1
View File
@@ -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."
}
+11 -1
View File
@@ -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."
}
+11 -1
View File
@@ -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."
}
+11 -1
View File
@@ -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ę."
}
+11 -1
View File
@@ -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 папок. Відкрийте вкладену папку, щоб звузити список."
}
+11 -1
View File
@@ -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 个文件夹,请进入子文件夹继续查找。"
}
+14
View File
@@ -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(<BindingHarness />)
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(<BindingHarness />)
pickAlgebra()
+77
View File
@@ -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(<ServerFolderPicker onClose={close} onSelect={select} />)
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(<ServerFolderPicker onClose={vi.fn()} onSelect={vi.fn()} />)
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(<ServerFolderPicker onClose={vi.fn()} onSelect={vi.fn()} />)
expect(await screen.findByRole('combobox', { name: 'Browse root' })).toHaveValue('D:\\Projects')
})