| 1 | package workbench |
| 2 | |
| 3 | import ( |
| 4 | "io" |
| 5 | "net/http" |
| 6 | "os" |
| 7 | "path/filepath" |
| 8 | "sort" |
| 9 | "strings" |
| 10 | |
| 11 | "github.com/sylvinus/agent-vm/internal/cage" |
| 12 | "github.com/sylvinus/agent-vm/internal/paths" |
| 13 | ) |
| 14 | |
| 15 | |
| 16 | |
| 17 | func (s *Server) projectDirectories(w http.ResponseWriter, r *http.Request) { |
| 18 | path := r.URL.Query().Get("path") |
| 19 | if path == "" { |
| 20 | path, _ = os.UserHomeDir() |
| 21 | } |
| 22 | if !filepath.IsAbs(path) { |
| 23 | http.Error(w, "请选择服务器上的绝对路径", 400) |
| 24 | return |
| 25 | } |
| 26 | real, err := paths.Resolve(path) |
| 27 | if err != nil { |
| 28 | http.Error(w, "服务器目录不存在或无法访问", 400) |
| 29 | return |
| 30 | } |
| 31 | reserved, err := privateProjectDirectories(s.profile) |
| 32 | if err == nil { |
| 33 | var home string |
| 34 | home, err = os.UserHomeDir() |
| 35 | if err == nil { |
| 36 | var other []string |
| 37 | other, err = privateProjectDirectories(filepath.Join(home, ".claude-cage")) |
| 38 | reserved = append(reserved, other...) |
| 39 | } |
| 40 | } |
| 41 | if err != nil { |
| 42 | http.Error(w, "无法验证环境存储目录", 500) |
| 43 | return |
| 44 | } |
| 45 | private := func(path string) bool { |
| 46 | for _, dir := range reserved { |
| 47 | if cage.StorageContains(dir, path) { |
| 48 | return true |
| 49 | } |
| 50 | } |
| 51 | return false |
| 52 | } |
| 53 | if private(real) { |
| 54 | http.Error(w, "Cage 配置目录不能作为项目浏览", 403) |
| 55 | return |
| 56 | } |
| 57 | directory, err := os.Open(real) |
| 58 | if err != nil { |
| 59 | http.Error(w, "无法读取服务器目录", 403) |
| 60 | return |
| 61 | } |
| 62 | defer directory.Close() |
| 63 | entries, err := directory.ReadDir(2001) |
| 64 | if err != nil && err != io.EOF { |
| 65 | http.Error(w, "无法读取服务器目录", 403) |
| 66 | return |
| 67 | } |
| 68 | if len(entries) > 2000 { |
| 69 | http.Error(w, "此目录项目过多,请直接输入更具体的路径", 413) |
| 70 | return |
| 71 | } |
| 72 | type child struct { |
| 73 | Name string `json:"name"` |
| 74 | Path string `json:"path"` |
| 75 | } |
| 76 | children := []child{} |
| 77 | for _, entry := range entries { |
| 78 | if !entry.IsDir() || strings.HasPrefix(entry.Name(), ".") { |
| 79 | continue |
| 80 | } |
| 81 | path := filepath.Join(real, entry.Name()) |
| 82 | if physical, err := paths.Resolve(path); err == nil && !private(physical) { |
| 83 | children = append(children, child{Name: entry.Name(), Path: physical}) |
| 84 | } |
| 85 | } |
| 86 | sort.Slice(children, func(i, j int) bool { return children[i].Name < children[j].Name }) |
| 87 | _, selectableError := validateWorkspace(real, s.profile) |
| 88 | jsonReply(w, map[string]any{"path": real, "parent": filepath.Dir(real), "directories": children, "selectable": selectableError == nil}) |
| 89 | } |