diff --git a/.github/workflows/release-qa-gate.yml b/.github/workflows/release-qa-gate.yml index bd90dd26b..bda7c2179 100644 --- a/.github/workflows/release-qa-gate.yml +++ b/.github/workflows/release-qa-gate.yml @@ -128,6 +128,8 @@ jobs: # failed that test. go build -tags server,nogui -ldflags "${LDFLAGS}" -o dist-bin/mcpproxy-server ./cmd/mcpproxy go build -o dist-bin/mcpfixture ./cmd/mcpfixture + # Spec 125: the skills-capable upstream of the Skills tab sweep. + go build -o dist-bin/skillsfixture ./cmd/skillsfixture go build -o dist-bin/oauthserver ./tests/oauthserver/cmd/server go build -o dist-bin/release-gate ./cmd/release-gate ./dist-bin/mcpproxy --version || true @@ -530,7 +532,12 @@ jobs: name: Web UI sweep (advisory) needs: build-candidate runs-on: ubuntu-latest - timeout-minutes: 20 + # Two sweeps in one job: run-web-smoke.sh (which had 20 minutes alone) and + # the Skills tab sweep with --self-test-first (two throwaway cores for the + # self-test, its own npm ci + Chromium install, eight serial scenarios; + # about 35 s locally with the browser and builds cached, about 1 min with a + # scenario timing out). 35 minutes leaves headroom for a cold runner. + timeout-minutes: 35 continue-on-error: true # advisory: never blocks the tag (FR-019 pattern) steps: - name: Checkout @@ -562,6 +569,28 @@ jobs: --name advisory/web-ui-sweep --advisory --report-dir "${GATE_REPORT_DIR}" \ -- bash scripts/run-web-smoke.sh + # Spec 125: the Skills tab sweep needs enable_skills and a skills-capable + # upstream, so it has its own launcher (throwaway core + cmd/skillsfixture + # on free loopback ports). It runs even when the sweep above failed, inside + # this advisory job, and records its own ADVISORY manifest entry + # (advisory/skills-tab-sweep), so a red run is listed under the verdict's + # advisory_failures; its fragment lands in GATE_REPORT_DIR, which the + # fragment upload below carries. Its results file (skills-sweep-results.json) + # and screenshots land under tmp/web-smoke-artifacts/, which the Playwright + # report upload below already carries. --self-test-first first proves that + # no ambient MCPPROXY_* (data dir, audit log path, ...) reaches the core, + # that the results writer redacts the API key, and that a DEBUG=1 run + # never prints it. + - name: Run Skills tab sweep (spec 125) + if: ${{ !cancelled() }} + env: + MCPPROXY_BINARY_PATH: ${{ github.workspace }}/dist-bin/mcpproxy + SKILLS_FIXTURE_BINARY: ${{ github.workspace }}/dist-bin/skillsfixture + run: | + ./dist-bin/release-gate run-suite \ + --name advisory/skills-tab-sweep --advisory --report-dir "${GATE_REPORT_DIR}" \ + -- bash scripts/run-skills-tab-sweep.sh --self-test-first --out "${GITHUB_WORKSPACE}/tmp/web-smoke-artifacts/skills-sweep" + - name: Upload Playwright report if: always() uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 diff --git a/ROADMAP.md b/ROADMAP.md index 2633f98ea..0c832a579 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -1262,7 +1262,7 @@ graph LR | Spec 108 profiles v3: scoped profiles, client binding, scope-aware observability | In progress | P1 | 194/195 (99%) | [108-profiles-v3](./specs/108-profiles-v3/) | | | Spec 109 navigation, scope filters and cross-surface UX consistency | In progress | P1 | 257/258 (100%) | [109-ux-navigation-consistency](./specs/109-ux-navigation-consistency/) | | | Spec 124 work sessions and the failure timeline | In progress | P1 | 0/74 (0%) | [124-session-failure-timeline](./specs/124-session-failure-timeline/) | | -| Spec 125 Skills over MCP: catalog, approval gate, read-only agent tools | In progress | P1 | 41/51 (80%) | [125-skills-over-mcp](./specs/125-skills-over-mcp/) | | +| Spec 125 Skills over MCP: catalog, approval gate, read-only agent tools | In progress | P1 | 44/51 (86%) | [125-skills-over-mcp](./specs/125-skills-over-mcp/) | | | Planning/docs truth automation | In progress | P2 | — | | | | Discovery-quality eval harness (Spec 065 second half) | In progress | P3 | — | [065-evaluation-foundation](./specs/065-evaluation-foundation/) | | | Spec 114 typed pending-call outcome + call correlation for long-running stdio tool calls | In review | P2 | — | | #1536 | @@ -1439,7 +1439,7 @@ Legend: `shipped` ≥95% checked · `in-flight` 1–94% · `drafted` 0% · `—` | [122-scanner-skillspector-checks](./specs/122-scanner-skillspector-checks/) | `shipped` | 31/31 (100%) | | [123-oauth-token-encryption](./specs/123-oauth-token-encryption/) | `drafted` | 0/56 (0%) | | [124-session-failure-timeline](./specs/124-session-failure-timeline/) | `drafted` | 0/74 (0%) | -| [125-skills-over-mcp](./specs/125-skills-over-mcp/) | `in-flight` | 41/51 (80%) | +| [125-skills-over-mcp](./specs/125-skills-over-mcp/) | `in-flight` | 44/51 (86%) | | [127-profile-argument-rules](./specs/127-profile-argument-rules/) | — | — | | [128-server-list-outcomes](./specs/128-server-list-outcomes/) | — | — | | [129-per-user-upstream-credentials](./specs/129-per-user-upstream-credentials/) | — | — | diff --git a/cmd/release-gate/webui_sweep_audit_test.go b/cmd/release-gate/webui_sweep_audit_test.go index 3844b97f4..279277f3e 100644 --- a/cmd/release-gate/webui_sweep_audit_test.go +++ b/cmd/release-gate/webui_sweep_audit_test.go @@ -2,6 +2,7 @@ package main import ( "path/filepath" + "regexp" "strings" "testing" @@ -82,6 +83,65 @@ func TestWebUISweepJobReportsAndUploads(t *testing.T) { if !strings.Contains(uploads, "playwright-report") { t.Errorf("the sweep job must upload the Playwright HTML report artifact; upload steps: %s", uploads) } + // Spec 125: the Skills tab sweep runs in the same advisory job, and its + // results file lands inside the uploaded artifact directory. + var skillsStep *step + for i := range sweep.Steps { + if strings.Contains(sweep.Steps[i].Run, "scripts/run-skills-tab-sweep.sh") { + skillsStep = &sweep.Steps[i] + } + } + if skillsStep == nil { + t.Fatalf("the sweep job must run scripts/run-skills-tab-sweep.sh; run steps: %s", runs) + } + if !strings.Contains(skillsStep.Run, "tmp/web-smoke-artifacts/") { + t.Errorf("run-skills-tab-sweep.sh must write into tmp/web-smoke-artifacts/ so its results file is uploaded with the job's artifacts: %s", skillsStep.Run) + } + // Its outcome must reach the gate verdict: wrapped in run-suite under its + // own advisory manifest entry, so a red skills sweep is listed under + // advisory_failures instead of vanishing inside continue-on-error. + for _, want := range []string{"release-gate run-suite", "--name " + gatereport.EntryAdvisorySkillsTabSweep, "--advisory", "--report-dir", "--self-test-first"} { + if !strings.Contains(skillsStep.Run, want) { + t.Errorf("the Skills tab sweep step must run through `release-gate run-suite --name %s --advisory --report-dir ... -- bash scripts/run-skills-tab-sweep.sh --self-test-first ...` (missing %q): %s", + gatereport.EntryAdvisorySkillsTabSweep, want, skillsStep.Run) + } + } + if skillsStep.If == "" || !strings.Contains(skillsStep.If, "!cancelled()") { + t.Errorf("the Skills tab sweep step must run even when the sweep before it failed (if: !cancelled()), got %q", skillsStep.If) + } +} + +// runSuiteNameRe matches the entry name of every `release-gate run-suite` call. +var runSuiteNameRe = regexp.MustCompile(`run-suite\s*\\?\s*--name\s+(\S+)`) + +// TestEveryRunSuiteNameIsInTheManifest: a run-suite call whose --name no +// manifest entry declares writes a fragment the merger treats as unexpected, +// and a manifest entry no step writes is a missing fragment. Every suite the +// gate workflow runs must be a declared entry, and every advisory entry that is +// a workflow step must be run by one. +func TestEveryRunSuiteNameIsInTheManifest(t *testing.T) { + wf := parseWorkflow(t, gateWorkflowPath) + declared := map[string]bool{} + for _, m := range gatereport.Manifest() { + declared[m.Name] = true + } + seen := map[string]bool{} + for jobName, job := range wf.Jobs { + for _, s := range job.Steps { + for _, m := range runSuiteNameRe.FindAllStringSubmatch(s.Run, -1) { + name := strings.Trim(m[1], `"'`) + seen[name] = true + if !declared[name] { + t.Errorf("job %q runs suite %q, which no gatereport.Manifest() entry declares", jobName, name) + } + } + } + } + for _, name := range []string{gatereport.EntryAdvisoryWebUISweep, gatereport.EntryAdvisorySkillsTabSweep, gatereport.EntryAdvisoryMacOSSmoke} { + if !seen[name] { + t.Errorf("no workflow step runs the advisory suite %q (its fragment would always be missing)", name) + } + } } // yamlFlatten renders a `with:` mapping node as a flat string for substring diff --git a/cmd/release-gate/webui_sweep_speclist_test.go b/cmd/release-gate/webui_sweep_speclist_test.go index 8cbe5d696..55317939d 100644 --- a/cmd/release-gate/webui_sweep_speclist_test.go +++ b/cmd/release-gate/webui_sweep_speclist_test.go @@ -20,21 +20,28 @@ import ( var playwrightTestLine = regexp.MustCompile(`"\$PLAYWRIGHT_BIN"\s+test\s+(.+)`) -// sweepSpecsRun parses the spec names off the launcher's `playwright test` line. +// sweepLaunchers are the scripts the web-ui-sweep job runs. run-web-smoke.sh +// is the standing sweep; run-skills-tab-sweep.sh (spec 125) runs the spec that +// needs a skills-capable upstream and enable_skills. +var sweepLaunchers = []string{"run-web-smoke.sh", "run-skills-tab-sweep.sh"} + +// sweepSpecsRun parses the spec names off every launcher's `playwright test` line. func sweepSpecsRun(t *testing.T) []string { t.Helper() - b, err := os.ReadFile(filepath.Join(repoRootFromTest, "scripts", "run-web-smoke.sh")) - if err != nil { - t.Fatal(err) - } - m := playwrightTestLine.FindStringSubmatch(string(b)) - if m == nil { - t.Fatal(`scripts/run-web-smoke.sh has no "$PLAYWRIGHT_BIN" test line: the sweep runs nothing`) - } var specs []string - for _, field := range strings.Fields(m[1]) { - if strings.HasSuffix(field, ".spec.ts") { - specs = append(specs, field) + for _, launcher := range sweepLaunchers { + b, err := os.ReadFile(filepath.Join(repoRootFromTest, "scripts", launcher)) + if err != nil { + t.Fatal(err) + } + m := playwrightTestLine.FindStringSubmatch(string(b)) + if m == nil { + t.Fatalf(`scripts/%s has no "$PLAYWRIGHT_BIN" test line: it runs nothing`, launcher) + } + for _, field := range strings.Fields(m[1]) { + if strings.HasSuffix(field, ".spec.ts") { + specs = append(specs, field) + } } } sort.Strings(specs) @@ -70,7 +77,7 @@ func specListProblems(run, onDisk []string, docs map[string]string) []string { } for _, name := range onDisk { if !has(run, name) { - problems = append(problems, name+" exists in e2e/web-ui-sweep but scripts/run-web-smoke.sh does not run it (an orphan spec never gates a release)") + problems = append(problems, name+" exists in e2e/web-ui-sweep but no sweep launcher (scripts/run-web-smoke.sh, scripts/run-skills-tab-sweep.sh) runs it (an orphan spec never gates a release)") } } for _, name := range run { diff --git a/cmd/release-gate/workflow_audit_test.go b/cmd/release-gate/workflow_audit_test.go index f3370eca6..f92e8df58 100644 --- a/cmd/release-gate/workflow_audit_test.go +++ b/cmd/release-gate/workflow_audit_test.go @@ -77,6 +77,7 @@ type job struct { type step struct { Uses string `yaml:"uses"` Run string `yaml:"run"` + If string `yaml:"if"` With yaml.Node `yaml:"with"` } diff --git a/cmd/skillsfixture/main.go b/cmd/skillsfixture/main.go new file mode 100644 index 000000000..00163fce4 --- /dev/null +++ b/cmd/skillsfixture/main.go @@ -0,0 +1,149 @@ +// Command skillsfixture serves a fake upstream MCP server with three skills so +// the Skills tab of the Web UI can be exercised against a real core (spec 125, +// docs/development/web-ui-verification.md). It is a development tool, not part +// of any release. +// +// skillsfixture -addr 127.0.0.1:18931 +// +// Point an upstream at /mcp (streamable HTTP). To make a skill +// change, POST the new bytes of one file: +// +// curl -X POST -H 'X-Skills-Fixture: mutate' --data-binary @SKILL.md \ +// 'http://127.0.0.1:18931/_fixture/mutate?skill=plain&file=SKILL.md' +// +// It answers only requests whose Host is the address it listens on (no DNS +// rebinding), and mutate refuses any request with an Origin header. +package main + +import ( + "flag" + "fmt" + "io" + "log" + "net" + "net/http" + "os" + "slices" + "strings" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/skills/skillstest" +) + +func main() { + addr := flag.String("addr", "127.0.0.1:0", "listen address (loopback only)") + flag.Parse() + if err := run(*addr); err != nil { + log.Fatal(err) + } +} + +func run(addr string) error { + host, _, err := net.SplitHostPort(addr) + if err != nil { + return err + } + if ip := net.ParseIP(host); host != "localhost" && (ip == nil || !ip.IsLoopback()) { + return fmt.Errorf("skillsfixture listens on loopback only, got %q", host) + } + ln, err := net.Listen("tcp", addr) + if err != nil { + return err + } + f := skillstest.NewDetached() + Seed(f) + if _, err := fmt.Fprintf(os.Stdout, "skillsfixture listening on http://%s/mcp\n", ln.Addr()); err != nil { + _ = ln.Close() + return fmt.Errorf("announce fixture address: %w", err) + } + return http.Serve(ln, Handler(f, allowedHosts(addr, ln.Addr())...)) +} + +// Seed registers the three skills: a plain one, one with a supporting text file +// and a binary file, and one with a file large enough to need several parts. +func Seed(f *skillstest.Fixture) { + f.AddSkill(skillstest.Skill{Path: "plain"}) + f.AddSkill(skillstest.Skill{ + Path: "with-files", + Files: map[string][]byte{ + "notes.txt": []byte("Supporting notes\nsecond line\n"), + "logo.bin": {0x89, 'P', 'N', 'G', 0x00, 0x01, 0x02, 0x03}, + }, + Binary: []string{"logo.bin"}, + }) + var big strings.Builder + for i := 1; big.Len() < 150*1024; i++ { + fmt.Fprintf(&big, "line %06d of the large reference file\n", i) + } + f.AddSkill(skillstest.Skill{ + Path: "big", + Files: map[string][]byte{"data/large.txt": []byte(big.String())}, + }) +} + +// MutateHeader must carry MutateHeaderValue on every mutate request. A web page +// cannot add a custom header to a cross-site request without a CORS preflight, +// which the fixture never grants, so a page the operator happens to have open +// cannot change a skill under review. +const ( + MutateHeader = "X-Skills-Fixture" + MutateHeaderValue = "mutate" +) + +// allowedHosts is the set of Host values the fixture answers: the address it +// actually listens on, plus localhost: when it was started as localhost. +func allowedHosts(requested string, actual net.Addr) []string { + out := []string{actual.String()} + if host, _, err := net.SplitHostPort(requested); err == nil && host == "localhost" { + if _, port, err := net.SplitHostPort(actual.String()); err == nil { + out = append(out, net.JoinHostPort("localhost", port)) + } + } + return out +} + +// Handler serves the fixture's JSON-RPC on every path except /_fixture/mutate, +// which replaces one file: POST ?skill=&file= with the new bytes +// as the body and the MutateHeader set. Any request whose Host is not one of +// hosts (DNS rebinding: a foreign name that resolves to 127.0.0.1) is refused +// with 421, and a mutate request that carries an Origin header (every browser +// request does) is refused with 403. +func Handler(f *skillstest.Fixture, hosts ...string) http.Handler { + mux := http.NewServeMux() + mux.HandleFunc("/_fixture/mutate", func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost { + http.Error(w, "POST only", http.StatusMethodNotAllowed) + return + } + if _, ok := r.Header["Origin"]; ok { + http.Error(w, "mutate refuses browser requests (Origin header present)", http.StatusForbidden) + return + } + if r.Header.Get(MutateHeader) != MutateHeaderValue { + http.Error(w, "mutate needs the header "+MutateHeader+": "+MutateHeaderValue, http.StatusForbidden) + return + } + skill, file := r.URL.Query().Get("skill"), r.URL.Query().Get("file") + if skill == "" || file == "" { + http.Error(w, "skill and file are required", http.StatusBadRequest) + return + } + body, err := io.ReadAll(io.LimitReader(r.Body, 4<<20)) + if err != nil || len(body) == 0 { + http.Error(w, "a non-empty body is required", http.StatusBadRequest) + return + } + if err := f.TryMutate(skill, file, body); err != nil { + http.Error(w, err.Error(), http.StatusNotFound) + return + } + w.WriteHeader(http.StatusNoContent) + }) + mux.Handle("/", f.Handler()) + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if !slices.Contains(hosts, r.Host) { + http.Error(w, "unexpected Host", http.StatusMisdirectedRequest) + return + } + mux.ServeHTTP(w, r) + }) +} diff --git a/cmd/skillsfixture/main_test.go b/cmd/skillsfixture/main_test.go new file mode 100644 index 000000000..9448c2aea --- /dev/null +++ b/cmd/skillsfixture/main_test.go @@ -0,0 +1,172 @@ +package main + +import ( + "bytes" + "encoding/json" + "net" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/skills/skillstest" +) + +func rpc(t *testing.T, url, method, uri string) map[string]any { + t.Helper() + body, _ := json.Marshal(map[string]any{"jsonrpc": "2.0", "id": 1, "method": method, "params": map[string]any{"uri": uri}}) + resp, err := http.Post(url, "application/json", bytes.NewReader(body)) + if err != nil { + t.Fatal(err) + } + defer func() { assert.NoError(t, resp.Body.Close()) }() + var out map[string]any + if err := json.NewDecoder(resp.Body).Decode(&out); err != nil { + t.Fatal(err) + } + return out +} + +// startFixture serves Handler on a loopback listener, bound to that listener's +// own address as the only accepted Host. +func startFixture(t *testing.T) *httptest.Server { + t.Helper() + f := skillstest.NewDetached() + Seed(f) + srv := httptest.NewUnstartedServer(nil) + srv.Config.Handler = Handler(f, srv.Listener.Addr().String()) + srv.Start() + t.Cleanup(srv.Close) + return srv +} + +// mutate posts one file change with the given extra headers. +func mutate(t *testing.T, base, query, body string, header map[string]string) int { + t.Helper() + req, err := http.NewRequest(http.MethodPost, base+"/_fixture/mutate?"+query, strings.NewReader(body)) + if err != nil { + t.Fatal(err) + } + req.Header.Set("Content-Type", "text/plain") + for k, v := range header { + req.Header.Set(k, v) + } + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + assert.NoError(t, resp.Body.Close()) + return resp.StatusCode +} + +func TestSeedServesThreeSkillsAndMutateChangesOne(t *testing.T) { + srv := startFixture(t) + + list := rpc(t, srv.URL+"/mcp", "skills/list", "") + entries := list["result"].(map[string]any)["skills"].([]any) + if len(entries) != 3 { + t.Fatalf("want 3 skills, got %d", len(entries)) + } + + large := rpc(t, srv.URL+"/mcp", "resources/read", "skill://big/data/large.txt") + text := large["result"].(map[string]any)["contents"].([]any)[0].(map[string]any)["text"].(string) + if len(text) <= 128*1024 { + t.Fatalf("large file is %d bytes, want more than two 64 KiB parts", len(text)) + } + + bin := rpc(t, srv.URL+"/mcp", "resources/read", "skill://with-files/logo.bin") + if _, ok := bin["result"].(map[string]any)["contents"].([]any)[0].(map[string]any)["blob"]; !ok { + t.Fatal("logo.bin must be served as a blob") + } + + before := rpc(t, srv.URL+"/mcp", "skills/get", "skill://plain/SKILL.md") + post := func(query, body string) int { + return mutate(t, srv.URL, query, body, map[string]string{MutateHeader: MutateHeaderValue}) + } + if c := post("skill=plain&file=SKILL.md", "---\nname: plain\ndescription: changed\n---\nnew\n"); c != http.StatusNoContent { + t.Fatalf("mutate status %d", c) + } + after := rpc(t, srv.URL+"/mcp", "skills/get", "skill://plain/SKILL.md") + if string(mustJSON(before)) == string(mustJSON(after)) { + t.Fatal("the listing did not change after mutate") + } + if c := post("skill=nope&file=SKILL.md", "x"); c != http.StatusNotFound { + t.Fatalf("unknown skill: status %d, want 404", c) + } + if c := post("skill=plain", "x"); c != http.StatusBadRequest { + t.Fatalf("missing file: status %d, want 400", c) + } + if c := post("skill=plain&file=SKILL.md", ""); c != http.StatusBadRequest { + t.Fatalf("empty body: status %d, want 400", c) + } +} + +// A web page can POST text/plain to 127.0.0.1 without a preflight; it cannot +// add a custom header, and a browser always names its Origin. Both refused. +func TestMutateRefusesCrossSiteWrites(t *testing.T) { + srv := startFixture(t) + const q, body = "skill=plain&file=SKILL.md", "---\nname: plain\ndescription: x\n---\nx\n" + if c := mutate(t, srv.URL, q, body, nil); c != http.StatusForbidden { + t.Fatalf("mutate without %s: status %d, want 403", MutateHeader, c) + } + if c := mutate(t, srv.URL, q, body, map[string]string{MutateHeader: "nope"}); c != http.StatusForbidden { + t.Fatalf("mutate with a wrong %s: status %d, want 403", MutateHeader, c) + } + if c := mutate(t, srv.URL, q, body, map[string]string{MutateHeader: MutateHeaderValue, "Origin": "https://evil.example"}); c != http.StatusForbidden { + t.Fatalf("mutate with an Origin header: status %d, want 403", c) + } + if c := mutate(t, srv.URL, q, body, map[string]string{MutateHeader: MutateHeaderValue, "Origin": "null"}); c != http.StatusForbidden { + t.Fatalf("mutate with Origin: null: status %d, want 403", c) + } + // The refusals changed nothing. + got := rpc(t, srv.URL+"/mcp", "skills/get", "skill://plain/SKILL.md") + if strings.Contains(string(mustJSON(got)), "description: x") { + t.Fatal("a refused mutate changed the skill") + } +} + +// DNS rebinding: a page on evil.example that resolves to 127.0.0.1 reaches the +// fixture with Host: evil.example:. Every path refuses a foreign Host. +func TestRefusesAForeignHost(t *testing.T) { + srv := startFixture(t) + _, port, _ := net.SplitHostPort(srv.Listener.Addr().String()) + for _, host := range []string{"evil.example:" + port, "evil.example", "localhost:" + port, "127.0.0.1:1"} { + for _, path := range []string{"/mcp", "/_fixture/mutate?skill=plain&file=SKILL.md"} { + req, _ := http.NewRequest(http.MethodPost, srv.URL+path, strings.NewReader(`{"jsonrpc":"2.0","id":1,"method":"skills/list"}`)) + req.Host = host + req.Header.Set(MutateHeader, MutateHeaderValue) + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + assert.NoError(t, resp.Body.Close()) + if resp.StatusCode != http.StatusMisdirectedRequest { + t.Errorf("Host %q %s: status %d, want 421", host, path, resp.StatusCode) + } + } + } + // The listener's own address is accepted. + if list := rpc(t, srv.URL+"/mcp", "skills/list", ""); list["result"] == nil { + t.Fatalf("own Host refused: %v", list) + } +} + +func TestAllowedHosts(t *testing.T) { + addr := &net.TCPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 18931} + if got := allowedHosts("127.0.0.1:0", addr); len(got) != 1 || got[0] != "127.0.0.1:18931" { + t.Fatalf("127.0.0.1: %v", got) + } + if got := allowedHosts("localhost:18931", addr); len(got) != 2 || got[1] != "localhost:18931" { + t.Fatalf("localhost: %v", got) + } +} + +func TestRunRefusesANonLoopbackAddress(t *testing.T) { + if err := run("0.0.0.0:0"); err == nil { + t.Fatal("want an error for a non-loopback address") + } +} + +func mustJSON(v any) []byte { b, _ := json.Marshal(v); return b } diff --git a/docs/development/release-gate.md b/docs/development/release-gate.md index ac4aa68b9..109133c5b 100644 --- a/docs/development/release-gate.md +++ b/docs/development/release-gate.md @@ -34,7 +34,7 @@ fragments against a hardcoded manifest and exits per the verdict. | `suite-scan-eval` | `suite/scan-eval` | 10 min | `go run ./cmd/scan-eval --gate --min-recall 0.90 --max-fp 0.05` over the detect corpus — runs on **every** tag regardless of changed paths (FR-015). | | `matrix-invariants` | `matrix/{stdio,http,sse,docker,oauth}`, `invariant/{activity-request-id,counters,quarantine-flow,upgrade-in-place}` | 20 min | Boots the candidate against five local fixture upstreams (connect → list → call → kill/reconnect) and asserts the US2 invariants against the live instance. | | `surface-consistency` | `invariant/surface-consistency` (T4) | 20 min | Boots the same matrix, adds quarantined/disabled/unhealthy/live servers and asserts the CLI, MCP and rendered Web UI agree with the core on every server's state — see [Surface consistency](#surface-consistency-t4--blocking). | -| `web-ui-sweep` | — (advisory `advisory/web-ui-sweep`, T2) | 20 min | Playwright sweep over the Web UI **served by the candidate binary**, with a live stdio fixture upstream. `continue-on-error: true` — see [Web UI sweep](#web-ui-sweep-t2--advisory). | +| `web-ui-sweep` | — (advisory `advisory/web-ui-sweep`, T2, and `advisory/skills-tab-sweep`, spec 125) | 35 min | Playwright sweep over the Web UI **served by the candidate binary**, with a live stdio fixture upstream. `continue-on-error: true` — see [Web UI sweep](#web-ui-sweep-t2--advisory). | | `verdict` | (merges all) | 10 min | `release-gate report` → `gate-report.json` + `$GITHUB_STEP_SUMMARY`; its exit code **is** the gate verdict. | Every job uploads its fragment with `if: always()`, so a job that dies before @@ -110,8 +110,8 @@ The `web-ui-sweep` job runs the Playwright sweep see [Web UI verification](web-ui-verification.md)) against the Web UI **served by the candidate binary** — embedded frontend, never a dev server — with a live `mcpfixture` stdio upstream so the servers/tools screens have real data. It -runs six spec files (the launcher's `playwright test` line is the list, and -`TestWebUISweepSpecListIsComplete` fails when it, `e2e/web-ui-sweep` and this +runs the spec files below (the launchers' `playwright test` lines are the list, and +`TestWebUISweepSpecListIsComplete` fails when they, `e2e/web-ui-sweep` and this page disagree): - `web-ui-sweep.spec.ts`: servers list, server detail (+ security tab), tools @@ -138,6 +138,34 @@ page disagree): 900 px: the header status pill names servers awaiting review, a secret-like Manual-add value is masked with a Show toggle, and profile Try it is readable and labels unsaved edits. +- `skills-tab.spec.ts` (spec 125): the Skills tab of Server Detail, run by its + own launcher [`scripts/run-skills-tab-sweep.sh`](https://github.com/smart-mcp-proxy/mcpproxy-go/blob/main/scripts/run-skills-tab-sweep.sh) + as a second step of the same job (it needs `enable_skills` and a + skills-capable upstream, `cmd/skillsfixture`, which `build-candidate` builds + into `gate-candidate`). It lists, views and pages skills, approves one, shows + a change made while the skill is open as a stale review, then the diff, and + blocks and unblocks. It writes `skills-sweep-results.json` (checked commit, + fixture command line and port, each scenario's pass/fail, and the skill + records read back after the approve, block and unblock steps) under + `tmp/web-smoke-artifacts/skills-sweep/`, so it is uploaded with the + `web-ui-sweep-playwright-report` artifact. It runs with `--self-test-first`, + which first proves (no browser) that no ambient `MCPPROXY_*` variable + (decoys for `MCPPROXY_DATA_DIR` / `MCPPROXY_DATA`, `MCPPROXY_AUDIT_LOG_PATH`, + `MCPPROXY_TPA_BUNDLE_PATH`, `MCPPROXY_CERTS_DIR`) reaches the throwaway core, + that the results writer redacts the API key and local paths, and that a + `DEBUG=1` run never prints the key. The step runs even when the + standing sweep failed, through `release-gate run-suite --name + advisory/skills-tab-sweep --advisory`, so its outcome is its own + non-blocking manifest entry: a red run is recorded as `advisory-fail` and + listed in the verdict's `advisory_failures` (a run that died before writing + its fragment is a missing advisory entry, listed there too), and + `continue-on-error` keeps the job from blocking the tag. The Playwright + config retries a failed test once in CI, but the skills spec is one stateful + serial group and turns retries off for itself (a retry would replay against + state the first attempt already changed); the results file records the first + failed attempt's error. `TestEveryRunSuiteNameIsInTheManifest` fails when a + `run-suite --name` in the workflow is not a manifest entry, or an advisory + entry has no step. Setup is not duplicated in YAML: the job calls [`scripts/run-web-smoke.sh`](https://github.com/smart-mcp-proxy/mcpproxy-go/blob/main/scripts/run-web-smoke.sh), @@ -168,7 +196,7 @@ It is **advisory**, on purpose while the sweep earns its flake record: > `TestPublishersDoNotShipSweepArtifacts` guards this. **Promotion to blocking** is a two-line change: set `Blocking: true` on the -`advisory/web-ui-sweep` manifest entry and drop `continue-on-error` from the job +`advisory/web-ui-sweep` (and/or `advisory/skills-tab-sweep`) manifest entry and drop `continue-on-error` from the job (the FR-016 end state). Do it once the sweep has passed on three consecutive release tags with no flaky or infrastructure failure — the same criterion T3 uses (FR-021). diff --git a/docs/development/web-ui-verification.md b/docs/development/web-ui-verification.md index 9576a6326..ec7198f79 100644 --- a/docs/development/web-ui-verification.md +++ b/docs/development/web-ui-verification.md @@ -32,6 +32,18 @@ Alongside it, [`e2e/web-ui-sweep/visual-a11y-sweep.spec.ts`](https://github.com/ [`e2e/web-ui-sweep/usertest-web-fixes.spec.ts`](https://github.com/smart-mcp-proxy/mcpproxy-go/blob/main/e2e/web-ui-sweep/usertest-web-fixes.spec.ts) guards three findings of the first-run user test (Spec 109 T202 and T201, Spec 108 T169) at 1440x900 and 900x900: the header status pill says "awaiting review" for the sweep's quarantined server (compact form keeps the text in its title, no sideways scroll), a secret-like Manual-add env value is a password input with a Show toggle (never submitted), and profile Try it shows no `[object Object]`, says it uses unsaved edits, and the tool counts read "Saved profile:" while a Deny toggle is unsaved. The wizard import flow is covered by vitest and live QA, because the smoke core uses the real HOME for client paths. +[`e2e/web-ui-sweep/skills-tab.spec.ts`](https://github.com/smart-mcp-proxy/mcpproxy-go/blob/main/e2e/web-ui-sweep/skills-tab.spec.ts) guards the Skills tab of Server Detail (`specs/125-skills-over-mcp`, PR-4a). It needs `enable_skills` and a skills-capable upstream, so it has its own launcher, [`scripts/run-skills-tab-sweep.sh`](https://github.com/smart-mcp-proxy/mcpproxy-go/blob/main/scripts/run-skills-tab-sweep.sh): + +```bash +./scripts/run-skills-tab-sweep.sh # results in tmp/skills-sweep/ +./scripts/run-skills-tab-sweep.sh --out DIR --report-html specs/125-skills-over-mcp/verification/report.html --no-screenshots +./scripts/run-skills-tab-sweep.sh --self-test # no browser: the clean-environment, redaction and DEBUG=1 checks +``` + +It builds the frontend and the core from the checkout (or takes `MCPPROXY_BINARY_PATH`, which must embed the frontend) and `cmd/skillsfixture` (or `SKILLS_FIXTURE_BINARY`), starts the fixture and a throwaway core on free loopback ports with a scratch data dir (never `~/.mcpproxy`: the core and the fixture start with a clean environment, `env -i` with only `PATH`, a scratch `HOME` and a scratch `TMPDIR`, so no `MCPPROXY_*` of the operator's reaches them (`MCPPROXY_DATA_DIR` would override the config's `data_dir`, `MCPPROXY_AUDIT_LOG_PATH` would audit into the operator's file), with `--data-dir` naming the scratch dir and a data dir under `$HOME/.mcpproxy` refused; `--self-test` proves decoys for the data dir, audit log, TPA bundle and certs paths are not touched, and that a `DEBUG=1` run, which prints progress lines and never uses xtrace, does not print the API key), `enable_skills: true`, a generated API key and the fixture as a `trust_mode: manual` streamable-http upstream, approves the server, runs the spec, and stops only what it started. The scenarios run in order against fresh state: list, viewer and part-by-part paging, approve, an upstream change to an approved skill while it is open (stale review, re-open, file diff, line diff, approve), an upstream change to a pending skill while it is open (stale review with Approve disabled, re-open), a change refreshed through the REST API that marks the open review stale through the live `skills.changed` event alone, block and unblock, and no page error. The scenarios are one serial group with retries off (a retry would replay against state the first attempt changed). The API key reaches the page through `localStorage`, never a URL, and the spec records no traces. It writes `skills-sweep-results.json` (`checked_commit` = `git rev-parse HEAD` and `working_tree_dirty`, with a dirty tree labelled pre-commit evidence; the fixture command as basename and arguments and its port; each scenario's pass/fail with the first failed attempt's error; and `GET /api/v1/servers//skills` read back after the approve, block and unblock steps: status, blocked, available, current_hash, approved_hash), plus screenshots, and exits non-zero on any failure. Every text file it writes, and every message it prints that can carry a path or a log (including the fixture or core log dumped on a startup failure), has the API key replaced by `***` and local paths by ``, ``, `` or `~` (paths inside the checkout are printed relative to it), the configured binary and browser paths and any other path whose first segment exists on the machine by `/` (text whose root does not exist there, such as a regex literal `/approved/i` or a route `/skills/refresh`, is kept); `--self-test` checks the stdout and stderr of a passing run and of a forced fixture and core startup failure for the key and for absolute paths. The release gate runs it with `--self-test-first` in the advisory `web-ui-sweep` job, recorded as the advisory manifest entry `advisory/skills-tab-sweep`. The committed report is `specs/125-skills-over-mcp/verification/report.html`, written from a clean commit with `--no-screenshots` (no embedded screenshots); the copy with screenshots is for artifacts. + +Manual fallback (to step through by hand): `go run ./cmd/skillsfixture -addr 127.0.0.1:` (three skills; `POST /_fixture/mutate?skill=&file=` with the new bytes and the header `X-Skills-Fixture: mutate` changes one; a request with an `Origin` header or a `Host` other than the listen address is refused), a core with `"enable_skills": true` and the fixture as a `trust_mode: manual` streamable-http upstream at `http://127.0.0.1:/mcp`, `POST /api/v1/servers//security/approve` with `{"force":true}`, then the spec with `MCPPROXY_BASE_URL`, `MCPPROXY_API_KEY`, `SWEEP_SERVER_NAME` and `SKILLS_FIXTURE_URL` set. + The release QA gate runs this exact script on every tag as its **advisory** `web-ui-sweep` job — see [Release Gate](release-gate.md#web-ui-sweep-t2--advisory). Extend the committed sweep when you add a screen worth guarding on releases; use the ad-hoc pattern below for the deeper, spec-specific verification that ships beside a spec. ## Ad-hoc, spec-specific verification diff --git a/docs/features/skills.md b/docs/features/skills.md index 64b71c2bb..7cca8fbf8 100644 --- a/docs/features/skills.md +++ b/docs/features/skills.md @@ -141,6 +141,18 @@ Every approval (by you, by the scan, or by `auto` mode), every hold of a changed mcpproxy activity list --type skill_quarantine_change ``` +### In the Web UI {#web-ui} + +The **Skills** tab of a server's page (`/ui/servers/?tab=skills`) does the +same review as the commands above: the list with one state chip per skill, the +file list, a text viewer that pages through large files, a comparison of the +approved copy with the current one (file by file, and line by line for one +changed text file), the scan result with its findings, and the Approve, Block and +Unblock buttons. Approve is bound to the hash and the server incarnation of the +version you opened: a new version that arrives while you review is shown as a +stale review with Approve off until you open it, and a skill that changed on the +server before the page knew is refused with a notice and the list reloads. See [Server Detail page](../web-ui/server-detail.md#skills-tab). + ### Reasons a skill is unusable | Reason | Meaning | diff --git a/docs/web-ui/server-detail.md b/docs/web-ui/server-detail.md index def5a9e57..28454cadc 100644 --- a/docs/web-ui/server-detail.md +++ b/docs/web-ui/server-detail.md @@ -13,10 +13,56 @@ The Server Detail page (URL: `/ui/servers/`) is where you inspect and edit a single upstream server. It opens from the Servers list or via the macOS tray's per-server submenu. -The page has four tabs: **Tools**, **Logs**, **Configuration**, and -**Security**. This page covers the Configuration tab — for the others, +The page has these tabs: **Tools**, **Review**, **Skills** (only when +[skills over MCP](../features/skills.md) is on and the server supports it), +**Logs**, **Configuration**, and **Security**. The active tab is kept in +`?tab=` (for example `?tab=skills`), so a reload or a shared link lands on the +same tab. This page covers the Skills and Configuration tabs — for the others, see the [Dashboard](dashboard.md) and [Activity Log](activity-log.md) pages. +## Skills tab + +The Skills tab is the Web UI for [reviewing skills](../features/skills.md#reviewing-skills) +that an upstream server offers. It appears when `enable_skills` is on and the +server announces the skills extension (or already has skill records). It is +never shown to a non-administrator user of the server edition, which gets no +skills endpoint at all. A `?tab=skills` link to a server where the tab is not +offered opens the Tools tab instead (and the URL says `?tab=tools`). + +- **List.** Every skill of the server with one state chip (Blocked, Unusable, + Changed, Awaiting review or Approved), whether it is offered to agents, its + file count and its scan verdict. **Refresh** reads the server's skills again; + the list also reloads by itself when a `skills.changed` event arrives for + this server. +- **Files and viewer.** The files of the selected skill with size and digest. + A text file opens in a viewer that reads it in 64 KiB parts (**Load more**); + once a skill has an approved copy you can switch the viewer between the + current and the approved copy. A binary file is listed but never shown. Every + part must be the version the list on screen names (same digest, same + offset); if a part of another version comes back, the text is dropped, the + viewer says "This file changed; reload to review the new version", and the + list reloads. +- **Changes.** For a skill with an approved copy, the files are compared by + path and digest (added, removed, changed, same). **Show line diff** compares + one changed text file line by line; a file over 256 KiB on either side is not + compared in the browser. A file whose approved copy is text has **View + approved**, which opens that copy; this covers a removed file and a text file + replaced by a binary file at the same path, which has no line diff. +- **Scan.** The verdict, whether the scan was complete and why not, and each + finding with its file, position, rule, severity and excerpt. +- **Approve, Block, Unblock.** Approve names the content hash and the server + incarnation of the version you opened. If a reload (Refresh, or a + `skills.changed` event) brings a new version of the open skill, or the server + was removed and added again, the page says "This skill changed while you were + reviewing it" and Approve stays off until you choose **Open the new + version**, which starts the review over (viewer and comparison reset). If + the skill changed on the server before the list showed it, nothing is + approved: the list reloads and a notice says so. + +Everything the upstream server wrote (names, descriptions, file names, file +text, finding excerpts) is shown as plain text and is never interpreted as +markup. + ## Configuration tab The Configuration tab is a read-and-edit view of the server's diff --git a/e2e/web-ui-sweep/skills-tab.spec.ts b/e2e/web-ui-sweep/skills-tab.spec.ts new file mode 100644 index 000000000..b993de480 --- /dev/null +++ b/e2e/web-ui-sweep/skills-tab.spec.ts @@ -0,0 +1,296 @@ +// Skills tab of Server Detail (spec 125 PR-4a, specs/125-skills-over-mcp T046). +// +// Drives the Web UI served by a REAL mcpproxy binary (embedded frontend) against +// cmd/skillsfixture registered as a manual-trust upstream with enable_skills on: +// 1. the Skills tab is offered and lists the three fixture skills as +// "Awaiting review"; +// 2. a skill's SKILL.md opens in the viewer, a 150 KiB file pages with Load more, +// and a binary file is listed but not offered for viewing; +// 3. approving a skill turns its chip to Approved; +// 4. changing an APPROVED skill's upstream bytes and pressing Refresh while it +// is open marks the open review stale (it shows the approved version, so it +// offers no Approve) until it is re-opened; then it is Changed, with the +// file-set diff and a line diff against the approved copy, and approving +// binds the new hash; +// 5. changing a PENDING skill's bytes while it is open marks the review stale +// and keeps its Approve button on screen but disabled; +// 6. a change refreshed through the REST API (no click in the page) reaches +// the open review by the live skills.changed event alone: its stale +// banner appears by itself; +// 7. block and unblock; +// 8. no uncaught page error anywhere. +// +// Normally run by scripts/run-skills-tab-sweep.sh, which starts everything and +// sets the environment (docs/development/web-ui-verification.md): +// MCPPROXY_BASE_URL, MCPPROXY_API_KEY the throwaway core +// SWEEP_SERVER_NAME the registered fixture upstream (default skillsfx) +// SKILLS_FIXTURE_URL http://127.0.0.1: of cmd/skillsfixture +// SKILLS_SWEEP_STATE_DIR optional: where GET /skills is saved after +// the approve, block and unblock steps +// SWEEP_SCREENSHOT_DIR optional: where the screenshots are saved +import { test, expect, Page } from '@playwright/test' +import fs from 'node:fs' +import path from 'node:path' + +const BASE = process.env.MCPPROXY_BASE_URL || 'http://127.0.0.1:18080' +const KEY = process.env.MCPPROXY_API_KEY || '' +const SERVER = process.env.SWEEP_SERVER_NAME || 'skillsfx' +const FIXTURE = process.env.SKILLS_FIXTURE_URL || '' + +test.skip(!FIXTURE, 'SKILLS_FIXTURE_URL is not set: start cmd/skillsfixture and register it as an upstream') +// One stateful serial group: each scenario builds on the records the previous +// one wrote (approved, changed, blocked). A retry would replay a scenario +// against state its first attempt already changed and always fail, hiding the +// original error, so this group never retries (the config retries once in CI). +test.describe.configure({ mode: 'serial', retries: 0 }) + +const pageErrors: string[] = [] + +// The key never goes into a page URL: a goto failure message (and so the +// results file and the HTML report) would carry it. The Web UI reads it from +// localStorage instead (frontend/src/services/api.ts initializeAPIKey), which an +// init script sets on the core's origin before any page script runs. +function url(route: string): string { + return `${BASE}/ui${route}` +} + +// The Web UI's own SSE request carries the key as ?apikey=, so a trace's +// network log would hold it: this spec records no traces (failure screenshots +// show the page only, never the address bar). +test.use({ trace: 'off' }) + +async function shot(page: Page, name: string, focus?: string) { + // The detail pane sits below the list; scroll the part worth seeing into view. + if (focus) await page.locator(focus).first().scrollIntoViewIfNeeded() + const body = await page.screenshot({ fullPage: false }) + await test.info().attach(`skills-tab-${name}`, { body, contentType: 'image/png' }) + const dir = process.env.SWEEP_SCREENSHOT_DIR + if (dir) { + fs.mkdirSync(dir, { recursive: true }) + fs.writeFileSync(path.join(dir, `skills-tab-${name}.png`), body) + } +} + +// Read back the core's own record of every skill after a step, for the +// launcher's results file. +async function saveState(step: string) { + const dir = process.env.SKILLS_SWEEP_STATE_DIR + if (!dir) return + const res = await fetch(`${BASE}/api/v1/servers/${SERVER}/skills`, { headers: { 'X-API-Key': KEY } }) + expect(res.status, `GET /skills after ${step}`).toBe(200) + const body = await res.json() + fs.mkdirSync(dir, { recursive: true }) + fs.writeFileSync(path.join(dir, `state-after-${step}.json`), JSON.stringify(body.data ?? body, null, 2)) +} + +/** The fixture's mutate endpoint wants this header (and refuses an Origin). */ +const MUTATE_HEADERS = { 'X-Skills-Fixture': 'mutate', 'Content-Type': 'text/plain' } + +const row = (page: Page, skill: string) => page.locator(`[data-test="skill-row-${skill}"]`) +const chip = (page: Page, skill: string) => page.locator(`[data-test="skill-chip-${skill}"]`) + +test.beforeEach(async ({ page }) => { + page.on('pageerror', err => pageErrors.push(err.message)) + if (KEY) { + await page.addInitScript(({ key, origin }) => { + if (window.location.origin === origin) window.localStorage.setItem('mcpproxy-api-key', key) + }, { key: KEY, origin: new URL(BASE).origin }) + } +}) + +test('the Skills tab lists the fixture skills as awaiting review', async ({ page }) => { + // The core reads skills on refresh; make sure the three records exist. + const refreshed = await fetch(`${BASE}/api/v1/servers/${SERVER}/skills/refresh`, { method: 'POST', headers: { 'X-API-Key': KEY } }) + expect(refreshed.status, 'POST /skills/refresh').toBe(200) + await page.goto(url(`/servers/${SERVER}?tab=skills`)) + await page.waitForLoadState('domcontentloaded') + const closeWizard = page.locator('[data-test="close-wizard"]') + if (await closeWizard.isVisible().catch(() => false)) await closeWizard.click() + await expect(page.locator('[data-test="skills-tab"]')).toBeVisible() + await expect(page.locator('[data-test="skills-tab"]')).toHaveClass(/tab-active/) + for (const s of ['plain', 'with-files', 'big']) { + await expect(chip(page, s)).toHaveText('Awaiting review') + } + await shot(page, '01-list') +}) + +test('views SKILL.md, pages a large file, and does not offer a binary file', async ({ page }) => { + await page.goto(url(`/servers/${SERVER}?tab=skills`)) + await row(page, 'plain').click() + await page.locator('[data-test="skill-view-SKILL.md"]').click() + await expect(page.locator('[data-test="skill-viewer-text"]')).toContainText('name: plain') + await shot(page, '02-viewer', '[data-test="skill-viewer"]') + + await row(page, 'big').click() + // The listed digest and size of data/large.txt in the copy being viewed (the + // current copy: View opens it), from the core's own listing; the file row on + // screen must name the same digest (its title holds the full value). + const FILE = 'data/large.txt' + const listingRes = await fetch(`${BASE}/api/v1/servers/${SERVER}/skills`, { headers: { 'X-API-Key': KEY } }) + expect(listingRes.status, 'GET /skills').toBe(200) + const listingBody = await listingRes.json() + const bigSkill = (listingBody.data ?? listingBody).skills.find((k: { path: string }) => k.path === 'big') + const listedFile = (bigSkill?.files ?? []).find((f: { path: string }) => f.path === FILE) + expect(listedFile?.digest, `the listing names ${FILE} in the current copy of big`).toBeTruthy() + await expect(page.locator(`[data-test="skill-file-${FILE}"] span.font-mono`)).toHaveAttribute('title', listedFile.digest) + // Every part is awaited as a response, and its text as a rendered update: the + // Load more button is hidden while a part loads, so its absence alone is not + // the end of the file. The end is a part with no next_offset. Each part must + // be of the current copy, carry the listed digest, start where the previous + // part ended (offsets in bytes, the first at 0), and the last one must end at + // the listed size. + const isPart = (offset: number) => (r: { url(): string }) => { + const u = new URL(r.url()) + return u.pathname.endsWith('/skills/content') && u.searchParams.get('file') === FILE && + Number(u.searchParams.get('offset') ?? 0) === offset + } + const text = page.locator('[data-test="skill-viewer-text"]') + const loadMore = page.locator('[data-test="skill-load-more"]') + let [res] = await Promise.all([page.waitForResponse(isPart(0)), page.locator(`[data-test="skill-view-${FILE}"]`).click()]) + let shown = 0 + let loads = 0 + let expectedOffset = 0 + for (;;) { + expect(res.status()).toBe(200) + expect(new URL(res.url()).searchParams.get('copy') ?? 'current', `part ${loads}: copy`).toBe('current') + const body = await res.json() + const part = body.data ?? body + expect(part.digest, `part ${loads}: digest`).toBe(listedFile.digest) + expect(part.offset, `part ${loads}: offset`).toBe(expectedOffset) + expect(part.size, `part ${loads}: size`).toBe(listedFile.size) + expectedOffset = part.offset + Buffer.byteLength(part.text, 'utf8') + shown += part.text.length + await expect.poll(() => text.evaluate(e => (e.textContent ?? '').length)).toBe(shown) + if (part.next_offset === undefined || part.next_offset === null) break + expect(part.next_offset, `part ${loads}: next_offset is where this part ends`).toBe(expectedOffset) + expect(loads, 'the file ends within ten parts').toBeLessThan(10) + if (loads === 0) { + await expect(text).toContainText('line 000001') + await expect(text).not.toContainText('line 003000') + } + await expect(loadMore).toBeVisible() + ;[res] = await Promise.all([page.waitForResponse(isPart(part.next_offset)), loadMore.click()]) + loads++ + } + expect(expectedOffset, 'the last part ends at the listed size').toBe(listedFile.size) + await expect(loadMore).toHaveCount(0) + expect(loads, '150 KiB needs more than one 64 KiB part').toBeGreaterThanOrEqual(2) + await expect(text).toContainText('line 003840') + await shot(page, '03-paged', '[data-test="skill-viewer"]') + + await row(page, 'with-files').click() + await expect(page.locator('[data-test="skill-file-logo.bin"]')).toContainText(/binary/i) + await expect(page.locator('[data-test="skill-view-logo.bin"]')).toHaveCount(0) + await expect(page.locator('[data-test="skill-view-notes.txt"]')).toBeVisible() +}) + +test('approve turns the chip to Approved', async ({ page }) => { + await page.goto(url(`/servers/${SERVER}?tab=skills`)) + await row(page, 'plain').click() + await page.locator('[data-test="skill-approve"]').click() + await expect(chip(page, 'plain')).toHaveText('Approved') + await expect(page.locator('[data-test="skills-notice"]')).toContainText(/approved/i) + await expect(page.locator('[data-test="skill-approve"]')).toHaveCount(0) + await saveState('approve') + await shot(page, '04-approved') +}) + +test('an upstream change plus Refresh shows Changed with a file diff and a line diff', async ({ page }) => { + const changed = '---\nname: plain\ndescription: test skill plain\n---\n# plain\nA new instruction line.\n' + const refused = await fetch(`${FIXTURE}/_fixture/mutate?skill=plain&file=SKILL.md`, { method: 'POST', body: changed }) + expect(refused.status, 'mutate without the fixture header is refused').toBe(403) + await page.goto(url(`/servers/${SERVER}?tab=skills`)) + await row(page, 'plain').click() + await expect(page.locator('[data-test="skill-stale"]')).toHaveCount(0) + const res = await fetch(`${FIXTURE}/_fixture/mutate?skill=plain&file=SKILL.md`, { method: 'POST', body: changed, headers: MUTATE_HEADERS }) + expect(res.status).toBe(204) + await page.locator('[data-test="skills-refresh"]').click() + await expect(chip(page, 'plain')).toHaveText('Changed') + // The open review was of the approved version: it is stale until re-opened. + await expect(page.locator('[data-test="skill-stale"]')).toContainText('This skill changed while you were reviewing it') + // The review on screen is still the approved version, so it offers no Approve; + // the new version's Approve appears only after the re-open below. + await expect(page.locator('[data-test="skill-approve"]')).toHaveCount(0) + await shot(page, '05a-stale', '[data-test="skill-stale"]') + await page.locator('[data-test="skill-reopen"]').click() + await expect(page.locator('[data-test="skill-stale"]')).toHaveCount(0) + await expect(page.locator('[data-test="skill-diff-SKILL.md"]')).toHaveAttribute('data-state', 'changed') + await page.locator('[data-test="skill-line-diff-SKILL.md"]').click() + const added = page.locator('[data-test="skill-diff-line"][data-op="add"]') + await expect(added).toHaveCount(1) + await expect(added).toContainText('A new instruction line.') + await shot(page, '05-changed-diff', '[data-test="skill-line-diff"]') + await page.locator('[data-test="skill-approve"]').click() + await expect(chip(page, 'plain')).toHaveText('Approved') + await saveState('approve-changed') +}) + +test('a pending skill changed while open is stale, with Approve disabled until re-opened', async ({ page }) => { + await page.goto(url(`/servers/${SERVER}?tab=skills`)) + await row(page, 'with-files').click() + const approve = page.locator('[data-test="skill-approve"]') + // Pending and not stale: Approve is offered and enabled. + await expect(approve).toBeEnabled() + await expect(page.locator('[data-test="skill-stale"]')).toHaveCount(0) + const res = await fetch(`${FIXTURE}/_fixture/mutate?skill=with-files&file=notes.txt`, { + method: 'POST', body: 'Supporting notes\nsecond line\na third line added upstream\n', headers: MUTATE_HEADERS, + }) + expect(res.status).toBe(204) + await page.locator('[data-test="skills-refresh"]').click() + await expect(page.locator('[data-test="skill-stale"]')).toContainText('This skill changed while you were reviewing it') + // Still pending (never approved), so the chip does not move... + await expect(chip(page, 'with-files')).toHaveText('Awaiting review') + // ...and SkillsPanel keeps the reviewed version on screen: its Approve stays, + // disabled, so the changed bytes cannot be approved unseen. + await expect(approve).toHaveCount(1) + await expect(approve).toBeDisabled() + await shot(page, '05b-pending-stale', '[data-test="skill-stale"]') + await page.locator('[data-test="skill-reopen"]').click() + await expect(page.locator('[data-test="skill-stale"]')).toHaveCount(0) + await expect(approve).toBeEnabled() +}) + +// Round-3 finding 1: the live skills.changed event (the core's SSE frame, +// re-dispatched by the system store) reloads the open review. Nothing in the +// page is clicked after the skill is opened: the change and the refresh happen +// upstream and through the REST API, and the banner has to appear by itself. +test('a refresh through the REST API marks the open review stale by the live event alone', async ({ page }) => { + await page.goto(url(`/servers/${SERVER}?tab=skills`)) + await row(page, 'big').click() + await expect(page.locator('[data-test="skill-approve"]')).toBeEnabled() + await expect(page.locator('[data-test="skill-stale"]')).toHaveCount(0) + const listed = page.waitForResponse(r => new URL(r.url()).pathname === `/api/v1/servers/${SERVER}/skills` && r.request().method() === 'GET') + const mutated = await fetch(`${FIXTURE}/_fixture/mutate?skill=big&file=SKILL.md`, { + method: 'POST', body: '---\nname: big\ndescription: test skill big\n---\n# big\nChanged upstream, refreshed over REST.\n', headers: MUTATE_HEADERS, + }) + expect(mutated.status).toBe(204) + const refreshed = await fetch(`${BASE}/api/v1/servers/${SERVER}/skills/refresh`, { method: 'POST', headers: { 'X-API-Key': KEY } }) + expect(refreshed.status, 'POST /skills/refresh').toBe(200) + // The page reloads the listing on its own (the skills.changed event)... + expect((await listed).status()).toBe(200) + // ...and the open review says it changed, with Approve off. + await expect(page.locator('[data-test="skill-stale"]')).toContainText('This skill changed while you were reviewing it') + await expect(page.locator('[data-test="skill-approve"]')).toBeDisabled() + await shot(page, '05c-live-event-stale', '[data-test="skill-stale"]') +}) + +test('block and unblock', async ({ page }) => { + await page.goto(url(`/servers/${SERVER}?tab=skills`)) + await row(page, 'with-files').click() + await page.locator('[data-test="skill-block"]').click() + await expect(chip(page, 'with-files')).toHaveText('Blocked') + await expect(page.locator('[data-test="skill-approve"]')).toHaveCount(0) + await saveState('block') + await shot(page, '06-blocked') + await page.locator('[data-test="skill-unblock"]').click() + await expect(chip(page, 'with-files')).toHaveText('Awaiting review') + await saveState('unblock') +}) + +test('the tab survives a reload through ?tab=skills and no page error was thrown', async ({ page }) => { + await page.goto(url(`/servers/${SERVER}?tab=skills`)) + await expect(page.locator('[data-test="skills-panel"]')).toBeVisible() + await page.reload() + await expect(page.locator('[data-test="skills-tab"]')).toHaveClass(/tab-active/) + expect(pageErrors, 'uncaught page errors').toEqual([]) +}) diff --git a/frontend/src/components/skills/SkillDetail.vue b/frontend/src/components/skills/SkillDetail.vue new file mode 100644 index 000000000..614a02ff2 --- /dev/null +++ b/frontend/src/components/skills/SkillDetail.vue @@ -0,0 +1,223 @@ + + + diff --git a/frontend/src/components/skills/SkillsPanel.vue b/frontend/src/components/skills/SkillsPanel.vue new file mode 100644 index 000000000..da86d1798 --- /dev/null +++ b/frontend/src/components/skills/SkillsPanel.vue @@ -0,0 +1,325 @@ + + + diff --git a/frontend/src/services/api.ts b/frontend/src/services/api.ts index 0d7c4e929..3fb553725 100644 --- a/frontend/src/services/api.ts +++ b/frontend/src/services/api.ts @@ -1,5 +1,5 @@ import type { APIResponse, Server, Tool, ToolApproval, SearchResult, StatusUpdate, StatusResponse, SecretRef, MigrationAnalysis, ConfigSecretsResponse, GetToolCallsResponse, GetToolCallDetailResponse, GetServerToolCallsResponse, GetConfigResponse, ValidateConfigResponse, ConfigApplyResult, ServerTokenMetrics, GetRegistriesResponse, SearchRegistryServersResponse, RegistrySummary, CatalogSearchResponse, GetSessionsResponse, GetSessionDetailResponse, InfoResponse, ActivityListResponse, ActivityDetailResponse, ActivityRecord, ActivitySummaryResponse, ImportResponse, AgentTokenInfo, CreateAgentTokenRequest, CreateAgentTokenResponse, RoutingInfo, ConnectStatusResponse, ClientStatus, ConnectResult, ConnectPreview, OnboardingStateResponse, OnboardingMarkRequest, DiagnosticFixResponse, GlobalToolsResponse, UsageAggregateResponse, UsageWindow, UsageSort, UsageStatus, AttentionResponse, ReviewQueueResponse, ServerReviewResponse } from '@/types' -import type { ProfileConfig, ProfileList, ProfileView, ProfileWriteResult, ProfileRenameResult, ProfileDeleteResult, EffectiveToolsResult, TryProfileResponse, AccessExplanation, ExplainSubjectQuery, ClientView, ClientsResponse, BulkAssignResponse, CustomClientResponse, RotateResponse, UpgradePreview, UpgradeApplyResult, ForgetClientResponse, ConnectOptions } from '@/types/api' +import type { ProfileConfig, ProfileList, ProfileView, ProfileWriteResult, ProfileRenameResult, ProfileDeleteResult, EffectiveToolsResult, TryProfileResponse, AccessExplanation, ExplainSubjectQuery, ClientView, ClientsResponse, BulkAssignResponse, CustomClientResponse, RotateResponse, UpgradePreview, UpgradeApplyResult, ForgetClientResponse, ConnectOptions, SkillsListResponse, SkillContentResponse, SkillCopy, SkillsResponse } from '@/types/api' import { joinHoldEvidence, type HoldEvidenceSource } from '@/utils/holdEvidence' @@ -221,13 +221,14 @@ class APIService { } } - private async request(endpoint: string, options: RequestInit = {}): Promise> { + private async request(endpoint: string, options: RequestInit = {}): Promise & { errorCode?: string }> { // Ensure API key initialization is complete if (!this.initialized) { console.log('API service not initialized, initializing now...') this.initializeAPIKey() } + let errorCode: string | undefined try { const headers: Record = { 'Content-Type': 'application/json', @@ -273,6 +274,7 @@ class APIService { // Try to extract error message from response body const errorData = await response.json().catch(() => ({})) const errorMsg = errorData.error || `HTTP ${response.status}: ${response.statusText}` + errorCode = typeof errorData.error_code === 'string' ? errorData.error_code : undefined console.error(`API request failed: ${errorMsg}`) // Special handling for authentication errors @@ -298,6 +300,8 @@ class APIService { return { success: false, error: error instanceof Error ? error.message : 'Unknown error', + // Spec 125: the stable error_code of the body, when it had one. + ...(errorCode ? { errorCode } : {}), } } } @@ -610,6 +614,52 @@ class APIService { }) } + // Spec 125 (skills over MCP, PR-4a): administrator-only skills routes. Failures + // carry `errorCode` (review_out_of_date, server_replaced, refresh_superseded, + // skill_unusable, ...). approve is bound to the reviewed hashes (expectedHashes: + // skill path -> current_hash) and to the server incarnation; the core answers + // 409 and writes nothing when either moved. + async getServerSkills(serverName: string): Promise> { + return this.request(`/api/v1/servers/${encodeURIComponent(serverName)}/skills`) + } + + async refreshServerSkills(serverName: string): Promise> { + return this.request(`/api/v1/servers/${encodeURIComponent(serverName)}/skills/refresh`, { method: 'POST' }) + } + + async getSkillContent( + serverName: string, + q: { skill: string; file?: string; copy?: SkillCopy; offset?: number; limit?: number }, + ): Promise> { + const params = new URLSearchParams({ skill: q.skill }) + if (q.file) params.set('file', q.file) + if (q.copy) params.set('copy', q.copy) + if (q.offset) params.set('offset', String(q.offset)) + if (q.limit) params.set('limit', String(q.limit)) + return this.request(`/api/v1/servers/${encodeURIComponent(serverName)}/skills/content?${params.toString()}`) + } + + async approveSkills(serverName: string, skills: string[], expectedHashes: Record, expectedIncarnation?: number): Promise> { + return this.request<{ approved: number }>(`/api/v1/servers/${encodeURIComponent(serverName)}/skills/approve`, { + method: 'POST', + body: JSON.stringify(withExpectedIncarnation({ skills, expected_hashes: expectedHashes }, expectedIncarnation)), + }) + } + + async blockSkills(serverName: string, skills: string[], expectedIncarnation?: number): Promise> { + return this.request<{ changed: number }>(`/api/v1/servers/${encodeURIComponent(serverName)}/skills/block`, { + method: 'POST', + body: JSON.stringify(withExpectedIncarnation({ skills }, expectedIncarnation)), + }) + } + + async unblockSkills(serverName: string, skills: string[], expectedIncarnation?: number): Promise> { + return this.request<{ changed: number }>(`/api/v1/servers/${encodeURIComponent(serverName)}/skills/unblock`, { + method: 'POST', + body: JSON.stringify(withExpectedIncarnation({ skills }, expectedIncarnation)), + }) + } + async setToolEnabled(serverName: string, toolName: string, enabled: boolean, expectedIncarnation?: number): Promise { } }) + // Spec 125: an administrator-only invalidation of a server's skills + // ({server, counts}); the Skills tab reloads when the server is its own. + es.addEventListener('skills.changed', (event) => { + try { + window.dispatchEvent(new CustomEvent('mcpproxy:skills-changed', { detail: JSON.parse(event.data) })) + } catch (error) { + console.error('Failed to parse SSE skills.changed event:', error) + } + }) + // Spec 108-f FR-038: both are invalidations. The payload is not used; the // profiles store and the clients store refetch. Scoped subscribers never // receive either event, so nothing relies on them for correctness. diff --git a/frontend/src/types/api.ts b/frontend/src/types/api.ts index ad5d486a8..0c4c666e5 100644 --- a/frontend/src/types/api.ts +++ b/frontend/src/types/api.ts @@ -19,6 +19,7 @@ export { // Import HealthStatus/Tier for use in this file import type { + APIResponse, CredentialState, HealthStatus, Tier, ProfileSource, ProfileBlockReason, ProfileView, ProfileList, ProfileWriteResult, ProfileUsedBy, ProfileToolCounts, ProfileToolRules, EffectiveTool, EffectiveToolsResult, AccessExplanation, ClientWarning, ClientView, @@ -1615,3 +1616,78 @@ export interface ExplainSubjectQuery { profile?: string anonymous?: boolean } + +// Spec 125 (skills over MCP, PR-4a): hand-written mirrors of +// internal/contracts/skills.go. The routes are administrator-only. Every text +// field below was written by an upstream server and is shown as inert text. +export interface SkillFileInfo { + path: string + size: number + digest: string + text: boolean +} + +export interface SkillScanFinding { + file: string + offset: number + rule: string + severity: string + evidence: string +} + +export interface SkillScanInfo { + verdict: string + complete: boolean + incomplete: string + scanned_at?: string + findings_truncated: boolean + findings: SkillScanFinding[] +} + +export type SkillStatus = 'pending' | 'approved' | 'changed' | 'unusable' + +export interface SkillEntry { + id: string + uri: string + path: string + name: string + description: string + status: SkillStatus | string + blocked: boolean + listed: boolean + available: boolean + unusable_reason: string + current_hash: string + approved_hash: string + approved_at?: string + approved_by: string + approved_files?: SkillFileInfo[] + files: SkillFileInfo[] + total_size: number + scan: SkillScanInfo +} + +export interface SkillsListResponse { + enabled: boolean + incarnation: number + server?: string + supported: boolean + expose_skills: boolean | null + last_refresh: string | null + error: string + truncated: boolean + skills: SkillEntry[] +} + +export interface SkillContentResponse { + text: string + offset: number + next_offset?: number + size: number + digest: string +} + +export type SkillCopy = 'current' | 'approved' + +/** A response of the skills routes: a failure also carries the body's stable error_code. */ +export type SkillsResponse = APIResponse & { errorCode?: string } diff --git a/frontend/src/utils/skills.ts b/frontend/src/utils/skills.ts new file mode 100644 index 000000000..56413be9b --- /dev/null +++ b/frontend/src/utils/skills.ts @@ -0,0 +1,241 @@ +// Spec 125 (skills over MCP, PR-4a): pure helpers for the Skills tab. +import type { SkillEntry, SkillFileInfo, SkillContentResponse, SkillsListResponse } from '@/types/api' + +export function skillsChangeIncludesServer(event: Event, serverName: string): boolean { + const payload = (event as CustomEvent).detail?.payload + return payload?.server === serverName || (Array.isArray(payload?.servers) && payload.servers.includes(serverName)) +} + +export type SkillTone = 'error' | 'warning' | 'info' | 'success' | 'neutral' + +/** The one state chip of a skill: blocked > unusable > changed > pending > approved. */ +export function skillStateChip(entry: Pick): { label: string; tone: SkillTone } { + if (entry.blocked) return { label: 'Blocked', tone: 'error' } + switch (entry.status) { + case 'unusable': return { label: 'Unusable', tone: 'neutral' } + case 'changed': return { label: 'Changed', tone: 'warning' } + case 'pending': return { label: 'Awaiting review', tone: 'info' } + case 'approved': return { label: 'Approved', tone: 'success' } + default: return { label: entry.status, tone: 'neutral' } + } +} + +export type FileDiffState = 'added' | 'removed' | 'changed' | 'same' +export interface FileDiffRow { + path: string + state: FileDiffState + before?: SkillFileInfo + after?: SkillFileInfo +} + +/** File-set diff of the approved copy against the current one, by path and digest. */ +export function skillFileDiff(approved: SkillFileInfo[] | undefined, current: SkillFileInfo[]): FileDiffRow[] { + const before = new Map((approved ?? []).map(f => [f.path, f])) + const after = new Map(current.map(f => [f.path, f])) + const rows: FileDiffRow[] = [] + for (const [path, a] of after) { + const b = before.get(path) + if (!b) rows.push({ path, state: 'added', after: a }) + else rows.push({ path, state: b.digest === a.digest ? 'same' : 'changed', before: b, after: a }) + } + for (const [path, b] of before) if (!after.has(path)) rows.push({ path, state: 'removed', before: b }) + return rows.sort((x, y) => (x.path < y.path ? -1 : x.path > y.path ? 1 : 0)) +} + +/** `skip` stands for a run of unchanged lines that is not shown; its text says how many. */ +export interface LineOp { op: 'same' | 'add' | 'del' | 'skip'; text: string } +export interface LineDiffResult { tooLarge: boolean; ops: LineOp[] } + +/** Largest middle section (lines a x lines b) the LCS table may have. */ +export const LINE_DIFF_MAX_CELLS = 4_000_000 +/** Unchanged lines kept on each side of a change; longer unchanged runs collapse to one `skip`. */ +export const LINE_DIFF_CONTEXT = 3 +/** Most ops a diff may render (after collapsing); past it the result is tooLarge. */ +export const LINE_DIFF_MAX_OPS = 5_000 + +/** + * Line diff of two texts. Common head and tail lines are peeled off first; the + * rest uses an LCS table that is never built past maxCells. The output is + * bounded too: every unchanged run that is more than LINE_DIFF_CONTEXT lines longer than + * the context it keeps (LINE_DIFF_CONTEXT on each side of a change) collapses to a "N unchanged lines" skip, and + * a diff that still has more than maxOps ops is tooLarge with no ops. The + * peeled head and tail are never expanded into one op per line. + */ +export function lineDiff(a: string, b: string, maxCells = LINE_DIFF_MAX_CELLS, maxOps = LINE_DIFF_MAX_OPS): LineDiffResult { + const x = a.split('\n'), y = b.split('\n') + let head = 0 + while (head < x.length && head < y.length && x[head] === y[head]) head++ + let tail = 0 + while (tail < x.length - head && tail < y.length - head && x[x.length - 1 - tail] === y[y.length - 1 - tail]) tail++ + const mx = x.slice(head, x.length - tail), my = y.slice(head, y.length - tail) + if ((mx.length + 1) * (my.length + 1) > maxCells) return { tooLarge: true, ops: [] } + // Every changed line is one op whatever the collapsing does. + if (mx.length + my.length > maxOps) return { tooLarge: true, ops: [] } + + const w = my.length + 1 + const t = new Uint32Array((mx.length + 1) * w) + for (let i = mx.length - 1; i >= 0; i--) { + for (let j = my.length - 1; j >= 0; j--) { + t[i * w + j] = mx[i] === my[j] ? t[(i + 1) * w + j + 1] + 1 : Math.max(t[(i + 1) * w + j], t[i * w + j + 1]) + } + } + const ops: LineOp[] = [] + // An unchanged run [from, to) of x: shown whole when short, else its edges + // next to a change and one skip for the rest. + const unchanged = (from: number, to: number, atStart: boolean, atEnd: boolean) => { + const n = to - from + const keepBefore = atStart ? 0 : LINE_DIFF_CONTEXT + const keepAfter = atEnd ? 0 : LINE_DIFF_CONTEXT + // A skip stands for more than LINE_DIFF_CONTEXT lines; a shorter run is shown whole. + if (n <= keepBefore + keepAfter + LINE_DIFF_CONTEXT) { for (let k = from; k < to; k++) ops.push({ op: 'same', text: x[k] }); return } + for (let k = from; k < from + keepBefore; k++) ops.push({ op: 'same', text: x[k] }) + ops.push({ op: 'skip', text: `${n - keepBefore - keepAfter} unchanged lines` }) + for (let k = to - keepAfter; k < to; k++) ops.push({ op: 'same', text: x[k] }) + } + const changed = mx.length > 0 || my.length > 0 + // The middle, with its unchanged runs as x indexes for collapsing. + let i = 0, j = 0 + let runStart = -1 + const flush = (end: number) => { if (runStart >= 0) { unchanged(runStart, end, false, false); runStart = -1 } } + unchanged(0, head, true, !changed) + while (i < mx.length && j < my.length) { + if (mx[i] === my[j]) { if (runStart < 0) runStart = head + i; i++; j++ } + else if (t[(i + 1) * w + j] >= t[i * w + j + 1]) { flush(head + i); ops.push({ op: 'del', text: mx[i++] }) } + else { flush(head + i); ops.push({ op: 'add', text: my[j++] }) } + } + flush(head + i) + while (i < mx.length) ops.push({ op: 'del', text: mx[i++] }) + while (j < my.length) ops.push({ op: 'add', text: my[j++] }) + if (changed) unchanged(x.length - tail, x.length, false, true) + if (ops.length > maxOps) return { tooLarge: true, ops: [] } + return { tooLarge: false, ops } +} + +/** + * The expected_hashes body of an approval: path -> the current_hash the reviewer + * saw. A null-prototype object keeps a path called "__proto__" an own key. + */ +export function skillExpectedHashes(entries: Array>): Record { + const out = Object.create(null) as Record + for (const e of entries) out[e.path] = e.current_hash + return out +} + +type PartResult = { success: boolean; data?: SkillContentResponse; error?: string; errorCode?: string } +export type WholeFileResult = + | { success: true; text: string; capped: boolean } + | { success: false; error: string; errorCode?: string } + +/** + * The client-side code of a part that does not belong to the version on screen: + * its digest is not the one the listing names for that file and copy, or it + * answers another offset. The text read so far is dropped, never joined. + */ +export const SKILL_CONTENT_CHANGED = 'content_changed' +export const SKILL_CONTENT_CHANGED_MESSAGE = 'This file changed; reload to review the new version.' + +/** True when a part is the expected version (digest) at the expected offset. */ +export function skillPartMatches(part: Pick, expectedDigest: string, expectedOffset: number): boolean { + return !!expectedDigest && part.digest === expectedDigest && part.offset === expectedOffset +} + +/** + * Reads every part of a file by next_offset, stopping after maxParts. Every + * part must carry expectedDigest (the digest the listing on screen names for + * this file and copy) and answer the offset asked for; otherwise the result is + * a SKILL_CONTENT_CHANGED failure with no text, so parts of two versions are + * never joined. + */ +export async function readWholeSkillFile(fetchPart: (offset: number) => Promise, expectedDigest: string, maxParts = 200): Promise { + let text = '' + let offset = 0 + for (let n = 0; n < maxParts; n++) { + const res = await fetchPart(offset) + if (!res.success || !res.data) return { success: false, error: res.error || 'Could not read the file', errorCode: res.errorCode } + if (!skillPartMatches(res.data, expectedDigest, offset)) { + return { success: false, error: SKILL_CONTENT_CHANGED_MESSAGE, errorCode: SKILL_CONTENT_CHANGED } + } + text += res.data.text + const next = res.data.next_offset + if (next === undefined || next === null) return { success: true, text, capped: false } + if (next <= offset) return { success: false, error: 'The server returned a part that does not advance' } + offset = next + } + return { success: true, text, capped: true } +} + +/** The digest the listing names for one file of one copy, or undefined. */ +export function skillFileDigest(entry: Pick, file: string, copy: 'current' | 'approved'): string | undefined { + const list = copy === 'approved' ? entry.approved_files : entry.files + return list?.find(f => f.path === file)?.digest +} + +/** + * The tab is offered when the feature is on and the server supports skills or + * has records. Only the administrator listing carries `supported`: a listing + * without it (the scoped/agent-token shape, SkillsAgentListResponse, which has + * no scan block either) is not offered. + */ +export function skillsTabVisible(listing: SkillsListResponse | undefined | null): boolean { + if (!listing || typeof listing.supported !== 'boolean') return false + return listing.enabled === true && (listing.supported || (listing.skills?.length ?? 0) > 0) +} + +/** + * The error code of a failed skills request. The listing and refresh routes send + * error_code; approve/block/unblock answer 409 server_replaced through the shared + * approval error writer, whose body has only `error` ("server_replaced: ..."), + * like the tool approval routes. The code is then the message's prefix (the + * only codes that writer puts first are read; any other message has no code). + */ +const MESSAGE_CODE = /^(server_replaced|review_out_of_date)\b(?=:|$)/ +export function skillErrorCode(code: string | undefined, message: string | undefined): string | undefined { + if (code) return code + return message ? MESSAGE_CODE.exec(message)?.[1] : undefined +} + +/** The request a notice answers: the refresh, or one of the writes. */ +export type SkillAction = 'refresh' | 'approve' | 'block' | 'unblock' +const NOTHING_DONE: Record = { + refresh: 'nothing was refreshed', approve: 'nothing was approved', block: 'nothing was blocked', unblock: 'nothing was unblocked', +} + +/** Operator-facing words for a failed skills request, worded for the action it refused. */ +export function skillErrorNotice(code: string | undefined, message: string | undefined, action: SkillAction = 'refresh'): string { + switch (skillErrorCode(code, message)) { + case 'review_out_of_date': + return 'This skill changed since you opened it, so nothing was approved. The list was reloaded; review it again.' + case 'server_replaced': + return `This server was removed and added again since you opened it, so ${NOTHING_DONE[action]}. The list was reloaded.` + // The refresh codes of POST /skills/refresh (a concurrent refresh is joined, never refused). + case 'refresh_superseded': + return 'The server reconnected during the refresh, so its skills are read again after the reconnect. The list was reloaded.' + case 'skills_not_supported': + return 'This server does not announce the skills extension, so there is nothing to refresh. The list was reloaded.' + case 'skills_disabled': + return `Skills over MCP was turned off (enable_skills), so ${NOTHING_DONE[action]}. The list was reloaded.` + default: + return message || 'The request failed' + } +} + +/** + * The notice after a successful approve, worded from the listing reloaded + * after it (round-4 finding 3): an approved skill is not necessarily offered to + * agents. `available` decides; the reason is the first one the listing shows. + * A skill the listing does not explain (the server is disabled or quarantined, + * which the listing does not carry) is "not offered yet" without a reason, and + * no listing (the reload failed) or no such skill gives a neutral "Approved.". + */ +export function skillApprovedNotice(listing: SkillsListResponse | null | undefined, path: string): string { + const s = listing?.skills?.find(k => k.path === path) + if (!listing || !s) return 'Approved.' + if (s.available) return 'Approved. Agents can use this skill now.' + let reason = '' + if (!listing.enabled) reason = 'Skills over MCP is turned off (enable_skills).' + else if (listing.expose_skills === false) reason = 'this server is excluded from agents (expose_skills: false).' + else if (s.blocked) reason = 'the skill is blocked.' + else if (!s.listed) reason = 'the server no longer lists this skill.' + else if (s.status !== 'approved') reason = `its state is now ${skillStateChip(s).label}.` + return reason ? `Approved. Not offered to agents yet: ${reason}` : 'Approved. Not offered to agents yet.' +} diff --git a/frontend/src/views/ServerDetail.vue b/frontend/src/views/ServerDetail.vue index 218036dc1..27a4fbacb 100644 --- a/frontend/src/views/ServerDetail.vue +++ b/frontend/src/views/ServerDetail.vue @@ -317,6 +317,8 @@ Tools ({{ serverTools.length }}) + +