Skip to content

AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.

dx(platform): merge master back into dev (#14225)

Nicholas Tindleef2d40e241ad
diff --git a/autogpt_platform/backend/backend/copilot/graphiti/falkordb_driver.py b/autogpt_platform/backend/backend/copilot/graphiti/falkordb_driver.py
index 811d7fb727..6ec86bf8b8 100644
--- a/autogpt_platform/backend/backend/copilot/graphiti/falkordb_driver.py
+++ b/autogpt_platform/backend/backend/copilot/graphiti/falkordb_driver.py
@@ -1,9 +1,11 @@
import asyncio
import logging
import random
+import re
from collections.abc import Awaitable
from typing import Any, cast
+from graphiti_core.driver.driver import GraphDriver
from graphiti_core.driver.falkordb import STOPWORDS
from graphiti_core.driver.falkordb_driver import FalkorDriver
from graphiti_core.helpers import validate_group_ids
@@ -33,6 +35,74 @@ _PENDING_QUEUE_OVERFLOW = "max pending queries exceeded"
_MAX_RETRY_DELAY_SECONDS = 2.0
+# Cypher clauses that mutate the graph. Deliberately CONSERVATIVE: anything
+# matching takes the write path, so a false positive merely preserves today's
+# behaviour, while a false negative would send a real write to RO_QUERY and
+# fail it. The runtime fallback below covers that case anyway.
+_WRITE_CLAUSE_RE = re.compile(
+ r"\b(CREATE|MERGE|SET|DELETE|DETACH|REMOVE|DROP|FOREACH)\b", re.IGNORECASE
+)
+
+# FalkorDB's error when the graph key does not exist yet.
+_EMPTY_KEY_ERROR = "invalid graph operation on empty key"
+
+# FalkorDB's error when a write is attempted through GRAPH.RO_QUERY:
+# "graph.RO_QUERY is to be executed only on read-only queries".
+#
+# Match the full phrase, not a bare "read-only" substring. A spurious match
+# would send a genuine READ down the write path and materialize the graph —
+# the exact bug this routing exists to prevent. Redis's own replica error says
+# "read only" with no hyphen, so it cannot collide with this.
+_RO_VIOLATION = "read-only quer"
+
+
+# Quoted string literals, and // or /* */ comments. Stripped before clause
+# detection so a value like ``{kind: 'CREATE'}`` in an otherwise read-only
+# query is not mistaken for a write clause — that misread would send the query
+# down the graph-materializing path and reintroduce the very bug this fixes.
+_CYPHER_NOISE_RE = re.compile(
+ r"'(?:[^'\\]|\\.)*'" # single-quoted literal
+ r"|\"(?:[^\"\\]|\\.)*\"" # double-quoted literal
+ r"|`(?:[^`]|``)*`" # back-quoted identifier
+ r"|//[^\n]*" # line comment
+ r"|/\*.*?\*/", # block comment
+ re.DOTALL,
+)
+
+
+# Procedure calls that WRITE but contain no standalone clause keyword, so
+# _WRITE_CLAUSE_RE alone misses them: `\bCREATE\b` does not match
+# `createNodeIndex` — there is no word boundary between "create" and "Node".
+# graphiti-core builds its three fulltext indices this way
+# (graphiti_core/graph_queries.py), so every one of them was classified
+# read-only and bounced off RO_QUERY on the first write for every new group.
+_WRITE_PROCEDURE_RE = re.compile(
+ r"\bdb\.idx\.fulltext\.(createNodeIndex|createRelationshipIndex|drop)\b"
+ r"|\bdb\.create\.",
+ re.IGNORECASE,
+)
+
+
+def _strip_cypher_noise(cypher_query_: str) -> str:
+ """Blank out literals/comments so only real clause keywords remain."""
+ return _CYPHER_NOISE_RE.sub(" ", cypher_query_ or "")
+
+
+def _is_read_only_cypher(cypher_query_: str) -> bool:
+ """True when the query contains no mutating clause.
+
+ Read-only queries go to ``GRAPH.RO_QUERY``. This matters far more than
+ performance: ``GRAPH.QUERY`` MATERIALIZES THE GRAPH even for a pure MATCH,
+ so routing reads through it silently creates an empty, permanently
+ resident graph for every user merely looked at. That is what filled
+ FalkorDB to its maxmemory ceiling twice (2026-08-16 and again 2026-08-23,
+ the latter in a single weekly community-rebuild sweep: 91 -> 19,033
+ graphs, 100% of sampled ones empty).
+ """
+ text = _strip_cypher_noise(cypher_query_)
+ return not (_WRITE_CLAUSE_RE.search(text) or _WRITE_PROCEDURE_RE.search(text))
+
+
def _is_pending_queue_overflow(exc: Exception) -> bool:
return _PENDING_QUEUE_OVERFLOW in str(exc).lower()
@@ -94,6 +164,31 @@ class AutoGPTFalkorDriver(FalkorDriver):
"""
await super().build_indices_and_constraints()
+ def clone(self, database: str) -> "GraphDriver":
+ """Clone onto the SUBCLASS, never a plain upstream ``FalkorDriver``.
+
+ Upstream's ``clone()`` constructs a bare ``FalkorDriver``, which would
+ re-enable the init-time ``build_indices`` task (#14052) *and* route
+ every read back through ``graph.query`` — resurrecting both mass
+ graph-materialization bugs with no test covering it.
+
+ Not exercised today: every AutoGPT call site passes a single group_id.
+ graphiti-core clones only when ``group_id != driver._database`` or when
+ a search spans 2+ groups, so this is one line of insurance against a
+ future multi-group read.
+ """
+ if database == self._database:
+ return self
+ # Upstream also special-cases ``default_group_id`` ('\\_') and maps it to
+ # a 'default_db' database. That branch is unreachable here: both
+ # graphiti.py clone sites call validate_group_id() first, whose
+ # ^[a-zA-Z0-9_-]+$ pattern rejects the backslash, and the group_id=None
+ # path never clones. Noted rather than mirrored — if it ever did become
+ # reachable, this would create a graph literally named '\\_'.
+ return AutoGPTFalkorDriver(
+ falkor_db=self.client, database=database, build_indices=False
+ )
+
async def execute_query(
self, cypher_query_, **kwargs
) -> tuple[list[dict[str, Any]], list[str], None] | None:
@@ -118,12 +213,56 @@ class AutoGPTFalkorDriver(FalkorDriver):
# runtime call upstream ``FalkorDriver.execute_query`` makes.
params = cast(dict[str, object], convert_datetimes_to_strings(dict(kwargs)))
attempts = max(1, graphiti_config.falkordb_query_max_attempts)
+ read_only = _is_read_only_cypher(cypher_query_)
- for attempt in range(attempts):
+ attempt = 0
+ while attempt < attempts:
try:
- result = await cast(Awaitable[Any], graph.query(cypher_query_, params))
- return self._to_records(result)
+ return self._to_records(
+ await self._dispatch(graph, cypher_query_, params, read_only)
+ )
except Exception as e:
+ message = str(e).lower()
+ if read_only and _EMPTY_KEY_ERROR in message:
+ # No graph for this group yet, which simply means no
+ # memories. Return an empty result rather than raising —
+ # and deliberately do NOT retry via ``graph.query``, since
+ # that would materialize the graph and reintroduce the bug
+ # this routing exists to prevent.
+ #
+ # CAVEAT: FalkorDB checks key existence BEFORE
+ # read-only-ness, so a MISCLASSIFIED WRITE against a
+ # missing graph lands here rather than in the RO-violation
+ # branch below, and is silently dropped. The classifier
+ # covers every write in graphiti-core and this repo today
+ # (clause keywords + write procedures), but log the query
+ # so a future novel write clause is traceable rather than
+ # invisible. Debug level because a genuine read against a
+ # group with no memories yet is entirely normal and common.
+ logger.debug(
+ "Read on a group with no graph yet; returning empty. "
+ "Query: %s",
+ cypher_query_,
+ )
+ return [], [], None
+ if read_only and _RO_VIOLATION in message:
+ # The classifier called a write read-only. Degrade to the
+ # write path and log the query so the missing clause or
+ # procedure can be added to _WRITE_CLAUSE_RE /
+ # _WRITE_PROCEDURE_RE.
+ #
+ # `read_only = False` + `continue` retries on the SAME
+ # attempt: the counter is not advanced here, so the write
+ # actually runs. Consuming an attempt instead would, on the
+ # final attempt or with max_attempts=1, skip the write
+ # entirely and fall through to the "unreachable" assertion.
+ logger.warning(
+ "Query classified read-only but rejected by RO_QUERY; "
+ "retrying as a write. Query: %s",
+ cypher_query_,
+ )
+ read_only = False
+ continue
if "already indexed" in str(e):
_UPSTREAM_QUERY_LOGGER.info(f"Index already exists: {e}")
return None
@@ -136,6 +275,7 @@ class AutoGPTFalkorDriver(FalkorDriver):
delay,
)
await asyncio.sleep(delay)
+ attempt += 1
continue
# ``params`` hold user memory content (names, facts) — omit them
# from this Sentry-routed log to avoid leaking PII. The exception
@@ -146,6 +286,18 @@ class AutoGPTFalkorDriver(FalkorDriver):
raise
raise AssertionError("unreachable: loop returns or raises on every path")
+ @staticmethod
+ async def _dispatch(graph, cypher_query_, params, read_only: bool) -> Any:
+ """Issue one attempt on the read-only or writing transport.
+
+ ``GRAPH.RO_QUERY`` cannot materialize a graph; ``GRAPH.QUERY`` does,
+ even for a bare MATCH. Keeping the choice here means every caller goes
+ through one place.
+ """
+ if read_only:
+ return await cast(Awaitable[Any], graph.ro_query(cypher_query_, params))
+ return await cast(Awaitable[Any], graph.query(cypher_query_, params))
+
@staticmethod
def _pending_queue_retry_delay(attempt: int) -> float:
"""Jittered exponential backoff (capped) so retries drain the queue over
diff --git a/autogpt_platform/backend/backend/copilot/graphiti/falkordb_driver_test.py b/autogpt_platform/backend/backend/copilot/graphiti/falkordb_driver_test.py
index 619a39d374..00ec8d1725 100644
--- a/autogpt_platform/backend/backend/copilot/graphiti/falkordb_driver_test.py
+++ b/autogpt_platform/backend/backend/copilot/graphiti/falkordb_driver_test.py
@@ -21,6 +21,13 @@ def _set_query(driver: AutoGPTFalkorDriver, side_effect) -> AsyncMock:
return query
+def _set_ro_query(driver: AutoGPTFalkorDriver, side_effect) -> AsyncMock:
+ """Wire ``graph.ro_query`` (reached via ``_get_graph``) to ``side_effect``."""
+ ro_query = AsyncMock(side_effect=side_effect)
+ driver.client.select_graph.return_value.ro_query = ro_query
+ return ro_query
+
+
def _overflow() -> Exception:
return Exception("Max pending queries exceeded")
@@ -187,7 +194,7 @@ async def test_execute_query_success_returns_upstream_shaped_records(
) -> None:
"""Happy path: no retry, and results are shaped like upstream
(list-of-dicts, header, None)."""
- _set_query(driver, [_FakeResult([("n.count", "count")], [[5]])])
+ _set_ro_query(driver, [_FakeResult([("n.count", "count")], [[5]])])
records, header, meta = await driver.execute_query("MATCH (n) RETURN count(n)")
@@ -202,7 +209,7 @@ async def test_execute_query_retries_pending_queue_overflow_then_succeeds(
) -> None:
"""Two transient overflows are retried; the third attempt succeeds and its
result is returned (memory op recovers instead of being dropped)."""
- query = _set_query(
+ query = _set_ro_query(
driver,
[_overflow(), _overflow(), _FakeResult([("x", "count")], [[1]])],
)
@@ -226,7 +233,7 @@ async def test_execute_query_raises_after_exhausting_retries(
) -> None:
"""A sustained overflow exhausts the budget, then raises AND logs exactly
one terminal error under the upstream logger (so Sentry sees one event)."""
- query = _set_query(driver, _overflow())
+ query = _set_ro_query(driver, _overflow())
# max_attempts=4 (non-default) proves the knob controls the attempt count.
with patch.object(fdb.asyncio, "sleep", new=AsyncMock()) as sleep, patch.object(
@@ -266,7 +273,7 @@ async def test_execute_query_non_overflow_error_fails_fast(
) -> None:
"""A genuine query error (Cypher typo, missing graph, teardown) is not
retried — it raises on the first attempt and logs once."""
- query = _set_query(driver, ValueError("syntax error near RETRN"))
+ query = _set_ro_query(driver, ValueError("syntax error near RETRN"))
with patch.object(fdb.asyncio, "sleep", new=AsyncMock()) as sleep, patch.object(
fdb, "_UPSTREAM_QUERY_LOGGER"
@@ -296,3 +303,183 @@ async def test_execute_query_already_indexed_returns_none_without_retry(
assert query.await_count == 1
sleep.assert_not_awaited()
upstream_logger.error.assert_not_called()
+
+
+# ---------------------------------------------------------------------------
+# Read-only query routing.
+#
+# GRAPH.QUERY materializes the graph even for a pure MATCH, so routing reads
+# through it silently creates an empty, permanently resident graph for every
+# user merely looked at. That filled FalkorDB to maxmemory twice — most
+# recently a single weekly community-rebuild sweep took prod from 91 to 19,033
+# graphs, 100% of sampled ones empty. Reads must use GRAPH.RO_QUERY.
+# ---------------------------------------------------------------------------
+
+
+ "cypher,expected_read_only",
+ [
+ ("MATCH (n) RETURN count(n)", True),
+ ("MATCH (n:Entity) WHERE n.group_id = $g RETURN n.name", True),
+ ("CALL db.idx.fulltext.queryNodes('Entity', $q) YIELD node RETURN node", True),
+ ("CREATE INDEX FOR (n:Entity) ON (n.uuid)", False),
+ ("MERGE (n:Entity {uuid: $u})", False),
+ ("MATCH (n) SET n.x = 1", False),
+ ("MATCH (n) DETACH DELETE n", False),
+ ("MATCH (n) REMOVE n.x", False),
+ ],
+)
+def test_read_only_cypher_classification(cypher, expected_read_only) -> None:
+ assert fdb._is_read_only_cypher(cypher) is expected_read_only
+
+
+async def test_read_only_query_uses_ro_query(driver: AutoGPTFalkorDriver) -> None:
+ """A MATCH must go to ro_query and must never touch the creating path."""
+ ro = _set_ro_query(driver, [_FakeResult([("x", "n")], [[1]])])
+ write = _set_query(driver, [_FakeResult([("x", "n")], [[1]])])
+ await driver.execute_query("MATCH (n) RETURN count(n)")
+ ro.assert_awaited_once()
+ write.assert_not_called()
+
+
+async def test_write_query_uses_query(driver: AutoGPTFalkorDriver) -> None:
+ ro = _set_ro_query(driver, [_FakeResult([], [])])
+ write = _set_query(driver, [_FakeResult([], [])])
+ await driver.execute_query("MERGE (n:Entity {uuid: $u})", u="x")
+ write.assert_awaited_once()
+ ro.assert_not_called()
+
+
+async def test_missing_graph_returns_empty_without_creating(
+ driver: AutoGPTFalkorDriver,
+) -> None:
+ """The regression guard.
+
+ A read against a group with no graph yet must yield an empty result, NOT
+ an error and NOT a fallback to ``graph.query`` — that fallback would
+ materialize the graph, which is the entire bug.
+ """
+ ro = _set_ro_query(driver, Exception("ERR Invalid graph operation on empty key"))
+ write = _set_query(driver, [_FakeResult([], [])])
+ records, header, _ = await driver.execute_query("MATCH (n) RETURN count(n)")
+ assert records == []
+ assert header == []
+ ro.assert_awaited_once()
+ write.assert_not_called()
+
+
+async def test_ro_violation_falls_back_to_write(driver: AutoGPTFalkorDriver) -> None:
+ """If the classifier is wrong, degrade to the write path rather than fail."""
+ ro = _set_ro_query(
+ driver, Exception("graph.RO_QUERY is to be executed only on read-only queries")
+ )
+ write = _set_query(driver, [_FakeResult([("x", "n")], [[1]])])
+ await driver.execute_query("MATCH (n) RETURN count(n)")
+ ro.assert_awaited_once()
+ write.assert_awaited_once()
+
+
+# --- regression guards for the review findings on the read-only routing ----
+
+
+ "cypher",
+ [
+ "MATCH (n {kind: 'CREATE'}) RETURN n",
+ 'MATCH (n) WHERE n.name = "DELETE" RETURN n',
+ "MATCH (n) RETURN n // SET is only mentioned in this comment",
+ "/* MERGE */ MATCH (n) RETURN n",
+ ],
+)
+def test_write_keywords_inside_literals_stay_read_only(cypher) -> None:
+ """A write keyword inside a string literal or comment must not flip the
+ query onto the graph-materializing path."""
+ assert fdb._is_read_only_cypher(cypher) is True
+
+
+async def test_ro_violation_on_final_attempt_still_writes(
+ driver: AutoGPTFalkorDriver,
+) -> None:
+ """The RO fallback must not consume a retry.
+
+ With max_attempts=1 (or on the last attempt) a fallback that burned an
+ attempt would exit the loop having never issued the write, hitting the
+ "unreachable" AssertionError.
+ """
+ ro = _set_ro_query(
+ driver, Exception("graph.RO_QUERY is to be executed only on read-only queries")
+ )
+ write = _set_query(driver, [_FakeResult([("x", "n")], [[1]])])
+ with patch(
+ "backend.copilot.graphiti.config.graphiti_config.falkordb_query_max_attempts",
+ 1,
+ ):
+ records, _, _ = await driver.execute_query("MATCH (n) RETURN count(n)")
+ assert records == [{"n": 1}]
+ ro.assert_awaited_once()
+ write.assert_awaited_once()
+
+
+# --- guards for the fulltext index-creation writes -------------------------
+
+
+ "cypher",
+ [
+ # graphiti-core builds all three fulltext indices this way. `\bCREATE\b`
+ # does NOT match `createNodeIndex`, so these were classified read-only
+ # and bounced off RO_QUERY on every new group's first write.
+ (
+ "CALL db.idx.fulltext.createNodeIndex({label: 'Episodic', stopwords: []},"
+ " 'content', 'source', 'source_description', 'group_id')"
+ ),
+ "CALL db.idx.fulltext.createNodeIndex({label: 'Entity'}, 'name')",
+ "CALL db.idx.fulltext.createNodeIndex({label: 'Community'}, 'name')",
+ "CALL db.idx.fulltext.drop('Entity')",
+ ],
+)
+def test_write_procedures_are_not_read_only(cypher) -> None:
+ assert fdb._is_read_only_cypher(cypher) is False
+
+
+def test_fulltext_query_procedure_stays_read_only() -> None:
+ """The search path must keep using RO_QUERY."""
+ assert (
+ fdb._is_read_only_cypher(
+ "CALL db.idx.fulltext.queryNodes('Entity', $query) YIELD node RETURN node"
+ )
+ is True
+ )
+
+
+def test_clone_returns_subclass_with_indices_disabled() -> None:
+ """Upstream clone() builds a plain FalkorDriver, which would re-enable the
+ init-time index task and route reads back through the creating path."""
+ driver = AutoGPTFalkorDriver(falkor_db=MagicMock())
+ driver._database = "user_a"
+ cloned = driver.clone("user_b")
+ assert isinstance(cloned, AutoGPTFalkorDriver)
+ assert cloned._build_indices_at_init is False
+ assert driver.clone("user_a") is driver
+
+
+async def test_unrelated_readonly_wording_does_not_trigger_write_fallback(
+ driver: AutoGPTFalkorDriver,
+) -> None:
+ """A spurious RO-violation match would send a genuine READ down the write
+ path and materialize the graph. Redis's replica error ("read only", no
+ hyphen) must not be mistaken for FalkorDB's RO_QUERY rejection."""
+ ro = _set_ro_query(
+ driver, Exception("READONLY You can't write against a read only replica.")
+ )
+ write = _set_query(driver, [_FakeResult([("x", "n")], [[1]])])
+ with pytest.raises(Exception, match="read only replica"):
+ await driver.execute_query("MATCH (n) RETURN count(n)")
+ ro.assert_awaited()
+ write.assert_not_called()
diff --git a/autogpt_platform/frontend/src/app/(platform)/PaywallGate/PaywallGate.tsx b/autogpt_platform/frontend/src/app/(platform)/PaywallGate/PaywallGate.tsx
index 43ac443cb7..d96891c87d 100644
--- a/autogpt_platform/frontend/src/app/(platform)/PaywallGate/PaywallGate.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/PaywallGate/PaywallGate.tsx
@@ -33,7 +33,7 @@ export function PaywallGate({ children }: { children: ReactNode }) {
select: (res) => (res.status === 200 ? res.data : null),
// Skip the call entirely when the flag is off — beta cohort never hits
// the paywall, no need to read /credits/subscription on every page load.
- enabled: isPaymentEnabled === true,
+ enabled: isPaymentEnabled === true && isLoggedIn,
},
});
diff --git a/autogpt_platform/frontend/src/app/(platform)/PaywallGate/__tests__/PaywallGate.test.tsx b/autogpt_platform/frontend/src/app/(platform)/PaywallGate/__tests__/PaywallGate.test.tsx
index 0230860ef5..54da99fa5f 100644
--- a/autogpt_platform/frontend/src/app/(platform)/PaywallGate/__tests__/PaywallGate.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/PaywallGate/__tests__/PaywallGate.test.tsx
@@ -27,8 +27,12 @@ let mockSubscriptionResult: {
data: MockSubscription | null | undefined;
isLoading: boolean;
} = { data: null, isLoading: false };
+let subscriptionQueryEnabled: boolean | undefined;
vi.mock("@/app/api/__generated__/endpoints/credits/credits", () => ({
- useGetSubscriptionStatus: () => mockSubscriptionResult,
+ useGetSubscriptionStatus: (options: { query?: { enabled?: boolean } }) => {
+ subscriptionQueryEnabled = options.query?.enabled;
+ return mockSubscriptionResult;
+ },
}));
// Mock environment — default to cloud so the gate logic is exercised; flip to
@@ -54,6 +58,7 @@ describe("PaywallGate", () => {
mockIsLoggedIn = true;
mockIsPaymentEnabled = false;
mockSubscriptionResult = { data: null, isLoading: false };
+ subscriptionQueryEnabled = undefined;
mockIsLocal = false;
});
@@ -92,6 +97,7 @@ describe("PaywallGate", () => {
);
expect(screen.getByText("protected")).toBeDefined();
expect(screen.queryByTestId("paywall-modal")).toBeNull();
+ expect(subscriptionQueryEnabled).toBe(false);
});
it("does not render modal in local dev even when paid cohort + tier is NO_TIER", () => {
diff --git a/autogpt_platform/frontend/src/app/(platform)/library/__tests__/low-credit-banner.test.tsx b/autogpt_platform/frontend/src/app/(platform)/library/__tests__/low-credit-banner.test.tsx
index 3235eabd5b..37be039cd7 100644
--- a/autogpt_platform/frontend/src/app/(platform)/library/__tests__/low-credit-banner.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/library/__tests__/low-credit-banner.test.tsx
@@ -17,6 +17,10 @@ import { Key } from "@/services/storage/local-storage";
import { TopUpPromptProvider } from "@/components/layout/TopUpPrompt/TopUpPromptProvider";
import LibraryPage from "../page";
+vi.mock("@/lib/auth/hooks/useAuth", () => ({
+ useAuth: () => ({ isUserLoading: false, isLoggedIn: true }),
+}));
+
// Billing must be on for the provider to derive `isOutOfCredits`; keep the real
// `Flag` enum so other flags the page reads (e.g. AGENT_BRIEFING) resolve.
vi.mock("@/services/feature-flags/use-get-flag", async (importActual) => {
diff --git a/autogpt_platform/frontend/src/components/layout/TopUpPrompt/TopUpPromptProvider.tsx b/autogpt_platform/frontend/src/components/layout/TopUpPrompt/TopUpPromptProvider.tsx
index 23bc810736..87a79531a1 100644
--- a/autogpt_platform/frontend/src/components/layout/TopUpPrompt/TopUpPromptProvider.tsx
+++ b/autogpt_platform/frontend/src/components/layout/TopUpPrompt/TopUpPromptProvider.tsx
@@ -1,8 +1,9 @@
"use client";
-import { ReactNode, useState } from "react";
+import { ReactNode, useEffect, useState } from "react";
import useCredits from "@/hooks/useCredits";
+import { useAuth } from "@/lib/auth/hooks/useAuth";
import { Flag, useGetFlag } from "@/services/feature-flags/use-get-flag";
import { DailyTopUpAutoOpener } from "./DailyTopUpAutoOpener";
@@ -14,10 +15,13 @@ interface Props {
}
export function TopUpPromptProvider({ children }: Props) {
+ const { user, isLoggedIn } = useAuth();
+ const identityKey = user?.id ?? null;
const isBillingEnabled = useGetFlag(Flag.ENABLE_PLATFORM_PAYMENT);
const { credits, autoTopUpConfig } = useCredits({
- fetchInitialCredits: true,
- fetchInitialAutoTopUpConfig: true,
+ identityKey,
+ fetchInitialCredits: isLoggedIn,
+ fetchInitialAutoTopUpConfig: isLoggedIn,
});
// Backend treats amount === 0 as disabled, so auto-refill only actually
@@ -38,6 +42,10 @@ export function TopUpPromptProvider({ children }: Props) {
const [isOpen, setIsOpen] = useState(false);
+ useEffect(() => {
+ setIsOpen(false);
+ }, [identityKey]);
+
function openTopUp() {
setIsOpen(true);
}
diff --git a/autogpt_platform/frontend/src/components/layout/TopUpPrompt/__tests__/TopUpPromptProvider.test.tsx b/autogpt_platform/frontend/src/components/layout/TopUpPrompt/__tests__/TopUpPromptProvider.test.tsx
index 1080f243d9..c7f8a3dbc3 100644
--- a/autogpt_platform/frontend/src/components/layout/TopUpPrompt/__tests__/TopUpPromptProvider.test.tsx
+++ b/autogpt_platform/frontend/src/components/layout/TopUpPrompt/__tests__/TopUpPromptProvider.test.tsx
@@ -15,10 +15,21 @@ import { Key } from "@/services/storage/local-storage";
import { TopUpPromptProvider } from "@/components/layout/TopUpPrompt/TopUpPromptProvider";
import { LowCreditBanner } from "@/components/layout/TopUpPrompt/LowCreditBanner/LowCreditBanner";
import { useTopUpPrompt } from "@/components/layout/TopUpPrompt/useTopUpPrompt";
+import { useState } from "react";
// Billing must be on for the provider to derive `isOutOfCredits`; keep the real
// `Flag` enum and let each test toggle whether the flag resolves true.
let isBillingEnabled = true;
+let authenticatedUserId: string | null = "user-a";
+
+// Simulate an authenticated user so that fetchInitialCredits and
+// fetchInitialAutoTopUpConfig are enabled (they gate on isLoggedIn).
+vi.mock("@/lib/auth/hooks/useAuth", () => ({
+ useAuth: () => ({
+ user: authenticatedUserId ? { id: authenticatedUserId } : null,
+ isLoggedIn: Boolean(authenticatedUserId),
+ }),
+}));
vi.mock("@/services/feature-flags/use-get-flag", async (importActual) => {
const actual =
@@ -58,22 +69,36 @@ function setupCredits(args: {
};
}
-function renderProvider() {
- return render(
+function providerTree() {
+ return (
<TopUpPromptProvider>
<div>ready</div>
+ <StatefulChild />
<LowCreditBanner />
- </TopUpPromptProvider>,
+ </TopUpPromptProvider>
+ );
+}
+
+function StatefulChild() {
+ const [value, setValue] = useState(0);
+ return (
+ <button onClick={() => setValue(value + 1)}>page state {value}</button>
);
}
+function renderProvider() {
+ return render(providerTree());
+}
+
beforeEach(() => {
localStorage.clear();
+ authenticatedUserId = "user-a";
isBillingEnabled = true;
});
afterEach(() => {
localStorage.clear();
+ vi.restoreAllMocks();
});
describe("TopUpPromptProvider daily auto-opener", () => {
@@ -157,6 +182,57 @@ describe("useTopUpPrompt without a provider", () => {
});
describe("TopUpPromptProvider out-of-credits suppression", () => {
+ test("does not fetch billing data when logged out", async () => {
+ authenticatedUserId = null;
+ let creditsRequested = false;
+ let autoTopUpRequested = false;
+ server.use(
+ getGetV1GetUserCreditsMockHandler(() => {
+ creditsRequested = true;
+ return { credits: 0 };
+ }),
+ getGetV1GetAutoTopUpMockHandler(() => {
+ autoTopUpRequested = true;
+ return { amount: 0, threshold: 0 };
+ }),
+ );
+
+ renderProvider();
+ await new Promise((resolve) => setTimeout(resolve, 0));
+
+ expect(creditsRequested).toBe(false);
+ expect(autoTopUpRequested).toBe(false);
+ });
+
+ test("resets and refetches billing state when the authenticated user changes", async () => {
+ let credits = 0;
+ let creditRequests = 0;
+ server.use(
+ getGetV1GetUserCreditsMockHandler(() => {
+ creditRequests += 1;
+ return { credits };
+ }),
+ getGetV1GetAutoTopUpMockHandler({ amount: 0, threshold: 0 }),
+ );
+
+ const view = renderProvider();
+
+ const banner = await screen.findByRole("alert");
+ expect(banner.textContent).toMatch(/out of automation credits/i);
+ expect(creditRequests).toBe(1);
+ fireEvent.click(screen.getByText("page state 0"));
+
+ credits = 500;
+ authenticatedUserId = "user-b";
+ view.rerender(providerTree());
+
+ await waitFor(() => expect(creditRequests).toBe(2));
+ expect(screen.getByText("page state 1")).toBeDefined();
+ await waitFor(() =>
+ expect(screen.queryByText(/out of automation credits/i)).toBeNull(),
+ );
+ });
+
test("suppresses dialog and banner when auto-refill is enabled", async () => {
const { waitForCreditsFetch } = setupCredits({
credits: 0,
diff --git a/autogpt_platform/frontend/src/hooks/useCredits.ts b/autogpt_platform/frontend/src/hooks/useCredits.ts
index cad6631273..de029901b4 100644
--- a/autogpt_platform/frontend/src/hooks/useCredits.ts
+++ b/autogpt_platform/frontend/src/hooks/useCredits.ts
@@ -3,15 +3,17 @@ import {
RefundRequest,
TransactionHistory,
} from "@/lib/autogpt-server-api/types";
-import { useCallback, useEffect, useMemo, useState } from "react";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useRouter } from "next/navigation";
export default function useCredits({
+ identityKey,
fetchInitialCredits = false,
fetchInitialAutoTopUpConfig = false,
fetchInitialTransactionHistory = false,
fetchInitialRefundRequests = false,
}: {
+ identityKey?: string | null;
fetchInitialCredits?: boolean;
fetchInitialAutoTopUpConfig?: boolean;
fetchInitialTransactionHistory?: boolean;
@@ -35,14 +37,25 @@ export default function useCredits({
amount: number;
threshold: number;
} | null>(null);
+ const identityKeyRef = useRef(identityKey);
+ const [stateIdentityKey, setStateIdentityKey] = useState(identityKey);
+
+ useEffect(() => {
+ identityKeyRef.current = identityKey;
+ setStateIdentityKey(identityKey);
+ setCredits(null);
+ setAutoTopUpConfig(null);
+ }, [identityKey]);
const api = useMemo(() => new AutoGPTServerAPI(), []);
const router = useRouter();
const fetchCredits = useCallback(async () => {
+ const requestIdentityKey = identityKey;
const response = await api.getUserCredit();
+ if (identityKeyRef.current !== requestIdentityKey) return;
setCredits(response.credits ?? null);
- }, [api]);
+ }, [api, identityKey]);
useEffect(() => {
if (!fetchInitialCredits) return;
@@ -50,9 +63,11 @@ export default function useCredits({
}, [fetchCredits, fetchInitialCredits]);
const fetchAutoTopUpConfig = useCallback(async () => {
+ const requestIdentityKey = identityKey;
const response = await api.getAutoTopUpConfig();
+ if (identityKeyRef.current !== requestIdentityKey) return;
setAutoTopUpConfig(response);
- }, [api]);
+ }, [api, identityKey]);
useEffect(() => {
if (!fetchInitialAutoTopUpConfig) return;
@@ -135,11 +150,11 @@ export default function useCredits({
}, []);
return {
- credits,
+ credits: stateIdentityKey === identityKey ? credits : null,
fetchCredits,
requestTopUp,
refundTopUp,
- autoTopUpConfig,
+ autoTopUpConfig: stateIdentityKey === identityKey ? autoTopUpConfig : null,
fetchAutoTopUpConfig,
updateAutoTopUpConfig,
transactionHistory,