From 8e0ac36507932e37d074eaf918eceb4d3cb02e4d Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Thu, 27 Aug 2026 13:39:01 +0300 Subject: [PATCH 1/2] fix(quarantine): stop counting a quarantined server's tools as available (#1064) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A quarantined server kept reporting its tools as available. `tool_count` stayed at its pre-quarantine value, `GET /api/v1/tools` returned every one of them, and the Servers page rendered the total under "Available across all servers" — while the search index correctly excluded them (#1061) and every call to those tools was refused with a SECURITY BLOCK. Two surfaces describing the same catalog disagreed, and the one an operator reads was the wrong one. Quarantine is neither "disabled" nor "disconnected": a quarantined server stays dialed with status ready on purpose, so the tray and Web UI can inspect it for review. It therefore passed the existing disabled/not-connected guard untouched. The stale count also survives the supervisor's disconnect-zeroing, because LoadConfiguredServers re-dials the server and the next reconcile re-sticks the retained snapshot. Adds one shared predicate, config.ServerContributesTools(enabled, quarantined), mirroring the answers runtime.serverEligibleForIndexing already gives the index writer and preflight.ClassifyTool gives dispatch, and adopts it at the surfaces that were each re-deriving "available" from a different field: - Projections zero the per-server count at the wire boundary: Runtime.GetAllServers, Server.GetAllServers, and both GetUpstreamStats paths (including the manager fallback, whose cached tool count no quarantine path invalidates). - Aggregates gate the sum: management.ListServers, Server.GetUpstreamStats, Manager.GetTotalToolCount. - GET /api/v1/tools and GET /api/v1/annotations/coverage skip quarantined servers. Skipping is a deliberate exclusion, not a fetch failure, so neither sets `partial`/`failed_servers`. - getVisibleToolCount returns 0 for a quarantined server. - The Web UI's totalTools excludes them too. Deliberately unchanged: - GET /api/v1/servers/{id}/tools still returns the full list. That is the review surface — it is how an operator inspects and approves a quarantined server, and after #1061 the StateView is its only source. Same for Server.GetQuarantinedServers, which exists to say how many tools await review. - isToolCallable stays quarantine-blind. It is the *search* filter and must reproduce merge-base semantics exactly (Spec 085 FR-006/FR-011), which require retrieve_tools to keep surfacing a quarantined server's lingering indexed tools; the stricter toolVisibleToSession applies the quarantine gate. TestVisibleToolCount_QuarantinedServer pins both halves so the two cannot be collapsed again. - stats.quarantined_servers and health admin_state=quarantined are untouched — they are the counterpart that must still show a non-zero number. Behaviour change worth calling out at review: users with quarantined servers will now report lower tool counts in /api/v1/status, the SSE servers.changed embed, /api/v1/profiles, the Prometheus tools-total gauge, the telemetry heartbeat, and the TOOLS column of `mcpproxy upstream list`. --- frontend/src/stores/servers.ts | 7 ++- frontend/tests/unit/servers-store.spec.ts | 53 ++++++++++++++++ internal/config/config.go | 17 +++++ .../config/server_contributes_tools_test.go | 49 +++++++++++++++ internal/httpapi/server.go | 27 ++++++-- internal/httpapi/server_global_tools_test.go | 62 +++++++++++++++++++ internal/management/service.go | 6 +- internal/management/service_test.go | 53 ++++++++++++++++ internal/runtime/runtime.go | 15 ++++- .../runtime/tool_quarantine_reindex_test.go | 9 +++ internal/server/mcp.go | 17 +++++ .../server/mcp_disabled_discovery_test.go | 27 ++++++++ internal/server/server.go | 52 +++++++++++++++- internal/upstream/manager.go | 5 +- 14 files changed, 384 insertions(+), 15 deletions(-) create mode 100644 internal/config/server_contributes_tools_test.go diff --git a/frontend/src/stores/servers.ts b/frontend/src/stores/servers.ts index b4f5b6725..da75122f8 100644 --- a/frontend/src/stores/servers.ts +++ b/frontend/src/stores/servers.ts @@ -44,10 +44,13 @@ export const useServersStore = defineStore('servers', () => { servers.value.filter(s => s.quarantined) ) - // Only count tools from enabled servers (Issue #285 fix) + // Only count tools that are actually available: enabled servers (Issue #285) + // that are not quarantined (Issue #1064 -- a quarantined server's tools are + // refused at dispatch and purged from the search index, so counting them + // tells the operator N tools are available when none of them are callable). const totalTools = computed(() => servers.value - .filter(s => s.enabled) + .filter(s => s.enabled && !s.quarantined) .reduce((sum, server) => sum + server.tool_count, 0) ) diff --git a/frontend/tests/unit/servers-store.spec.ts b/frontend/tests/unit/servers-store.spec.ts index fa2f12cd7..5f540ba1e 100644 --- a/frontend/tests/unit/servers-store.spec.ts +++ b/frontend/tests/unit/servers-store.spec.ts @@ -281,3 +281,56 @@ describe('useServersStore — a successful list clears a stale error', () => { expect(store.servers).toHaveLength(1) }) }) + +// Issue #1064: a quarantined server's tools are refused at dispatch and purged +// from the search index, so counting them under "Available across all servers" +// tells the operator N tools are available when none of them are callable. +describe('useServersStore — totalTools counts only available tools (#1064)', () => { + beforeEach(() => { + setActivePinia(createPinia()) + vi.clearAllMocks() + }) + + function srv(overrides: Record = {}) { + return { + name: 'srv', + protocol: 'http' as const, + enabled: true, + quarantined: false, + connected: true, + connecting: false, + tool_count: 0, + ...overrides, + } + } + + async function load(servers: Record[]) { + const store = useServersStore() + ;(api.getServers as any).mockResolvedValue({ success: true, data: { servers } }) + await store.fetchServers(true) + return store + } + + it('excludes a quarantined server', async () => { + const store = await load([ + srv({ name: 'clean', tool_count: 5 }), + srv({ name: 'held', quarantined: true, tool_count: 7 }), + ]) + expect(store.totalTools).toBe(5) + }) + + it('still excludes a disabled server (issue #285)', async () => { + const store = await load([ + srv({ name: 'clean', tool_count: 5 }), + srv({ name: 'off', enabled: false, tool_count: 3 }), + ]) + expect(store.totalTools).toBe(5) + }) + + it('counts nothing when every server is quarantined', async () => { + const store = await load([srv({ name: 'held', quarantined: true, tool_count: 9 })]) + expect(store.totalTools).toBe(0) + // ...while the server itself is still listed for review. + expect(store.quarantinedServers).toHaveLength(1) + }) +}) diff --git a/internal/config/config.go b/internal/config/config.go index 4e1ac5584..d9676b872 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -2036,6 +2036,23 @@ func (sc *ServerConfig) IsQuarantineSkipped() bool { return sc.EffectiveTrustMode() == TrustModeAuto } +// ServerContributesTools reports whether a server's tools count as AVAILABLE to +// an agent. A quarantined server's tools are refused by every dispatch path +// (the SECURITY BLOCK in internal/server/mcp.go) and are withheld from the +// search index (#1061), so it contributes zero — the same answer the index +// writer's serverEligibleForIndexing and preflight.ClassifyTool already give. +// Takes plain bools because most callers hold a stateview server status rather +// than a *ServerConfig. Issue #1064. +func ServerContributesTools(enabled, quarantined bool) bool { + return enabled && !quarantined +} + +// ContributesTools is the *ServerConfig form of ServerContributesTools. A nil +// receiver contributes nothing. +func (sc *ServerConfig) ContributesTools() bool { + return sc != nil && ServerContributesTools(sc.Enabled, sc.Quarantined) +} + // IsAutoApproveToolChanges reports the configured per-server intent to auto-approve // tool changes/additions (disabling per-server rug-pull protection). It is provided // for the runtime consumers that adopt it in MCP-2931 and is NOT yet consulted at diff --git a/internal/config/server_contributes_tools_test.go b/internal/config/server_contributes_tools_test.go new file mode 100644 index 000000000..bcd386038 --- /dev/null +++ b/internal/config/server_contributes_tools_test.go @@ -0,0 +1,49 @@ +package config + +import "testing" + +// Issue #1064: "available tools" had three independent enabled-only predicates +// and three surfaces with no predicate at all, so a quarantined server -- which +// deliberately stays connected and ready so the tray and Web UI can inspect it +// for review -- kept reporting its tools as available while every call to them +// was refused and the search index correctly held nothing. +// +// This truth table is the mirror of runtime.serverEligibleForIndexing's +// (TestServerEligibleForIndexing in internal/runtime): the security predicate +// that decides what may be INDEXED and the availability predicate that decides +// what is COUNTED must give the same answer for the same server, or the two +// surfaces disagree again. +func TestServerContributesTools(t *testing.T) { + cases := []struct { + name string + enabled bool + quarantined bool + want bool + }{ + {"enabled and trusted", true, false, true}, + {"enabled but quarantined", true, true, false}, + {"disabled", false, false, false}, + {"disabled and quarantined", false, true, false}, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + if got := ServerContributesTools(tc.enabled, tc.quarantined); got != tc.want { + t.Fatalf("ServerContributesTools(enabled=%v, quarantined=%v) = %v, want %v", + tc.enabled, tc.quarantined, got, tc.want) + } + + sc := &ServerConfig{Name: tc.name, Enabled: tc.enabled, Quarantined: tc.quarantined} + if got := sc.ContributesTools(); got != tc.want { + t.Fatalf("(%+v).ContributesTools() = %v, want %v", sc, got, tc.want) + } + }) + } +} + +func TestServerContributesToolsNilReceiver(t *testing.T) { + var sc *ServerConfig + if sc.ContributesTools() { + t.Fatal("a nil server config must contribute no tools") + } +} diff --git a/internal/httpapi/server.go b/internal/httpapi/server.go index f065074c1..9ca385487 100644 --- a/internal/httpapi/server.go +++ b/internal/httpapi/server.go @@ -3199,11 +3199,14 @@ func (s *Server) handleGetGlobalTools(w http.ResponseWriter, r *http.Request) { } // Use the same management-service path as the per-server tools endpoint so - // behaviour is consistent: a disabled / not-connected server returns an - // empty tool set (NOT an error), so it contributes zero tools without - // being mislabelled as a failed server. Fall back to the controller path - // when the management service is unavailable (keeps unit tests + minimal - // deployments working). + // behaviour is consistent. A disabled / not-connected server reaches us as + // an empty tool set (NOT an error) because disabling disconnects it, so it + // contributes zero tools without being mislabelled as a failed server. + // Quarantine is neither of those things -- a quarantined server stays + // dialed for security inspection and status stays ready -- so it needs the + // explicit guard in the loop below (#1064). Fall back to the controller + // path when the management service is unavailable (keeps unit tests + + // minimal deployments working). mgmtSvc, hasMgmt := s.controller.GetManagementService().(interface { GetServerTools(ctx context.Context, name string) ([]map[string]interface{}, error) }) @@ -3227,6 +3230,15 @@ func (s *Server) handleGetGlobalTools(w http.ResponseWriter, r *http.Request) { if name == "" { continue } + // #1064: a quarantined server contributes nothing here -- its tools are + // unreachable (SECURITY BLOCK at dispatch) and its descriptions are the + // TPA payload #1061 removed from the index. Skipping is not a failure, + // so it must not set Partial / FailedServers. Disabled servers still + // appear, per the GlobalToolsResponse contract; the review surface + // GET /api/v1/servers/{id}/tools is likewise untouched. + if quarantined, _ := srv["quarantined"].(bool); quarantined { + continue + } generic, terr := getTools(name) if terr != nil { @@ -5786,6 +5798,11 @@ func (s *Server) handleAnnotationCoverage(w http.ResponseWriter, r *http.Request if name == "" { continue } + // #1064: a quarantined server's tools are not available, so they are + // not part of the annotation-coverage denominator either. + if quarantined, _ := srv["quarantined"].(bool); quarantined { + continue + } tools, err := s.controller.GetServerTools(name) if err != nil { diff --git a/internal/httpapi/server_global_tools_test.go b/internal/httpapi/server_global_tools_test.go index 0e51a4e33..eee23002c 100644 --- a/internal/httpapi/server_global_tools_test.go +++ b/internal/httpapi/server_global_tools_test.go @@ -214,3 +214,65 @@ func TestGlobalTools_ScanHoldEvidenceSurfaced(t *testing.T) { assert.NotContains(t, legacy, "held_reason", "records without hold evidence must stay unchanged") assert.NotContains(t, legacy, "held_signals") } + +// Issue #1064: a quarantined server kept reporting its tools as available. +// Unlike the DISABLED case — which reaches this handler as an empty tool set +// only because disabling disconnects the server — quarantine leaves the server +// dialed for security inspection with status ready, so the tools came straight +// through while every call to them was refused and the search index correctly +// held nothing. +func TestGlobalTools_QuarantinedServerContributesNothing(t *testing.T) { + ctrl := &globalToolsController{ + allServers: []map[string]interface{}{ + {"name": "github", "quarantined": false}, + {"name": "memory", "quarantined": true}, + // A disabled server must STILL contribute its tools: the + // GlobalToolsResponse contract lists them as disabled rather than + // hiding them. + {"name": "notes", "quarantined": false}, + }, + serverTools: map[string][]map[string]interface{}{ + "github": { + {"name": "create_issue", "description": "Create issue"}, + {"name": "delete_repo", "description": "Delete repo"}, + }, + "memory": { + {"name": "store", "description": "Store memory"}, + {"name": "recall", "description": "Recall memory"}, + {"name": "forget", "description": "Forget memory"}, + }, + "notes": { + {"name": "append", "description": "Append note"}, + }, + }, + configDenied: map[string]bool{"notes\x00append": true}, + } + + data := doGlobalTools(t, ctrl) + + tools := data["tools"].([]interface{}) + byName := map[string]string{} + for _, x := range tools { + tm := x.(map[string]interface{}) + byName[tm["name"].(string)] = tm["server_name"].(string) + } + + assert.Contains(t, byName, "create_issue") + assert.Contains(t, byName, "delete_repo") + assert.Contains(t, byName, "append", "a disabled server's tools must still be listed") + + for _, quarantined := range []string{"store", "recall", "forget"} { + assert.NotContains(t, byName, quarantined, + "quarantined server's tools must not be reported as available") + } + + stats := data["stats"].(map[string]interface{}) + assert.Equal(t, float64(3), stats["total"]) + + // Skipping a quarantined server is a deliberate exclusion, not a fetch + // failure — it must not be reported as a degraded response. + assert.NotEqual(t, true, data["partial"]) + if failed, ok := data["failed_servers"]; ok { + assert.Empty(t, failed, "a quarantined server is not a failed server") + } +} diff --git a/internal/management/service.go b/internal/management/service.go index bd7e97c99..4bebbd76d 100644 --- a/internal/management/service.go +++ b/internal/management/service.go @@ -457,8 +457,10 @@ func (s *service) ListServers(ctx context.Context) ([]*contracts.Server, *contra // Extract numeric fields if toolCount, ok := srvRaw["tool_count"].(int); ok { srv.ToolCount = toolCount - // Only count tools from enabled servers in the total - if srv.Enabled { + // Only count tools from servers that actually contribute available + // tools: enabled, and not quarantined (#1064 -- a quarantined + // server's tools are refused at dispatch and purged from the index). + if config.ServerContributesTools(srv.Enabled, srv.Quarantined) { stats.TotalTools += toolCount } } diff --git a/internal/management/service_test.go b/internal/management/service_test.go index 4ae978152..f3ffbf000 100644 --- a/internal/management/service_test.go +++ b/internal/management/service_test.go @@ -324,6 +324,59 @@ func TestListServers(t *testing.T) { } }) + // Issue #1064: a quarantined server stays connected and status ready -- that + // is deliberate, the tray and Web UI must inspect it for review -- so the + // enabled-only guard above never fired for it and its tools were still + // summed as "Available across all servers" while every call to them was + // refused. + t.Run("TotalTools excludes quarantined servers", func(t *testing.T) { + runtime := newMockRuntime() + runtime.servers = []map[string]interface{}{ + { + "id": "server1", + "name": "clean-server", + "enabled": true, + "connected": true, + "quarantined": false, + "tool_count": 5, + }, + { + "id": "server2", + "name": "quarantined-server", + "enabled": true, + "connected": true, // still dialed, for security inspection + "quarantined": true, + "tool_count": 7, // must NOT be counted + }, + { + "id": "server3", + "name": "disabled-server", + "enabled": false, + "connected": false, + "quarantined": false, + "tool_count": 3, // must NOT be counted (issue #285) + }, + } + + svc := NewService(runtime, cfg, "", emitter, nil, logger) + servers, stats, err := svc.ListServers(context.Background()) + + require.NoError(t, err) + assert.Len(t, servers, 3) + assert.Equal(t, 5, stats.TotalTools, + "TotalTools must exclude both quarantined and disabled servers") + + // The quarantined server is still listed and still flagged: the review + // surface must not go dark just because the count went to zero. + byName := map[string]*contracts.Server{} + for i := range servers { + byName[servers[i].Name] = servers[i] + } + require.Contains(t, byName, "quarantined-server") + assert.True(t, byName["quarantined-server"].Quarantined) + assert.Equal(t, 1, stats.QuarantinedServers) + }) + t.Run("runtime error", func(t *testing.T) { runtime := newMockRuntime() runtime.getAllError = fmt.Errorf("runtime error") diff --git a/internal/runtime/runtime.go b/internal/runtime/runtime.go index 58125b095..d0bc51068 100644 --- a/internal/runtime/runtime.go +++ b/internal/runtime/runtime.go @@ -2169,6 +2169,17 @@ func (r *Runtime) GetAllServers() ([]map[string]interface{}, error) { // once, here, so every consumer (Web UI, tray, CLI) gets the clean chain. lastError := stringutil.CollapseRepeatedErrorWrappers(serverStatus.LastError) + // #1064: a quarantined server's tools are not available to an agent -- + // every dispatch is refused and the search index is purged (#1061) -- + // but the stale pre-quarantine count survives in the StateView because + // the supervisor re-sticks it on reconcile and AddServer re-dials the + // server for inspection. Zero it here, at the wire boundary, so every + // consumer of this projection agrees with the index. + availableToolCount := serverStatus.ToolCount + if serverStatus.Quarantined { + availableToolCount = 0 + } + serverMap := map[string]interface{}{ "id": serverStatus.Name, "name": serverStatus.Name, @@ -2180,7 +2191,7 @@ func (r *Runtime) GetAllServers() ([]map[string]interface{}, error) { "created": created, "connected": connected, "connecting": connecting, - "tool_count": serverStatus.ToolCount, + "tool_count": availableToolCount, "last_error": lastError, "status": status, "should_retry": false, @@ -2353,7 +2364,7 @@ func (r *Runtime) GetAllServers() ([]map[string]interface{}, error) { HasRefreshToken: hasRefreshToken, UserLoggedOut: userLoggedOut, CallTimeOAuthRequired: callTimeOAuthRequired, - ToolCount: serverStatus.ToolCount, + ToolCount: availableToolCount, MissingSecret: health.ExtractMissingSecret(lastError), OAuthConfigErr: health.ExtractOAuthConfigError(lastError), } diff --git a/internal/runtime/tool_quarantine_reindex_test.go b/internal/runtime/tool_quarantine_reindex_test.go index c3681c44f..7c74593dc 100644 --- a/internal/runtime/tool_quarantine_reindex_test.go +++ b/internal/runtime/tool_quarantine_reindex_test.go @@ -237,6 +237,15 @@ func TestServerEligibleForIndexing(t *testing.T) { assert.False(t, rt.serverEligibleForIndexing("quarantined"), "quarantined server is ineligible") assert.False(t, rt.serverEligibleForIndexing("disabled"), "disabled server is ineligible") assert.False(t, rt.serverEligibleForIndexing("absent"), "server absent from config is ineligible") + + // #1064: the availability predicate (what gets COUNTED) must agree with this + // security predicate (what gets INDEXED) for every enabled/quarantined pair. + // They diverged once already -- the index was purged on quarantine while the + // counting surfaces went on reporting the pre-quarantine number. + for _, srv := range rt.Config().Servers { + assert.Equalf(t, rt.serverEligibleForIndexing(srv.Name), srv.ContributesTools(), + "serverEligibleForIndexing and ContributesTools disagree about %q", srv.Name) + } } // TestReindexAfterApproval_QuarantinedServerNotIndexed guards the TOCTOU diff --git a/internal/server/mcp.go b/internal/server/mcp.go index 069e41dcc..d613491c2 100644 --- a/internal/server/mcp.go +++ b/internal/server/mcp.go @@ -5941,6 +5941,16 @@ func (p *MCPProxyServer) getVisibleToolCount(serverName string) int { return 0 } + // #1064: a quarantined server contributes no AVAILABLE tools -- every + // dispatch to them is refused with a SECURITY BLOCK. Gated here rather than + // in isToolCallable, which is the search filter and must stay + // quarantine-blind to preserve merge-base retrieve_tools semantics + // (Spec 085 FR-006/FR-011). The tools themselves stay in the StateView so + // the review surface can still list them. + if cfg, err := p.storage.GetUpstreamServer(serverName); err == nil && cfg != nil && cfg.Quarantined { + return 0 + } + supervisor := p.mainServer.runtime.Supervisor() if supervisor == nil { return 0 @@ -6094,6 +6104,13 @@ func (p *MCPProxyServer) isToolCallable(serverName, toolName string) bool { return false } + // NOTE: quarantine is deliberately NOT gated here. isToolCallable is the + // SEARCH filter and must reproduce merge-base semantics exactly (Spec 085 + // FR-006/FR-011) -- retrieve_tools still surfaces a quarantined server's + // lingering indexed tools; the stricter p.toolVisibleToSession is what + // applies the quarantine gate. The #1064 counting fix lives in + // getVisibleToolCount instead. + // Config-layer filter — evaluated at call time, never written to BBolt. // A tool absent from enabled_tools or present in disabled_tools is hard off. if p.mainServer != nil && p.mainServer.runtime != nil { diff --git a/internal/server/mcp_disabled_discovery_test.go b/internal/server/mcp_disabled_discovery_test.go index f800a680d..5b20ab917 100644 --- a/internal/server/mcp_disabled_discovery_test.go +++ b/internal/server/mcp_disabled_discovery_test.go @@ -238,3 +238,30 @@ func TestServerToolCounts_Conditional(t *testing.T) { assert.NotContains(t, js, "pending_approval") assert.NotContains(t, js, "server_disabled") } + +// Issue #1064: the visible tool count reported for a quarantined server must be +// zero -- every dispatch to its tools is refused with a SECURITY BLOCK. +// +// The gate lives in getVisibleToolCount, NOT in isToolCallable: isToolCallable +// is the SEARCH filter and must stay quarantine-blind so retrieve_tools keeps +// its merge-base semantics (Spec 085 FR-006/FR-011, pinned by +// TestToolVisibility_RetrieveParity_Admin, which requires a quarantined +// server's lingering indexed tool to still be returned by search). This test +// pins both halves so a future "fix" cannot collapse them again. +func TestVisibleToolCount_QuarantinedServer(t *testing.T) { + proxy := createTestMCPProxyServer(t) + require.NoError(t, proxy.storage.SaveUpstreamServer(&config.ServerConfig{ + Name: "held", Enabled: true, Quarantined: true, + })) + require.NoError(t, proxy.storage.SaveUpstreamServer(&config.ServerConfig{ + Name: "clean", Enabled: true, + })) + + assert.Equal(t, 0, proxy.getVisibleToolCount("held"), + "a quarantined server contributes no available tools") + + // ...but the search filter still ignores quarantine, on purpose. + assert.True(t, proxy.isToolCallable("held", "store"), + "isToolCallable is the search filter and must stay quarantine-blind (Spec 085)") + assert.True(t, proxy.isToolCallable("clean", "store")) +} diff --git a/internal/server/server.go b/internal/server/server.go index 7fc7a8201..fd71c8ce0 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -1139,6 +1139,15 @@ func (s *Server) GetUpstreamStats() map[string]interface{} { connecting := strings.EqualFold(state, "connecting") + // #1064: a quarantined server contributes no available tools. + // This entry map carries no enabled/quarantined key, so + // downstream consumers (contracts.ConvertUpstreamStatsToServerStats) + // cannot gate on it -- the value has to be zeroed here. + availableToolCount := status.ToolCount + if status.Quarantined { + availableToolCount = 0 + } + entry := map[string]interface{}{ "state": state, "connected": status.Connected, @@ -1146,7 +1155,7 @@ func (s *Server) GetUpstreamStats() map[string]interface{} { "retry_count": status.RetryCount, "should_retry": false, "name": status.Name, - "tool_count": status.ToolCount, + "tool_count": availableToolCount, } if entry["name"] == "" { @@ -1194,7 +1203,9 @@ func (s *Server) GetUpstreamStats() map[string]interface{} { if status.Quarantined { quarantinedCount++ } - totalTools += status.ToolCount + if config.ServerContributesTools(status.Enabled, status.Quarantined) { + totalTools += status.ToolCount + } serverStats[name] = entry } @@ -1214,8 +1225,16 @@ func (s *Server) GetUpstreamStats() map[string]interface{} { // Enhance stats with tool counts per server when falling back if servers, ok := stats["servers"].(map[string]interface{}); ok { + quarantined := s.quarantinedServerNames() for id, serverInfo := range servers { if serverMap, ok := serverInfo.(map[string]interface{}); ok { + // #1064: getServerToolCount reads the managed client's tool-count + // cache, which no quarantine path invalidates, so it would hand + // back the pre-quarantine number. Gate it on the config instead. + if quarantined[id] { + serverMap["tool_count"] = 0 + continue + } serverMap["tool_count"] = s.getServerToolCount(id) } } @@ -1328,6 +1347,15 @@ func (s *Server) GetAllServers() ([]map[string]interface{}, error) { healthStatus := health.CalculateHealth(healthInput, health.DefaultHealthConfig()) + // #1064: quarantined tools are not available -- see the same guard in + // Runtime.GetAllServers. GetQuarantinedServers below deliberately keeps + // the real count: that view exists to tell a reviewer how many tools + // await approval. + availableToolCount := serverStatus.ToolCount + if serverStatus.Quarantined { + availableToolCount = 0 + } + serverMap := map[string]interface{}{ "name": serverStatus.Name, "url": url, @@ -1340,7 +1368,7 @@ func (s *Server) GetAllServers() ([]map[string]interface{}, error) { "created": created, "connected": connected, "connecting": connecting, - "tool_count": serverStatus.ToolCount, + "tool_count": availableToolCount, "last_error": serverStatus.LastError, "status": status, "should_retry": false, // Managed by Actor internally now @@ -1833,6 +1861,24 @@ func (s *Server) QuarantineServer(serverName string, quarantined bool) error { // getServerToolCount returns the number of tools for a specific server // Returns cached tool count only (non-blocking) to avoid stalling SSE/API responses +// quarantinedServerNames returns the set of configured server names currently in +// quarantine. Used to gate cached tool counts on the GetUpstreamStats fallback +// path, where neither the manager stats entry nor getServerToolCount has access +// to the server config. Issue #1064. +func (s *Server) quarantinedServerNames() map[string]bool { + out := make(map[string]bool) + cfg := s.runtime.Config() + if cfg == nil { + return out + } + for _, srv := range cfg.Servers { + if srv != nil && srv.Quarantined { + out[srv.Name] = true + } + } + return out +} + func (s *Server) getServerToolCount(serverID string) int { client, exists := s.runtime.UpstreamManager().GetClient(serverID) if !exists { diff --git a/internal/upstream/manager.go b/internal/upstream/manager.go index 988d329e5..e47a169f7 100644 --- a/internal/upstream/manager.go +++ b/internal/upstream/manager.go @@ -1772,7 +1772,10 @@ func (m *Manager) GetTotalToolCount() int { } // Read config through the thread-safe accessor (MCP-770). cfg := client.GetConfig() - if cfg == nil || !cfg.Enabled || !client.IsConnected() { + // #1064: a quarantined server stays dialed for security inspection, so + // IsConnected() is true and its cached count is still the pre-quarantine + // number -- exclude it explicitly. + if cfg == nil || !cfg.ContributesTools() || !client.IsConnected() { continue } From a8b4ecbeff8ee678a0e1ba60aa49bfc171c5a415 Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Thu, 27 Aug 2026 13:39:23 +0300 Subject: [PATCH 2/2] =?UTF-8?q?fix(webui):=20three=20presentation=20defect?= =?UTF-8?q?s=20=E2=80=94=20contradictory=20card,=20raw=20enum,=20stale=20a?= =?UTF-8?q?uth=20error=20(#1065)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 1. A server card asserted two contradictory security states at once The card rendered a green "Clean" scan verdict directly above a yellow "Quarantined — needs security review" banner. Both are individually true, but stacked as peers they tell the operator opposite things: the scan verdict is about CONTENT, quarantine is about REVIEW STATE. While quarantined, the standalone verdict badge is suppressed and the verdict is folded into the banner as a subordinate clause ("Last scan: clean — still needs review"), so the card carries exactly one security headline. This is the subordination ServerDetail's spec-088 banner already does, and the same shape as the #938 held-tools downgrade one level up. Nothing changes when the server is not quarantined. Every verdict still ends in a request to review, including the failed case, which is an INCOMPLETE scan and never a threat verdict. The Servers v-memo key gains security_scan.status and finding_counts.warning: the store updates server objects in place to preserve identity, so without them a scan settling on an already-quarantined server left a stale verdict. 2. The Activity Type column mixed two vocabularies formatType fell through `|| type` for anything unmapped, so raw snake_case landed in a column otherwise full of title-cased prose. Four backend types had no label, not the one reported: tool_quarantine_change, security_scan (already rendering raw today — it has had a findings drawer since #1046), credential_broker and prompt_get. The map is completed and exported as ACTIVITY_TYPE_LABELS, and the passthrough is replaced with a snake_case -> Title Case fallback so an unmapped value can never leak raw again. Server-level and tool-level quarantine keep distinct labels. The filter dropdown is derived from the same map instead of being hand-copied (it was three types short), and ActivityWidget's duplicate icon map is deleted in favour of the shared one. The recurrence guard lives in Go, not vitest: internal/storage/activity_label_parity_test.go fails when a backend type has no Web-UI label. .github/workflows/frontend.yml is path-filtered to frontend/**, so a vitest-only guard would never run on the Go-only change that adds a type. A second test asserts ValidActivityTypes covers every declared constant, so the first cannot go vacuously green. 3. A stale auth error survived a successful sign-in With no stored key, /ui/activity showed the auth modal, an inline red "Invalid or missing API key" panel behind it, and a Disconnected chip. Entering a valid key re-authenticated the header — counts and the Live badge came back — but the view body kept the red panel and rendered zero rows until the user clicked Retry by hand. Every view holds its load error in a component-local ref that nothing outside the component can reach, and no auth-recovered signal existed to reach it. Adds a monotonic authEpoch to the system store, bumped by markAuthRecovered() only on a genuine failed->ok transition. App.vue keys on it, so a repaired auth remounts the current view and its error, loading state and data reset to their declared initial values while onMounted re-runs. Keyed on authEpoch alone: folding in the route path would remount ServerDetail on every :serverName change and break the Dashboard's single instance across /, /usage and /overview. reloadAfterAuth() re-primes the surfaces the key cannot reach (fetchInfo, fetchRouting, checkAuth — the router guard does not run for a key-driven remount), and SidebarNav watches the epoch for its badge counts rather than being remounted, which would also reset its open submenu and scroll. AuthErrorModal's "Refresh & Retry" now validates the reloaded key before reporting success and emits `refresh(verified)`. It previously cleared the auth flag without verifying anything, which is why it could not safely invalidate views — and why the stale panel survived on that path. --- frontend/src/App.vue | 47 +++++-- frontend/src/components/ActivityWidget.vue | 13 +- frontend/src/components/AuthErrorModal.vue | 29 +++- frontend/src/components/ServerCard.vue | 52 +++++++- frontend/src/components/SidebarNav.vue | 17 ++- frontend/src/stores/system.ts | 22 +++ frontend/src/utils/activity.ts | 47 ++++++- frontend/src/views/Activity.vue | 22 ++- frontend/src/views/Servers.vue | 9 +- .../tests/unit/activity-type-labels.spec.ts | 42 ++++++ frontend/tests/unit/activity.spec.ts | 4 +- .../tests/unit/auth-recovery-epoch.spec.ts | 115 ++++++++++++++++ ...rver-card-quarantine-scan-headline.spec.ts | 126 ++++++++++++++++++ .../storage/activity_label_parity_test.go | 60 +++++++++ 14 files changed, 548 insertions(+), 57 deletions(-) create mode 100644 frontend/tests/unit/activity-type-labels.spec.ts create mode 100644 frontend/tests/unit/auth-recovery-epoch.spec.ts create mode 100644 frontend/tests/unit/server-card-quarantine-scan-headline.spec.ts create mode 100644 internal/storage/activity_label_parity_test.go diff --git a/frontend/src/App.vue b/frontend/src/App.vue index cf6b639d6..c068a20e0 100644 --- a/frontend/src/App.vue +++ b/frontend/src/App.vue @@ -17,7 +17,14 @@ its track and the footer ended up overlapping the last row at 390px (UX audit F14). -->
- + +
@@ -79,24 +86,44 @@ function handleAuthModalClose() { systemStore.setAuthRequired(false) } +// Re-prime everything that only loads at mount. The key covers +// the routed view, but these surfaces live outside it and would otherwise keep +// their failed state until a full page reload (#1065). +async function reloadAfterAuth() { + systemStore.connectEventSource() + serversStore.fetchServers() + systemStore.fetchInfo() // TopHeader version / update state + systemStore.fetchRouting() // TopHeader routing chip + // Server-edition role-based nav. The router guard does not run for a + // key-driven remount, so re-check here. + await authStore.checkAuth() +} + function handleAuthModalAuthenticated() { authModal.show = false authModal.lastError = '' - systemStore.setAuthRequired(false) + // markAuthRecovered, not setAuthRequired(false): this path validated the key, + // so it is safe to invalidate every view that failed while auth was broken. + systemStore.markAuthRecovered() - // Refresh data now that we're authenticated - systemStore.connectEventSource() - serversStore.fetchServers() + void reloadAfterAuth() } -function handleAuthModalRefresh() { +function handleAuthModalRefresh(verified: boolean) { + if (!verified) { + // The reloaded key did not authenticate. Leave the modal and the + // auth-required flag in place rather than remounting every view onto a + // key that is still 401. + return + } + authModal.show = false authModal.lastError = '' - systemStore.setAuthRequired(false) + // The modal verified the reloaded key, so this is a real recovery and the + // views holding stale auth errors must be invalidated too (#1065). + systemStore.markAuthRecovered() - // Reconnect with potentially new API key - systemStore.connectEventSource() - serversStore.fetchServers() + void reloadAfterAuth() } // Handle API authentication errors diff --git a/frontend/src/components/ActivityWidget.vue b/frontend/src/components/ActivityWidget.vue index 3b08314f2..c0b0926ab 100644 --- a/frontend/src/components/ActivityWidget.vue +++ b/frontend/src/components/ActivityWidget.vue @@ -105,6 +105,7 @@ import api from '@/services/api' import type { ActivityRecord, ActivitySummaryResponse } from '@/types/api' import { formatPreflightSummary, + getTypeIcon, isChildCall, isPreflightActivity, statusPresentation, @@ -161,18 +162,6 @@ const formatRelativeTime = (timestamp: string): string => { return `${Math.floor(diff / 86400000)}d ago` } -const getTypeIcon = (type: string): string => { - const typeIcons: Record = { - 'tool_call': '🔧', - 'policy_decision': '🛡️', - 'quarantine_change': '⚠️', - 'server_change': '🔄', - // Spec 098: required-tools preflight - 'preflight': '🛫' - } - return typeIcons[type] || '📋' -} - // Lifecycle onMounted(() => { loadData() diff --git a/frontend/src/components/AuthErrorModal.vue b/frontend/src/components/AuthErrorModal.vue index 8106efed6..7bf0704b2 100644 --- a/frontend/src/components/AuthErrorModal.vue +++ b/frontend/src/components/AuthErrorModal.vue @@ -109,7 +109,9 @@ interface Props { interface Emits { (e: 'close'): void (e: 'authenticated'): void - (e: 'refresh'): void + // `verified` says whether the reloaded key actually authenticated. App.vue + // only invalidates views when it did (#1065). + (e: 'refresh', verified: boolean): void } const props = withDefaults(defineProps(), { @@ -175,10 +177,27 @@ async function handleSetAPIKey() { } } -function handleRefresh() { - // Reinitialize API key from URL/localStorage - api.reinitializeAPIKey() - emit('refresh') +async function handleRefresh() { + // Reinitialize API key from URL/localStorage, then VERIFY it before telling + // the app auth is repaired. Without the verification this path could only + // assert recovery, so it could not safely invalidate the views holding stale + // auth errors -- and #1065's stale red panel survived on this path. + isValidating.value = true + inputError.value = '' + try { + api.reinitializeAPIKey() + const isValid = await api.validateAPIKey() + emit('refresh', isValid) + if (!isValid) { + inputError.value = 'No valid API key found — enter one above' + } + } catch (error) { + console.error('API key refresh error:', error) + inputError.value = error instanceof Error ? error.message : 'Refresh failed' + emit('refresh', false) + } finally { + isValidating.value = false + } } function handleClose() { diff --git a/frontend/src/components/ServerCard.vue b/frontend/src/components/ServerCard.vue index 9f7336914..7c49ea071 100644 --- a/frontend/src/components/ServerCard.vue +++ b/frontend/src/components/ServerCard.vue @@ -85,7 +85,14 @@ -
+ +
-
- +
+ - Quarantined — needs security review +
+
Quarantined — needs security review
+
{{ quarantineScanNote }}
+
{ } }) +// #1065: the subordinate half of the quarantine banner. Same reasoning as the +// #938 held-tools downgrade above, one level up -- a reassuring statement must +// never sit as a peer of a warning one. While quarantined the standalone badge +// is suppressed and its verdict is restated here as a clause of the quarantine +// headline: the verdict informs the review, it does not settle it. Returns '' +// when there is nothing worth saying, keeping the banner a one-liner. +const quarantineScanNote = computed(() => { + const scan = props.server.security_scan + const status = scan?.status + if (!scan || !status || status === 'not_scanned') return '' + switch (status) { + case 'scanning': + return 'Security scan in progress…' + case 'failed': + // A failed scan is an INCOMPLETE scan, never a threat verdict -- mirrors + // the scan-failed precaution branch in utils/quarantineBanner.ts. + return 'Last scan could not complete — still needs review' + case 'clean': + return 'Last scan: clean — still needs review' + case 'warnings': { + const n = scan.finding_counts?.warning ?? 0 + return `Last scan: ${n} warning${n !== 1 ? 's' : ''} — needs review` + } + case 'dangerous': + return 'Last scan: dangerous findings — needs review' + default: + return '' + } +}) + // Determine if error message should be shown (FR-018, FR-019) // Suppress verbose last_error when health.action already conveys the issue const shouldShowError = computed(() => { diff --git a/frontend/src/components/SidebarNav.vue b/frontend/src/components/SidebarNav.vue index 9becef7f4..11ee99d73 100644 --- a/frontend/src/components/SidebarNav.vue +++ b/frontend/src/components/SidebarNav.vue @@ -475,7 +475,7 @@