Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

fix(notices): handle missing app notices gracefully

Steven Enamakela53c8d21c332
diff --git a/app/src/components/notices/useAppNotices.ts b/app/src/components/notices/useAppNotices.ts
new file mode 100644
index 0000000000..37d855955b
--- /dev/null
+++ b/app/src/components/notices/useAppNotices.ts
@@ -0,0 +1,206 @@
+/**
+ * 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.
+ *
+ * So the sources are merged here and rendered once, by {@link NoticeCenter}.
+ * Adding a source means adding a block to this hook — not another
+ * shell-mounted component.
+ *
+ * Ordering is severity-first (error, then warning, then info) and stable
+ * within a severity, so the most serious notice is what the collapsed FAB
+ * summarises.
+ */
+import { useCallback, useMemo, useState } from 'react';
+import { useNavigate } from 'react-router-dom';
+
+import { useEmbeddingBudgetState } from '../../hooks/useEmbeddingBudgetState';
+import { useUsageState } from '../../hooks/useUsageState';
+import { useT } from '../../lib/i18n/I18nContext';
+import { useAppDispatch, useAppSelector } from '../../store/hooks';
+import { selectActiveUserErrors } from '../../store/userErrorsSelectors';
+import { dismissUserError, resolveUserError } from '../../store/userErrorsSlice';
+import type { UserActionableError, UserErrorAction } from '../../types/userError';
+import { PRICING_URL } from '../../utils/links';
+import { openUrl } from '../../utils/openUrl';
+
+export type NoticeSeverity = 'error' | 'warning' | 'info';
+
+export interface AppNotice {
+ /** Stable across re-renders — also the React key and the dismissal key. */
+ id: string;
+ severity: NoticeSeverity;
+ title: string;
+ body: string;
+ /** Optional footnote (source · time · recurrence). */
+ meta?: string;
+ /** Primary next step. Omitted when there is nothing to click. */
+ actionLabel?: string;
+ onAction?: () => void;
+ /** Omitted when the notice must not be silenced. */
+ onDismiss?: () => void;
+}
+
+/** Deep-link target for each classified-error action. `dismiss` has no route. */
+const ACTION_ROUTE: Record<Exclude<UserErrorAction, 'dismiss'>, string> = {
+ open_billing: '/settings/billing',
+ 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',
+};
+
+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',
+};
+
+const SEVERITY_RANK: Record<NoticeSeverity, number> = { error: 0, warning: 1, info: 2 };
+
+/** Highest severity present, or `null` for an empty list. */
+export function peakSeverity(notices: readonly AppNotice[]): NoticeSeverity | null {
+ return notices.reduce<NoticeSeverity | null>(
+ (peak, notice) =>
+ peak === null || SEVERITY_RANK[notice.severity] < SEVERITY_RANK[peak] ? notice.severity : peak,
+ null
+ );
+}
+
+// Wall-clock read for resolve/dismiss timestamps, at module scope so the
+// component body never calls an impure function during render
+// (react-hooks/purity). Only reached from event handlers.
+const nowMs = (): number => Date.now();
+
+export function useAppNotices(): AppNotice[] {
+ const { t } = useT();
+ const dispatch = useAppDispatch();
+ const navigate = useNavigate();
+ const active = useAppSelector(selectActiveUserErrors);
+ const { level: budgetLevel, pct: budgetPct } = useEmbeddingBudgetState();
+ const { teamUsage, isLoading: usageLoading, isAtLimit, isNearLimit, isFreeTier } = useUsageState();
+
+ // Per-session, per-key dismissal for the derived (non-store) notices.
+ //
+ // Keyed by notice id, and the embedding-budget id carries its level, so
+ // silencing the 75% warning does NOT also silence the 90% escalation — that
+ // would put the user back in the silent failure this whole surface exists to
+ // prevent. Deliberately not persisted: a warning that survives a restart it
+ // no longer applies to is worse than one shown twice.
+ const [dismissed, setDismissed] = useState<ReadonlySet<string>>(() => new Set());
+ const dismiss = useCallback((id: string) => {
+ setDismissed(prev => new Set(prev).add(id));
+ }, []);
+
+ const runErrorAction = useCallback(
+ (entry: UserActionableError) => {
+ if (entry.action !== 'dismiss') navigate(ACTION_ROUTE[entry.action]);
+ dispatch(resolveUserError({ id: entry.id, at: nowMs() }));
+ },
+ [dispatch, navigate]
+ );
+
+ return useMemo(() => {
+ const notices: AppNotice[] = [];
+
+ // ── Classified runtime errors (#3931) ──────────────────────────────
+ for (const entry of active) {
+ notices.push({
+ id: entry.id,
+ severity: entry.severity,
+ title: t(entry.titleKey),
+ body: t(entry.bodyKey),
+ meta: [
+ t(`userErrors.scope.${entry.scope}`, entry.scope),
+ new Date(entry.lastSeenAt).toLocaleTimeString(),
+ entry.count > 1 ? `×${entry.count}` : null,
+ ]
+ .filter(Boolean)
+ .join(' · '),
+ ...(entry.action !== 'dismiss'
+ ? {
+ actionLabel: t(ACTION_LABEL_KEY[entry.action]),
+ onAction: () => runErrorAction(entry),
+ }
+ : {}),
+ onDismiss: () => dispatch(dismissUserError({ id: entry.id })),
+ });
+ }
+
+ // ── 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';
+ const show = isAtLimit || (isNearLimit && isFreeTier);
+ if (show && !dismissed.has(upsellId)) {
+ notices.push({
+ id: upsellId,
+ severity: isAtLimit ? 'error' : 'warning',
+ title: isAtLimit ? t('upsell.global.limitTitle') : t('upsell.global.nearLimitTitle'),
+ body: isAtLimit
+ ? t('upsell.global.limitMessage')
+ : t('upsell.global.nearLimitMessage').replace(
+ '{pct}',
+ String(Math.round(usagePctOf(teamUsage)))
+ ),
+ actionLabel: t('chat.upgrade'),
+ onAction: () => void openUrl(PRICING_URL),
+ // At the limit the app is already gated, so silencing it would hide
+ // the only explanation of why nothing works.
+ ...(isAtLimit ? {} : { onDismiss: () => dismiss(upsellId) }),
+ });
+ }
+ }
+
+ return notices.sort((a, b) => SEVERITY_RANK[a.severity] - SEVERITY_RANK[b.severity]);
+ }, [
+ active,
+ budgetLevel,
+ budgetPct,
+ dismiss,
+ dismissed,
+ dispatch,
+ isAtLimit,
+ isFreeTier,
+ isNearLimit,
+ navigate,
+ runErrorAction,
+ t,
+ teamUsage,
+ usageLoading,
+ ]);
+}
+
+/** Percentage used, from whichever shape the usage payload carries. */
+function usagePctOf(teamUsage: { usagePct?: number } | null): number {
+ return Math.round((teamUsage?.usagePct ?? 0) * 100);
+}