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.

feat(platform): add FORCE_ALL_FLAGS to turn every feature flag on locally (#14742)

Abhimanyu Yadav8cdd78abf0fb
diff --git a/autogpt_platform/backend/.env.default b/autogpt_platform/backend/.env.default
index 5ceda6fdab..b313deeb5e 100644
--- a/autogpt_platform/backend/.env.default
+++ b/autogpt_platform/backend/.env.default
@@ -259,6 +259,18 @@ SENTRY_DSN=
# Feature Flags
LAUNCH_DARKLY_SDK_KEY=
+# Local-dev master switch: turn EVERY boolean feature flag on at once, without
+# listing them. Off by default; local dev only, where LaunchDarkly is
+# unconfigured and every flag is otherwise off. A per-flag FORCE_FLAG_<NAME>
+# below still wins, so one flag can be excluded with =false. Non-boolean flags
+# (stripe-product-id-topup, copilot-model-routing, the copilot tier/cost JSON
+# flags) are left to LaunchDarkly. Ignored, with an error log, unless
+# APP_ENV=local -- `dev` and `prod` are real deployments, not a developer's
+# machine. That includes the single-container image, whose entrypoint exports
+# APP_ENV=dev; use the per-flag FORCE_FLAG_<NAME> below there instead. Set the
+# matching NEXT_PUBLIC_FORCE_ALL_FLAGS in frontend/.env for the UI.
+# Left commented: .env.default ships to every install.
+# FORCE_ALL_FLAGS=true
# Content Generation & Media
DID_API_KEY=
diff --git a/autogpt_platform/backend/backend/conftest.py b/autogpt_platform/backend/backend/conftest.py
index 9b3a19bfad..d5d40d64ad 100644
--- a/autogpt_platform/backend/backend/conftest.py
+++ b/autogpt_platform/backend/backend/conftest.py
@@ -28,6 +28,15 @@ async def server():
yield server
[email protected](autouse=True)
+def no_force_all_flags(monkeypatch: pytest.MonkeyPatch):
+ """``load_dotenv()`` above copies ``.env`` into ``os.environ``, so a developer
+ who turned on ``FORCE_ALL_FLAGS`` locally would otherwise fail every
+ flag-off test. Tests that want the switch on set it themselves."""
+ monkeypatch.delenv("FORCE_ALL_FLAGS", raising=False)
+ monkeypatch.delenv("NEXT_PUBLIC_FORCE_ALL_FLAGS", raising=False)
+
+
@pytest.fixture
def test_user_id() -> str:
"""Test user ID fixture."""
diff --git a/autogpt_platform/backend/backend/util/feature_flag.py b/autogpt_platform/backend/backend/util/feature_flag.py
index 7779a59810..64bd348ff1 100644
--- a/autogpt_platform/backend/backend/util/feature_flag.py
+++ b/autogpt_platform/backend/backend/util/feature_flag.py
@@ -14,7 +14,7 @@ from ldclient.config import Config
from typing_extensions import ParamSpec
from backend.util.cache import cached
-from backend.util.settings import Settings
+from backend.util.settings import AppEnvironment, Settings
logger = logging.getLogger(__name__)
@@ -435,7 +435,76 @@ async def _evaluate_flag_value(
return default, False
-def _env_flag_override(flag_key: Flag) -> bool | None:
+_TRUTHY = ("1", "true", "yes", "on")
+
+# Flags whose callers read a string / JSON value through
+# ``get_feature_flag_value`` rather than a bool. The master switch below skips
+# them so it never hands a bare ``True`` to a caller expecting a payload
+# (mirrors the frontend's ``ARRAY_TYPED_FLAGS``). ``get_feature_flag_value``
+# itself never consults the env override; this set only matters on the boolean
+# paths (``evaluate_feature_flag``, ``feature_flag``,
+# ``create_feature_flag_dependency``).
+_NON_BOOLEAN_FLAG_VALUES: frozenset[str] = frozenset(
+ {
+ Flag.STRIPE_PRODUCT_ID_TOPUP.value,
+ Flag.COPILOT_MODEL_ROUTING.value,
+ Flag.COPILOT_TIER_MULTIPLIERS.value,
+ Flag.COPILOT_COST_LIMITS.value,
+ Flag.COPILOT_TIER_WORKSPACE_STORAGE_LIMITS.value,
+ Flag.COPILOT_TIER_STRIPE_PRICES.value,
+ Flag.CARD_REQUIRED_TRIAL_OFFER.value,
+ }
+)
+
+# Log the master switch's state once per process, not once per evaluation.
+_force_all_logged = False
+
+
+def _force_all_flags_enabled() -> bool:
+ """Master local-dev switch to turn every boolean flag on at once.
+
+ Set ``FORCE_ALL_FLAGS=true`` (or the ``NEXT_PUBLIC_FORCE_ALL_FLAGS`` the
+ frontend reads, so one shared var flips both sides) to force every boolean
+ flag on without listing them. A per-flag ``FORCE_FLAG_<NAME>`` still wins,
+ so a single flag can be excluded with ``=false`` while the rest stay on.
+ Defaults off. Intended for local dev, where LaunchDarkly is unconfigured
+ and every flag is otherwise off.
+
+ Ignored (with an error log) unless ``app_env`` is local: one env var must
+ not open every fail-closed gate for every user at once, and ``dev`` is a
+ real, publicly reachable deployment rather than a developer's machine.
+ That also rules out the single-container image, whose entrypoint exports
+ ``APP_ENV=dev``; per-flag ``FORCE_FLAG_<NAME>`` remains the escape hatch
+ there, since those overrides are unaffected by this guard.
+ """
+ global _force_all_logged
+ switched_on = False
+ for name in ("FORCE_ALL_FLAGS", "NEXT_PUBLIC_FORCE_ALL_FLAGS"):
+ raw = os.environ.get(name)
+ if raw is not None and raw.strip().lower() in _TRUTHY:
+ switched_on = True
+ break
+ if not switched_on:
+ return False
+ if settings.config.app_env != AppEnvironment.LOCAL:
+ if not _force_all_logged:
+ logger.error(
+ "FORCE_ALL_FLAGS is set but app_env is "
+ f"{settings.config.app_env.value}, not local; ignoring it. "
+ "The master switch is for local dev only."
+ )
+ _force_all_logged = True
+ return False
+ if not _force_all_logged:
+ logger.warning(
+ "FORCE_ALL_FLAGS is on: every boolean feature flag is forced on "
+ "(per-flag FORCE_FLAG_<NAME>=false still wins)."
+ )
+ _force_all_logged = True
+ return True
+
+
+def _env_flag_override(flag_key: Flag | str) -> bool | None:
"""Return a local override for ``flag_key`` from the environment.
Set ``FORCE_FLAG_<NAME>=true|false`` (``NAME`` = flag value with
@@ -448,14 +517,24 @@ def _env_flag_override(flag_key: Flag) -> bool | None:
frontend (the frontend requires the ``NEXT_PUBLIC_`` prefix to
expose the value to the browser bundle).
+ When no per-flag override is set, the ``FORCE_ALL_FLAGS`` master switch
+ (see :func:`_force_all_flags_enabled`) forces every boolean flag on;
+ non-boolean flags are left to LaunchDarkly.
+
Example: ``FORCE_FLAG_CHAT_MODE_OPTION=true`` forces
``Flag.CHAT_MODE_OPTION`` on regardless of LaunchDarkly.
+
+ Accepts a raw flag key string as well as a :class:`Flag`, so the
+ ``feature_flag`` decorator (which holds a raw key) shares this path.
"""
- suffix = flag_key.value.upper().replace("-", "_")
+ key_value = flag_key.value if isinstance(flag_key, Flag) else flag_key
+ suffix = key_value.upper().replace("-", "_")
for prefix in ("FORCE_FLAG_", "NEXT_PUBLIC_FORCE_FLAG_"):
raw = os.environ.get(prefix + suffix)
if raw is not None:
- return raw.strip().lower() in ("1", "true", "yes", "on")
+ return raw.strip().lower() in _TRUTHY
+ if _force_all_flags_enabled() and key_value not in _NON_BOOLEAN_FLAG_VALUES:
+ return True
return None
@@ -537,7 +616,17 @@ def feature_flag(
if not user_id:
raise ValueError("user_id is required")
- if not get_client().is_initialized():
+ # A local env override (per-flag FORCE_FLAG_*, or the
+ # FORCE_ALL_FLAGS master switch) wins over LaunchDarkly and
+ # applies even when the client is uninitialised — the normal
+ # local-dev state, where the decorator would otherwise 404.
+ override = _env_flag_override(flag_key)
+ if override is not None:
+ logger.debug(
+ f"Feature flag {flag_key} overridden by env: {override}"
+ )
+ is_enabled = override
+ elif not get_client().is_initialized():
logger.warning(
"LaunchDarkly not initialized, "
f"using default {flag_key}={repr(default)}"
@@ -564,6 +653,11 @@ def feature_flag(
raise HTTPException(status_code=404, detail="Feature not available")
return await func(*args, **kwargs)
+ except HTTPException:
+ # A disabled flag is an expected outcome, not an evaluation
+ # error: logging it here would file an ERROR for every request
+ # to a gated-off route. The status is already correct.
+ raise
except Exception as e:
logger.error(f"Error evaluating feature flag {flag_key}: {e}")
raise
@@ -608,6 +702,17 @@ def create_feature_flag_dependency(
# For routes that don't require authentication, use anonymous context
check_user_id = user_id or "anonymous"
+ # A local env override (per-flag FORCE_FLAG_*, or the FORCE_ALL_FLAGS
+ # master switch) wins over LaunchDarkly and applies even when the client
+ # is unconfigured — the normal local-dev state, where this dependency
+ # would otherwise 404.
+ override = _env_flag_override(flag_key)
+ if override is not None:
+ logger.debug(f"Feature flag {flag_key.value} overridden by env: {override}")
+ if not override:
+ raise HTTPException(status_code=404, detail="Feature not available")
+ return
+
if not is_configured():
logger.debug(
f"LaunchDarkly not configured, using default {flag_key.value}={default}"
@@ -630,6 +735,10 @@ def create_feature_flag_dependency(
if not is_enabled:
raise HTTPException(status_code=404, detail="Feature not available")
+ except HTTPException:
+ # A disabled flag is an answer, not a failure: the 404s raised
+ # above must not be rewritten as a 500 by the handler below.
+ raise
except Exception as e:
logger.warning(
f"LaunchDarkly error for flag {flag_key.value}: {e}, using default={default}"
diff --git a/autogpt_platform/backend/backend/util/feature_flag_test.py b/autogpt_platform/backend/backend/util/feature_flag_test.py
index d39ff01cc4..ae38a30759 100644
--- a/autogpt_platform/backend/backend/util/feature_flag_test.py
+++ b/autogpt_platform/backend/backend/util/feature_flag_test.py
@@ -1,6 +1,8 @@
+import ast
import datetime
import logging
import uuid
+from pathlib import Path
import pytest
from fastapi import HTTPException
@@ -8,9 +10,12 @@ from ldclient import Context, LDClient
import backend.util.feature_flag as feature_flag_module
from backend.util.feature_flag import (
+ _NON_BOOLEAN_FLAG_VALUES,
Flag,
_env_flag_override,
_fetch_user_context_data,
+ _force_all_flags_enabled,
+ create_feature_flag_dependency,
evaluate_feature_flag,
feature_flag,
get_client,
@@ -18,6 +23,7 @@ from backend.util.feature_flag import (
mock_flag_variation,
shutdown_launchdarkly,
)
+from backend.util.settings import AppEnvironment
@pytest.fixture
@@ -178,6 +184,356 @@ class TestEnvFlagOverride:
assert _env_flag_override(Flag.CHAT) is True
+def _flags_read_via_get_feature_flag_value() -> set[str]:
+ """Flag values passed to ``get_feature_flag_value`` across the backend.
+
+ Walks the AST of every module that mentions the function and collects
+ the ``Flag.X`` / ``Flag.X.value`` first arguments. Call sites that pass
+ a non-literal (``feature_flag``'s own raw-string key) are skipped —
+ there is no flag identity to check there.
+ """
+ backend_root = Path(feature_flag_module.__file__).parent.parent
+ found: set[str] = set()
+ for path in backend_root.rglob("*.py"):
+ if path.name.endswith("_test.py"):
+ continue
+ source = path.read_text(encoding="utf-8")
+ if "get_feature_flag_value" not in source:
+ continue
+ for node in ast.walk(ast.parse(source)):
+ if not isinstance(node, ast.Call) or not node.args:
+ continue
+ func = node.func
+ name = (
+ func.attr
+ if isinstance(func, ast.Attribute)
+ else getattr(func, "id", None)
+ )
+ if name != "get_feature_flag_value":
+ continue
+ arg = node.args[0]
+ if isinstance(arg, ast.Attribute) and arg.attr == "value":
+ arg = arg.value
+ if not isinstance(arg, ast.Attribute):
+ continue
+ if isinstance(arg.value, ast.Name) and arg.value.id == "Flag":
+ found.add(Flag[arg.attr].value)
+ return found
+
+
+class TestForceAllFlags:
+ def _clear(self, monkeypatch: pytest.MonkeyPatch):
+ for name in (
+ "FORCE_ALL_FLAGS",
+ "NEXT_PUBLIC_FORCE_ALL_FLAGS",
+ "FORCE_FLAG_CHAT",
+ "NEXT_PUBLIC_FORCE_FLAG_CHAT",
+ ):
+ monkeypatch.delenv(name, raising=False)
+
+ def test_off_by_default(self, monkeypatch: pytest.MonkeyPatch):
+ self._clear(monkeypatch)
+ assert _force_all_flags_enabled() is False
+ assert _env_flag_override(Flag.CHAT) is None
+
+ def test_forces_boolean_flag_on(self, monkeypatch: pytest.MonkeyPatch):
+ self._clear(monkeypatch)
+ monkeypatch.setenv("FORCE_ALL_FLAGS", "true")
+ assert _force_all_flags_enabled() is True
+ assert _env_flag_override(Flag.CHAT) is True
+
+ def test_next_public_master_switch(self, monkeypatch: pytest.MonkeyPatch):
+ self._clear(monkeypatch)
+ monkeypatch.setenv("NEXT_PUBLIC_FORCE_ALL_FLAGS", "1")
+ assert _env_flag_override(Flag.CHAT) is True
+
+ def test_skips_non_boolean_flags(self, monkeypatch: pytest.MonkeyPatch):
+ self._clear(monkeypatch)
+ monkeypatch.setenv("FORCE_ALL_FLAGS", "true")
+ assert _env_flag_override(Flag.STRIPE_PRODUCT_ID_TOPUP) is None
+ assert _env_flag_override(Flag.COPILOT_MODEL_ROUTING) is None
+ for value in _NON_BOOLEAN_FLAG_VALUES:
+ assert _env_flag_override(value) is None, value
+
+ def test_non_boolean_set_covers_every_json_valued_flag(self):
+ """Every flag read through ``get_feature_flag_value`` as a payload.
+
+ Cross-checked against the real call sites rather than against the
+ set's own literals: a newly-added JSON-valued flag that someone
+ reads via ``get_feature_flag_value`` but forgets to list in
+ ``_NON_BOOLEAN_FLAG_VALUES`` would be force-all'd to ``True`` and
+ handed to a caller expecting a payload, so this test must fail on
+ that omission rather than restate the set.
+ """
+ read_as_payload = _flags_read_via_get_feature_flag_value()
+ assert read_as_payload, "no call sites found - the scanner is broken"
+ missing = read_as_payload - _NON_BOOLEAN_FLAG_VALUES
+ assert not missing, (
+ f"{sorted(missing)} are read through get_feature_flag_value as a "
+ "payload but are missing from _NON_BOOLEAN_FLAG_VALUES, so "
+ "FORCE_ALL_FLAGS would force them to True"
+ )
+
+ def test_per_flag_false_wins_over_force_all(self, monkeypatch: pytest.MonkeyPatch):
+ self._clear(monkeypatch)
+ monkeypatch.setenv("FORCE_ALL_FLAGS", "true")
+ monkeypatch.setenv("FORCE_FLAG_CHAT", "false")
+ assert _env_flag_override(Flag.CHAT) is False
+
+ def test_accepts_raw_string_key(self, monkeypatch: pytest.MonkeyPatch):
+ self._clear(monkeypatch)
+ monkeypatch.setenv("FORCE_ALL_FLAGS", "true")
+ assert _env_flag_override(Flag.CHAT.value) is True
+
+ def test_falsey_value_does_not_force(self, monkeypatch: pytest.MonkeyPatch):
+ self._clear(monkeypatch)
+ monkeypatch.setenv("FORCE_ALL_FLAGS", "false")
+ assert _force_all_flags_enabled() is False
+ assert _env_flag_override(Flag.CHAT) is None
+
+ def test_ignored_in_production(
+ self, monkeypatch: pytest.MonkeyPatch, mocker, caplog: pytest.LogCaptureFixture
+ ):
+ self._clear(monkeypatch)
+ monkeypatch.setattr(feature_flag_module, "_force_all_logged", False)
+ mocker.patch.object(
+ feature_flag_module.settings.config, "app_env", AppEnvironment.PRODUCTION
+ )
+ monkeypatch.setenv("FORCE_ALL_FLAGS", "true")
+ with caplog.at_level(logging.ERROR, logger="backend.util.feature_flag"):
+ assert _force_all_flags_enabled() is False
+ assert _env_flag_override(Flag.CHAT) is None
+ assert "FORCE_ALL_FLAGS is set but app_env is prod, not local" in caplog.text
+
+ def test_ignored_in_shared_development(
+ self, monkeypatch: pytest.MonkeyPatch, mocker, caplog: pytest.LogCaptureFixture
+ ):
+ """``dev`` is a shared deployment, not a developer's machine.
+
+ The single-container entrypoint exports ``APP_ENV=dev``, so a
+ production-only guard would leave every fail-closed gate open for
+ every user of a publicly reachable dev instance.
+ """
+ self._clear(monkeypatch)
+ monkeypatch.setattr(feature_flag_module, "_force_all_logged", False)
+ mocker.patch.object(
+ feature_flag_module.settings.config, "app_env", AppEnvironment.DEVELOPMENT
+ )
+ monkeypatch.setenv("FORCE_ALL_FLAGS", "true")
+ with caplog.at_level(logging.ERROR, logger="backend.util.feature_flag"):
+ assert _force_all_flags_enabled() is False
+ assert _env_flag_override(Flag.CHAT) is None
+ assert "FORCE_ALL_FLAGS is set but app_env is dev, not local" in caplog.text
+
+ def test_per_flag_override_still_works_in_development(
+ self, monkeypatch: pytest.MonkeyPatch, mocker
+ ):
+ """The per-flag escape hatch is what single-container users keep."""
+ self._clear(monkeypatch)
+ mocker.patch.object(
+ feature_flag_module.settings.config, "app_env", AppEnvironment.DEVELOPMENT
+ )
+ monkeypatch.setenv("FORCE_FLAG_CHAT", "true")
+ assert _env_flag_override(Flag.CHAT) is True
+
+ def test_per_flag_override_still_works_in_production(
+ self, monkeypatch: pytest.MonkeyPatch, mocker
+ ):
+ self._clear(monkeypatch)
+ mocker.patch.object(
+ feature_flag_module.settings.config, "app_env", AppEnvironment.PRODUCTION
+ )
+ monkeypatch.setenv("FORCE_FLAG_CHAT", "true")
+ assert _env_flag_override(Flag.CHAT) is True
+
+ def test_honoured_in_local(self, monkeypatch: pytest.MonkeyPatch, mocker):
+ self._clear(monkeypatch)
+ mocker.patch.object(
+ feature_flag_module.settings.config, "app_env", AppEnvironment.LOCAL
+ )
+ monkeypatch.setenv("FORCE_ALL_FLAGS", "true")
+ assert _env_flag_override(Flag.CHAT) is True
+
+ def test_warns_once_when_honoured(
+ self, monkeypatch: pytest.MonkeyPatch, mocker, caplog: pytest.LogCaptureFixture
+ ):
+ self._clear(monkeypatch)
+ monkeypatch.setattr(feature_flag_module, "_force_all_logged", False)
+ mocker.patch.object(
+ feature_flag_module.settings.config, "app_env", AppEnvironment.LOCAL
+ )
+ monkeypatch.setenv("FORCE_ALL_FLAGS", "true")
+ with caplog.at_level(logging.WARNING, logger="backend.util.feature_flag"):
+ assert _force_all_flags_enabled() is True
+ assert _force_all_flags_enabled() is True
+ warnings = [
+ r for r in caplog.records if "FORCE_ALL_FLAGS is on" in r.getMessage()
+ ]
+ assert len(warnings) == 1
+ assert warnings[0].levelno == logging.WARNING
+
+
+class TestEnvOverrideWiring:
+ """The decorator and the router dependency must honour the env override
+ before their "LaunchDarkly not initialised / not configured" bail-out,
+ which is the normal local-dev state."""
+
+ @pytest.fixture(autouse=True)
+ def clear_env(self, monkeypatch: pytest.MonkeyPatch):
+ for name in (
+ "FORCE_ALL_FLAGS",
+ "NEXT_PUBLIC_FORCE_ALL_FLAGS",
+ "FORCE_FLAG_TEST_FLAG",
+ "NEXT_PUBLIC_FORCE_FLAG_TEST_FLAG",
+ "FORCE_FLAG_CHAT",
+ "NEXT_PUBLIC_FORCE_FLAG_CHAT",
+ ):
+ monkeypatch.delenv(name, raising=False)
+
+ @pytest.mark.asyncio
+ async def test_decorator_force_all_wins_over_uninitialised_client(
+ self, ld_client, monkeypatch: pytest.MonkeyPatch
+ ):
+ ld_client.is_initialized.return_value = False
+ monkeypatch.setenv("FORCE_ALL_FLAGS", "true")
+
+ @feature_flag("test-flag")
+ async def test_function(user_id: str):
+ return "success"
+
+ assert await test_function(user_id="test-user") == "success"
+ ld_client.variation.assert_not_called()
+
+ @pytest.mark.asyncio
+ async def test_decorator_per_flag_false_wins_over_launchdarkly(
+ self, ld_client, monkeypatch: pytest.MonkeyPatch
+ ):
+ ld_client.variation.return_value = True
+ monkeypatch.setenv("FORCE_FLAG_TEST_FLAG", "false")
+
+ @feature_flag("test-flag")
+ async def test_function(user_id: str):
+ return "success"
+
+ with pytest.raises(HTTPException) as exc_info:
+ await test_function(user_id="test-user")
+ assert exc_info.value.status_code == 404
+ ld_client.variation.assert_not_called()
+
+ @pytest.mark.asyncio
+ async def test_dependency_force_all_wins_over_unconfigured_sdk(
+ self, mocker, monkeypatch: pytest.MonkeyPatch
+ ):
+ mocker.patch("backend.util.feature_flag.is_configured", return_value=False)
+ monkeypatch.setenv("FORCE_ALL_FLAGS", "true")
+
+ check_feature_flag = create_feature_flag_dependency(Flag.CHAT)
+ assert await check_feature_flag(user_id=None) is None
+
+ @pytest.mark.asyncio
+ async def test_dependency_per_flag_false_returns_404(
+ self, mocker, monkeypatch: pytest.MonkeyPatch
+ ):
+ mocker.patch("backend.util.feature_flag.is_configured", return_value=False)
+ monkeypatch.setenv("FORCE_ALL_FLAGS", "true")
+ monkeypatch.setenv("FORCE_FLAG_CHAT", "false")
+
+ # default=True so the 404 can only come from the override, not the
+ # unconfigured-SDK fallback.
+ check_feature_flag = create_feature_flag_dependency(Flag.CHAT, default=True)
+ with pytest.raises(HTTPException) as exc_info:
+ await check_feature_flag(user_id=None)
+ assert exc_info.value.status_code == 404
+
+ @pytest.mark.asyncio
+ async def test_decorator_disabled_flag_is_not_logged_as_an_error(
+ self, ld_client, caplog: pytest.LogCaptureFixture
+ ):
+ """A gated-off route is an expected outcome, not an evaluation error.
+
+ The 404 is raised inside the decorator's try block, so without an
+ explicit passthrough every request to a disabled route files an
+ ERROR and buries real flag-evaluation failures.
+ """
+ ld_client.variation.return_value = False
+
+ @feature_flag("test-flag")
+ async def test_function(user_id: str):
+ return "success"
+
+ with caplog.at_level(logging.ERROR, logger="backend.util.feature_flag"):
+ with pytest.raises(HTTPException) as exc_info:
+ await test_function(user_id="test-user")
+ assert exc_info.value.status_code == 404
+ assert "Error evaluating feature flag" not in caplog.text
+
+ @pytest.mark.asyncio
+ async def test_decorator_still_logs_real_evaluation_errors(
+ self, ld_client, caplog: pytest.LogCaptureFixture
+ ):
+ """The passthrough must not silence genuine failures."""
+ ld_client.is_initialized.side_effect = RuntimeError("LD exploded")
+
+ @feature_flag("test-flag")
+ async def test_function(user_id: str):
+ return "success"
+
+ with caplog.at_level(logging.ERROR, logger="backend.util.feature_flag"):
+ with pytest.raises(RuntimeError):
+ await test_function(user_id="test-user")
+ assert "Error evaluating feature flag" in caplog.text
+
+ @pytest.mark.asyncio
+ async def test_dependency_disabled_flag_returns_404_not_500(
+ self, ld_client, mocker
+ ):
+ """A disabled flag is an answer, not a LaunchDarkly failure.
+
+ The 404 is raised inside the try block that catches LaunchDarkly
+ errors, so without an explicit re-raise the generic handler turns
+ every gated-off route into a 500.
+ """
+ mocker.patch("backend.util.feature_flag.is_configured", return_value=True)
+ ld_client.is_initialized.return_value = True
+ ld_client.variation.return_value = False
+
+ check_feature_flag = create_feature_flag_dependency(Flag.CHAT)
+ with pytest.raises(HTTPException) as exc_info:
+ await check_feature_flag(user_id="test-user")
+ assert exc_info.value.status_code == 404
+ assert exc_info.value.detail == "Feature not available"
+
+ @pytest.mark.asyncio
+ async def test_dependency_uninitialised_client_returns_404_not_500(
+ self, ld_client, mocker
+ ):
+ """Same for the 404 raised on the uninitialised-client branch."""
+ mocker.patch("backend.util.feature_flag.is_configured", return_value=True)
+ ld_client.is_initialized.return_value = False
+
+ check_feature_flag = create_feature_flag_dependency(Flag.CHAT)
+ with pytest.raises(HTTPException) as exc_info:
+ await check_feature_flag(user_id="test-user")
+ assert exc_info.value.status_code == 404
+
+ @pytest.mark.asyncio
+ async def test_dependency_launchdarkly_error_still_returns_500(
+ self, ld_client, mocker
+ ):
+ """The re-raise must not swallow genuine LaunchDarkly failures."""
+ mocker.patch("backend.util.feature_flag.is_configured", return_value=True)
+ ld_client.is_initialized.return_value = True
+ mocker.patch(
+ "backend.util.feature_flag.is_feature_enabled",
+ new=mocker.AsyncMock(side_effect=RuntimeError("LD exploded")),
+ )
+
+ check_feature_flag = create_feature_flag_dependency(Flag.CHAT)
+ with pytest.raises(HTTPException) as exc_info:
+ await check_feature_flag(user_id="test-user")
+ assert exc_info.value.status_code == 500
+
+
class TestUserContext:
@staticmethod
def _stub_flag_fields(mocker, *, created_at, role=None, email="[email protected]"):
diff --git a/autogpt_platform/frontend/.env.default b/autogpt_platform/frontend/.env.default
index 0d7ca01e1a..160df2732e 100644
--- a/autogpt_platform/frontend/.env.default
+++ b/autogpt_platform/frontend/.env.default
@@ -57,6 +57,13 @@ NEXT_PUBLIC_BEHAVE_AS=LOCAL
# Feature flags
NEXT_PUBLIC_LAUNCHDARKLY_ENABLED=false
NEXT_PUBLIC_LAUNCHDARKLY_CLIENT_ID=687ab1372f497809b131e06e
+# Local-dev master switch: turn EVERY boolean feature flag on at once, without
+# listing them. Off by default. A per-flag NEXT_PUBLIC_FORCE_FLAG_<NAME> still
+# wins, so one flag can be excluded with =false; array/JSON flags keep their
+# LaunchDarkly / default values. Pair it with FORCE_ALL_FLAGS in backend/.env
+# so both sides agree, and restart the dev server — NEXT_PUBLIC_* vars are
+# inlined at build time. Left commented: .env.default ships to every install.
+# NEXT_PUBLIC_FORCE_ALL_FLAGS=true
# Debugging
NEXT_PUBLIC_REACT_QUERY_DEVTOOL=true
diff --git a/autogpt_platform/frontend/src/services/feature-flags/__tests__/envFlagOverride.test.ts b/autogpt_platform/frontend/src/services/feature-flags/__tests__/envFlagOverride.test.ts
index df0a7bdbd2..6171cd63a0 100644
--- a/autogpt_platform/frontend/src/services/feature-flags/__tests__/envFlagOverride.test.ts
+++ b/autogpt_platform/frontend/src/services/feature-flags/__tests__/envFlagOverride.test.ts
@@ -120,3 +120,45 @@ describe("readEnvOverride covers every Flag arm", () => {
}
});
});
+
+describe("NEXT_PUBLIC_FORCE_ALL_FLAGS master switch", () => {
+ // `isForceAllFlags` is resolved once at module load, so each case needs a
+ // fresh module graph with NODE_ENV already stubbed.
+ async function loadWith(nodeEnv: string) {
+ vi.resetModules();
+ vi.stubEnv("NODE_ENV", nodeEnv);
+ vi.stubEnv("NEXT_PUBLIC_FORCE_ALL_FLAGS", "true");
+ return import("../use-get-flag");
+ }
+
+ beforeEach(() => {
+ vi.unstubAllEnvs();
+ });
+
+ it("forces a boolean flag on outside a production build", async () => {
+ const { envFlagOverride: override, Flag: F } =
+ await loadWith("development");
+ expect(override(F.CHAT_MODE_OPTION)).toBe(true);
+ });
+
+ it("is inert in a production build, so a stray env var cannot be baked into the client bundle", async () => {
+ const { envFlagOverride: override, Flag: F } = await loadWith("production");
+ expect(override(F.CHAT_MODE_OPTION)).toBeUndefined();
+ });
+
+ it("leaves per-flag overrides working in a production build", async () => {
+ vi.resetModules();
+ vi.stubEnv("NODE_ENV", "production");
+ vi.stubEnv("NEXT_PUBLIC_FORCE_FLAG_CHAT_MODE_OPTION", "true");
+ const { envFlagOverride: override, Flag: F } = await import(
+ "../use-get-flag"
+ );
+ expect(override(F.CHAT_MODE_OPTION)).toBe(true);
+ });
+
+ it("still skips array-typed flags when forced on", async () => {
+ const { envFlagOverride: override, Flag: F } =
+ await loadWith("development");
+ expect(override(F.BETA_BLOCKS)).toBeUndefined();
+ });
+});
diff --git a/autogpt_platform/frontend/src/services/feature-flags/__tests__/with-feature-flag.test.tsx b/autogpt_platform/frontend/src/services/feature-flags/__tests__/with-feature-flag.test.tsx
new file mode 100644
index 0000000000..3ccdbe8c4a
--- /dev/null
+++ b/autogpt_platform/frontend/src/services/feature-flags/__tests__/with-feature-flag.test.tsx
@@ -0,0 +1,78 @@
+import { render, screen, waitFor } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const router = vi.hoisted(() => ({ push: vi.fn() }));
+
+vi.mock("launchdarkly-react-client-sdk", () => ({
+ useFlags: () => ({}),
+}));
+
+vi.mock("next/navigation", () => ({
+ useRouter: () => router,
+}));
+
+vi.mock("@/app/(platform)/marketplace/components/HeroSection/helpers", () => ({
+ DEFAULT_SEARCH_TERMS: [],
+}));
+
+vi.mock("@/services/environment", () => ({
+ environment: { areFeatureFlagsEnabled: () => false },
+}));
+
+const FORCE_ALL = "NEXT_PUBLIC_FORCE_ALL_FLAGS";
+const PER_FLAG = "NEXT_PUBLIC_FORCE_FLAG_GRAPHITI_MEMORY";
+
+function Gated() {
+ return <div>gated content</div>;
+}
+
+// `isForceAllFlags` is read once at module load, so each case sets the env
+// first, drops the module cache, and imports the HOC fresh.
+async function renderGated() {
+ vi.resetModules();
+ const { withFeatureFlag } = await import("../with-feature-flag");
+ const { Flag } = await import("../use-get-flag");
+ const Page = withFeatureFlag(Gated, Flag.GRAPHITI_MEMORY);
+ return render(<Page />);
+}
+
+describe("withFeatureFlag env override", () => {
+ beforeEach(() => {
+ delete process.env[FORCE_ALL];
+ delete process.env[PER_FLAG];
+ router.push.mockClear();
+ });
+
+ afterEach(() => {
+ delete process.env[FORCE_ALL];
+ delete process.env[PER_FLAG];
+ });
+
+ it("renders the wrapped component on first paint when force-all is on", async () => {
+ process.env[FORCE_ALL] = "true";
+
+ const { container } = await renderGated();
+
+ expect(screen.getByText("gated content")).toBeTruthy();
+ expect(container.querySelector(".animate-spin")).toBeNull();
+ expect(router.push).not.toHaveBeenCalled();
+ });
+
+ it("redirects to /404 when a per-flag false overrides force-all", async () => {
+ process.env[FORCE_ALL] = "true";
+ process.env[PER_FLAG] = "false";
+
+ await renderGated();
+
+ await waitFor(() => expect(router.push).toHaveBeenCalledWith("/404"));
+ expect(screen.queryByText("gated content")).toBeNull();
+ });
+
+ it("keeps the spinner while LaunchDarkly has not answered and nothing is forced", async () => {
+ const { container } = await renderGated();
+
+ expect(container.querySelector(".animate-spin")).not.toBeNull();
+ expect(screen.queryByText("gated content")).toBeNull();
+ expect(router.push).not.toHaveBeenCalled();
+ });
+});
diff --git a/autogpt_platform/frontend/src/services/feature-flags/use-get-flag.ts b/autogpt_platform/frontend/src/services/feature-flags/use-get-flag.ts
index f652d1acab..8d865d3cef 100644
--- a/autogpt_platform/frontend/src/services/feature-flags/use-get-flag.ts
+++ b/autogpt_platform/frontend/src/services/feature-flags/use-get-flag.ts
@@ -193,9 +193,16 @@ const ARRAY_TYPED_FLAGS: ReadonlySet<Flag> = new Set([
// ``NEXT_PUBLIC_FORCE_FLAG_<NAME>`` still wins, so one flag can be excluded
// with ``=false`` while the rest stay forced. Array/JSON-typed flags keep
// their LaunchDarkly / default values.
-const isForceAllFlags = ["1", "true", "yes", "on"].includes(
- (process.env.NEXT_PUBLIC_FORCE_ALL_FLAGS ?? "").trim().toLowerCase(),
-);
+//
+// Inert in a production build, mirroring the backend's app_env guard:
+// NEXT_PUBLIC_* vars are inlined at build time, so one stray value in a
+// production env file would otherwise bake every fail-closed gate open into
+// the client bundle. Per-flag overrides are unaffected.
+const isForceAllFlags =
+ process.env.NODE_ENV !== "production" &&
+ ["1", "true", "yes", "on"].includes(
+ (process.env.NEXT_PUBLIC_FORCE_ALL_FLAGS ?? "").trim().toLowerCase(),
+ );
export function envFlagOverride<T extends Flag>(
flag: T,
diff --git a/autogpt_platform/frontend/src/services/feature-flags/with-feature-flag.tsx b/autogpt_platform/frontend/src/services/feature-flags/with-feature-flag.tsx
index 79ed9d92ce..e7ec683333 100644
--- a/autogpt_platform/frontend/src/services/feature-flags/with-feature-flag.tsx
+++ b/autogpt_platform/frontend/src/services/feature-flags/with-feature-flag.tsx
@@ -3,6 +3,7 @@
import { useFlags } from "launchdarkly-react-client-sdk";
import { useRouter } from "next/navigation";
import { useEffect, useState } from "react";
+import { envFlagOverride, Flag } from "./use-get-flag";
export function withFeatureFlag<P extends object>(
WrappedComponent: React.ComponentType<P>,
@@ -11,20 +12,26 @@ export function withFeatureFlag<P extends object>(
return function FeatureFlaggedComponent(props: P) {
const flags = useFlags();
const router = useRouter();
- const [hasFlagLoaded, setHasFlagLoaded] = useState(false);
+
+ // The local env override (per-flag NEXT_PUBLIC_FORCE_FLAG_*, or the
+ // NEXT_PUBLIC_FORCE_ALL_FLAGS master switch) wins over LaunchDarkly, so a
+ // page gated by this HOC respects force-all like the useGetFlag hook does.
+ const override = envFlagOverride(flagKey as Flag);
+ const isEnabled = override !== undefined ? override : flags[flagKey];
+
+ const [hasFlagLoaded, setHasFlagLoaded] = useState(override !== undefined);
useEffect(() => {
- // Only proceed if flags received
- if (flags && flagKey in flags) {
+ if (override !== undefined || (flags && flagKey in flags)) {
setHasFlagLoaded(true);
}
- }, [flags]);
+ }, [flags, override]);
useEffect(() => {
- if (hasFlagLoaded && !flags[flagKey]) {
+ if (hasFlagLoaded && !isEnabled) {
router.push("/404");
}
- }, [hasFlagLoaded, flags, router]);
+ }, [hasFlagLoaded, isEnabled, router]);
// Show loading state until flags loaded
if (!hasFlagLoaded) {
@@ -36,7 +43,7 @@ export function withFeatureFlag<P extends object>(
}
// If flag is loaded but false, return null (will redirect)
- if (!flags[flagKey]) {
+ if (!isEnabled) {
return null;
}