Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
feat: add native folder picker and interactive directory browser for team workspaces
Oleksandr Ivanchenko982d89522842
diff --git a/frontend/src/components/FolderBrowserModal.tsx b/frontend/src/components/FolderBrowserModal.tsxnew file mode 100644index 00000000..91bff985--- /dev/null+++ b/frontend/src/components/FolderBrowserModal.tsx@@ -0,0 +1,268 @@+import React, { useState, useEffect } from 'react';+import { X, Folder, ChevronRight, ArrowUp, Check, RefreshCw, FolderSearch, Home, Laptop } from 'lucide-react';+import { playSfx } from '../audio/chiptune';++export interface FolderBrowserModalProps {+ isOpen: boolean;+ initialPath?: string;+ onClose: () => void;+ onSelectPath: (path: string) => void;+}++interface QuickPath {+ name: string;+ path: string;+}++interface DirectoriesResponse {+ current_path: string;+ parent_path?: string | null;+ directories: string[];+ quick_paths: QuickPath[];+}++export const FolderBrowserModal: React.FC<FolderBrowserModalProps> = ({+ isOpen,+ initialPath,+ onClose,+ onSelectPath,+}) => {+ const [currentPath, setCurrentPath] = useState(initialPath || '');+ const [parentPath, setParentPath] = useState<string | null>(null);+ const [directories, setDirectories] = useState<string[]>([]);+ const [quickPaths, setQuickPaths] = useState<QuickPath[]>([]);+ const [loading, setLoading] = useState(false);+ const [error, setError] = useState<string | null>(null);++ const fetchDirectories = async (path?: string) => {+ setLoading(true);+ setError(null);+ try {+ const url = path ? `/api/system/directories?path=${encodeURIComponent(path)}` : '/api/system/directories';+ const res = await fetch(url);+ if (!res.ok) {+ throw new Error('Failed to load folder directory');+ }+ const data: DirectoriesResponse = await res.json();+ setCurrentPath(data.current_path);+ setParentPath(data.parent_path || null);+ setDirectories(data.directories);+ setQuickPaths(data.quick_paths);+ } catch (err) {+ setError(err instanceof Error ? err.message : 'Error reading folder');+ } finally {+ setLoading(false);+ }+ };++ useEffect(() => {+ if (isOpen) {+ fetchDirectories(initialPath);+ }+ }, [isOpen, initialPath]);++ if (!isOpen) return null;++ const handleNavigate = (subDir: string) => {+ playSfx('click');+ const separator = currentPath.endsWith('/') ? '' : '/';+ const target = `${currentPath}${separator}${subDir}`;+ fetchDirectories(target);+ };++ const handleNavigateParent = () => {+ if (parentPath) {+ playSfx('click');+ fetchDirectories(parentPath);+ }+ };++ const handleSelectCurrent = () => {+ playSfx('fanfare');+ onSelectPath(currentPath);+ onClose();+ };++ // Split path for breadcrumb navigation+ const pathParts = currentPath.split('/').filter(Boolean);++ return (+ <div className="fixed inset-0 z-50 bg-black/80 backdrop-blur-sm flex items-center justify-center p-4 select-none animate-in fade-in duration-150">+ <div className="bg-zinc-900 border border-zinc-800 rounded-2xl max-w-xl w-full p-5 text-zinc-100 shadow-2xl flex flex-col max-h-[85vh]">+ {/* Header */}+ <div className="flex items-center justify-between border-b border-zinc-800 pb-3 mb-3">+ <div className="flex items-center gap-2">+ <div className="w-7 h-7 rounded-lg bg-amber-500/10 border border-amber-500/20 flex items-center justify-center text-amber-400">+ <FolderSearch size={15} />+ </div>+ <div>+ <h3 className="text-sm font-semibold text-zinc-100">Select Folder</h3>+ <p className="text-[11px] text-zinc-400">Choose a local directory for your team workspace</p>+ </div>+ </div>+ <button+ onClick={() => {+ playSfx('click');+ onClose();+ }}+ className="p-1 rounded-lg text-zinc-400 hover:text-zinc-100 hover:bg-zinc-800 transition-colors"+ >+ <X size={17} />+ </button>+ </div>++ {/* Quick Jump Locations */}+ {quickPaths.length > 0 && (+ <div className="mb-3">+ <div className="text-[11px] font-medium text-zinc-400 mb-1.5 flex items-center gap-1">+ <span>Quick Jumps:</span>+ </div>+ <div className="flex flex-wrap gap-1.5">+ {quickPaths.map((qp, idx) => (+ <button+ key={idx}+ type="button"+ onClick={() => {+ playSfx('click');+ fetchDirectories(qp.path);+ }}+ className={`px-2 py-1 rounded-md text-[11px] font-mono border transition-all flex items-center gap-1.5 ${+ currentPath === qp.path+ ? 'bg-amber-500/20 text-amber-300 border-amber-500/40 shadow-sm'+ : 'bg-zinc-950 text-zinc-400 border-zinc-800 hover:border-zinc-700 hover:text-zinc-200'+ }`}+ >+ {qp.name.includes('Home') ? (+ <Home size={11} className="text-sky-400" />+ ) : (+ <Laptop size={11} className="text-zinc-400" />+ )}+ <span>{qp.name}</span>+ </button>+ ))}+ </div>+ </div>+ )}++ {/* Current Path Bar & Breadcrumbs */}+ <div className="bg-zinc-950 border border-zinc-800 rounded-lg p-2 mb-3 flex items-center justify-between gap-2 overflow-x-auto text-xs font-mono">+ <div className="flex items-center gap-1 min-w-0 flex-1 overflow-x-auto">+ <button+ type="button"+ onClick={() => fetchDirectories('/')}+ className="hover:text-amber-400 text-zinc-500 px-1 py-0.5 rounded transition-colors"+ >+ /+ </button>+ {pathParts.map((part, index) => {+ const fullSegmentPath = '/' + pathParts.slice(0, index + 1).join('/');+ const isLast = index === pathParts.length - 1;++ return (+ <React.Fragment key={index}>+ <ChevronRight size={12} className="text-zinc-600 flex-shrink-0" />+ <button+ type="button"+ onClick={() => fetchDirectories(fullSegmentPath)}+ className={`px-1 py-0.5 rounded transition-colors truncate max-w-[140px] ${+ isLast ? 'text-amber-400 font-semibold bg-amber-500/10' : 'text-zinc-400 hover:text-zinc-200'+ }`}+ title={fullSegmentPath}+ >+ {part}+ </button>+ </React.Fragment>+ );+ })}+ </div>++ <div className="flex items-center gap-1 flex-shrink-0">+ {parentPath && (+ <button+ type="button"+ onClick={handleNavigateParent}+ className="p-1 rounded bg-zinc-900 border border-zinc-800 hover:bg-zinc-800 text-zinc-300 text-[11px] flex items-center gap-1 px-2 transition-colors"+ title="Go to parent directory"+ >+ <ArrowUp size={12} />+ <span>Up</span>+ </button>+ )}+ <button+ type="button"+ onClick={() => fetchDirectories(currentPath)}+ className="p-1 rounded bg-zinc-900 border border-zinc-800 hover:bg-zinc-800 text-zinc-400 hover:text-zinc-200 transition-colors"+ title="Refresh"+ >+ <RefreshCw size={12} className={loading ? 'animate-spin' : ''} />+ </button>+ </div>+ </div>++ {error && (+ <div className="p-2 mb-3 bg-rose-500/10 border border-rose-500/20 rounded-lg text-rose-300 text-xs">+ {error}+ </div>+ )}++ {/* Directory List */}+ <div className="flex-1 overflow-y-auto border border-zinc-800 rounded-lg bg-zinc-950/60 p-1 min-h-[200px] max-h-[300px]">+ {loading ? (+ <div className="flex items-center justify-center h-36 text-xs text-zinc-500 gap-2">+ <RefreshCw size={14} className="animate-spin text-amber-400" />+ <span>Scanning directories...</span>+ </div>+ ) : directories.length === 0 ? (+ <div className="flex flex-col items-center justify-center h-36 text-xs text-zinc-500">+ <Folder size={24} className="text-zinc-600 mb-1 opacity-60" />+ <span>No subdirectories in this folder</span>+ </div>+ ) : (+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-1 p-1">+ {directories.map((dir) => (+ <button+ key={dir}+ type="button"+ onClick={() => handleNavigate(dir)}+ className="flex items-center gap-2 p-2 rounded-lg text-left text-xs text-zinc-300 hover:bg-zinc-800/80 hover:text-zinc-100 border border-transparent hover:border-zinc-700/60 transition-all group"+ >+ <Folder size={15} className="text-amber-400/80 group-hover:text-amber-400 flex-shrink-0" />+ <span className="truncate flex-1 font-mono">{dir}</span>+ <ChevronRight size={12} className="text-zinc-600 group-hover:text-zinc-400 flex-shrink-0" />+ </button>+ ))}+ </div>+ )}+ </div>++ {/* Footer Actions */}+ <div className="flex items-center justify-between pt-3 mt-3 border-t border-zinc-800">+ <div className="text-[11px] text-zinc-400 truncate max-w-xs font-mono">+ Selected: <span className="text-zinc-200">{currentPath || 'None'}</span>+ </div>+ <div className="flex items-center gap-2">+ <button+ type="button"+ onClick={() => {+ playSfx('click');+ onClose();+ }}+ className="px-3 py-1.5 rounded-lg text-xs font-medium text-zinc-300 hover:text-zinc-100 hover:bg-zinc-800 transition-colors"+ >+ Cancel+ </button>+ <button+ type="button"+ onClick={handleSelectCurrent}+ disabled={!currentPath}+ className="flex items-center gap-1.5 px-3.5 py-1.5 bg-sky-600 hover:bg-sky-500 text-white rounded-lg text-xs font-medium transition-colors shadow-sm disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer"+ >+ <Check size={13} />+ <span>Select Current Folder</span>+ </button>+ </div>+ </div>+ </div>+ </div>+ );+};diff --git a/frontend/src/components/ManageTeamModal.tsx b/frontend/src/components/ManageTeamModal.tsxindex 8eaa7070..42ebda8c 100644--- a/frontend/src/components/ManageTeamModal.tsx+++ b/frontend/src/components/ManageTeamModal.tsx@@ -1,7 +1,8 @@import React, { useState, useEffect } from 'react';-import { X, Users, Trash2, Check, AlertTriangle, ShieldCheck, Folder, GitBranch } from 'lucide-react';+import { X, Users, Trash2, Check, AlertTriangle, ShieldCheck, Folder, GitBranch, FolderSearch } from 'lucide-react';import { ModernAvatar } from './ModernAvatar';import { Team, Kwant } from './Sidebar';+import { FolderBrowserModal } from './FolderBrowserModal';import { playSfx } from '../audio/chiptune';interface ManageTeamModalProps {@@ -36,6 +37,8 @@ export const ManageTeamModal: React.FC<ManageTeamModalProps> = ({const [workspaceType, setWorkspaceType] = useState<'local' | 'repo' | 'default'>('default');const [workspacePath, setWorkspacePath] = useState('');const [repoUrl, setRepoUrl] = useState('');+ const [isBrowsing, setIsBrowsing] = useState(false);+ const [isFolderBrowserOpen, setIsFolderBrowserOpen] = useState(false);const [leadKwantId, setLeadKwantId] = useState('');const [memberIds, setMemberIds] = useState<string[]>([]);const [isDeleting, setIsDeleting] = useState(false);@@ -43,6 +46,29 @@ export const ManageTeamModal: React.FC<ManageTeamModalProps> = ({const [isSaving, setIsSaving] = useState(false);const [error, setError] = useState<string | null>(null);+ const handleBrowseFolder = async () => {+ playSfx('click');+ setIsBrowsing(true);+ try {+ const res = await fetch('/api/system/select-folder', { method: 'POST' });+ if (res.ok) {+ const data = await res.json();+ if (data.path) {+ setWorkspacePath(data.path);+ playSfx('coin');+ return;+ } else if (data.canceled) {+ return;+ }+ }+ setIsFolderBrowserOpen(true);+ } catch {+ setIsFolderBrowserOpen(true);+ } finally {+ setIsBrowsing(false);+ }+ };+useEffect(() => {if (team) {setName(team.name);@@ -259,15 +285,74 @@ export const ManageTeamModal: React.FC<ManageTeamModalProps> = ({</div>{workspaceType === 'local' && (- <div>- <input- type="text"- value={workspacePath}- onChange={(e) => setWorkspacePath(e.target.value)}- placeholder="e.g. ~/projects/my-app or /path/to/folder"- className="w-full bg-zinc-950 border border-zinc-800 rounded-lg px-3 py-2 text-xs text-zinc-100 placeholder-zinc-600 focus:border-sky-500 focus:outline-none transition-colors font-mono"- />- <p className="text-[11px] text-zinc-500 mt-1">+ <div className="space-y-2">+ <div className="flex gap-2 items-center">+ <input+ type="text"+ value={workspacePath}+ onChange={(e) => setWorkspacePath(e.target.value)}+ placeholder="e.g. ~/projects/my-app or /path/to/folder"+ className="flex-1 bg-zinc-950 border border-zinc-800 rounded-lg px-3 py-2 text-xs text-zinc-100 placeholder-zinc-600 focus:border-sky-500 focus:outline-none transition-colors font-mono"+ />+ <button+ type="button"+ onClick={handleBrowseFolder}+ disabled={isBrowsing}+ className="flex items-center gap-1.5 px-3 py-2 bg-zinc-800 hover:bg-zinc-700 active:bg-zinc-600 text-zinc-200 border border-zinc-700 rounded-lg text-xs font-medium transition-colors shadow-sm cursor-pointer whitespace-nowrap disabled:opacity-50"+ title="Open native folder chooser"+ >+ <Folder size={14} className="text-amber-400" />+ <span>{isBrowsing ? 'Selecting...' : 'Browse...'}</span>+ </button>+ <button+ type="button"+ onClick={() => {+ playSfx('click');+ setIsFolderBrowserOpen(true);+ }}+ className="p-2 bg-zinc-800 hover:bg-zinc-700 text-zinc-300 border border-zinc-700 rounded-lg transition-colors cursor-pointer"+ title="Explore local directories in-app"+ >+ <FolderSearch size={14} className="text-sky-400" />+ </button>+ </div>++ {/* Quick Directory Chips */}+ <div className="flex flex-wrap items-center gap-1.5 text-[11px]">+ <span className="text-zinc-500">Quick:</span>+ <button+ type="button"+ onClick={() => {+ playSfx('click');+ setWorkspacePath('~/dev/kwnt');+ }}+ className="px-2 py-0.5 rounded bg-zinc-950 border border-zinc-800 text-zinc-400 hover:text-zinc-200 hover:border-zinc-700 font-mono transition-colors"+ >+ ~/dev/kwnt+ </button>+ <button+ type="button"+ onClick={() => {+ playSfx('click');+ setWorkspacePath('~');+ }}+ className="px-2 py-0.5 rounded bg-zinc-950 border border-zinc-800 text-zinc-400 hover:text-zinc-200 hover:border-zinc-700 font-mono transition-colors"+ >+ ~+ </button>+ <button+ type="button"+ onClick={() => {+ playSfx('click');+ setWorkspacePath('~/dev');+ }}+ className="px-2 py-0.5 rounded bg-zinc-950 border border-zinc-800 text-zinc-400 hover:text-zinc-200 hover:border-zinc-700 font-mono transition-colors"+ >+ ~/dev+ </button>+ </div>++ <p className="text-[11px] text-zinc-500">Team members will execute commands and tools directly in this directory.</p></div>@@ -405,6 +490,16 @@ export const ManageTeamModal: React.FC<ManageTeamModalProps> = ({</div></form></div>++ <FolderBrowserModal+ isOpen={isFolderBrowserOpen}+ initialPath={workspacePath}+ onClose={() => setIsFolderBrowserOpen(false)}+ onSelectPath={(p) => {+ setWorkspacePath(p);+ playSfx('coin');+ }}+ /></div>);};diff --git a/frontend/src/components/NewTeamModal.tsx b/frontend/src/components/NewTeamModal.tsxindex 767e536d..77feb594 100644--- a/frontend/src/components/NewTeamModal.tsx+++ b/frontend/src/components/NewTeamModal.tsx@@ -1,7 +1,8 @@import React, { useState, useEffect } from 'react';-import { X, Users, AlertCircle, Folder, GitBranch } from 'lucide-react';+import { X, Users, AlertCircle, Folder, GitBranch, FolderSearch } from 'lucide-react';import { ModernAvatar } from './ModernAvatar';import { Kwant, Team } from './Sidebar';+import { FolderBrowserModal } from './FolderBrowserModal';import { playSfx } from '../audio/chiptune';export interface NewTeamModalProps {@@ -32,11 +33,36 @@ export const NewTeamModal: React.FC<NewTeamModalProps> = ({const [workspaceType, setWorkspaceType] = useState<'local' | 'repo' | 'default'>('local');const [workspacePath, setWorkspacePath] = useState('');const [repoUrl, setRepoUrl] = useState('');+ const [isBrowsing, setIsBrowsing] = useState(false);+ const [isFolderBrowserOpen, setIsFolderBrowserOpen] = useState(false);const [leadKwantId, setLeadKwantId] = useState('');const [selectedMembers, setSelectedMembers] = useState<string[]>([]);const [submitting, setSubmitting] = useState(false);const [error, setError] = useState<string | null>(null);+ const handleBrowseFolder = async () => {+ playSfx('click');+ setIsBrowsing(true);+ try {+ const res = await fetch('/api/system/select-folder', { method: 'POST' });+ if (res.ok) {+ const data = await res.json();+ if (data.path) {+ setWorkspacePath(data.path);+ playSfx('coin');+ return;+ } else if (data.canceled) {+ return;+ }+ }+ setIsFolderBrowserOpen(true);+ } catch {+ setIsFolderBrowserOpen(true);+ } finally {+ setIsBrowsing(false);+ }+ };+// Initialize or reset defaults when modal opens or kwants changeuseEffect(() => {if (isOpen) {@@ -274,15 +300,74 @@ export const NewTeamModal: React.FC<NewTeamModalProps> = ({</div>{workspaceType === 'local' && (- <div>- <input- type="text"- value={workspacePath}- onChange={(e) => setWorkspacePath(e.target.value)}- placeholder="e.g. ~/projects/my-app or /path/to/folder"- className="w-full bg-zinc-950 border border-zinc-800 rounded-lg px-3 py-2 text-xs text-zinc-100 placeholder-zinc-600 focus:border-sky-500 focus:outline-none transition-colors font-mono"- />- <p className="text-[11px] text-zinc-500 mt-1">+ <div className="space-y-2">+ <div className="flex gap-2 items-center">+ <input+ type="text"+ value={workspacePath}+ onChange={(e) => setWorkspacePath(e.target.value)}+ placeholder="e.g. ~/projects/my-app or /path/to/folder"+ className="flex-1 bg-zinc-950 border border-zinc-800 rounded-lg px-3 py-2 text-xs text-zinc-100 placeholder-zinc-600 focus:border-sky-500 focus:outline-none transition-colors font-mono"+ />+ <button+ type="button"+ onClick={handleBrowseFolder}+ disabled={isBrowsing}+ className="flex items-center gap-1.5 px-3 py-2 bg-zinc-800 hover:bg-zinc-700 active:bg-zinc-600 text-zinc-200 border border-zinc-700 rounded-lg text-xs font-medium transition-colors shadow-sm cursor-pointer whitespace-nowrap disabled:opacity-50"+ title="Open native folder chooser"+ >+ <Folder size={14} className="text-amber-400" />+ <span>{isBrowsing ? 'Selecting...' : 'Browse...'}</span>+ </button>+ <button+ type="button"+ onClick={() => {+ playSfx('click');+ setIsFolderBrowserOpen(true);+ }}+ className="p-2 bg-zinc-800 hover:bg-zinc-700 text-zinc-300 border border-zinc-700 rounded-lg transition-colors cursor-pointer"+ title="Explore local directories in-app"+ >+ <FolderSearch size={14} className="text-sky-400" />+ </button>+ </div>++ {/* Quick Directory Chips */}+ <div className="flex flex-wrap items-center gap-1.5 text-[11px]">+ <span className="text-zinc-500">Quick:</span>+ <button+ type="button"+ onClick={() => {+ playSfx('click');+ setWorkspacePath('~/dev/kwnt');+ }}+ className="px-2 py-0.5 rounded bg-zinc-950 border border-zinc-800 text-zinc-400 hover:text-zinc-200 hover:border-zinc-700 font-mono transition-colors"+ >+ ~/dev/kwnt+ </button>+ <button+ type="button"+ onClick={() => {+ playSfx('click');+ setWorkspacePath('~');+ }}+ className="px-2 py-0.5 rounded bg-zinc-950 border border-zinc-800 text-zinc-400 hover:text-zinc-200 hover:border-zinc-700 font-mono transition-colors"+ >+ ~+ </button>+ <button+ type="button"+ onClick={() => {+ playSfx('click');+ setWorkspacePath('~/dev');+ }}+ className="px-2 py-0.5 rounded bg-zinc-950 border border-zinc-800 text-zinc-400 hover:text-zinc-200 hover:border-zinc-700 font-mono transition-colors"+ >+ ~/dev+ </button>+ </div>++ <p className="text-[11px] text-zinc-500">Team members will execute commands and tools directly in this directory.</p></div>@@ -409,6 +494,16 @@ export const NewTeamModal: React.FC<NewTeamModalProps> = ({</div></form></div>++ <FolderBrowserModal+ isOpen={isFolderBrowserOpen}+ initialPath={workspacePath}+ onClose={() => setIsFolderBrowserOpen(false)}+ onSelectPath={(p) => {+ setWorkspacePath(p);+ playSfx('coin');+ }}+ /></div>);};diff --git a/src/server/mod.rs b/src/server/mod.rsindex ab7ba43b..6205d273 100644--- a/src/server/mod.rs+++ b/src/server/mod.rs@@ -66,6 +66,8 @@ pub fn create_router(state: AppState) -> Router {.route("/api/chat/cancel", post(routes::cancel_chat)).route("/api/approvals/:id/resolve", post(routes::resolve_approval)).route("/api/settings", get(routes::get_settings).post(routes::save_settings))+ .route("/api/system/directories", get(routes::list_system_directories))+ .route("/api/system/select-folder", post(routes::select_folder)).route("/api/events", get(sse::sse_handler)).fallback(crate::embedded::static_handler).layer(cors)diff --git a/src/server/routes.rs b/src/server/routes.rsindex c812ca31..6df1140e 100644--- a/src/server/routes.rs+++ b/src/server/routes.rs@@ -4,11 +4,12 @@ use crate::db::models::*;use crate::drivers::{find_cli_binary, resolve_driver_for_model, RuntimeEvent, TurnInput};use crate::router::{parse_mentions_with_lookup, TagMention, TeamDecision};use axum::{- extract::{Path, State},+ extract::{Path, Query, State},http::StatusCode,response::IntoResponse,Json,};+use std::path::PathBuf;use serde::{Deserialize, Serialize};use serde_json::json;use tokio::sync::mpsc;@@ -883,3 +884,196 @@ pub async fn save_settings(Ok(Json(json!({ "status": "saved" })))}+#[derive(Debug, Deserialize)]+pub struct DirectoriesQuery {+ pub path: Option<String>,+}++#[derive(Debug, Serialize)]+pub struct QuickPath {+ pub name: String,+ pub path: String,+}++#[derive(Debug, Serialize)]+pub struct DirectoriesResponse {+ pub current_path: String,+ pub parent_path: Option<String>,+ pub directories: Vec<String>,+ pub quick_paths: Vec<QuickPath>,+}++pub async fn list_system_directories(+ Query(query): Query<DirectoriesQuery>,+) -> Result<Json<DirectoriesResponse>, StatusCode> {+ let home_dir = std::env::var("HOME").ok().map(PathBuf::from);+ let current_dir = std::env::current_dir().ok();++ let target_path = if let Some(p) = query.path.filter(|s| !s.trim().is_empty()) {+ let trimmed = p.trim();+ if trimmed.starts_with("~/") {+ if let Some(ref home) = home_dir {+ home.join(&trimmed[2..])+ } else {+ PathBuf::from(trimmed)+ }+ } else {+ PathBuf::from(trimmed)+ }+ } else if let Some(ref cur) = current_dir {+ cur.clone()+ } else if let Some(ref home) = home_dir {+ home.clone()+ } else {+ PathBuf::from("/")+ };++ let canonical_target = match target_path.canonicalize() {+ Ok(c) => c,+ Err(_) => target_path.clone(),+ };++ let mut directories = Vec::new();+ if let Ok(mut entries) = tokio::fs::read_dir(&canonical_target).await {+ while let Ok(Some(entry)) = entries.next_entry().await {+ if let Ok(file_type) = entry.file_type().await {+ if file_type.is_dir() {+ let name = entry.file_name().to_string_lossy().to_string();+ if !name.starts_with('.') {+ directories.push(name);+ }+ }+ }+ }+ }+ directories.sort_by(|a, b| a.to_lowercase().cmp(&b.to_lowercase()));++ let parent_path = canonical_target.parent().map(|p| p.to_string_lossy().to_string());++ let mut quick_paths = Vec::new();+ if let Some(ref cur) = current_dir {+ quick_paths.push(QuickPath {+ name: "Current Project".into(),+ path: cur.to_string_lossy().to_string(),+ });+ }+ if let Some(ref home) = home_dir {+ quick_paths.push(QuickPath {+ name: "Home (~)".into(),+ path: home.to_string_lossy().to_string(),+ });+ let dev_path = home.join("dev");+ if dev_path.exists() {+ quick_paths.push(QuickPath {+ name: "~/dev".into(),+ path: dev_path.to_string_lossy().to_string(),+ });+ }+ let projects_path = home.join("projects");+ if projects_path.exists() {+ quick_paths.push(QuickPath {+ name: "~/projects".into(),+ path: projects_path.to_string_lossy().to_string(),+ });+ }+ let docs_path = home.join("Documents");+ if docs_path.exists() {+ quick_paths.push(QuickPath {+ name: "Documents".into(),+ path: docs_path.to_string_lossy().to_string(),+ });+ }+ }++ Ok(Json(DirectoriesResponse {+ current_path: canonical_target.to_string_lossy().to_string(),+ parent_path,+ directories,+ quick_paths,+ }))+}++#[derive(Debug, Serialize, Deserialize)]+pub struct SelectFolderResponse {+ pub path: Option<String>,+ pub canceled: bool,+}++pub async fn select_folder() -> Result<Json<SelectFolderResponse>, StatusCode> {+ if std::env::var("KWNT_TEST_MODE").is_ok() {+ return Ok(Json(SelectFolderResponse {+ path: None,+ canceled: true,+ }));+ }++ #[cfg(target_os = "macos")]+ {+ let res = tokio::process::Command::new("osascript")+ .arg("-e")+ .arg("POSIX path of (choose folder with prompt \"Select Team Workspace Folder:\")")+ .output()+ .await;++ match res {+ Ok(output) if output.status.success() => {+ let raw = String::from_utf8_lossy(&output.stdout);+ let path = raw.trim().trim_end_matches('/').to_string();+ if !path.is_empty() {+ return Ok(Json(SelectFolderResponse {+ path: Some(path),+ canceled: false,+ }));+ }+ }+ Ok(output) => {+ let err = String::from_utf8_lossy(&output.stderr);+ if err.contains("User canceled") || err.contains("-128") {+ return Ok(Json(SelectFolderResponse {+ path: None,+ canceled: true,+ }));+ }+ tracing::warn!("osascript folder picker output error: {}", err);+ }+ Err(e) => {+ tracing::warn!("Failed to invoke osascript: {}", e);+ }+ }+ }++ #[cfg(target_os = "linux")]+ {+ let res = tokio::process::Command::new("zenity")+ .arg("--file-selection")+ .arg("--directory")+ .arg("--title=Select Team Workspace Folder")+ .output()+ .await;++ if let Ok(output) = res {+ if output.status.success() {+ let raw = String::from_utf8_lossy(&output.stdout);+ let path = raw.trim().trim_end_matches('/').to_string();+ if !path.is_empty() {+ return Ok(Json(SelectFolderResponse {+ path: Some(path),+ canceled: false,+ }));+ }+ } else {+ return Ok(Json(SelectFolderResponse {+ path: None,+ canceled: true,+ }));+ }+ }+ }++ // Fallback if native dialog is not supported on platform or headless+ Ok(Json(SelectFolderResponse {+ path: None,+ canceled: false,+ }))+}+diff --git a/tests/server_test.rs b/tests/server_test.rsindex 5b2ff543..c261b33a 100644--- a/tests/server_test.rs+++ b/tests/server_test.rs@@ -300,4 +300,70 @@ async fn test_cancel_chat_with_null_fields_only_cancels_target_kwant() {assert!(tokens.contains_key("other-session"));}+#[tokio::test]+async fn test_system_directories_endpoint() {+ let tmp = tempdir().unwrap();+ let db = Database::init(tmp.path()).await.unwrap();+ let config = Config::default();+ let tools = ToolRunner::new(tmp.path().join("workspace"));+ let broker = PermissionBroker::new();+ let router = LayaRouter::new(config.laya_url.clone());++ let state = AppState::new(config, db, tools, broker, router);+ let app = create_router(state);++ // Create test subdirectories inside tmp+ std::fs::create_dir_all(tmp.path().join("project-alpha")).unwrap();+ std::fs::create_dir_all(tmp.path().join("project-beta")).unwrap();+ std::fs::write(tmp.path().join("some-file.txt"), "hello").unwrap();++ let uri = format!("/api/system/directories?path={}", tmp.path().display());+ let req = Request::builder()+ .uri(&uri)+ .body(Body::empty())+ .unwrap();++ let resp = app.clone().oneshot(req).await.unwrap();+ assert_eq!(resp.status(), StatusCode::OK);++ let body = axum::body::to_bytes(resp.into_body(), 1024 * 64).await.unwrap();+ let json: serde_json::Value = serde_json::from_slice(&body).unwrap();++ let dirs = json["directories"].as_array().expect("directories array");+ let dir_names: Vec<&str> = dirs.iter().filter_map(|d| d.as_str()).collect();++ assert!(dir_names.contains(&"project-alpha"));+ assert!(dir_names.contains(&"project-beta"));+ assert!(!dir_names.contains(&"some-file.txt"), "Files should not be listed as directories");+ assert!(json["current_path"].is_string());+ assert!(json["quick_paths"].is_array());+}++#[tokio::test]+async fn test_system_select_folder_endpoint() {+ std::env::set_var("KWNT_TEST_MODE", "1");+ let tmp = tempdir().unwrap();+ let db = Database::init(tmp.path()).await.unwrap();+ let config = Config::default();+ let tools = ToolRunner::new(tmp.path().join("workspace"));+ let broker = PermissionBroker::new();+ let router = LayaRouter::new(config.laya_url.clone());++ let state = AppState::new(config, db, tools, broker, router);+ let app = create_router(state);++ let req = Request::builder()+ .method("POST")+ .uri("/api/system/select-folder")+ .body(Body::empty())+ .unwrap();++ let resp = app.clone().oneshot(req).await.unwrap();+ assert_eq!(resp.status(), StatusCode::OK);++ let body = axum::body::to_bytes(resp.into_body(), 1024 * 64).await.unwrap();+ let json: serde_json::Value = serde_json::from_slice(&body).unwrap();+ assert!(json.get("canceled").is_some());+}+