Files
skillshare/internal/server/handler_extensions.go
T
Willie bfc402fe96 feat(mcp): open an Agent's MCP config folder, and project files, from the dashboard (#554)
* feat(mcp): open an Agent's MCP config folder, and project files, from the dashboard

A user who wants their own editor (Notepad++ on Windows) found setting
both PATH and $EDITOR too much just to open a config file, and could not
find any entry point for the MCP files of an mcp.projects root (#538).

Each Agent row on the MCP page now also has Open folder, which opens the
folder holding the file in the file manager, so any program can open it
from there. Before the Agent has written its file, it opens the closest
folder that exists. The project MCP tab gets the same Agents list for
that project's files. The open endpoint resolves project paths from the
config, as it does global ones, so a request still cannot name another
file, and folder and file opens keep the same-machine and headless
guards. The file manager launch is shared with the extensions folder.

* fix(mcp): keep a project's existing Agent files listed for remote viewers

Codex review: the project MCP tab built its Agents list from the
project's targets plus the files this viewer could open. A viewer on a
LAN address or behind a proxy can open none, so an existing file of an
Agent outside the project's targets dropped off the list, although the
docs say it shows with its path and only the open buttons go.

The list now returns which files exist apart from whether this viewer
may open them, and the page shows the open buttons only when local.

* fix(mcp): list the Agents a project's own servers write to in its file rail

Codex review: a server that exists only in one project can pick Agents
outside the project's targets, and sync writes their project files, but
the project tab listed only the project's targets and files that already
existed. Before the first sync such an Agent had no row, so its path
could not be copied and its folder could not be opened.

The list now also takes the targets of the project's own servers. Global
servers reach a project only through its targets, so they add nothing.
The rule lives in mcpView as projectFileTargets, with a unit test.
2026-10-13 15:00:39 +08:00

203 lines
6.8 KiB
Go

package server
import (
"errors"
"fmt"
"net/http"
"os"
"os/exec"
"path/filepath"
"runtime"
"time"
"skillshare/internal/childproc"
"skillshare/internal/install"
syncpkg "skillshare/internal/sync"
)
// extensionInfo is the JSON shape for one extension in the management list.
type extensionInfo struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
Builtin bool `json:"builtin"`
Installed bool `json:"installed"`
UsedBy []string `json:"used_by,omitempty"` // names of extras referencing this extension
}
// extensionUsage maps each extension name to the extras (by name) whose targets
// reference it, so the UI can warn before removing an in-use extension.
func (s *Server) extensionUsage() map[string][]string {
usage := make(map[string][]string)
for _, extra := range s.extrasConfig() {
seen := make(map[string]bool)
for _, t := range extra.Targets {
if t.Extension == "" || seen[t.Extension] {
continue
}
seen[t.Extension] = true
usage[t.Extension] = append(usage[t.Extension], extra.Name)
}
}
return usage
}
// extensionsDir returns the transform-extensions directory for the current
// mode (~/.config/skillshare/extensions globally, .skillshare/extensions in
// project mode).
func (s *Server) extensionsDir() string {
return filepath.Join(filepath.Dir(s.configPath()), "extensions")
}
// handleExtensionsList — GET /api/extensions
// Lists installed extensions (with descriptions) merged with the built-in
// catalog, so the UI can show what's installed and what's available to install.
func (s *Server) handleExtensionsList(w http.ResponseWriter, r *http.Request) {
dir := s.extensionsDir()
names, err := syncpkg.ListExtensions(dir)
if err != nil {
writeError(w, http.StatusInternalServerError, err.Error())
return
}
usage := s.extensionUsage()
infos := make([]extensionInfo, 0, len(names))
seen := make(map[string]bool, len(names))
for _, name := range names {
info := extensionInfo{Name: name, Builtin: install.IsBuiltinExtension(name), Installed: true, UsedBy: usage[name]}
// Built-ins use the catalog description (consistent, formal wording);
// local extensions fall back to their own extension.yaml description.
if info.Builtin {
info.Description = install.BuiltinExtensionDescription(name)
} else if spec, derr := syncpkg.LoadExtensionSpec(filepath.Join(dir, name), name); derr == nil {
info.Description = spec.Description
}
infos = append(infos, info)
seen[name] = true
}
// Append built-ins that aren't installed yet (available to download).
for _, b := range install.BuiltinExtensions {
if !seen[b.Name] {
infos = append(infos, extensionInfo{Name: b.Name, Description: b.Description, Builtin: true, Installed: false})
}
}
writeJSON(w, map[string]any{"extensions": infos})
}
// handleExtensionsInstall — POST /api/extensions/install {"name": "codex-agents"}
// Downloads a built-in extension into the current mode's extensions directory.
func (s *Server) handleExtensionsInstall(w http.ResponseWriter, r *http.Request) {
start := time.Now()
var body struct {
Name string `json:"name"`
}
if err := decodeJSON(w, r, &body, defaultJSONBodyLimit); err != nil {
if !errors.Is(err, errBodyTooLarge) {
writeError(w, http.StatusBadRequest, "invalid JSON body")
}
return
}
if !install.IsBuiltinExtension(body.Name) {
writeError(w, http.StatusBadRequest, "unknown built-in extension: "+body.Name)
return
}
dir := s.extensionsDir()
if err := install.InstallBuiltinExtension(body.Name, dir); err != nil {
writeError(w, http.StatusInternalServerError, "failed to install extension: "+err.Error())
return
}
s.writeOpsLog("extensions-install", "ok", start, map[string]any{
"name": body.Name,
"scope": "ui",
}, "")
writeJSON(w, map[string]any{"success": true, "name": body.Name})
}
// handleExtensionsOpen — POST /api/extensions/open
// Opens the current mode's extensions directory in the OS file manager
// (Finder on macOS, Explorer on Windows, the default handler on Linux/BSD).
func (s *Server) handleExtensionsOpen(w http.ResponseWriter, r *http.Request) {
start := time.Now()
if os.Getenv("SKILLSHARE_HEADLESS") == "1" {
writeError(w, http.StatusConflict, "refusing to open file manager: SKILLSHARE_HEADLESS=1")
return
}
dir := s.extensionsDir()
if err := os.MkdirAll(dir, 0755); err != nil {
writeError(w, http.StatusInternalServerError, "failed to create extensions dir: "+err.Error())
return
}
if status, err := openFileManager(dir); err != nil {
writeError(w, status, err.Error())
return
}
s.writeOpsLog("extensions-open", "ok", start, map[string]any{
"path": dir,
"scope": "ui",
}, "")
writeJSON(w, map[string]any{"path": dir})
}
// openFileManager opens dir in the OS file manager without waiting for it. On failure it
// returns the HTTP status to report.
func openFileManager(dir string) (int, error) {
if os.Getenv("SKILLSHARE_HEADLESS") == "1" {
return http.StatusConflict, errors.New("refusing to open file manager: SKILLSHARE_HEADLESS=1")
}
var cmd *exec.Cmd
switch runtime.GOOS {
case "darwin":
cmd = exec.Command("open", dir)
case "windows":
cmd = exec.Command("explorer", dir)
case "linux", "freebsd", "openbsd", "netbsd":
cmd = exec.Command("xdg-open", dir)
default:
return http.StatusNotImplemented, errors.New("opening a file manager is not supported on this platform")
}
cmd.Stdin, cmd.Stdout, cmd.Stderr = nil, nil, nil
if err := childproc.StartDetached(cmd); err != nil {
return http.StatusInternalServerError, fmt.Errorf("failed to open file manager: %w", err)
}
// Explorer returns a non-zero exit code even on success; ignore Wait result.
go func() { _ = cmd.Wait() }()
return 0, nil
}
// handleExtensionsRemove — DELETE /api/extensions/{name}
// Removes an installed extension from the current mode's extensions directory.
// The UI is expected to warn the user first when the extension is still
// referenced by an extra (see extensionInfo.UsedBy); this endpoint performs the
// removal unconditionally once confirmed.
func (s *Server) handleExtensionsRemove(w http.ResponseWriter, r *http.Request) {
start := time.Now()
name := r.PathValue("name")
// Guard against path traversal: name must be a single path component.
if name == "" || name == "." || name == ".." || name != filepath.Base(name) {
writeError(w, http.StatusBadRequest, "invalid extension name")
return
}
path := filepath.Join(s.extensionsDir(), name)
if _, err := os.Stat(path); err != nil {
writeError(w, http.StatusNotFound, "extension not installed: "+name)
return
}
if err := os.RemoveAll(path); err != nil {
writeError(w, http.StatusInternalServerError, "failed to remove extension: "+err.Error())
return
}
s.writeOpsLog("extensions-remove", "ok", start, map[string]any{
"name": name,
"scope": "ui",
}, "")
writeJSON(w, map[string]any{"success": true, "name": name})
}