From 89ca8043d77acb884bd2b2f1403dbdee9d649a57 Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Wed, 18 Nov 2026 14:57:28 +0200 Subject: [PATCH 01/18] feat(skills): Skills tab on the server page of the Web UI (spec 125, PR-4a) An administrator can now review skills in the Web UI: the list with state chips, the file list, a paged viewer of the current or approved copy, the changes since the approved copy (file set by digest and a line diff), scan findings, approve, block, unblock and refresh. skills.changed reloads the tab. Review binding: Approve sends the hash and incarnation of the version the reviewer opened. A reload that changes them marks the review stale and disables Approve until the new version is opened. Every part the viewer and the line diff read must carry the digest listed for that file and copy, so parts of two versions are never joined. A 409 reloads and is never retried. Also: the API client keeps error_code on failures (additive); the tab falls back to Tools when it is not offered and is never requested for a tenant; cmd/skillsfixture is a loopback-only skills upstream for the sweep (Host check, mutate needs a custom header and refuses an Origin); scripts/run-skills-tab-sweep.sh runs the browser sweep in one command and writes a results file, and runs in the advisory release-gate web-ui-sweep job. Review queue and Home attention rows for skills and the macOS labels are the next PR (PR-4b). Related #1895 --- .github/workflows/release-qa-gate.yml | 16 + ROADMAP.md | 2 +- cmd/release-gate/webui_sweep_audit_test.go | 14 + cmd/release-gate/webui_sweep_speclist_test.go | 33 +- cmd/skillsfixture/main.go | 146 +++++++ cmd/skillsfixture/main_test.go | 170 ++++++++ docs/development/release-gate.md | 18 +- docs/development/web-ui-verification.md | 11 + docs/features/skills.md | 12 + docs/web-ui/server-detail.md | 49 ++- e2e/web-ui-sweep/skills-tab.spec.ts | 202 +++++++++ .../src/components/skills/SkillDetail.vue | 213 +++++++++ .../src/components/skills/SkillsPanel.vue | 217 ++++++++++ frontend/src/services/api.ts | 54 ++- frontend/src/stores/system.ts | 10 + frontend/src/types/api.ts | 76 ++++ frontend/src/utils/skills.ts | 156 +++++++ frontend/src/views/ServerDetail.vue | 80 +++- frontend/tests/unit/fixtures/skills125.ts | 19 + .../unit/server-detail-skills-tab.spec.ts | 177 ++++++++ .../tests/unit/server-detail-tab-url.spec.ts | 7 + frontend/tests/unit/skill-detail.spec.ts | 227 ++++++++++ frontend/tests/unit/skills-api.spec.ts | 73 ++++ frontend/tests/unit/skills-inert-text.spec.ts | 40 ++ frontend/tests/unit/skills-panel.spec.ts | 255 +++++++++++ .../tests/unit/skills-sse-redispatch.spec.ts | 29 ++ frontend/tests/unit/skills-utils.spec.ts | 140 ++++++ internal/skills/skillstest/fixture.go | 51 ++- scripts/run-skills-tab-sweep.sh | 404 ++++++++++++++++++ specs/125-skills-over-mcp/tasks.md | 8 +- .../verification/report.html | 20 + .../verification/skills-sweep-results.json | 173 ++++++++ 32 files changed, 3073 insertions(+), 29 deletions(-) create mode 100644 cmd/skillsfixture/main.go create mode 100644 cmd/skillsfixture/main_test.go create mode 100644 e2e/web-ui-sweep/skills-tab.spec.ts create mode 100644 frontend/src/components/skills/SkillDetail.vue create mode 100644 frontend/src/components/skills/SkillsPanel.vue create mode 100644 frontend/src/utils/skills.ts create mode 100644 frontend/tests/unit/fixtures/skills125.ts create mode 100644 frontend/tests/unit/server-detail-skills-tab.spec.ts create mode 100644 frontend/tests/unit/skill-detail.spec.ts create mode 100644 frontend/tests/unit/skills-api.spec.ts create mode 100644 frontend/tests/unit/skills-inert-text.spec.ts create mode 100644 frontend/tests/unit/skills-panel.spec.ts create mode 100644 frontend/tests/unit/skills-sse-redispatch.spec.ts create mode 100644 frontend/tests/unit/skills-utils.spec.ts create mode 100755 scripts/run-skills-tab-sweep.sh create mode 100644 specs/125-skills-over-mcp/verification/report.html create mode 100644 specs/125-skills-over-mcp/verification/skills-sweep-results.json diff --git a/.github/workflows/release-qa-gate.yml b/.github/workflows/release-qa-gate.yml index bd90dd26b..94742ab03 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 @@ -562,6 +564,20 @@ 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; its results file (skills-sweep-results.json) and + # screenshots land under tmp/web-smoke-artifacts/, which the Playwright + # report upload below already carries. + - 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: | + bash scripts/run-skills-tab-sweep.sh --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 ba7080e52..166f21e09 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -1207,4 +1207,4 @@ 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%) | diff --git a/cmd/release-gate/webui_sweep_audit_test.go b/cmd/release-gate/webui_sweep_audit_test.go index 3844b97f4..a394eb300 100644 --- a/cmd/release-gate/webui_sweep_audit_test.go +++ b/cmd/release-gate/webui_sweep_audit_test.go @@ -82,6 +82,20 @@ 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) + } } // 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/skillsfixture/main.go b/cmd/skillsfixture/main.go new file mode 100644 index 000000000..c865cf071 --- /dev/null +++ b/cmd/skillsfixture/main.go @@ -0,0 +1,146 @@ +// 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) + fmt.Fprintf(os.Stdout, "skillsfixture listening on http://%s/mcp\n", ln.Addr()) + 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..b7437198d --- /dev/null +++ b/cmd/skillsfixture/main_test.go @@ -0,0 +1,170 @@ +package main + +import ( + "bytes" + "encoding/json" + "net" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "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 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) + } + 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) + } + 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..512f00218 100644 --- a/docs/development/release-gate.md +++ b/docs/development/release-gate.md @@ -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,20 @@ 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. The step runs even when the + standing sweep failed; a red step marks the job failed, which + `continue-on-error` keeps advisory. Its outcome is not a separate manifest + entry: read the results file. 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), diff --git a/docs/development/web-ui-verification.md b/docs/development/web-ui-verification.md index 9576a6326..c12be5c0f 100644 --- a/docs/development/web-ui-verification.md +++ b/docs/development/web-ui-verification.md @@ -32,6 +32,17 @@ 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 +``` + +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`), `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 while the skill is open (stale review, re-open, file diff, line diff, approve), block and unblock, and no page error. It writes `skills-sweep-results.json` (the checked commit, and whether the working tree was dirty; the fixture command line and port; each scenario's pass/fail; 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. The release gate runs it in the advisory `web-ui-sweep` job. The committed report is `specs/125-skills-over-mcp/verification/report.html`. + +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..89886b356 100644 --- a/docs/web-ui/server-detail.md +++ b/docs/web-ui/server-detail.md @@ -13,10 +13,55 @@ 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 removed text file has **View approved**, which + opens its approved copy. +- **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..45c429544 --- /dev/null +++ b/e2e/web-ui-sweep/skills-tab.spec.ts @@ -0,0 +1,202 @@ +// 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 the upstream bytes and pressing Refresh while the skill is open +// marks the open review stale (Approve off) 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. block and unblock; +// 6. 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') +test.describe.configure({ mode: 'serial' }) + +const pageErrors: string[] = [] + +function url(route: string): string { + const sep = route.includes('?') ? '&' : '?' + return KEY ? `${BASE}/ui${route}${sep}apikey=${encodeURIComponent(KEY)}` : `${BASE}/ui${route}` +} + +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)) +}) + +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() + // 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. + const isPart = (offset: number) => (r: { url(): string }) => { + const u = new URL(r.url()) + return u.pathname.endsWith('/skills/content') && u.searchParams.get('file') === 'data/large.txt' && + 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-data/large.txt"]').click()]) + let shown = 0 + let loads = 0 + for (;;) { + expect(res.status()).toBe(200) + const body = await res.json() + const part = body.data ?? body + 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(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++ + } + 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('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..a8fac05f5 --- /dev/null +++ b/frontend/src/components/skills/SkillDetail.vue @@ -0,0 +1,213 @@ + + + diff --git a/frontend/src/components/skills/SkillsPanel.vue b/frontend/src/components/skills/SkillsPanel.vue new file mode 100644 index 000000000..dbccb001d --- /dev/null +++ b/frontend/src/components/skills/SkillsPanel.vue @@ -0,0 +1,217 @@ + + + diff --git a/frontend/src/services/api.ts b/frontend/src/services/api.ts index 0d7c4e929..98eef82d5 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_in_progress, + // 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..7b0ccda6f --- /dev/null +++ b/frontend/src/utils/skills.ts @@ -0,0 +1,156 @@ +// Spec 125 (skills over MCP, PR-4a): pure helpers for the Skills tab. +import type { SkillEntry, SkillFileInfo, SkillContentResponse, SkillsListResponse } from '@/types/api' + +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)) +} + +export interface LineOp { op: 'same' | 'add' | 'del'; 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 + +/** + * 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, in which case the + * result is tooLarge with no ops. + */ +export function lineDiff(a: string, b: string, maxCells = LINE_DIFF_MAX_CELLS): 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: [] } + + 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[] = x.slice(0, head).map(text => ({ op: 'same', text })) + let i = 0, j = 0 + while (i < mx.length && j < my.length) { + if (mx[i] === my[j]) { ops.push({ op: 'same', text: mx[i] }); i++; j++ } + else if (t[(i + 1) * w + j] >= t[i * w + j + 1]) ops.push({ op: 'del', text: mx[i++] }) + else ops.push({ op: 'add', text: my[j++] }) + } + while (i < mx.length) ops.push({ op: 'del', text: mx[i++] }) + while (j < my.length) ops.push({ op: 'add', text: my[j++] }) + for (const text of x.slice(x.length - tail)) ops.push({ op: 'same', text }) + 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. */ +export function skillsTabVisible(listing: SkillsListResponse | undefined | null): boolean { + return !!listing && listing.enabled && (listing.supported || (listing.skills?.length ?? 0) > 0) +} + +/** Operator-facing words for an error code of the skills routes. */ +export function skillErrorNotice(code: string | undefined, message: string | undefined): string { + switch (code) { + 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 was changed. The list was reloaded.' + case 'refresh_in_progress': + return 'A refresh is already running for this server. The list updates when it finishes.' + default: + return message || 'The request failed' + } +} diff --git a/frontend/src/views/ServerDetail.vue b/frontend/src/views/ServerDetail.vue index 218036dc1..8dc6d4c34 100644 --- a/frontend/src/views/ServerDetail.vue +++ b/frontend/src/views/ServerDetail.vue @@ -317,6 +317,8 @@ Tools ({{ serverTools.length }}) + + - + +
@@ -74,22 +75,23 @@

Scan

+

- Verdict: - at {{ formatDateTime(skill.scan.scanned_at) }} + Verdict: + at {{ formatDateTime(scan.scanned_at) }}

-

- Scan incomplete: +

+ Scan incomplete:

-
    -
  • +
      +
    • @ {{ f.offset }}
      
               
    -

    More findings exist than are listed.

    +

    More findings exist than are listed.

@@ -117,6 +119,7 @@ const emit = defineEmits<{ const LINE_DIFF_MAX_BYTES = 256 * 1024 const chip = computed(() => skillStateChip(props.skill)) +const scan = computed(() => props.skill.scan as SkillEntry['scan'] | undefined) const chipClass = computed(() => `badge-${({ error: 'error', warning: 'warning', info: 'info', success: 'success', neutral: 'ghost' })[chip.value.tone]}`) const canApprove = computed(() => !props.skill.blocked && (props.skill.status === 'pending' || props.skill.status === 'changed')) const diffRows = computed(() => props.skill.approved_files ? skillFileDiff(props.skill.approved_files, props.skill.files) : null) diff --git a/frontend/src/components/skills/SkillsPanel.vue b/frontend/src/components/skills/SkillsPanel.vue index dbccb001d..d63b51f8e 100644 --- a/frontend/src/components/skills/SkillsPanel.vue +++ b/frontend/src/components/skills/SkillsPanel.vue @@ -51,8 +51,8 @@ {{ s.available ? 'Offered to agents' : 'Not offered' }} - {{ s.files.length }} file{{ s.files.length === 1 ? '' : 's' }} - scan: + {{ s.files?.length ?? 0 }} file{{ (s.files?.length ?? 0) === 1 ? '' : 's' }} + scan: @@ -108,7 +108,10 @@ let reviewToken = 0 const selectedPath = computed(() => review.value?.path ?? null) const liveSelected = computed(() => listing.value?.skills.find(s => s.path === selectedPath.value) ?? null) +// Opening (or re-opening) a skill starts a new review: a notice that answered +// the previous one (e.g. "Approved.") is not carried over to it. function open(s: SkillEntry) { + notice.value = '' review.value = { path: s.path, entry: s, incarnation: listing.value?.incarnation ?? 0, token: ++reviewToken, stale: false } } @@ -152,8 +155,12 @@ async function refresh() { const res = await api.refreshServerSkills(server) if (!isCurrent(server, v)) return refreshing.value = false - if (res.success && res.data) { requestSeq++; apply(res.data) } - else notice.value = skillErrorNotice(res.errorCode, res.error) + if (res.success && res.data) { requestSeq++; apply(res.data); return } + // A failed refresh (refresh_superseded, skills_not_supported, skills_disabled, + // server_replaced, a 500) reloads the listing: the notice says it was reloaded, + // and the stored records may have moved even though this refresh did not apply. + notice.value = skillErrorNotice(res.errorCode, res.error) + await load() } // Spec 117 style binding: the approval names the hash and the incarnation of diff --git a/frontend/src/services/api.ts b/frontend/src/services/api.ts index 98eef82d5..3fb553725 100644 --- a/frontend/src/services/api.ts +++ b/frontend/src/services/api.ts @@ -615,7 +615,7 @@ class APIService { } // Spec 125 (skills over MCP, PR-4a): administrator-only skills routes. Failures - // carry `errorCode` (review_out_of_date, server_replaced, refresh_in_progress, + // 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. diff --git a/frontend/src/utils/skills.ts b/frontend/src/utils/skills.ts index 7b0ccda6f..f2710df84 100644 --- a/frontend/src/utils/skills.ts +++ b/frontend/src/utils/skills.ts @@ -136,9 +136,15 @@ export function skillFileDigest(entry: Pick f.path === file)?.digest } -/** The tab is offered when the feature is on and the server supports skills or has records. */ +/** + * 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 { - return !!listing && listing.enabled && (listing.supported || (listing.skills?.length ?? 0) > 0) + if (!listing || typeof listing.supported !== 'boolean') return false + return listing.enabled === true && (listing.supported || (listing.skills?.length ?? 0) > 0) } /** Operator-facing words for an error code of the skills routes. */ @@ -148,8 +154,13 @@ export function skillErrorNotice(code: string | undefined, message: string | und 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 was changed. The list was reloaded.' - case 'refresh_in_progress': - return 'A refresh is already running for this server. The list updates when it finishes.' + // 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 was refreshed. The list was reloaded.' default: return message || 'The request failed' } diff --git a/frontend/src/views/ServerDetail.vue b/frontend/src/views/ServerDetail.vue index 8dc6d4c34..4d0eb2255 100644 --- a/frontend/src/views/ServerDetail.vue +++ b/frontend/src/views/ServerDetail.vue @@ -1715,26 +1715,40 @@ function leaveSkillsTabIfNotOffered() { else if (route.query.tab === 'skills') void router.replace({ query: { ...route.query, tab: 'tools' } }) } async function checkSkillsTab(reset = true) { - const gen = ++skillsCheckGeneration + // A first check (reset) supersedes every earlier one. A background re-check + // (reset=false, after skills.changed) takes the generation only when it has + // a successful answer, so a failed one never drops a first check still in + // flight and never changes the tab. + const gen = reset ? ++skillsCheckGeneration : skillsCheckGeneration const name = props.serverName if (reset) { skillsTabVisible.value = false skillsTabChecked.value = false } if (isTenant.value) { + if (!reset) return skillsTabVisible.value = false skillsTabChecked.value = true leaveSkillsTabIfNotOffered() return } let visible = false + let answered = false try { const res = await api.getServerSkills(name) - visible = !!res.success && listingOffersSkills(res.data) + answered = !!res.success + visible = answered && listingOffersSkills(res.data) } catch { - // The tab is optional; no answer means no tab. + // The tab is optional; no answer means no tab (on a first check). + } + if (gen !== skillsCheckGeneration || name !== props.serverName) return + // A failed background re-check (a 409 server_replaced right after the + // reviewer's own write, a 500, a network error) leaves the tab as it is: it + // must not unmount the review that is open. + if (!reset) { + if (!answered) return + ++skillsCheckGeneration } - if (gen !== skillsCheckGeneration) return skillsTabVisible.value = visible skillsTabChecked.value = true leaveSkillsTabIfNotOffered() diff --git a/frontend/tests/unit/server-detail-skills-tab.spec.ts b/frontend/tests/unit/server-detail-skills-tab.spec.ts index 6888034b8..750f8c74a 100644 --- a/frontend/tests/unit/server-detail-skills-tab.spec.ts +++ b/frontend/tests/unit/server-detail-skills-tab.spec.ts @@ -164,6 +164,38 @@ describe('ServerDetail Skills tab (Spec 125)', () => { wrapper.unmount() }) + // Round-2 finding 3: a failed background re-check keeps the open review. + it('a failed re-check after a skills change (409 or 500) keeps the tab and the open panel', async () => { + const { wrapper, router } = await mountServerDetail('/servers/alpha?tab=skills') + expect(wrapper.find('[data-test="skills-panel"]').exists()).toBe(true) + for (const failure of [ + { success: false, error: 'server_replaced: x', errorCode: 'server_replaced' }, + { success: false, error: 'internal error' }, + ]) { + ;(api.getServerSkills as any).mockResolvedValue(failure) + window.dispatchEvent(new CustomEvent('mcpproxy:skills-changed', { detail: { server: 'alpha' } })) + await flushPromises(); await flushPromises() + expect(wrapper.find('[data-test="skills-tab"]').exists()).toBe(true) + expect(wrapper.find('[data-test="skills-panel"]').exists()).toBe(true) + expect(router.currentRoute.value.query.tab).toBe('skills') + } + // A thrown request is a failure too. + ;(api.getServerSkills as any).mockRejectedValue(new Error('network')) + window.dispatchEvent(new CustomEvent('mcpproxy:skills-changed', { detail: { server: 'alpha' } })) + await flushPromises(); await flushPromises() + expect(wrapper.find('[data-test="skills-panel"]').exists()).toBe(true) + wrapper.unmount() + }) + + // Round-2 finding 11: an agent-token listing (no `supported`) offers no tab. + it('hides the tab for an agent-shaped listing without `supported`', async () => { + ;(api.getServerSkills as any).mockResolvedValue({ success: true, data: { enabled: true, server: 'alpha', skills: [{ path: 'hf', status: 'approved', files: [] }] } }) + const { wrapper, router } = await mountServerDetail('/servers/alpha?tab=skills') + expect(wrapper.find('[data-test="skills-tab"]').exists()).toBe(false) + expect(wrapper.find('[data-test="skills-panel"]').exists()).toBe(false) + expect(router.currentRoute.value.query.tab).toBe('tools') + }) + it('an in-place change to a server that offers skills honours its ?tab=skills (not judged by the previous server)', async () => { ;(api.getServerSkills as any).mockResolvedValue({ success: true, data: makeListing([], { enabled: false }) }) const { wrapper, router } = await mountServerDetail('/servers/alpha') diff --git a/frontend/tests/unit/skill-detail.spec.ts b/frontend/tests/unit/skill-detail.spec.ts index 38bd1013c..73fb2ad0d 100644 --- a/frontend/tests/unit/skill-detail.spec.ts +++ b/frontend/tests/unit/skill-detail.spec.ts @@ -220,6 +220,30 @@ describe('SkillDetail', () => { expect(w.get('[data-test="skill-viewer-text"]').text()).toBe('approved text') }) + // Round-2 finding 6: a text file replaced by a binary file at the same path. + it('offers View approved when the approved copy is text and the current file is binary', async () => { + m(api.getSkillContent).mockResolvedValue(ok({ text: 'old text', offset: 0, size: 8, digest: 'sha256:t' })) + const w = mountDetail(makeSkill('a', { + status: 'changed', approved_hash: 'sk1-old', + approved_files: [skillFile('SKILL.md'), skillFile('notes', 'sha256:t', 8, true)], + files: [skillFile('SKILL.md'), skillFile('notes', 'sha256:bin', 8, false)], + })) + expect(w.get('[data-test="skill-diff-notes"]').attributes('data-state')).toBe('changed') + // No line diff (the current copy is binary), but the approved copy can be read. + expect(w.find('[data-test="skill-line-diff-notes"]').exists()).toBe(false) + await w.get('[data-test="skill-view-approved-notes"]').trigger('click'); await flushPromises() + expect(api.getSkillContent).toHaveBeenCalledWith('srv', { skill: 'a', file: 'notes', copy: 'approved', offset: 0 }) + expect(w.get('[data-test="skill-viewer-text"]').text()).toBe('old text') + }) + + // Round-2 finding 11: an entry without a scan block (the agent shape) does not throw. + it('renders an entry without a scan block', () => { + const s = makeSkill('a') as any + delete s.scan + const w = mountDetail(s) + expect(w.get('[data-test="skill-scan"]').text()).toContain('not scanned') + }) + it('disables Approve while the review is stale', () => { const w = mount(SkillDetail, { props: { serverName: 'srv', skill: makeSkill('a'), busy: false, stale: true } }) expect(w.get('[data-test="skill-approve"]').attributes('disabled')).toBeDefined() diff --git a/frontend/tests/unit/skills-panel.spec.ts b/frontend/tests/unit/skills-panel.spec.ts index 8975e6808..4b0452eb4 100644 --- a/frontend/tests/unit/skills-panel.spec.ts +++ b/frontend/tests/unit/skills-panel.spec.ts @@ -131,15 +131,74 @@ describe('SkillsPanel', () => { expect(api.getServerSkills).toHaveBeenCalledTimes(3) }) - it('refresh replaces the listing; a 409 refresh_in_progress shows a notice', async () => { + // Round-2 finding 4: the backend sends refresh_superseded (never refresh_in_progress), + // and the notice says the list was reloaded, so a failed refresh reloads it. + it('refresh replaces the listing; a 409 refresh_superseded shows a notice and reloads the listing', async () => { m(api.getServerSkills).mockResolvedValue(ok(makeListing([makeSkill('a')]))) const w = mountPanel(); await flushPromises() m(api.refreshServerSkills).mockResolvedValueOnce(ok(makeListing([makeSkill('a'), makeSkill('new')]))) await w.get('[data-test="skills-refresh"]').trigger('click'); await flushPromises() expect(w.find('[data-test="skill-row-new"]').exists()).toBe(true) - m(api.refreshServerSkills).mockResolvedValueOnce({ success: false, error: 'refresh_in_progress: x', errorCode: 'refresh_in_progress' }) + expect(api.getServerSkills).toHaveBeenCalledTimes(1) + m(api.getServerSkills).mockResolvedValue(ok(makeListing([makeSkill('a'), makeSkill('after')]))) + m(api.refreshServerSkills).mockResolvedValueOnce({ success: false, error: 'server srv reconnected during the refresh', errorCode: 'refresh_superseded' }) + await w.get('[data-test="skills-refresh"]').trigger('click'); await flushPromises() + expect(w.get('[data-test="skills-notice"]').text()).toMatch(/reconnected during the refresh/i) + expect(w.get('[data-test="skills-notice"]').text()).toMatch(/reloaded/i) + expect(api.getServerSkills).toHaveBeenCalledTimes(2) + expect(w.find('[data-test="skill-row-after"]').exists()).toBe(true) + }) + + it('a refresh failing with skills_not_supported or a 500 also reloads the listing', async () => { + m(api.getServerSkills).mockResolvedValue(ok(makeListing([makeSkill('a')]))) + const w = mountPanel(); await flushPromises() + m(api.refreshServerSkills).mockResolvedValueOnce({ success: false, error: 'server srv does not announce the skills extension', errorCode: 'skills_not_supported' }) + await w.get('[data-test="skills-refresh"]').trigger('click'); await flushPromises() + expect(w.get('[data-test="skills-notice"]').text()).toMatch(/does not announce the skills extension/i) + expect(api.getServerSkills).toHaveBeenCalledTimes(2) + m(api.refreshServerSkills).mockResolvedValueOnce({ success: false, error: 'boom' }) await w.get('[data-test="skills-refresh"]').trigger('click'); await flushPromises() - expect(w.get('[data-test="skills-notice"]').text()).toMatch(/already running/i) + expect(w.get('[data-test="skills-notice"]').text()).toContain('boom') + expect(api.getServerSkills).toHaveBeenCalledTimes(3) + }) + + // Round-2 finding 5: a write notice belongs to the review it answered. + it('opening another skill clears the write notice', async () => { + m(api.getServerSkills).mockResolvedValue(ok(makeListing([makeSkill('a'), makeSkill('b')]))) + m(api.approveSkills).mockResolvedValue(ok({ approved: 1 })) + const w = mountPanel(); await flushPromises() + await w.get('[data-test="skill-row-a"]').trigger('click'); await flushPromises() + await w.get('[data-test="skill-approve"]').trigger('click'); await flushPromises() + expect(w.get('[data-test="skills-notice"]').text()).toMatch(/approved/i) + await w.get('[data-test="skill-row-b"]').trigger('click'); await flushPromises() + expect(w.find('[data-test="skills-notice"]').exists()).toBe(false) + }) + + it('switching skill after the write answer but before its reload finishes shows no notice on the new one', async () => { + m(api.getServerSkills).mockResolvedValueOnce(ok(makeListing([makeSkill('a'), makeSkill('b')]))) + m(api.approveSkills).mockResolvedValue(ok({ approved: 1 })) + let releaseReload: (v: unknown) => void = () => {} + m(api.getServerSkills).mockReturnValueOnce(new Promise(r => { releaseReload = r })) + const w = mountPanel(); await flushPromises() + await w.get('[data-test="skill-row-a"]').trigger('click'); await flushPromises() + await w.get('[data-test="skill-approve"]').trigger('click'); await flushPromises() + // The answer is in; the reload is still in flight. + expect(api.getServerSkills).toHaveBeenCalledTimes(2) + await w.get('[data-test="skill-row-b"]').trigger('click'); await flushPromises() + releaseReload(ok(makeListing([makeSkill('a', { status: 'approved' }), makeSkill('b')]))); await flushPromises() + expect(w.get('[data-test="skill-name"]').text()).toBe('b') + expect(w.find('[data-test="skills-notice"]').exists()).toBe(false) + }) + + // Round-2 finding 11: the agent-token listing shape has no scan block. + it('renders an entry without a scan block (agent shape) without throwing', async () => { + const s = makeSkill('a', { status: 'approved' }) as any + delete s.scan + m(api.getServerSkills).mockResolvedValue(ok(makeListing([s]))) + const w = mountPanel(); await flushPromises() + expect(w.get('[data-test="skill-chip-a"]').text()).toBe('Approved') + await w.get('[data-test="skill-row-a"]').trigger('click'); await flushPromises() + expect(w.find('[data-test="skill-detail"]').exists()).toBe(true) }) it('reloads on mcpproxy:skills-changed for its own server only', async () => { diff --git a/frontend/tests/unit/skills-utils.spec.ts b/frontend/tests/unit/skills-utils.spec.ts index 357d1617e..21928e309 100644 --- a/frontend/tests/unit/skills-utils.spec.ts +++ b/frontend/tests/unit/skills-utils.spec.ts @@ -127,13 +127,22 @@ describe('skillsTabVisible', () => { expect(skillsTabVisible({ enabled: true, supported: true, skills: [] } as any)).toBe(true) expect(skillsTabVisible({ enabled: true, supported: false, skills: [{}] } as any)).toBe(true) }) + + // Round-2 finding 11: the agent-token shape has no `supported` (and no scan). + it('treats a listing without `supported` (the agent shape) as not offered', () => { + expect(skillsTabVisible({ enabled: true, skills: [{ path: 'a', status: 'approved' }] } as any)).toBe(false) + expect(skillsTabVisible({ enabled: true, skills: [] } as any)).toBe(false) + }) }) describe('skillErrorNotice', () => { it('names the stale-review and replaced-server cases and passes the rest through', () => { expect(skillErrorNotice('review_out_of_date', 'x')).toMatch(/changed since you opened it/i) expect(skillErrorNotice('server_replaced', 'x')).toMatch(/removed and added again/i) - expect(skillErrorNotice('refresh_in_progress', 'x')).toMatch(/already running/i) + // The refresh codes the backend sends (internal/httpapi/skills.go). + expect(skillErrorNotice('refresh_superseded', 'x')).toMatch(/reconnected during the refresh/i) + expect(skillErrorNotice('skills_not_supported', 'x')).toMatch(/does not announce the skills extension/i) + expect(skillErrorNotice('skills_disabled', 'x')).toMatch(/turned off/i) expect(skillErrorNotice('skill_unusable', 'cannot approve: bad')).toBe('cannot approve: bad') expect(skillErrorNotice(undefined, 'plain')).toBe('plain') }) diff --git a/internal/gatereport/gatereport.go b/internal/gatereport/gatereport.go index f0ce36c91..50cc80008 100644 --- a/internal/gatereport/gatereport.go +++ b/internal/gatereport/gatereport.go @@ -116,6 +116,13 @@ const ( // listed under advisory_failures) without blocking publication. EntryAdvisoryWebUISweep = "advisory/web-ui-sweep" + // EntryAdvisorySkillsTabSweep is the Spec 125 Skills tab browser sweep + // (scripts/run-skills-tab-sweep.sh), a second step of the advisory + // web-ui-sweep job. ADVISORY like the T2 sweep: a red run (or one that + // died before writing its fragment) is listed under advisory_failures and + // never blocks the tag. + EntryAdvisorySkillsTabSweep = "advisory/skills-tab-sweep" + // EntryAdvisoryMacOSSmoke is the Spec 081 T3 macOS tray smoke (US4, // FR-019/FR-020). ADVISORY until it has passed on 3 consecutive release // tags (FR-021); a failure lands in advisory_failures and never blocks. @@ -130,7 +137,8 @@ const ( // Manifest returns the hardcoded expected-entries manifest: 5 matrix cells + // 5 invariants (incl. the T4 surface-consistency check) + 5 assembled suite -// jobs (FR-003) + 2 advisory entries (the T2 Web UI sweep, the T3 macOS smoke). +// jobs (FR-003) + 3 advisory entries (the T2 Web UI sweep, the Spec 125 Skills +// tab sweep, the T3 macOS smoke). func Manifest() []ManifestEntry { return []ManifestEntry{ {Name: EntryMatrixStdio, Blocking: true}, @@ -152,6 +160,7 @@ func Manifest() []ManifestEntry { {Name: EntrySuiteScanEval, Blocking: true}, {Name: EntryAdvisoryWebUISweep, Blocking: false}, + {Name: EntryAdvisorySkillsTabSweep, Blocking: false}, {Name: EntryAdvisoryMacOSSmoke, Blocking: false}, } diff --git a/internal/gatereport/gatereport_test.go b/internal/gatereport/gatereport_test.go index 6e056be87..505063140 100644 --- a/internal/gatereport/gatereport_test.go +++ b/internal/gatereport/gatereport_test.go @@ -382,3 +382,61 @@ func TestMarkdown_ContainsVerdictAndRows(t *testing.T) { t.Error("unescaped pipe in markdown table reason") } } + +// Spec 125: the Skills tab sweep (scripts/run-skills-tab-sweep.sh) runs in the +// advisory web-ui-sweep job. It is its own ADVISORY manifest entry, so a red +// skills sweep (or one that died before writing its fragment) is listed under +// advisory_failures and never blocks the tag. +func TestManifest_SkillsTabSweep_IsAdvisory(t *testing.T) { + if EntryAdvisorySkillsTabSweep != "advisory/skills-tab-sweep" { + t.Fatalf("entry name = %q, want advisory/skills-tab-sweep", EntryAdvisorySkillsTabSweep) + } + var found bool + for _, m := range Manifest() { + if m.Name != EntryAdvisorySkillsTabSweep { + continue + } + found = true + if m.Blocking || m.Reserved { + t.Errorf("%s must be advisory (Blocking:false) and not reserved, got %+v", m.Name, m) + } + } + if !found { + t.Fatalf("manifest is missing the %s entry", EntryAdvisorySkillsTabSweep) + } +} + +func TestMerge_SkillsTabSweepFailureOrMissing_IsAdvisoryOnly(t *testing.T) { + for _, status := range []Status{StatusFail, StatusAdvisoryFail} { + frags := passAllBlocking() + for i := range frags { + if frags[i].Name == EntryAdvisorySkillsTabSweep { + frags[i].Status = status + } + } + r := Merge(frags) + if !r.Passed() { + t.Fatalf("skills tab sweep %s must not block the gate: %v", status, r.BlockingFailures) + } + if len(r.AdvisoryFailures) != 1 || !strings.Contains(r.AdvisoryFailures[0], EntryAdvisorySkillsTabSweep) { + t.Errorf("skills tab sweep %s must be an advisory failure, got %v", status, r.AdvisoryFailures) + } + } + var kept []Fragment + for _, f := range passAllBlocking() { + if f.Name != EntryAdvisorySkillsTabSweep { + kept = append(kept, f) + } + } + r := Merge(kept) + if !r.Passed() { + t.Fatalf("a missing skills sweep fragment must not block the gate: %v", r.BlockingFailures) + } + e := entryByName(t, r, EntryAdvisorySkillsTabSweep) + if e.Status != StatusFail || e.Reason != ReasonMissingFragment { + t.Errorf("got status=%s reason=%q, want fail/%q", e.Status, e.Reason, ReasonMissingFragment) + } + if len(r.AdvisoryFailures) != 1 || !strings.Contains(r.AdvisoryFailures[0], EntryAdvisorySkillsTabSweep) { + t.Errorf("missing skills sweep fragment must surface as an advisory failure, got %v", r.AdvisoryFailures) + } +} diff --git a/scripts/run-skills-tab-sweep.sh b/scripts/run-skills-tab-sweep.sh index c4517b033..6e3c21514 100755 --- a/scripts/run-skills-tab-sweep.sh +++ b/scripts/run-skills-tab-sweep.sh @@ -8,8 +8,11 @@ # It starts, and on exit stops, only what it started: # * cmd/skillsfixture on a free loopback port; # * a core on a free high loopback port with a scratch data dir (never -# ~/.mcpproxy), enable_skills on, a generated throwaway API key, and the -# fixture as a trust_mode: manual streamable-http upstream; +# ~/.mcpproxy: MCPPROXY_DATA_DIR / MCPPROXY_DATA, which would override the +# config's data_dir, are removed from its environment, --data-dir names the +# scratch dir, HOME points at a scratch home, and a data dir under +# $HOME/.mcpproxy is refused), enable_skills on, a generated throwaway API +# key, and the fixture as a trust_mode: manual streamable-http upstream; # then approves the server, runs the spec, and reads the core's own skill # records back after the approve, block and unblock steps. # @@ -27,12 +30,25 @@ fi usage() { cat </tmp/skills-sweep) --report-html FILE also write a self-contained HTML report (one section per scenario, with its screenshots) to FILE + --no-screenshots write the --report-html report without embedded + screenshots (the copy committed under specs/; the + screenshots stay in --out/screenshots for artifacts) + --self-test no browser: prove that an ambient MCPPROXY_DATA_DIR / + MCPPROXY_DATA never reaches the core (it starts one with + both set to decoy dirs and checks the database lands in + the scratch dir only), that a data dir under + \$HOME/.mcpproxy is refused, and that the results writer + records the first failed attempt and redacts the API key + and local paths + --self-test-first run the --self-test checks, then the sweep (the release + gate does this, so both land in one advisory entry) -h, --help print this message Environment: @@ -44,9 +60,14 @@ Environment: download (offline machines) Output (in --out): - skills-sweep-results.json commit, fixture command line and port, each - scenario's pass/fail, and GET /skills read back - after the approve, block and unblock steps + skills-sweep-results.json checked_commit (git rev-parse HEAD) and + working_tree_dirty (a dirty tree is labelled + pre-commit evidence), fixture command (basename + + args) and port, each scenario's pass/fail (the + first failed attempt's error), and GET /skills read + back after the approve, block and unblock steps. + The API key is replaced by *** and local paths by + ///~ in every text file written screenshots/ state/ playwright-results.json core.log fixture.log Exit status is non-zero when any scenario failed or a state is missing. EOF @@ -56,11 +77,17 @@ SCRIPT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) REPO_ROOT=$(cd "$SCRIPT_DIR/.." && pwd) OUT="$REPO_ROOT/tmp/skills-sweep" REPORT_HTML="" +SCREENSHOTS=1 +SELF_TEST=0 +SELF_TEST_FIRST=0 while [[ $# -gt 0 ]]; do case "$1" in --out) OUT="${2:?--out needs a directory}"; shift 2 ;; --report-html) REPORT_HTML="${2:?--report-html needs a file}"; shift 2 ;; + --no-screenshots) SCREENSHOTS=0; shift ;; + --self-test) SELF_TEST=1; shift ;; + --self-test-first) SELF_TEST_FIRST=1; shift ;; -h|--help) usage; exit 0 ;; *) echo "unknown argument: $1" >&2; usage >&2; exit 2 ;; esac @@ -77,22 +104,48 @@ required node required npm required git -mkdir -p "$OUT" -OUT=$(cd "$OUT" && pwd) -if [[ -n "$REPORT_HTML" ]]; then - mkdir -p "$(dirname "$REPORT_HTML")" - REPORT_HTML="$(cd "$(dirname "$REPORT_HTML")" && pwd)/$(basename "$REPORT_HTML")" +if [[ $SCREENSHOTS -eq 0 && -z "$REPORT_HTML" ]]; then + echo "--no-screenshots only applies to --report-html" >&2 + exit 2 fi -rm -rf "$OUT/screenshots" "$OUT/state" "$OUT/playwright-results.json" "$OUT/skills-sweep-results.json" -mkdir -p "$OUT/screenshots" "$OUT/state" SERVER="${SWEEP_SERVER_NAME:-skillsfx}" WORK=$(mktemp -d "${TMPDIR:-/tmp}/skills-sweep.XXXXXX") +WORK=$(cd "$WORK" && pwd -P) DATA_DIR="$WORK/data" +CORE_HOME="$WORK/home" CONFIG_PATH="$WORK/mcp_config.json" CORE_LOG="$WORK/core.log" FIXTURE_LOG="$WORK/fixture.log" -mkdir -p "$DATA_DIR" +mkdir -p "$DATA_DIR" "$CORE_HOME" +# The operator's real home, captured before anything is started: the core runs +# with HOME=$CORE_HOME, and the guard below compares against this one. +OPERATOR_HOME="${HOME:-}" + +# Throwaway, not guessable: the key guards the core's whole admin API (see +# scripts/run-web-smoke.sh for why an ambient MCPPROXY_API_KEY is never used). +API_KEY="skills-sweep-$(node -e 'process.stdout.write(require("crypto").randomBytes(24).toString("hex"))')" +if [[ ${#API_KEY} -lt 32 ]]; then + echo "failed to generate a random API key" >&2 + exit 1 +fi + +# Every text file this script leaves behind goes through redact_file: the API +# key becomes *** and the local paths become placeholders. Set once OUT is known. +OUT_REAL="" +redact_file() { + [[ -f "$1" ]] || return 0 + SWEEP_REDACT_KEY="$API_KEY" SWEEP_REDACT_OUT="$OUT_REAL" SWEEP_REDACT_REPO="$REPO_ROOT" \ + SWEEP_REDACT_WORK="$WORK" SWEEP_REDACT_HOME="$OPERATOR_HOME" node -e ' +const fs = require("fs"), f = process.argv[1], e = process.env +let t = fs.readFileSync(f, "utf8") +const key = e.SWEEP_REDACT_KEY +if (key) for (const k of [key, encodeURIComponent(key)]) t = t.split(k).join("***") +const paths = [[e.SWEEP_REDACT_OUT, ""], [e.SWEEP_REDACT_WORK, ""], [e.SWEEP_REDACT_REPO, ""], [e.SWEEP_REDACT_HOME, "~"]] + .filter(([p]) => p && p.length > 1).sort((a, b) => b[0].length - a[0].length) +for (const [p, r] of paths) t = t.split(p).join(r) +fs.writeFileSync(f, t)' "$1" +} cleanup() { local pid @@ -102,26 +155,275 @@ cleanup() { wait "$pid" >/dev/null 2>&1 || true fi done - cp "$CORE_LOG" "$OUT/core.log" 2>/dev/null || true - cp "$FIXTURE_LOG" "$OUT/fixture.log" 2>/dev/null || true + if [[ -n "$OUT_REAL" ]]; then + cp "$CORE_LOG" "$OUT_REAL/core.log" 2>/dev/null && redact_file "$OUT_REAL/core.log" + cp "$FIXTURE_LOG" "$OUT_REAL/fixture.log" 2>/dev/null && redact_file "$OUT_REAL/fixture.log" + fi rm -rf "$WORK" } trap cleanup EXIT +# Refuses a data dir that is, or is inside, the operator's ~/.mcpproxy (by the +# path as written and by its physical path, so a symlink does not get past it). +data_dir_allowed() { + local dir="$1" real="$1" home_real="" bad + [[ -n "$OPERATOR_HOME" ]] || return 0 + [[ -d "$dir" ]] && real=$(cd "$dir" && pwd -P) + [[ -d "$OPERATOR_HOME" ]] && home_real=$(cd "$OPERATOR_HOME" && pwd -P) + for bad in "$OPERATOR_HOME/.mcpproxy" ${home_real:+"$home_real/.mcpproxy"}; do + case "$dir/" in "$bad/"*) return 1 ;; esac + case "$real/" in "$bad/"*) return 1 ;; esac + done + return 0 +} + +# Writes the throwaway config. Every value is generated here (ports, a temp +# path, a hex key), so the heredoc cannot be broken by quoting; the temp path +# is checked to be sure. $1: listen address, $2: the fixture's /mcp URL or "". +write_config() { + local listen="$1" fixture_mcp="$2" servers="[]" + case "$DATA_DIR" in + *'"'* | *\\* | *$'\n'*) echo "scratch dir path cannot be embedded in JSON: $DATA_DIR" >&2; exit 1 ;; + esac + if [[ -n "$fixture_mcp" ]]; then + servers=$(printf '[\n {\n "name": "%s",\n "url": "%s",\n "protocol": "streamable-http",\n "enabled": true,\n "trust_mode": "manual"\n }\n ]' "$SERVER" "$fixture_mcp") + fi + cat >"$CONFIG_PATH" <&2 + exit 1 + fi + env -u MCPPROXY_DATA_DIR -u MCPPROXY_DATA \ + HOME="$CORE_HOME" HEADLESS=1 DO_NOT_TRACK=1 MCPPROXY_TELEMETRY=false MCPPROXY_API_KEY="$API_KEY" \ + "$CORE_BIN" serve --config "$CONFIG_PATH" --data-dir "$DATA_DIR" --listen "$listen" >"$CORE_LOG" 2>&1 & + CORE_PID=$! +} + +# Waits for the core's REST API; $1: base URL. +wait_core() { + local base="$1" attempt code + for attempt in $(seq 1 60); do + code=$(curl -s --connect-timeout 2 --max-time 5 -o /dev/null -w '%{http_code}' -H "X-API-Key: ${API_KEY}" "$base/api/v1/servers" || true) + [[ "$code" == "200" ]] && return 0 + if ! kill -0 "$CORE_PID" >/dev/null 2>&1 || [[ $attempt -eq 60 ]]; then + echo "core did not become ready at $base" >&2 + cat "$CORE_LOG" >&2 + exit 1 + fi + sleep 1 + done +} + +# The core opened its database in the scratch dir, and only there. +check_core_data_dir() { + if [[ ! -f "$DATA_DIR/config.db" ]]; then + echo "the core did not open its database in the scratch data dir ($DATA_DIR/config.db is missing)" >&2 + exit 1 + fi +} + # A port the kernel just handed out and released. A race with another process # is possible but harmless: the start below fails fast and says so. free_port() { node -e 'const s=require("net").createServer();s.listen(0,"127.0.0.1",()=>{process.stdout.write(String(s.address().port));s.close()})' } -# Throwaway, not guessable: the key guards the core's whole admin API (see -# scripts/run-web-smoke.sh for why an ambient MCPPROXY_API_KEY is never used). -API_KEY="skills-sweep-$(node -e 'process.stdout.write(require("crypto").randomBytes(24).toString("hex"))')" -if [[ ${#API_KEY} -lt 32 ]]; then - echo "failed to generate a random API key" >&2 - exit 1 +# --- results writer ------------------------------------------------------------- +# write_results OUT COMMIT DIRTY FIXTURE_PORT PW_STATUS SERVER CORE_PORT FIXTURE_CMD... +# Writes OUT/skills-sweep-results.json from OUT/playwright-results.json and +# OUT/state/. A scenario's status and error are those of its FIRST failed +# attempt (a retry replays against changed state and would hide the original +# error). The fixture command is recorded as basename + args. The file is then +# redacted (API key, local paths). Exit status 0 only when everything passed. +write_results() { + local out="$1" + node - "$@" <<'NODE' +const fs = require('fs'), path = require('path') +const [out, commit, dirty, fixturePort, pwStatus, server, corePort, ...fixtureCmd] = process.argv.slice(2) +const problems = [] +const scenarios = [] +try { + const report = JSON.parse(fs.readFileSync(path.join(out, 'playwright-results.json'), 'utf8')) + const walk = (suite) => { + for (const spec of suite.specs || []) { + const results = (spec.tests || []).flatMap(t => t.results || []) + const last = results[results.length - 1] + const firstFailed = results.find(r => r.status !== 'passed' && r.status !== 'skipped') + const passed = spec.ok === true && !!last && last.status === 'passed' + const status = passed ? (firstFailed ? 'flaky' : 'passed') : (firstFailed || last || { status: 'not run' }).status + const errOf = r => r && (r.error || (r.errors || [])[0]) + const err = errOf(firstFailed) || (!passed ? errOf(last) : undefined) + scenarios.push({ title: spec.title, passed, status, attempts: results.length, + error: err ? String(err.message || err.value || '').slice(0, 2000) : undefined }) + } + for (const s of suite.suites || []) walk(s) + } + for (const s of report.suites || []) walk(s) +} catch (e) { problems.push(`no Playwright JSON report: ${e.message}`) } +if (scenarios.length === 0) problems.push('no scenario ran') +for (const s of scenarios) if (!s.passed) problems.push(`scenario failed: ${s.title} (${s.status})`) +const states = {} +for (const step of ['approve', 'approve-changed', 'block', 'unblock']) { + const file = path.join(out, 'state', `state-after-${step}.json`) + try { + const d = JSON.parse(fs.readFileSync(file, 'utf8')) + states[step] = { incarnation: d.incarnation, skills: (d.skills || []).map(s => ({ + path: s.path, status: s.status, blocked: s.blocked, available: s.available, + current_hash: s.current_hash, approved_hash: s.approved_hash })) } + } catch { problems.push(`missing state after ${step}`) } +} +const isDirty = dirty === 'true' +const result = { + // `git rev-parse HEAD` of the checkout the sweep ran from. + checked_commit: commit, + working_tree_dirty: isDirty, + // A dirty tree is not the commit: this file is pre-commit evidence only. + evidence: isDirty ? 'pre-commit' : 'commit', + checked: isDirty + ? `pre-commit evidence: a working tree with uncommitted changes on top of ${commit}; regenerate from a clean checkout before committing this file` + : commit, + generated_at: new Date().toISOString(), + fixture: { command: fixtureCmd.length ? [path.basename(fixtureCmd[0]), ...fixtureCmd.slice(1)] : [], port: Number(fixturePort) }, + core: { listen: `127.0.0.1:${corePort}`, server, enable_skills: true, trust_mode: 'manual' }, + playwright_exit_code: Number(pwStatus), + scenarios, + states, + passed: problems.length === 0 && Number(pwStatus) === 0, + problems, +} +fs.writeFileSync(path.join(out, 'skills-sweep-results.json'), JSON.stringify(result, null, 2) + '\n') +process.exit(result.passed ? 0 : 1) +NODE + local status=$? + redact_file "$out/skills-sweep-results.json" + return $status +} + +# --- self-test ------------------------------------------------------------------ +# run_self_test: no browser. Uses its own data dir and output dir, so a sweep +# that follows it (--self-test-first) starts from fresh state. +st_fail() { echo "self-test FAILED: $*" >&2; exit 1; } +run_self_test() { + local sweep_data_dir="$DATA_DIR" st_port d step st_status results enc_key st_out decoy_new decoy_legacy + DATA_DIR="$WORK/st-data" + mkdir -p "$DATA_DIR" + + # 1. The guard refuses the operator's ~/.mcpproxy and anything inside it. + [[ -n "$OPERATOR_HOME" ]] || st_fail "HOME is not set" + data_dir_allowed "$OPERATOR_HOME/.mcpproxy" && st_fail "a data dir of \$HOME/.mcpproxy was allowed" + data_dir_allowed "$OPERATOR_HOME/.mcpproxy/sub" && st_fail "a data dir under \$HOME/.mcpproxy was allowed" + data_dir_allowed "$DATA_DIR" || st_fail "the scratch data dir was refused" + echo "self-test: a data dir under \$HOME/.mcpproxy is refused; the scratch dir is allowed" + + # 2. An ambient MCPPROXY_DATA_DIR / MCPPROXY_DATA does not reach the core. + decoy_new="$WORK/decoy-data-dir" + decoy_legacy="$WORK/decoy-data-legacy" + mkdir -p "$decoy_new" "$decoy_legacy" + st_port=$(free_port) + write_config "127.0.0.1:${st_port}" "" + MCPPROXY_DATA_DIR="$decoy_new" MCPPROXY_DATA="$decoy_legacy" start_core "127.0.0.1:${st_port}" + wait_core "http://127.0.0.1:${st_port}" + check_core_data_dir + for d in "$decoy_new" "$decoy_legacy"; do + if [[ -n "$(ls -A "$d" 2>/dev/null)" ]]; then + st_fail "the core wrote into the ambient data dir $d: $(ls -A "$d")" + fi + done + kill "$CORE_PID" >/dev/null 2>&1 || true + wait "$CORE_PID" >/dev/null 2>&1 || true + CORE_PID="" + echo "self-test: with MCPPROXY_DATA_DIR and MCPPROXY_DATA set to decoys, the core opened its database in the scratch dir only" + + # 3. The results writer: first failed attempt, redaction, provenance. + st_out="$WORK/st-out" + OUT_REAL="$st_out" + mkdir -p "$st_out/state" + for step in approve approve-changed block unblock; do + printf '{"incarnation":1,"skills":[{"path":"plain","status":"approved","blocked":false,"available":true,"current_hash":"sk1-a","approved_hash":"sk1-a"}]}' >"$st_out/state/state-after-${step}.json" + done + enc_key=$(node -e 'process.stdout.write(encodeURIComponent(process.argv[1]))' "$API_KEY") + # shellcheck disable=SC2016 # the JS template literals are expanded by node + ST_OUT="$st_out" API_KEY="$API_KEY" ENC_KEY="$enc_key" REPO_ROOT="$REPO_ROOT" node -e ' +const fs = require("fs"), e = process.env +const report = { suites: [{ specs: [ + { title: "retried", ok: false, tests: [{ results: [ + { status: "failed", error: { message: `page.goto: net::ERR at http://127.0.0.1:1/ui?apikey=${e.ENC_KEY} key=${e.API_KEY} in ${e.REPO_ROOT}/e2e/x.spec.ts` } }, + { status: "failed", error: { message: "the retry replayed against changed state" } }] }] }, + { title: "fine", ok: true, tests: [{ results: [{ status: "passed" }] }] }, +] }] } +fs.writeFileSync(e.ST_OUT + "/playwright-results.json", JSON.stringify(report))' + set +e + write_results "$st_out" "0123456789abcdef0123456789abcdef01234567" true 4242 1 skillsfx 4343 "$WORK/bin/skillsfixture" -addr 127.0.0.1:4242 + st_status=$? + set -e + [[ $st_status -ne 0 ]] || st_fail "the results writer passed a failed run" + results="$st_out/skills-sweep-results.json" + grep -qF "$API_KEY" "$results" && st_fail "the API key is in the results file" + grep -qF "$enc_key" "$results" && st_fail "the URL-encoded API key is in the results file" + grep -qF "$WORK" "$results" && st_fail "a scratch path is in the results file" + grep -qF "$REPO_ROOT" "$results" && st_fail "the repo path is in the results file" + node -e ' +const r = JSON.parse(require("fs").readFileSync(process.argv[1], "utf8")) +const s = r.scenarios.find(x => x.title === "retried") +const fail = m => { console.error("self-test FAILED: " + m); process.exit(1) } +if (!s || s.passed || s.status !== "failed" || s.attempts !== 2) fail("retried scenario: " + JSON.stringify(s)) +if (!/apikey=\*\*\*/.test(s.error) || !/key=\*\*\*/.test(s.error)) fail("the key was not replaced by ***: " + s.error) +if (/changed state/.test(s.error)) fail("the retry error was recorded instead of the first failure") +if (!s.error.includes("/e2e/x.spec.ts")) fail("the repo path was not replaced: " + s.error) +if (JSON.stringify(r.fixture.command) !== JSON.stringify(["skillsfixture", "-addr", "127.0.0.1:4242"])) fail("fixture command: " + JSON.stringify(r.fixture.command)) +if (r.checked_commit !== "0123456789abcdef0123456789abcdef01234567" || r.working_tree_dirty !== true || r.evidence !== "pre-commit" || !/^pre-commit evidence/.test(r.checked)) fail("provenance: " + JSON.stringify([r.checked_commit, r.working_tree_dirty, r.evidence, r.checked])) +' "$results" + echo "self-test: the results writer records the first failed attempt, redacts the key and local paths, and labels a dirty tree pre-commit evidence" + echo "self-test passed" + DATA_DIR="$sweep_data_dir" + OUT_REAL="" +} + +if [[ $SELF_TEST -eq 1 ]]; then + CORE_BIN="${MCPPROXY_BINARY_PATH:-}" + if [[ -z "$CORE_BIN" ]]; then + required go + # The data-dir proof needs no frontend: a plain build of the core. + CORE_BIN="$WORK/bin/mcpproxy" + (cd "$REPO_ROOT" && go build -o "$CORE_BIN" ./cmd/mcpproxy) + fi + run_self_test + exit 0 fi +mkdir -p "$OUT" +OUT=$(cd "$OUT" && pwd -P) +OUT_REAL="$OUT" +if [[ -n "$REPORT_HTML" ]]; then + mkdir -p "$(dirname "$REPORT_HTML")" + REPORT_HTML="$(cd "$(dirname "$REPORT_HTML")" && pwd -P)/$(basename "$REPORT_HTML")" +fi +rm -rf "$OUT/screenshots" "$OUT/state" "$OUT/playwright-results.json" "$OUT/skills-sweep-results.json" +mkdir -p "$OUT/screenshots" "$OUT/state" + # --- binaries --------------------------------------------------------------- CORE_BIN="${MCPPROXY_BINARY_PATH:-}" if [[ -z "$CORE_BIN" ]]; then @@ -150,6 +452,10 @@ for b in "$CORE_BIN" "$FIXTURE_BIN"; do exit 1 fi done +if [[ $SELF_TEST_FIRST -eq 1 ]]; then + run_self_test +fi +OUT_REAL="$OUT" # --- fixture ---------------------------------------------------------------- FIXTURE_PORT=$(free_port) @@ -176,50 +482,12 @@ echo "skillsfixture ready at $FIXTURE_URL" CORE_PORT=$(free_port) LISTEN="127.0.0.1:${CORE_PORT}" BASE_URL="http://${LISTEN}" -# Every value below is generated here (ports, a temp path, a hex key), so the -# heredoc cannot be broken by quoting; the temp path is checked to be sure. -case "$DATA_DIR" in - *'"'* | *\\* | *$'\n'*) echo "scratch dir path cannot be embedded in JSON: $DATA_DIR" >&2; exit 1 ;; -esac -cat >"$CONFIG_PATH" <"$CORE_LOG" 2>&1 & -CORE_PID=$! +write_config "$LISTEN" "${FIXTURE_URL}/mcp" +start_core "$LISTEN" H=(-H "X-API-Key: ${API_KEY}") -for attempt in $(seq 1 60); do - code=$(curl -s --connect-timeout 2 --max-time 5 -o /dev/null -w '%{http_code}' "${H[@]}" "$BASE_URL/api/v1/servers" || true) - [[ "$code" == "200" ]] && break - if ! kill -0 "$CORE_PID" >/dev/null 2>&1 || [[ $attempt -eq 60 ]]; then - echo "core did not become ready at $BASE_URL" >&2 - cat "$CORE_LOG" >&2 - exit 1 - fi - sleep 1 -done -echo "core ready at $BASE_URL" +wait_core "$BASE_URL" +check_core_data_dir +echo "core ready at $BASE_URL (data dir: the scratch dir)" # Approve the (quarantined) server, then wait until a refresh reads the three # skills: that needs the upstream connected and the extension announced. @@ -273,6 +541,9 @@ else "$PLAYWRIGHT_BIN" install chromium fi +# The key reaches the spec through the environment only: it sets it in the Web +# UI's localStorage, never in a page URL, and records no traces (the Web UI's +# SSE URL carries it). Playwright's own output stays in the scratch dir. set +e ( cd "$SWEEP_DIR" || exit 1 @@ -284,82 +555,43 @@ set +e SWEEP_SCREENSHOT_DIR="$OUT/screenshots" \ SWEEP_REPORT_DIR="$OUT/playwright-report" \ PLAYWRIGHT_JSON_OUTPUT_NAME="$OUT/playwright-results.json" \ - "$PLAYWRIGHT_BIN" test skills-tab.spec.ts --reporter=list,json + "$PLAYWRIGHT_BIN" test skills-tab.spec.ts --reporter=list,json --output "$WORK/test-results" ) PLAYWRIGHT_STATUS=$? set -e +redact_file "$OUT/playwright-results.json" +for f in "$OUT"/state/*.json; do redact_file "$f"; done # --- results file ------------------------------------------------------------- COMMIT=$(git -C "$REPO_ROOT" rev-parse HEAD) DIRTY=false if [[ -n "$(git -C "$REPO_ROOT" status --porcelain)" ]]; then DIRTY=true; fi set +e -node - "$OUT" "$COMMIT" "$DIRTY" "$FIXTURE_PORT" "$PLAYWRIGHT_STATUS" "$SERVER" "$CORE_PORT" "${FIXTURE_CMD[@]}" <<'NODE' -const fs = require('fs'), path = require('path') -const [out, commit, dirty, fixturePort, pwStatus, server, corePort, ...fixtureCmd] = process.argv.slice(2) -const problems = [] -const scenarios = [] -try { - const report = JSON.parse(fs.readFileSync(path.join(out, 'playwright-results.json'), 'utf8')) - const walk = (suite) => { - for (const spec of suite.specs || []) { - const results = (spec.tests || []).flatMap(t => t.results || []) - const last = results[results.length - 1] - const status = last ? last.status : 'not run' - scenarios.push({ title: spec.title, passed: spec.ok === true && status === 'passed', status, - error: last && last.error ? String(last.error.message || '').slice(0, 2000) : undefined }) - } - for (const s of suite.suites || []) walk(s) - } - for (const s of report.suites || []) walk(s) -} catch (e) { problems.push(`no Playwright JSON report: ${e.message}`) } -if (scenarios.length === 0) problems.push('no scenario ran') -for (const s of scenarios) if (!s.passed) problems.push(`scenario failed: ${s.title} (${s.status})`) -const states = {} -for (const step of ['approve', 'approve-changed', 'block', 'unblock']) { - const file = path.join(out, 'state', `state-after-${step}.json`) - try { - const d = JSON.parse(fs.readFileSync(file, 'utf8')) - states[step] = { incarnation: d.incarnation, skills: (d.skills || []).map(s => ({ - path: s.path, status: s.status, blocked: s.blocked, available: s.available, - current_hash: s.current_hash, approved_hash: s.approved_hash })) } - } catch { problems.push(`missing state after ${step}`) } -} -const result = { - checked_commit: commit, - working_tree_dirty: dirty === 'true', - checked: dirty === 'true' ? `working tree on top of ${commit}` : commit, - generated_at: new Date().toISOString(), - fixture: { command: fixtureCmd, port: Number(fixturePort) }, - core: { listen: `127.0.0.1:${corePort}`, server, enable_skills: true, trust_mode: 'manual' }, - playwright_exit_code: Number(pwStatus), - scenarios, - states, - passed: problems.length === 0 && Number(pwStatus) === 0, - problems, -} -fs.writeFileSync(path.join(out, 'skills-sweep-results.json'), JSON.stringify(result, null, 2) + '\n') -process.exit(result.passed ? 0 : 1) -NODE +write_results "$OUT" "$COMMIT" "$DIRTY" "$FIXTURE_PORT" "$PLAYWRIGHT_STATUS" "$SERVER" "$CORE_PORT" "${FIXTURE_CMD[@]}" RESULT_STATUS=$? set -e if [[ -n "$REPORT_HTML" ]]; then - node - "$OUT" "$REPORT_HTML" <<'NODE' + node - "$OUT" "$REPORT_HTML" "$SCREENSHOTS" <<'NODE' const fs = require('fs'), path = require('path') -const [out, dest] = process.argv.slice(2) +const [out, dest, screenshots] = process.argv.slice(2) +const withShots = screenshots === '1' const r = JSON.parse(fs.readFileSync(path.join(out, 'skills-sweep-results.json'), 'utf8')) const esc = s => String(s).replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]) const img = name => { + if (!withShots) return '' const f = path.join(out, 'screenshots', `skills-tab-${name}.png`) return fs.existsSync(f) ? `${esc(name)}` : '' } +const shotNote = shots => (!withShots && shots.length) + ? `

Screenshots (not embedded in this copy): ${shots.map(s => `screenshots/skills-tab-${esc(s)}.png`).join(', ')}

` : '' // One section per scenario, in spec order, with what it proves and its screenshots. const about = [ ['Tab and list', 'The Skills tab is offered on a server with enable_skills on and a skills-capable upstream (cmd/skillsfixture, manual trust). The three skills show as Awaiting review and Not offered.', ['01-list']], ['Viewer and paging', 'SKILL.md opens in the text viewer (inert text). A 150 KiB file is read part by part: each Load more waits for its content response and the rendered text, every part carries the digest listed on screen, and the last part has no next_offset. A binary file (logo.bin) is listed as binary, not shown, with no View button.', ['02-viewer', '03-paged']], ['Approve', 'Approve sends the current_hash and incarnation of the version the reviewer opened; the chip turns Approved.', ['04-approved']], - ['Changed while open, re-open, diff', 'A mutate without the X-Skills-Fixture header is refused (403). The upstream bytes change while the skill is open; after Refresh the chip says Changed and the open review says it changed while you were reviewing it. Re-opening shows the file-set diff (SKILL.md changed) and the line diff with the added line; approving binds the new hash.', ['05a-stale', '05-changed-diff']], + ['Changed while open, re-open, diff', 'A mutate without the X-Skills-Fixture header is refused (403). The approved skill plain changes upstream while it is open; after Refresh the chip says Changed and the open review says it changed while you were reviewing it (the review shows the approved version, so it offers no Approve). Re-opening shows the file-set diff (SKILL.md changed) and the line diff with the added line; approving binds the new hash.', ['05a-stale', '05-changed-diff']], + ['Pending skill changed while open', 'The pending skill with-files changes upstream while it is open; after Refresh the review is marked stale and its Approve button stays on screen but disabled, until the new version is re-opened.', ['05b-pending-stale']], ['Block and unblock', 'Block marks the skill Blocked and removes Approve; Unblock returns it to Awaiting review.', ['06-blocked']], ['Reload', 'The tab survives a reload through ?tab=skills, and no uncaught page error was thrown in any scenario.', []], ] @@ -373,19 +605,22 @@ const passed = r.scenarios.filter(s => s.passed).length const sections = r.scenarios.map((s, i) => { const [title, text, shots] = about[i] || [s.title, '', []] const badge = s.passed ? 'PASS' : 'FAIL' - return `
${i + 1}. ${esc(title)} ${badge}

${esc(s.title)}

${esc(text)}

${s.error ? `
${esc(s.error)}
` : ''}${shots.map(img).join('')}
` + return `
${i + 1}. ${esc(title)} ${badge}

${esc(s.title)}

${esc(text)}

${s.error ? `
${esc(s.error)}
` : ''}${shots.map(img).join('')}${shotNote(shots)}
` }).join('\n') +const provenance = r.working_tree_dirty + ? `
Pre-commit evidence. The working tree had uncommitted changes on top of ${esc(r.checked_commit)}; this report does not describe that commit. Regenerate it from a clean checkout before committing it.
` + : '' const html = `Spec 125 Skills tab verification

Spec 125: Skills tab (PR-4a) Playwright verification

-
${passed} of ${r.scenarios.length} scenarios passed, ${esc(r.generated_at.slice(0, 10))}, produced by scripts/run-skills-tab-sweep.sh from ${esc(r.checked)}.
-A throwaway core (${esc(r.core.listen)}, scratch data dir, enable_skills: true, generated API key) served the embedded frontend; the upstream ${esc(r.core.server)} (trust_mode: manual) was ${esc([path.basename(r.fixture.command[0]), ...r.fixture.command.slice(1)].join(' '))} on port ${r.fixture.port}.
-Spec: e2e/web-ui-sweep/skills-tab.spec.ts. Results file: skills-sweep-results.json. Repeat: ./scripts/run-skills-tab-sweep.sh --report-html specs/125-skills-over-mcp/verification/report.html.
+${provenance}
${passed} of ${r.scenarios.length} scenarios passed, ${esc(r.generated_at.slice(0, 10))}, produced by scripts/run-skills-tab-sweep.sh from commit ${esc(r.checked_commit)} (working tree ${r.working_tree_dirty ? 'dirty' : 'clean'}).
+A throwaway core (${esc(r.core.listen)}, scratch data dir, enable_skills: true, generated API key) served the embedded frontend; the upstream ${esc(r.core.server)} (trust_mode: manual) was ${esc(r.fixture.command.join(' '))} on port ${r.fixture.port}.
+Spec: e2e/web-ui-sweep/skills-tab.spec.ts. Results file: skills-sweep-results.json. Repeat: ./scripts/run-skills-tab-sweep.sh --report-html specs/125-skills-over-mcp/verification/report.html --no-screenshots.
${sections}
Skill records read back from GET /api/v1/servers/${esc(r.core.server)}/skills

After approve

${stateTable('approve')}

After approving the change

${stateTable('approve-changed')}

After block

${stateTable('block')}

After unblock

${stateTable('unblock')}
@@ -393,7 +628,10 @@ ${sections} ` fs.writeFileSync(dest, html) NODE - echo "HTML report written to $REPORT_HTML" + # Every string in the report comes from the redacted results file; the copy + # without screenshots (pure text) is redacted once more as a whole. + [[ $SCREENSHOTS -eq 0 ]] && redact_file "$REPORT_HTML" + echo "HTML report written to $REPORT_HTML$([[ $SCREENSHOTS -eq 0 ]] && echo ' (no embedded screenshots)')" fi echo "results: $OUT/skills-sweep-results.json" diff --git a/specs/125-skills-over-mcp/contracts/rest-api.md b/specs/125-skills-over-mcp/contracts/rest-api.md index 64331cc05..841be8cae 100644 --- a/specs/125-skills-over-mcp/contracts/rest-api.md +++ b/specs/125-skills-over-mcp/contracts/rest-api.md @@ -52,7 +52,7 @@ Admin only until PR-3; afterwards a scoped caller may read the approved copy of ## `POST /servers/{id}/skills/refresh` -Admin only. Starts a refresh and returns the listing once applied, or 409 `refresh_in_progress` joined to the running one. 409 `skills_not_supported` when the server does not announce the extension. +Admin only. Starts a refresh and returns the listing once applied. Refresh is single-flight: a caller that arrives while a refresh of the server is running joins it and gets its result (no error). 409 `refresh_superseded` when the server reconnected during the refresh (its skills are read again after the reconnect), 409 `skills_disabled` when `enable_skills` is off or was turned off during the refresh, 409 `skills_not_supported` when the server does not announce the extension, 409 `server_replaced` when the server was removed or replaced while its skills were read. ## `POST /servers/{id}/skills/approve` (PR-2) From 1961d592b49949b701f88392585407c004b7e0f8 Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Wed, 18 Nov 2026 15:41:57 +0200 Subject: [PATCH 03/18] fix(skills): review round 3 for the Skills tab and its sweep - skills.changed reaches the tab: consumers read the SSE frame's payload (tests use the real frame through the store); a new e2e step shows an open review going stale from a REST-triggered refresh alone. - SkillsPanel load, refresh and write never reject unhandled and never leave a spinner on. - Overlapping visibility checks are ordered by request sequence. - An unchanged reload keeps the open viewer; the copy toggle offers only text copies; the line diff collapses unchanged runs and caps its output. - Sweep script: the core and fixture start with a clean environment, so no inherited MCPPROXY_* (audit log, data dir, certs, bundle path) reaches them; the self-test proves it with decoys. DEBUG=1 no longer uses xtrace and never prints the key. - web-ui-sweep job timeout 20 -> 35 minutes for both sweeps. Related #1895 --- .github/workflows/release-qa-gate.yml | 12 +- docs/development/release-gate.md | 8 +- docs/development/web-ui-verification.md | 4 +- e2e/web-ui-sweep/skills-tab.spec.ts | 31 ++++- .../src/components/skills/SkillDetail.vue | 15 ++- .../src/components/skills/SkillsPanel.vue | 33 ++++-- frontend/src/utils/skills.ts | 47 ++++++-- frontend/src/views/ServerDetail.vue | 30 +++-- frontend/tests/unit/fixtures/skills125.ts | 23 ++++ .../unit/server-detail-skills-tab.spec.ts | 43 ++++++- frontend/tests/unit/skill-detail.spec.ts | 34 ++++++ frontend/tests/unit/skills-panel.spec.ts | 84 +++++++++++-- .../tests/unit/skills-sse-redispatch.spec.ts | 10 +- frontend/tests/unit/skills-utils.spec.ts | 33 +++++- scripts/run-skills-tab-sweep.sh | 111 ++++++++++++++---- 15 files changed, 435 insertions(+), 83 deletions(-) diff --git a/.github/workflows/release-qa-gate.yml b/.github/workflows/release-qa-gate.yml index d5355ded3..bda7c2179 100644 --- a/.github/workflows/release-qa-gate.yml +++ b/.github/workflows/release-qa-gate.yml @@ -532,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 @@ -573,8 +578,9 @@ jobs: # 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 - # an ambient MCPPROXY_DATA_DIR never reaches the core and that the results - # writer redacts the API key. + # 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: diff --git a/docs/development/release-gate.md b/docs/development/release-gate.md index 28d6a2eeb..a97964b71 100644 --- a/docs/development/release-gate.md +++ b/docs/development/release-gate.md @@ -149,9 +149,11 @@ page disagree): 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 an ambient `MCPPROXY_DATA_DIR` / - `MCPPROXY_DATA` never reaches the throwaway core and that the results writer - redacts the API key and local paths. The step runs even when the + 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 diff --git a/docs/development/web-ui-verification.md b/docs/development/web-ui-verification.md index d4b3405ff..c43ed6e73 100644 --- a/docs/development/web-ui-verification.md +++ b/docs/development/web-ui-verification.md @@ -37,10 +37,10 @@ Alongside it, [`e2e/web-ui-sweep/visual-a11y-sweep.spec.ts`](https://github.com/ ```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 data-dir and redaction checks +./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 runs with `MCPPROXY_DATA_DIR` and the legacy `MCPPROXY_DATA` removed from its environment, since either would override the config's `data_dir`, with `--data-dir` naming the scratch dir, `HOME` pointing at a scratch home, and a data dir under `$HOME/.mcpproxy` refused; `--self-test` proves an ambient `MCPPROXY_DATA_DIR` does not reach the core), `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), 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 has the API key replaced by `***` and local paths by ``, ``, `` or `~`. 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. +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 has the API key replaced by `***` and local paths by ``, ``, `` or `~`. 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. diff --git a/e2e/web-ui-sweep/skills-tab.spec.ts b/e2e/web-ui-sweep/skills-tab.spec.ts index 2fddf1f79..0caca8ec5 100644 --- a/e2e/web-ui-sweep/skills-tab.spec.ts +++ b/e2e/web-ui-sweep/skills-tab.spec.ts @@ -14,8 +14,11 @@ // 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. block and unblock; -// 7. no uncaught page error anywhere. +// 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): @@ -225,6 +228,30 @@ test('a pending skill changed while open is stale, with Approve disabled until r 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() diff --git a/frontend/src/components/skills/SkillDetail.vue b/frontend/src/components/skills/SkillDetail.vue index 54cd3414a..614a02ff2 100644 --- a/frontend/src/components/skills/SkillDetail.vue +++ b/frontend/src/components/skills/SkillDetail.vue @@ -40,7 +40,7 @@
- +
@@ -124,7 +124,7 @@ const chipClass = computed(() => `badge-${({ error: 'error', warning: 'warning', const canApprove = computed(() => !props.skill.blocked && (props.skill.status === 'pending' || props.skill.status === 'changed')) const diffRows = computed(() => props.skill.approved_files ? skillFileDiff(props.skill.approved_files, props.skill.files) : null) const diffBadge = { added: 'badge-success', removed: 'badge-error', changed: 'badge-warning', same: 'badge-ghost' } as const -const lineClass = { same: '', add: 'bg-success/20', del: 'bg-error/20' } as const +const lineClass = { same: '', add: 'bg-success/20', del: 'bg-error/20', skip: 'text-base-content/50 italic' } as const function shortDigest(d: string) { return d.replace(/^sha256:/, '').slice(0, 12) } function formatSkillSize(n: number) { @@ -143,7 +143,11 @@ const lineDiffState = ref(null) // A reload that moved the skill's content, or a different skill, drops every // fetched text: it described a copy that is no longer the one on screen. let generation = 0 -watch(() => [props.serverName, props.skill.path, props.skill.current_hash, props.skill.approved_hash], () => { +// Watched as one string: a getter returning a fresh array would fire on every +// new `skill` object, even when the reload moved nothing (e.g. a skills.changed +// for another skill, or a block), and drop the pages the reviewer loaded. +const contentKey = computed(() => JSON.stringify([props.serverName, props.skill.path, props.skill.current_hash, props.skill.approved_hash])) +watch(contentKey, () => { generation++ viewer.value = null lineDiffState.value = null @@ -155,7 +159,10 @@ async function fetchPart(file: string, copy: SkillCopy, offset: number) { return { res, stale: gen !== generation } } -function hasCopy(file: string, copy: SkillCopy) { return skillFileDigest(props.skill, file, copy) !== undefined } +function hasCopy(file: string, copy: SkillCopy) { + const list = copy === 'approved' ? props.skill.approved_files : props.skill.files + return list?.some(f => f.path === file && f.text === true) ?? false +} async function viewFile(file: string, copy: SkillCopy) { // reactive() so the identity checks below compare the proxy the template sees. diff --git a/frontend/src/components/skills/SkillsPanel.vue b/frontend/src/components/skills/SkillsPanel.vue index d63b51f8e..0ac8180c8 100644 --- a/frontend/src/components/skills/SkillsPanel.vue +++ b/frontend/src/components/skills/SkillsPanel.vue @@ -25,6 +25,8 @@ List truncated

+ +

@@ -139,21 +141,36 @@ function apply(data: SkillsListResponse) { else r.stale = true } +// A thrown request (a network error) is an answer like any other failure: it +// is turned into {success:false} so the spinner and the buttons are reset and +// the error is shown, but only while the request is still the current one. +type Answer = { success: boolean; data?: T; error?: string; errorCode?: string } +async function settle(run: () => Promise>): Promise> { + try { + return await run() + } catch (e) { + return { success: false, error: e instanceof Error && e.message ? e.message : 'The request failed' } + } +} + async function load() { const server = props.serverName, v = visit, seq = ++requestSeq loading.value = true - const res = await api.getServerSkills(server) + const res = await settle(() => api.getServerSkills(server)) if (!isCurrent(server, v, seq)) return loading.value = false if (res.success && res.data) apply(res.data) else error.value = res.error || 'Could not load skills' } +// One refresh in flight per visit: a late answer of an earlier one never +// resets the button of a newer one. +let refreshSeq = 0 async function refresh() { - const server = props.serverName, v = visit + const server = props.serverName, v = visit, mine = ++refreshSeq refreshing.value = true - const res = await api.refreshServerSkills(server) - if (!isCurrent(server, v)) return + const res = await settle(() => api.refreshServerSkills(server)) + if (!isCurrent(server, v) || mine !== refreshSeq) return refreshing.value = false if (res.success && res.data) { requestSeq++; apply(res.data); return } // A failed refresh (refresh_superseded, skills_not_supported, skills_disabled, @@ -171,7 +188,7 @@ async function refresh() { async function write(run: () => Promise<{ success: boolean; error?: string; errorCode?: string }>, done: string) { const server = props.serverName, v = visit, token = review.value?.token busy.value = true - const res = await run() + const res = await settle(run) if (!isCurrent(server, v)) return busy.value = false if (review.value?.token === token) notice.value = res.success ? done : skillErrorNotice(res.errorCode, res.error) @@ -200,9 +217,11 @@ function setBlocked(block: boolean) { ) } +// The store re-dispatches the core's frame whole ({payload: {server, counts}, +// timestamp}), like every other runtime event. function onSkillsChanged(e: Event) { - const detail = (e as CustomEvent).detail as { server?: string } | null - if (detail?.server === props.serverName) void load() + const detail = (e as CustomEvent).detail as { payload?: { server?: string } } | null + if (detail?.payload?.server === props.serverName) void load() } watch(() => props.serverName, () => { diff --git a/frontend/src/utils/skills.ts b/frontend/src/utils/skills.ts index f2710df84..5abde1699 100644 --- a/frontend/src/utils/skills.ts +++ b/frontend/src/utils/skills.ts @@ -37,18 +37,26 @@ export function skillFileDiff(approved: SkillFileInfo[] | undefined, current: Sk return rows.sort((x, y) => (x.path < y.path ? -1 : x.path > y.path ? 1 : 0)) } -export interface LineOp { op: 'same' | 'add' | 'del'; text: string } +/** `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, in which case the - * result is tooLarge with no ops. + * 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): LineDiffResult { +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++ @@ -56,6 +64,8 @@ export function lineDiff(a: string, b: string, maxCells = LINE_DIFF_MAX_CELLS): 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) @@ -64,16 +74,35 @@ export function lineDiff(a: string, b: string, maxCells = LINE_DIFF_MAX_CELLS): 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[] = x.slice(0, head).map(text => ({ op: 'same', text })) + 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]) { ops.push({ op: 'same', text: mx[i] }); i++; j++ } - else if (t[(i + 1) * w + j] >= t[i * w + j + 1]) ops.push({ op: 'del', text: mx[i++] }) - else ops.push({ op: 'add', text: my[j++] }) + 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++] }) - for (const text of x.slice(x.length - tail)) ops.push({ op: 'same', text }) + if (changed) unchanged(x.length - tail, x.length, false, true) + if (ops.length > maxOps) return { tooLarge: true, ops: [] } return { tooLarge: false, ops } } diff --git a/frontend/src/views/ServerDetail.vue b/frontend/src/views/ServerDetail.vue index 4d0eb2255..153170942 100644 --- a/frontend/src/views/ServerDetail.vue +++ b/frontend/src/views/ServerDetail.vue @@ -1700,7 +1700,12 @@ const isTenant = computed(() => useAuthStore().principalKind === 'tenant') const skillsTabVisible = ref(false) // False while the check for the server on screen is in flight. const skillsTabChecked = ref(false) -let skillsCheckGeneration = 0 +// Every check takes a sequence number. A first check (reset) supersedes every +// earlier one; a background re-check's answer is applied only when it is newer +// than the last applied answer, so overlapping re-checks that return in reverse +// order never let an older answer replace a newer one. +let skillsCheckSeq = 0 +let skillsCheckFloor = 0 // answers with a sequence <= this are dropped // A Skills tab that is not offered (feature off, server without skills, a // failed check, a tenant) is never left open: it falls back to Tools, and the // activeTab watch below writes ?tab=tools like any other tab change. @@ -1715,13 +1720,12 @@ function leaveSkillsTabIfNotOffered() { else if (route.query.tab === 'skills') void router.replace({ query: { ...route.query, tab: 'tools' } }) } async function checkSkillsTab(reset = true) { - // A first check (reset) supersedes every earlier one. A background re-check - // (reset=false, after skills.changed) takes the generation only when it has - // a successful answer, so a failed one never drops a first check still in - // flight and never changes the tab. - const gen = reset ? ++skillsCheckGeneration : skillsCheckGeneration + // A failed background re-check (reset=false, after skills.changed) never + // drops a first check still in flight and never changes the tab. + const seq = ++skillsCheckSeq const name = props.serverName if (reset) { + skillsCheckFloor = seq - 1 skillsTabVisible.value = false skillsTabChecked.value = false } @@ -1741,14 +1745,13 @@ async function checkSkillsTab(reset = true) { } catch { // The tab is optional; no answer means no tab (on a first check). } - if (gen !== skillsCheckGeneration || name !== props.serverName) return + if (seq <= skillsCheckFloor || name !== props.serverName) return // A failed background re-check (a 409 server_replaced right after the // reviewer's own write, a 500, a network error) leaves the tab as it is: it // must not unmount the review that is open. - if (!reset) { - if (!answered) return - ++skillsCheckGeneration - } + if (!reset && !answered) return + // Applied: every answer to an older request is now out of date. + skillsCheckFloor = seq skillsTabVisible.value = visible skillsTabChecked.value = true leaveSkillsTabIfNotOffered() @@ -4181,9 +4184,10 @@ watch(logTail, () => { }) // Spec 125: a skills change on this server can turn the tab on or off. +// The store re-dispatches the core's frame whole ({payload: {server, counts}, timestamp}). function handleSkillsChangedEvent(e: Event) { - const detail = (e as CustomEvent).detail as { server?: string } | null - if (detail?.server === props.serverName) void checkSkillsTab(false) + const detail = (e as CustomEvent).detail as { payload?: { server?: string } } | null + if (detail?.payload?.server === props.serverName) void checkSkillsTab(false) } // Load data on mount diff --git a/frontend/tests/unit/fixtures/skills125.ts b/frontend/tests/unit/fixtures/skills125.ts index 75d208b27..b1b338af5 100644 --- a/frontend/tests/unit/fixtures/skills125.ts +++ b/frontend/tests/unit/fixtures/skills125.ts @@ -17,3 +17,26 @@ export const makeListing = (skills: SkillEntry[], over: Partial(data: T) => ({ success: true, data }) + +/** + * Connects the real system store to a fake EventSource and returns a function + * that delivers a skills.changed frame exactly as the core writes it + * ({"payload": {server, counts}, "timestamp": n}, internal/httpapi/server.go) + * through the store's own re-dispatch to `mcpproxy:skills-changed`. Call it with + * a Pinia active and the spec's mocked api object (it sets createEventSource). + */ +export async function connectSkillsSSE(apiMock: object): Promise<(server: string, counts?: Record) => void> { + const { vi } = await import('vitest') + const { useSystemStore } = await import('@/stores/system') + const g = globalThis as any + if (!g.EventSource) g.EventSource = { CONNECTING: 0, OPEN: 1, CLOSED: 2 } + const listeners: Record void> = {} + const a = apiMock as Record + a.createEventSource = vi.fn(() => ({ + onopen: null, onmessage: null, onerror: null, readyState: 1, close: vi.fn(), + addEventListener: (type: string, cb: (ev: { data: string }) => void) => { listeners[type] = cb }, + })) + if (typeof a.hasAPIKey !== 'function') a.hasAPIKey = vi.fn(() => true) + useSystemStore().connectEventSource() + return (server, counts = {}) => listeners['skills.changed']({ data: JSON.stringify({ payload: { server, counts }, timestamp: 1763300000 }) }) +} diff --git a/frontend/tests/unit/server-detail-skills-tab.spec.ts b/frontend/tests/unit/server-detail-skills-tab.spec.ts index 750f8c74a..b316ce1cd 100644 --- a/frontend/tests/unit/server-detail-skills-tab.spec.ts +++ b/frontend/tests/unit/server-detail-skills-tab.spec.ts @@ -7,7 +7,7 @@ import { createPinia, setActivePinia } from 'pinia' import { createRouter, createWebHistory } from 'vue-router' import { useAuthStore } from '@/stores/auth' import api from '@/services/api' -import { makeListing, makeSkill } from './fixtures/skills125' +import { connectSkillsSSE, makeListing, makeSkill } from './fixtures/skills125' const ok = (data: T) => Promise.resolve({ success: true, data }) @@ -34,6 +34,8 @@ vi.mock('@/services/api', () => { } } }) +let emitSkillsChanged: (server: string) => void = () => { throw new Error('not connected') } + async function mountServerDetail(path: string, tenant = false) { const pinia = createPinia() setActivePinia(pinia) @@ -51,6 +53,8 @@ async function mountServerDetail(path: string, tenant = false) { await router.isReady() const wrapper = mount(ServerDetail, { props: { serverName: 'alpha' }, global: { plugins: [pinia, router] } }) await flushPromises(); await flushPromises() + // Round-3 finding 1: skills.changed reaches the view through the real store's re-dispatch of the core's frame. + emitSkillsChanged = await connectSkillsSSE(api) return { wrapper, router } } @@ -157,7 +161,7 @@ describe('ServerDetail Skills tab (Spec 125)', () => { const { wrapper, router } = await mountServerDetail('/servers/alpha?tab=skills') expect(wrapper.find('[data-test="skills-panel"]').exists()).toBe(true) ;(api.getServerSkills as any).mockResolvedValue({ success: true, data: makeListing([], { enabled: false }) }) - window.dispatchEvent(new CustomEvent('mcpproxy:skills-changed', { detail: { server: 'alpha' } })) + emitSkillsChanged('alpha') await flushPromises(); await flushPromises() expect(wrapper.find('[data-test="skills-tab"]').exists()).toBe(false) expect(router.currentRoute.value.query.tab).toBe('tools') @@ -173,7 +177,7 @@ describe('ServerDetail Skills tab (Spec 125)', () => { { success: false, error: 'internal error' }, ]) { ;(api.getServerSkills as any).mockResolvedValue(failure) - window.dispatchEvent(new CustomEvent('mcpproxy:skills-changed', { detail: { server: 'alpha' } })) + emitSkillsChanged('alpha') await flushPromises(); await flushPromises() expect(wrapper.find('[data-test="skills-tab"]').exists()).toBe(true) expect(wrapper.find('[data-test="skills-panel"]').exists()).toBe(true) @@ -181,7 +185,7 @@ describe('ServerDetail Skills tab (Spec 125)', () => { } // A thrown request is a failure too. ;(api.getServerSkills as any).mockRejectedValue(new Error('network')) - window.dispatchEvent(new CustomEvent('mcpproxy:skills-changed', { detail: { server: 'alpha' } })) + emitSkillsChanged('alpha') await flushPromises(); await flushPromises() expect(wrapper.find('[data-test="skills-panel"]').exists()).toBe(true) wrapper.unmount() @@ -206,4 +210,35 @@ describe('ServerDetail Skills tab (Spec 125)', () => { expect(wrapper.find('[data-test="skills-tab"]').classes()).toContain('tab-active') expect(router.currentRoute.value.query.tab).toBe('skills') }) + // Round-3 finding 3: overlapping background re-checks are ordered by request: + // only an answer newer than the last applied one changes the tab. + for (const order of ['older answer first', 'newer answer first'] as const) { + it(`two overlapping re-checks keep the newer answer (${order})`, async () => { + const { wrapper, router } = await mountServerDetail('/servers/alpha?tab=skills') + expect(wrapper.find('[data-test="skills-panel"]').exists()).toBe(true) + const pending: Array<(v: unknown) => void> = [] + ;(api.getServerSkills as any).mockImplementation(() => new Promise(r => { pending.push(r) })) + emitSkillsChanged('alpha') // older: will say "unsupported" + emitSkillsChanged('alpha') // newer: will say "supported" + await flushPromises() + // Each event reaches ServerDetail's listener first, then SkillsPanel's reload: + // requests are [check 1, reload 1, check 2, reload 2]. + expect(api.getServerSkills).toHaveBeenCalledTimes(1 + 1 + 4) + const [older, newer] = [pending[0], pending[2]] + const unsupported = { success: true, data: makeListing([], { supported: false }) } + const supported = { success: true, data: makeListing([makeSkill('hf')]) } + if (order === 'older answer first') { older(unsupported); await flushPromises(); newer(supported) } + else { newer(supported); await flushPromises(); older(unsupported) } + pending[1](supported); pending[3](supported) + await flushPromises(); await flushPromises() + // The newer answer ("supported") is the one that stands either way. + expect(wrapper.find('[data-test="skills-tab"]').exists()).toBe(true) + if (order === 'newer answer first') { + // The older answer came after it and was dropped: the open review was never unmounted. + expect(wrapper.find('[data-test="skills-panel"]').exists()).toBe(true) + expect(router.currentRoute.value.query.tab).toBe('skills') + } + wrapper.unmount() + }) + } }) diff --git a/frontend/tests/unit/skill-detail.spec.ts b/frontend/tests/unit/skill-detail.spec.ts index 73fb2ad0d..cccfef7e2 100644 --- a/frontend/tests/unit/skill-detail.spec.ts +++ b/frontend/tests/unit/skill-detail.spec.ts @@ -234,6 +234,40 @@ describe('SkillDetail', () => { await w.get('[data-test="skill-view-approved-notes"]').trigger('click'); await flushPromises() expect(api.getSkillContent).toHaveBeenCalledWith('srv', { skill: 'a', file: 'notes', copy: 'approved', offset: 0 }) expect(w.get('[data-test="skill-viewer-text"]').text()).toBe('old text') + // Round-3 finding 5: the current copy is binary (the content route answers 415), so it is not offered. + expect(w.find('[data-test="skill-copy-current"]').exists()).toBe(false) + expect(w.get('[data-test="skill-viewer-copy"]').text()).toBe('approved copy') + }) + + it('does not offer the approved copy when it is binary and the current file is text', async () => { + m(api.getSkillContent).mockResolvedValue(ok({ text: 'new text', offset: 0, size: 8, digest: 'sha256:t' })) + const w = mountDetail(makeSkill('a', { + status: 'changed', approved_hash: 'sk1-old', + approved_files: [skillFile('SKILL.md'), skillFile('notes', 'sha256:bin', 8, false)], + files: [skillFile('SKILL.md'), skillFile('notes', 'sha256:t', 8, true)], + })) + expect(w.find('[data-test="skill-view-approved-notes"]').exists()).toBe(false) + await w.get('[data-test="skill-view-notes"]').trigger('click'); await flushPromises() + expect(w.get('[data-test="skill-viewer-text"]').text()).toBe('new text') + expect(w.find('[data-test="skill-copy-approved"]').exists()).toBe(false) + expect(w.get('[data-test="skill-viewer-copy"]').text()).toBe('current copy') + }) + + // Round-3 finding 4: a reload that moved nothing (same server, path and hashes) + // keeps the open viewer and the pages loaded into it. + it('keeps an open paged viewer across an unchanged reload, and drops it on a real change', async () => { + m(api.getSkillContent) + .mockResolvedValueOnce(ok({ text: 'part1', offset: 0, size: 10, digest: D, next_offset: 5 })) + .mockResolvedValueOnce(ok({ text: 'part2', offset: 5, size: 10, digest: D })) + const w = mountDetail(makeSkill('a')) + await w.get('[data-test="skill-view-SKILL.md"]').trigger('click'); await flushPromises() + await w.get('[data-test="skill-load-more"]').trigger('click'); await flushPromises() + expect(w.get('[data-test="skill-viewer-text"]').text()).toBe('part1part2') + // The same version again as a new object (e.g. a skills.changed for another skill, or a block). + await w.setProps({ skill: makeSkill('a', { blocked: true }) }); await flushPromises() + expect(w.get('[data-test="skill-viewer-text"]').text()).toBe('part1part2') + await w.setProps({ skill: makeSkill('a', { blocked: true, current_hash: 'sk1-moved' }) }); await flushPromises() + expect(w.find('[data-test="skill-viewer"]').exists()).toBe(false) }) // Round-2 finding 11: an entry without a scan block (the agent shape) does not throw. diff --git a/frontend/tests/unit/skills-panel.spec.ts b/frontend/tests/unit/skills-panel.spec.ts index 4b0452eb4..e2dfc2fb1 100644 --- a/frontend/tests/unit/skills-panel.spec.ts +++ b/frontend/tests/unit/skills-panel.spec.ts @@ -2,7 +2,8 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import { flushPromises, mount } from '@vue/test-utils' import SkillsPanel from '@/components/skills/SkillsPanel.vue' import api from '@/services/api' -import { makeListing, makeSkill, ok } from './fixtures/skills125' +import { createPinia, setActivePinia } from 'pinia' +import { connectSkillsSSE, makeListing, makeSkill, ok } from './fixtures/skills125' vi.mock('@/services/api', () => ({ default: { getServerSkills: vi.fn(), refreshServerSkills: vi.fn(), getSkillContent: vi.fn(), @@ -11,10 +12,14 @@ vi.mock('@/services/api', () => ({ default: { const m = (f: unknown) => f as ReturnType const mountPanel = (serverName = 'srv') => mount(SkillsPanel, { props: { serverName } }) +// Round-3 finding 1: every skills.changed goes through the real store's re-dispatch of the core's frame. +let emitSkillsChanged: (server: string) => void = () => { throw new Error('not connected') } describe('SkillsPanel', () => { - beforeEach(() => { + beforeEach(async () => { vi.clearAllMocks() + setActivePinia(createPinia()) + emitSkillsChanged = await connectSkillsSSE(api) m(api.getSkillContent).mockResolvedValue(ok({ text: 'body', offset: 0, size: 4, digest: 'd' })) }) @@ -204,14 +209,14 @@ describe('SkillsPanel', () => { it('reloads on mcpproxy:skills-changed for its own server only', async () => { m(api.getServerSkills).mockResolvedValue(ok(makeListing([makeSkill('a')]))) const w = mountPanel(); await flushPromises() - window.dispatchEvent(new CustomEvent('mcpproxy:skills-changed', { detail: { server: 'other' } })) + emitSkillsChanged('other') await flushPromises() expect(api.getServerSkills).toHaveBeenCalledTimes(1) - window.dispatchEvent(new CustomEvent('mcpproxy:skills-changed', { detail: { server: 'srv' } })) + emitSkillsChanged('srv') await flushPromises() expect(api.getServerSkills).toHaveBeenCalledTimes(2) w.unmount() - window.dispatchEvent(new CustomEvent('mcpproxy:skills-changed', { detail: { server: 'srv' } })) + emitSkillsChanged('srv') await flushPromises() expect(api.getServerSkills).toHaveBeenCalledTimes(2) }) @@ -233,7 +238,7 @@ describe('SkillsPanel', () => { await w.get('[data-test="skill-row-a"]').trigger('click'); await flushPromises() expect(w.find('[data-test="skill-detail"]').exists()).toBe(true) m(api.getServerSkills).mockResolvedValue(ok(makeListing([makeSkill('b')]))) - window.dispatchEvent(new CustomEvent('mcpproxy:skills-changed', { detail: { server: 'srv' } })) + emitSkillsChanged('srv') await flushPromises() expect(w.find('[data-test="skill-detail"]').exists()).toBe(false) }) @@ -247,7 +252,7 @@ describe('SkillsPanel', () => { expect(w.find('[data-test="skill-stale"]').exists()).toBe(false) // A skills.changed reload replaces the entry; the chip still says Awaiting review. m(api.getServerSkills).mockResolvedValue(ok(makeListing([makeSkill('a', { current_hash: 'sk1-unread' })], { incarnation: 3 }))) - window.dispatchEvent(new CustomEvent('mcpproxy:skills-changed', { detail: { server: 'srv' } })) + emitSkillsChanged('srv') await flushPromises() expect(w.get('[data-test="skill-chip-a"]').text()).toBe('Awaiting review') expect(w.get('[data-test="skill-stale"]').text()).toMatch(/This skill changed while you were reviewing it/) @@ -269,7 +274,7 @@ describe('SkillsPanel', () => { const w = mountPanel(); await flushPromises() await w.get('[data-test="skill-row-a"]').trigger('click'); await flushPromises() m(api.getServerSkills).mockResolvedValue(ok(makeListing([makeSkill('a')], { incarnation: 4 }))) - window.dispatchEvent(new CustomEvent('mcpproxy:skills-changed', { detail: { server: 'srv' } })) + emitSkillsChanged('srv') await flushPromises() expect(w.find('[data-test="skill-stale"]').exists()).toBe(true) expect(w.get('[data-test="skill-approve"]').attributes('disabled')).toBeDefined() @@ -280,7 +285,7 @@ describe('SkillsPanel', () => { const w = mountPanel(); await flushPromises() await w.get('[data-test="skill-row-a"]').trigger('click'); await flushPromises() m(api.getServerSkills).mockResolvedValue(ok(makeListing([makeSkill('a', { blocked: true })]))) - window.dispatchEvent(new CustomEvent('mcpproxy:skills-changed', { detail: { server: 'srv' } })) + emitSkillsChanged('srv') await flushPromises() expect(w.find('[data-test="skill-stale"]').exists()).toBe(false) expect(w.find('[data-test="skill-unblock"]').exists()).toBe(true) @@ -311,4 +316,65 @@ describe('SkillsPanel', () => { expect(w.get('[data-test="skill-viewer-error"]').text()).toMatch(/This file changed/) expect(api.getServerSkills).toHaveBeenCalledTimes(2) }) + // Round-3 finding 2: a thrown request (network error) never leaves an + // unhandled rejection or a stuck spinner/disabled button. + it('a thrown load shows an error with a retry and stops loading', async () => { + m(api.getServerSkills).mockRejectedValueOnce(new Error('network')) + const w = mountPanel(); await flushPromises() + expect(w.get('[data-test="skills-error"]').text()).toContain('network') + expect(w.find('.loading-spinner').exists()).toBe(false) + m(api.getServerSkills).mockResolvedValueOnce(ok(makeListing([makeSkill('a')]))) + await w.get('[data-test="skills-retry"]').trigger('click'); await flushPromises() + expect(w.find('[data-test="skill-row-a"]').exists()).toBe(true) + expect(w.find('[data-test="skills-error"]').exists()).toBe(false) + }) + + it('a thrown reload keeps the listing on screen and shows the error', async () => { + m(api.getServerSkills).mockResolvedValueOnce(ok(makeListing([makeSkill('a')]))) + const w = mountPanel(); await flushPromises() + m(api.getServerSkills).mockRejectedValueOnce(new Error('network')) + emitSkillsChanged('srv'); await flushPromises() + expect(w.find('[data-test="skill-row-a"]').exists()).toBe(true) + expect(w.get('[data-test="skills-load-error"]').text()).toContain('network') + }) + + it('a thrown refresh resets the Refresh button, says so and reloads', async () => { + m(api.getServerSkills).mockResolvedValue(ok(makeListing([makeSkill('a')]))) + const w = mountPanel(); await flushPromises() + m(api.refreshServerSkills).mockRejectedValueOnce(new Error('network')) + await w.get('[data-test="skills-refresh"]').trigger('click'); await flushPromises() + expect(w.get('[data-test="skills-refresh"]').attributes('disabled')).toBeUndefined() + expect(w.get('[data-test="skills-notice"]').text()).toContain('network') + expect(api.getServerSkills).toHaveBeenCalledTimes(2) + }) + + it('a thrown approve resets busy, shows the error and reloads', async () => { + m(api.getServerSkills).mockResolvedValue(ok(makeListing([makeSkill('a')]))) + m(api.approveSkills).mockRejectedValueOnce(new Error('network')) + const w = mountPanel(); await flushPromises() + await w.get('[data-test="skill-row-a"]').trigger('click'); await flushPromises() + await w.get('[data-test="skill-approve"]').trigger('click'); await flushPromises() + expect(w.get('[data-test="skill-approve"]').attributes('disabled')).toBeUndefined() + expect(w.get('[data-test="skills-notice"]').text()).toContain('network') + expect(api.getServerSkills).toHaveBeenCalledTimes(2) + }) + + it('a thrown answer for the previous server changes nothing on the new one', async () => { + let failA: (e: unknown) => void = () => {} + let failRefresh: (e: unknown) => void = () => {} + m(api.getServerSkills).mockImplementation((name: string) => + name === 'a' ? new Promise((_, rej) => { failA = rej }) : Promise.resolve(ok(makeListing([makeSkill('only_b')])))) + const w = mountPanel('a') + await w.setProps({ serverName: 'b' }); await flushPromises() + m(api.refreshServerSkills).mockReturnValueOnce(new Promise((_, rej) => { failRefresh = rej })) + await w.get('[data-test="skills-refresh"]').trigger('click'); await flushPromises() + failA(new Error('late a')); await flushPromises() + expect(w.find('[data-test="skills-error"]').exists()).toBe(false) + expect(w.find('[data-test="skills-load-error"]').exists()).toBe(false) + expect(w.find('[data-test="skill-row-only_b"]').exists()).toBe(true) + // The refresh for b is still in flight: its button stays busy. + expect(w.get('[data-test="skills-refresh"]').attributes('disabled')).toBeDefined() + failRefresh(new Error('net')); await flushPromises() + expect(w.get('[data-test="skills-refresh"]').attributes('disabled')).toBeUndefined() + }) }) diff --git a/frontend/tests/unit/skills-sse-redispatch.spec.ts b/frontend/tests/unit/skills-sse-redispatch.spec.ts index 4e2aa0bd3..a55ead799 100644 --- a/frontend/tests/unit/skills-sse-redispatch.spec.ts +++ b/frontend/tests/unit/skills-sse-redispatch.spec.ts @@ -10,7 +10,10 @@ vi.mock('@/services/api', () => ({ })) describe('SSE skills.changed', () => { - it('is re-dispatched as mcpproxy:skills-changed with the parsed payload', () => { + // Round-3 finding 1: the core wraps every runtime event as {payload, timestamp}; + // the frame is re-dispatched whole, like servers.changed and attention.changed, + // and consumers read detail.payload. + it('is re-dispatched as mcpproxy:skills-changed with the whole frame the core writes', () => { setActivePinia(createPinia()) const listeners: Record void> = {} ;(api.createEventSource as any).mockReturnValue({ @@ -21,9 +24,10 @@ describe('SSE skills.changed', () => { const on = (e: Event) => seen.push((e as CustomEvent).detail) window.addEventListener('mcpproxy:skills-changed', on) useSystemStore().connectEventSource() - listeners['skills.changed']({ data: JSON.stringify({ server: 'hf', counts: { pending: 1 } }) }) + const frame = { payload: { server: 'hf', counts: { pending: 1 } }, timestamp: 1763300000 } + listeners['skills.changed']({ data: JSON.stringify(frame) }) listeners['skills.changed']({ data: 'not json' }) window.removeEventListener('mcpproxy:skills-changed', on) - expect(seen).toEqual([{ server: 'hf', counts: { pending: 1 } }]) + expect(seen).toEqual([frame]) }) }) diff --git a/frontend/tests/unit/skills-utils.spec.ts b/frontend/tests/unit/skills-utils.spec.ts index 21928e309..ddc6a9e6a 100644 --- a/frontend/tests/unit/skills-utils.spec.ts +++ b/frontend/tests/unit/skills-utils.spec.ts @@ -1,7 +1,7 @@ import { describe, expect, it, vi } from 'vitest' import { skillStateChip, skillFileDiff, lineDiff, skillExpectedHashes, readWholeSkillFile, - skillsTabVisible, skillErrorNotice, SKILL_CONTENT_CHANGED, + skillsTabVisible, skillErrorNotice, SKILL_CONTENT_CHANGED, LINE_DIFF_CONTEXT, LINE_DIFF_MAX_OPS, } from '@/utils/skills' const file = (path: string, digest: string, size = 10, text = true) => ({ path, size, digest, text }) @@ -54,6 +54,37 @@ describe('lineDiff', () => { expect(r.tooLarge).toBe(true) expect(r.ops).toEqual([]) }) + // Round-3 finding 6: the output is bounded, not only the LCS middle. + it('collapses a huge shared prefix and suffix around a one-line change', () => { + const shared = Array.from({ length: 130_000 }, (_, i) => `line ${i}`) + const a = [...shared, 'old', ...shared].join('\n') + const b = [...shared, 'new', ...shared].join('\n') + const r = lineDiff(a, b) + expect(r.tooLarge).toBe(false) + expect(r.ops.length).toBeLessThan(20) + const ops = r.ops.map(o => `${o.op}:${o.text}`) + expect(ops).toContain('del:old') + expect(ops).toContain('add:new') + expect(ops[0]).toBe(`skip:${130_000 - LINE_DIFF_CONTEXT} unchanged lines`) + expect(ops[ops.length - 1]).toBe(`skip:${130_000 - LINE_DIFF_CONTEXT} unchanged lines`) + expect(ops).toContain(`same:line ${130_000 - 1}`) + expect(ops).not.toContain(`same:line ${130_000 - 1 - LINE_DIFF_CONTEXT}`) + }) + it('collapses an unchanged run inside the middle, and keeps a short one', () => { + const run = Array.from({ length: 50 }, (_, i) => `m${i}`) + const r = lineDiff(['x', ...run, 'y', 'k1', 'k2'].join('\n'), ['X', ...run, 'Y', 'k1', 'k2'].join('\n')) + const ops = r.ops.map(o => `${o.op}:${o.text}`) + expect(ops).toContain(`skip:${50 - 2 * LINE_DIFF_CONTEXT} unchanged lines`) + expect(ops.slice(-2)).toEqual(['same:k1', 'same:k2']) + }) + it('is too large when the changed lines alone pass the op limit', () => { + const a = Array.from({ length: 10 }, (_, i) => `a${i}`).join('\n') + const b = Array.from({ length: 30_000 }, (_, i) => `b${i}`).join('\n') + const r = lineDiff(a, b) + expect(r.tooLarge).toBe(true) + expect(r.ops).toEqual([]) + expect(LINE_DIFF_MAX_OPS).toBeLessThan(30_000) + }) }) describe('skillExpectedHashes', () => { diff --git a/scripts/run-skills-tab-sweep.sh b/scripts/run-skills-tab-sweep.sh index 6e3c21514..d295fd2e5 100755 --- a/scripts/run-skills-tab-sweep.sh +++ b/scripts/run-skills-tab-sweep.sh @@ -8,10 +8,11 @@ # It starts, and on exit stops, only what it started: # * cmd/skillsfixture on a free loopback port; # * a core on a free high loopback port with a scratch data dir (never -# ~/.mcpproxy: MCPPROXY_DATA_DIR / MCPPROXY_DATA, which would override the -# config's data_dir, are removed from its environment, --data-dir names the -# scratch dir, HOME points at a scratch home, and a data dir under -# $HOME/.mcpproxy is refused), enable_skills on, a generated throwaway API +# ~/.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; --data-dir names the scratch +# dir, and a data dir under $HOME/.mcpproxy is refused), enable_skills on, +# a generated throwaway API # key, and the fixture as a trust_mode: manual streamable-http upstream; # then approves the server, runs the spec, and reads the core's own skill # records back after the approve, block and unblock steps. @@ -24,9 +25,14 @@ set -euo pipefail -if [[ "${DEBUG:-}" == "1" ]]; then - set -x -fi +# No xtrace, not even with DEBUG=1: a traced line would print the throwaway API +# key (its assignment, the X-API-Key header, the core's environment, the +# redaction call). DEBUG=1 prints progress lines instead (debug below), none of +# which carries a secret; --self-test checks a DEBUG=1 run's stderr for the key. +debug() { + if [[ "${DEBUG:-}" == "1" ]]; then echo "debug: $*" >&2; fi + return 0 +} usage() { cat <&2 exit 1 fi - env -u MCPPROXY_DATA_DIR -u MCPPROXY_DATA \ - HOME="$CORE_HOME" HEADLESS=1 DO_NOT_TRACK=1 MCPPROXY_TELEMETRY=false MCPPROXY_API_KEY="$API_KEY" \ + debug "starting the core on $listen (data dir: the scratch dir)" + clean_env HEADLESS=1 DO_NOT_TRACK=1 MCPPROXY_TELEMETRY=false MCPPROXY_API_KEY="$API_KEY" \ "$CORE_BIN" serve --config "$CONFIG_PATH" --data-dir "$DATA_DIR" --listen "$listen" >"$CORE_LOG" 2>&1 & CORE_PID=$! } @@ -327,9 +348,11 @@ NODE # that follows it (--self-test-first) starts from fresh state. st_fail() { echo "self-test FAILED: $*" >&2; exit 1; } run_self_test() { - local sweep_data_dir="$DATA_DIR" st_port d step st_status results enc_key st_out decoy_new decoy_legacy + local sweep_data_dir="$DATA_DIR" st_port d step st_status results enc_key st_out decoy_new decoy_legacy decoy_audit_dir decoy_certs decoy_tpa DATA_DIR="$WORK/st-data" mkdir -p "$DATA_DIR" + # The DEBUG=1 child of step 4 hands its key to the parent (a scratch file of the parent's). + if [[ -n "${SWEEP_SELF_TEST_CHILD:-}" ]]; then printf '%s' "$API_KEY" >"$SWEEP_SELF_TEST_CHILD"; fi # 1. The guard refuses the operator's ~/.mcpproxy and anything inside it. [[ -n "$OPERATOR_HOME" ]] || st_fail "HOME is not set" @@ -341,10 +364,16 @@ run_self_test() { # 2. An ambient MCPPROXY_DATA_DIR / MCPPROXY_DATA does not reach the core. decoy_new="$WORK/decoy-data-dir" decoy_legacy="$WORK/decoy-data-legacy" - mkdir -p "$decoy_new" "$decoy_legacy" + decoy_audit_dir="$WORK/decoy-audit" + decoy_certs="$WORK/decoy-certs" + decoy_tpa="$WORK/decoy-tpa/bundle.json" + mkdir -p "$decoy_new" "$decoy_legacy" "$decoy_audit_dir" "$decoy_certs" st_port=$(free_port) write_config "127.0.0.1:${st_port}" "" - MCPPROXY_DATA_DIR="$decoy_new" MCPPROXY_DATA="$decoy_legacy" start_core "127.0.0.1:${st_port}" + MCPPROXY_DATA_DIR="$decoy_new" MCPPROXY_DATA="$decoy_legacy" \ + MCPPROXY_AUDIT_LOG_ENABLED=true MCPPROXY_AUDIT_LOG_PATH="$decoy_audit_dir/audit.jsonl" \ + MCPPROXY_TPA_BUNDLE_PATH="$decoy_tpa" MCPPROXY_CERTS_DIR="$decoy_certs" \ + start_core "127.0.0.1:${st_port}" wait_core "http://127.0.0.1:${st_port}" check_core_data_dir for d in "$decoy_new" "$decoy_legacy"; do @@ -357,6 +386,21 @@ run_self_test() { CORE_PID="" echo "self-test: with MCPPROXY_DATA_DIR and MCPPROXY_DATA set to decoys, the core opened its database in the scratch dir only" + # 2b. Nothing else of the operator's environment reaches the core either: + # MCPPROXY_AUDIT_LOG_ENABLED/PATH would turn auditing on into a file of the + # operator's (internal/config/loader.go), and MCPPROXY_TPA_BUNDLE_PATH / + # MCPPROXY_CERTS_DIR name more paths. The core of 2. ran with all of them set + # to decoys; it must have touched none, and its log must name none. + for d in "$decoy_audit_dir" "$decoy_certs"; do + if [[ -n "$(ls -A "$d" 2>/dev/null)" ]]; then + st_fail "the core wrote into the ambient decoy $d: $(ls -A "$d")" + fi + done + for d in "$decoy_audit_dir" "$decoy_certs" "$decoy_tpa"; do + grep -qF "$d" "$CORE_LOG" && st_fail "the core log names the ambient decoy $d" + done + echo "self-test: with MCPPROXY_AUDIT_LOG_PATH, MCPPROXY_TPA_BUNDLE_PATH and MCPPROXY_CERTS_DIR set to decoys, the core touched none of them" + # 3. The results writer: first failed attempt, redaction, provenance. st_out="$WORK/st-out" OUT_REAL="$st_out" @@ -397,6 +441,24 @@ if (JSON.stringify(r.fixture.command) !== JSON.stringify(["skillsfixture", "-add if (r.checked_commit !== "0123456789abcdef0123456789abcdef01234567" || r.working_tree_dirty !== true || r.evidence !== "pre-commit" || !/^pre-commit evidence/.test(r.checked)) fail("provenance: " + JSON.stringify([r.checked_commit, r.working_tree_dirty, r.evidence, r.checked])) ' "$results" echo "self-test: the results writer records the first failed attempt, redacts the key and local paths, and labels a dirty tree pre-commit evidence" + + # 4. DEBUG=1 never prints the key: the whole self-test above (config, core + # start with the key, curl with the key header, redaction) runs again as a + # child with DEBUG=1, which hands back its own key through a scratch file; + # the child's stderr must not contain it. The child skips this step. + if [[ -z "${SWEEP_SELF_TEST_CHILD:-}" ]]; then + local probe_err="$WORK/debug-probe.stderr" probe_key="$WORK/debug-probe.key" probe_status + set +e + DEBUG=1 SWEEP_SELF_TEST_CHILD="$probe_key" MCPPROXY_BINARY_PATH="$CORE_BIN" \ + bash "$SCRIPT_DIR/$(basename "${BASH_SOURCE[0]}")" --self-test >/dev/null 2>"$probe_err" + probe_status=$? + set -e + [[ -s "$probe_key" ]] || st_fail "the DEBUG=1 self-test run did not hand back its key (exit $probe_status)" + # Never echo the child's stderr here: it is what is being checked for the key. + grep -qF "$(cat "$probe_key")" "$probe_err" && st_fail "a DEBUG=1 run printed its API key to stderr ($(grep -cF "$(cat "$probe_key")" "$probe_err") lines)" + [[ $probe_status -eq 0 ]] || st_fail "the DEBUG=1 self-test run failed (exit $probe_status)" + echo "self-test: a DEBUG=1 run (the self-test as a child) never printed its API key to stderr" + fi echo "self-test passed" DATA_DIR="$sweep_data_dir" OUT_REAL="" @@ -462,7 +524,8 @@ FIXTURE_PORT=$(free_port) FIXTURE_ADDR="127.0.0.1:${FIXTURE_PORT}" FIXTURE_URL="http://${FIXTURE_ADDR}" FIXTURE_CMD=("$FIXTURE_BIN" -addr "$FIXTURE_ADDR") -"${FIXTURE_CMD[@]}" >"$FIXTURE_LOG" 2>&1 & +debug "starting skillsfixture on $FIXTURE_ADDR" +clean_env "${FIXTURE_CMD[@]}" >"$FIXTURE_LOG" 2>&1 & FIXTURE_PID=$! for attempt in $(seq 1 30); do if curl -s --connect-timeout 1 --max-time 3 -o /dev/null -X POST -H 'Content-Type: application/json' \ @@ -512,6 +575,7 @@ if [[ $ready -ne 1 ]]; then fi echo "server ${SERVER} approved; three skills listed" +debug "running Playwright" # --- Playwright (same locked install as scripts/run-web-smoke.sh) ------------- SWEEP_DIR="$REPO_ROOT/e2e/web-ui-sweep" export PLAYWRIGHT_BROWSERS_PATH="${PLAYWRIGHT_BROWSERS_PATH:-$REPO_ROOT/tmp/playwright-browsers}" @@ -592,6 +656,7 @@ const about = [ ['Approve', 'Approve sends the current_hash and incarnation of the version the reviewer opened; the chip turns Approved.', ['04-approved']], ['Changed while open, re-open, diff', 'A mutate without the X-Skills-Fixture header is refused (403). The approved skill plain changes upstream while it is open; after Refresh the chip says Changed and the open review says it changed while you were reviewing it (the review shows the approved version, so it offers no Approve). Re-opening shows the file-set diff (SKILL.md changed) and the line diff with the added line; approving binds the new hash.', ['05a-stale', '05-changed-diff']], ['Pending skill changed while open', 'The pending skill with-files changes upstream while it is open; after Refresh the review is marked stale and its Approve button stays on screen but disabled, until the new version is re-opened.', ['05b-pending-stale']], + ['Live skills.changed', 'With the pending skill big open, its SKILL.md changes upstream and the refresh is made through POST /api/v1/servers/{id}/skills/refresh, not in the page. The core\'s skills.changed SSE frame, re-dispatched by the Web UI, reloads the listing by itself and the open review shows the stale banner with Approve disabled.', ['05c-live-event-stale']], ['Block and unblock', 'Block marks the skill Blocked and removes Approve; Unblock returns it to Awaiting review.', ['06-blocked']], ['Reload', 'The tab survives a reload through ?tab=skills, and no uncaught page error was thrown in any scenario.', []], ] From d10ee8b6706624e6ed1211d8fbde3c36b7f92014 Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Fri, 20 Nov 2026 12:33:46 +0200 Subject: [PATCH 04/18] fix(skills): review round 4 for the Skills tab and its sweep - run-skills-tab-sweep.sh: the core and the fixture were started through a backgrounded shell function, so $! was a subshell's PID and cleanup killed that shell, orphaning the server (seen in practice: cores and fixtures of earlier runs left running). They now start through a CLEAN_ENV array, so the recorded PID is the server itself; stop_started (the EXIT trap and the self-test restart) reads the process tree before signalling, sends SIGTERM to the tree, SIGKILLs what is left after 15 s, and touches nothing else. --self-test gains a step proving the recorded PIDs are the core and the fixture (by name and by the listening port), that after cleanup no PID of the run nor either port is alive, and that an unrelated process survives. - ServerDetail.vue: a late visibility answer arriving after the view was unmounted wrote ?tab=tools into the next page's URL. Every ?tab= write now requires the view to be mounted and the URL to be this server's (urlIsThisView). Tests cover a deferred check that answers after unmount and after a server switch (the switch was already guarded by the name check; the unmount case failed before the fix). - SkillsPanel.vue: the approve notice is worded from the reloaded listing's `available` for that skill (skillApprovedNotice): "Agents can use this skill now" only when available, "Not offered to agents yet: " (feature off, expose_skills: false, blocked, no longer listed, state moved) or without a reason (server disabled or quarantined), and a neutral "Approved." when the reload failed. - skills-tab.spec.ts: the paging scenario now asserts that every part is of the current copy, carries the digest and size the core lists for the file (and the file row shows on screen), starts where the previous part ended and its next_offset is where it ends, and that the last part ends at the listed size. The report text for the scenario says exactly that. Related #1895 --- e2e/web-ui-sweep/skills-tab.spec.ts | 28 +++- .../src/components/skills/SkillsPanel.vue | 30 ++-- frontend/src/utils/skills.ts | 21 +++ frontend/src/views/ServerDetail.vue | 13 +- .../unit/server-detail-skills-tab.spec.ts | 38 +++++ frontend/tests/unit/skills-panel.spec.ts | 42 +++++ scripts/run-skills-tab-sweep.sh | 155 ++++++++++++++---- 7 files changed, 279 insertions(+), 48 deletions(-) diff --git a/e2e/web-ui-sweep/skills-tab.spec.ts b/e2e/web-ui-sweep/skills-tab.spec.ts index 0caca8ec5..b993de480 100644 --- a/e2e/web-ui-sweep/skills-tab.spec.ts +++ b/e2e/web-ui-sweep/skills-tab.spec.ts @@ -122,26 +122,47 @@ test('views SKILL.md, pages a large file, and does not offer a binary file', asy 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. + // 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') === 'data/large.txt' && + 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-data/large.txt"]').click()]) + 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') @@ -151,6 +172,7 @@ test('views SKILL.md, pages a large file, and does not offer a binary file', asy ;[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') diff --git a/frontend/src/components/skills/SkillsPanel.vue b/frontend/src/components/skills/SkillsPanel.vue index 0ac8180c8..e0cf182f4 100644 --- a/frontend/src/components/skills/SkillsPanel.vue +++ b/frontend/src/components/skills/SkillsPanel.vue @@ -86,7 +86,7 @@ import { computed, onMounted, onUnmounted, ref, watch } from 'vue' import api from '@/services/api' import type { SkillEntry, SkillsListResponse } from '@/types/api' import { formatDateTime } from '@/utils/datetime' -import { skillStateChip, skillExpectedHashes, skillErrorNotice } from '@/utils/skills' +import { skillStateChip, skillExpectedHashes, skillErrorNotice, skillApprovedNotice } from '@/utils/skills' import SkillDetail from './SkillDetail.vue' const props = defineProps<{ serverName: string }>() @@ -153,14 +153,16 @@ async function settle(run: () => Promise>): Promise> { } } -async function load() { +// Returns the listing it applied, or null (a failure, or a superseded answer). +async function load(): Promise { const server = props.serverName, v = visit, seq = ++requestSeq loading.value = true const res = await settle(() => api.getServerSkills(server)) - if (!isCurrent(server, v, seq)) return + if (!isCurrent(server, v, seq)) return null loading.value = false - if (res.success && res.data) apply(res.data) - else error.value = res.error || 'Could not load skills' + if (res.success && res.data) { apply(res.data); return res.data } + error.value = res.error || 'Could not load skills' + return null } // One refresh in flight per visit: a late answer of an earlier one never @@ -184,15 +186,23 @@ async function refresh() { // the listing on screen. A 409 reloads and tells the operator; it never retries. // The answer is shown only while the same review is still open: a late answer // for a skill the reviewer has left is not shown on the next one (the listing is -// still reloaded). -async function write(run: () => Promise<{ success: boolean; error?: string; errorCode?: string }>, done: string) { +// still reloaded). A success notice given as a function is worded from the +// listing reloaded after the write (null when that reload did not apply). +type DoneNotice = string | ((reloaded: SkillsListResponse | null) => string) +async function write(run: () => Promise<{ success: boolean; error?: string; errorCode?: string }>, done: DoneNotice) { const server = props.serverName, v = visit, token = review.value?.token busy.value = true const res = await settle(run) if (!isCurrent(server, v)) return busy.value = false - if (review.value?.token === token) notice.value = res.success ? done : skillErrorNotice(res.errorCode, res.error) - await load() + if (!res.success || typeof done === 'string') { + if (review.value?.token === token) notice.value = res.success ? done as string : skillErrorNotice(res.errorCode, res.error) + await load() + return + } + const reloaded = await load() + // Still the same review (or none: the reload dropped a skill that vanished). + if (isCurrent(server, v) && (!review.value || review.value.token === token)) notice.value = done(reloaded) } // Approve sends exactly the hash and the incarnation the reviewer opened. @@ -201,7 +211,7 @@ function approve() { if (!r || r.stale || busy.value) return return write( () => api.approveSkills(props.serverName, [r.path], skillExpectedHashes([r.entry]), r.incarnation), - 'Approved. Agents can use this skill now.', + reloaded => skillApprovedNotice(reloaded, r.path), ) } diff --git a/frontend/src/utils/skills.ts b/frontend/src/utils/skills.ts index 5abde1699..862efa2b0 100644 --- a/frontend/src/utils/skills.ts +++ b/frontend/src/utils/skills.ts @@ -194,3 +194,24 @@ export function skillErrorNotice(code: string | undefined, message: string | und 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 153170942..bab9e51bf 100644 --- a/frontend/src/views/ServerDetail.vue +++ b/frontend/src/views/ServerDetail.vue @@ -1712,12 +1712,20 @@ let skillsCheckFloor = 0 // answers with a sequence <= this are dropped function skillsTabRefused() { return isTenant.value || (skillsTabChecked.value && !skillsTabVisible.value) } +// Round-4 finding 2: `route` is the router's current route, not this view's. +// A late answer (a visibility check, any async step) may arrive after this view +// was unmounted, or after the URL moved to another server; it must never write +// ?tab= into that URL. Every ?tab= write goes through this check. +let viewMounted = true +function urlIsThisView(): boolean { + return viewMounted && route.params.serverName === props.serverName +} function leaveSkillsTabIfNotOffered() { if (!skillsTabRefused()) return if (activeTab.value === 'skills') activeTab.value = 'tools' // activeTab may already read 'tools' (readTabFromQuery set it in the same // tick), in which case the watch does not fire: write the URL here. - else if (route.query.tab === 'skills') void router.replace({ query: { ...route.query, tab: 'tools' } }) + else if (route.query.tab === 'skills' && urlIsThisView()) void router.replace({ query: { ...route.query, tab: 'tools' } }) } async function checkSkillsTab(reset = true) { // A failed background re-check (reset=false, after skills.changed) never @@ -1762,7 +1770,7 @@ async function checkSkillsTab(reset = true) { // link. The initial value is read from `?tab=` in onMounted below; this watch // only ever writes forward from there. watch(activeTab, (tab) => { - if (route.query.tab === tab) return + if (route.query.tab === tab || !urlIsThisView()) return void router.replace({ query: { ...route.query, tab } }) }) // Sets activeTab from `?tab=` (or resets it to the default when absent), @@ -4221,6 +4229,7 @@ onMounted(() => { // Cleanup polling on unmount onUnmounted(() => { + viewMounted = false stopScanPolling() window.removeEventListener('mcpproxy:scan-settled', handleScanSettledEvent) window.removeEventListener('mcpproxy:servers-changed', handleServersChangedEvent) diff --git a/frontend/tests/unit/server-detail-skills-tab.spec.ts b/frontend/tests/unit/server-detail-skills-tab.spec.ts index b316ce1cd..5fa15db34 100644 --- a/frontend/tests/unit/server-detail-skills-tab.spec.ts +++ b/frontend/tests/unit/server-detail-skills-tab.spec.ts @@ -210,6 +210,44 @@ describe('ServerDetail Skills tab (Spec 125)', () => { expect(wrapper.find('[data-test="skills-tab"]').classes()).toContain('tab-active') expect(router.currentRoute.value.query.tab).toBe('skills') }) + // Round-4 finding 2: a late visibility answer never writes ?tab= into a URL + // that is no longer this view's: not after unmount, not after a server switch. + it('a check that answers after unmount writes nothing into the next URL', async () => { + let release: (v: unknown) => void = () => {} + ;(api.getServerSkills as any).mockReturnValueOnce(new Promise(r => { release = r })) + const { wrapper, router } = await mountServerDetail('/servers/alpha') + wrapper.unmount() + // The next view (here a fresh page of the same server) asks for the Skills tab. + await router.push('/servers/alpha?tab=skills&focus=x') + const replace = vi.spyOn(router, 'replace') + release({ success: true, data: makeListing([], { supported: false }) }) + await flushPromises(); await flushPromises() + expect(replace).not.toHaveBeenCalled() + expect(router.currentRoute.value.fullPath).toBe('/servers/alpha?tab=skills&focus=x') + }) + + it('a check that answers after a server switch writes nothing into the new server URL', async () => { + const pending: Array<(v: unknown) => void> = [] + ;(api.getServerSkills as any).mockImplementation(() => new Promise(r => { pending.push(r) })) + const { wrapper, router } = await mountServerDetail('/servers/alpha') + await router.push('/servers/beta?tab=skills') + await wrapper.setProps({ serverName: 'beta' }) + await flushPromises() + const replace = vi.spyOn(router, 'replace') + // alpha's late answer says "no skills"; beta's check is still in flight. + pending[0]({ success: true, data: makeListing([], { supported: false }) }) + await flushPromises(); await flushPromises() + expect(replace).not.toHaveBeenCalled() + expect(router.currentRoute.value.fullPath).toBe('/servers/beta?tab=skills') + // The same holds once alpha's view is gone and beta's answer arrives late. + wrapper.unmount() + await router.push('/servers/beta?tab=skills&next=1') + for (const r of pending.slice(1)) r({ success: true, data: makeListing([], { supported: false }) }) + await flushPromises(); await flushPromises() + expect(replace).not.toHaveBeenCalled() + expect(router.currentRoute.value.fullPath).toBe('/servers/beta?tab=skills&next=1') + }) + // Round-3 finding 3: overlapping background re-checks are ordered by request: // only an answer newer than the last applied one changes the tab. for (const order of ['older answer first', 'newer answer first'] as const) { diff --git a/frontend/tests/unit/skills-panel.spec.ts b/frontend/tests/unit/skills-panel.spec.ts index e2dfc2fb1..1bd0749b9 100644 --- a/frontend/tests/unit/skills-panel.spec.ts +++ b/frontend/tests/unit/skills-panel.spec.ts @@ -74,6 +74,48 @@ describe('SkillsPanel', () => { expect(api.getServerSkills).toHaveBeenCalledTimes(2) // reloaded after the write }) + // Round-4 finding 3: the approve notice is worded from the reloaded listing's + // `available` for that skill, never a blanket "Agents can use this skill now". + describe('approve notice follows the reloaded availability', () => { + const approveWith = async (after: ReturnType | { success: false; error: string }) => { + m(api.getServerSkills).mockResolvedValueOnce(ok(makeListing([makeSkill('a')]))) + m(api.approveSkills).mockResolvedValue(ok({ approved: 1 })) + const w = mountPanel(); await flushPromises() + await w.get('[data-test="skill-row-a"]').trigger('click'); await flushPromises() + m(api.getServerSkills).mockResolvedValue('success' in after ? after : ok(after)) + await w.get('[data-test="skill-approve"]').trigger('click'); await flushPromises() + return w.get('[data-test="skills-notice"] span').text() + } + const approved = (over: Parameters[1] = {}) => makeSkill('a', { status: 'approved', approved_hash: 'sk1-a', ...over }) + + it('available: says agents can use it', async () => { + expect(await approveWith(makeListing([approved({ available: true })]))).toContain('Approved. Agents can use this skill now.') + }) + for (const [why, listing, reason] of [ + ['expose_skills: false', makeListing([approved()], { expose_skills: false }), /expose_skills: false/], + ['the skill is blocked', makeListing([approved({ blocked: true })]), /blocked/i], + ['the upstream no longer lists it', makeListing([approved({ listed: false })]), /no longer lists/i], + ['the feature is off', makeListing([approved()], { enabled: false }), /enable_skills/], + ] as const) { + it(`not available (${why}): says not offered, with the reason`, async () => { + const text = await approveWith(listing) + expect(text).not.toMatch(/agents can use/i) + expect(text).toMatch(/^Approved\. Not offered to agents yet: /) + expect(text).toMatch(reason) + }) + } + it('not available for a reason the listing does not show (server disabled or quarantined): says not offered', async () => { + const text = await approveWith(makeListing([approved()])) + expect(text).not.toMatch(/agents can use/i) + expect(text).toMatch(/^Approved\. Not offered to agents yet\b/) + }) + it('unknown (the reload failed): a neutral "Approved."', async () => { + const text = await approveWith({ success: false, error: 'boom' }) + expect(text).not.toMatch(/agents/i) + expect(text).toMatch(/^Approved\.(\s|$)/) + }) + }) + it('a 409 review_out_of_date reloads the list and says nothing was approved, with no retry', async () => { m(api.getServerSkills).mockResolvedValueOnce(ok(makeListing([makeSkill('a', { current_hash: 'sk1-1' })]))) m(api.approveSkills).mockResolvedValue({ success: false, error: 'review_out_of_date: x', errorCode: 'review_out_of_date' }) diff --git a/scripts/run-skills-tab-sweep.sh b/scripts/run-skills-tab-sweep.sh index d295fd2e5..4de8de4bc 100755 --- a/scripts/run-skills-tab-sweep.sh +++ b/scripts/run-skills-tab-sweep.sh @@ -52,7 +52,10 @@ Options: reach the core (it starts one with all of them set to decoys and checks the database lands in the scratch dir only and no decoy is touched), that a data dir under - \$HOME/.mcpproxy is refused, that the results writer + \$HOME/.mcpproxy is refused, that the recorded PIDs + are the core and the fixture themselves and cleanup + leaves no process or listening port of the run alive + (and nothing else touched), that the results writer records the first failed attempt and redacts the API key and local paths, and that a DEBUG=1 run never prints the API key @@ -156,14 +159,43 @@ for (const [p, r] of paths) t = t.split(p).join(r) fs.writeFileSync(f, t)' "$1" } +# Prints $1 and every process descended from it (children first found by +# pgrep -P, recursively). +process_tree() { + local child + [[ -n "$1" ]] || return 0 + echo "$1" + for child in $(pgrep -P "$1" 2>/dev/null || true); do process_tree "$child"; done +} + +# Stops the core and the fixture this run started (CORE_PID, FIXTURE_PID) and +# every process descended from them, and nothing else: the tree is read before +# the first signal (a child of a stopped server is re-parented and would no +# longer be found), SIGTERM goes to the whole tree, and whatever of it is still +# alive after 15 s (the core's graceful shutdown) gets SIGKILL. +stop_started() { + local tree pid attempt alive + tree="$(process_tree "${CORE_PID:-}") $(process_tree "${FIXTURE_PID:-}")" + # The group's stderr also takes the shell's own "Terminated" job notices. + { + for pid in $tree; do kill "$pid" || true; done + for attempt in $(seq 1 150); do + alive="" + for pid in $tree; do kill -0 "$pid" && alive="$alive $pid"; done + [[ -z "$alive" ]] && break + sleep 0.1 + done + for pid in $alive; do kill -9 "$pid" || true; done + for pid in "${CORE_PID:-}" "${FIXTURE_PID:-}"; do + [[ -n "$pid" ]] && { wait "$pid" || true; } + done + } >/dev/null 2>&1 + CORE_PID="" + FIXTURE_PID="" +} + cleanup() { - local pid - for pid in "${CORE_PID:-}" "${FIXTURE_PID:-}"; do - if [[ -n "$pid" ]] && kill -0 "$pid" >/dev/null 2>&1; then - kill "$pid" >/dev/null 2>&1 || true - wait "$pid" >/dev/null 2>&1 || true - fi - done + stop_started if [[ -n "$OUT_REAL" ]]; then cp "$CORE_LOG" "$OUT_REAL/core.log" 2>/dev/null && redact_file "$OUT_REAL/core.log" cp "$FIXTURE_LOG" "$OUT_REAL/fixture.log" 2>/dev/null && redact_file "$OUT_REAL/fixture.log" @@ -223,12 +255,14 @@ JSON # explicitly by start_core. CORE_TMP="$WORK/tmp" mkdir -p "$CORE_TMP" -clean_env() { - env -i PATH="${PATH:-/usr/bin:/bin}" HOME="$CORE_HOME" TMPDIR="$CORE_TMP" "$@" -} +# An array, not a function: a backgrounded function runs in a subshell, so $! +# would be that shell's PID and stopping it would orphan the server. With the +# array, "${CLEAN_ENV[@]}" cmd ... & forks once and execs env, which execs cmd: +# $! is the server's own PID. +CLEAN_ENV=(env -i "PATH=${PATH:-/usr/bin:/bin}" "HOME=$CORE_HOME" "TMPDIR=$CORE_TMP") # Starts the core detached from the operator's data and environment: -# clean_env above, --data-dir (which wins over the file and the environment) +# CLEAN_ENV above, --data-dir (which wins over the file and the environment) # names the scratch dir, and HOME is a scratch home, so a default path can never # resolve to the operator's ~/.mcpproxy. $1: listen. start_core() { @@ -238,11 +272,31 @@ start_core() { exit 1 fi debug "starting the core on $listen (data dir: the scratch dir)" - clean_env HEADLESS=1 DO_NOT_TRACK=1 MCPPROXY_TELEMETRY=false MCPPROXY_API_KEY="$API_KEY" \ + "${CLEAN_ENV[@]}" HEADLESS=1 DO_NOT_TRACK=1 MCPPROXY_TELEMETRY=false MCPPROXY_API_KEY="$API_KEY" \ "$CORE_BIN" serve --config "$CONFIG_PATH" --data-dir "$DATA_DIR" --listen "$listen" >"$CORE_LOG" 2>&1 & CORE_PID=$! } +# Starts the fixture (FIXTURE_CMD, FIXTURE_URL) and waits for its /mcp. +start_fixture() { + local attempt + debug "starting skillsfixture on $FIXTURE_ADDR" + "${CLEAN_ENV[@]}" "${FIXTURE_CMD[@]}" >"$FIXTURE_LOG" 2>&1 & + FIXTURE_PID=$! + for attempt in $(seq 1 30); do + if curl -s --connect-timeout 1 --max-time 3 -o /dev/null -X POST -H 'Content-Type: application/json' \ + -d '{"jsonrpc":"2.0","id":1,"method":"skills/list"}' "$FIXTURE_URL/mcp"; then + return 0 + fi + if ! kill -0 "$FIXTURE_PID" >/dev/null 2>&1 || [[ $attempt -eq 30 ]]; then + echo "skillsfixture did not start on $FIXTURE_ADDR" >&2 + cat "$FIXTURE_LOG" >&2 + exit 1 + fi + sleep 0.5 + done +} + # Waits for the core's REST API; $1: base URL. wait_core() { local base="$1" attempt code @@ -381,9 +435,7 @@ run_self_test() { st_fail "the core wrote into the ambient data dir $d: $(ls -A "$d")" fi done - kill "$CORE_PID" >/dev/null 2>&1 || true - wait "$CORE_PID" >/dev/null 2>&1 || true - CORE_PID="" + stop_started echo "self-test: with MCPPROXY_DATA_DIR and MCPPROXY_DATA set to decoys, the core opened its database in the scratch dir only" # 2b. Nothing else of the operator's environment reaches the core either: @@ -401,6 +453,51 @@ run_self_test() { done echo "self-test: with MCPPROXY_AUDIT_LOG_PATH, MCPPROXY_TPA_BUNDLE_PATH and MCPPROXY_CERTS_DIR set to decoys, the core touched none of them" + # 2c. Cleanup stops what the run started, and only that. The recorded PIDs + # must be the core and the fixture themselves (not a shell around them, whose + # death would orphan the server), each must own its listening port, and after + # stop_started (what the EXIT trap runs) neither PID, no process descended + # from them, and neither port is alive, while an unrelated process of the + # same shell is left running. + local st_fx_port st_core_port tree pid want got bystander listener + st_fx_port=$(free_port) + FIXTURE_ADDR="127.0.0.1:${st_fx_port}" + FIXTURE_URL="http://${FIXTURE_ADDR}" + FIXTURE_CMD=("$FIXTURE_BIN" -addr "$FIXTURE_ADDR") + start_fixture + st_core_port=$(free_port) + write_config "127.0.0.1:${st_core_port}" "" + start_core "127.0.0.1:${st_core_port}" + wait_core "http://127.0.0.1:${st_core_port}" + sleep 30 & + bystander=$! + for pid in "$CORE_PID:$CORE_BIN:$st_core_port" "$FIXTURE_PID:$FIXTURE_BIN:$st_fx_port"; do + IFS=: read -r pid want st_port <<<"$pid" + want=$(basename "$want"); want=${want:0:15} + got=$(ps -o comm= -p "$pid" 2>/dev/null || true); got=$(basename "${got:-?}"); got=${got:0:15} + [[ "$got" == "$want" ]] || st_fail "the recorded PID $pid is '$got', not the $want process it started" + if command -v lsof >/dev/null 2>&1; then + listener=$(lsof -nP -iTCP:"$st_port" -sTCP:LISTEN -t 2>/dev/null | head -1 || true) + [[ "$listener" == "$pid" ]] || st_fail "port $st_port is held by PID '${listener}', not by the recorded PID $pid ($want)" + fi + done + tree="$(process_tree "$CORE_PID") $(process_tree "$FIXTURE_PID")" + stop_started + for pid in $tree; do + kill -0 "$pid" >/dev/null 2>&1 && st_fail "PID $pid ($(ps -o comm= -p "$pid" 2>/dev/null)) of the run is still alive after cleanup" + done + for st_port in "$st_core_port" "$st_fx_port"; do + set +e + curl -s --connect-timeout 1 --max-time 2 -o /dev/null "http://127.0.0.1:${st_port}/" + got=$? + set -e + [[ $got -eq 7 ]] || st_fail "port $st_port still answers after cleanup (curl exit $got)" + done + kill -0 "$bystander" >/dev/null 2>&1 || st_fail "cleanup killed a process it did not start" + kill "$bystander" >/dev/null 2>&1 || true + wait "$bystander" >/dev/null 2>&1 || true + echo "self-test: the recorded PIDs are the core and the fixture themselves; after cleanup no process of the run is alive and both ports are closed, an unrelated process is untouched" + # 3. The results writer: first failed attempt, redaction, provenance. st_out="$WORK/st-out" OUT_REAL="$st_out" @@ -449,7 +546,7 @@ if (r.checked_commit !== "0123456789abcdef0123456789abcdef01234567" || r.working if [[ -z "${SWEEP_SELF_TEST_CHILD:-}" ]]; then local probe_err="$WORK/debug-probe.stderr" probe_key="$WORK/debug-probe.key" probe_status set +e - DEBUG=1 SWEEP_SELF_TEST_CHILD="$probe_key" MCPPROXY_BINARY_PATH="$CORE_BIN" \ + DEBUG=1 SWEEP_SELF_TEST_CHILD="$probe_key" MCPPROXY_BINARY_PATH="$CORE_BIN" SKILLS_FIXTURE_BINARY="$FIXTURE_BIN" \ bash "$SCRIPT_DIR/$(basename "${BASH_SOURCE[0]}")" --self-test >/dev/null 2>"$probe_err" probe_status=$? set -e @@ -472,6 +569,12 @@ if [[ $SELF_TEST -eq 1 ]]; then CORE_BIN="$WORK/bin/mcpproxy" (cd "$REPO_ROOT" && go build -o "$CORE_BIN" ./cmd/mcpproxy) fi + FIXTURE_BIN="${SKILLS_FIXTURE_BINARY:-}" + if [[ -z "$FIXTURE_BIN" ]]; then + required go + FIXTURE_BIN="$WORK/bin/skillsfixture" + (cd "$REPO_ROOT" && go build -o "$FIXTURE_BIN" ./cmd/skillsfixture) + fi run_self_test exit 0 fi @@ -524,21 +627,7 @@ FIXTURE_PORT=$(free_port) FIXTURE_ADDR="127.0.0.1:${FIXTURE_PORT}" FIXTURE_URL="http://${FIXTURE_ADDR}" FIXTURE_CMD=("$FIXTURE_BIN" -addr "$FIXTURE_ADDR") -debug "starting skillsfixture on $FIXTURE_ADDR" -clean_env "${FIXTURE_CMD[@]}" >"$FIXTURE_LOG" 2>&1 & -FIXTURE_PID=$! -for attempt in $(seq 1 30); do - if curl -s --connect-timeout 1 --max-time 3 -o /dev/null -X POST -H 'Content-Type: application/json' \ - -d '{"jsonrpc":"2.0","id":1,"method":"skills/list"}' "$FIXTURE_URL/mcp"; then - break - fi - if ! kill -0 "$FIXTURE_PID" >/dev/null 2>&1 || [[ $attempt -eq 30 ]]; then - echo "skillsfixture did not start on $FIXTURE_ADDR" >&2 - cat "$FIXTURE_LOG" >&2 - exit 1 - fi - sleep 0.5 -done +start_fixture echo "skillsfixture ready at $FIXTURE_URL" # --- core ------------------------------------------------------------------- @@ -652,7 +741,7 @@ const shotNote = shots => (!withShots && shots.length) // One section per scenario, in spec order, with what it proves and its screenshots. const about = [ ['Tab and list', 'The Skills tab is offered on a server with enable_skills on and a skills-capable upstream (cmd/skillsfixture, manual trust). The three skills show as Awaiting review and Not offered.', ['01-list']], - ['Viewer and paging', 'SKILL.md opens in the text viewer (inert text). A 150 KiB file is read part by part: each Load more waits for its content response and the rendered text, every part carries the digest listed on screen, and the last part has no next_offset. A binary file (logo.bin) is listed as binary, not shown, with no View button.', ['02-viewer', '03-paged']], + ['Viewer and paging', 'SKILL.md opens in the text viewer (inert text). A 150 KiB file (data/large.txt of big) is read part by part in at least three parts: each Load more waits for its content response and for the rendered text to grow by that part. Every part is of the current copy, its digest equals the digest the core lists for that file in the current copy (the same digest the file row shows on screen), its size equals the listed size, its offset is where the previous part ended (in bytes, the first at 0) and its next_offset is where it ends; the last part has no next_offset and ends at the listed size. A binary file (logo.bin) is listed as binary, not shown, with no View button.', ['02-viewer', '03-paged']], ['Approve', 'Approve sends the current_hash and incarnation of the version the reviewer opened; the chip turns Approved.', ['04-approved']], ['Changed while open, re-open, diff', 'A mutate without the X-Skills-Fixture header is refused (403). The approved skill plain changes upstream while it is open; after Refresh the chip says Changed and the open review says it changed while you were reviewing it (the review shows the approved version, so it offers no Approve). Re-opening shows the file-set diff (SKILL.md changed) and the line diff with the added line; approving binds the new hash.', ['05a-stale', '05-changed-diff']], ['Pending skill changed while open', 'The pending skill with-files changes upstream while it is open; after Refresh the review is marked stale and its Approve button stays on screen but disabled, until the new version is re-opened.', ['05b-pending-stale']], From 046fc174fc130e724ce57693df2935ebaa4ea26c Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Fri, 20 Nov 2026 12:34:52 +0200 Subject: [PATCH 05/18] docs(skills): browser sweep evidence for d10ee8b67 Related #1895 --- .../verification/report.html | 24 ++++---- .../verification/skills-sweep-results.json | 55 +++++++++++++------ 2 files changed, 50 insertions(+), 29 deletions(-) diff --git a/specs/125-skills-over-mcp/verification/report.html b/specs/125-skills-over-mcp/verification/report.html index 0a578acbb..5d31be6d6 100644 --- a/specs/125-skills-over-mcp/verification/report.html +++ b/specs/125-skills-over-mcp/verification/report.html @@ -1,20 +1,22 @@ Spec 125 Skills tab verification

Spec 125: Skills tab (PR-4a) Playwright verification

-
6 of 6 scenarios passed, 2026-11-18, produced by scripts/run-skills-tab-sweep.sh from working tree on top of 6370f1f45e05cec3b095da62bddcd6a0d4bfb025.
-A throwaway core (127.0.0.1:64512, scratch data dir, enable_skills: true, generated API key) served the embedded frontend; the upstream skillsfx (trust_mode: manual) was skillsfixture -addr 127.0.0.1:64492 on port 64492.
-Spec: e2e/web-ui-sweep/skills-tab.spec.ts. Results file: skills-sweep-results.json. Repeat: ./scripts/run-skills-tab-sweep.sh --report-html specs/125-skills-over-mcp/verification/report.html.
-
1. Tab and list PASS

the Skills tab lists the fixture skills as awaiting review

The Skills tab is offered on a server with enable_skills on and a skills-capable upstream (cmd/skillsfixture, manual trust). The three skills show as Awaiting review and Not offered.

01-list
-
2. Viewer and paging PASS

views SKILL.md, pages a large file, and does not offer a binary file

SKILL.md opens in the text viewer (inert text). A 150 KiB file is read part by part: each Load more waits for its content response and the rendered text, every part carries the digest listed on screen, and the last part has no next_offset. A binary file (logo.bin) is listed as binary, not shown, with no View button.

02-viewer03-paged
-
3. Approve PASS

approve turns the chip to Approved

Approve sends the current_hash and incarnation of the version the reviewer opened; the chip turns Approved.

04-approved
-
4. Changed while open, re-open, diff PASS

an upstream change plus Refresh shows Changed with a file diff and a line diff

A mutate without the X-Skills-Fixture header is refused (403). The upstream bytes change while the skill is open; after Refresh the chip says Changed and the open review says it changed while you were reviewing it. Re-opening shows the file-set diff (SKILL.md changed) and the line diff with the added line; approving binds the new hash.

05a-stale05-changed-diff
-
5. Block and unblock PASS

block and unblock

Block marks the skill Blocked and removes Approve; Unblock returns it to Awaiting review.

06-blocked
-
6. Reload PASS

the tab survives a reload through ?tab=skills and no page error was thrown

The tab survives a reload through ?tab=skills, and no uncaught page error was thrown in any scenario.

+
8 of 8 scenarios passed, 2026-11-20, produced by scripts/run-skills-tab-sweep.sh from commit d10ee8b6706624e6ed1211d8fbde3c36b7f92014 (working tree clean).
+A throwaway core (127.0.0.1:60072, scratch data dir, enable_skills: true, generated API key) served the embedded frontend; the upstream skillsfx (trust_mode: manual) was skillsfixture -addr 127.0.0.1:60070 on port 60070.
+Spec: e2e/web-ui-sweep/skills-tab.spec.ts. Results file: skills-sweep-results.json. Repeat: ./scripts/run-skills-tab-sweep.sh --report-html specs/125-skills-over-mcp/verification/report.html --no-screenshots.
+
1. Tab and list PASS

the Skills tab lists the fixture skills as awaiting review

The Skills tab is offered on a server with enable_skills on and a skills-capable upstream (cmd/skillsfixture, manual trust). The three skills show as Awaiting review and Not offered.

Screenshots (not embedded in this copy): screenshots/skills-tab-01-list.png

+
2. Viewer and paging PASS

views SKILL.md, pages a large file, and does not offer a binary file

SKILL.md opens in the text viewer (inert text). A 150 KiB file (data/large.txt of big) is read part by part in at least three parts: each Load more waits for its content response and for the rendered text to grow by that part. Every part is of the current copy, its digest equals the digest the core lists for that file in the current copy (the same digest the file row shows on screen), its size equals the listed size, its offset is where the previous part ended (in bytes, the first at 0) and its next_offset is where it ends; the last part has no next_offset and ends at the listed size. A binary file (logo.bin) is listed as binary, not shown, with no View button.

Screenshots (not embedded in this copy): screenshots/skills-tab-02-viewer.png, screenshots/skills-tab-03-paged.png

+
3. Approve PASS

approve turns the chip to Approved

Approve sends the current_hash and incarnation of the version the reviewer opened; the chip turns Approved.

Screenshots (not embedded in this copy): screenshots/skills-tab-04-approved.png

+
4. Changed while open, re-open, diff PASS

an upstream change plus Refresh shows Changed with a file diff and a line diff

A mutate without the X-Skills-Fixture header is refused (403). The approved skill plain changes upstream while it is open; after Refresh the chip says Changed and the open review says it changed while you were reviewing it (the review shows the approved version, so it offers no Approve). Re-opening shows the file-set diff (SKILL.md changed) and the line diff with the added line; approving binds the new hash.

Screenshots (not embedded in this copy): screenshots/skills-tab-05a-stale.png, screenshots/skills-tab-05-changed-diff.png

+
5. Pending skill changed while open PASS

a pending skill changed while open is stale, with Approve disabled until re-opened

The pending skill with-files changes upstream while it is open; after Refresh the review is marked stale and its Approve button stays on screen but disabled, until the new version is re-opened.

Screenshots (not embedded in this copy): screenshots/skills-tab-05b-pending-stale.png

+
6. Live skills.changed PASS

a refresh through the REST API marks the open review stale by the live event alone

With the pending skill big open, its SKILL.md changes upstream and the refresh is made through POST /api/v1/servers/{id}/skills/refresh, not in the page. The core's skills.changed SSE frame, re-dispatched by the Web UI, reloads the listing by itself and the open review shows the stale banner with Approve disabled.

Screenshots (not embedded in this copy): screenshots/skills-tab-05c-live-event-stale.png

+
7. Block and unblock PASS

block and unblock

Block marks the skill Blocked and removes Approve; Unblock returns it to Awaiting review.

Screenshots (not embedded in this copy): screenshots/skills-tab-06-blocked.png

+
8. Reload PASS

the tab survives a reload through ?tab=skills and no page error was thrown

The tab survives a reload through ?tab=skills, and no uncaught page error was thrown in any scenario.

Skill records read back from GET /api/v1/servers/skillsfx/skills -

After approve

skillstatusblockedavailablecurrent_hashapproved_hash
bigpendingfalsefalsesk1-e546542d22642918aeab759cd6ebd414e007f0e78e7597a568a737ec3ebda041
plainapprovedfalsetruesk1-b23404c9e4197b2f0f05125a948ce5f69b6b011ed9a8abcf1b9f8a63f04eaff7sk1-b23404c9e4197b2f0f05125a948ce5f69b6b011ed9a8abcf1b9f8a63f04eaff7
with-filespendingfalsefalsesk1-11bf1bd99f40de60b2ebb00ea7d54be85ce487d61abcea4e7c14f725168097e3

After approving the change

skillstatusblockedavailablecurrent_hashapproved_hash
bigpendingfalsefalsesk1-e546542d22642918aeab759cd6ebd414e007f0e78e7597a568a737ec3ebda041
plainapprovedfalsetruesk1-03097acd9229c426c9b900e1e7a08d63d52b89d512708a8ed3235a80c79ff8b5sk1-03097acd9229c426c9b900e1e7a08d63d52b89d512708a8ed3235a80c79ff8b5
with-filespendingfalsefalsesk1-11bf1bd99f40de60b2ebb00ea7d54be85ce487d61abcea4e7c14f725168097e3

After block

skillstatusblockedavailablecurrent_hashapproved_hash
bigpendingfalsefalsesk1-e546542d22642918aeab759cd6ebd414e007f0e78e7597a568a737ec3ebda041
plainapprovedfalsetruesk1-03097acd9229c426c9b900e1e7a08d63d52b89d512708a8ed3235a80c79ff8b5sk1-03097acd9229c426c9b900e1e7a08d63d52b89d512708a8ed3235a80c79ff8b5
with-filespendingtruefalsesk1-11bf1bd99f40de60b2ebb00ea7d54be85ce487d61abcea4e7c14f725168097e3

After unblock

skillstatusblockedavailablecurrent_hashapproved_hash
bigpendingfalsefalsesk1-e546542d22642918aeab759cd6ebd414e007f0e78e7597a568a737ec3ebda041
plainapprovedfalsetruesk1-03097acd9229c426c9b900e1e7a08d63d52b89d512708a8ed3235a80c79ff8b5sk1-03097acd9229c426c9b900e1e7a08d63d52b89d512708a8ed3235a80c79ff8b5
with-filespendingfalsefalsesk1-11bf1bd99f40de60b2ebb00ea7d54be85ce487d61abcea4e7c14f725168097e3
+

After approve

skillstatusblockedavailablecurrent_hashapproved_hash
bigpendingfalsefalsesk1-e546542d22642918aeab759cd6ebd414e007f0e78e7597a568a737ec3ebda041
plainapprovedfalsetruesk1-b23404c9e4197b2f0f05125a948ce5f69b6b011ed9a8abcf1b9f8a63f04eaff7sk1-b23404c9e4197b2f0f05125a948ce5f69b6b011ed9a8abcf1b9f8a63f04eaff7
with-filespendingfalsefalsesk1-11bf1bd99f40de60b2ebb00ea7d54be85ce487d61abcea4e7c14f725168097e3

After approving the change

skillstatusblockedavailablecurrent_hashapproved_hash
bigpendingfalsefalsesk1-e546542d22642918aeab759cd6ebd414e007f0e78e7597a568a737ec3ebda041
plainapprovedfalsetruesk1-03097acd9229c426c9b900e1e7a08d63d52b89d512708a8ed3235a80c79ff8b5sk1-03097acd9229c426c9b900e1e7a08d63d52b89d512708a8ed3235a80c79ff8b5
with-filespendingfalsefalsesk1-11bf1bd99f40de60b2ebb00ea7d54be85ce487d61abcea4e7c14f725168097e3

After block

skillstatusblockedavailablecurrent_hashapproved_hash
bigpendingfalsefalsesk1-1c78d19e9aee62b7cdb33fccb285107beaa369ea754f66d43f3538a0367a9949
plainapprovedfalsetruesk1-03097acd9229c426c9b900e1e7a08d63d52b89d512708a8ed3235a80c79ff8b5sk1-03097acd9229c426c9b900e1e7a08d63d52b89d512708a8ed3235a80c79ff8b5
with-filespendingtruefalsesk1-58734ade9dd0562aade1f395b623dffbd7caad4b9c2b72d23cc6cafbde76648c

After unblock

skillstatusblockedavailablecurrent_hashapproved_hash
bigpendingfalsefalsesk1-1c78d19e9aee62b7cdb33fccb285107beaa369ea754f66d43f3538a0367a9949
plainapprovedfalsetruesk1-03097acd9229c426c9b900e1e7a08d63d52b89d512708a8ed3235a80c79ff8b5sk1-03097acd9229c426c9b900e1e7a08d63d52b89d512708a8ed3235a80c79ff8b5
with-filespendingfalsefalsesk1-58734ade9dd0562aade1f395b623dffbd7caad4b9c2b72d23cc6cafbde76648c
diff --git a/specs/125-skills-over-mcp/verification/skills-sweep-results.json b/specs/125-skills-over-mcp/verification/skills-sweep-results.json index 80a94aa73..5d118c0db 100644 --- a/specs/125-skills-over-mcp/verification/skills-sweep-results.json +++ b/specs/125-skills-over-mcp/verification/skills-sweep-results.json @@ -1,18 +1,19 @@ { - "checked_commit": "6370f1f45e05cec3b095da62bddcd6a0d4bfb025", - "working_tree_dirty": true, - "checked": "working tree on top of 6370f1f45e05cec3b095da62bddcd6a0d4bfb025", - "generated_at": "2026-11-18T12:54:51.927Z", + "checked_commit": "d10ee8b6706624e6ed1211d8fbde3c36b7f92014", + "working_tree_dirty": false, + "evidence": "commit", + "checked": "d10ee8b6706624e6ed1211d8fbde3c36b7f92014", + "generated_at": "2026-11-20T10:34:36.753Z", "fixture": { "command": [ - "/var/folders/4g/2h26g7ks4fg23brxvvj6p6hr0000gn/T//skills-sweep.K6rjBB/bin/skillsfixture", + "skillsfixture", "-addr", - "127.0.0.1:64492" + "127.0.0.1:60070" ], - "port": 64492 + "port": 60070 }, "core": { - "listen": "127.0.0.1:64512", + "listen": "127.0.0.1:60072", "server": "skillsfx", "enable_skills": true, "trust_mode": "manual" @@ -22,32 +23,50 @@ { "title": "the Skills tab lists the fixture skills as awaiting review", "passed": true, - "status": "passed" + "status": "passed", + "attempts": 1 }, { "title": "views SKILL.md, pages a large file, and does not offer a binary file", "passed": true, - "status": "passed" + "status": "passed", + "attempts": 1 }, { "title": "approve turns the chip to Approved", "passed": true, - "status": "passed" + "status": "passed", + "attempts": 1 }, { "title": "an upstream change plus Refresh shows Changed with a file diff and a line diff", "passed": true, - "status": "passed" + "status": "passed", + "attempts": 1 + }, + { + "title": "a pending skill changed while open is stale, with Approve disabled until re-opened", + "passed": true, + "status": "passed", + "attempts": 1 + }, + { + "title": "a refresh through the REST API marks the open review stale by the live event alone", + "passed": true, + "status": "passed", + "attempts": 1 }, { "title": "block and unblock", "passed": true, - "status": "passed" + "status": "passed", + "attempts": 1 }, { "title": "the tab survives a reload through ?tab=skills and no page error was thrown", "passed": true, - "status": "passed" + "status": "passed", + "attempts": 1 } ], "states": { @@ -117,7 +136,7 @@ "status": "pending", "blocked": false, "available": false, - "current_hash": "sk1-e546542d22642918aeab759cd6ebd414e007f0e78e7597a568a737ec3ebda041", + "current_hash": "sk1-1c78d19e9aee62b7cdb33fccb285107beaa369ea754f66d43f3538a0367a9949", "approved_hash": "" }, { @@ -133,7 +152,7 @@ "status": "pending", "blocked": true, "available": false, - "current_hash": "sk1-11bf1bd99f40de60b2ebb00ea7d54be85ce487d61abcea4e7c14f725168097e3", + "current_hash": "sk1-58734ade9dd0562aade1f395b623dffbd7caad4b9c2b72d23cc6cafbde76648c", "approved_hash": "" } ] @@ -146,7 +165,7 @@ "status": "pending", "blocked": false, "available": false, - "current_hash": "sk1-e546542d22642918aeab759cd6ebd414e007f0e78e7597a568a737ec3ebda041", + "current_hash": "sk1-1c78d19e9aee62b7cdb33fccb285107beaa369ea754f66d43f3538a0367a9949", "approved_hash": "" }, { @@ -162,7 +181,7 @@ "status": "pending", "blocked": false, "available": false, - "current_hash": "sk1-11bf1bd99f40de60b2ebb00ea7d54be85ce487d61abcea4e7c14f725168097e3", + "current_hash": "sk1-58734ade9dd0562aade1f395b623dffbd7caad4b9c2b72d23cc6cafbde76648c", "approved_hash": "" } ] From f1889571e465798fdf48d9c3625fe57a902db3c2 Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Fri, 20 Nov 2026 12:52:19 +0200 Subject: [PATCH 06/18] fix(skills): review round 5 for the Skills tab and its sweep - SkillsPanel: refresh() takes its place in the request order when it starts (seq = ++requestSeq, alongside its own refreshSeq for the button). Its listing is applied only while it is still the newest request; a superseded refresh reloads instead, so a late refresh answer never overwrites a newer listing applied by a load that started later. - SkillsPanel: stale latch. An approve 409 review_out_of_date / server_replaced for the open review, and SkillDetail's content-changed (viewer digest/offset mismatch, line-diff part of another version), mark the open review stale synchronously, before the reload. Only an explicit re-open clears it, so a pending or failed reload never re-enables Approve (disabled while stale, banner shown). - run-skills-tab-sweep.sh: printed paths go through say_path (relative to the repo root, else ///~), the fixture and core log dumps on a startup failure, server responses and st_fail messages go through redact_stream (the same redactor as redact_file). The self-test checks the stdout and stderr of a passing DEBUG=1 run and of a forced fixture and core startup failure for the API key (plain and URL-encoded) and for absolute paths under the scratch dirs and home. - Tests: deferred refresh/load ordering; each stale signal followed by a pending and by a failed reload; a late 409 for a review the reviewer left does not mark the new one. Related #1895 --- docs/development/web-ui-verification.md | 2 +- .../src/components/skills/SkillsPanel.vue | 36 ++++- frontend/tests/unit/skills-panel.spec.ts | 101 ++++++++++++- scripts/run-skills-tab-sweep.sh | 139 +++++++++++++----- 4 files changed, 236 insertions(+), 42 deletions(-) diff --git a/docs/development/web-ui-verification.md b/docs/development/web-ui-verification.md index c43ed6e73..45171cacc 100644 --- a/docs/development/web-ui-verification.md +++ b/docs/development/web-ui-verification.md @@ -40,7 +40,7 @@ Alongside it, [`e2e/web-ui-sweep/visual-a11y-sweep.spec.ts`](https://github.com/ ./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 has the API key replaced by `***` and local paths by ``, ``, `` or `~`. 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. +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); `--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. diff --git a/frontend/src/components/skills/SkillsPanel.vue b/frontend/src/components/skills/SkillsPanel.vue index e0cf182f4..93bd5cd4a 100644 --- a/frontend/src/components/skills/SkillsPanel.vue +++ b/frontend/src/components/skills/SkillsPanel.vue @@ -75,7 +75,7 @@ @approve="approve()" @block="setBlocked(true)" @unblock="setBlocked(false)" - @content-changed="load" + @content-changed="onContentChanged" /> @@ -117,6 +117,19 @@ function open(s: SkillEntry) { review.value = { path: s.path, entry: s, incarnation: listing.value?.incarnation ?? 0, token: ++reviewToken, stale: false } } +// The latch: once set, only open() (the reviewer's explicit re-open) clears it; +// apply() never does. +const STALE_CODES = new Set(['review_out_of_date', 'server_replaced']) +function markStale(token: number | undefined) { + if (review.value && review.value.token === token) review.value.stale = true +} + +// SkillDetail read a part of another version: the open review is out of date. +function onContentChanged() { + markStale(review.value?.token) + void load() +} + function chipClass(s: SkillEntry) { return `badge-${({ error: 'error', warning: 'warning', info: 'info', success: 'success', neutral: 'ghost' })[skillStateChip(s).tone]}` } @@ -166,15 +179,23 @@ async function load(): Promise { } // One refresh in flight per visit: a late answer of an earlier one never -// resets the button of a newer one. +// resets the button of a newer one. A refresh takes its place in the request +// order when it starts (like load()): its listing is applied only while it is +// still the newest request; a load that started later and answered first has +// newer records, so a superseded refresh reloads instead of overwriting them. let refreshSeq = 0 async function refresh() { - const server = props.serverName, v = visit, mine = ++refreshSeq + const server = props.serverName, v = visit, mine = ++refreshSeq, seq = ++requestSeq refreshing.value = true const res = await settle(() => api.refreshServerSkills(server)) if (!isCurrent(server, v) || mine !== refreshSeq) return refreshing.value = false - if (res.success && res.data) { requestSeq++; apply(res.data); return } + if (res.success && res.data) { + if (!isCurrent(server, v, seq)) { await load(); return } + loading.value = false + apply(res.data) + return + } // A failed refresh (refresh_superseded, skills_not_supported, skills_disabled, // server_replaced, a 500) reloads the listing: the notice says it was reloaded, // and the stored records may have moved even though this refresh did not apply. @@ -196,7 +217,12 @@ async function write(run: () => Promise<{ success: boolean; error?: string; erro if (!isCurrent(server, v)) return busy.value = false if (!res.success || typeof done === 'string') { - if (review.value?.token === token) notice.value = res.success ? done as string : skillErrorNotice(res.errorCode, res.error) + if (review.value?.token === token) { + notice.value = res.success ? done as string : skillErrorNotice(res.errorCode, res.error) + // The server says the open version is out of date: latch it before the + // reload, so a reload that is pending or fails never re-enables Approve. + if (!res.success && STALE_CODES.has(res.errorCode ?? '')) markStale(token) + } await load() return } diff --git a/frontend/tests/unit/skills-panel.spec.ts b/frontend/tests/unit/skills-panel.spec.ts index 1bd0749b9..b0bcc6b07 100644 --- a/frontend/tests/unit/skills-panel.spec.ts +++ b/frontend/tests/unit/skills-panel.spec.ts @@ -3,7 +3,7 @@ import { flushPromises, mount } from '@vue/test-utils' import SkillsPanel from '@/components/skills/SkillsPanel.vue' import api from '@/services/api' import { createPinia, setActivePinia } from 'pinia' -import { connectSkillsSSE, makeListing, makeSkill, ok } from './fixtures/skills125' +import { connectSkillsSSE, makeListing, makeSkill, ok, skillFile } from './fixtures/skills125' vi.mock('@/services/api', () => ({ default: { getServerSkills: vi.fn(), refreshServerSkills: vi.fn(), getSkillContent: vi.fn(), @@ -419,4 +419,103 @@ describe('SkillsPanel', () => { failRefresh(new Error('net')); await flushPromises() expect(w.get('[data-test="skills-refresh"]').attributes('disabled')).toBeUndefined() }) + + // Round-5 finding 1: a refresh takes its place in the request order when it + // starts, so a load that started later and answered first is never overwritten. + it('a late refresh answer never overwrites a newer listing applied by a later load', async () => { + m(api.getServerSkills).mockResolvedValueOnce(ok(makeListing([makeSkill('a')]))) + const w = mountPanel(); await flushPromises() + let releaseRefresh: (v: unknown) => void = () => {} + m(api.refreshServerSkills).mockReturnValueOnce(new Promise(r => { releaseRefresh = r })) + await w.get('[data-test="skills-refresh"]').trigger('click'); await flushPromises() + let releaseLoad: (v: unknown) => void = () => {} + m(api.getServerSkills).mockReturnValueOnce(new Promise(r => { releaseLoad = r })) + emitSkillsChanged('srv'); await flushPromises() + releaseLoad(ok(makeListing([makeSkill('a'), makeSkill('newer_b')]))); await flushPromises() + expect(w.find('[data-test="skill-row-newer_b"]').exists()).toBe(true) + // The follow-up load the superseded refresh asks for is still in flight. + m(api.getServerSkills).mockReturnValue(new Promise(() => {})) + releaseRefresh(ok(makeListing([makeSkill('a'), makeSkill('older_a')]))); await flushPromises() + expect(w.find('[data-test="skill-row-newer_b"]').exists()).toBe(true) + expect(w.find('[data-test="skill-row-older_a"]').exists()).toBe(false) + expect(w.get('[data-test="skills-refresh"]').attributes('disabled')).toBeUndefined() + expect(api.getServerSkills).toHaveBeenCalledTimes(3) + }) + + it('a refresh that is still the newest request applies its listing', async () => { + m(api.getServerSkills).mockResolvedValueOnce(ok(makeListing([makeSkill('a')]))) + const w = mountPanel(); await flushPromises() + let releaseRefresh: (v: unknown) => void = () => {} + m(api.refreshServerSkills).mockReturnValueOnce(new Promise(r => { releaseRefresh = r })) + await w.get('[data-test="skills-refresh"]').trigger('click'); await flushPromises() + releaseRefresh(ok(makeListing([makeSkill('a'), makeSkill('fresh')]))); await flushPromises() + expect(w.find('[data-test="skill-row-fresh"]').exists()).toBe(true) + expect(api.getServerSkills).toHaveBeenCalledTimes(1) + }) + + // Round-5 finding 2: a signal that the open version is out of date marks the + // review stale at once; a reload that is pending or fails never re-enables Approve. + describe('stale latch', () => { + const changedSkill = () => makeSkill('a', { + status: 'changed', approved_hash: 'sk1-old', + approved_files: [skillFile('SKILL.md', 'sha256:appr', 5)], files: [skillFile('SKILL.md', 'sha256:cur', 5)], + }) + const signals: Array<[string, (w: ReturnType) => Promise]> = [ + ['approve 409 review_out_of_date', async w => { + m(api.approveSkills).mockResolvedValueOnce({ success: false, error: 'review_out_of_date: x', errorCode: 'review_out_of_date' }) + await w.get('[data-test="skill-approve"]').trigger('click'); await flushPromises() + }], + ['approve 409 server_replaced', async w => { + m(api.approveSkills).mockResolvedValueOnce({ success: false, error: 'server_replaced: x', errorCode: 'server_replaced' }) + await w.get('[data-test="skill-approve"]').trigger('click'); await flushPromises() + }], + ['a viewer part of another version', async w => { + m(api.getSkillContent).mockResolvedValue(ok({ text: 'x', offset: 0, size: 1, digest: 'sha256:moved' })) + await w.get('[data-test="skill-view-SKILL.md"]').trigger('click'); await flushPromises() + }], + ['a line-diff part of another version', async w => { + m(api.getSkillContent).mockResolvedValue(ok({ text: 'x', offset: 0, size: 1, digest: 'sha256:moved' })) + await w.get('[data-test="skill-line-diff-SKILL.md"]').trigger('click'); await flushPromises() + }], + ] + const reloads: Array<[string, () => unknown]> = [ + ['pending', () => new Promise(() => {})], + ['failed', () => Promise.resolve({ success: false, error: 'reload boom' })], + ] + for (const [signal, fire] of signals) { + for (const [outcome, reload] of reloads) { + it(`${signal}, reload ${outcome}: Approve stays off and the banner shows until re-open`, async () => { + m(api.getServerSkills).mockResolvedValueOnce(ok(makeListing([changedSkill()]))) + const w = mountPanel(); await flushPromises() + await w.get('[data-test="skill-row-a"]').trigger('click'); await flushPromises() + expect(w.get('[data-test="skill-approve"]').attributes('disabled')).toBeUndefined() + m(api.getServerSkills).mockImplementation(reload) + await fire(w) + expect(api.getServerSkills).toHaveBeenCalledTimes(2) + expect(w.find('[data-test="skill-stale"]').exists()).toBe(true) + expect(w.get('[data-test="skill-approve"]').attributes('disabled')).toBeDefined() + const calls = m(api.approveSkills).mock.calls.length + await w.get('[data-test="skill-approve"]').trigger('click'); await flushPromises() + expect(m(api.approveSkills).mock.calls.length).toBe(calls) + // Re-opening is the reviewer's explicit step: it clears the latch. + await w.get('[data-test="skill-row-a"]').trigger('click'); await flushPromises() + expect(w.find('[data-test="skill-stale"]').exists()).toBe(false) + expect(w.get('[data-test="skill-approve"]').attributes('disabled')).toBeUndefined() + }) + } + } + + it('a stale signal for a review the reviewer has left does not mark the new one', async () => { + m(api.getServerSkills).mockResolvedValue(ok(makeListing([makeSkill('a'), makeSkill('b')]))) + let release: (v: unknown) => void = () => {} + m(api.approveSkills).mockReturnValueOnce(new Promise(r => { release = r })) + const w = mountPanel(); await flushPromises() + await w.get('[data-test="skill-row-a"]').trigger('click'); await flushPromises() + await w.get('[data-test="skill-approve"]').trigger('click'); await flushPromises() + await w.get('[data-test="skill-row-b"]').trigger('click'); await flushPromises() + release({ success: false, error: 'review_out_of_date: x', errorCode: 'review_out_of_date' }); await flushPromises() + expect(w.find('[data-test="skill-stale"]').exists()).toBe(false) + expect(w.get('[data-test="skill-approve"]').attributes('disabled')).toBeUndefined() + }) + }) }) diff --git a/scripts/run-skills-tab-sweep.sh b/scripts/run-skills-tab-sweep.sh index 4de8de4bc..baac32f3c 100755 --- a/scripts/run-skills-tab-sweep.sh +++ b/scripts/run-skills-tab-sweep.sh @@ -57,8 +57,9 @@ Options: leaves no process or listening port of the run alive (and nothing else touched), that the results writer records the first failed attempt and redacts the API key - and local paths, and that a DEBUG=1 run never prints the - API key + and local paths, and that neither a passing DEBUG=1 run + nor a run whose fixture or core fails to start prints + the API key or an absolute local path --self-test-first run the --self-test checks, then the sweep (the release gate does this, so both land in one advisory entry) -h, --help print this message @@ -142,21 +143,43 @@ if [[ ${#API_KEY} -lt 32 ]]; then exit 1 fi -# Every text file this script leaves behind goes through redact_file: the API -# key becomes *** and the local paths become placeholders. Set once OUT is known. +# Self-test hook: a child run of --self-test hands its key and its scratch dir +# to the parent (a scratch file of the parent's), which checks the child's +# output for both. +if [[ -n "${SWEEP_SELF_TEST_CHILD:-}" ]]; then printf '%s\n%s\n' "$API_KEY" "$WORK" >"$SWEEP_SELF_TEST_CHILD"; fi + +# Every text file this script leaves behind goes through redact_file, and every +# message it prints that can carry a path or a log through redact_stream: the +# API key becomes *** and the local paths become placeholders. OUT_REAL is set +# once OUT is known. OUT_REAL="" -redact_file() { - [[ -f "$1" ]] || return 0 - SWEEP_REDACT_KEY="$API_KEY" SWEEP_REDACT_OUT="$OUT_REAL" SWEEP_REDACT_REPO="$REPO_ROOT" \ - SWEEP_REDACT_WORK="$WORK" SWEEP_REDACT_HOME="$OPERATOR_HOME" node -e ' +# shellcheck disable=SC2016 # JavaScript, expanded by node +REDACT_JS=' const fs = require("fs"), f = process.argv[1], e = process.env -let t = fs.readFileSync(f, "utf8") +let t = f ? fs.readFileSync(f, "utf8") : fs.readFileSync(0, "utf8") const key = e.SWEEP_REDACT_KEY if (key) for (const k of [key, encodeURIComponent(key)]) t = t.split(k).join("***") const paths = [[e.SWEEP_REDACT_OUT, ""], [e.SWEEP_REDACT_WORK, ""], [e.SWEEP_REDACT_REPO, ""], [e.SWEEP_REDACT_HOME, "~"]] .filter(([p]) => p && p.length > 1).sort((a, b) => b[0].length - a[0].length) for (const [p, r] of paths) t = t.split(p).join(r) -fs.writeFileSync(f, t)' "$1" +if (f) fs.writeFileSync(f, t); else process.stdout.write(t)' +redact_node() { + SWEEP_REDACT_KEY="$API_KEY" SWEEP_REDACT_OUT="$OUT_REAL" SWEEP_REDACT_REPO="$REPO_ROOT" \ + SWEEP_REDACT_WORK="$WORK" SWEEP_REDACT_HOME="$OPERATOR_HOME" node -e "$REDACT_JS" "$@" +} +redact_file() { + [[ -f "$1" ]] || return 0 + redact_node "$1" +} +# Copies stdin to stdout, redacted. +redact_stream() { redact_node; } +# A path as printed: relative to the repo root when it is inside it, else with +# the placeholders of redact_stream. +say_path() { + case "$1" in + "$REPO_ROOT"/*) printf '%s' "${1#"$REPO_ROOT"/}" ;; + *) printf '%s' "$1" | redact_stream ;; + esac } # Prints $1 and every process descended from it (children first found by @@ -268,7 +291,7 @@ CLEAN_ENV=(env -i "PATH=${PATH:-/usr/bin:/bin}" "HOME=$CORE_HOME" "TMPDIR=$CORE_ start_core() { local listen="$1" if ! data_dir_allowed "$DATA_DIR"; then - echo "refusing to start: data dir $DATA_DIR is under $OPERATOR_HOME/.mcpproxy" >&2 + echo "refusing to start: data dir $(say_path "$DATA_DIR") is under ~/.mcpproxy" >&2 exit 1 fi debug "starting the core on $listen (data dir: the scratch dir)" @@ -290,7 +313,7 @@ start_fixture() { fi if ! kill -0 "$FIXTURE_PID" >/dev/null 2>&1 || [[ $attempt -eq 30 ]]; then echo "skillsfixture did not start on $FIXTURE_ADDR" >&2 - cat "$FIXTURE_LOG" >&2 + redact_stream <"$FIXTURE_LOG" >&2 exit 1 fi sleep 0.5 @@ -305,7 +328,7 @@ wait_core() { [[ "$code" == "200" ]] && return 0 if ! kill -0 "$CORE_PID" >/dev/null 2>&1 || [[ $attempt -eq 60 ]]; then echo "core did not become ready at $base" >&2 - cat "$CORE_LOG" >&2 + redact_stream <"$CORE_LOG" >&2 exit 1 fi sleep 1 @@ -315,7 +338,7 @@ wait_core() { # The core opened its database in the scratch dir, and only there. check_core_data_dir() { if [[ ! -f "$DATA_DIR/config.db" ]]; then - echo "the core did not open its database in the scratch data dir ($DATA_DIR/config.db is missing)" >&2 + echo "the core did not open its database in the scratch data dir ($(say_path "$DATA_DIR/config.db") is missing)" >&2 exit 1 fi } @@ -400,13 +423,29 @@ NODE # --- self-test ------------------------------------------------------------------ # run_self_test: no browser. Uses its own data dir and output dir, so a sweep # that follows it (--self-test-first) starts from fresh state. -st_fail() { echo "self-test FAILED: $*" >&2; exit 1; } +# st_check_child_output LABEL OUTPUT HANDOFF: the output of a child run (stdout +# and stderr) contains neither the child's API key nor any absolute path under +# its scratch dir, this run's scratch dir (the children's --out lives there) or +# the operator's home (the repo is under it). Never echoes the output. +st_check_child_output() { + local label="$1" output="$2" handoff="$3" child_key child_work p + [[ -s "$handoff" ]] || st_fail "$label did not hand back its key" + child_key=$(sed -n 1p "$handoff") + child_work=$(sed -n 2p "$handoff") + [[ ${#child_key} -ge 32 && -n "$child_work" ]] || st_fail "$label handed back no key or scratch dir" + grep -qF "$child_key" "$output" && st_fail "$label printed its API key ($(grep -cF "$child_key" "$output") lines)" + grep -qF "$(node -e 'process.stdout.write(encodeURIComponent(process.argv[1]))' "$child_key")" "$output" && st_fail "$label printed its URL-encoded API key" + for p in "$child_work" "${child_work#/private}" "$WORK" "${WORK#/private}" "$OPERATOR_HOME" "$REPO_ROOT"; do + [[ ${#p} -gt 1 ]] || continue + grep -qF "$p" "$output" && st_fail "$label printed a local path ($(grep -cF "$p" "$output") lines)" + done + return 0 +} +st_fail() { printf 'self-test FAILED: %s\n' "$*" | redact_stream >&2; exit 1; } run_self_test() { local sweep_data_dir="$DATA_DIR" st_port d step st_status results enc_key st_out decoy_new decoy_legacy decoy_audit_dir decoy_certs decoy_tpa DATA_DIR="$WORK/st-data" mkdir -p "$DATA_DIR" - # The DEBUG=1 child of step 4 hands its key to the parent (a scratch file of the parent's). - if [[ -n "${SWEEP_SELF_TEST_CHILD:-}" ]]; then printf '%s' "$API_KEY" >"$SWEEP_SELF_TEST_CHILD"; fi # 1. The guard refuses the operator's ~/.mcpproxy and anything inside it. [[ -n "$OPERATOR_HOME" ]] || st_fail "HOME is not set" @@ -539,22 +578,52 @@ if (r.checked_commit !== "0123456789abcdef0123456789abcdef01234567" || r.working ' "$results" echo "self-test: the results writer records the first failed attempt, redacts the key and local paths, and labels a dirty tree pre-commit evidence" - # 4. DEBUG=1 never prints the key: the whole self-test above (config, core - # start with the key, curl with the key header, redaction) runs again as a - # child with DEBUG=1, which hands back its own key through a scratch file; - # the child's stderr must not contain it. The child skips this step. + # 4. DEBUG=1 never prints the key or a local path: the whole self-test above + # (config, core start with the key, curl with the key header, redaction) runs + # again as a child with DEBUG=1, which hands back its own key and scratch dir + # through a scratch file; the child's stdout and stderr must contain neither, + # nor a path under the operator's home. The child skips steps 4 and 5. if [[ -z "${SWEEP_SELF_TEST_CHILD:-}" ]]; then - local probe_err="$WORK/debug-probe.stderr" probe_key="$WORK/debug-probe.key" probe_status + local probe_out="$WORK/debug-probe.out" probe_key="$WORK/debug-probe.key" probe_status set +e DEBUG=1 SWEEP_SELF_TEST_CHILD="$probe_key" MCPPROXY_BINARY_PATH="$CORE_BIN" SKILLS_FIXTURE_BINARY="$FIXTURE_BIN" \ - bash "$SCRIPT_DIR/$(basename "${BASH_SOURCE[0]}")" --self-test >/dev/null 2>"$probe_err" + bash "$SCRIPT_DIR/$(basename "${BASH_SOURCE[0]}")" --self-test >"$probe_out" 2>&1 probe_status=$? set -e - [[ -s "$probe_key" ]] || st_fail "the DEBUG=1 self-test run did not hand back its key (exit $probe_status)" - # Never echo the child's stderr here: it is what is being checked for the key. - grep -qF "$(cat "$probe_key")" "$probe_err" && st_fail "a DEBUG=1 run printed its API key to stderr ($(grep -cF "$(cat "$probe_key")" "$probe_err") lines)" + st_check_child_output "a passing DEBUG=1 self-test run" "$probe_out" "$probe_key" [[ $probe_status -eq 0 ]] || st_fail "the DEBUG=1 self-test run failed (exit $probe_status)" - echo "self-test: a DEBUG=1 run (the self-test as a child) never printed its API key to stderr" + grep -qF "self-test passed" "$probe_out" || st_fail "the DEBUG=1 self-test run did not pass" + echo "self-test: a passing DEBUG=1 run (the self-test as a child) printed no API key and no local path" + + # 5. A startup failure dumps the fixture's or the core's log, redacted. A + # sweep run as a child with a stand-in fixture (then a stand-in core) that + # prints its scratch HOME and TMPDIR, its arguments and (the core) its + # environment with the API key, then exits 1: the run must fail, print the + # log with the placeholders, and print no key and no local path. + local fakes="$WORK/st-fakes" which bin want + mkdir -p "$fakes" + # shellcheck disable=SC2016 # expanded by the stand-in's own shell + printf '#!/bin/sh\necho "fixture HOME=$HOME TMPDIR=$TMPDIR args: $*"\nexit 1\n' >"$fakes/skillsfixture" + printf '#!/bin/sh\necho "core args: $*"\nenv\nexit 1\n' >"$fakes/mcpproxy" + chmod +x "$fakes/skillsfixture" "$fakes/mcpproxy" + for which in fixture core; do + if [[ $which == fixture ]]; then bin=("$CORE_BIN" "$fakes/skillsfixture"); want="skillsfixture did not start" + else bin=("$fakes/mcpproxy" "$FIXTURE_BIN"); want="core did not become ready"; fi + rm -f "$probe_key" + set +e + SWEEP_SELF_TEST_CHILD="$probe_key" MCPPROXY_BINARY_PATH="${bin[0]}" SKILLS_FIXTURE_BINARY="${bin[1]}" \ + bash "$SCRIPT_DIR/$(basename "${BASH_SOURCE[0]}")" --out "$WORK/st-fail-$which" >"$probe_out" 2>&1 + probe_status=$? + set -e + st_check_child_output "a run whose $which fails to start" "$probe_out" "$probe_key" + [[ $probe_status -ne 0 ]] || st_fail "a run whose $which fails to start exited 0" + grep -qF "$want" "$probe_out" || st_fail "a run whose $which fails to start did not say '$want'" + grep -qF "/" "$probe_out" || st_fail "a run whose $which fails to start did not print its log through the redactor" + if [[ $which == core ]]; then + grep -qF "MCPPROXY_API_KEY=***" "$probe_out" || st_fail "the core's environment with the redacted key was not in the dumped log" + fi + done + echo "self-test: a fixture or core startup failure prints its log redacted, with no API key and no local path" fi echo "self-test passed" DATA_DIR="$sweep_data_dir" @@ -613,7 +682,7 @@ if [[ -z "$FIXTURE_BIN" ]]; then fi for b in "$CORE_BIN" "$FIXTURE_BIN"; do if [[ ! -x "$b" ]]; then - echo "not an executable: $b" >&2 + echo "not an executable: $(say_path "$b")" >&2 exit 1 fi done @@ -646,7 +715,7 @@ echo "core ready at $BASE_URL (data dir: the scratch dir)" code=$(curl -s --max-time 10 -o "$WORK/approve.json" -w '%{http_code}' -X POST "${H[@]}" \ -H 'Content-Type: application/json' -d '{"force":true}' "$BASE_URL/api/v1/servers/${SERVER}/security/approve") if [[ "$code" != "200" ]]; then - echo "approving ${SERVER} failed with HTTP $code: $(cat "$WORK/approve.json")" >&2 + echo "approving ${SERVER} failed with HTTP $code: $(redact_stream <"$WORK/approve.json")" >&2 exit 1 fi ready=0 @@ -659,7 +728,7 @@ for attempt in $(seq 1 60); do sleep 1 done if [[ $ready -ne 1 ]]; then - echo "the core never listed the fixture's three skills; last refresh: $(cat "$WORK/refresh.json" 2>/dev/null)" >&2 + echo "the core never listed the fixture's three skills; last refresh: $( (redact_stream <"$WORK/refresh.json") 2>/dev/null)" >&2 exit 1 fi echo "server ${SERVER} approved; three skills listed" @@ -675,7 +744,7 @@ lock_hash() { LOCK_STAMP="$SWEEP_DIR/node_modules/.sweep-lock-sha256" WANT_LOCK_HASH=$(lock_hash "$SWEEP_DIR/package-lock.json") if [[ -z "$WANT_LOCK_HASH" ]]; then - echo "cannot hash $SWEEP_DIR/package-lock.json" >&2 + echo "cannot hash $(say_path "$SWEEP_DIR/package-lock.json")" >&2 exit 1 fi HAVE_LOCK_HASH="" @@ -687,7 +756,7 @@ fi PLAYWRIGHT_BIN="$SWEEP_DIR/node_modules/.bin/playwright" if [[ -n "${PW_CHROMIUM:-}" ]]; then # playwright.config.ts launches this binary instead of a downloaded one. - echo "using PW_CHROMIUM=$PW_CHROMIUM (no browser download)" + echo "using PW_CHROMIUM=$(say_path "$PW_CHROMIUM") (no browser download)" elif [[ "$(uname -s)" == "Linux" ]]; then "$PLAYWRIGHT_BIN" install --with-deps chromium else @@ -785,12 +854,12 @@ NODE # Every string in the report comes from the redacted results file; the copy # without screenshots (pure text) is redacted once more as a whole. [[ $SCREENSHOTS -eq 0 ]] && redact_file "$REPORT_HTML" - echo "HTML report written to $REPORT_HTML$([[ $SCREENSHOTS -eq 0 ]] && echo ' (no embedded screenshots)')" + echo "HTML report written to $(say_path "$REPORT_HTML")$([[ $SCREENSHOTS -eq 0 ]] && echo ' (no embedded screenshots)')" fi -echo "results: $OUT/skills-sweep-results.json" +echo "results: $(say_path "$OUT/skills-sweep-results.json")" if [[ $PLAYWRIGHT_STATUS -ne 0 || $RESULT_STATUS -ne 0 ]]; then - echo "skills tab sweep FAILED (playwright exit $PLAYWRIGHT_STATUS); see $OUT" >&2 + echo "skills tab sweep FAILED (playwright exit $PLAYWRIGHT_STATUS); see $(say_path "$OUT")" >&2 exit 1 fi echo "skills tab sweep passed" From 9722b1e16e57e82209c9e399ccd71706b9c065b8 Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Fri, 20 Nov 2026 12:53:52 +0200 Subject: [PATCH 07/18] docs(skills): browser sweep evidence for f1889571e Related #1895 --- specs/125-skills-over-mcp/verification/report.html | 4 ++-- .../verification/skills-sweep-results.json | 12 ++++++------ 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/specs/125-skills-over-mcp/verification/report.html b/specs/125-skills-over-mcp/verification/report.html index 5d31be6d6..6bcdab6f5 100644 --- a/specs/125-skills-over-mcp/verification/report.html +++ b/specs/125-skills-over-mcp/verification/report.html @@ -6,8 +6,8 @@ .t{color:#57606a;font-size:.85em;margin:.25rem 0}img{max-width:100%;border:1px solid #d0d7de;border-radius:4px;margin:.25rem 0}code{background:#eaeef2;padding:0 .25rem;border-radius:3px;font-size:.85em} table{border-collapse:collapse;font-size:.85em;margin:.5rem 0}td,th{border:1px solid #d0d7de;padding:.2rem .4rem;text-align:left}

Spec 125: Skills tab (PR-4a) Playwright verification

-
8 of 8 scenarios passed, 2026-11-20, produced by scripts/run-skills-tab-sweep.sh from commit d10ee8b6706624e6ed1211d8fbde3c36b7f92014 (working tree clean).
-A throwaway core (127.0.0.1:60072, scratch data dir, enable_skills: true, generated API key) served the embedded frontend; the upstream skillsfx (trust_mode: manual) was skillsfixture -addr 127.0.0.1:60070 on port 60070.
+
8 of 8 scenarios passed, 2026-11-20, produced by scripts/run-skills-tab-sweep.sh from commit f1889571e465798fdf48d9c3625fe57a902db3c2 (working tree clean).
+A throwaway core (127.0.0.1:50574, scratch data dir, enable_skills: true, generated API key) served the embedded frontend; the upstream skillsfx (trust_mode: manual) was skillsfixture -addr 127.0.0.1:50572 on port 50572.
Spec: e2e/web-ui-sweep/skills-tab.spec.ts. Results file: skills-sweep-results.json. Repeat: ./scripts/run-skills-tab-sweep.sh --report-html specs/125-skills-over-mcp/verification/report.html --no-screenshots.
1. Tab and list PASS

the Skills tab lists the fixture skills as awaiting review

The Skills tab is offered on a server with enable_skills on and a skills-capable upstream (cmd/skillsfixture, manual trust). The three skills show as Awaiting review and Not offered.

Screenshots (not embedded in this copy): screenshots/skills-tab-01-list.png

2. Viewer and paging PASS

views SKILL.md, pages a large file, and does not offer a binary file

SKILL.md opens in the text viewer (inert text). A 150 KiB file (data/large.txt of big) is read part by part in at least three parts: each Load more waits for its content response and for the rendered text to grow by that part. Every part is of the current copy, its digest equals the digest the core lists for that file in the current copy (the same digest the file row shows on screen), its size equals the listed size, its offset is where the previous part ended (in bytes, the first at 0) and its next_offset is where it ends; the last part has no next_offset and ends at the listed size. A binary file (logo.bin) is listed as binary, not shown, with no View button.

Screenshots (not embedded in this copy): screenshots/skills-tab-02-viewer.png, screenshots/skills-tab-03-paged.png

diff --git a/specs/125-skills-over-mcp/verification/skills-sweep-results.json b/specs/125-skills-over-mcp/verification/skills-sweep-results.json index 5d118c0db..1c155754f 100644 --- a/specs/125-skills-over-mcp/verification/skills-sweep-results.json +++ b/specs/125-skills-over-mcp/verification/skills-sweep-results.json @@ -1,19 +1,19 @@ { - "checked_commit": "d10ee8b6706624e6ed1211d8fbde3c36b7f92014", + "checked_commit": "f1889571e465798fdf48d9c3625fe57a902db3c2", "working_tree_dirty": false, "evidence": "commit", - "checked": "d10ee8b6706624e6ed1211d8fbde3c36b7f92014", - "generated_at": "2026-11-20T10:34:36.753Z", + "checked": "f1889571e465798fdf48d9c3625fe57a902db3c2", + "generated_at": "2026-11-20T10:53:27.518Z", "fixture": { "command": [ "skillsfixture", "-addr", - "127.0.0.1:60070" + "127.0.0.1:50572" ], - "port": 60070 + "port": 50572 }, "core": { - "listen": "127.0.0.1:60072", + "listen": "127.0.0.1:50574", "server": "skillsfx", "enable_skills": true, "trust_mode": "manual" From 72e14ec9d60cbf58da8b15cbe99b0e3a8223f2fe Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Fri, 20 Nov 2026 13:13:01 +0200 Subject: [PATCH 08/18] fix(skills): review round 6 for the Skills tab and its sweep - Approve, block and unblock answer 409 server_replaced through the shared approval error writer, whose body has no error_code. skillErrorCode reads the code from the message prefix (server_replaced, review_out_of_date) when error_code is absent, so a real refusal latches the review stale and shows the worded notice instead of the raw text. The panel tests now use the core's real bodies for approve, block and unblock. - A live skills.changed for the server turns Approve off (for the open review and one opened from the listing on screen) until a reload for the server applies: an unchanged hash turns it back on, a moved hash marks the review stale as before. A banner says so and offers Reload. Tests for a pending and a failed reload. - Every write takes an operation number; only the newest write publishes a notice, so a slow reload after an approve no longer replaces "Blocked.". - skillErrorNotice is worded per action: skills_disabled and server_replaced say nothing was approved / blocked / unblocked / refreshed. - run-skills-tab-sweep.sh: npm ci, npm run build, go build, playwright install and the Playwright run are captured into scratch files (run_logged) and printed only redacted, with their exit statuses kept. The redactor reduces any other absolute path under a filesystem root to /basename, and say_path does so for any path outside the known prefixes. --self-test adds say_path/redact_stream checks, a forced Playwright failure with a stand-in PW_CHROMIUM under /tmp that dumps its environment, and a failing go build. - docs/development/release-gate.md: the web-ui-sweep job has 35 minutes. Related #1895 --- docs/development/release-gate.md | 2 +- .../src/components/skills/SkillsPanel.vue | 46 +++-- frontend/src/utils/skills.ts | 29 +++- frontend/tests/unit/skills-panel.spec.ts | 158 ++++++++++++++++-- frontend/tests/unit/skills-utils.spec.ts | 28 +++- scripts/run-skills-tab-sweep.sh | 157 +++++++++++++---- 6 files changed, 363 insertions(+), 57 deletions(-) diff --git a/docs/development/release-gate.md b/docs/development/release-gate.md index a97964b71..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, and `advisory/skills-tab-sweep`, spec 125) | 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 diff --git a/frontend/src/components/skills/SkillsPanel.vue b/frontend/src/components/skills/SkillsPanel.vue index 93bd5cd4a..0b9c8e391 100644 --- a/frontend/src/components/skills/SkillsPanel.vue +++ b/frontend/src/components/skills/SkillsPanel.vue @@ -63,6 +63,10 @@ This skill changed while you were reviewing it. Approve is off until you open the new version.
+
+ The server's skills changed. Approve is off until the list is reloaded. + +
() @@ -97,6 +101,11 @@ const error = ref('') const notice = ref('') const refreshing = ref(false) const busy = ref(false) +// A live skills.changed for this server: the records moved, so the version on +// screen may be out of date. Approve is off (for the open review and for one +// opened from the listing still on screen) until a reload for this server +// applies; apply() then clears it, or marks the review stale if its hash moved. +const awaitingReload = ref(false) // The review in progress: the entry and the incarnation as they were when the // reviewer opened the skill. A reload never swaps in a new version of the @@ -145,6 +154,7 @@ const isCurrent = (server: string, v: number, seq?: number) => function apply(data: SkillsListResponse) { listing.value = data error.value = '' + awaitingReload.value = false const r = review.value if (!r) return const live = data.skills.find(s => s.path === r.path) @@ -199,7 +209,7 @@ async function refresh() { // A failed refresh (refresh_superseded, skills_not_supported, skills_disabled, // server_replaced, a 500) reloads the listing: the notice says it was reloaded, // and the stored records may have moved even though this refresh did not apply. - notice.value = skillErrorNotice(res.errorCode, res.error) + notice.value = skillErrorNotice(res.errorCode, res.error, 'refresh') await load() } @@ -209,33 +219,43 @@ async function refresh() { // for a skill the reviewer has left is not shown on the next one (the listing is // still reloaded). A success notice given as a function is worded from the // listing reloaded after the write (null when that reload did not apply). +// Every write takes an operation number when it starts; only the newest write +// publishes a notice, so a slow reload after an earlier write never replaces +// the notice of a later one (approve, then block: "Blocked." stays). type DoneNotice = string | ((reloaded: SkillsListResponse | null) => string) -async function write(run: () => Promise<{ success: boolean; error?: string; errorCode?: string }>, done: DoneNotice) { - const server = props.serverName, v = visit, token = review.value?.token +let writeSeq = 0 +async function write(action: SkillAction, run: () => Promise<{ success: boolean; error?: string; errorCode?: string }>, done: DoneNotice) { + const server = props.serverName, v = visit, token = review.value?.token, op = ++writeSeq + const mayPublish = () => op === writeSeq && isCurrent(server, v) busy.value = true const res = await settle(run) if (!isCurrent(server, v)) return busy.value = false if (!res.success || typeof done === 'string') { if (review.value?.token === token) { - notice.value = res.success ? done as string : skillErrorNotice(res.errorCode, res.error) + // The approval routes answer 409 server_replaced with no error_code: the + // code is read from the message. + const code = res.success ? undefined : skillErrorCode(res.errorCode, res.error) // The server says the open version is out of date: latch it before the // reload, so a reload that is pending or fails never re-enables Approve. - if (!res.success && STALE_CODES.has(res.errorCode ?? '')) markStale(token) + if (code && STALE_CODES.has(code)) markStale(token) + if (mayPublish()) notice.value = res.success ? done as string : skillErrorNotice(code, res.error, action) } await load() return } const reloaded = await load() - // Still the same review (or none: the reload dropped a skill that vanished). - if (isCurrent(server, v) && (!review.value || review.value.token === token)) notice.value = done(reloaded) + // Still the newest write and the same review (or none: the reload dropped a + // skill that vanished). + if (mayPublish() && (!review.value || review.value.token === token)) notice.value = done(reloaded) } // Approve sends exactly the hash and the incarnation the reviewer opened. function approve() { const r = review.value - if (!r || r.stale || busy.value) return + if (!r || r.stale || awaitingReload.value || busy.value) return return write( + 'approve', () => api.approveSkills(props.serverName, [r.path], skillExpectedHashes([r.entry]), r.incarnation), reloaded => skillApprovedNotice(reloaded, r.path), ) @@ -245,6 +265,7 @@ function setBlocked(block: boolean) { const r = review.value if (!r || busy.value) return return write( + block ? 'block' : 'unblock', // Called as methods: the API client's methods use `this`. () => (block ? api.blockSkills(props.serverName, [r.path], r.incarnation) @@ -257,7 +278,9 @@ function setBlocked(block: boolean) { // timestamp}), like every other runtime event. function onSkillsChanged(e: Event) { const detail = (e as CustomEvent).detail as { payload?: { server?: string } } | null - if (detail?.payload?.server === props.serverName) void load() + if (detail?.payload?.server !== props.serverName) return + awaitingReload.value = true + void load() } watch(() => props.serverName, () => { @@ -268,6 +291,7 @@ watch(() => props.serverName, () => { notice.value = '' refreshing.value = false busy.value = false + awaitingReload.value = false void load() }) diff --git a/frontend/src/utils/skills.ts b/frontend/src/utils/skills.ts index 862efa2b0..8a2c52cb0 100644 --- a/frontend/src/utils/skills.ts +++ b/frontend/src/utils/skills.ts @@ -176,20 +176,39 @@ export function skillsTabVisible(listing: SkillsListResponse | undefined | null) return listing.enabled === true && (listing.supported || (listing.skills?.length ?? 0) > 0) } -/** Operator-facing words for an error code of the skills routes. */ -export function skillErrorNotice(code: string | undefined, message: string | undefined): string { - switch (code) { +/** + * 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 was changed. The list was reloaded.' + 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 was refreshed. The list was reloaded.' + return `Skills over MCP was turned off (enable_skills), so ${NOTHING_DONE[action]}. The list was reloaded.` default: return message || 'The request failed' } diff --git a/frontend/tests/unit/skills-panel.spec.ts b/frontend/tests/unit/skills-panel.spec.ts index b0bcc6b07..7a1735e87 100644 --- a/frontend/tests/unit/skills-panel.spec.ts +++ b/frontend/tests/unit/skills-panel.spec.ts @@ -15,6 +15,20 @@ const mountPanel = (serverName = 'srv') => mount(SkillsPanel, { props: { serverN // Round-3 finding 1: every skills.changed goes through the real store's re-dispatch of the core's frame. let emitSkillsChanged: (server: string) => void = () => { throw new Error('not connected') } +// Round-6 finding 1: the bodies the core really sends, as the API client returns +// them. approve/block/unblock answer 409 server_replaced through +// writeApprovalWriteError (internal/httpapi/server_incarnation.go), which has NO +// error_code: the runtime's ServerReplacedError text, or the sentinel's text. +// review_out_of_date (approve only) does carry error_code. +const REPLACED = { success: false, error: "server_replaced: server 'srv' was removed or replaced since it was reviewed" } +const REPLACED_SENTINEL = { success: false, error: 'server_replaced: the server was removed or replaced since it was reviewed' } +const OUT_OF_DATE = { + success: false, + error: 'review_out_of_date: skill review of server srv is out of date (changed since the review: a); nothing was approved', + errorCode: 'review_out_of_date', +} +const DISABLED = { success: false, error: 'skills_disabled: enable_skills is off; set enable_skills: true in the configuration', errorCode: 'skills_disabled' } + describe('SkillsPanel', () => { beforeEach(async () => { vi.clearAllMocks() @@ -118,7 +132,7 @@ describe('SkillsPanel', () => { it('a 409 review_out_of_date reloads the list and says nothing was approved, with no retry', async () => { m(api.getServerSkills).mockResolvedValueOnce(ok(makeListing([makeSkill('a', { current_hash: 'sk1-1' })]))) - m(api.approveSkills).mockResolvedValue({ success: false, error: 'review_out_of_date: x', errorCode: 'review_out_of_date' }) + m(api.approveSkills).mockResolvedValue(OUT_OF_DATE) const w = mountPanel(); await flushPromises() await w.get('[data-test="skill-row-a"]').trigger('click'); await flushPromises() m(api.getServerSkills).mockResolvedValue(ok(makeListing([makeSkill('a', { current_hash: 'sk1-2', status: 'changed' })]))) @@ -129,15 +143,72 @@ describe('SkillsPanel', () => { expect(w.get('[data-test="skill-chip-a"]').text()).toBe('Changed') }) - it('a 409 server_replaced reloads the list and says so', async () => { + // Round-6 finding 1: the real 409 server_replaced body of every write route has + // no error_code; the code is read from the message, the notice names it and the + // review is latched stale. + for (const [action, body] of [ + ['approve', REPLACED], ['approve', REPLACED_SENTINEL], ['block', REPLACED], ['unblock', REPLACED], + ] as const) { + it(`a real 409 server_replaced on ${action} (${body.error.slice(17, 40)}…) reloads, says so and latches the review stale`, async () => { + const blocked = action === 'unblock' + m(api.getServerSkills).mockResolvedValueOnce(ok(makeListing([makeSkill('a', { blocked })]))) + const fn = action === 'approve' ? api.approveSkills : action === 'block' ? api.blockSkills : api.unblockSkills + m(fn).mockResolvedValue(body) + const w = mountPanel(); await flushPromises() + await w.get('[data-test="skill-row-a"]').trigger('click'); await flushPromises() + // The reload after the refusal fails: the latch alone keeps Approve off. + m(api.getServerSkills).mockResolvedValue({ success: false, error: 'reload boom' }) + await w.get(`[data-test="skill-${action}"]`).trigger('click'); await flushPromises() + expect(fn).toHaveBeenCalledTimes(1) // no retry + expect(api.getServerSkills).toHaveBeenCalledTimes(2) + const notice = w.get('[data-test="skills-notice"]').text() + expect(notice).toMatch(/removed and added again/i) + expect(notice).not.toContain('server_replaced:') + expect(w.find('[data-test="skill-stale"]').exists()).toBe(true) + if (!blocked) expect(w.get('[data-test="skill-approve"]').attributes('disabled')).toBeDefined() + }) + } + + // Round-6 finding 4: a write refused with skills_disabled says what was not done. + for (const [action, verb] of [['approve', 'approved'], ['block', 'blocked'], ['unblock', 'unblocked']] as const) { + it(`a 409 skills_disabled on ${action} says nothing was ${verb}, not refreshed`, async () => { + m(api.getServerSkills).mockResolvedValue(ok(makeListing([makeSkill('a', { blocked: action === 'unblock' })]))) + const fn = action === 'approve' ? api.approveSkills : action === 'block' ? api.blockSkills : api.unblockSkills + m(fn).mockResolvedValue(DISABLED) + const w = mountPanel(); await flushPromises() + await w.get('[data-test="skill-row-a"]').trigger('click'); await flushPromises() + await w.get(`[data-test="skill-${action}"]`).trigger('click'); await flushPromises() + const notice = w.get('[data-test="skills-notice"]').text() + expect(notice).toMatch(/turned off/i) + expect(notice).toContain(`nothing was ${verb}`) + expect(notice).not.toMatch(/refreshed/i) + }) + } + + it('a 409 skills_disabled on refresh still says nothing was refreshed', async () => { m(api.getServerSkills).mockResolvedValue(ok(makeListing([makeSkill('a')]))) - m(api.approveSkills).mockResolvedValue({ success: false, error: 'server_replaced: x', errorCode: 'server_replaced' }) + const w = mountPanel(); await flushPromises() + m(api.refreshServerSkills).mockResolvedValueOnce(DISABLED) + await w.get('[data-test="skills-refresh"]').trigger('click'); await flushPromises() + expect(w.get('[data-test="skills-notice"]').text()).toMatch(/nothing was refreshed/) + }) + + // Round-6 finding 3: only the newest write publishes its notice. + it('a late approve reload never overwrites the notice of a newer block', async () => { + m(api.getServerSkills).mockResolvedValueOnce(ok(makeListing([makeSkill('a')]))) + m(api.approveSkills).mockResolvedValue(ok({ approved: 1 })) + m(api.blockSkills).mockResolvedValue(ok({ changed: 1 })) + let releaseApproveReload: (v: unknown) => void = () => {} const w = mountPanel(); await flushPromises() await w.get('[data-test="skill-row-a"]').trigger('click'); await flushPromises() + m(api.getServerSkills).mockReturnValueOnce(new Promise(r => { releaseApproveReload = r })) await w.get('[data-test="skill-approve"]').trigger('click'); await flushPromises() - expect(api.approveSkills).toHaveBeenCalledTimes(1) // no retry - expect(api.getServerSkills).toHaveBeenCalledTimes(2) - expect(w.get('[data-test="skills-notice"]').text()).toMatch(/removed and added again/i) + // Approve answered; its reload is in flight. The reviewer blocks. + m(api.getServerSkills).mockResolvedValueOnce(ok(makeListing([makeSkill('a', { status: 'approved', blocked: true })]))) + await w.get('[data-test="skill-block"]').trigger('click'); await flushPromises() + expect(w.get('[data-test="skills-notice"] span').text()).toBe('Blocked.') + releaseApproveReload(ok(makeListing([makeSkill('a', { status: 'approved', available: true })]))); await flushPromises() + expect(w.get('[data-test="skills-notice"] span').text()).toBe('Blocked.') }) it('a 422 skill_unusable shows the message', async () => { @@ -342,7 +413,7 @@ describe('SkillsPanel', () => { await w.get('[data-test="skill-row-a"]').trigger('click'); await flushPromises() await w.get('[data-test="skill-approve"]').trigger('click'); await flushPromises() await w.get('[data-test="skill-row-b"]').trigger('click'); await flushPromises() - release({ success: false, error: 'review_out_of_date: x', errorCode: 'review_out_of_date' }); await flushPromises() + release(OUT_OF_DATE); await flushPromises() expect(w.find('[data-test="skills-notice"]').exists()).toBe(false) expect(w.get('[data-test="skill-name"]').text()).toBe('b') expect(api.getServerSkills).toHaveBeenCalledTimes(2) @@ -462,13 +533,19 @@ describe('SkillsPanel', () => { }) const signals: Array<[string, (w: ReturnType) => Promise]> = [ ['approve 409 review_out_of_date', async w => { - m(api.approveSkills).mockResolvedValueOnce({ success: false, error: 'review_out_of_date: x', errorCode: 'review_out_of_date' }) + m(api.approveSkills).mockResolvedValueOnce(OUT_OF_DATE) await w.get('[data-test="skill-approve"]').trigger('click'); await flushPromises() }], + // Round-6 finding 1: the real body, with no error_code. ['approve 409 server_replaced', async w => { - m(api.approveSkills).mockResolvedValueOnce({ success: false, error: 'server_replaced: x', errorCode: 'server_replaced' }) + m(api.approveSkills).mockResolvedValueOnce(REPLACED) await w.get('[data-test="skill-approve"]').trigger('click'); await flushPromises() }], + ['block 409 server_replaced', async w => { + m(api.blockSkills).mockResolvedValueOnce(REPLACED) + await w.get('[data-test="skill-block"]').trigger('click'); await flushPromises() + }], + ['a viewer part of another version', async w => { m(api.getSkillContent).mockResolvedValue(ok({ text: 'x', offset: 0, size: 1, digest: 'sha256:moved' })) await w.get('[data-test="skill-view-SKILL.md"]').trigger('click'); await flushPromises() @@ -505,6 +582,67 @@ describe('SkillsPanel', () => { } } + // Round-6 finding 2: a live skills.changed says the records moved; until a + // reload for this server applies, Approve is off for the open review (and for + // a review opened from the listing still on screen). + describe('after a live skills.changed', () => { + const openA = async () => { + m(api.getServerSkills).mockResolvedValueOnce(ok(makeListing([changedSkill()]))) + const w = mountPanel(); await flushPromises() + await w.get('[data-test="skill-row-a"]').trigger('click'); await flushPromises() + expect(w.get('[data-test="skill-approve"]').attributes('disabled')).toBeUndefined() + return w + } + const approveIsOff = async (w: ReturnType) => { + expect(w.get('[data-test="skill-approve"]').attributes('disabled')).toBeDefined() + expect(w.find('[data-test="skill-checking"]').exists()).toBe(true) + await w.get('[data-test="skill-approve"]').trigger('click'); await flushPromises() + expect(api.approveSkills).not.toHaveBeenCalled() + } + + it('reload pending: Approve is off; the reload applying with the same hash turns it back on', async () => { + const w = await openA() + let release: (v: unknown) => void = () => {} + m(api.getServerSkills).mockReturnValueOnce(new Promise(r => { release = r })) + emitSkillsChanged('srv'); await flushPromises() + await approveIsOff(w) + release(ok(makeListing([changedSkill()]))); await flushPromises() + expect(w.find('[data-test="skill-checking"]').exists()).toBe(false) + expect(w.find('[data-test="skill-stale"]').exists()).toBe(false) + expect(w.get('[data-test="skill-approve"]').attributes('disabled')).toBeUndefined() + }) + + it('reload failed: Approve stays off, also after re-opening, until a reload applies', async () => { + const w = await openA() + m(api.getServerSkills).mockResolvedValueOnce({ success: false, error: 'reload boom' }) + emitSkillsChanged('srv'); await flushPromises() + await approveIsOff(w) + await w.get('[data-test="skill-row-a"]').trigger('click'); await flushPromises() + await approveIsOff(w) + // The banner's reload applies the same version: Approve is back on. + m(api.getServerSkills).mockResolvedValueOnce(ok(makeListing([changedSkill()]))) + await w.get('[data-test="skill-checking-reload"]').trigger('click'); await flushPromises() + expect(w.find('[data-test="skill-checking"]').exists()).toBe(false) + expect(w.get('[data-test="skill-approve"]').attributes('disabled')).toBeUndefined() + }) + + it('reload applies a new hash: the review is stale as before', async () => { + const w = await openA() + m(api.getServerSkills).mockResolvedValueOnce(ok(makeListing([{ ...changedSkill(), current_hash: 'sk1-moved' }]))) + emitSkillsChanged('srv'); await flushPromises() + expect(w.find('[data-test="skill-checking"]').exists()).toBe(false) + expect(w.find('[data-test="skill-stale"]').exists()).toBe(true) + expect(w.get('[data-test="skill-approve"]').attributes('disabled')).toBeDefined() + }) + + it('a skills.changed for another server does not turn Approve off', async () => { + const w = await openA() + emitSkillsChanged('other'); await flushPromises() + expect(w.find('[data-test="skill-checking"]').exists()).toBe(false) + expect(w.get('[data-test="skill-approve"]').attributes('disabled')).toBeUndefined() + }) + }) + it('a stale signal for a review the reviewer has left does not mark the new one', async () => { m(api.getServerSkills).mockResolvedValue(ok(makeListing([makeSkill('a'), makeSkill('b')]))) let release: (v: unknown) => void = () => {} @@ -513,7 +651,7 @@ describe('SkillsPanel', () => { await w.get('[data-test="skill-row-a"]').trigger('click'); await flushPromises() await w.get('[data-test="skill-approve"]').trigger('click'); await flushPromises() await w.get('[data-test="skill-row-b"]').trigger('click'); await flushPromises() - release({ success: false, error: 'review_out_of_date: x', errorCode: 'review_out_of_date' }); await flushPromises() + release(OUT_OF_DATE); await flushPromises() expect(w.find('[data-test="skill-stale"]').exists()).toBe(false) expect(w.get('[data-test="skill-approve"]').attributes('disabled')).toBeUndefined() }) diff --git a/frontend/tests/unit/skills-utils.spec.ts b/frontend/tests/unit/skills-utils.spec.ts index ddc6a9e6a..c2ba96867 100644 --- a/frontend/tests/unit/skills-utils.spec.ts +++ b/frontend/tests/unit/skills-utils.spec.ts @@ -1,7 +1,7 @@ import { describe, expect, it, vi } from 'vitest' import { skillStateChip, skillFileDiff, lineDiff, skillExpectedHashes, readWholeSkillFile, - skillsTabVisible, skillErrorNotice, SKILL_CONTENT_CHANGED, LINE_DIFF_CONTEXT, LINE_DIFF_MAX_OPS, + skillsTabVisible, skillErrorNotice, skillErrorCode, SKILL_CONTENT_CHANGED, LINE_DIFF_CONTEXT, LINE_DIFF_MAX_OPS, } from '@/utils/skills' const file = (path: string, digest: string, size = 10, text = true) => ({ path, size, digest, text }) @@ -177,4 +177,30 @@ describe('skillErrorNotice', () => { expect(skillErrorNotice('skill_unusable', 'cannot approve: bad')).toBe('cannot approve: bad') expect(skillErrorNotice(undefined, 'plain')).toBe('plain') }) + + // Round-6 finding 1: approve/block/unblock answer 409 server_replaced with no + // error_code (writeApprovalWriteError); the code is the message's prefix. + it('reads the code from the message when the body has no error_code', () => { + expect(skillErrorCode(undefined, "server_replaced: server 'srv' was removed or replaced since it was reviewed")).toBe('server_replaced') + expect(skillErrorCode(undefined, 'server_replaced: the server was removed or replaced since it was reviewed')).toBe('server_replaced') + expect(skillErrorCode(undefined, 'review_out_of_date: skill review of server srv is out of date (changed since the review: a); nothing was approved')).toBe('review_out_of_date') + expect(skillErrorCode('skill_unusable', 'server_replaced: x')).toBe('skill_unusable') + expect(skillErrorCode(undefined, 'Failed to approve skills: server_replaced: x')).toBeUndefined() + expect(skillErrorCode(undefined, 'server_replacedx: y')).toBeUndefined() + expect(skillErrorCode(undefined, undefined)).toBeUndefined() + expect(skillErrorNotice(undefined, "server_replaced: server 'srv' was removed or replaced since it was reviewed", 'block')).toMatch(/removed and added again/i) + }) + + // Round-6 finding 4: the notice names the action that was refused. + it('words skills_disabled and server_replaced per action', () => { + expect(skillErrorNotice('skills_disabled', 'x')).toMatch(/nothing was refreshed/) + expect(skillErrorNotice('skills_disabled', 'x', 'refresh')).toMatch(/nothing was refreshed/) + for (const [action, verb] of [['approve', 'approved'], ['block', 'blocked'], ['unblock', 'unblocked']] as const) { + const n = skillErrorNotice('skills_disabled', 'x', action) + expect(n).toMatch(/turned off/i) + expect(n).toContain(`nothing was ${verb}`) + expect(n).not.toMatch(/refreshed/) + expect(skillErrorNotice('server_replaced', 'x', action)).toContain(`nothing was ${verb}`) + } + }) }) diff --git a/scripts/run-skills-tab-sweep.sh b/scripts/run-skills-tab-sweep.sh index baac32f3c..c4e07485e 100755 --- a/scripts/run-skills-tab-sweep.sh +++ b/scripts/run-skills-tab-sweep.sh @@ -57,9 +57,12 @@ Options: leaves no process or listening port of the run alive (and nothing else touched), that the results writer records the first failed attempt and redacts the API key - and local paths, and that neither a passing DEBUG=1 run - nor a run whose fixture or core fails to start prints - the API key or an absolute local path + and local paths, that printed paths are relative, + placeholders or /basename, and that neither a + passing DEBUG=1 run nor a run whose fixture or core + fails to start, whose Playwright fails (a stand-in + PW_CHROMIUM outside every known prefix) or whose build + fails prints the API key or an absolute local path --self-test-first run the --self-test checks, then the sweep (the release gate does this, so both land in one advisory entry) -h, --help print this message @@ -162,6 +165,13 @@ if (key) for (const k of [key, encodeURIComponent(key)]) t = t.split(k).join("** const paths = [[e.SWEEP_REDACT_OUT, ""], [e.SWEEP_REDACT_WORK, ""], [e.SWEEP_REDACT_REPO, ""], [e.SWEEP_REDACT_HOME, "~"]] .filter(([p]) => p && p.length > 1).sort((a, b) => b[0].length - a[0].length) for (const [p, r] of paths) t = t.split(p).join(r) +// Any other absolute local path (a browser named by PW_CHROMIUM, a browser +// download dir, a toolchain path in a stack trace or in PATH) is reduced to +// /basename. Only paths under a filesystem root are touched, so a URL path +// (http://host:port/api/...) or a placeholder (/e2e/...) is kept. +const roots = "Users|home|private|var|tmp|usr|opt|etc|Library|System|Applications|Volumes|nix|root|snap|mnt|media|srv|bin|sbin|lib|lib64|run|__w" +const abs = new RegExp("(^|[\\s\"\x27`(\\[=,:;])(/(?:" + roots + ")(?=/|[\\s\"\x27`()\\[\\],:;]|$)(?:/[^\\s\"\x27`()\\[\\],:;]*)*)", "gm") +t = t.replace(abs, (m, pre, p) => pre + "/" + p.split("/").filter(Boolean).pop()) if (f) fs.writeFileSync(f, t); else process.stdout.write(t)' redact_node() { SWEEP_REDACT_KEY="$API_KEY" SWEEP_REDACT_OUT="$OUT_REAL" SWEEP_REDACT_REPO="$REPO_ROOT" \ @@ -174,12 +184,37 @@ redact_file() { # Copies stdin to stdout, redacted. redact_stream() { redact_node; } # A path as printed: relative to the repo root when it is inside it, else with -# the placeholders of redact_stream. +# the placeholders of redact_stream, and any other absolute path (outside every +# known prefix, e.g. PW_CHROMIUM=/usr/bin/chromium) as /basename. say_path() { - case "$1" in - "$REPO_ROOT"/*) printf '%s' "${1#"$REPO_ROOT"/}" ;; - *) printf '%s' "$1" | redact_stream ;; + local p="$1" pre + case "$p" in + "$REPO_ROOT"/*) printf '%s' "${p#"$REPO_ROOT"/}"; return 0 ;; esac + if [[ "$p" == /* ]]; then + for pre in "$OUT_REAL" "$WORK" "$OPERATOR_HOME"; do + if [[ ${#pre} -gt 1 && "$p" == "$pre"/* ]]; then printf '%s' "$p" | redact_stream; return 0; fi + done + printf '/%s' "$(basename "$p")" + return 0 + fi + printf '%s' "$p" | redact_stream +} + +# run_logged NAME CMD...: runs CMD with its stdout and stderr captured into the +# scratch file $WORK/logs/NAME.log, then prints only a redacted copy of it (the +# tools' own output names the repo, the home, a browser download dir or the +# browser, and Playwright's launch errors carry the browser's environment with +# the API key). Returns CMD's exit status. Call it as `run_logged ... || status=$?` +# (or as a plain command where a failure should end the run under set -e). +run_logged() { + local name="$1" log status=0 + shift + mkdir -p "$WORK/logs" + log="$WORK/logs/$name.log" + "$@" >"$log" 2>&1 || status=$? + redact_stream <"$log" + return "$status" } # Prints $1 and every process descended from it (children first found by @@ -454,6 +489,19 @@ run_self_test() { data_dir_allowed "$DATA_DIR" || st_fail "the scratch data dir was refused" echo "self-test: a data dir under \$HOME/.mcpproxy is refused; the scratch dir is allowed" + # 1b. A printed path never shows an absolute local path: inside the repo it is + # relative, under a known prefix it gets its placeholder, and any other + # absolute path is reduced to /basename (say_path), also inside a + # message or a captured log (redact_stream). + local got_path + got_path=$(say_path "$REPO_ROOT/e2e/web-ui-sweep/x.json"); [[ "$got_path" == "e2e/web-ui-sweep/x.json" ]] || st_fail "say_path in the repo gave '$got_path'" + got_path=$(say_path "$WORK/st-data/config.db"); [[ "$got_path" == "/st-data/config.db" ]] || st_fail "say_path in the scratch dir gave '$got_path'" + got_path=$(say_path "/usr/bin/chromium"); [[ "$got_path" == "/chromium" ]] || st_fail "say_path of an outside path gave '$got_path'" + got_path=$(say_path "/srv/odd place/chrome"); [[ "$got_path" == "/chrome" ]] || st_fail "say_path of an outside path with a space gave '$got_path'" + got_path=$(printf 'launch /opt/google/chrome/chrome failed; PATH=/usr/local/bin:/opt/homebrew/bin url http://127.0.0.1:1/api/v1/servers key %s' "$API_KEY" | redact_stream) + [[ "$got_path" == 'launch /chrome failed; PATH=/bin:/bin url http://127.0.0.1:1/api/v1/servers key ***' ]] || st_fail "redact_stream gave '$got_path'" + echo "self-test: printed paths are relative, placeholders or /basename; URLs are kept" + # 2. An ambient MCPPROXY_DATA_DIR / MCPPROXY_DATA does not reach the core. decoy_new="$WORK/decoy-data-dir" decoy_legacy="$WORK/decoy-data-legacy" @@ -624,6 +672,56 @@ if (r.checked_commit !== "0123456789abcdef0123456789abcdef01234567" || r.working fi done echo "self-test: a fixture or core startup failure prints its log redacted, with no API key and no local path" + + # 6. A Playwright failure prints Playwright's own output (list reporter, + # launch errors with the browser's logs) redacted only. A sweep run as a + # child with PW_CHROMIUM naming a stand-in browser outside every known + # prefix (a fresh dir under /tmp, not the scratch dir, the repo or the + # home), which prints its arguments and its environment (the API key is in + # it) and exits 1: the run must fail, say so, name the browser as + # /chromium, print Playwright's failure, and print no key and no + # absolute path of the stand-in. + local ext ext_real + ext=$(mktemp -d /tmp/skills-sweep-pwext.XXXXXX) + ext_real=$(cd "$ext" && pwd -P) + # shellcheck disable=SC2016 # expanded by the stand-in's own shell + printf '#!/bin/sh\necho "stand-in browser $0 args: $*" >&2\nenv >&2\nexit 1\n' >"$ext/chromium" + chmod +x "$ext/chromium" + rm -f "$probe_key" + set +e + SWEEP_SELF_TEST_CHILD="$probe_key" PW_CHROMIUM="$ext/chromium" MCPPROXY_BINARY_PATH="$CORE_BIN" SKILLS_FIXTURE_BINARY="$FIXTURE_BIN" \ + bash "$SCRIPT_DIR/$(basename "${BASH_SOURCE[0]}")" --out "$WORK/st-pw-fail" >"$probe_out" 2>&1 + probe_status=$? + set -e + rm -rf "$ext" + st_check_child_output "a run whose Playwright fails" "$probe_out" "$probe_key" + for p in "$ext" "$ext_real" "${ext_real#/private}"; do + grep -qF "$p" "$probe_out" && st_fail "a run whose Playwright fails printed the stand-in browser's path ($(grep -cF "$p" "$probe_out") lines)" + done + [[ $probe_status -ne 0 ]] || st_fail "a run whose Playwright fails exited 0" + grep -qF "skills tab sweep FAILED" "$probe_out" || st_fail "a run whose Playwright fails did not say so" + grep -qF "using PW_CHROMIUM=/chromium" "$probe_out" || st_fail "a run whose Playwright fails did not name the browser as /chromium" + grep -qE "[0-9]+ failed" "$probe_out" || st_fail "a run whose Playwright fails did not print Playwright's own summary" + echo "self-test: a Playwright failure with an outside PW_CHROMIUM prints Playwright's output redacted, with no API key and no absolute path" + + # 7. Build output is printed redacted too: a self-test run as a child that + # has to build the fixture, with a stand-in go first on PATH that prints its + # working directory, its home and its arguments and exits 1. + local fakego="$WORK/st-fakego" + mkdir -p "$fakego" + # shellcheck disable=SC2016 # expanded by the stand-in's own shell + printf '#!/bin/sh\necho "go in $PWD home $HOME args: $*"\necho "go: error at $PWD/cmd/skillsfixture/main.go:1" >&2\nexit 1\n' >"$fakego/go" + chmod +x "$fakego/go" + rm -f "$probe_key" + set +e + SWEEP_SELF_TEST_CHILD="$probe_key" PATH="$fakego:$PATH" MCPPROXY_BINARY_PATH="$CORE_BIN" SKILLS_FIXTURE_BINARY="" \ + bash "$SCRIPT_DIR/$(basename "${BASH_SOURCE[0]}")" --self-test >"$probe_out" 2>&1 + probe_status=$? + set -e + st_check_child_output "a run whose go build fails" "$probe_out" "$probe_key" + [[ $probe_status -ne 0 ]] || st_fail "a run whose go build fails exited 0" + grep -qF "go: error at /cmd/skillsfixture/main.go:1" "$probe_out" || st_fail "a run whose go build fails did not print the build output redacted" + echo "self-test: a failing build prints its output redacted, with no absolute path" fi echo "self-test passed" DATA_DIR="$sweep_data_dir" @@ -636,13 +734,13 @@ if [[ $SELF_TEST -eq 1 ]]; then required go # The data-dir proof needs no frontend: a plain build of the core. CORE_BIN="$WORK/bin/mcpproxy" - (cd "$REPO_ROOT" && go build -o "$CORE_BIN" ./cmd/mcpproxy) + (cd "$REPO_ROOT" && run_logged go-build-core go build -o "$CORE_BIN" ./cmd/mcpproxy) fi FIXTURE_BIN="${SKILLS_FIXTURE_BINARY:-}" if [[ -z "$FIXTURE_BIN" ]]; then required go FIXTURE_BIN="$WORK/bin/skillsfixture" - (cd "$REPO_ROOT" && go build -o "$FIXTURE_BIN" ./cmd/skillsfixture) + (cd "$REPO_ROOT" && run_logged go-build-fixture go build -o "$FIXTURE_BIN" ./cmd/skillsfixture) fi run_self_test exit 0 @@ -664,21 +762,21 @@ if [[ -z "$CORE_BIN" ]]; then required go echo "building the frontend and the core (embedded frontend) from this checkout..." if [[ ! -d "$REPO_ROOT/frontend/node_modules" ]]; then - (cd "$REPO_ROOT/frontend" && npm ci) + (cd "$REPO_ROOT/frontend" && run_logged frontend-npm-ci npm ci) fi - (cd "$REPO_ROOT/frontend" && npm run build) + (cd "$REPO_ROOT/frontend" && run_logged frontend-build npm run build) rm -rf "$REPO_ROOT/web/frontend" mkdir -p "$REPO_ROOT/web/frontend/dist" cp -r "$REPO_ROOT/frontend/dist/." "$REPO_ROOT/web/frontend/dist/" touch "$REPO_ROOT/web/frontend/dist/.gitkeep" CORE_BIN="$WORK/bin/mcpproxy" - (cd "$REPO_ROOT" && go build -o "$CORE_BIN" ./cmd/mcpproxy) + (cd "$REPO_ROOT" && run_logged go-build-core go build -o "$CORE_BIN" ./cmd/mcpproxy) fi FIXTURE_BIN="${SKILLS_FIXTURE_BINARY:-}" if [[ -z "$FIXTURE_BIN" ]]; then required go FIXTURE_BIN="$WORK/bin/skillsfixture" - (cd "$REPO_ROOT" && go build -o "$FIXTURE_BIN" ./cmd/skillsfixture) + (cd "$REPO_ROOT" && run_logged go-build-fixture go build -o "$FIXTURE_BIN" ./cmd/skillsfixture) fi for b in "$CORE_BIN" "$FIXTURE_BIN"; do if [[ ! -x "$b" ]]; then @@ -750,7 +848,7 @@ fi HAVE_LOCK_HASH="" [[ -f "$LOCK_STAMP" ]] && HAVE_LOCK_HASH=$(cat "$LOCK_STAMP") if [[ ! -x "$SWEEP_DIR/node_modules/.bin/playwright" || "$HAVE_LOCK_HASH" != "$WANT_LOCK_HASH" ]]; then - (cd "$SWEEP_DIR" && npm ci) + (cd "$SWEEP_DIR" && run_logged sweep-npm-ci npm ci) printf '%s' "$WANT_LOCK_HASH" >"$LOCK_STAMP" fi PLAYWRIGHT_BIN="$SWEEP_DIR/node_modules/.bin/playwright" @@ -758,29 +856,30 @@ if [[ -n "${PW_CHROMIUM:-}" ]]; then # playwright.config.ts launches this binary instead of a downloaded one. echo "using PW_CHROMIUM=$(say_path "$PW_CHROMIUM") (no browser download)" elif [[ "$(uname -s)" == "Linux" ]]; then - "$PLAYWRIGHT_BIN" install --with-deps chromium + run_logged playwright-install "$PLAYWRIGHT_BIN" install --with-deps chromium else - "$PLAYWRIGHT_BIN" install chromium + run_logged playwright-install "$PLAYWRIGHT_BIN" install chromium fi # The key reaches the spec through the environment only: it sets it in the Web # UI's localStorage, never in a page URL, and records no traces (the Web UI's -# SSE URL carries it). Playwright's own output stays in the scratch dir. -set +e +# SSE URL carries it). Playwright's own output (the list reporter, failure stack +# traces, launch errors with the browser's logs) is captured into the scratch +# dir and printed redacted; its exit status is kept. +PLAYWRIGHT_STATUS=0 ( cd "$SWEEP_DIR" || exit 1 - MCPPROXY_BASE_URL="$BASE_URL" \ - MCPPROXY_API_KEY="$API_KEY" \ - SWEEP_SERVER_NAME="$SERVER" \ - SKILLS_FIXTURE_URL="$FIXTURE_URL" \ - SKILLS_SWEEP_STATE_DIR="$OUT/state" \ - SWEEP_SCREENSHOT_DIR="$OUT/screenshots" \ - SWEEP_REPORT_DIR="$OUT/playwright-report" \ - PLAYWRIGHT_JSON_OUTPUT_NAME="$OUT/playwright-results.json" \ + run_logged playwright-test env \ + MCPPROXY_BASE_URL="$BASE_URL" \ + MCPPROXY_API_KEY="$API_KEY" \ + SWEEP_SERVER_NAME="$SERVER" \ + SKILLS_FIXTURE_URL="$FIXTURE_URL" \ + SKILLS_SWEEP_STATE_DIR="$OUT/state" \ + SWEEP_SCREENSHOT_DIR="$OUT/screenshots" \ + SWEEP_REPORT_DIR="$OUT/playwright-report" \ + PLAYWRIGHT_JSON_OUTPUT_NAME="$OUT/playwright-results.json" \ "$PLAYWRIGHT_BIN" test skills-tab.spec.ts --reporter=list,json --output "$WORK/test-results" -) -PLAYWRIGHT_STATUS=$? -set -e +) || PLAYWRIGHT_STATUS=$? redact_file "$OUT/playwright-results.json" for f in "$OUT"/state/*.json; do redact_file "$f"; done From b01a8f77ee4b839f8e1925ee35fec95f63edb2fe Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Fri, 20 Nov 2026 13:29:36 +0200 Subject: [PATCH 09/18] docs(skills): browser sweep evidence for 72e14ec9d Related #1895 --- specs/125-skills-over-mcp/verification/report.html | 4 ++-- .../verification/skills-sweep-results.json | 12 ++++++------ 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/specs/125-skills-over-mcp/verification/report.html b/specs/125-skills-over-mcp/verification/report.html index 6bcdab6f5..13aba293b 100644 --- a/specs/125-skills-over-mcp/verification/report.html +++ b/specs/125-skills-over-mcp/verification/report.html @@ -6,8 +6,8 @@ .t{color:#57606a;font-size:.85em;margin:.25rem 0}img{max-width:100%;border:1px solid #d0d7de;border-radius:4px;margin:.25rem 0}code{background:#eaeef2;padding:0 .25rem;border-radius:3px;font-size:.85em} table{border-collapse:collapse;font-size:.85em;margin:.5rem 0}td,th{border:1px solid #d0d7de;padding:.2rem .4rem;text-align:left}

Spec 125: Skills tab (PR-4a) Playwright verification

-
8 of 8 scenarios passed, 2026-11-20, produced by scripts/run-skills-tab-sweep.sh from commit f1889571e465798fdf48d9c3625fe57a902db3c2 (working tree clean).
-A throwaway core (127.0.0.1:50574, scratch data dir, enable_skills: true, generated API key) served the embedded frontend; the upstream skillsfx (trust_mode: manual) was skillsfixture -addr 127.0.0.1:50572 on port 50572.
+
8 of 8 scenarios passed, 2026-11-20, produced by scripts/run-skills-tab-sweep.sh from commit 72e14ec9d60cbf58da8b15cbe99b0e3a8223f2fe (working tree clean).
+A throwaway core (127.0.0.1:52878, scratch data dir, enable_skills: true, generated API key) served the embedded frontend; the upstream skillsfx (trust_mode: manual) was skillsfixture -addr 127.0.0.1:52876 on port 52876.
Spec: e2e/web-ui-sweep/skills-tab.spec.ts. Results file: skills-sweep-results.json. Repeat: ./scripts/run-skills-tab-sweep.sh --report-html specs/125-skills-over-mcp/verification/report.html --no-screenshots.
1. Tab and list PASS

the Skills tab lists the fixture skills as awaiting review

The Skills tab is offered on a server with enable_skills on and a skills-capable upstream (cmd/skillsfixture, manual trust). The three skills show as Awaiting review and Not offered.

Screenshots (not embedded in this copy): screenshots/skills-tab-01-list.png

2. Viewer and paging PASS

views SKILL.md, pages a large file, and does not offer a binary file

SKILL.md opens in the text viewer (inert text). A 150 KiB file (data/large.txt of big) is read part by part in at least three parts: each Load more waits for its content response and for the rendered text to grow by that part. Every part is of the current copy, its digest equals the digest the core lists for that file in the current copy (the same digest the file row shows on screen), its size equals the listed size, its offset is where the previous part ended (in bytes, the first at 0) and its next_offset is where it ends; the last part has no next_offset and ends at the listed size. A binary file (logo.bin) is listed as binary, not shown, with no View button.

Screenshots (not embedded in this copy): screenshots/skills-tab-02-viewer.png, screenshots/skills-tab-03-paged.png

diff --git a/specs/125-skills-over-mcp/verification/skills-sweep-results.json b/specs/125-skills-over-mcp/verification/skills-sweep-results.json index 1c155754f..8318c317c 100644 --- a/specs/125-skills-over-mcp/verification/skills-sweep-results.json +++ b/specs/125-skills-over-mcp/verification/skills-sweep-results.json @@ -1,19 +1,19 @@ { - "checked_commit": "f1889571e465798fdf48d9c3625fe57a902db3c2", + "checked_commit": "72e14ec9d60cbf58da8b15cbe99b0e3a8223f2fe", "working_tree_dirty": false, "evidence": "commit", - "checked": "f1889571e465798fdf48d9c3625fe57a902db3c2", - "generated_at": "2026-11-20T10:53:27.518Z", + "checked": "72e14ec9d60cbf58da8b15cbe99b0e3a8223f2fe", + "generated_at": "2026-11-20T11:29:32.591Z", "fixture": { "command": [ "skillsfixture", "-addr", - "127.0.0.1:50572" + "127.0.0.1:52876" ], - "port": 50572 + "port": 52876 }, "core": { - "listen": "127.0.0.1:50574", + "listen": "127.0.0.1:52878", "server": "skillsfx", "enable_skills": true, "trust_mode": "manual" From 1698add39fea40675fc57401afe0358cfd0f3d42 Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Fri, 20 Nov 2026 13:49:57 +0200 Subject: [PATCH 10/18] fix(skills): review round 7 for the Skills tab and its sweep - SkillsPanel: refresh and every write take a number from one shared notice order when they start; a notice is published only while its action is still the newest, so a late refresh failure no longer replaces "Blocked." (and a late block no longer replaces a newer refresh notice). Spinner and button resets and the reconcile reloads do not depend on it. Deferred tests both ways. - run-skills-tab-sweep.sh: the redactor reduces any absolute filesystem path to /basename whatever its root (no root allowlist), also after an ANSI colour code or a JSON escape, and keeps URL paths, bare core routes and the placeholders. The configured paths (PW_CHROMIUM, the binaries, the browser dir) are replaced as a whole, so a path with a space is covered too. --self-test adds /data and /work roots, JSON-escaped and coloured messages, a configured path with a space, and checks the forced Playwright failure's JSON report and results file for the stand-in path and the key. - The --out and --report-html directories are made through run_logged and checked writable up front: an unwritable one fails at once with redacted diagnostics. --self-test covers an unwritable --out and report parent (a missing subdir of a read-only dir, and the read-only dir itself). Related #1895 --- .../src/components/skills/SkillsPanel.vue | 22 ++-- frontend/tests/unit/skills-panel.spec.ts | 34 +++++ scripts/run-skills-tab-sweep.sh | 117 +++++++++++++++--- 3 files changed, 149 insertions(+), 24 deletions(-) diff --git a/frontend/src/components/skills/SkillsPanel.vue b/frontend/src/components/skills/SkillsPanel.vue index 0b9c8e391..f0d3c80d1 100644 --- a/frontend/src/components/skills/SkillsPanel.vue +++ b/frontend/src/components/skills/SkillsPanel.vue @@ -148,6 +148,10 @@ function chipClass(s: SkillEntry) { // this one, is dropped. let visit = 0 let requestSeq = 0 +// The notice order shared by refresh and every write: each takes a number when +// it starts, and publishes a notice only while it is still the newest action. +// Spinner and button resets and the reconcile reloads do not depend on it. +let noticeSeq = 0 const isCurrent = (server: string, v: number, seq?: number) => server === props.serverName && v === visit && (seq === undefined || seq === requestSeq) @@ -195,7 +199,7 @@ async function load(): Promise { // newer records, so a superseded refresh reloads instead of overwriting them. let refreshSeq = 0 async function refresh() { - const server = props.serverName, v = visit, mine = ++refreshSeq, seq = ++requestSeq + const server = props.serverName, v = visit, mine = ++refreshSeq, seq = ++requestSeq, op = ++noticeSeq refreshing.value = true const res = await settle(() => api.refreshServerSkills(server)) if (!isCurrent(server, v) || mine !== refreshSeq) return @@ -209,7 +213,9 @@ async function refresh() { // A failed refresh (refresh_superseded, skills_not_supported, skills_disabled, // server_replaced, a 500) reloads the listing: the notice says it was reloaded, // and the stored records may have moved even though this refresh did not apply. - notice.value = skillErrorNotice(res.errorCode, res.error, 'refresh') + // Only while no later action (another refresh, a write) has started: the + // reconcile reload below runs either way. + if (op === noticeSeq) notice.value = skillErrorNotice(res.errorCode, res.error, 'refresh') await load() } @@ -219,14 +225,14 @@ async function refresh() { // for a skill the reviewer has left is not shown on the next one (the listing is // still reloaded). A success notice given as a function is worded from the // listing reloaded after the write (null when that reload did not apply). -// Every write takes an operation number when it starts; only the newest write -// publishes a notice, so a slow reload after an earlier write never replaces -// the notice of a later one (approve, then block: "Blocked." stays). +// Every write takes an operation number when it starts, from the one notice +// order it shares with refresh (noticeSeq); only the newest action publishes a +// notice, so a slow answer or reload of an earlier one never replaces the +// notice of a later one (approve, then block: "Blocked." stays). type DoneNotice = string | ((reloaded: SkillsListResponse | null) => string) -let writeSeq = 0 async function write(action: SkillAction, run: () => Promise<{ success: boolean; error?: string; errorCode?: string }>, done: DoneNotice) { - const server = props.serverName, v = visit, token = review.value?.token, op = ++writeSeq - const mayPublish = () => op === writeSeq && isCurrent(server, v) + const server = props.serverName, v = visit, token = review.value?.token, op = ++noticeSeq + const mayPublish = () => op === noticeSeq && isCurrent(server, v) busy.value = true const res = await settle(run) if (!isCurrent(server, v)) return diff --git a/frontend/tests/unit/skills-panel.spec.ts b/frontend/tests/unit/skills-panel.spec.ts index 7a1735e87..fae16951a 100644 --- a/frontend/tests/unit/skills-panel.spec.ts +++ b/frontend/tests/unit/skills-panel.spec.ts @@ -193,6 +193,40 @@ describe('SkillsPanel', () => { expect(w.get('[data-test="skills-notice"]').text()).toMatch(/nothing was refreshed/) }) + // Round-7 finding 1: refresh and the writes share one notice order, taken + // when each action starts; a late refresh failure never replaces a newer notice. + it('a late refresh failure never overwrites the notice of a newer block, and still resets and reloads', async () => { + m(api.getServerSkills).mockResolvedValue(ok(makeListing([makeSkill('a')]))) + m(api.blockSkills).mockResolvedValue(ok({ changed: 1 })) + let failRefresh: (v: unknown) => void = () => {} + m(api.refreshServerSkills).mockReturnValueOnce(new Promise(r => { failRefresh = r })) + const w = mountPanel(); await flushPromises() + await w.get('[data-test="skill-row-a"]').trigger('click'); await flushPromises() + await w.get('[data-test="skills-refresh"]').trigger('click'); await flushPromises() + await w.get('[data-test="skill-block"]').trigger('click'); await flushPromises() + expect(w.get('[data-test="skills-notice"] span').text()).toBe('Blocked.') + const loads = m(api.getServerSkills).mock.calls.length + failRefresh({ success: false, error: 'server srv reconnected during the refresh', errorCode: 'refresh_superseded' }); await flushPromises() + expect(w.get('[data-test="skills-notice"] span').text()).toBe('Blocked.') + expect(w.get('[data-test="skills-refresh"]').attributes('disabled')).toBeUndefined() + expect(m(api.getServerSkills).mock.calls.length).toBe(loads + 1) // the reconcile reload still runs + }) + + it('a late block notice never overwrites the notice of a newer refresh failure', async () => { + m(api.getServerSkills).mockResolvedValue(ok(makeListing([makeSkill('a')]))) + let releaseBlock: (v: unknown) => void = () => {} + m(api.blockSkills).mockReturnValueOnce(new Promise(r => { releaseBlock = r })) + const w = mountPanel(); await flushPromises() + await w.get('[data-test="skill-row-a"]').trigger('click'); await flushPromises() + await w.get('[data-test="skill-block"]').trigger('click'); await flushPromises() + m(api.refreshServerSkills).mockResolvedValueOnce({ success: false, error: 'boom-refresh' }) + await w.get('[data-test="skills-refresh"]').trigger('click'); await flushPromises() + expect(w.get('[data-test="skills-notice"] span').text()).toBe('boom-refresh') + releaseBlock(ok({ changed: 1 })); await flushPromises() + expect(w.get('[data-test="skills-notice"] span').text()).toBe('boom-refresh') + expect(w.get('[data-test="skill-block"]').attributes('disabled')).toBeUndefined() + }) + // Round-6 finding 3: only the newest write publishes its notice. it('a late approve reload never overwrites the notice of a newer block', async () => { m(api.getServerSkills).mockResolvedValueOnce(ok(makeListing([makeSkill('a')]))) diff --git a/scripts/run-skills-tab-sweep.sh b/scripts/run-skills-tab-sweep.sh index c4e07485e..1d79aee33 100755 --- a/scripts/run-skills-tab-sweep.sh +++ b/scripts/run-skills-tab-sweep.sh @@ -156,26 +156,47 @@ if [[ -n "${SWEEP_SELF_TEST_CHILD:-}" ]]; then printf '%s\n%s\n' "$API_KEY" "$WO # API key becomes *** and the local paths become placeholders. OUT_REAL is set # once OUT is known. OUT_REAL="" +# Paths the run was configured with (PW_CHROMIUM, the binaries, the browser +# dir), newline-separated: each is replaced as a whole by /basename even +# when it holds a space, wherever it is printed. Added to by redact_extra_add. +REDACT_EXTRA="" +redact_extra_add() { + local p + for p in "$@"; do [[ "$p" == /* ]] && REDACT_EXTRA+="$p"$'\n'; done + return 0 +} +redact_extra_add "${PW_CHROMIUM:-}" "${MCPPROXY_BINARY_PATH:-}" "${SKILLS_FIXTURE_BINARY:-}" "${PLAYWRIGHT_BROWSERS_PATH:-}" # shellcheck disable=SC2016 # JavaScript, expanded by node REDACT_JS=' const fs = require("fs"), f = process.argv[1], e = process.env let t = f ? fs.readFileSync(f, "utf8") : fs.readFileSync(0, "utf8") const key = e.SWEEP_REDACT_KEY if (key) for (const k of [key, encodeURIComponent(key)]) t = t.split(k).join("***") +const base = p => p.split("/").filter(Boolean).pop() || "" const paths = [[e.SWEEP_REDACT_OUT, ""], [e.SWEEP_REDACT_WORK, ""], [e.SWEEP_REDACT_REPO, ""], [e.SWEEP_REDACT_HOME, "~"]] .filter(([p]) => p && p.length > 1).sort((a, b) => b[0].length - a[0].length) +// A configured path outside the known prefixes, as a whole (it may hold a space). +const known = paths.map(([p]) => p) +const extra = (e.SWEEP_REDACT_EXTRA || "").split("\n") + .filter(p => p.length > 1 && p.startsWith("/") && !known.some(k => p === k || p.startsWith(k + "/"))) + .sort((a, b) => b.length - a.length) +for (const p of extra) t = t.split(p).join("/" + base(p)) for (const [p, r] of paths) t = t.split(p).join(r) -// Any other absolute local path (a browser named by PW_CHROMIUM, a browser -// download dir, a toolchain path in a stack trace or in PATH) is reduced to -// /basename. Only paths under a filesystem root are touched, so a URL path -// (http://host:port/api/...) or a placeholder (/e2e/...) is kept. -const roots = "Users|home|private|var|tmp|usr|opt|etc|Library|System|Applications|Volumes|nix|root|snap|mnt|media|srv|bin|sbin|lib|lib64|run|__w" -const abs = new RegExp("(^|[\\s\"\x27`(\\[=,:;])(/(?:" + roots + ")(?=/|[\\s\"\x27`()\\[\\],:;]|$)(?:/[^\\s\"\x27`()\\[\\],:;]*)*)", "gm") -t = t.replace(abs, (m, pre, p) => pre + "/" + p.split("/").filter(Boolean).pop()) +// Any other absolute filesystem path, whatever its root (/data, /work, /opt, +// ...), is reduced to /basename: a path that starts the text or follows +// a space, a quote, a bracket, "=", ",", ":", ";", an ANSI colour code or a +// JSON escape (\n, \t, \u001b[..m). A URL path follows its host, so it is kept +// (http://127.0.0.1:1/api/...), and so is a bare route of the core (/api/..., +// /mcp, /ui, /events) and a placeholder (/e2e/...). +const pre = "(^|[\\s\"\x27`(\\[{=,:;]|\x1b\\[[0-9;]*m|\\\\u001b\\[[0-9;]*m|\\\\[nrt\"])" +const seg = "[^\\s\"\x27`()\\[\\]{}<>,:;\\\\/\x1b]+" +const route = "(?!(?:api|mcp|ui|events|healthz|readyz)(?:[/?#\\s\"\x27`)\\],:;\\\\]|$))" +const abs = new RegExp(pre + "(/" + route + seg + "(?:/" + seg + ")*/?)", "gm") +t = t.replace(abs, (m, p1, p) => p1 + "/" + base(p)) if (f) fs.writeFileSync(f, t); else process.stdout.write(t)' redact_node() { SWEEP_REDACT_KEY="$API_KEY" SWEEP_REDACT_OUT="$OUT_REAL" SWEEP_REDACT_REPO="$REPO_ROOT" \ - SWEEP_REDACT_WORK="$WORK" SWEEP_REDACT_HOME="$OPERATOR_HOME" node -e "$REDACT_JS" "$@" + SWEEP_REDACT_WORK="$WORK" SWEEP_REDACT_HOME="$OPERATOR_HOME" SWEEP_REDACT_EXTRA="$REDACT_EXTRA" node -e "$REDACT_JS" "$@" } redact_file() { [[ -f "$1" ]] || return 0 @@ -500,7 +521,21 @@ run_self_test() { got_path=$(say_path "/srv/odd place/chrome"); [[ "$got_path" == "/chrome" ]] || st_fail "say_path of an outside path with a space gave '$got_path'" got_path=$(printf 'launch /opt/google/chrome/chrome failed; PATH=/usr/local/bin:/opt/homebrew/bin url http://127.0.0.1:1/api/v1/servers key %s' "$API_KEY" | redact_stream) [[ "$got_path" == 'launch /chrome failed; PATH=/bin:/bin url http://127.0.0.1:1/api/v1/servers key ***' ]] || st_fail "redact_stream gave '$got_path'" - echo "self-test: printed paths are relative, placeholders or /basename; URLs are kept" + # Roots in no list: /data and /work (round 7), a colour code and JSON escapes + # in front of a path (Playwright's JSON report), and a bare core route kept. + got_path=$(printf 'executable doesn'\''t exist at /data/tools/chromium; /work/tools/chromium:1 GET /api/v1/servers and /mcp' | redact_stream) + [[ "$got_path" == 'executable doesn'\''t exist at /chromium; /chromium:1 GET /api/v1/servers and /mcp' ]] || st_fail "redact_stream of /data and /work roots gave '$got_path'" + got_path=$(printf '{"message":"\\u001b[31mError\\u001b[39m: at /data/tools/chromium\\n/work/x/y.js\\t\\"/data/q\\""}' | redact_stream) + [[ "$got_path" == '{"message":"\u001b[31mError\u001b[39m: at /chromium\n/y.js\t\"/q\""}' ]] || st_fail "redact_stream of a JSON-escaped message gave '$got_path'" + got_path=$(printf 'x\033[2m/data/tools/chromium\033[22m' | redact_stream) + [[ "$got_path" == $'x\033[2m/chromium\033[22m' ]] || st_fail "redact_stream after an ANSI code gave '$got_path'" + # A configured path with a space is replaced as a whole. + local saved_extra="$REDACT_EXTRA" + redact_extra_add "/data/odd tools/chromium" + got_path=$(printf 'launching /data/odd tools/chromium --headless' | redact_stream) + REDACT_EXTRA="$saved_extra" + [[ "$got_path" == 'launching /chromium --headless' ]] || st_fail "redact_stream of a configured path with a space gave '$got_path'" + echo "self-test: printed paths are relative, placeholders or /basename (any root, configured paths whole); URLs and routes are kept" # 2. An ambient MCPPROXY_DATA_DIR / MCPPROXY_DATA does not reach the core. decoy_new="$WORK/decoy-data-dir" @@ -681,8 +716,12 @@ if (r.checked_commit !== "0123456789abcdef0123456789abcdef01234567" || r.working # it) and exits 1: the run must fail, say so, name the browser as # /chromium, print Playwright's failure, and print no key and no # absolute path of the stand-in. - local ext ext_real - ext=$(mktemp -d /tmp/skills-sweep-pwext.XXXXXX) + local ext ext_dir ext_real f + ext_dir=$(mktemp -d /tmp/skills-sweep-pwext.XXXXXX) + # A space in the path: the generic rule alone would stop at it; the + # configured path is replaced as a whole. + ext="$ext_dir/odd tools" + mkdir -p "$ext" ext_real=$(cd "$ext" && pwd -P) # shellcheck disable=SC2016 # expanded by the stand-in's own shell printf '#!/bin/sh\necho "stand-in browser $0 args: $*" >&2\nenv >&2\nexit 1\n' >"$ext/chromium" @@ -693,10 +732,14 @@ if (r.checked_commit !== "0123456789abcdef0123456789abcdef01234567" || r.working bash "$SCRIPT_DIR/$(basename "${BASH_SOURCE[0]}")" --out "$WORK/st-pw-fail" >"$probe_out" 2>&1 probe_status=$? set -e - rm -rf "$ext" + rm -rf "$ext_dir" st_check_child_output "a run whose Playwright fails" "$probe_out" "$probe_key" - for p in "$ext" "$ext_real" "${ext_real#/private}"; do - grep -qF "$p" "$probe_out" && st_fail "a run whose Playwright fails printed the stand-in browser's path ($(grep -cF "$p" "$probe_out") lines)" + for f in "$probe_out" "$WORK/st-pw-fail/playwright-results.json" "$WORK/st-pw-fail/skills-sweep-results.json"; do + [[ -f "$f" ]] || st_fail "a run whose Playwright fails left no $(basename "$f")" + grep -qF "$(sed -n 1p "$probe_key")" "$f" && st_fail "a run whose Playwright fails wrote its API key into $(basename "$f")" + for p in "$ext_dir" "$ext_real" "${ext_real#/private}" "${ext_dir#/private}"; do + grep -qF "$p" "$f" && st_fail "a run whose Playwright fails printed the stand-in browser's path into $(basename "$f") ($(grep -cF "$p" "$f") lines)" + done done [[ $probe_status -ne 0 ]] || st_fail "a run whose Playwright fails exited 0" grep -qF "skills tab sweep FAILED" "$probe_out" || st_fail "a run whose Playwright fails did not say so" @@ -722,6 +765,35 @@ if (r.checked_commit !== "0123456789abcdef0123456789abcdef01234567" || r.working [[ $probe_status -ne 0 ]] || st_fail "a run whose go build fails exited 0" grep -qF "go: error at /cmd/skillsfixture/main.go:1" "$probe_out" || st_fail "a run whose go build fails did not print the build output redacted" echo "self-test: a failing build prints its output redacted, with no absolute path" + + # 8. An unwritable --out or report parent fails at once, with the mkdir + # diagnostics redacted: a read-only dir (a new subdir cannot be made in it, + # and the dir itself is not writable). Skipped as root, who can write it. + if [[ "$(id -u)" != "0" ]]; then + local ro="$WORK/st-readonly" case_args + mkdir -p "$ro" + chmod 555 "$ro" + for case_args in "--out|$ro/sub" "--out|$ro" "--report-html|$ro/sub/report.html" "--report-html|$ro/report.html"; do + IFS='|' read -r which p <<<"$case_args" + rm -f "$probe_key" + set +e + if [[ $which == --out ]]; then + SWEEP_SELF_TEST_CHILD="$probe_key" MCPPROXY_BINARY_PATH="$CORE_BIN" SKILLS_FIXTURE_BINARY="$FIXTURE_BIN" \ + bash "$SCRIPT_DIR/$(basename "${BASH_SOURCE[0]}")" --out "$p" >"$probe_out" 2>&1 + else + SWEEP_SELF_TEST_CHILD="$probe_key" MCPPROXY_BINARY_PATH="$CORE_BIN" SKILLS_FIXTURE_BINARY="$FIXTURE_BIN" \ + bash "$SCRIPT_DIR/$(basename "${BASH_SOURCE[0]}")" --out "$WORK/st-ro-out" --report-html "$p" >"$probe_out" 2>&1 + fi + probe_status=$? + set -e + st_check_child_output "a run with an unwritable $which" "$probe_out" "$probe_key" + [[ $probe_status -ne 0 ]] || st_fail "a run with an unwritable $which ($(say_path "$p")) exited 0" + grep -qF "cannot create or write the" "$probe_out" || st_fail "a run with an unwritable $which ($(say_path "$p")) did not say so" + grep -qF "skillsfixture ready" "$probe_out" && st_fail "a run with an unwritable $which started the sweep" + done + chmod 755 "$ro" + echo "self-test: an unwritable --out or report directory fails at once, with its diagnostics redacted" + fi fi echo "self-test passed" DATA_DIR="$sweep_data_dir" @@ -746,11 +818,24 @@ if [[ $SELF_TEST -eq 1 ]]; then exit 0 fi -mkdir -p "$OUT" +# The output dirs are made through run_logged, so a failure's diagnostics +# (mkdir names the absolute path) are printed redacted, and checked writable +# up front, so an unwritable dir fails here and not after the whole sweep. +# $1: what it is, $2: the dir. +make_writable_dir() { + local status=0 + run_logged "mkdir-$1" mkdir -p "$2" >&2 || status=$? + if [[ $status -eq 0 && ! -w "$2" ]]; then status=1; fi + if [[ $status -ne 0 ]]; then + echo "cannot create or write the $1 directory $(say_path "$2") (status $status)" >&2 + exit 1 + fi +} +make_writable_dir out "$OUT" OUT=$(cd "$OUT" && pwd -P) OUT_REAL="$OUT" if [[ -n "$REPORT_HTML" ]]; then - mkdir -p "$(dirname "$REPORT_HTML")" + make_writable_dir report "$(dirname "$REPORT_HTML")" REPORT_HTML="$(cd "$(dirname "$REPORT_HTML")" && pwd -P)/$(basename "$REPORT_HTML")" fi rm -rf "$OUT/screenshots" "$OUT/state" "$OUT/playwright-results.json" "$OUT/skills-sweep-results.json" From be491e063ba574057ac6bee12d4dcaef49982624 Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Fri, 20 Nov 2026 13:52:28 +0200 Subject: [PATCH 11/18] docs(skills): browser sweep evidence for 1698add39 Related #1895 --- specs/125-skills-over-mcp/verification/report.html | 4 ++-- .../verification/skills-sweep-results.json | 12 ++++++------ 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/specs/125-skills-over-mcp/verification/report.html b/specs/125-skills-over-mcp/verification/report.html index 13aba293b..e43b582b3 100644 --- a/specs/125-skills-over-mcp/verification/report.html +++ b/specs/125-skills-over-mcp/verification/report.html @@ -6,8 +6,8 @@ .t{color:#57606a;font-size:.85em;margin:.25rem 0}img{max-width:100%;border:1px solid #d0d7de;border-radius:4px;margin:.25rem 0}code{background:#eaeef2;padding:0 .25rem;border-radius:3px;font-size:.85em} table{border-collapse:collapse;font-size:.85em;margin:.5rem 0}td,th{border:1px solid #d0d7de;padding:.2rem .4rem;text-align:left}

Spec 125: Skills tab (PR-4a) Playwright verification

-
8 of 8 scenarios passed, 2026-11-20, produced by scripts/run-skills-tab-sweep.sh from commit 72e14ec9d60cbf58da8b15cbe99b0e3a8223f2fe (working tree clean).
-A throwaway core (127.0.0.1:52878, scratch data dir, enable_skills: true, generated API key) served the embedded frontend; the upstream skillsfx (trust_mode: manual) was skillsfixture -addr 127.0.0.1:52876 on port 52876.
+
8 of 8 scenarios passed, 2026-11-20, produced by scripts/run-skills-tab-sweep.sh from commit 1698add39fea40675fc57401afe0358cfd0f3d42 (working tree clean).
+A throwaway core (127.0.0.1:64486, scratch data dir, enable_skills: true, generated API key) served the embedded frontend; the upstream skillsfx (trust_mode: manual) was skillsfixture -addr 127.0.0.1:64484 on port 64484.
Spec: e2e/web-ui-sweep/skills-tab.spec.ts. Results file: skills-sweep-results.json. Repeat: ./scripts/run-skills-tab-sweep.sh --report-html specs/125-skills-over-mcp/verification/report.html --no-screenshots.
1. Tab and list PASS

the Skills tab lists the fixture skills as awaiting review

The Skills tab is offered on a server with enable_skills on and a skills-capable upstream (cmd/skillsfixture, manual trust). The three skills show as Awaiting review and Not offered.

Screenshots (not embedded in this copy): screenshots/skills-tab-01-list.png

2. Viewer and paging PASS

views SKILL.md, pages a large file, and does not offer a binary file

SKILL.md opens in the text viewer (inert text). A 150 KiB file (data/large.txt of big) is read part by part in at least three parts: each Load more waits for its content response and for the rendered text to grow by that part. Every part is of the current copy, its digest equals the digest the core lists for that file in the current copy (the same digest the file row shows on screen), its size equals the listed size, its offset is where the previous part ended (in bytes, the first at 0) and its next_offset is where it ends; the last part has no next_offset and ends at the listed size. A binary file (logo.bin) is listed as binary, not shown, with no View button.

Screenshots (not embedded in this copy): screenshots/skills-tab-02-viewer.png, screenshots/skills-tab-03-paged.png

diff --git a/specs/125-skills-over-mcp/verification/skills-sweep-results.json b/specs/125-skills-over-mcp/verification/skills-sweep-results.json index 8318c317c..3246eea31 100644 --- a/specs/125-skills-over-mcp/verification/skills-sweep-results.json +++ b/specs/125-skills-over-mcp/verification/skills-sweep-results.json @@ -1,19 +1,19 @@ { - "checked_commit": "72e14ec9d60cbf58da8b15cbe99b0e3a8223f2fe", + "checked_commit": "1698add39fea40675fc57401afe0358cfd0f3d42", "working_tree_dirty": false, "evidence": "commit", - "checked": "72e14ec9d60cbf58da8b15cbe99b0e3a8223f2fe", - "generated_at": "2026-11-20T11:29:32.591Z", + "checked": "1698add39fea40675fc57401afe0358cfd0f3d42", + "generated_at": "2026-11-20T11:52:22.280Z", "fixture": { "command": [ "skillsfixture", "-addr", - "127.0.0.1:52876" + "127.0.0.1:64484" ], - "port": 52876 + "port": 64484 }, "core": { - "listen": "127.0.0.1:52878", + "listen": "127.0.0.1:64486", "server": "skillsfx", "enable_skills": true, "trust_mode": "manual" From 3e59c6efe5533c7f1743b0d4f052855db12e472d Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Fri, 20 Nov 2026 13:54:34 +0200 Subject: [PATCH 12/18] Redact macOS temporary path aliases in Skills sweep diagnostics --- scripts/run-skills-tab-sweep.sh | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/scripts/run-skills-tab-sweep.sh b/scripts/run-skills-tab-sweep.sh index 1d79aee33..cbcea67a4 100755 --- a/scripts/run-skills-tab-sweep.sh +++ b/scripts/run-skills-tab-sweep.sh @@ -181,7 +181,13 @@ const extra = (e.SWEEP_REDACT_EXTRA || "").split("\n") .filter(p => p.length > 1 && p.startsWith("/") && !known.some(k => p === k || p.startsWith(k + "/"))) .sort((a, b) => b.length - a.length) for (const p of extra) t = t.split(p).join("/" + base(p)) -for (const [p, r] of paths) t = t.split(p).join(r) +// macOS tools can print the same temporary directory with or without /private. +for (const [p, r] of paths) { + t = t.split(p).join(r) + if (process.platform === "darwin" && /^\/private\/(tmp|var)\//.test(p)) { + t = t.split(p.slice("/private".length)).join(r) + } +} // Any other absolute filesystem path, whatever its root (/data, /work, /opt, // ...), is reduced to /basename: a path that starts the text or follows // a space, a quote, a bracket, "=", ",", ":", ";", an ANSI colour code or a @@ -724,7 +730,7 @@ if (r.checked_commit !== "0123456789abcdef0123456789abcdef01234567" || r.working mkdir -p "$ext" ext_real=$(cd "$ext" && pwd -P) # shellcheck disable=SC2016 # expanded by the stand-in's own shell - printf '#!/bin/sh\necho "stand-in browser $0 args: $*" >&2\nenv >&2\nexit 1\n' >"$ext/chromium" + printf '#!/bin/sh\necho "stand-in browser $0 args: $*" >&2\necho "MCPPROXY_API_KEY=$MCPPROXY_API_KEY" >&2\nexit 1\n' >"$ext/chromium" chmod +x "$ext/chromium" rm -f "$probe_key" set +e From 30e6443d841bbd246497cb5d410b0ed9ffa322f8 Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Fri, 20 Nov 2026 14:06:33 +0200 Subject: [PATCH 13/18] fix(skills): review round 8 for the Skills tab and its sweep SkillsPanel: - A refresh refused with server_replaced (error_code or the message prefix, through skillErrorCode) latches the open review stale before its reload, so a pending or failed reload never leaves Approve on. - Unmounting ends the visit: a write or refresh answered after unmount shows nothing and starts no reconcile request. - A notice is shown when no later action has already shown one (lastPublishedOp), so a successful refresh, which shows nothing, no longer hides an earlier approve's failure. run-skills-tab-sweep.sh: - The HTML report writer (write_report) no longer redacts the escaped HTML a second time, which put a raw after entities such as >. - The catch-all reduces an absolute path only when its first segment exists on this machine, so regex literals (/approved/i, /tab-active/) and route fragments (/skills/refresh, /servers/{id}/skills) are kept; configured paths are still replaced whole. A root this machine does not have is kept (said in the comment and in docs/development/web-ui-verification.md). - An existing read-only report file fails up front; the browsers dir goes through make_writable_dir; the report writer's output is captured, printed redacted, and its status kept. - Self-test 6's stand-in browser dumps its whole environment again. - --self-test covers all of these: the kept strings, a temp-dir path, a missing root, the report strings after escaping, a failing report write, a read-only report file and an unwritable PLAYWRIGHT_BROWSERS_PATH. Related #1895 --- docs/development/web-ui-verification.md | 2 +- .../src/components/skills/SkillsPanel.vue | 37 ++- frontend/tests/unit/skills-panel.spec.ts | 69 +++++ scripts/run-skills-tab-sweep.sh | 248 ++++++++++++------ 4 files changed, 267 insertions(+), 89 deletions(-) diff --git a/docs/development/web-ui-verification.md b/docs/development/web-ui-verification.md index 45171cacc..ec7198f79 100644 --- a/docs/development/web-ui-verification.md +++ b/docs/development/web-ui-verification.md @@ -40,7 +40,7 @@ Alongside it, [`e2e/web-ui-sweep/visual-a11y-sweep.spec.ts`](https://github.com/ ./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); `--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. +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. diff --git a/frontend/src/components/skills/SkillsPanel.vue b/frontend/src/components/skills/SkillsPanel.vue index f0d3c80d1..86b9c142e 100644 --- a/frontend/src/components/skills/SkillsPanel.vue +++ b/frontend/src/components/skills/SkillsPanel.vue @@ -149,9 +149,16 @@ function chipClass(s: SkillEntry) { let visit = 0 let requestSeq = 0 // The notice order shared by refresh and every write: each takes a number when -// it starts, and publishes a notice only while it is still the newest action. +// it starts, and its notice is shown only if no later action has already shown +// one (an action that shows nothing, e.g. a successful refresh, hides nothing). // Spinner and button resets and the reconcile reloads do not depend on it. let noticeSeq = 0 +let lastPublishedOp = 0 +function publish(op: number, text: string) { + if (op <= lastPublishedOp) return + lastPublishedOp = op + notice.value = text +} const isCurrent = (server: string, v: number, seq?: number) => server === props.serverName && v === visit && (seq === undefined || seq === requestSeq) @@ -213,9 +220,13 @@ async function refresh() { // A failed refresh (refresh_superseded, skills_not_supported, skills_disabled, // server_replaced, a 500) reloads the listing: the notice says it was reloaded, // and the stored records may have moved even though this refresh did not apply. - // Only while no later action (another refresh, a write) has started: the + // Its notice is shown unless a later action already showed one (publish); the // reconcile reload below runs either way. - if (op === noticeSeq) notice.value = skillErrorNotice(res.errorCode, res.error, 'refresh') + // server_replaced: the open review belongs to the server that was replaced; + // latch it before the reload, as a write does. + const code = skillErrorCode(res.errorCode, res.error) + if (code === 'server_replaced') markStale(review.value?.token) + publish(op, skillErrorNotice(code, res.error, 'refresh')) await load() } @@ -226,13 +237,14 @@ async function refresh() { // still reloaded). A success notice given as a function is worded from the // listing reloaded after the write (null when that reload did not apply). // Every write takes an operation number when it starts, from the one notice -// order it shares with refresh (noticeSeq); only the newest action publishes a -// notice, so a slow answer or reload of an earlier one never replaces the -// notice of a later one (approve, then block: "Blocked." stays). +// order it shares with refresh (noticeSeq); a notice is shown only if no later +// action has shown one (publish), so a slow answer or reload of an earlier one +// never replaces the notice of a later one (approve, then block: "Blocked." +// stays), and an action that shows nothing hides nothing. type DoneNotice = string | ((reloaded: SkillsListResponse | null) => string) async function write(action: SkillAction, run: () => Promise<{ success: boolean; error?: string; errorCode?: string }>, done: DoneNotice) { const server = props.serverName, v = visit, token = review.value?.token, op = ++noticeSeq - const mayPublish = () => op === noticeSeq && isCurrent(server, v) + const mayPublish = () => isCurrent(server, v) busy.value = true const res = await settle(run) if (!isCurrent(server, v)) return @@ -245,7 +257,7 @@ async function write(action: SkillAction, run: () => Promise<{ success: boolean; // The server says the open version is out of date: latch it before the // reload, so a reload that is pending or fails never re-enables Approve. if (code && STALE_CODES.has(code)) markStale(token) - if (mayPublish()) notice.value = res.success ? done as string : skillErrorNotice(code, res.error, action) + if (mayPublish()) publish(op, res.success ? done as string : skillErrorNotice(code, res.error, action)) } await load() return @@ -253,7 +265,7 @@ async function write(action: SkillAction, run: () => Promise<{ success: boolean; const reloaded = await load() // Still the newest write and the same review (or none: the reload dropped a // skill that vanished). - if (mayPublish() && (!review.value || review.value.token === token)) notice.value = done(reloaded) + if (mayPublish() && (!review.value || review.value.token === token)) publish(op, done(reloaded)) } // Approve sends exactly the hash and the incarnation the reviewer opened. @@ -305,5 +317,10 @@ onMounted(() => { window.addEventListener('mcpproxy:skills-changed', onSkillsChanged) void load() }) -onUnmounted(() => window.removeEventListener('mcpproxy:skills-changed', onSkillsChanged)) +// Unmounting ends the visit: an answer still pending (a write, a refresh, a +// load) then fails isCurrent(), so it shows nothing and starts no reload. +onUnmounted(() => { + window.removeEventListener('mcpproxy:skills-changed', onSkillsChanged) + visit++ +}) diff --git a/frontend/tests/unit/skills-panel.spec.ts b/frontend/tests/unit/skills-panel.spec.ts index fae16951a..afb485154 100644 --- a/frontend/tests/unit/skills-panel.spec.ts +++ b/frontend/tests/unit/skills-panel.spec.ts @@ -193,6 +193,75 @@ describe('SkillsPanel', () => { expect(w.get('[data-test="skills-notice"]').text()).toMatch(/nothing was refreshed/) }) + // Round-8 finding A: a refresh refused with server_replaced latches the open + // review stale before its reload, like a write does. + describe('refresh 409 server_replaced', () => { + const bodies = [ + ['with error_code', { success: false, error: 'server_replaced: the server was removed or replaced while its skills were read; retry', errorCode: 'server_replaced' }], + ['message only', { success: false, error: 'server_replaced: the server was removed or replaced while its skills were read; retry' }], + ] as const + const reloads: Array<[string, () => unknown]> = [ + ['pending', () => new Promise(() => {})], + ['failed', () => Promise.resolve({ success: false, error: 'reload boom' })], + ] + for (const [kind, body] of bodies) { + for (const [outcome, reload] of reloads) { + it(`${kind}, reload ${outcome}: the review is stale and Approve is off`, async () => { + m(api.getServerSkills).mockResolvedValueOnce(ok(makeListing([makeSkill('a')]))) + const w = mountPanel(); await flushPromises() + await w.get('[data-test="skill-row-a"]').trigger('click'); await flushPromises() + m(api.getServerSkills).mockImplementation(reload) + m(api.refreshServerSkills).mockResolvedValueOnce(body) + await w.get('[data-test="skills-refresh"]').trigger('click'); await flushPromises() + expect(api.getServerSkills).toHaveBeenCalledTimes(2) + expect(w.get('[data-test="skills-notice"]').text()).toMatch(/removed and added again/i) + expect(w.find('[data-test="skill-stale"]').exists()).toBe(true) + expect(w.get('[data-test="skill-approve"]').attributes('disabled')).toBeDefined() + await w.get('[data-test="skill-approve"]').trigger('click'); await flushPromises() + expect(api.approveSkills).not.toHaveBeenCalled() + }) + } + } + }) + + // Round-8 finding B: answers that arrive after unmount publish nothing and + // start no request. + it('a write and a refresh answered after unmount start no further request', async () => { + m(api.getServerSkills).mockResolvedValue(ok(makeListing([makeSkill('a')]))) + let releaseApprove: (v: unknown) => void = () => {} + let releaseRefresh: (v: unknown) => void = () => {} + m(api.approveSkills).mockReturnValueOnce(new Promise(r => { releaseApprove = r })) + m(api.refreshServerSkills).mockReturnValueOnce(new Promise(r => { releaseRefresh = r })) + const w = mountPanel(); await flushPromises() + await w.get('[data-test="skill-row-a"]').trigger('click'); await flushPromises() + await w.get('[data-test="skill-approve"]').trigger('click'); await flushPromises() + await w.get('[data-test="skills-refresh"]').trigger('click'); await flushPromises() + const calls = () => [api.getServerSkills, api.refreshServerSkills, api.approveSkills, api.blockSkills, api.unblockSkills, api.getSkillContent] + .reduce((n, f) => n + m(f).mock.calls.length, 0) + const before = calls() + w.unmount() + releaseApprove(ok({ approved: 1 })) + releaseRefresh({ success: false, error: 'boom', errorCode: 'refresh_superseded' }) + await flushPromises() + expect(calls()).toBe(before) + }) + + // Round-8 finding C: a refresh that publishes nothing does not hide the + // failure of an earlier write. + it('an approve failing after a successful refresh still shows its notice', async () => { + m(api.getServerSkills).mockResolvedValue(ok(makeListing([makeSkill('a')]))) + let releaseApprove: (v: unknown) => void = () => {} + m(api.approveSkills).mockReturnValueOnce(new Promise(r => { releaseApprove = r })) + const w = mountPanel(); await flushPromises() + await w.get('[data-test="skill-row-a"]').trigger('click'); await flushPromises() + await w.get('[data-test="skill-approve"]').trigger('click'); await flushPromises() + m(api.refreshServerSkills).mockResolvedValueOnce(ok(makeListing([makeSkill('a')]))) + await w.get('[data-test="skills-refresh"]').trigger('click'); await flushPromises() + expect(w.find('[data-test="skills-notice"]').exists()).toBe(false) + releaseApprove(OUT_OF_DATE); await flushPromises() + expect(w.get('[data-test="skills-notice"]').text()).toMatch(/changed since you opened it/i) + }) + // Round-7 finding 1: refresh and the writes share one notice order, taken // when each action starts; a late refresh failure never replaces a newer notice. it('a late refresh failure never overwrites the notice of a newer block, and still resets and reloads', async () => { diff --git a/scripts/run-skills-tab-sweep.sh b/scripts/run-skills-tab-sweep.sh index cbcea67a4..fba2c753f 100755 --- a/scripts/run-skills-tab-sweep.sh +++ b/scripts/run-skills-tab-sweep.sh @@ -188,17 +188,28 @@ for (const [p, r] of paths) { t = t.split(p.slice("/private".length)).join(r) } } -// Any other absolute filesystem path, whatever its root (/data, /work, /opt, -// ...), is reduced to /basename: a path that starts the text or follows -// a space, a quote, a bracket, "=", ",", ":", ";", an ANSI colour code or a -// JSON escape (\n, \t, \u001b[..m). A URL path follows its host, so it is kept +// Any other absolute filesystem path is reduced to /basename when its +// first segment exists on this machine (/usr, /tmp, /var, /opt, /data where +// there is one, ...): a path that starts the text or follows a space, a quote, +// a bracket, "=", ",", ":", ";", an ANSI colour code or a JSON escape (\n, \t, +// \u001b[..m). Text whose first segment does not exist here is not a local +// path and is kept: a regex literal (/approved/i), a route fragment +// (/skills/refresh, /servers/{id}/skills), and so a path under a root this +// machine does not have. A configured path (PW_CHROMIUM, ...) is replaced whole +// above, whatever its root. A URL path follows its host, so it is kept // (http://127.0.0.1:1/api/...), and so is a bare route of the core (/api/..., // /mcp, /ui, /events) and a placeholder (/e2e/...). const pre = "(^|[\\s\"\x27`(\\[{=,:;]|\x1b\\[[0-9;]*m|\\\\u001b\\[[0-9;]*m|\\\\[nrt\"])" const seg = "[^\\s\"\x27`()\\[\\]{}<>,:;\\\\/\x1b]+" const route = "(?!(?:api|mcp|ui|events|healthz|readyz)(?:[/?#\\s\"\x27`)\\],:;\\\\]|$))" const abs = new RegExp(pre + "(/" + route + seg + "(?:/" + seg + ")*/?)", "gm") -t = t.replace(abs, (m, p1, p) => p1 + "/" + base(p)) +const rootExists = new Map() +const isLocal = p => { + const first = p.split("/")[1] + if (!rootExists.has(first)) rootExists.set(first, fs.existsSync("/" + first)) + return rootExists.get(first) +} +t = t.replace(abs, (m, p1, p) => isLocal(p) ? p1 + "/" + base(p) : m) if (f) fs.writeFileSync(f, t); else process.stdout.write(t)' redact_node() { SWEEP_REDACT_KEY="$API_KEY" SWEEP_REDACT_OUT="$OUT_REAL" SWEEP_REDACT_REPO="$REPO_ROOT" \ @@ -482,6 +493,71 @@ NODE return $status } +# write_report OUT DEST SCREENSHOTS(1|0): the HTML report from +# OUT/skills-sweep-results.json, one section per scenario. Every string in it +# comes from the redacted results file and is HTML-escaped, so the report is not +# redacted again (a second pass would match after an entity such as > and +# put a raw into the HTML). The writer's own output (a failed write +# names the destination) is captured and printed redacted; its status is kept. +write_report() { + run_logged report-html node - "$1" "$2" "$3" >&2 <<'NODE' +const fs = require('fs'), path = require('path') +const [out, dest, screenshots] = process.argv.slice(2) +const withShots = screenshots === '1' +const r = JSON.parse(fs.readFileSync(path.join(out, 'skills-sweep-results.json'), 'utf8')) +const esc = s => String(s).replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]) +const img = name => { + if (!withShots) return '' + const f = path.join(out, 'screenshots', `skills-tab-${name}.png`) + return fs.existsSync(f) ? `${esc(name)}` : '' +} +const shotNote = shots => (!withShots && shots.length) + ? `

Screenshots (not embedded in this copy): ${shots.map(s => `screenshots/skills-tab-${esc(s)}.png`).join(', ')}

` : '' +// One section per scenario, in spec order, with what it proves and its screenshots. +const about = [ + ['Tab and list', 'The Skills tab is offered on a server with enable_skills on and a skills-capable upstream (cmd/skillsfixture, manual trust). The three skills show as Awaiting review and Not offered.', ['01-list']], + ['Viewer and paging', 'SKILL.md opens in the text viewer (inert text). A 150 KiB file (data/large.txt of big) is read part by part in at least three parts: each Load more waits for its content response and for the rendered text to grow by that part. Every part is of the current copy, its digest equals the digest the core lists for that file in the current copy (the same digest the file row shows on screen), its size equals the listed size, its offset is where the previous part ended (in bytes, the first at 0) and its next_offset is where it ends; the last part has no next_offset and ends at the listed size. A binary file (logo.bin) is listed as binary, not shown, with no View button.', ['02-viewer', '03-paged']], + ['Approve', 'Approve sends the current_hash and incarnation of the version the reviewer opened; the chip turns Approved.', ['04-approved']], + ['Changed while open, re-open, diff', 'A mutate without the X-Skills-Fixture header is refused (403). The approved skill plain changes upstream while it is open; after Refresh the chip says Changed and the open review says it changed while you were reviewing it (the review shows the approved version, so it offers no Approve). Re-opening shows the file-set diff (SKILL.md changed) and the line diff with the added line; approving binds the new hash.', ['05a-stale', '05-changed-diff']], + ['Pending skill changed while open', 'The pending skill with-files changes upstream while it is open; after Refresh the review is marked stale and its Approve button stays on screen but disabled, until the new version is re-opened.', ['05b-pending-stale']], + ['Live skills.changed', 'With the pending skill big open, its SKILL.md changes upstream and the refresh is made through POST /api/v1/servers/{id}/skills/refresh, not in the page. The core\'s skills.changed SSE frame, re-dispatched by the Web UI, reloads the listing by itself and the open review shows the stale banner with Approve disabled.', ['05c-live-event-stale']], + ['Block and unblock', 'Block marks the skill Blocked and removes Approve; Unblock returns it to Awaiting review.', ['06-blocked']], + ['Reload', 'The tab survives a reload through ?tab=skills, and no uncaught page error was thrown in any scenario.', []], +] +const stateTable = step => { + const s = r.states[step] + if (!s) return `

missing

` + return `${s.skills.map(k => + ``).join('')}
skillstatusblockedavailablecurrent_hashapproved_hash
${esc(k.path)}${esc(k.status)}${k.blocked}${k.available}${esc(k.current_hash)}${esc(k.approved_hash || '')}
` +} +const passed = r.scenarios.filter(s => s.passed).length +const sections = r.scenarios.map((s, i) => { + const [title, text, shots] = about[i] || [s.title, '', []] + const badge = s.passed ? 'PASS' : 'FAIL' + return `
${i + 1}. ${esc(title)} ${badge}

${esc(s.title)}

${esc(text)}

${s.error ? `
${esc(s.error)}
` : ''}${shots.map(img).join('')}${shotNote(shots)}
` +}).join('\n') +const provenance = r.working_tree_dirty + ? `
Pre-commit evidence. The working tree had uncommitted changes on top of ${esc(r.checked_commit)}; this report does not describe that commit. Regenerate it from a clean checkout before committing it.
` + : '' +const html = `Spec 125 Skills tab verification + +

Spec 125: Skills tab (PR-4a) Playwright verification

+${provenance}
${passed} of ${r.scenarios.length} scenarios passed, ${esc(r.generated_at.slice(0, 10))}, produced by scripts/run-skills-tab-sweep.sh from commit ${esc(r.checked_commit)} (working tree ${r.working_tree_dirty ? 'dirty' : 'clean'}).
+A throwaway core (${esc(r.core.listen)}, scratch data dir, enable_skills: true, generated API key) served the embedded frontend; the upstream ${esc(r.core.server)} (trust_mode: manual) was ${esc(r.fixture.command.join(' '))} on port ${r.fixture.port}.
+Spec: e2e/web-ui-sweep/skills-tab.spec.ts. Results file: skills-sweep-results.json. Repeat: ./scripts/run-skills-tab-sweep.sh --report-html specs/125-skills-over-mcp/verification/report.html --no-screenshots.
+${sections} +
Skill records read back from GET /api/v1/servers/${esc(r.core.server)}/skills +

After approve

${stateTable('approve')}

After approving the change

${stateTable('approve-changed')}

After block

${stateTable('block')}

After unblock

${stateTable('unblock')}
+ +` +fs.writeFileSync(dest, html) +NODE +} # --- self-test ------------------------------------------------------------------ # run_self_test: no browser. Uses its own data dir and output dir, so a sweep # that follows it (--self-test-first) starts from fresh state. @@ -518,30 +594,42 @@ run_self_test() { # 1b. A printed path never shows an absolute local path: inside the repo it is # relative, under a known prefix it gets its placeholder, and any other - # absolute path is reduced to /basename (say_path), also inside a - # message or a captured log (redact_stream). + # absolute path is reduced to /basename (say_path); inside a message or + # a captured log (redact_stream) so is any path whose root exists here. local got_path got_path=$(say_path "$REPO_ROOT/e2e/web-ui-sweep/x.json"); [[ "$got_path" == "e2e/web-ui-sweep/x.json" ]] || st_fail "say_path in the repo gave '$got_path'" got_path=$(say_path "$WORK/st-data/config.db"); [[ "$got_path" == "/st-data/config.db" ]] || st_fail "say_path in the scratch dir gave '$got_path'" got_path=$(say_path "/usr/bin/chromium"); [[ "$got_path" == "/chromium" ]] || st_fail "say_path of an outside path gave '$got_path'" got_path=$(say_path "/srv/odd place/chrome"); [[ "$got_path" == "/chrome" ]] || st_fail "say_path of an outside path with a space gave '$got_path'" - got_path=$(printf 'launch /opt/google/chrome/chrome failed; PATH=/usr/local/bin:/opt/homebrew/bin url http://127.0.0.1:1/api/v1/servers key %s' "$API_KEY" | redact_stream) + got_path=$(printf 'launch /usr/lib/chrome/chrome failed; PATH=/usr/local/bin:/bin url http://127.0.0.1:1/api/v1/servers key %s' "$API_KEY" | redact_stream) [[ "$got_path" == 'launch /chrome failed; PATH=/bin:/bin url http://127.0.0.1:1/api/v1/servers key ***' ]] || st_fail "redact_stream gave '$got_path'" - # Roots in no list: /data and /work (round 7), a colour code and JSON escapes - # in front of a path (Playwright's JSON report), and a bare core route kept. - got_path=$(printf 'executable doesn'\''t exist at /data/tools/chromium; /work/tools/chromium:1 GET /api/v1/servers and /mcp' | redact_stream) - [[ "$got_path" == 'executable doesn'\''t exist at /chromium; /chromium:1 GET /api/v1/servers and /mcp' ]] || st_fail "redact_stream of /data and /work roots gave '$got_path'" - got_path=$(printf '{"message":"\\u001b[31mError\\u001b[39m: at /data/tools/chromium\\n/work/x/y.js\\t\\"/data/q\\""}' | redact_stream) + # A real absolute path (a temp dir outside the known prefixes), also after a + # colour code or a JSON escape (Playwright's JSON report); a bare route kept. + local st_real st_real_dir + st_real_dir=$(mktemp -d /tmp/skills-sweep-st.XXXXXX) + st_real="$st_real_dir/tools/chromium" + got_path=$(printf 'executable doesn'\''t exist at %s; %s:1 GET /api/v1/servers and /mcp' "$st_real" "$st_real" | redact_stream) + [[ "$got_path" == 'executable doesn'\''t exist at /chromium; /chromium:1 GET /api/v1/servers and /mcp' ]] || st_fail "redact_stream of a temp-dir path gave '$got_path'" + got_path=$(printf '{"message":"\\u001b[31mError\\u001b[39m: at %s\\n/usr/x/y.js\\t\\"/tmp/q\\""}' "$st_real" | redact_stream) [[ "$got_path" == '{"message":"\u001b[31mError\u001b[39m: at /chromium\n/y.js\t\"/q\""}' ]] || st_fail "redact_stream of a JSON-escaped message gave '$got_path'" - got_path=$(printf 'x\033[2m/data/tools/chromium\033[22m' | redact_stream) + got_path=$(printf 'x\033[2m%s\033[22m' "$st_real" | redact_stream) [[ "$got_path" == $'x\033[2m/chromium\033[22m' ]] || st_fail "redact_stream after an ANSI code gave '$got_path'" + rmdir "$st_real_dir" + # Not paths (round 8): regex literals and route fragments of Playwright's + # messages are kept, and so is a path whose root does not exist here. + local no_root="/skills-sweep-no-root-$$" kept + [[ -e "$no_root" ]] && st_fail "$no_root exists" + for kept in 'Expected pattern: /approved/i' 'toHaveClass(/tab-active/)' "waiting for '/skills/refresh'" 'POST /servers/{id}/skills' "at $no_root/tools/chromium"; do + got_path=$(printf '%s' "$kept" | redact_stream) + [[ "$got_path" == "$kept" ]] || st_fail "redact_stream changed '$kept' to '$got_path'" + done # A configured path with a space is replaced as a whole. local saved_extra="$REDACT_EXTRA" redact_extra_add "/data/odd tools/chromium" got_path=$(printf 'launching /data/odd tools/chromium --headless' | redact_stream) REDACT_EXTRA="$saved_extra" [[ "$got_path" == 'launching /chromium --headless' ]] || st_fail "redact_stream of a configured path with a space gave '$got_path'" - echo "self-test: printed paths are relative, placeholders or /basename (any root, configured paths whole); URLs and routes are kept" + echo "self-test: printed paths are relative, placeholders or /basename (configured paths whole); URLs, routes and regex literals are kept" # 2. An ambient MCPPROXY_DATA_DIR / MCPPROXY_DATA does not reach the core. decoy_new="$WORK/decoy-data-dir" @@ -642,6 +730,8 @@ const report = { suites: [{ specs: [ { status: "failed", error: { message: `page.goto: net::ERR at http://127.0.0.1:1/ui?apikey=${e.ENC_KEY} key=${e.API_KEY} in ${e.REPO_ROOT}/e2e/x.spec.ts` } }, { status: "failed", error: { message: "the retry replayed against changed state" } }] }] }, { title: "fine", ok: true, tests: [{ results: [{ status: "passed" }] }] }, + { title: "report-strings", ok: false, tests: [{ results: [ + { status: "failed", error: { message: `at ${e.REPO_ROOT}/e2e/web-ui-sweep/x.spec.ts:1:2 launching /usr/bin/chromium waiting for \x27/skills/refresh\x27 Expected pattern: /approved/i in /usr/local/usr` } }] }] }, ] }] } fs.writeFileSync(e.ST_OUT + "/playwright-results.json", JSON.stringify(report))' set +e @@ -667,6 +757,33 @@ if (r.checked_commit !== "0123456789abcdef0123456789abcdef01234567" || r.working ' "$results" echo "self-test: the results writer records the first failed attempt, redacts the key and local paths, and labels a dirty tree pre-commit evidence" + # 3b. The report without screenshots keeps the redacted, escaped strings of + # the results intact (round 8: no second pass over the escaped HTML), and a + # failing report write prints its diagnostics redacted, with its status. + local want_err="at /e2e/web-ui-sweep/x.spec.ts:1:2 launching /chromium waiting for '/skills/refresh' Expected pattern: /approved/i in /usr" + node -e ' +const r = JSON.parse(require("fs").readFileSync(process.argv[1], "utf8")) +const s = r.scenarios.find(x => x.title === "report-strings") +if (!s || s.error !== process.argv[2]) { console.error("self-test FAILED: report-strings error: " + JSON.stringify(s && s.error)); process.exit(1) } +' "$results" "$want_err" + write_report "$st_out" "$st_out/report.html" 0 >"$WORK/st-report.out" 2>&1 || st_fail "the report writer failed: $(redact_stream <"$WORK/st-report.out")" + grep -qF "at <repo>/e2e/web-ui-sweep/x.spec.ts:1:2 launching <path>/chromium waiting for '/skills/refresh' Expected pattern: /approved/i in <path>/usr" "$st_out/report.html" || + st_fail "the report does not carry the failure message intact: $(grep -o 'at <repo>[^<]*' "$st_out/report.html" | head -1)" + grep -qF "" "$st_out/report.html" && st_fail "the report has a raw in its HTML" + grep -qF "$REPO_ROOT" "$st_out/report.html" && st_fail "the report names the repo path" + local ro_report="$WORK/st-ro-report" + mkdir -p "$ro_report" + chmod 555 "$ro_report" + set +e + write_report "$st_out" "$ro_report/report.html" 0 >"$WORK/st-report.out" 2>&1 + st_status=$? + set -e + chmod 755 "$ro_report" + [[ $st_status -ne 0 ]] || st_fail "a report write into a read-only dir exited 0" + grep -qF "$WORK" "$WORK/st-report.out" && st_fail "a failing report write printed a local path" + grep -qF "/st-ro-report/report.html" "$WORK/st-report.out" || st_fail "a failing report write did not print its diagnostics redacted" + echo "self-test: the report keeps the escaped strings intact; a failing report write prints its diagnostics redacted and fails" + # 4. DEBUG=1 never prints the key or a local path: the whole self-test above # (config, core start with the key, curl with the key header, redaction) runs # again as a child with DEBUG=1, which hands back its own key and scratch dir @@ -730,7 +847,7 @@ if (r.checked_commit !== "0123456789abcdef0123456789abcdef01234567" || r.working mkdir -p "$ext" ext_real=$(cd "$ext" && pwd -P) # shellcheck disable=SC2016 # expanded by the stand-in's own shell - printf '#!/bin/sh\necho "stand-in browser $0 args: $*" >&2\necho "MCPPROXY_API_KEY=$MCPPROXY_API_KEY" >&2\nexit 1\n' >"$ext/chromium" + printf '#!/bin/sh\necho "stand-in browser $0 args: $*" >&2\nenv >&2\nexit 1\n' >"$ext/chromium" chmod +x "$ext/chromium" rm -f "$probe_key" set +e @@ -798,7 +915,35 @@ if (r.checked_commit !== "0123456789abcdef0123456789abcdef01234567" || r.working grep -qF "skillsfixture ready" "$probe_out" && st_fail "a run with an unwritable $which started the sweep" done chmod 755 "$ro" - echo "self-test: an unwritable --out or report directory fails at once, with its diagnostics redacted" + # An existing read-only report FILE in a writable dir fails at once too. + local ro_file_dir="$WORK/st-rofile" + mkdir -p "$ro_file_dir" + : >"$ro_file_dir/report.html" + chmod 444 "$ro_file_dir/report.html" + rm -f "$probe_key" + set +e + SWEEP_SELF_TEST_CHILD="$probe_key" MCPPROXY_BINARY_PATH="$CORE_BIN" SKILLS_FIXTURE_BINARY="$FIXTURE_BIN" \ + bash "$SCRIPT_DIR/$(basename "${BASH_SOURCE[0]}")" --out "$WORK/st-ro-out" --report-html "$ro_file_dir/report.html" >"$probe_out" 2>&1 + probe_status=$? + set -e + chmod 644 "$ro_file_dir/report.html" + st_check_child_output "a run with a read-only report file" "$probe_out" "$probe_key" + [[ $probe_status -ne 0 ]] || st_fail "a run with a read-only report file exited 0" + grep -qF "cannot write the report file" "$probe_out" || st_fail "a run with a read-only report file did not say so" + grep -qF "skillsfixture ready" "$probe_out" && st_fail "a run with a read-only report file started the sweep" + # An unwritable PLAYWRIGHT_BROWSERS_PATH fails with redacted diagnostics. + chmod 555 "$ro" + rm -f "$probe_key" + set +e + SWEEP_SELF_TEST_CHILD="$probe_key" PLAYWRIGHT_BROWSERS_PATH="$ro/browsers" MCPPROXY_BINARY_PATH="$CORE_BIN" SKILLS_FIXTURE_BINARY="$FIXTURE_BIN" \ + bash "$SCRIPT_DIR/$(basename "${BASH_SOURCE[0]}")" --out "$WORK/st-ro-out" >"$probe_out" 2>&1 + probe_status=$? + set -e + chmod 755 "$ro" + st_check_child_output "a run with an unwritable PLAYWRIGHT_BROWSERS_PATH" "$probe_out" "$probe_key" + [[ $probe_status -ne 0 ]] || st_fail "a run with an unwritable PLAYWRIGHT_BROWSERS_PATH exited 0" + grep -qF "cannot create or write the browsers directory" "$probe_out" || st_fail "a run with an unwritable PLAYWRIGHT_BROWSERS_PATH did not say so" + echo "self-test: an unwritable --out, report directory, report file or browsers directory fails with its diagnostics redacted" fi fi echo "self-test passed" @@ -843,6 +988,12 @@ OUT_REAL="$OUT" if [[ -n "$REPORT_HTML" ]]; then make_writable_dir report "$(dirname "$REPORT_HTML")" REPORT_HTML="$(cd "$(dirname "$REPORT_HTML")" && pwd -P)/$(basename "$REPORT_HTML")" + # The file itself: an existing read-only file (or a directory) in a writable + # dir would only fail at the very end. + if [[ -e "$REPORT_HTML" && ( ! -f "$REPORT_HTML" || ! -w "$REPORT_HTML" ) ]]; then + echo "cannot write the report file $(say_path "$REPORT_HTML")" >&2 + exit 1 + fi fi rm -rf "$OUT/screenshots" "$OUT/state" "$OUT/playwright-results.json" "$OUT/skills-sweep-results.json" mkdir -p "$OUT/screenshots" "$OUT/state" @@ -926,7 +1077,7 @@ debug "running Playwright" # --- Playwright (same locked install as scripts/run-web-smoke.sh) ------------- SWEEP_DIR="$REPO_ROOT/e2e/web-ui-sweep" export PLAYWRIGHT_BROWSERS_PATH="${PLAYWRIGHT_BROWSERS_PATH:-$REPO_ROOT/tmp/playwright-browsers}" -mkdir -p "$PLAYWRIGHT_BROWSERS_PATH" +make_writable_dir browsers "$PLAYWRIGHT_BROWSERS_PATH" lock_hash() { node -e 'const c=require("crypto"),f=require("fs");process.stdout.write(c.createHash("sha256").update(f.readFileSync(process.argv[1])).digest("hex"))' "$1" 2>/dev/null || true } @@ -984,66 +1135,7 @@ RESULT_STATUS=$? set -e if [[ -n "$REPORT_HTML" ]]; then - node - "$OUT" "$REPORT_HTML" "$SCREENSHOTS" <<'NODE' -const fs = require('fs'), path = require('path') -const [out, dest, screenshots] = process.argv.slice(2) -const withShots = screenshots === '1' -const r = JSON.parse(fs.readFileSync(path.join(out, 'skills-sweep-results.json'), 'utf8')) -const esc = s => String(s).replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]) -const img = name => { - if (!withShots) return '' - const f = path.join(out, 'screenshots', `skills-tab-${name}.png`) - return fs.existsSync(f) ? `${esc(name)}` : '' -} -const shotNote = shots => (!withShots && shots.length) - ? `

Screenshots (not embedded in this copy): ${shots.map(s => `screenshots/skills-tab-${esc(s)}.png`).join(', ')}

` : '' -// One section per scenario, in spec order, with what it proves and its screenshots. -const about = [ - ['Tab and list', 'The Skills tab is offered on a server with enable_skills on and a skills-capable upstream (cmd/skillsfixture, manual trust). The three skills show as Awaiting review and Not offered.', ['01-list']], - ['Viewer and paging', 'SKILL.md opens in the text viewer (inert text). A 150 KiB file (data/large.txt of big) is read part by part in at least three parts: each Load more waits for its content response and for the rendered text to grow by that part. Every part is of the current copy, its digest equals the digest the core lists for that file in the current copy (the same digest the file row shows on screen), its size equals the listed size, its offset is where the previous part ended (in bytes, the first at 0) and its next_offset is where it ends; the last part has no next_offset and ends at the listed size. A binary file (logo.bin) is listed as binary, not shown, with no View button.', ['02-viewer', '03-paged']], - ['Approve', 'Approve sends the current_hash and incarnation of the version the reviewer opened; the chip turns Approved.', ['04-approved']], - ['Changed while open, re-open, diff', 'A mutate without the X-Skills-Fixture header is refused (403). The approved skill plain changes upstream while it is open; after Refresh the chip says Changed and the open review says it changed while you were reviewing it (the review shows the approved version, so it offers no Approve). Re-opening shows the file-set diff (SKILL.md changed) and the line diff with the added line; approving binds the new hash.', ['05a-stale', '05-changed-diff']], - ['Pending skill changed while open', 'The pending skill with-files changes upstream while it is open; after Refresh the review is marked stale and its Approve button stays on screen but disabled, until the new version is re-opened.', ['05b-pending-stale']], - ['Live skills.changed', 'With the pending skill big open, its SKILL.md changes upstream and the refresh is made through POST /api/v1/servers/{id}/skills/refresh, not in the page. The core\'s skills.changed SSE frame, re-dispatched by the Web UI, reloads the listing by itself and the open review shows the stale banner with Approve disabled.', ['05c-live-event-stale']], - ['Block and unblock', 'Block marks the skill Blocked and removes Approve; Unblock returns it to Awaiting review.', ['06-blocked']], - ['Reload', 'The tab survives a reload through ?tab=skills, and no uncaught page error was thrown in any scenario.', []], -] -const stateTable = step => { - const s = r.states[step] - if (!s) return `

missing

` - return `${s.skills.map(k => - ``).join('')}
skillstatusblockedavailablecurrent_hashapproved_hash
${esc(k.path)}${esc(k.status)}${k.blocked}${k.available}${esc(k.current_hash)}${esc(k.approved_hash || '')}
` -} -const passed = r.scenarios.filter(s => s.passed).length -const sections = r.scenarios.map((s, i) => { - const [title, text, shots] = about[i] || [s.title, '', []] - const badge = s.passed ? 'PASS' : 'FAIL' - return `
${i + 1}. ${esc(title)} ${badge}

${esc(s.title)}

${esc(text)}

${s.error ? `
${esc(s.error)}
` : ''}${shots.map(img).join('')}${shotNote(shots)}
` -}).join('\n') -const provenance = r.working_tree_dirty - ? `
Pre-commit evidence. The working tree had uncommitted changes on top of ${esc(r.checked_commit)}; this report does not describe that commit. Regenerate it from a clean checkout before committing it.
` - : '' -const html = `Spec 125 Skills tab verification - -

Spec 125: Skills tab (PR-4a) Playwright verification

-${provenance}
${passed} of ${r.scenarios.length} scenarios passed, ${esc(r.generated_at.slice(0, 10))}, produced by scripts/run-skills-tab-sweep.sh from commit ${esc(r.checked_commit)} (working tree ${r.working_tree_dirty ? 'dirty' : 'clean'}).
-A throwaway core (${esc(r.core.listen)}, scratch data dir, enable_skills: true, generated API key) served the embedded frontend; the upstream ${esc(r.core.server)} (trust_mode: manual) was ${esc(r.fixture.command.join(' '))} on port ${r.fixture.port}.
-Spec: e2e/web-ui-sweep/skills-tab.spec.ts. Results file: skills-sweep-results.json. Repeat: ./scripts/run-skills-tab-sweep.sh --report-html specs/125-skills-over-mcp/verification/report.html --no-screenshots.
-${sections} -
Skill records read back from GET /api/v1/servers/${esc(r.core.server)}/skills -

After approve

${stateTable('approve')}

After approving the change

${stateTable('approve-changed')}

After block

${stateTable('block')}

After unblock

${stateTable('unblock')}
- -` -fs.writeFileSync(dest, html) -NODE - # Every string in the report comes from the redacted results file; the copy - # without screenshots (pure text) is redacted once more as a whole. - [[ $SCREENSHOTS -eq 0 ]] && redact_file "$REPORT_HTML" + write_report "$OUT" "$REPORT_HTML" "$SCREENSHOTS" echo "HTML report written to $(say_path "$REPORT_HTML")$([[ $SCREENSHOTS -eq 0 ]] && echo ' (no embedded screenshots)')" fi From eb3533bc30b4e17b1c605cfd1e0e902c332bb5bd Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Fri, 20 Nov 2026 14:08:28 +0200 Subject: [PATCH 14/18] docs(skills): browser sweep evidence for 30e6443d8 Related #1895 --- specs/125-skills-over-mcp/verification/report.html | 4 ++-- .../verification/skills-sweep-results.json | 12 ++++++------ 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/specs/125-skills-over-mcp/verification/report.html b/specs/125-skills-over-mcp/verification/report.html index e43b582b3..d7235994f 100644 --- a/specs/125-skills-over-mcp/verification/report.html +++ b/specs/125-skills-over-mcp/verification/report.html @@ -6,8 +6,8 @@ .t{color:#57606a;font-size:.85em;margin:.25rem 0}img{max-width:100%;border:1px solid #d0d7de;border-radius:4px;margin:.25rem 0}code{background:#eaeef2;padding:0 .25rem;border-radius:3px;font-size:.85em} table{border-collapse:collapse;font-size:.85em;margin:.5rem 0}td,th{border:1px solid #d0d7de;padding:.2rem .4rem;text-align:left}

Spec 125: Skills tab (PR-4a) Playwright verification

-
8 of 8 scenarios passed, 2026-11-20, produced by scripts/run-skills-tab-sweep.sh from commit 1698add39fea40675fc57401afe0358cfd0f3d42 (working tree clean).
-A throwaway core (127.0.0.1:64486, scratch data dir, enable_skills: true, generated API key) served the embedded frontend; the upstream skillsfx (trust_mode: manual) was skillsfixture -addr 127.0.0.1:64484 on port 64484.
+
8 of 8 scenarios passed, 2026-11-20, produced by scripts/run-skills-tab-sweep.sh from commit 30e6443d841bbd246497cb5d410b0ed9ffa322f8 (working tree clean).
+A throwaway core (127.0.0.1:54556, scratch data dir, enable_skills: true, generated API key) served the embedded frontend; the upstream skillsfx (trust_mode: manual) was skillsfixture -addr 127.0.0.1:54554 on port 54554.
Spec: e2e/web-ui-sweep/skills-tab.spec.ts. Results file: skills-sweep-results.json. Repeat: ./scripts/run-skills-tab-sweep.sh --report-html specs/125-skills-over-mcp/verification/report.html --no-screenshots.
1. Tab and list PASS

the Skills tab lists the fixture skills as awaiting review

The Skills tab is offered on a server with enable_skills on and a skills-capable upstream (cmd/skillsfixture, manual trust). The three skills show as Awaiting review and Not offered.

Screenshots (not embedded in this copy): screenshots/skills-tab-01-list.png

2. Viewer and paging PASS

views SKILL.md, pages a large file, and does not offer a binary file

SKILL.md opens in the text viewer (inert text). A 150 KiB file (data/large.txt of big) is read part by part in at least three parts: each Load more waits for its content response and for the rendered text to grow by that part. Every part is of the current copy, its digest equals the digest the core lists for that file in the current copy (the same digest the file row shows on screen), its size equals the listed size, its offset is where the previous part ended (in bytes, the first at 0) and its next_offset is where it ends; the last part has no next_offset and ends at the listed size. A binary file (logo.bin) is listed as binary, not shown, with no View button.

Screenshots (not embedded in this copy): screenshots/skills-tab-02-viewer.png, screenshots/skills-tab-03-paged.png

diff --git a/specs/125-skills-over-mcp/verification/skills-sweep-results.json b/specs/125-skills-over-mcp/verification/skills-sweep-results.json index 3246eea31..09a49d016 100644 --- a/specs/125-skills-over-mcp/verification/skills-sweep-results.json +++ b/specs/125-skills-over-mcp/verification/skills-sweep-results.json @@ -1,19 +1,19 @@ { - "checked_commit": "1698add39fea40675fc57401afe0358cfd0f3d42", + "checked_commit": "30e6443d841bbd246497cb5d410b0ed9ffa322f8", "working_tree_dirty": false, "evidence": "commit", - "checked": "1698add39fea40675fc57401afe0358cfd0f3d42", - "generated_at": "2026-11-20T11:52:22.280Z", + "checked": "30e6443d841bbd246497cb5d410b0ed9ffa322f8", + "generated_at": "2026-11-20T12:08:22.273Z", "fixture": { "command": [ "skillsfixture", "-addr", - "127.0.0.1:64484" + "127.0.0.1:54554" ], - "port": 64484 + "port": 54554 }, "core": { - "listen": "127.0.0.1:64486", + "listen": "127.0.0.1:54556", "server": "skillsfx", "enable_skills": true, "trust_mode": "manual" From 459a4d2740ce47ac095c1400943165a12159a8da Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Fri, 20 Nov 2026 14:13:36 +0200 Subject: [PATCH 15/18] fix(skills): review round 9 for the Skills tab and its sweep - write_results runs its node writer through run_logged: a failed write of skills-sweep-results.json (an unwritable file, a directory at the path, a full disk) prints node's diagnostics redacted, and the status stays non-zero. - redact_file, the other direct node writer, captures a failed in-place rewrite's error and prints it redacted, keeping the status. - --self-test calls the results writer with a directory and with a read-only file at the results path: non-zero exit, the path printed as /..., no absolute path and no key. Related #1895 --- scripts/run-skills-tab-sweep.sh | 41 +++++++++++++++++++++++++++++---- 1 file changed, 36 insertions(+), 5 deletions(-) diff --git a/scripts/run-skills-tab-sweep.sh b/scripts/run-skills-tab-sweep.sh index fba2c753f..4e70280ff 100755 --- a/scripts/run-skills-tab-sweep.sh +++ b/scripts/run-skills-tab-sweep.sh @@ -215,9 +215,15 @@ redact_node() { SWEEP_REDACT_KEY="$API_KEY" SWEEP_REDACT_OUT="$OUT_REAL" SWEEP_REDACT_REPO="$REPO_ROOT" \ SWEEP_REDACT_WORK="$WORK" SWEEP_REDACT_HOME="$OPERATOR_HOME" SWEEP_REDACT_EXTRA="$REDACT_EXTRA" node -e "$REDACT_JS" "$@" } +# Rewrites the file in place. A failed rewrite (an unwritable file, a full +# disk) names the file in node's error: that error is printed redacted, and the +# status is kept. redact_file() { [[ -f "$1" ]] || return 0 - redact_node "$1" + local err status=0 + err=$(redact_node "$1" 2>&1 >/dev/null) || status=$? + if [[ $status -ne 0 ]]; then printf '%s\n' "$err" | redact_stream >&2; fi + return "$status" } # Copies stdin to stdout, redacted. redact_stream() { redact_node; } @@ -429,9 +435,11 @@ free_port() { # attempt (a retry replays against changed state and would hide the original # error). The fixture command is recorded as basename + args. The file is then # redacted (API key, local paths). Exit status 0 only when everything passed. +# The writer's own output (a failed write names the results path) is captured +# and printed redacted (run_logged); a failed write is a non-zero status too. write_results() { - local out="$1" - node - "$@" <<'NODE' + local out="$1" status=0 + run_logged results node - "$@" >&2 <<'NODE' const fs = require('fs'), path = require('path') const [out, commit, dirty, fixturePort, pwStatus, server, corePort, ...fixtureCmd] = process.argv.slice(2) const problems = [] @@ -488,8 +496,8 @@ const result = { fs.writeFileSync(path.join(out, 'skills-sweep-results.json'), JSON.stringify(result, null, 2) + '\n') process.exit(result.passed ? 0 : 1) NODE - local status=$? - redact_file "$out/skills-sweep-results.json" + status=$? + redact_file "$out/skills-sweep-results.json" || status=$? return $status } @@ -784,6 +792,29 @@ if (!s || s.error !== process.argv[2]) { console.error("self-test FAILED: report grep -qF "/st-ro-report/report.html" "$WORK/st-report.out" || st_fail "a failing report write did not print its diagnostics redacted" echo "self-test: the report keeps the escaped strings intact; a failing report write prints its diagnostics redacted and fails" + # 3c. A results file that cannot be written (a directory at its path, or an + # existing read-only file) fails the results writer with its diagnostics + # redacted: no absolute path, no key (round 9). + local rr_dir rr_case + for rr_case in dir readonly; do + [[ $rr_case == readonly && "$(id -u)" == "0" ]] && continue + rr_dir="$WORK/st-results-$rr_case" + mkdir -p "$rr_dir" + if [[ $rr_case == dir ]]; then mkdir -p "$rr_dir/skills-sweep-results.json" + else printf '{}' >"$rr_dir/skills-sweep-results.json"; chmod 444 "$rr_dir/skills-sweep-results.json"; fi + set +e + write_results "$rr_dir" "0123456789abcdef0123456789abcdef01234567" false 4242 0 skillsfx 4343 "$WORK/bin/skillsfixture" -addr 127.0.0.1:4242 >"$WORK/st-results.out" 2>&1 + st_status=$? + set -e + [[ $rr_case == readonly ]] && chmod 644 "$rr_dir/skills-sweep-results.json" + [[ $st_status -ne 0 ]] || st_fail "a results write to a $rr_case path exited 0" + grep -qF "$WORK" "$WORK/st-results.out" && st_fail "a failing results write ($rr_case) printed a local path" + grep -qF "${WORK#/private}" "$WORK/st-results.out" && st_fail "a failing results write ($rr_case) printed a local path" + grep -qF "$API_KEY" "$WORK/st-results.out" && st_fail "a failing results write ($rr_case) printed the API key" + grep -qF "/st-results-$rr_case/skills-sweep-results.json" "$WORK/st-results.out" || st_fail "a failing results write ($rr_case) did not print its diagnostics redacted" + done + echo "self-test: a results file that cannot be written fails the results writer with its diagnostics redacted" + # 4. DEBUG=1 never prints the key or a local path: the whole self-test above # (config, core start with the key, curl with the key header, redaction) runs # again as a child with DEBUG=1, which hands back its own key and scratch dir From a8cfc9a9e2caefea6dbd3794b3f9dc912a89783d Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Fri, 20 Nov 2026 14:15:05 +0200 Subject: [PATCH 16/18] docs(skills): browser sweep evidence for 459a4d274 Related #1895 --- specs/125-skills-over-mcp/verification/report.html | 4 ++-- .../verification/skills-sweep-results.json | 12 ++++++------ 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/specs/125-skills-over-mcp/verification/report.html b/specs/125-skills-over-mcp/verification/report.html index d7235994f..3a7940a67 100644 --- a/specs/125-skills-over-mcp/verification/report.html +++ b/specs/125-skills-over-mcp/verification/report.html @@ -6,8 +6,8 @@ .t{color:#57606a;font-size:.85em;margin:.25rem 0}img{max-width:100%;border:1px solid #d0d7de;border-radius:4px;margin:.25rem 0}code{background:#eaeef2;padding:0 .25rem;border-radius:3px;font-size:.85em} table{border-collapse:collapse;font-size:.85em;margin:.5rem 0}td,th{border:1px solid #d0d7de;padding:.2rem .4rem;text-align:left}

Spec 125: Skills tab (PR-4a) Playwright verification

-
8 of 8 scenarios passed, 2026-11-20, produced by scripts/run-skills-tab-sweep.sh from commit 30e6443d841bbd246497cb5d410b0ed9ffa322f8 (working tree clean).
-A throwaway core (127.0.0.1:54556, scratch data dir, enable_skills: true, generated API key) served the embedded frontend; the upstream skillsfx (trust_mode: manual) was skillsfixture -addr 127.0.0.1:54554 on port 54554.
+
8 of 8 scenarios passed, 2026-11-20, produced by scripts/run-skills-tab-sweep.sh from commit 459a4d2740ce47ac095c1400943165a12159a8da (working tree clean).
+A throwaway core (127.0.0.1:56437, scratch data dir, enable_skills: true, generated API key) served the embedded frontend; the upstream skillsfx (trust_mode: manual) was skillsfixture -addr 127.0.0.1:56435 on port 56435.
Spec: e2e/web-ui-sweep/skills-tab.spec.ts. Results file: skills-sweep-results.json. Repeat: ./scripts/run-skills-tab-sweep.sh --report-html specs/125-skills-over-mcp/verification/report.html --no-screenshots.
1. Tab and list PASS

the Skills tab lists the fixture skills as awaiting review

The Skills tab is offered on a server with enable_skills on and a skills-capable upstream (cmd/skillsfixture, manual trust). The three skills show as Awaiting review and Not offered.

Screenshots (not embedded in this copy): screenshots/skills-tab-01-list.png

2. Viewer and paging PASS

views SKILL.md, pages a large file, and does not offer a binary file

SKILL.md opens in the text viewer (inert text). A 150 KiB file (data/large.txt of big) is read part by part in at least three parts: each Load more waits for its content response and for the rendered text to grow by that part. Every part is of the current copy, its digest equals the digest the core lists for that file in the current copy (the same digest the file row shows on screen), its size equals the listed size, its offset is where the previous part ended (in bytes, the first at 0) and its next_offset is where it ends; the last part has no next_offset and ends at the listed size. A binary file (logo.bin) is listed as binary, not shown, with no View button.

Screenshots (not embedded in this copy): screenshots/skills-tab-02-viewer.png, screenshots/skills-tab-03-paged.png

diff --git a/specs/125-skills-over-mcp/verification/skills-sweep-results.json b/specs/125-skills-over-mcp/verification/skills-sweep-results.json index 09a49d016..716416a93 100644 --- a/specs/125-skills-over-mcp/verification/skills-sweep-results.json +++ b/specs/125-skills-over-mcp/verification/skills-sweep-results.json @@ -1,19 +1,19 @@ { - "checked_commit": "30e6443d841bbd246497cb5d410b0ed9ffa322f8", + "checked_commit": "459a4d2740ce47ac095c1400943165a12159a8da", "working_tree_dirty": false, "evidence": "commit", - "checked": "30e6443d841bbd246497cb5d410b0ed9ffa322f8", - "generated_at": "2026-11-20T12:08:22.273Z", + "checked": "459a4d2740ce47ac095c1400943165a12159a8da", + "generated_at": "2026-11-20T12:14:59.854Z", "fixture": { "command": [ "skillsfixture", "-addr", - "127.0.0.1:54554" + "127.0.0.1:56435" ], - "port": 54554 + "port": 56435 }, "core": { - "listen": "127.0.0.1:54556", + "listen": "127.0.0.1:56437", "server": "skillsfx", "enable_skills": true, "trust_mode": "manual" From 36e268f731f0d8df4f50566281f04ffebe9b8651 Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Fri, 20 Nov 2026 15:00:18 +0200 Subject: [PATCH 17/18] fix(web): refresh Skills tabs for bulk server updates --- frontend/src/components/skills/SkillsPanel.vue | 5 ++--- frontend/src/utils/skills.ts | 5 +++++ frontend/src/views/ServerDetail.vue | 5 ++--- frontend/tests/unit/fixtures/skills125.ts | 4 ++-- .../tests/unit/server-detail-skills-tab.spec.ts | 15 ++++++++++++++- 5 files changed, 25 insertions(+), 9 deletions(-) diff --git a/frontend/src/components/skills/SkillsPanel.vue b/frontend/src/components/skills/SkillsPanel.vue index 86b9c142e..da86d1798 100644 --- a/frontend/src/components/skills/SkillsPanel.vue +++ b/frontend/src/components/skills/SkillsPanel.vue @@ -90,7 +90,7 @@ import { computed, onMounted, onUnmounted, ref, watch } from 'vue' import api from '@/services/api' import type { SkillEntry, SkillsListResponse } from '@/types/api' import { formatDateTime } from '@/utils/datetime' -import { skillStateChip, skillExpectedHashes, skillErrorCode, skillErrorNotice, skillApprovedNotice, type SkillAction } from '@/utils/skills' +import { skillsChangeIncludesServer, skillStateChip, skillExpectedHashes, skillErrorCode, skillErrorNotice, skillApprovedNotice, type SkillAction } from '@/utils/skills' import SkillDetail from './SkillDetail.vue' const props = defineProps<{ serverName: string }>() @@ -295,8 +295,7 @@ function setBlocked(block: boolean) { // The store re-dispatches the core's frame whole ({payload: {server, counts}, // timestamp}), like every other runtime event. function onSkillsChanged(e: Event) { - const detail = (e as CustomEvent).detail as { payload?: { server?: string } } | null - if (detail?.payload?.server !== props.serverName) return + if (!skillsChangeIncludesServer(e, props.serverName)) return awaitingReload.value = true void load() } diff --git a/frontend/src/utils/skills.ts b/frontend/src/utils/skills.ts index 8a2c52cb0..56413be9b 100644 --- a/frontend/src/utils/skills.ts +++ b/frontend/src/utils/skills.ts @@ -1,6 +1,11 @@ // 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. */ diff --git a/frontend/src/views/ServerDetail.vue b/frontend/src/views/ServerDetail.vue index bab9e51bf..27a4fbacb 100644 --- a/frontend/src/views/ServerDetail.vue +++ b/frontend/src/views/ServerDetail.vue @@ -1609,7 +1609,7 @@ import FlaggedToolsPanel from '@/components/FlaggedToolsPanel.vue' import ReviewScreen from '@/components/ReviewScreen.vue' import SkillsPanel from '@/components/skills/SkillsPanel.vue' import { useAuthStore } from '@/stores/auth' -import { skillsTabVisible as listingOffersSkills } from '@/utils/skills' +import { skillsChangeIncludesServer, skillsTabVisible as listingOffersSkills } from '@/utils/skills' import type { Hint } from '@/components/CollapsibleHintsPanel.vue' import type { Server, Tool, ToolApproval, SecurityScanReport, HealthStatus } from '@/types' import api from '@/services/api' @@ -4194,8 +4194,7 @@ watch(logTail, () => { // Spec 125: a skills change on this server can turn the tab on or off. // The store re-dispatches the core's frame whole ({payload: {server, counts}, timestamp}). function handleSkillsChangedEvent(e: Event) { - const detail = (e as CustomEvent).detail as { payload?: { server?: string } } | null - if (detail?.payload?.server === props.serverName) void checkSkillsTab(false) + if (skillsChangeIncludesServer(e, props.serverName)) void checkSkillsTab(false) } // Load data on mount diff --git a/frontend/tests/unit/fixtures/skills125.ts b/frontend/tests/unit/fixtures/skills125.ts index b1b338af5..84b1f07c2 100644 --- a/frontend/tests/unit/fixtures/skills125.ts +++ b/frontend/tests/unit/fixtures/skills125.ts @@ -25,7 +25,7 @@ export const ok = (data: T) => ({ success: true, data }) * through the store's own re-dispatch to `mcpproxy:skills-changed`. Call it with * a Pinia active and the spec's mocked api object (it sets createEventSource). */ -export async function connectSkillsSSE(apiMock: object): Promise<(server: string, counts?: Record) => void> { +export async function connectSkillsSSE(apiMock: object): Promise<(server: string | string[], counts?: Record) => void> { const { vi } = await import('vitest') const { useSystemStore } = await import('@/stores/system') const g = globalThis as any @@ -38,5 +38,5 @@ export async function connectSkillsSSE(apiMock: object): Promise<(server: string })) if (typeof a.hasAPIKey !== 'function') a.hasAPIKey = vi.fn(() => true) useSystemStore().connectEventSource() - return (server, counts = {}) => listeners['skills.changed']({ data: JSON.stringify({ payload: { server, counts }, timestamp: 1763300000 }) }) + return (server, counts = {}) => listeners['skills.changed']({ data: JSON.stringify({ payload: Array.isArray(server) ? { servers: server } : { server, counts }, timestamp: 1763300000 }) }) } diff --git a/frontend/tests/unit/server-detail-skills-tab.spec.ts b/frontend/tests/unit/server-detail-skills-tab.spec.ts index 5fa15db34..74d9f1488 100644 --- a/frontend/tests/unit/server-detail-skills-tab.spec.ts +++ b/frontend/tests/unit/server-detail-skills-tab.spec.ts @@ -34,7 +34,7 @@ vi.mock('@/services/api', () => { } } }) -let emitSkillsChanged: (server: string) => void = () => { throw new Error('not connected') } +let emitSkillsChanged: (server: string | string[]) => void = () => { throw new Error('not connected') } async function mountServerDetail(path: string, tenant = false) { const pinia = createPinia() @@ -157,6 +157,19 @@ describe('ServerDetail Skills tab (Spec 125)', () => { expect(wrapper.find('[data-test="skills-panel"]').exists()).toBe(true) }) + it('rechecks an open Skills tab only when a bulk change includes its server', async () => { + const { wrapper, router } = await mountServerDetail('/servers/alpha?tab=skills') + vi.mocked(api.getServerSkills).mockClear() + emitSkillsChanged(['beta', 'gamma']) + await flushPromises() + expect(api.getServerSkills).not.toHaveBeenCalled() + vi.mocked(api.getServerSkills).mockResolvedValue({ success: true, data: makeListing([], { enabled: false }) }) + emitSkillsChanged(['beta', 'alpha']) + await flushPromises() + expect(router.currentRoute.value.query.tab).toBe('tools') + wrapper.unmount() + }) + it('falls back to Tools when a skills change turns the open tab off', async () => { const { wrapper, router } = await mountServerDetail('/servers/alpha?tab=skills') expect(wrapper.find('[data-test="skills-panel"]').exists()).toBe(true) From efa8c0ca214ea5866b27695015d3808950da2e97 Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Fri, 20 Nov 2026 15:16:55 +0200 Subject: [PATCH 18/18] fix(skillsfixture): handle startup output and check response cleanup --- cmd/skillsfixture/main.go | 5 ++++- cmd/skillsfixture/main_test.go | 8 +++++--- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/cmd/skillsfixture/main.go b/cmd/skillsfixture/main.go index c865cf071..00163fce4 100644 --- a/cmd/skillsfixture/main.go +++ b/cmd/skillsfixture/main.go @@ -51,7 +51,10 @@ func run(addr string) error { } f := skillstest.NewDetached() Seed(f) - fmt.Fprintf(os.Stdout, "skillsfixture listening on http://%s/mcp\n", ln.Addr()) + 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())...)) } diff --git a/cmd/skillsfixture/main_test.go b/cmd/skillsfixture/main_test.go index b7437198d..9448c2aea 100644 --- a/cmd/skillsfixture/main_test.go +++ b/cmd/skillsfixture/main_test.go @@ -9,6 +9,8 @@ import ( "strings" "testing" + "github.com/stretchr/testify/assert" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/skills/skillstest" ) @@ -19,7 +21,7 @@ func rpc(t *testing.T, url, method, uri string) map[string]any { if err != nil { t.Fatal(err) } - defer resp.Body.Close() + 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) @@ -55,7 +57,7 @@ func mutate(t *testing.T, base, query, body string, header map[string]string) in if err != nil { t.Fatal(err) } - resp.Body.Close() + assert.NoError(t, resp.Body.Close()) return resp.StatusCode } @@ -139,7 +141,7 @@ func TestRefusesAForeignHost(t *testing.T) { if err != nil { t.Fatal(err) } - resp.Body.Close() + assert.NoError(t, resp.Body.Close()) if resp.StatusCode != http.StatusMisdirectedRequest { t.Errorf("Host %q %s: status %d, want 421", host, path, resp.StatusCode) }