The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
fix(notices): handle missing embedding budget state gracefully
Steven Enamakeld5436d536916
diff --git a/app/src/components/notices/NoticeCenter.tsx b/app/src/components/notices/NoticeCenter.tsxindex d45b142206..bbee5aaa64 100644--- a/app/src/components/notices/NoticeCenter.tsx+++ b/app/src/components/notices/NoticeCenter.tsx@@ -3,18 +3,14 @@** A small, quiet FAB in the **bottom-right** corner with a count badge,* opening a panel of everything currently worth telling them: classified- * runtime errors, the memory-embedding budget, plan usage limits. Sources are+ * runtime errors and plan usage limits. Sources are* merged by {@link useAppNotices}; this file is presentation only.** It replaces the full-width banners that used to be pushed above every route- * (`GlobalUpsellBanner`, `MemoryEmbeddingBudgetBanner`). Those displaced page+ * (`GlobalUpsellBanner`). Those displaced page* content for something the user frequently cannot act on at that moment, and* up to three could stack. Nothing is lost by moving them here: the copy, the- * CTA and the dismissal rules are carried over intact, including the OS-level- * notification for an exhausted memory budget, which fires from- * {@link useEmbeddingBudgetNativeNotice} independently of whether this panel- * is open — the point of that notification is to reach someone who is *not*- * looking at the app.+ * CTA and the dismissal rules are carried over intact.** Privacy: only translated copy and privacy-safe metadata are rendered — never* raw provider responses, tokens, prompts, or PII.@@ -26,7 +22,6 @@ import { cn } from '../../lib/cn';import { useT } from '../../lib/i18n/I18nContext';import { Button } from '../ui';import { type AppNotice, type NoticeSeverity, peakSeverity, useAppNotices } from './useAppNotices';-import { useEmbeddingBudgetNativeNotice } from './useEmbeddingBudgetNativeNotice';/** Accent per severity — the badge fill and the row's leading icon. */const SEVERITY_STYLE: Record<NoticeSeverity, { badge: string; icon: string }> = {@@ -99,10 +94,6 @@ export default function NoticeCenter() {const { t } = useT();const notices = useAppNotices();const [open, setOpen] = useState(false);- // Reaches a user who is not looking at the app; deliberately independent of- // whether this panel is open, or even rendered (the hook runs before the- // empty-list early return below).- useEmbeddingBudgetNativeNotice();const panelRef = useRef<HTMLDivElement | null>(null);// Close on Escape while the panel is open. A fixed overlay with no dismissaldiff --git a/app/src/components/notices/useAppNotices.ts b/app/src/components/notices/useAppNotices.tsindex 3d13c784ee..8fe941ef15 100644--- a/app/src/components/notices/useAppNotices.ts+++ b/app/src/components/notices/useAppNotices.ts@@ -1,13 +1,12 @@/*** Every notice the app raises, as one list.*- * The problem this solves is fragmentation: the same state was surfaced twice- * in two different chromes. "Memory has stopped growing" existed both as a- * classified `UserActionableError` (panel) and as a full-width- * `MemoryEmbeddingBudgetBanner` pushed above every route, and the usage-limit- * upsell had a third. A banner that displaces page content is the loudest- * possible treatment for something the user often cannot act on right now, and- * three of them could stack.+ * The problem this solves is fragmentation: the same state was surfaced in+ * several chromes (a classified `UserActionableError` panel entry, and+ * full-width banners pushed above every route for the usage-limit upsell). A+ * banner that displaces page content is the loudest possible treatment for+ * something the user often cannot act on right now, and several of them could+ * stack.** So the sources are merged here and rendered once, by {@link NoticeCenter}.* Adding a source means adding a block to this hook — not another@@ -21,7 +20,6 @@ import { useCallback, useMemo, useState } from 'react';import { useNavigate } from 'react-router-dom';import { formatResetTime } from '../../features/conversations/utils/format';-import { useEmbeddingBudgetState } from '../../hooks/useEmbeddingBudgetState';import { useUsageState } from '../../hooks/useUsageState';import { useT } from '../../lib/i18n/I18nContext';import { applyOpenRouterFreeModels } from '../../services/api/openrouterFreeModels';@@ -64,24 +62,15 @@ export interface AppNotice {const ACTION_ROUTE: Record<Exclude<UserErrorAction, 'dismiss'>, string> = {open_billing: '/settings/account',open_provider_settings: '/settings/llm',- // #5324: both memory-embedding remediations (local Ollama, BYO key) live on- // this one screen, so a single CTA covers them without the user needing to- // know which one applies.- open_embeddings_settings: '/connections?tab=embeddings',// Opening this screen also restarts the integration health poll, so it is// both the explanation and the retry.open_connections: '/connections?tab=skills',- // openhuman#5820: re-syncing memory's sources happens on the Memory page's- // Documents chip (per-source Sync and Sync all).- open_memory_sync: '/connections?tab=brain&brain=documents',};const ACTION_LABEL_KEY: Record<Exclude<UserErrorAction, 'dismiss'>, string> = {open_billing: 'userErrors.action.openBilling',open_provider_settings: 'userErrors.action.openProviderSettings',- open_embeddings_settings: 'userErrors.action.openEmbeddingsSettings',open_connections: 'userErrors.action.openConnections',- open_memory_sync: 'userErrors.action.openMemorySync',};const SEVERITY_RANK: Record<NoticeSeverity, number> = { error: 0, warning: 1, info: 2 };@@ -118,7 +107,6 @@ export function useAppNotices(): AppNotice[] {const dispatch = useAppDispatch();const navigate = useNavigate();const active = useAppSelector(selectActiveUserErrors);- const { level: budgetLevel, pct: budgetPct } = useEmbeddingBudgetState();const {teamUsage,isLoading: usageLoading,@@ -190,27 +178,6 @@ export function useAppNotices(): AppNotice[] {});}- // ── Memory embedding budget (#5324) ────────────────────────────────- // The id carries the level so an escalation is a *new* notice rather than- // a mutation of a dismissed one.- const budgetId = `memory-embedding-budget:${budgetLevel}`;- if (budgetLevel !== 'none' && !dismissed.has(budgetId)) {- const exhausted = budgetLevel === 'exhausted';- notices.push({- id: budgetId,- // Exhausted is not a warning: memory has already stopped growing.- severity: exhausted ? 'error' : 'warning',- title: exhausted ? t('memoryBudget.exhaustedTitle') : t('memoryBudget.approachingTitle'),- body: exhausted- ? t('memoryBudget.exhaustedMessage')- : t('memoryBudget.approachingMessage').replace('{pct}', String(budgetPct)),- actionLabel: t('memoryBudget.cta'),- onAction: () => navigate(ACTION_ROUTE.open_embeddings_settings),- // Only the early warning can be silenced; the escalations cannot.- ...(budgetLevel === 'warn' ? { onDismiss: () => dismiss(budgetId) } : {}),- });- }-// ── Plan usage limit ───────────────────────────────────────────────if (!usageLoading && teamUsage) {const upsellId = isAtLimit ? 'usage:at-limit' : 'usage:near-limit';@@ -285,8 +252,6 @@ export function useAppNotices(): AppNotice[] {return notices.sort((a, b) => SEVERITY_RANK[a.severity] - SEVERITY_RANK[b.severity]);}, [active,- budgetLevel,- budgetPct,dismiss,dismissed,dispatch,diff --git a/app/src/components/notices/useEmbeddingBudgetNativeNotice.ts b/app/src/components/notices/useEmbeddingBudgetNativeNotice.tsdeleted file mode 100644index c533c7caa7..0000000000--- a/app/src/components/notices/useEmbeddingBudgetNativeNotice.ts+++ /dev/null@@ -1,43 +0,0 @@-/**- * OS-level notification for an exhausted memory-embedding budget (#5324).- *- * Separate from the in-app notice because it serves the opposite case: the- * panel and the FAB only reach a user who is *looking* at the app, and the- * failure this issue is about is memory silently stopping while nobody was.- * Email is the backend's half; this is the client's.- *- * Fires only on `exhausted`, never on the 75%/90% warnings — those are not yet- * a broken state, and an OS notification for them would be noise.- */-import { useEffect } from 'react';--import { useEmbeddingBudgetState } from '../../hooks/useEmbeddingBudgetState';-import { useT } from '../../lib/i18n/I18nContext';-import { showNativeNotification } from '../../lib/nativeNotifications/tauriBridge';--/**- * Module-scoped so the notification fires at most once per app session. The- * budget state re-reads on every usage poll; without this the user would get a- * notification every 60s, which trains them to mute the app.- */-let nativeNotificationSent = false;--/** Test seam — resets the once-per-session latch. */-export function __resetNativeNotificationLatchForTests() {- nativeNotificationSent = false;-}--export function useEmbeddingBudgetNativeNotice(): void {- const { t } = useT();- const { level } = useEmbeddingBudgetState();-- useEffect(() => {- if (level !== 'exhausted' || nativeNotificationSent) return;- nativeNotificationSent = true;- void showNativeNotification({- title: t('memoryBudget.exhaustedTitle'),- body: t('memoryBudget.exhaustedMessage'),- tag: 'memory-embedding-budget-exhausted',- });- }, [level, t]);-}diff --git a/app/src/hooks/__tests__/useEmbeddingBudgetState.test.ts b/app/src/hooks/__tests__/useEmbeddingBudgetState.test.tsdeleted file mode 100644index dc45c31a2c..0000000000--- a/app/src/hooks/__tests__/useEmbeddingBudgetState.test.ts+++ /dev/null@@ -1,344 +0,0 @@-/**- * useEmbeddingBudgetState tests (#5324).- *- * The two things that must never break: the thresholds the issue specifies,- * and the guard that keeps users who fund their own embeddings from ever- * seeing a managed-budget warning. A false alarm here trains users to ignore- * the real one.- */-import { act, renderHook } from '@testing-library/react';-import { beforeEach, describe, expect, it, vi } from 'vitest';--import { requestUsageRefresh } from '../usageRefresh';-import {- EMBEDDING_BUDGET_URGENT_PCT,- EMBEDDING_BUDGET_WARN_PCT,- embeddingBudgetLevel,- isManagedEmbeddingProvider,- useEmbeddingBudgetState,-} from '../useEmbeddingBudgetState';--const mockLoadEmbeddingsSettings = vi.hoisted(() => vi.fn());-const mockUseUsageState = vi.hoisted(() => vi.fn());-const mockUseCoreState = vi.hoisted(() => vi.fn());-const mockGetTeamUsage = vi.hoisted(() => vi.fn());--vi.mock('../../services/api/embeddingsApi', () => ({- loadEmbeddingsSettings: mockLoadEmbeddingsSettings,-}));--vi.mock('../useUsageState', () => ({ useUsageState: mockUseUsageState }));--vi.mock('../../providers/CoreStateProvider', () => ({ useCoreState: mockUseCoreState }));--vi.mock('../../services/api/creditsApi', () => ({- creditsApi: { getTeamUsage: mockGetTeamUsage },-}));--/** Authenticated session with a managed cycle budget half-consumed. */-function defaultMocks() {- mockUseCoreState.mockReturnValue({ snapshot: { auth: { isAuthenticated: true } } });- mockUseUsageState.mockReturnValue({- usagePct: 0.5,- isBudgetExhausted: false,- isLoading: false,- teamUsage: { cycleBudgetUsd: 10, remainingUsd: 5 },- });-}--describe('embeddingBudgetLevel', () => {- it('stays silent below the warning threshold', () => {- expect(embeddingBudgetLevel(0, false)).toBe('none');- expect(embeddingBudgetLevel(EMBEDDING_BUDGET_WARN_PCT - 0.01, false)).toBe('none');- });-- it('warns at exactly 75%', () => {- expect(embeddingBudgetLevel(EMBEDDING_BUDGET_WARN_PCT, false)).toBe('warn');- });-- it('escalates at exactly 90%', () => {- expect(embeddingBudgetLevel(EMBEDDING_BUDGET_URGENT_PCT, false)).toBe('urgent');- expect(embeddingBudgetLevel(EMBEDDING_BUDGET_URGENT_PCT - 0.001, false)).toBe('warn');- });-- it('reports exhausted regardless of the derived percentage', () => {- // The hard `remainingUsd <= 0` verdict is authoritative: a percentage that- // rounds below 100 must not downgrade an actually-spent budget.- expect(embeddingBudgetLevel(0.97, true)).toBe('exhausted');- expect(embeddingBudgetLevel(0, true)).toBe('exhausted');- });-});--describe('isManagedEmbeddingProvider', () => {- it('recognises the managed provider slugs', () => {- expect(isManagedEmbeddingProvider('openhuman')).toBe(true);- expect(isManagedEmbeddingProvider('managed')).toBe(true);- expect(isManagedEmbeddingProvider('cloud')).toBe(true);- });-- it('matches on the slug when a model suffix is present', () => {- expect(isManagedEmbeddingProvider('openhuman:voyage-3')).toBe(true);- expect(isManagedEmbeddingProvider('ollama:nomic-embed-text')).toBe(false);- });-- it('treats user-funded providers as unaffected by the managed budget', () => {- for (const p of ['ollama', 'openai', 'voyage', 'custom:http://localhost:1234']) {- expect(isManagedEmbeddingProvider(p)).toBe(false);- }- });-- it('is conservative about an unknown provider', () => {- // A failed provider read must never manufacture a budget warning.- expect(isManagedEmbeddingProvider(null)).toBe(false);- expect(isManagedEmbeddingProvider(undefined)).toBe(false);- expect(isManagedEmbeddingProvider('')).toBe(false);- });-- it('ignores case and surrounding whitespace', () => {- expect(isManagedEmbeddingProvider(' OpenHuman ')).toBe(true);- });-});--// ── #5324: the provider must be re-read, or the warning outlives its fix ────--describe('useEmbeddingBudgetState provider refresh', () => {- beforeEach(() => {- mockLoadEmbeddingsSettings.mockReset();- mockGetTeamUsage.mockReset();- defaultMocks();- });-- it('re-reads the provider on an interval while embeddings are managed', async () => {- vi.useFakeTimers();- mockLoadEmbeddingsSettings.mockResolvedValue({ provider: 'openhuman' });- const { result, unmount } = renderHook(() => useEmbeddingBudgetState());-- // Flush the initial read inside `act` so `setProvider` commits before the- // assertions — otherwise the managed-gated interval below never arms.- await act(async () => {- await vi.advanceTimersByTimeAsync(0);- });- expect(mockLoadEmbeddingsSettings).toHaveBeenCalledTimes(1);- expect(result.current.isManagedEmbeddings).toBe(true);-- // A user who follows the CTA and switches to local Ollama must stop being- // told their memory is broken, without restarting the app.- mockLoadEmbeddingsSettings.mockResolvedValue({ provider: 'ollama:nomic-embed-text' });- await act(async () => {- await vi.advanceTimersByTimeAsync(60_000);- });- expect(mockLoadEmbeddingsSettings).toHaveBeenCalledTimes(2);- expect(result.current.isManagedEmbeddings).toBe(false);-- // Once off the managed budget the polling stops — no cost for the majority- // of users who fund their own embeddings.- await act(async () => {- await vi.advanceTimersByTimeAsync(180_000);- });- expect(mockLoadEmbeddingsSettings).toHaveBeenCalledTimes(2);-- unmount();- vi.useRealTimers();- });-- it('re-reads the provider when usage refreshes', async () => {- mockLoadEmbeddingsSettings.mockResolvedValue({ provider: 'ollama' });- renderHook(() => useEmbeddingBudgetState());- await vi.waitFor(() => expect(mockLoadEmbeddingsSettings).toHaveBeenCalledTimes(1));-- // The other direction: a user switching ONTO managed embeddings starts- // being warned without waiting for a remount.- requestUsageRefresh();- await vi.waitFor(() => expect(mockLoadEmbeddingsSettings).toHaveBeenCalledTimes(2));- });-});--// ── #5324: session boundaries + the routed-away managed-embeddings gap ──────--describe('useEmbeddingBudgetState session + managed-embeddings gaps', () => {- beforeEach(() => {- mockLoadEmbeddingsSettings.mockReset();- mockGetTeamUsage.mockReset();- defaultMocks();- });-- // CodeRabbit: a managed provider carried over from a previous user must not- // combine with a new session's usage into a false warning.- it('clears a stale managed provider when the session ends', async () => {- mockLoadEmbeddingsSettings.mockResolvedValue({ provider: 'openhuman' });- const { result, rerender } = renderHook(() => useEmbeddingBudgetState());- await vi.waitFor(() => expect(result.current.isManagedEmbeddings).toBe(true));-- // Sign out: no live session, no usage payload.- mockUseCoreState.mockReturnValue({ snapshot: { auth: { isAuthenticated: false } } });- mockUseUsageState.mockReturnValue({- usagePct: 0,- isBudgetExhausted: false,- isLoading: false,- teamUsage: null,- });- rerender();-- await vi.waitFor(() => {- expect(result.current.isManagedEmbeddings).toBe(false);- expect(result.current.level).toBe('none');- });- });-- // Codex: chat + background workloads routed off OpenHuman (so useUsageState- // reports no payload) while embeddings stay on the managed budget. The- // warning must still reach this user via a direct budget read.- it('warns a routed-away user whose embeddings still bill against the managed budget', async () => {- mockUseUsageState.mockReturnValue({- usagePct: 0,- isBudgetExhausted: false,- isLoading: false,- teamUsage: null,- });- mockLoadEmbeddingsSettings.mockResolvedValue({ provider: 'openhuman' });- mockGetTeamUsage.mockResolvedValue({ cycleBudgetUsd: 10, remainingUsd: 1 });-- const { result } = renderHook(() => useEmbeddingBudgetState());-- await vi.waitFor(() => {- expect(mockGetTeamUsage).toHaveBeenCalledTimes(1);- expect(result.current.level).toBe('urgent');- expect(result.current.pct).toBe(90);- });- });-- // A failed direct read must never manufacture a warning.- it('stays silent when the direct budget read fails', async () => {- mockUseUsageState.mockReturnValue({- usagePct: 0,- isBudgetExhausted: false,- isLoading: false,- teamUsage: null,- });- mockLoadEmbeddingsSettings.mockResolvedValue({ provider: 'openhuman' });- mockGetTeamUsage.mockRejectedValue(new Error('usage unavailable'));-- const { result } = renderHook(() => useEmbeddingBudgetState());-- await vi.waitFor(() => expect(mockGetTeamUsage).toHaveBeenCalled());- expect(result.current.level).toBe('none');- expect(result.current.isManagedEmbeddings).toBe(true);- });-- // The common managed user (useUsageState already has the figure) must not- // pay for a second billing round-trip.- it('does not issue a direct budget read when useUsageState already has usage', async () => {- mockLoadEmbeddingsSettings.mockResolvedValue({ provider: 'openhuman' });- const { result } = renderHook(() => useEmbeddingBudgetState());- await vi.waitFor(() => expect(result.current.isManagedEmbeddings).toBe(true));- expect(mockGetTeamUsage).not.toHaveBeenCalled();- expect(result.current.pct).toBe(50);- });-- // A routed-away user on local/BYO embeddings still sees nothing — and we do- // not even issue the direct read for them.- it('never reads the managed budget for a routed-away BYO-embeddings user', async () => {- mockUseUsageState.mockReturnValue({- usagePct: 0,- isBudgetExhausted: false,- isLoading: false,- teamUsage: null,- });- mockLoadEmbeddingsSettings.mockResolvedValue({ provider: 'ollama:nomic-embed-text' });-- const { result } = renderHook(() => useEmbeddingBudgetState());- await vi.waitFor(() => expect(mockLoadEmbeddingsSettings).toHaveBeenCalled());- expect(mockGetTeamUsage).not.toHaveBeenCalled();- expect(result.current.level).toBe('none');- expect(result.current.isManagedEmbeddings).toBe(false);- });-- // CodeRabbit: `teamUsage` is also null while useUsageState's own request is- // still in flight — the fallback must NOT fire then, or a normal managed user- // duplicates the getTeamUsage() call useUsageState is about to make.- it('does not read the managed budget while the primary usage request is loading', async () => {- mockUseUsageState.mockReturnValue({- usagePct: 0,- isBudgetExhausted: false,- isLoading: true, // primary usage request pending, not routed-away- teamUsage: null,- });- mockLoadEmbeddingsSettings.mockResolvedValue({ provider: 'openhuman' });-- const { result } = renderHook(() => useEmbeddingBudgetState());- await vi.waitFor(() => expect(mockLoadEmbeddingsSettings).toHaveBeenCalled());- expect(mockGetTeamUsage).not.toHaveBeenCalled();- expect(result.current.level).toBe('none'); // still loading → silent- });-- // Reviewer M3gA-Mind (#5402): `provider` is the picker's own setting and is- // NOT authoritative for how embeddings are funded. A user who enabled local- // embeddings through Local AI Settings runs fully local, bills nothing — and- // still reads `provider: "cloud"`, because nothing rewrites that field. The- // core now resolves the real ladder and sends `effective_provider`; gating on- // the stale field would put a non-dismissible "memory has stopped growing"- // banner on every screen the moment their CHAT budget crossed 90%.- it('gates on the effective embedder, not the stale provider setting', async () => {- mockUseUsageState.mockReturnValue({- usagePct: 0.95,- isBudgetExhausted: false,- isLoading: false,- teamUsage: { cycleBudgetUsd: 10, remainingUsd: 0.5 },- });- mockLoadEmbeddingsSettings.mockResolvedValue({- provider: 'cloud',- effective_provider: 'ollama',- });-- const { result } = renderHook(() => useEmbeddingBudgetState());- await vi.waitFor(() => expect(mockLoadEmbeddingsSettings).toHaveBeenCalled());- expect(result.current.isManagedEmbeddings).toBe(false);- expect(result.current.level).toBe('none');- });-- // The other direction: `effective_provider` must be able to turn the warning- // ON as well, so it is a correction of the signal and not a mute switch.- it('warns when the effective embedder is the managed cloud one', async () => {- mockUseUsageState.mockReturnValue({- usagePct: 0.95,- isBudgetExhausted: false,- isLoading: false,- teamUsage: { cycleBudgetUsd: 10, remainingUsd: 0.5 },- });- mockLoadEmbeddingsSettings.mockResolvedValue({- provider: 'ollama:nomic-embed-text',- effective_provider: 'cloud',- });-- const { result } = renderHook(() => useEmbeddingBudgetState());- await vi.waitFor(() => expect(result.current.isManagedEmbeddings).toBe(true));- expect(result.current.level).toBe('urgent');- });-- // `unconfigured` (signed in, but the ladder found no usable provider) bills- // nothing, so it must not be treated as managed either.- it('treats an unconfigured effective embedder as unmanaged', async () => {- mockUseUsageState.mockReturnValue({- usagePct: 0.95,- isBudgetExhausted: true,- isLoading: false,- teamUsage: { cycleBudgetUsd: 10, remainingUsd: 0 },- });- mockLoadEmbeddingsSettings.mockResolvedValue({- provider: 'cloud',- effective_provider: 'unconfigured',- });-- const { result } = renderHook(() => useEmbeddingBudgetState());- await vi.waitFor(() => expect(mockLoadEmbeddingsSettings).toHaveBeenCalled());- expect(result.current.isManagedEmbeddings).toBe(false);- expect(result.current.level).toBe('none');- });-- // A core old enough not to send the field must keep working off `provider`.- it('falls back to the provider setting when the core sends no effective_provider', async () => {- mockLoadEmbeddingsSettings.mockResolvedValue({ provider: 'openhuman' });- const { result } = renderHook(() => useEmbeddingBudgetState());- await vi.waitFor(() => expect(result.current.isManagedEmbeddings).toBe(true));- });-});diff --git a/app/src/hooks/useEmbeddingBudgetState.ts b/app/src/hooks/useEmbeddingBudgetState.tsdeleted file mode 100644index 8b0937076a..0000000000--- a/app/src/hooks/useEmbeddingBudgetState.ts+++ /dev/null@@ -1,280 +0,0 @@-/**- * Memory-embedding budget state (#5324).- *- * The failure this exists to prevent: a heavy user's managed embedding budget- * runs out, every embed job fails as `unrecoverable`, and the Memory Tree- * silently stops growing. The only signal was a yellow banner inside a- * settings panel nobody opens, so users experienced it as "the app has been- * broken for a month" without knowing why.- *- * ## Which budget this reads, and why- *- * There is no separate embedding meter. Managed embeddings are billed against- * the *same* managed cycle budget as chat — the cloud embed route returns the- * identical `USER_INSUFFICIENT_CREDITS` / "Insufficient budget" error — so- * `useUsageState().usagePct` is the authoritative consumption figure for both.- * This hook adds the memory-specific *framing* on top: it only fires when the- * user's embeddings actually route through that managed budget, and it steers- * toward the embedding-specific fixes (local Ollama, BYO key) rather than the- * plan upgrade `GlobalUpsellBanner` already offers.- *- * A user on local Ollama or a BYO key is unaffected by the managed budget for- * embeddings, so they must never see this — a false alarm here would teach- * users to ignore the real one.- */-import { useCallback, useEffect, useState } from 'react';--import { useCoreState } from '../providers/CoreStateProvider';-import { creditsApi, type TeamUsage } from '../services/api/creditsApi';-import { loadEmbeddingsSettings } from '../services/api/embeddingsApi';-import { CoreRpcError } from '../services/coreRpcClient';-import { subscribeUsageRefresh } from './usageRefresh';-import { useUsageState } from './useUsageState';--/** Consumption at which the dismissible early warning appears. */-export const EMBEDDING_BUDGET_WARN_PCT = 0.75;-/** Consumption at which the warning becomes non-dismissible. */-export const EMBEDDING_BUDGET_URGENT_PCT = 0.9;--/**- * Provider slugs that bill against the managed cycle budget. Everything else- * (`ollama:*`, `openai`, `voyage`, `custom:*`, `none`, `unconfigured`,- * `unknown`, …) is funded by the user — or by nobody — so the managed budget- * running out does not stop their memory from growing.- */-const MANAGED_PROVIDER_SLUGS = ['openhuman', 'managed', 'cloud'];--/** Grep prefix for this hook's lifecycle diagnostics. */-const LOG = '[embedding-budget]';--/**- * Privacy-safe error label. Never log the raw error: it can carry endpoint- * URLs, request bodies, or backend messages quoting user content. A kind plus- * (for our own typed errors) the stable discriminator is enough to diagnose.- */-function errorKind(err: unknown): string {- if (err instanceof CoreRpcError) return `core_rpc:${err.kind}`;- if (err instanceof Error) return `error:${err.name}`;- return 'unknown';-}--export type EmbeddingBudgetLevel = 'none' | 'warn' | 'urgent' | 'exhausted';--export interface EmbeddingBudgetState {- /** Which banner (if any) the user should see. `none` renders nothing. */- level: EmbeddingBudgetLevel;- /** Whole-percent consumption, for the warning copy. */- pct: number;- /** True while the provider or usage read is still in flight. */- isLoading: boolean;- /** True when embeddings bill against the managed budget. */- isManagedEmbeddings: boolean;-}--/** True when `provider` bills against the managed cycle budget. */-export function isManagedEmbeddingProvider(provider: string | null | undefined): boolean {- if (!provider) return false;- // Providers are stored either bare (`openhuman`) or as `slug:model`- // (`ollama:nomic-embed-text`), so compare on the slug only.- const slug = provider.trim().toLowerCase().split(':')[0];- return MANAGED_PROVIDER_SLUGS.includes(slug);-}--/**- * Pure threshold mapping, exported so the levels can be tested without- * mocking the RPC layer.- *- * `isExhausted` wins over the percentage because the two can disagree: a- * hard `remainingUsd <= 0` verdict is authoritative even if the derived- * percentage rounds to something under 100.- */-export function embeddingBudgetLevel(usagePct: number, isExhausted: boolean): EmbeddingBudgetLevel {- if (isExhausted) return 'exhausted';- if (usagePct >= EMBEDDING_BUDGET_URGENT_PCT) return 'urgent';- if (usagePct >= EMBEDDING_BUDGET_WARN_PCT) return 'warn';- return 'none';-}--/** Derived budget snapshot: percent consumed + hard-exhausted verdict. */-interface DerivedBudget {- pct: number;- exhausted: boolean;-}--/**- * Percent-consumed + exhausted verdict from a raw `TeamUsage`. Byte-identical- * to `useUsageState`'s own derivation so the fallback path (below) can never- * disagree with the primary path on the same underlying budget.- */-function deriveBudget(usage: TeamUsage): DerivedBudget {- const pct =- usage.cycleBudgetUsd > 0.01- ? Math.max(0, Math.min(1, (usage.cycleBudgetUsd - usage.remainingUsd) / usage.cycleBudgetUsd))- : 0;- const exhausted = usage.cycleBudgetUsd > 0.01 && usage.remainingUsd <= 0.01;- return { pct, exhausted };-}--/**- * How often the embeddings provider is re-read while it still bills against- * the managed budget. Matches `useUsageState`'s cache TTL.- */-const PROVIDER_RECHECK_MS = 60_000;--export function useEmbeddingBudgetState(): EmbeddingBudgetState {- const { snapshot } = useCoreState();- const isAuthenticated = snapshot.auth.isAuthenticated;- const { usagePct, isBudgetExhausted, isLoading: usageLoading, teamUsage } = useUsageState();- const [provider, setProvider] = useState<string | null>(null);- const [providerLoading, setProviderLoading] = useState(true);- // Fallback budget snapshot for the routed-away-but-managed-embeddings case.- // `useUsageState` deliberately returns no `teamUsage` when every chat +- // background workload is routed off OpenHuman (#2020 privacy optimisation) —- // but managed embeddings still bill against the managed cycle budget, so we- // read it directly there rather than letting that bypass silence the warning.- const [fallbackUsage, setFallbackUsage] = useState<DerivedBudget | null>(null);- const [reloadCount, setReloadCount] = useState(0);-- const reload = useCallback(() => setReloadCount(n => n + 1), []);-- // Depend on the *presence* of a usage payload, not the object itself — the- // object identity is not part of this hook's contract, and keying an effect- // on it would re-fire the read on every render for any caller whose- // `useUsageState` returns a fresh object.- const hasUsage = teamUsage !== null;-- useEffect(() => {- // Gate the provider/budget reads on a live session, NOT on the presence of- // a usage payload. `teamUsage` is null both when signed out AND when an- // authenticated user has routed chat away while keeping managed embeddings- // — the two must be handled differently, so `hasUsage` cannot be the gate.- //- // Signed out / offline: clear any provider carried over from a previous- // user so the next session cannot combine this user's usage with the prior- // user's managed provider (which would show a false managed-budget warning- // before the fresh read resolves). Then skip the RPCs, which require a- // session anyway.- if (!isAuthenticated) {- console.debug(`${LOG} skip: not authenticated — cleared provider + fallback budget`);- setProvider(null);- setFallbackUsage(null);- setProviderLoading(false);- return;- }- let cancelled = false;- setProviderLoading(true);- console.debug(`${LOG} provider read start (hasUsage=${hasUsage} usageLoading=${usageLoading})`);- void (async () => {- try {- const settings = await loadEmbeddingsSettings();- if (cancelled) return;- // Gate on the *effective* embedder, not the picker setting. The core- // resolves local Ollama from the Local AI "Memory embeddings" toggle or- // the `memory_tree.embedding_endpoint` override, and neither rewrites- // `provider` — so a fully-local user still reads `provider: "cloud"`- // there and would be told their memory stopped growing while it is- // growing fine (reviewer M3gA-Mind, #5402). Fall back to `provider`- // only for a core old enough not to send the field.- const nextProvider = settings.effective_provider ?? settings.provider;- const managed = isManagedEmbeddingProvider(nextProvider);- console.debug(- `${LOG} provider read ok: effective=${nextProvider} ` +- `configured=${settings.provider} managed=${managed}`- );- setProvider(nextProvider);- // Only reach for the direct budget read when it is actually needed:- // embeddings bill against the managed budget AND `useUsageState` has- // SETTLED with no payload (chat routed away). `teamUsage` is also null- // while `useUsageState`'s own request is still in flight, so gate on- // `!usageLoading` too — otherwise a normal managed user whose provider- // read resolves first fires a redundant `getTeamUsage()` that- // `useUsageState` is about to make anyway.- if (managed && !hasUsage && !usageLoading) {- console.debug(`${LOG} fallback budget read start (managed + usage settled empty)`);- try {- const usage = await creditsApi.getTeamUsage();- if (!cancelled) setFallbackUsage(deriveBudget(usage));- console.debug(`${LOG} fallback budget read ok`);- } catch (err) {- // Auth-expired is handled globally by coreRpcClient; any failure- // here just means "no budget data", so stay silent rather than- // guess. Never manufacture a warning from a failed read.- if (err instanceof CoreRpcError && err.kind === 'auth_expired') {- console.debug(`${LOG} fallback budget read skipped: session expired`);- if (!cancelled) setFallbackUsage(null);- } else {- console.warn(`${LOG} fallback budget read failed kind=${errorKind(err)}`);- if (!cancelled) setFallbackUsage(null);- }- }- } else if (!cancelled) {- // Not needed (BYO/local, or `useUsageState` already has the figure).- console.debug(- `${LOG} fallback budget read not needed ` +- `(managed=${managed} hasUsage=${hasUsage} usageLoading=${usageLoading})`- );- setFallbackUsage(null);- }- } catch (err) {- // Conservative on failure: an unknown provider is treated as- // NOT managed, so a transient RPC error can never manufacture a- // budget warning for a user who funds their own embeddings.- console.warn(`${LOG} provider read failed kind=${errorKind(err)} — treating as unmanaged`);- if (!cancelled) {- setProvider(null);- setFallbackUsage(null);- }- } finally {- if (!cancelled) setProviderLoading(false);- }- })();- return () => {- cancelled = true;- };- }, [reloadCount, isAuthenticated, hasUsage, usageLoading]);-- const isManagedEmbeddings = isManagedEmbeddingProvider(provider);-- // Without this the warning outlives its own fix. The banner is mounted for- // the app's lifetime, so a single mount-time read means a user who follows- // the CTA and switches to local Ollama keeps being told their memory is- // broken until they restart the app — which would make the remediation look- // like it did not work.- //- // Only re-polls while embeddings still bill against the managed budget, so- // the majority of users (BYO key, local) cost nothing. The subscription- // below covers the other direction.- useEffect(() => {- if (!isManagedEmbeddings) {- console.debug(`${LOG} polling off (embeddings do not bill the managed budget)`);- return;- }- console.debug(`${LOG} polling on every ${PROVIDER_RECHECK_MS}ms`);- const id = window.setInterval(reload, PROVIDER_RECHECK_MS);- return () => {- console.debug(`${LOG} polling stopped`);- window.clearInterval(id);- };- }, [isManagedEmbeddings, reload]);-- // Any usage refresh (sign-in, plan change, manual refresh) also re-reads the- // provider, so a user who *switches onto* managed embeddings starts being- // warned without waiting for a remount.- useEffect(() => subscribeUsageRefresh(reload), [reload]);- const isLoading = usageLoading || providerLoading;-- // Prefer `useUsageState`'s figure; fall back to the direct read for the- // routed-away managed-embeddings case. When neither is available the session- // never reached the billing API (signed out / offline) — claiming a budget- // state from that is guesswork, so stay silent.- const budget: DerivedBudget | null = teamUsage- ? { pct: usagePct, exhausted: isBudgetExhausted }- : fallbackUsage;-- const level =- isLoading || !isManagedEmbeddings || !budget- ? 'none'- : embeddingBudgetLevel(budget.pct, budget.exhausted);-- return { level, pct: Math.round((budget?.pct ?? 0) * 100), isLoading, isManagedEmbeddings };-}diff --git a/app/src/types/userError.ts b/app/src/types/userError.tsindex 15ee1bf739..3fd3cea0db 100644--- a/app/src/types/userError.ts+++ b/app/src/types/userError.ts@@ -15,20 +15,11 @@/*** Stable discriminator the UI branches on. Extend as new states are added.- *- * `memory_budget_exhausted` (#5324) is deliberately separate from- * `budget_exceeded` even though both originate in the same managed cycle- * budget: the consequence and the fix differ. Chat being gated is immediately- * visible and is fixed by adding credits; memory silently stopping is- * invisible and is fixed by pointing embeddings at local Ollama or a BYO key.- * Collapsing them would send memory users to the billing screen, which does- * not solve their problem.*/export type UserErrorKind =| 'insufficient_credits'| 'budget_exceeded'| 'api_key_missing'- | 'memory_budget_exhausted'/*** The local model runtime a workload depends on is not usable — Ollama is* not running, or the configured model was never pulled (#5354). Mirrors the@@ -44,14 +35,6 @@ export type UserErrorKind =* connections have stopped working.*/| 'integration_degraded'- /**- * The memory-tree store was corrupt and has been quarantined + rebuilt- * empty (openhuman#5820). Mirrors the core-side `STORE_CORRUPT_KIND`- * token. The damaged file is preserved on disk beside the store; the- * rebuilt tree repopulates by re-syncing sources, which is why the action- * deep-links to the Memory page's Documents chip, not a settings screen.- */- | 'memory_store_corrupt'/*** A reply the agent finished could not be shown: neither the core's write* nor the client's append left a row, and re-reading the thread did not@@ -76,11 +59,8 @@ export type UserErrorScope =export type UserErrorAction =| 'open_billing'| 'open_provider_settings'- | 'open_embeddings_settings'/** The connections screen — where integration health is polled and re-read. */| 'open_connections'- /** Memory → Documents — where memory sources are re-synced after a store rebuild. */- | 'open_memory_sync'| 'dismiss';export type UserErrorSeverity = 'warning' | 'error';