Skip to content

Self-improving AI Employees for everyone

fix(credentials): honest key panels, and the Gateway card that fits

trohitg5b3e0569c3f7
diff --git a/.env.template b/.env.template
index 4ee232a6..84a68f4f 100644
--- a/.env.template
+++ b/.env.template
@@ -334,7 +334,7 @@ WEBSOCKET_API_KEY=
AI_PROXY_DEFAULT_PORT=11434
# OpenCompany Gateway (docs-internal/llm_gateway.md). When enabled, the
-# Connectors panel offers "OpenCompany Gateway": with a gateway key there, LLM
+# Connectors panel offers the "Gateway" card: with a gateway key there, LLM
# calls for a provider this install has no key of its own for go through the
# gateway, billed to the key owner's monthly allowance.
OPENCOMPANY_GATEWAY_ENABLED=false
diff --git a/client/src/components/credentials/__tests__/useCredentialPanel.test.tsx b/client/src/components/credentials/__tests__/useCredentialPanel.test.tsx
new file mode 100644
index 00000000..3921ce2b
--- /dev/null
+++ b/client/src/components/credentials/__tests__/useCredentialPanel.test.tsx
@@ -0,0 +1,98 @@
+/**
+ * useCredentialPanel's `stored` follows the server: removing a key leaves the
+ * panel disconnected (no Connected badge, no Valid button, no status line)
+ * instead of flipping back from the pre-removal cache entry.
+ */
+
+import React from 'react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { act, renderHook, waitFor } from '@testing-library/react';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+
+const sendRequest = vi.fn();
+const removeApiKey = vi.fn();
+
+vi.mock('../../../contexts/WebSocketContext', () => ({
+ useWebSocket: () => ({ sendRequest }),
+}));
+
+vi.mock('../../../hooks/useApiKeys', () => ({
+ useApiKeys: () => ({
+ validateApiKey: vi.fn(),
+ saveApiKey: vi.fn(),
+ removeApiKey,
+ getProviderDefaults: vi.fn(),
+ saveProviderDefaults: vi.fn(),
+ getProviderUsageSummary: vi.fn(),
+ getAPIUsageSummary: vi.fn(),
+ getStoredModels: vi.fn(),
+ getModelConstraints: vi.fn(),
+ isConnected: true,
+ }),
+}));
+
+import { useCredentialPanel } from '../useCredentialPanel';
+import type { ProviderConfig } from '../types';
+
+const CONFIG: ProviderConfig = {
+ id: 'opencompany_gateway',
+ name: 'Gateway',
+ category: 'ai',
+ categoryLabel: 'AI models',
+ color: '',
+ kind: 'apiKey',
+ iconRef: 'lucide:Sparkles',
+ fields: [{ key: 'apiKey', label: 'Gateway key', secret: true }],
+ ws: { login: '', logout: '', status: 'gateway_status' },
+};
+
+let client: QueryClient;
+const wrapper = ({ children }: { children: React.ReactNode }) => (
+ <QueryClientProvider client={client}>{children}</QueryClientProvider>
+);
+
+describe('useCredentialPanel', () => {
+ beforeEach(() => {
+ client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ sendRequest.mockReset();
+ removeApiKey.mockReset();
+ });
+
+ it('stays disconnected after its key is removed', async () => {
+ let hasKey = true;
+ // The post-removal refetch waits until released, so the panel renders in
+ // between, as it does over a real socket.
+ let release: () => void = () => {};
+ let gate: Promise<void> | null = null;
+ sendRequest.mockImplementation(async (type: string) => {
+ if (type === 'get_stored_api_key') {
+ if (gate) await gate;
+ return { hasKey, apiKey: hasKey ? 'sk-gateway' : undefined };
+ }
+ if (type === 'gateway_status') return { summary: '$0.00 of $50.00 used' };
+ return {};
+ });
+ removeApiKey.mockImplementation(async () => {
+ hasKey = false;
+ gate = new Promise((resolve) => {
+ release = resolve;
+ });
+ });
+
+ const { result } = renderHook(() => useCredentialPanel(CONFIG, true), { wrapper });
+ await waitFor(() => expect(result.current.stored).toBe(true));
+ await waitFor(() => expect(result.current.statusSummary).toBe('$0.00 of $50.00 used'));
+
+ let removal: Promise<unknown> = Promise.resolve();
+ act(() => {
+ removal = result.current.actions.remove('opencompany_gateway');
+ });
+ await waitFor(() => expect(removeApiKey).toHaveBeenCalledWith('opencompany_gateway'));
+ await act(async () => {
+ release();
+ await removal;
+ });
+
+ expect(result.current.stored).toBe(false);
+ });
+});
diff --git a/client/src/components/credentials/useCredentialPanel.ts b/client/src/components/credentials/useCredentialPanel.ts
index eb74cccd..d61fb958 100644
--- a/client/src/components/credentials/useCredentialPanel.ts
+++ b/client/src/components/credentials/useCredentialPanel.ts
@@ -212,8 +212,10 @@ export function useCredentialPanel(config: ProviderConfig, visible: boolean) {
}),
remove: (key: string) => execute('remove', async () => {
await removeApiKey(key);
- setStored(false);
+ // Refetch before clearing `stored`: the sync above would read the
+ // pre-removal `hadStored` and flip it straight back to true.
await invalidateValues();
+ setStored(false);
}),
oauthLogin: () => execute('login', async () => {
const res = await sendRequest(config.ws!.login, {});
diff --git a/client/src/hooks/__tests__/useApiKeys.test.ts b/client/src/hooks/__tests__/useApiKeys.test.ts
index 3045c8b4..5ad1e213 100644
--- a/client/src/hooks/__tests__/useApiKeys.test.ts
+++ b/client/src/hooks/__tests__/useApiKeys.test.ts
@@ -93,6 +93,18 @@ describe('useApiKeys.validateApiKey', () => {
expect(result.current.isValidating).toBe(false);
});
+ it("keeps a valid key's message out of error, which panels show as a failure", async () => {
+ wsMock.validateApiKey.mockResolvedValue({ valid: true, message: 'Connected: $0.00 of $50.00 used.' });
+ const { result } = renderHook(() => useApiKeys());
+ let validation: any;
+ await act(async () => {
+ validation = await result.current.validateApiKey('opencompany_gateway', 'sk-gw');
+ });
+ expect(validation.isValid).toBe(true);
+ expect(validation.error).toBeUndefined();
+ expect(result.current.validationError).toBeNull();
+ });
+
it('sets validationError on invalid response', async () => {
wsMock.validateApiKey.mockResolvedValue({
valid: false,
diff --git a/client/src/hooks/useApiKeys.ts b/client/src/hooks/useApiKeys.ts
index 49814f8d..9a38bc28 100644
--- a/client/src/hooks/useApiKeys.ts
+++ b/client/src/hooks/useApiKeys.ts
@@ -179,9 +179,11 @@ export const useApiKeys = (): UseApiKeysResult => {
setValidationError(result.message || 'Validation failed');
}
+ // A valid key's message ("API key validated", the gateway's allowance)
+ // is not an error: panels show `error` as a failure.
return {
isValid: result.valid,
- error: result.message,
+ error: result.valid ? undefined : result.message,
models: result.models
};
} catch (error: any) {
@@ -296,7 +298,7 @@ export const useApiKeys = (): UseApiKeysResult => {
return {
isValid: result.valid,
- error: result.message
+ error: result.valid ? undefined : result.message
};
} catch (error: any) {
const errorMsg = error.message || 'Validation failed';
@@ -328,7 +330,7 @@ export const useApiKeys = (): UseApiKeysResult => {
return {
isValid: result.valid,
- error: result.message
+ error: result.valid ? undefined : result.message
};
} catch (error: any) {
const errorMsg = error.message || 'Validation failed';
diff --git a/docs-internal/llm_gateway.md b/docs-internal/llm_gateway.md
index 2ac810f8..c8e5a8ef 100644
--- a/docs-internal/llm_gateway.md
+++ b/docs-internal/llm_gateway.md
@@ -6,7 +6,12 @@ OpenCompany's hosted LLM gateway is the stock open-source LiteLLM Proxy, deploye
## OpenCompany's side
-**Turning it on.** `OPENCOMPANY_GATEWAY_ENABLED=true` (`gateway_enabled`, default off) lists the **OpenCompany Gateway** card in Connectors (`requires_setting` in `server/config/credential_providers.json`, honoured by `CredentialRegistry.get_all_providers`). `OPENCOMPANY_GATEWAY_URL` (`gateway_url`) points at the gateway. Off, behaviour is exactly as before. Distributed mode keeps it off: the gateway key has no 1Password support yet.
+**Turning it on.**
+- `OPENCOMPANY_GATEWAY_ENABLED=true` (`gateway_enabled`, default off) lists the **Gateway** card, by OpenCompany, under AI models in Connectors. It is gated by `requires_setting` in `server/config/credential_providers.json`, honoured by `CredentialRegistry.get_all_providers`.
+- **Where it appears:** in normal mode, the Get Started guide's Connect an AI model step and Connectors; in dev mode, API Credentials. Both shells use the same `CredentialsBrowser`.
+- `OPENCOMPANY_GATEWAY_URL` (`gateway_url`) points at the gateway.
+- Off, behaviour is exactly as before.
+- **No 1Password:** the router reads the key on every call, which a 1Password lookup can't serve. So the card offers no 1Password source (`catalogue_extras`), and distributed mode keeps the gateway off.
**The key.** One gateway key per install, saved like any API key (`OpenCompanyGatewayCredential`, `services/gateway/credential.py`, default `validate`). Its probe calls the gateway's `/user/info` with the key: 401 means a wrong key; 403 means an LLM-API key, and the person is told to create a Default one. The card's `ws.status` hook (`gateway_status`, `services/gateway/handlers.py`) returns the allowance as one line, which the API-key panel shows under the key (`statusSummary` in `useCredentialPanel`).
diff --git a/server/config/credential_providers.json b/server/config/credential_providers.json
index e0de1ff3..8f9d0ee8 100644
--- a/server/config/credential_providers.json
+++ b/server/config/credential_providers.json
@@ -115,7 +115,7 @@
},
"opencompany_gateway": {
"_description": "The hosted OpenCompany Gateway (gateway/, docs-internal/llm_gateway.md). One key per install, stored like any API key; LLM calls for a provider the install has no key of its own for go through the gateway on the key owner's monthly allowance (services/gateway). Not an LLM provider itself: no llm_defaults.json block, so it never appears in model pickers. Listed only while OPENCOMPANY_GATEWAY_ENABLED is on (requires_setting). ws.status feeds the card's allowance line.",
- "name": "OpenCompany Gateway",
+ "name": "Gateway",
"publisher": "OpenCompany",
"verified": true,
"consumer_category": "ai",
diff --git a/server/services/gateway/credential.py b/server/services/gateway/credential.py
index a252d490..ada39b82 100644
--- a/server/services/gateway/credential.py
+++ b/server/services/gateway/credential.py
@@ -8,6 +8,8 @@ Default key (needed to show the allowance) from an LLM-API one.
from __future__ import annotations
+from typing import Any, Dict, Optional
+
from services.plugin.credential import ApiKeyCredential, ProbeResult
from .allowance import parse_user_info, user_info
@@ -21,6 +23,13 @@ class OpenCompanyGatewayCredential(ApiKeyCredential):
key_location = "bearer"
docs_url = "https://docs.litellm.ai/docs/proxy/virtual_keys"
+ @classmethod
+ async def catalogue_extras(cls, *, principal: Optional[str] = None) -> Optional[Dict[str, Any]]:
+ # No 1Password source: the router reads the key on every LLM call
+ # (services/gateway/routing.py), which a 1Password lookup can't
+ # serve, so a bound key would show as connected and never be used.
+ return {"sourceSupported": False}
+
@classmethod
async def _probe(cls, api_key: str) -> ProbeResult:
from core.container import container
diff --git a/server/services/gateway/errors.py b/server/services/gateway/errors.py
index e0851b07..43e9bc97 100644
--- a/server/services/gateway/errors.py
+++ b/server/services/gateway/errors.py
@@ -24,7 +24,7 @@ _DENIED = "The OpenCompany Gateway denied this request."
_RATE_LIMITED = "The OpenCompany Gateway is rate-limiting requests. Retry after a short delay."
_UNREACHABLE = "Could not reach the OpenCompany Gateway."
_UNAVAILABLE = "The OpenCompany Gateway is temporarily unavailable."
-_RECONNECT = "Reconnect the OpenCompany Gateway in Settings > Connectors"
+_RECONNECT = "Reconnect the Gateway connector in Settings > Connectors"
_OWN_KEY = "add your own key for this provider in Settings > Connectors"
_RAISE = f"Ask your OpenCompany admin to raise it, or {_OWN_KEY}"
_OTHER_MODEL = f"Choose another model, or {_OWN_KEY}."
diff --git a/server/tests/gateway/test_connector.py b/server/tests/gateway/test_connector.py
index 354810a7..1d0995da 100644
--- a/server/tests/gateway/test_connector.py
+++ b/server/tests/gateway/test_connector.py
@@ -53,6 +53,21 @@ async def test_a_rejected_key_is_left_to_validate_to_word(monkeypatch):
await credential_module.OpenCompanyGatewayCredential._probe("sk-wrong")
+async def test_the_card_offers_no_1password_source(monkeypatch):
+ """The router reads the key on every LLM call, which a 1Password lookup
+ can't serve: a bound key would show as connected and never be used."""
+ from services.credential_registry import provider_connection_state
+ from services.plugin.credential import CREDENTIAL_REGISTRY
+
+ # A plain API-key credential would get the 1Password tab; this one opts out.
+ assert CREDENTIAL_REGISTRY.get("opencompany_gateway") is credential_module.OpenCompanyGatewayCredential
+ auth = MagicMock(distributed_credentials=False)
+ auth.has_valid_key = AsyncMock(return_value=True)
+ auth.get_oauth_tokens = AsyncMock(return_value=None)
+ state = await provider_connection_state({"id": "opencompany_gateway", "kind": "apiKey"}, auth)
+ assert state["sourceSupported"] is False
+
+
async def test_status_without_a_stored_key(monkeypatch):
from core.container import container
diff --git a/server/tests/gateway/test_errors.py b/server/tests/gateway/test_errors.py
index 452f9293..54e72392 100644
--- a/server/tests/gateway/test_errors.py
+++ b/server/tests/gateway/test_errors.py
@@ -57,7 +57,7 @@ def test_a_rejected_gateway_key_points_at_the_gateway_card():
error = explain(LLMError.from_exception("openai", exc), exc)
assert error.category is LLMErrorCategory.AUTHENTICATION
assert "OpenCompany Gateway" in error.user_message
- assert "Reconnect the OpenCompany Gateway" in error.hint
+ assert "Reconnect the Gateway connector" in error.hint
def test_wording_never_changes_retry_behaviour():