Skip to content

Self-improving AI Employees for everyone

fix(credentials): palette indicator flashes red→green on delete (3 root causes)

trohitg2c88527dc08d
diff --git a/client/src/components/credentials/CredentialsPalette.tsx b/client/src/components/credentials/CredentialsPalette.tsx
index f4af0c67..4260c698 100644
--- a/client/src/components/credentials/CredentialsPalette.tsx
+++ b/client/src/components/credentials/CredentialsPalette.tsx
@@ -39,6 +39,7 @@ import { Search, X } from 'lucide-react';
import { Input } from '@/components/ui/input';
import { cn } from '@/lib/utils';
import { NodeIcon } from '../../assets/icons';
+import { useWebSocket } from '../../contexts/WebSocketContext';
import type { ProviderConfig, CategoryGroup } from './types';
// ============================================================================
@@ -50,8 +51,6 @@ export interface CredentialsPaletteProps {
categories: CategoryGroup[];
selectedId: string | null;
onSelect: (id: string) => void;
- /** Map of provider id → has stored/validated key. Drives the green status dot. */
- storedKeys?: Record<string, boolean>;
/** Height of the scrollable list area. */
height?: number | string;
/** Optional placeholder for the search input. */
@@ -135,6 +134,77 @@ function groupFiltered(filtered: ProviderConfig[], categoryOrder: CategoryGroup[
return { groups, groupCounts, flatItems };
}
+// ============================================================================
+// Status indicator — three states: configured + validated, configured but
+// validation failed, not configured. "Validated" is meaningful only for
+// providers that go through `validate_api_key` (AI providers + the special
+// google_maps / apify validators); for OAuth + QR-pairing flows the
+// validation cache is empty and a stored credential renders as success.
+// ============================================================================
+
+type CredStatus = 'unconfigured' | 'stored' | 'failed';
+
+const STATUS_CLASSES: Record<CredStatus, string> = {
+ unconfigured: 'bg-muted-foreground/30',
+ stored: 'bg-success',
+ failed: 'bg-destructive',
+};
+
+const STATUS_LABEL: Record<CredStatus, string> = {
+ unconfigured: 'Not configured',
+ stored: 'Configured',
+ failed: 'Validation failed',
+};
+
+interface ProviderStatusDotProps {
+ providerId: string;
+ stored: boolean;
+}
+
+/** Memo'd indicator. Reads `apiKeyStatuses[id]` only when it exists, so
+ * providers without a validation flow (OAuth, QR pairing) don't pay
+ * for the lookup, and any future state (failed validation, etc.)
+ * renders without touching the row's click / selection logic. */
+const ProviderStatusDot = memo<ProviderStatusDotProps>(function ProviderStatusDot({
+ providerId,
+ stored,
+}) {
+ const { apiKeyStatuses } = useWebSocket();
+ const validation = apiKeyStatuses[providerId];
+
+ // Treat the broadcast that fires on delete (`message === 'deleted'`)
+ // as unconfigured for the brief window before the catalogue refetch
+ // lands and flips `stored` to false. Without this the dot flashes red
+ // for ~300 ms (the invalidateCatalogue debounce) every time a key is
+ // removed, even though the user's intent was deletion, not failure.
+ const justDeleted = validation?.message === 'deleted';
+
+ let status: CredStatus;
+ let title = STATUS_LABEL.unconfigured;
+ if (!stored || justDeleted) {
+ status = 'unconfigured';
+ } else if (validation && validation.valid === false) {
+ status = 'failed';
+ title = validation.message
+ ? `${STATUS_LABEL.failed}: ${validation.message}`
+ : STATUS_LABEL.failed;
+ } else {
+ status = 'stored';
+ title = STATUS_LABEL.stored;
+ }
+
+ return (
+ <span
+ aria-label={STATUS_LABEL[status]}
+ title={title}
+ className={cn(
+ 'h-2 w-2 shrink-0 rounded-full transition-colors',
+ STATUS_CLASSES[status],
+ )}
+ />
+ );
+});
+
// ============================================================================
// Row renderer — memoized to stop upstream re-renders from cascading
// ============================================================================
@@ -164,9 +234,7 @@ const ProviderRow = memo<RowProps>(function ProviderRow({ provider, selected, on
className="h-3.5 w-3.5 shrink-0 text-sm"
/>
<span className="flex-1 truncate">{provider.name}</span>
- {provider.stored && (
- <span aria-label="Credential stored" className="h-2 w-2 rounded-full bg-success" />
- )}
+ <ProviderStatusDot providerId={provider.id} stored={!!provider.stored} />
</Command.Item>
);
});
diff --git a/client/src/contexts/WebSocketContext.tsx b/client/src/contexts/WebSocketContext.tsx
index 21b11c79..e941c4d3 100644
--- a/client/src/contexts/WebSocketContext.tsx
+++ b/client/src/contexts/WebSocketContext.tsx
@@ -2183,14 +2183,16 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chi
const deleteApiKeyAsync = useCallback(async (provider: string): Promise<boolean> => {
try {
await sendRequest<any>('delete_api_key', { provider });
-
- // Remove from apiKeyStatuses on successful delete
- setApiKeyStatuses(prev => {
- const newStatuses = { ...prev };
- delete newStatuses[provider];
- return newStatuses;
- });
-
+ // Don't optimistically clear apiKeyStatuses[provider] here. The
+ // backend's `api_key_status` broadcast (fired before this reply
+ // lands) already wrote `{valid: false, hasKey: false, message:
+ // 'deleted'}` to every connected client. The catalogue refetch
+ // (debounced 300 ms after `credential_catalogue_updated`) will
+ // flip `provider.stored` to false. A local optimistic clear here
+ // raced with the broadcast and produced a green-flash mid-delete:
+ // broadcast → red, optimistic clear → green (validation undefined
+ // but stored still cached true), catalogue refetch → gray.
+ // Trusting the broadcast pipeline gives a clean red → gray.
return true;
} catch (error) {
console.error('[WebSocket] Failed to delete API key:', error);
diff --git a/server/services/auth.py b/server/services/auth.py
index 88b6d1ed..fcdfb515 100644
--- a/server/services/auth.py
+++ b/server/services/auth.py
@@ -85,6 +85,29 @@ class AuthService:
"""Create hash for API key identification."""
return hashlib.sha256(api_key.encode()).hexdigest()[:16]
+ def _bump_catalogue_version(self) -> None:
+ """Notify the credential registry that a credential has changed.
+
+ Bumps the registry's mutation counter so the next call to
+ ``CredentialRegistry.get_version()`` returns a new content hash.
+ The frontend's conditional ``since: <prior version>`` fetch then
+ receives a fresh catalogue with updated ``stored`` flags
+ instead of ``{unchanged: true}``. Without this bump, the version
+ is constant for the life of the process and the per-provider
+ ``stored`` flag stays stale on every connected client until the
+ process restarts.
+
+ Local import to avoid an import cycle at module load time.
+ Failures are swallowed (logged at WARNING) so a missing registry
+ never blocks a credential mutation from completing.
+ """
+ try:
+ from services.credential_registry import get_credential_registry
+
+ get_credential_registry().invalidate_version()
+ except Exception as e: # noqa: BLE001 — best-effort signal
+ logger.warning("Failed to bump credential catalogue version: %s", e)
+
async def store_api_key(
self,
provider: str,
@@ -123,6 +146,13 @@ class AuthService:
models=list(models),
)
+ # 3. Bump the catalogue version so the frontend's conditional
+ # fetch (``since: <prior version>``) returns a fresh
+ # catalogue instead of ``{unchanged: true}`` — without
+ # this the per-provider ``stored`` flag stays stale on
+ # every connected client until the process restarts.
+ self._bump_catalogue_version()
+
logger.info(f"Stored and cached API key for {provider}")
return True
@@ -226,6 +256,9 @@ class AuthService:
# 2. Cache evict only after DB succeeds. One pop, not two.
self._api_key_cache.pop(cache_key, None)
+ # 3. Bump the catalogue version — same reason as store.
+ self._bump_catalogue_version()
+
logger.info(f"Removed API key for {provider}")
return True
@@ -307,6 +340,11 @@ class AuthService:
"scopes": scopes,
}
+ # 3. Bump the catalogue version so the frontend's conditional
+ # fetch returns fresh ``stored`` flags after this OAuth
+ # save (login).
+ self._bump_catalogue_version()
+
logger.info(f"Stored OAuth tokens for {provider}")
return True
@@ -497,11 +535,14 @@ class AuthService:
try:
cache_key = f"{customer_id}_{provider}"
- # Remove from memory cache
+ # 1. DB delete first (canonical source).
+ await self.credentials_db.delete_oauth_tokens(provider, customer_id)
+
+ # 2. Cache evict after DB succeeds.
self._oauth_cache.pop(cache_key, None)
- # Remove from encrypted database
- await self.credentials_db.delete_oauth_tokens(provider, customer_id)
+ # 3. Bump the catalogue version — same reason as store.
+ self._bump_catalogue_version()
logger.info(f"Removed OAuth tokens for {provider}")
return True
diff --git a/server/services/credential_registry.py b/server/services/credential_registry.py
index 2349d609..0cd65e8f 100644
--- a/server/services/credential_registry.py
+++ b/server/services/credential_registry.py
@@ -44,6 +44,10 @@ class CredentialRegistry:
self._raw: Optional[Dict[str, Any]] = None
self._resolved_providers: Optional[Dict[str, Dict[str, Any]]] = None
self._version: Optional[str] = None
+ # Bumped on every credential mutation; folded into the version
+ # hash so the conditional fetch returns fresh ``stored`` flags.
+ # See ``get_version()`` + ``invalidate_version()``.
+ self._mutation_seq: int = 0
@classmethod
def get_instance(cls) -> "CredentialRegistry":
@@ -162,21 +166,42 @@ class CredentialRegistry:
return out
def get_version(self) -> str:
- """Content-sha256 of the resolved catalogue (providers + categories).
+ """Content-sha256 of the resolved catalogue (providers + categories +
+ mutation counter).
Used by clients for warm-start cache invalidation: when the hash
changes, the client fetches a fresh catalogue; otherwise it serves
from IndexedDB with zero network traffic.
+
+ The mutation counter is bumped by ``invalidate_version()`` on every
+ credential save / delete / oauth-disconnect — this is what makes
+ the conditional fetch ("`since: <prior version>`") actually return
+ fresh data after a mutation. Without it the hash would only depend
+ on the static catalogue JSON, the version would be constant for
+ the life of the process, and the conditional fetch would always
+ return ``{unchanged: true}`` even after a key was deleted — leaving
+ the per-provider ``stored`` flag stuck at ``true`` on every client.
"""
if self._version is None:
payload = {
"providers": self.get_all_providers(),
"categories": self.get_categories(),
+ "mutation_seq": self._mutation_seq,
}
encoded = json.dumps(payload, sort_keys=True, separators=(",", ":")).encode("utf-8")
self._version = hashlib.sha256(encoded).hexdigest()
return self._version
+ def invalidate_version(self) -> None:
+ """Bump the mutation counter so the next ``get_version()`` returns a
+ new hash. Call this from every credential mutation path (store /
+ remove / oauth-disconnect) so the frontend's conditional fetch
+ actually returns fresh ``stored`` flags. Cheap — just a counter
+ increment + clearing the cached hash.
+ """
+ self._mutation_seq += 1
+ self._version = None
+
def get_catalogue(self) -> Dict[str, Any]:
"""Full payload returned by the `get_credential_catalogue` WebSocket handler."""
return {