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): PostHog answers feature flags by default, and the browser asks the backend for them (#15583)
Reinier van der Leer9305d8d38e59
diff --git a/autogpt_platform/backend/.env.default b/autogpt_platform/backend/.env.defaultindex 4eacd7b4d4..578cbbb6db 100644--- a/autogpt_platform/backend/.env.default+++ b/autogpt_platform/backend/.env.default@@ -293,15 +293,16 @@ SENTRY_DSN=# Feature FlagsLAUNCH_DARKLY_SDK_KEY=-# Which vendor answers a flag read: launchdarkly (default), posthog, or dual+# Which vendor answers a flag read: posthog (default), launchdarkly, or dual# (evaluate both, always serve LaunchDarkly here, log every disagreement).-FEATURE_FLAG_BACKEND=launchdarkly+# Without POSTHOG_API_KEY every flag reads as its code default.+FEATURE_FLAG_BACKEND=posthog# 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>+# listing them. Off by default; local dev only, where no flag vendor is+# configured and every flag is otherwise its default. 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+# flags) are left to the flag vendor. 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 thediff --git a/autogpt_platform/backend/backend/api/features/feature_flags/routes_test.py b/autogpt_platform/backend/backend/api/features/feature_flags/routes_test.pyindex ca583e3ace..ce80adbe8f 100644--- a/autogpt_platform/backend/backend/api/features/feature_flags/routes_test.py+++ b/autogpt_platform/backend/backend/api/features/feature_flags/routes_test.py@@ -262,6 +262,19 @@ async def test_with_no_vendor_configured_every_flag_is_the_frontends_default(mocassert body["configured"] is False+async def test_posthog_with_no_key_leaves_every_flag_to_the_frontend(+ mocker, monkeypatch: pytest.MonkeyPatch+):+ mocker.patch.object(+ ff.settings.config, "feature_flag_backend", FeatureFlagBackend.POSTHOG+ )+ mocker.patch.object(ph.settings.secrets, "posthog_api_key", "")+ monkeypatch.setattr(ph, "_client", None)+ monkeypatch.setattr(ph, "_init_attempted", False)++ assert await _get_flags(USER_ID) == {"flags": {}, "configured": False}++@pytest.mark.parametrize("user_id,visitor_id,terms",[("u-other", None, SEARCH_TERMS), (None, VISITOR, VISITOR_TERMS)],diff --git a/autogpt_platform/backend/backend/data/subscription_trial_config_test.py b/autogpt_platform/backend/backend/data/subscription_trial_config_test.pyindex 7dff7702c9..aaec1b39ae 100644--- a/autogpt_platform/backend/backend/data/subscription_trial_config_test.py+++ b/autogpt_platform/backend/backend/data/subscription_trial_config_test.py@@ -10,6 +10,8 @@ from ldclient.integrations.test_data import TestDatafrom pydantic import ValidationErrorfrom backend.data import subscription_trial_config as trials+from backend.util import feature_flag+from backend.util.settings import FeatureFlagBackend@contextmanager@@ -300,7 +302,13 @@ async def test_the_recommended_rule_fails_closed_through_the_real_evaluator(try:with patch.object(trials, "is_feature_enabled", AsyncMock(return_value=True)- ), patch("backend.util.feature_flag.ldclient.get", return_value=client), patch(+ ), patch.object(+ feature_flag.settings.config,+ "feature_flag_backend",+ FeatureFlagBackend.LAUNCHDARKLY,+ ), patch(+ "backend.util.feature_flag.ldclient.get", return_value=client+ ), patch("backend.util.feature_flag._fetch_user_context_status",AsyncMock(return_value=(Context.builder("user-1").kind("user").build(), True)diff --git a/autogpt_platform/backend/backend/util/feature_flag/__init__.py b/autogpt_platform/backend/backend/util/feature_flag/__init__.pyindex cadb97667d..969b23e223 100644--- a/autogpt_platform/backend/backend/util/feature_flag/__init__.py+++ b/autogpt_platform/backend/backend/util/feature_flag/__init__.py@@ -220,7 +220,7 @@ def initialize_feature_flags() -> None:if backend is not FeatureFlagBackend.POSTHOG:initialize_launchdarkly()if backend is not FeatureFlagBackend.LAUNCHDARKLY:- if not settings.secrets.posthog_secret_key:+ if posthog.is_configured() and not settings.secrets.posthog_secret_key:logger.warning(f"Feature flag backend is {backend.value} without ""POSTHOG_SECRET_KEY: every flag read becomes a remote "@@ -517,20 +517,28 @@ async def _evaluate_flag_value(``evaluated`` is False whenever *default* is standing in for an answer thevendor could not give."""- context = None- if attributes:- # Layered once, so every vendor evaluates the same per-request facts.- user_context, context_resolved = await _fetch_user_context_status(user_id)- context = (_with_request_attributes(user_context, attributes), context_resolved)backend = settings.config.feature_flag_backend- if backend is FeatureFlagBackend.POSTHOG:- result = await _evaluate_posthog(- flag_key, user_id, default, context, exposure=flag_key in EXPERIMENT_FLAGS- )- elif backend is FeatureFlagBackend.DUAL:- result = await _evaluate_dual(flag_key, user_id, default, context)+ if backend is FeatureFlagBackend.POSTHOG and posthog.get_flag_client() is None:+ # As on LaunchDarkly: no client means the default, without a user lookup.+ result = (default, False)else:- result = await _evaluate_launchdarkly(flag_key, user_id, default, context)+ context = None+ if attributes:+ # Layered once, so every vendor evaluates the same per-request facts.+ user_context, resolved = await _fetch_user_context_status(user_id)+ context = (_with_request_attributes(user_context, attributes), resolved)+ if backend is FeatureFlagBackend.POSTHOG:+ result = await _evaluate_posthog(+ flag_key,+ user_id,+ default,+ context,+ exposure=flag_key in EXPERIMENT_FLAGS,+ )+ elif backend is FeatureFlagBackend.DUAL:+ result = await _evaluate_dual(flag_key, user_id, default, context)+ else:+ result = await _evaluate_launchdarkly(flag_key, user_id, default, context)_record_flag_for_sentry(flag_key, *result)return resultdiff --git a/autogpt_platform/backend/backend/util/feature_flag/backends_test.py b/autogpt_platform/backend/backend/util/feature_flag/backends_test.pyindex 6db05b8436..b27af3ea87 100644--- a/autogpt_platform/backend/backend/util/feature_flag/backends_test.py+++ b/autogpt_platform/backend/backend/util/feature_flag/backends_test.py@@ -1,4 +1,4 @@-"""Backend selection: launchdarkly (default), posthog, and the dual diff run."""+"""Backend selection: posthog (default), launchdarkly, and the dual diff run."""import asyncioimport json@@ -65,6 +65,8 @@ _FORCE_PREFIXES = (@pytest.fixturedef ld_client(mocker):+ """LaunchDarkly serving from a ready client; a dual test switches after."""+ use_backend(mocker, FeatureFlagBackend.LAUNCHDARKLY)client = mocker.Mock(spec=LDClient)mocker.patch("backend.util.feature_flag.ldclient.get", return_value=client)client.is_initialized.return_value = True@@ -106,18 +108,62 @@ def stub_posthog(mocker, *, value, payload=None):return client-class TestDefaultBackendIsUnchanged:- """Phase 1 is a no-op until the setting is flipped."""+class TestTheDefaultBackend:+ def test_the_default_is_posthog(self):+ # The field's default, since a developer's .env may set the variable.+ default = Config.model_fields["feature_flag_backend"].default+ assert default is FeatureFlagBackend.POSTHOG- def test_the_default_is_launchdarkly(self):- assert (- ff.settings.config.feature_flag_backend is FeatureFlagBackend.LAUNCHDARKLY- )++class TestPostHogWithoutAKey:+ """The default backend as a self-hosted install and CI run it."""++ @pytest.fixture(autouse=True)+ def no_key(self, mocker, monkeypatch: pytest.MonkeyPatch):+ use_backend(mocker, FeatureFlagBackend.POSTHOG)+ mocker.patch.object(ph.settings.secrets, "posthog_api_key", "")+ mocker.patch.object(ff.settings.secrets, "posthog_secret_key", "")+ monkeypatch.setattr(ph, "_client", None)+ monkeypatch.setattr(ph, "_init_attempted", False)+ monkeypatch.setattr(ph, "_shut_down", False)@pytest.mark.asyncio- async def test_the_default_never_touches_posthog(- self, mocker, ld_client, user_context+ @pytest.mark.parametrize("attributes", [None, {"country": "US"}])+ async def test_a_read_serves_its_default_without_a_user_lookup(+ self, mocker, attributes):+ user_id = str(uuid.uuid4())+ lookup = mocker.patch(+ "backend.util.feature_flag._fetch_user_context_status",+ return_value=(Context.create(user_id), True),+ )++ value = await ff.get_feature_flag_value(+ Flag.HIRE_EXPERTS.value, user_id, True, attributes=attributes+ )++ assert value is True+ lookup.assert_not_called()++ def test_startup_warns_once_and_logs_no_error(self, caplog):+ with caplog.at_level(logging.WARNING):+ ff.initialize_feature_flags()++ assert [(r.levelno, r.getMessage()) for r in caplog.records] == [+ (+ logging.WARNING,+ "PostHog API key not configured; flag reads will not resolve",+ )+ ]+++class TestLaunchDarklyBackendLeavesPostHogAlone:+ @pytest.fixture(autouse=True)+ def launchdarkly(self, mocker):+ use_backend(mocker, FeatureFlagBackend.LAUNCHDARKLY)++ @pytest.mark.asyncio+ async def test_a_read_never_touches_posthog(self, mocker, ld_client, user_context):posthog = mocker.patch.object(ph, "evaluate_flag")ld_client.variation_detail.return_value = served(True)@@ -126,9 +172,7 @@ class TestDefaultBackendIsUnchanged:posthog.assert_not_called()@pytest.mark.asyncio- async def test_the_default_reads_launchdarkly_for_raw_values(- self, ld_client, user_context- ):+ async def test_a_raw_value_is_read_from_launchdarkly(self, ld_client, user_context):ld_client.variation_detail.return_value = served({"daily": 5})assert await ff.get_feature_flag_value("copilot-cost-limits", "system") == {@@ -157,9 +201,9 @@ class TestAnUnknownBackendValue:"""Settings is built at import of every module that reads a flag, so arejected value is a boot crash rather than a misconfigured flag read."""- def test_a_typo_falls_back_to_launchdarkly(self, monkeypatch):- monkeypatch.setenv("FEATURE_FLAG_BACKEND", "posthogg")- assert Config().feature_flag_backend is FeatureFlagBackend.LAUNCHDARKLY+ def test_a_typo_falls_back_to_the_default(self, monkeypatch):+ monkeypatch.setenv("FEATURE_FLAG_BACKEND", "launch-darkly")+ assert Config().feature_flag_backend is FeatureFlagBackend.POSTHOGdef test_the_value_is_case_insensitive(self, monkeypatch):monkeypatch.setenv("FEATURE_FLAG_BACKEND", "PostHog")@@ -663,6 +707,7 @@ class TestLaunchDarklyAnswers:):"""A switched-off flag still answers with its off variation; a flagLaunchDarkly does not have answers nothing, whatever the default."""+ use_backend(mocker, FeatureFlagBackend.LAUNCHDARKLY)td = TestData.data_source()configure(td)ld = _launchdarkly_with(td)diff --git a/autogpt_platform/backend/backend/util/feature_flag/definition_cache_test.py b/autogpt_platform/backend/backend/util/feature_flag/definition_cache_test.pyindex b2c5c93f98..6fe5ce483f 100644--- a/autogpt_platform/backend/backend/util/feature_flag/definition_cache_test.py+++ b/autogpt_platform/backend/backend/util/feature_flag/definition_cache_test.py@@ -400,8 +400,14 @@ class TestClientWiring:assert kwargs["enable_local_evaluation"] is False-class TestDefaultBackendIsUntouched:- """`launchdarkly` is the default, and it reaches none of this."""+class TestLaunchDarklyBackendIsUntouched:+ """`launchdarkly` reaches none of this."""++ @pytest.fixture(autouse=True)+ def launchdarkly(self, mocker):+ mocker.patch.object(+ ff.settings.config, "feature_flag_backend", FeatureFlagBackend.LAUNCHDARKLY+ )@pytest.fixturedef ld_client(self, mocker):@@ -418,13 +424,8 @@ class TestDefaultBackendIsUntouched:return_value=(context, True),)- def test_the_default_flag_backend_is_launchdarkly(self):- assert (- ff.settings.config.feature_flag_backend is FeatureFlagBackend.LAUNCHDARKLY- )-@pytest.mark.asyncio- async def test_the_default_builds_no_definition_cache(+ async def test_a_read_builds_no_definition_cache(self, mocker, ld_client, user_context):build = mocker.patch.object(ph, "get_flag_definition_cache")diff --git a/autogpt_platform/backend/backend/util/feature_flag/feature_flag_test.py b/autogpt_platform/backend/backend/util/feature_flag/feature_flag_test.pyindex 66222233f1..c0c3070b42 100644--- a/autogpt_platform/backend/backend/util/feature_flag/feature_flag_test.py+++ b/autogpt_platform/backend/backend/util/feature_flag/feature_flag_test.py@@ -27,7 +27,17 @@ from backend.util.feature_flag import (mock_flag_variation,shutdown_launchdarkly,)-from backend.util.settings import AppEnvironment+from backend.util.settings import AppEnvironment, FeatureFlagBackend++[email protected](autouse=True)+def launchdarkly_serves(mocker):+ # This file covers the LaunchDarkly path, which is no longer the default.+ mocker.patch.object(+ feature_flag_module.settings.config,+ "feature_flag_backend",+ FeatureFlagBackend.LAUNCHDARKLY,+ )@pytest.fixturediff --git a/autogpt_platform/backend/backend/util/settings.py b/autogpt_platform/backend/backend/util/settings.pyindex 02af64ac36..4b246ede88 100644--- a/autogpt_platform/backend/backend/util/settings.py+++ b/autogpt_platform/backend/backend/util/settings.py@@ -926,10 +926,10 @@ class Config(UpdateTrackingModel["Config"], BaseSettings):)feature_flag_backend: FeatureFlagBackend = Field(- default=FeatureFlagBackend.LAUNCHDARKLY,- description="Which vendor answers feature flag reads: launchdarkly "- "(default), posthog, or dual (evaluate both, serve LaunchDarkly, log "- "every disagreement).",+ default=FeatureFlagBackend.POSTHOG,+ description="Which vendor answers feature flag reads: posthog "+ "(default), launchdarkly, or dual (evaluate both, serve LaunchDarkly, "+ "log every disagreement).",)@field_validator("feature_flag_backend", mode="before")@@ -947,9 +947,9 @@ class Config(UpdateTrackingModel["Config"], BaseSettings):except ValueError:logger.warning(f"Unknown FEATURE_FLAG_BACKEND {v!r}, "- f"falling back to {FeatureFlagBackend.LAUNCHDARKLY.value}"+ f"falling back to {FeatureFlagBackend.POSTHOG.value}")- return FeatureFlagBackend.LAUNCHDARKLY+ return FeatureFlagBackend.POSTHOGposthog_flag_definition_cache: FlagDefinitionCacheBackend = Field(default=FlagDefinitionCacheBackend.REDIS,diff --git a/autogpt_platform/frontend/.env.default b/autogpt_platform/frontend/.env.defaultindex ed5ff22594..a17d62e8d6 100644--- a/autogpt_platform/frontend/.env.default+++ b/autogpt_platform/frontend/.env.default@@ -66,12 +66,12 @@ NEXT_PUBLIC_BEHAVE_AS=LOCAL# Feature flagsNEXT_PUBLIC_LAUNCHDARKLY_ENABLED=falseNEXT_PUBLIC_LAUNCHDARKLY_CLIENT_ID=687ab1372f497809b131e06e-# Which vendor answers a flag read: launchdarkly (default), posthog, or dual-# (read both, report every disagreement, and serve LaunchDarkly when it is-# configured — otherwise PostHog, since LaunchDarkly's answer never arrives-# without its provider), or server (ask our backend, which answers from the-# vendor its FEATURE_FLAG_BACKEND names, as the backend's own reads see it).-NEXT_PUBLIC_FEATURE_FLAG_BACKEND=launchdarkly+# Which vendor answers a flag read: server (default; ask our backend, which+# answers from the vendor its FEATURE_FLAG_BACKEND names, as the backend's own+# reads see it), launchdarkly, posthog, or dual (read both, report every+# disagreement, and serve LaunchDarkly when it is configured — otherwise+# PostHog, since LaunchDarkly's answer never arrives without its provider).+NEXT_PUBLIC_FEATURE_FLAG_BACKEND=server# 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 theirdiff --git a/autogpt_platform/frontend/AGENTS.md b/autogpt_platform/frontend/AGENTS.mdindex 7456c3796b..ae80a12ee9 100644--- a/autogpt_platform/frontend/AGENTS.md+++ b/autogpt_platform/frontend/AGENTS.md@@ -62,7 +62,7 @@ Do NOT skip these steps. If any command reports errors, fix them and re-run unti- **Workflow Builder**: Visual graph editor using @xyflow/react- **UI Components**: shadcn/ui (Radix UI primitives) with Tailwind CSS styling- **Icons**: Hugeicons (stroke-rounded) only, rendered through the `Icon` atom-- **Feature Flags**: LaunchDarkly integration+- **Feature Flags**: read from the backend's `/api/feature-flags` by default, which answers from PostHog- **Error Handling**: ErrorCard for render errors, toast for mutations, Sentry for exceptions- **Testing**: Vitest + React Testing Library + MSW for integration tests (primary), Playwright for E2E, Storybook for visualdiff --git a/autogpt_platform/frontend/CONTRIBUTING.md b/autogpt_platform/frontend/CONTRIBUTING.mdindex 3aa52090fc..c9baeaf75b 100644--- a/autogpt_platform/frontend/CONTRIBUTING.md+++ b/autogpt_platform/frontend/CONTRIBUTING.md@@ -120,7 +120,7 @@ See [Component structure](#-component-structure) and [Styling](#-styling) sectioIf a feature will ship across multiple PRs, guard it with a flag so we can merge iteratively.-- Use [LaunchDarkly](https://www.launchdarkly.com) based flags (see Feature Flags below)+- See Feature Flags below- Avoid long-lived feature branches### 3) Open PR and get reviews ✅@@ -497,7 +497,7 @@ You don't need to wrap components in error boundaries manually unless you need c## 🚩 Feature Flags-- Flags are powered by [LaunchDarkly](https://docs.launchdarkly.com/)+- By default the browser reads its flags from the backend (`GET /api/feature-flags`), which answers from PostHog; see `docs/engineering/feature-flags.md`- Use the helper APIs under `src/services/feature-flags`Check a flag in a client component:@@ -534,7 +534,7 @@ Adding new flags:- `launchdarkly`: LaunchDarkly- `posthog`: PostHog- `dual`: both; create it in LaunchDarkly, then copy it over with `backend/scripts/sync_feature_flags_to_posthog.py`- - `server`: whichever the backend's `FEATURE_FLAG_BACKEND` names, by the same rule+ - `server` (default): whichever the backend's `FEATURE_FLAG_BACKEND` names (`posthog` by default), by the same rule---diff --git a/autogpt_platform/frontend/src/app/(platform)/library/__tests__/main.test.tsx b/autogpt_platform/frontend/src/app/(platform)/library/__tests__/main.test.tsxindex 6f6d7f3794..c58634eb15 100644--- a/autogpt_platform/frontend/src/app/(platform)/library/__tests__/main.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/library/__tests__/main.test.tsx@@ -224,6 +224,9 @@ describe("LibraryPage", () => {render(<LibraryPage />);- expect(await screen.findByText("Running Agent")).toBeDefined();+ // The briefing panel's running list names it too, once executions load.+ expect(+ (await screen.findAllByText("Running Agent")).length,+ ).toBeGreaterThan(0);});});diff --git a/autogpt_platform/frontend/src/mocks/mock-handlers.ts b/autogpt_platform/frontend/src/mocks/mock-handlers.tsindex cf0ba81d7d..5c8c96ca17 100644--- a/autogpt_platform/frontend/src/mocks/mock-handlers.ts+++ b/autogpt_platform/frontend/src/mocks/mock-handlers.ts@@ -16,6 +16,7 @@ import {import { getCreditsMock } from "@/app/api/__generated__/endpoints/credits/credits.msw";import { getDefaultMock } from "@/app/api/__generated__/endpoints/default/default.msw";import { getEmailMock } from "@/app/api/__generated__/endpoints/email/email.msw";+import { getGetFeatureFlagsMockHandler } from "@/app/api/__generated__/endpoints/feature-flags/feature-flags.msw";import { getExecutionsMock } from "@/app/api/__generated__/endpoints/executions/executions.msw";import { getExpertsMock } from "@/app/api/__generated__/endpoints/experts/experts.msw";import { getFilesMock } from "@/app/api/__generated__/endpoints/files/files.msw";@@ -41,6 +42,8 @@ export const mockHandlers = [http.get("/api/proxy/api/credits/pro-activation/current", () =>HttpResponse.json({ detail: "No activation in progress" }, { status: 404 }),),+ // No flag vendor unless a test provides one, so every flag serves its default.+ getGetFeatureFlagsMockHandler({ flags: {}, configured: false }),...getAdminMock(),...getAnalyticsMock(),...getApiKeysMock(),diff --git a/autogpt_platform/frontend/src/services/feature-flags/__tests__/feature-flag-provider.test.tsx b/autogpt_platform/frontend/src/services/feature-flags/__tests__/feature-flag-provider.test.tsxindex 25b8cb974f..247d66083d 100644--- a/autogpt_platform/frontend/src/services/feature-flags/__tests__/feature-flag-provider.test.tsx+++ b/autogpt_platform/frontend/src/services/feature-flags/__tests__/feature-flag-provider.test.tsx@@ -1,6 +1,11 @@import { act, render, screen } from "@testing-library/react";import type { ReactNode } from "react";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++// These read LaunchDarkly; `flag-backend` picks the vendor once, at load.+vi.hoisted(() => {+ process.env.NEXT_PUBLIC_FEATURE_FLAG_BACKEND = "launchdarkly";+});import { FeatureFlagProvider } from "../feature-flag-provider";import { Flag, useFlagStatus } from "../use-get-flag";diff --git a/autogpt_platform/frontend/src/services/feature-flags/__tests__/flag-backends.test.tsx b/autogpt_platform/frontend/src/services/feature-flags/__tests__/flag-backends.test.tsxindex c60f53312e..24e74b5a66 100644--- a/autogpt_platform/frontend/src/services/feature-flags/__tests__/flag-backends.test.tsx+++ b/autogpt_platform/frontend/src/services/feature-flags/__tests__/flag-backends.test.tsx@@ -71,9 +71,21 @@ vi.mock("@/services/environment", () => ({const HIRE_EXPERTS = "hire-experts";-describe("launchdarkly is the default backend", () => {+describe("the default backend", () => {+ it.each([undefined, "", "launch-darkly"])(+ "asks the server when the backend is %j",+ async (backend) => {+ await loadWithBackend(backend);+ const { FLAG_BACKEND } = await import("../flag-backend");++ expect(FLAG_BACKEND).toBe("server");+ },+ );+});++describe("launchdarkly backend", () => {it("reads the LaunchDarkly value and never touches PostHog", async () => {- const { Flag, useGetFlag } = await loadWithBackend(undefined);+ const { Flag, useGetFlag } = await loadWithBackend("launchdarkly");launchDarkly.flags = { [HIRE_EXPERTS]: true };const { result } = renderHook(() => useGetFlag(Flag.HIRE_EXPERTS));@@ -84,7 +96,7 @@ describe("launchdarkly is the default backend", () => {});it("reports a flag LaunchDarkly has not answered for as not ready", async () => {- const { Flag, useFlagStatus } = await loadWithBackend(undefined);+ const { Flag, useFlagStatus } = await loadWithBackend("launchdarkly");launchDarkly.flags = {};const { result } = renderHook(() => useFlagStatus(Flag.HIRE_EXPERTS));@@ -385,7 +397,7 @@ describe("dual backend", () => {describe("Sentry's flag context", () => {it.each([- ["launchdarkly", undefined],+ ["launchdarkly", "launchdarkly"],["posthog", "posthog"],["dual", "dual"],])("records the served boolean in %s mode", async (_, backend) => {@@ -403,7 +415,7 @@ describe("Sentry's flag context", () => {});it("records a flag read by a component that throws in the same render", async () => {- const { Flag, useGetFlag } = await loadWithBackend(undefined);+ const { Flag, useGetFlag } = await loadWithBackend("launchdarkly");vi.spyOn(console, "error").mockImplementation(() => {});launchDarkly.flags = { [HIRE_EXPERTS]: true };let recordedAtCatch: unknown[][] = [];@@ -435,7 +447,7 @@ describe("Sentry's flag context", () => {it("records the default it serves while flags are disabled", async () => {env.launchDarklyEnabled = false;- const { Flag, useGetFlag } = await loadWithBackend(undefined);+ const { Flag, useGetFlag } = await loadWithBackend("launchdarkly");launchDarkly.flags = { [HIRE_EXPERTS]: true };const { result } = renderHook(() => useGetFlag(Flag.HIRE_EXPERTS));@@ -449,7 +461,7 @@ describe("Sentry's flag context", () => {it("records nothing for an env-forced flag", async () => {const { Flag, useFlagStatus, useGetFlag } =- await loadWithBackend(undefined);+ await loadWithBackend("launchdarkly");process.env.NEXT_PUBLIC_FORCE_FLAG_HIRE_EXPERTS = "true";renderHook(() => useFlagStatus(Flag.HIRE_EXPERTS));@@ -459,7 +471,7 @@ describe("Sentry's flag context", () => {});it("records nothing for a JSON-valued flag", async () => {- const { Flag, useGetFlag } = await loadWithBackend(undefined);+ const { Flag, useGetFlag } = await loadWithBackend("launchdarkly");launchDarkly.flags = { "copilot-bot-platforms": { slack: false } };renderHook(() => useGetFlag(Flag.COPILOT_BOT_PLATFORMS));@@ -468,7 +480,7 @@ describe("Sentry's flag context", () => {});it("still serves the flag when recording throws", async () => {- const { Flag, useGetFlag } = await loadWithBackend(undefined);+ const { Flag, useGetFlag } = await loadWithBackend("launchdarkly");sentry.addFeatureFlag.mockImplementation(() => {throw new Error("sentry down");});diff --git a/autogpt_platform/frontend/src/services/feature-flags/__tests__/flag-defaults.test.ts b/autogpt_platform/frontend/src/services/feature-flags/__tests__/flag-defaults.test.tsindex af118a3fe6..bf72ff4c8f 100644--- a/autogpt_platform/frontend/src/services/feature-flags/__tests__/flag-defaults.test.ts+++ b/autogpt_platform/frontend/src/services/feature-flags/__tests__/flag-defaults.test.ts@@ -1,5 +1,10 @@import { renderHook } from "@testing-library/react";import { beforeEach, describe, expect, it, vi } from "vitest";++// These read LaunchDarkly; `flag-backend` picks the vendor once, at load.+vi.hoisted(() => {+ process.env.NEXT_PUBLIC_FEATURE_FLAG_BACKEND = "launchdarkly";+});import { Flag, useGetFlag } from "../use-get-flag";// LD is enabled but has not answered for any key — the exact windowdiff --git a/autogpt_platform/frontend/src/services/feature-flags/__tests__/ld-init-timeout.test.tsx b/autogpt_platform/frontend/src/services/feature-flags/__tests__/ld-init-timeout.test.tsxindex 80c6419716..3ece7394e5 100644--- a/autogpt_platform/frontend/src/services/feature-flags/__tests__/ld-init-timeout.test.tsx+++ b/autogpt_platform/frontend/src/services/feature-flags/__tests__/ld-init-timeout.test.tsx@@ -1,6 +1,11 @@import { render, screen } from "@testing-library/react";import type { ReactNode } from "react";import { describe, expect, it, vi } from "vitest";++// These read LaunchDarkly; `flag-backend` picks the vendor once, at load.+vi.hoisted(() => {+ process.env.NEXT_PUBLIC_FEATURE_FLAG_BACKEND = "launchdarkly";+});import { LD_INIT_TIMEOUT_SECONDS } from "../constants";import { FeatureFlagProvider } from "../feature-flag-provider";import { Flag, useGetFlag } from "../use-get-flag";diff --git a/autogpt_platform/frontend/src/services/feature-flags/__tests__/pw-flag-overrides.test.tsx b/autogpt_platform/frontend/src/services/feature-flags/__tests__/pw-flag-overrides.test.tsxindex 7c23286bd4..c519617188 100644--- a/autogpt_platform/frontend/src/services/feature-flags/__tests__/pw-flag-overrides.test.tsx+++ b/autogpt_platform/frontend/src/services/feature-flags/__tests__/pw-flag-overrides.test.tsx@@ -1,6 +1,11 @@import { renderHook } from "@testing-library/react";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+// These read LaunchDarkly; `flag-backend` picks the vendor once, at load.+vi.hoisted(() => {+ process.env.NEXT_PUBLIC_FEATURE_FLAG_BACKEND = "launchdarkly";+});+vi.mock("launchdarkly-react-client-sdk", () => ({useFlags: () => ({}),}));diff --git a/autogpt_platform/frontend/src/services/feature-flags/flag-backend.ts b/autogpt_platform/frontend/src/services/feature-flags/flag-backend.tsindex 01dcd814e5..be5be487e9 100644--- a/autogpt_platform/frontend/src/services/feature-flags/flag-backend.ts+++ b/autogpt_platform/frontend/src/services/feature-flags/flag-backend.ts@@ -6,9 +6,11 @@ export type FlagBackend = "launchdarkly" | "posthog" | "dual" | "server";const configured = process.env.NEXT_PUBLIC_FEATURE_FLAG_BACKEND;export const FLAG_BACKEND: FlagBackend =- configured === "posthog" || configured === "dual" || configured === "server"+ configured === "launchdarkly" ||+ configured === "posthog" ||+ configured === "dual"? configured- : "launchdarkly";+ : "server";export function usesLaunchDarkly() {return FLAG_BACKEND === "launchdarkly" || FLAG_BACKEND === "dual";diff --git a/docs/engineering/feature-flags.md b/docs/engineering/feature-flags.mdindex 02d66c8210..71282bae9e 100644--- a/docs/engineering/feature-flags.md+++ b/docs/engineering/feature-flags.md@@ -1,8 +1,10 @@# Feature flagsWhich vendor answers a flag read is set per deployment by `FEATURE_FLAG_BACKEND`:-`launchdarkly` (the default), `posthog`, or `dual` — evaluate both, serve-LaunchDarkly's answer, and log every disagreement. Call sites are unaffected by+`posthog` (the default), `launchdarkly`, or `dual` — evaluate both, serve+LaunchDarkly's answer, and log every disagreement. Without `POSTHOG_API_KEY`+the default reads every flag as its code default, which is what a self-hosted+install and CI get. Call sites are unaffected bythe choice; they read through `evaluate_feature_flag()` on the backend and`useGetFlag` / `useFlagStatus` on the frontend.@@ -26,16 +28,17 @@ is defined in each project. The **Projects** tab on the[flag list](https://eu.posthog.com/project/281733/feature_flags?tab=projects)and on each flag's page shows a flag across both projects side by side.-**Until Prod switches to PostHog**, Prod serves LaunchDarkly's answers-(`FEATURE_FLAG_BACKEND=dual` only compares PostHog's against them), so a change-to a Prod flag is made in LaunchDarkly and mirrored in the Prod PostHog project.+Dev and Prod both run `FEATURE_FLAG_BACKEND=posthog`, so a flag is changed in+that environment's PostHog project and LaunchDarkly answers nothing there.-**The browser.** With `NEXT_PUBLIC_FEATURE_FLAG_BACKEND=server` the browser-gets its flags from the backend's `GET /api/feature-flags`, which evaluates+**The browser.** With `NEXT_PUBLIC_FEATURE_FLAG_BACKEND=server`, the default,+the browser gets its flags from the backend's `GET /api/feature-flags`, which evaluatesthem through the same path as the backend's own reads, so the browser and thebackend give one answer from one project. A Vercel preview in `server` mode-gets the answer of the backend it calls. The other values read flags in the-browser itself: `launchdarkly` (the default) from LaunchDarkly, and `posthog` /+gets the answer of the backend it calls, and a backend with no vendor answers+`configured: false`, so the browser serves its own defaults and stops asking.+The other values read flags in the browser itself: `launchdarkly` from+LaunchDarkly, and `posthog` /`dual` from the project `NEXT_PUBLIC_POSTHOG_KEY` names. `useExperiment` readsposthog-js in every mode.@@ -92,8 +95,7 @@ wire and has no definitions to share.**Per environment.** Leave the defaults on `dev` and `prod`: both run severalreplicas against a shared Redis, which is what the cache is for. Local-development and CI run `FEATURE_FLAG_BACKEND=launchdarkly`, so none of this is-reached; set `POSTHOG_FLAG_DEFINITION_CACHE=memory` if you want to exercise+development and CI have no PostHog keys, so none of this is reached; set `POSTHOG_FLAG_DEFINITION_CACHE=memory` if you want to exercisePostHog locally without Redis.### What the refresher isdiff --git a/docs/platform/contributing/agent-collaboration-architecture.md b/docs/platform/contributing/agent-collaboration-architecture.mdindex 8de6faada0..08d7dcf3ed 100644--- a/docs/platform/contributing/agent-collaboration-architecture.md+++ b/docs/platform/contributing/agent-collaboration-architecture.md@@ -170,7 +170,7 @@ keeps the ceiling proportionate, and it is why a user with no subscriptiongets zero: a plan that may not spend may not delegate.On the code defaults, which is what production serves today — the two-LaunchDarkly flags that can override the base limits and the tier multipliers+feature flags that can override the base limits and the tier multipliers(`copilot-cost-limits`, `copilot-tier-multipliers`) are both off there:| Plan | Daily allowance | Per-tree ceiling | Per-turn cap |diff --git a/docs/platform/contributing/managing-llm-models.md b/docs/platform/contributing/managing-llm-models.mdindex f62539f34d..3370b24ce0 100644--- a/docs/platform/contributing/managing-llm-models.md+++ b/docs/platform/contributing/managing-llm-models.md@@ -24,7 +24,7 @@ Each `CatalogModel` entry:| `creator` | Who trained the model (display metadata; must match a `CatalogCreator.name`). || `context_window` / `max_output_tokens` | Token limits. || `price_tier` | 1 (cheapest) to 3 (most expensive); used for display. |-| `is_enabled` | **The kill switch.** A disabled model is refused at serve time — even when LaunchDarkly routes to it. |+| `is_enabled` | **The kill switch.** A disabled model is refused at serve time — even when the routing flag routes to it. || `visibility` | Who may *see* the model: `GA` (everyone), `EMPLOYEES`, `ADMINS`, or `HIDDEN`. `HIDDEN` models still **serve when explicitly routed** — that is the pre-launch testing state. Informational until the catalog-driven picker lands (today a model stays out of block pickers by not having an enum line); the field is the picker's contract. Visibility never overrides `is_enabled`. || `fallback_model_slug` | Standing replacement pointer: the retirement CLI defaults `--replacement` to it, and it is reserved for future automatic failover. || `supports_*` | Capability flags (tools, JSON output, reasoning, parallel tool calls). Informational and authored opportunistically — `False` means *not asserted*, not "unsupported"; nothing consumes them at runtime yet, so only rely on authored `True` values. |@@ -57,7 +57,7 @@ above). The catalog's integrity tests enforce this convention.**Cells apply only on the managed cloud deployment** (`BEHAVE_AS=cloud`).Self-hosted installs — cloud transport or local — always resolve-LaunchDarkly → env: a cell set for the cloud platform travels in the+the routing flag → env: a cell set for the cloud platform travels in theshipped file but never overrides a self-hosted operator's`CHAT_*_MODEL` configuration.@@ -88,24 +88,24 @@ Two notes. The file is public: a `HIDDEN` model is hidden from pickers, **not frEach `(mode, tier)` cell resolves through three layers, top wins:-1. **LaunchDarkly `copilot-model-routing`** — per-user JSON flag returning model slugs; used for cohort experiments and rollouts. Optional: when LD is down, resolution falls through and only A/B targeting is lost.+1. **The `copilot-model-routing` feature flag** — per-user JSON flag returning model slugs; used for cohort experiments and rollouts. Optional: when the flag vendor is down, resolution falls through and only A/B targeting is lost.2. **Catalog routing cell** — the PR-authored default above.3. **`CHAT_*_MODEL` environment variables** — the bootstrap floor (see `.env.default`).-On the managed cloud, the catalog is the serve-time gate for layers 1–2: a slug that is unknown to the catalog or has `is_enabled: False` is refused — logged every time, reported to Sentry once per slug — and resolution falls through to the next layer. A typo'd LD slug therefore degrades to the default instead of erroring at users. Self-hosted installs and local transports skip the gate entirely (LD → env, their slugs are their own business). Assistant messages served by the baseline path are stamped with the model that served them and which layer picked it (`ChatMessage.model` / `routingSource`), which is what allows product-intelligence to compare model quality; the SDK path resolves through the same chain (message stamping covers the baseline path today).+On the managed cloud, the catalog is the serve-time gate for layers 1–2: a slug that is unknown to the catalog or has `is_enabled: False` is refused — logged every time, reported to Sentry once per slug — and resolution falls through to the next layer. A typo'd slug in the flag therefore degrades to the default instead of erroring at users. Self-hosted installs and local transports skip the gate entirely (flag → env, their slugs are their own business). Assistant messages served by the baseline path are stamped with the model that served them and which layer picked it (`ChatMessage.model` / `routingSource`), which is what allows product-intelligence to compare model quality; the SDK path resolves through the same chain (message stamping covers the baseline path today).## Rolling out a new model1. Add the model to the catalog with `visibility="HIDDEN"` — registered and routable, invisible in any picker or public listing.-2. Add an LD targeting rule on `copilot-model-routing` sending your test cohort (e.g. employees) to its slug.+2. Send your test cohort (e.g. employees) to its slug on the `copilot-model-routing` flag, in the vendor `FEATURE_FLAG_BACKEND` names. On PostHog, the default, that is a variant whose JSON payload carries the slug, served by a release condition matching the cohort, in each environment's own project; on LaunchDarkly, a targeting rule.3. Watch product-intelligence quality scores segmented by the stamped model column.-4. Graduate: flip `visibility` to `GA` and set the routing cell in a catalog PR; delete the LD rule.+4. Graduate: flip `visibility` to `GA` and set the routing cell in a catalog PR; remove the cohort's condition from the flag.## Retiring a modelRetirement has two halves:-1. **Stop it serving**: a catalog PR setting `is_enabled: False` (kill switch — beats LD routing). Two caveats: if the model is also a `CHAT_*_MODEL` env default, the env floor still serves it (loudly — log + Sentry) until you change that default; and existing agent graphs referencing it keep executing and billing — the kill switch stops NEW serving, step 2 is what stops stored graphs.+1. **Stop it serving**: a catalog PR setting `is_enabled: False`. On the managed cloud this is the kill switch: it beats the routing flag and hides the model from block pickers. Two caveats: if the model is also a `CHAT_*_MODEL` env default, the env floor still serves it (loudly — log + Sentry) until you change that default; and existing agent graphs referencing it keep executing and billing — the kill switch stops NEW serving, step 2 is what stops stored graphs. Self-hosted installs and local transports skip the catalog gate, so there it only hides the model from pickers: to stop AutoPilot serving it, remove its route from the `copilot-model-routing` flag and change any `CHAT_*_MODEL` default that still selects it.2. **Migrate existing graph nodes** onto a replacement so users' agents keep working:```bashdiff --git a/docs/platform/copilot-local-llm.md b/docs/platform/copilot-local-llm.mdindex 725b37ac0a..bcfac6ea34 100644--- a/docs/platform/copilot-local-llm.md+++ b/docs/platform/copilot-local-llm.md@@ -46,19 +46,20 @@ four chat transports. When `CHAT_USE_LOCAL=true`:The downgrade is logged at WARNING when an `extended_thinking` requestarrives — there is no 500. The frontend toggle should already be hidden-because the `CHAT_MODE_OPTION` LaunchDarkly flag defaults off in+because the `CHAT_MODE_OPTION` feature flag defaults off inself-hosted deployments.On the managed cloud platform (`BEHAVE_AS=cloud`), `CHAT_*_MODEL` env-vars are the *bottom* layer of model resolution: LaunchDarkly per-user-override → the LLM catalog's routing cell+vars are the *bottom* layer of model resolution: the `copilot-model-routing`+flag's per-user override → the LLM catalog's routing cell(`backend/data/llm_registry/catalog.py`) → env default, with slugsunknown to the catalog or disabled in it refused at serve time.**On self-hosted installs — any transport — the catalog's routing cellsare skipped entirely**: they are the cloud deployment's config travelingin the shipped file, and they never override your `CHAT_*_MODEL`-configuration. Resolution here is LaunchDarkly → `CHAT_*_MODEL`, exactly+configuration. Resolution here is the `copilot-model-routing` flag →+`CHAT_*_MODEL`, exactlythe pre-catalog behavior; your env vars stay authoritative. See[Managing LLM Models](contributing/managing-llm-models.md).