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.
refactor(frontend): standardise with environment service (#11209)
Ubbe063dc5cf65cc
diff --git a/autogpt_platform/frontend/instrumentation-client.ts b/autogpt_platform/frontend/instrumentation-client.tsindex 3e601b1136..c208b749dd 100644--- a/autogpt_platform/frontend/instrumentation-client.ts+++ b/autogpt_platform/frontend/instrumentation-client.ts@@ -2,18 +2,11 @@// The config you add here will be used whenever a users loads a page in their browser.// https://docs.sentry.io/platforms/javascript/guides/nextjs/-import {- AppEnv,- BehaveAs,- getAppEnv,- getBehaveAs,- getEnvironmentStr,-} from "@/lib/utils";+import { environment } from "@/services/environment";import * as Sentry from "@sentry/nextjs";-const isProdOrDev = [AppEnv.PROD, AppEnv.DEV].includes(getAppEnv());--const isCloud = getBehaveAs() === BehaveAs.CLOUD;+const isProdOrDev = environment.isProd() || environment.isDev();+const isCloud = environment.isCloud();const isDisabled = process.env.DISABLE_SENTRY === "true";const shouldEnable = !isDisabled && isProdOrDev && isCloud;@@ -21,7 +14,7 @@ const shouldEnable = !isDisabled && isProdOrDev && isCloud;Sentry.init({dsn: "https://fe4e4aa4a283391808a5da396da20159@o4505260022104064.ingest.us.sentry.io/4507946746380288",- environment: getEnvironmentStr(),+ environment: environment.getEnvironmentStr(),enabled: shouldEnable,diff --git a/autogpt_platform/frontend/scripts/generate-api-queries.ts b/autogpt_platform/frontend/scripts/generate-api-queries.tsindex a11e7329c3..0c6fa717a3 100644--- a/autogpt_platform/frontend/scripts/generate-api-queries.ts+++ b/autogpt_platform/frontend/scripts/generate-api-queries.ts@@ -1,16 +1,16 @@#!/usr/bin/env node-import { getAgptServerBaseUrl } from "@/lib/env-config";import { execSync } from "child_process";import * as path from "path";import * as fs from "fs";import * as os from "os";+import { environment } from "@/services/environment";function fetchOpenApiSpec(): void {const args = process.argv.slice(2);const forceFlag = args.includes("--force");- const baseUrl = getAgptServerBaseUrl();+ const baseUrl = environment.getAGPTServerBaseUrl();const openApiUrl = `${baseUrl}/openapi.json`;const outputPath = path.join(__dirname,diff --git a/autogpt_platform/frontend/sentry.edge.config.ts b/autogpt_platform/frontend/sentry.edge.config.tsindex 614be377ad..a07ef139b5 100644--- a/autogpt_platform/frontend/sentry.edge.config.ts+++ b/autogpt_platform/frontend/sentry.edge.config.ts@@ -3,18 +3,11 @@// Note that this config is unrelated to the Vercel Edge Runtime and is also required when running locally.// https://docs.sentry.io/platforms/javascript/guides/nextjs/+import { environment } from "@/services/environment";import * as Sentry from "@sentry/nextjs";-import {- AppEnv,- BehaveAs,- getAppEnv,- getBehaveAs,- getEnvironmentStr,-} from "./src/lib/utils";-const isProdOrDev = [AppEnv.PROD, AppEnv.DEV].includes(getAppEnv());--const isCloud = getBehaveAs() === BehaveAs.CLOUD;+const isProdOrDev = environment.isProd() || environment.isDev();+const isCloud = environment.isCloud();const isDisabled = process.env.DISABLE_SENTRY === "true";const shouldEnable = !isDisabled && isProdOrDev && isCloud;@@ -22,7 +15,7 @@ const shouldEnable = !isDisabled && isProdOrDev && isCloud;Sentry.init({dsn: "https://fe4e4aa4a283391808a5da396da20159@o4505260022104064.ingest.us.sentry.io/4507946746380288",- environment: getEnvironmentStr(),+ environment: environment.getEnvironmentStr(),enabled: shouldEnable,diff --git a/autogpt_platform/frontend/sentry.server.config.ts b/autogpt_platform/frontend/sentry.server.config.tsindex aea80ee8e4..97c159737a 100644--- a/autogpt_platform/frontend/sentry.server.config.ts+++ b/autogpt_platform/frontend/sentry.server.config.ts@@ -2,19 +2,12 @@// The config you add here will be used whenever the server handles a request.// https://docs.sentry.io/platforms/javascript/guides/nextjs/-import {- AppEnv,- BehaveAs,- getAppEnv,- getBehaveAs,- getEnvironmentStr,-} from "@/lib/utils";+import { environment } from "@/services/environment";import * as Sentry from "@sentry/nextjs";// import { NodeProfilingIntegration } from "@sentry/profiling-node";-const isProdOrDev = [AppEnv.PROD, AppEnv.DEV].includes(getAppEnv());--const isCloud = getBehaveAs() === BehaveAs.CLOUD;+const isProdOrDev = environment.isProd() || environment.isDev();+const isCloud = environment.isCloud();const isDisabled = process.env.DISABLE_SENTRY === "true";const shouldEnable = !isDisabled && isProdOrDev && isCloud;@@ -22,7 +15,7 @@ const shouldEnable = !isDisabled && isProdOrDev && isCloud;Sentry.init({dsn: "https://fe4e4aa4a283391808a5da396da20159@o4505260022104064.ingest.us.sentry.io/4507946746380288",- environment: getEnvironmentStr(),+ environment: environment.getEnvironmentStr(),enabled: shouldEnable,diff --git a/autogpt_platform/frontend/src/app/(platform)/auth/auth-code-error/page.tsx b/autogpt_platform/frontend/src/app/(platform)/auth/auth-code-error/page.tsxindex fa630774f4..a9cbe5b29c 100644--- a/autogpt_platform/frontend/src/app/(platform)/auth/auth-code-error/page.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/auth/auth-code-error/page.tsx@@ -1,6 +1,5 @@"use client";-import { isServerSide } from "@/lib/utils/is-server-side";import { useEffect, useState } from "react";import { Button } from "@/components/atoms/Button/Button";import { Text } from "@/components/atoms/Text/Text";@@ -8,6 +7,7 @@ import { Card } from "@/components/atoms/Card/Card";import { WaitlistErrorContent } from "@/components/auth/WaitlistErrorContent";import { isWaitlistErrorFromParams } from "@/app/api/auth/utils";import { useRouter } from "next/navigation";+import { environment } from "@/services/environment";export default function AuthErrorPage() {const [errorType, setErrorType] = useState<string | null>(null);@@ -17,7 +17,7 @@ export default function AuthErrorPage() {useEffect(() => {// This code only runs on the client side- if (!isServerSide()) {+ if (!environment.isServerSide()) {const hash = window.location.hash.substring(1); // Remove the leading '#'const params = new URLSearchParams(hash);diff --git a/autogpt_platform/frontend/src/app/(platform)/build/components/legacy-builder/OttoChatWidget.tsx b/autogpt_platform/frontend/src/app/(platform)/build/components/legacy-builder/OttoChatWidget.tsxindex 3eaf75951d..7dd7b83edb 100644--- a/autogpt_platform/frontend/src/app/(platform)/build/components/legacy-builder/OttoChatWidget.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/build/components/legacy-builder/OttoChatWidget.tsx@@ -6,6 +6,7 @@ import ReactMarkdown from "react-markdown";import type { GraphID } from "@/lib/autogpt-server-api/types";import { askOtto } from "@/app/(platform)/build/actions";import { cn } from "@/lib/utils";+import { environment } from "@/services/environment";interface Message {type: "user" | "assistant";@@ -129,7 +130,7 @@ export default function OttoChatWidget({};// Don't render the chat widget if we're not on the build page or in local mode- if (process.env.NEXT_PUBLIC_BEHAVE_AS !== "CLOUD") {+ if (environment.isLocal()) {return null;}diff --git a/autogpt_platform/frontend/src/app/(platform)/login/page.tsx b/autogpt_platform/frontend/src/app/(platform)/login/page.tsxindex 4770970475..db52430aed 100644--- a/autogpt_platform/frontend/src/app/(platform)/login/page.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/login/page.tsx@@ -8,9 +8,9 @@ import { EmailNotAllowedModal } from "@/components/auth/EmailNotAllowedModal";import { GoogleOAuthButton } from "@/components/auth/GoogleOAuthButton";import Turnstile from "@/components/auth/Turnstile";import { Form, FormField } from "@/components/__legacy__/ui/form";-import { getBehaveAs } from "@/lib/utils";import { LoadingLogin } from "./components/LoadingLogin";import { useLoginPage } from "./useLoginPage";+import { environment } from "@/services/environment";export default function LoginPage() {const {@@ -118,7 +118,7 @@ export default function LoginPage() {type="login"message={feedback}isError={!!feedback}- behaveAs={getBehaveAs()}+ behaveAs={environment.getBehaveAs()}/></Form><AuthCard.BottomTextdiff --git a/autogpt_platform/frontend/src/app/(platform)/login/useLoginPage.ts b/autogpt_platform/frontend/src/app/(platform)/login/useLoginPage.tsindex cee4927007..276ab05102 100644--- a/autogpt_platform/frontend/src/app/(platform)/login/useLoginPage.ts+++ b/autogpt_platform/frontend/src/app/(platform)/login/useLoginPage.ts@@ -1,6 +1,5 @@import { useTurnstile } from "@/hooks/useTurnstile";import { useSupabase } from "@/lib/supabase/hooks/useSupabase";-import { BehaveAs, getBehaveAs } from "@/lib/utils";import { loginFormSchema, LoginProvider } from "@/types/auth";import { zodResolver } from "@hookform/resolvers/zod";import { useRouter } from "next/navigation";@@ -8,6 +7,7 @@ import { useCallback, useEffect, useState } from "react";import { useForm } from "react-hook-form";import z from "zod";import { useToast } from "@/components/molecules/Toast/use-toast";+import { environment } from "@/services/environment";export function useLoginPage() {const { supabase, user, isUserLoading } = useSupabase();@@ -18,7 +18,7 @@ export function useLoginPage() {const [isLoading, setIsLoading] = useState(false);const [isGoogleLoading, setIsGoogleLoading] = useState(false);const [showNotAllowedModal, setShowNotAllowedModal] = useState(false);- const isCloudEnv = getBehaveAs() === BehaveAs.CLOUD;+ const isCloudEnv = environment.isCloud();const isVercelPreview = process.env.NEXT_PUBLIC_VERCEL_ENV === "preview";const turnstile = useTurnstile({diff --git a/autogpt_platform/frontend/src/app/(platform)/signup/page.tsx b/autogpt_platform/frontend/src/app/(platform)/signup/page.tsxindex ea1aefb6c4..dff878436d 100644--- a/autogpt_platform/frontend/src/app/(platform)/signup/page.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/signup/page.tsx@@ -17,10 +17,10 @@ import {FormItem,FormLabel,} from "@/components/__legacy__/ui/form";-import { getBehaveAs } from "@/lib/utils";import { WarningOctagonIcon } from "@phosphor-icons/react/dist/ssr";import { LoadingSignup } from "./components/LoadingSignup";import { useSignupPage } from "./useSignupPage";+import { environment } from "@/services/environment";export default function SignupPage() {const {@@ -196,7 +196,7 @@ export default function SignupPage() {type="signup"message={feedback}isError={!!feedback}- behaveAs={getBehaveAs()}+ behaveAs={environment.getBehaveAs()}/><AuthCard.BottomTextdiff --git a/autogpt_platform/frontend/src/app/(platform)/signup/useSignupPage.ts b/autogpt_platform/frontend/src/app/(platform)/signup/useSignupPage.tsindex 9ffcb3aee5..f598ab2257 100644--- a/autogpt_platform/frontend/src/app/(platform)/signup/useSignupPage.ts+++ b/autogpt_platform/frontend/src/app/(platform)/signup/useSignupPage.ts@@ -1,6 +1,5 @@import { useTurnstile } from "@/hooks/useTurnstile";import { useSupabase } from "@/lib/supabase/hooks/useSupabase";-import { BehaveAs, getBehaveAs } from "@/lib/utils";import { LoginProvider, signupFormSchema } from "@/types/auth";import { zodResolver } from "@hookform/resolvers/zod";import { useRouter } from "next/navigation";@@ -8,6 +7,7 @@ import { useCallback, useEffect, useState } from "react";import { useForm } from "react-hook-form";import z from "zod";import { useToast } from "@/components/molecules/Toast/use-toast";+import { environment } from "@/services/environment";export function useSignupPage() {const { supabase, user, isUserLoading } = useSupabase();@@ -19,7 +19,7 @@ export function useSignupPage() {const [isGoogleLoading, setIsGoogleLoading] = useState(false);const [showNotAllowedModal, setShowNotAllowedModal] = useState(false);- const isCloudEnv = getBehaveAs() === BehaveAs.CLOUD;+ const isCloudEnv = environment.isCloud();const isVercelPreview = process.env.NEXT_PUBLIC_VERCEL_ENV === "preview";const turnstile = useTurnstile({diff --git a/autogpt_platform/frontend/src/app/api/mutators/custom-mutator.ts b/autogpt_platform/frontend/src/app/api/mutators/custom-mutator.tsindex 17e32256ee..f5eb56abe8 100644--- a/autogpt_platform/frontend/src/app/api/mutators/custom-mutator.ts+++ b/autogpt_platform/frontend/src/app/api/mutators/custom-mutator.ts@@ -3,20 +3,19 @@ import {createRequestHeaders,getServerAuthToken,} from "@/lib/autogpt-server-api/helpers";-import { isServerSide } from "@/lib/utils/is-server-side";-import { getAgptServerBaseUrl } from "@/lib/env-config";import { transformDates } from "./date-transformer";+import { environment } from "@/services/environment";const FRONTEND_BASE_URL =process.env.NEXT_PUBLIC_FRONTEND_BASE_URL || "http://localhost:3000";const API_PROXY_BASE_URL = `${FRONTEND_BASE_URL}/api/proxy`; // Sending request via nextjs Serverconst getBaseUrl = (): string => {- if (!isServerSide()) {+ if (!environment.isServerSide()) {return API_PROXY_BASE_URL;} else {- return getAgptServerBaseUrl();+ return environment.getAGPTServerBaseUrl();}};@@ -77,7 +76,7 @@ export const customMutator = async <// The caching in React Query in our system depends on the url, so the base_url could be different for the server and client sides.const fullUrl = `${baseUrl}${url}${queryString}`;- if (isServerSide()) {+ if (environment.isServerSide()) {try {const token = await getServerAuthToken();const authHeaders = createRequestHeaders(token, !!data, contentType);@@ -100,7 +99,7 @@ export const customMutator = async <response_data?.detail || response_data?.message || response.statusText;console.error(- `Request failed ${isServerSide() ? "on server" : "on client"}`,+ `Request failed ${environment.isServerSide() ? "on server" : "on client"}`,{ status: response.status, url: fullUrl, data: response_data },);diff --git a/autogpt_platform/frontend/src/app/api/proxy/[...path]/route.ts b/autogpt_platform/frontend/src/app/api/proxy/[...path]/route.tsindex ad39185dbd..f5408eb0a6 100644--- a/autogpt_platform/frontend/src/app/api/proxy/[...path]/route.ts+++ b/autogpt_platform/frontend/src/app/api/proxy/[...path]/route.ts@@ -3,12 +3,12 @@ import {makeAuthenticatedFileUpload,makeAuthenticatedRequest,} from "@/lib/autogpt-server-api/helpers";-import { getAgptServerBaseUrl } from "@/lib/env-config";+import { environment } from "@/services/environment";import { NextRequest, NextResponse } from "next/server";function buildBackendUrl(path: string[], queryString: string): string {const backendPath = path.join("/");- return `${getAgptServerBaseUrl()}/${backendPath}${queryString}`;+ return `${environment.getAGPTServerBaseUrl()}/${backendPath}${queryString}`;}async function handleJsonRequest(diff --git a/autogpt_platform/frontend/src/app/layout.tsx b/autogpt_platform/frontend/src/app/layout.tsxindex 258a08a9bd..93ff9c18b0 100644--- a/autogpt_platform/frontend/src/app/layout.tsx+++ b/autogpt_platform/frontend/src/app/layout.tsx@@ -11,8 +11,9 @@ import { Toaster } from "@/components/molecules/Toast/toaster";import { ReactQueryDevtools } from "@tanstack/react-query-devtools";import { SpeedInsights } from "@vercel/speed-insights/next";import { Analytics } from "@vercel/analytics/next";-import { headers } from "next/headers";import Script from "next/script";+import { environment } from "@/services/environment";+import { headers } from "next/headers";export const metadata: Metadata = {title: "AutoGPT Platform",@@ -26,7 +27,8 @@ export default async function RootLayout({}>) {const headersList = await headers();const host = headersList.get("host") || "";- const isPlatformDomain = host === "platform.agpt.co";+ const withAnalytics = environment.areAnalyticsEnabled(host);+return (<htmllang="en"@@ -37,14 +39,14 @@ export default async function RootLayout({<GoogleAnalyticsgaId={process.env.NEXT_PUBLIC_GA_MEASUREMENT_ID || "G-FH2XK2W4GN"} // This is the measurement Id for the Google Analytics dev project/>- {isPlatformDomain && (+ {withAnalytics ? (<Scriptstrategy="afterInteractive"data-website-id="dfid_g5wtBIiHUwSkWKcGz80lu"data-domain="agpt.co"src="https://datafa.st/js/script.js"/>- )}+ ) : null}</head><body><Providersdiff --git a/autogpt_platform/frontend/src/components/auth/AuthFeedback.tsx b/autogpt_platform/frontend/src/components/auth/AuthFeedback.tsxindex 84bba731aa..0820892584 100644--- a/autogpt_platform/frontend/src/components/auth/AuthFeedback.tsx+++ b/autogpt_platform/frontend/src/components/auth/AuthFeedback.tsx@@ -1,7 +1,7 @@import { HelpItem } from "@/components/auth/help-item";import { Card, CardContent } from "@/components/__legacy__/ui/card";-import { BehaveAs } from "@/lib/utils";import { AlertCircle, CheckCircle } from "lucide-react";+import { BehaveAs } from "@/services/environment";interface Props {type: "login" | "signup";diff --git a/autogpt_platform/frontend/src/components/auth/Turnstile.tsx b/autogpt_platform/frontend/src/components/auth/Turnstile.tsxindex a2e1625141..bb9e9b7d05 100644--- a/autogpt_platform/frontend/src/components/auth/Turnstile.tsx+++ b/autogpt_platform/frontend/src/components/auth/Turnstile.tsx@@ -1,6 +1,6 @@"use client";import { cn } from "@/lib/utils";-import { isServerSide } from "@/lib/utils/is-server-side";+import { environment } from "@/services/environment";import { useEffect, useRef, useState } from "react";export interface TurnstileProps {@@ -32,7 +32,7 @@ export function Turnstile({// Load the Turnstile scriptuseEffect(() => {- if (isServerSide() || !shouldRender) return;+ if (environment.isServerSide() || !shouldRender) return;// Skip if already loadedif (window.turnstile) {diff --git a/autogpt_platform/frontend/src/components/contextual/InfiniteScroll/useInfiniteScroll.ts b/autogpt_platform/frontend/src/components/contextual/InfiniteScroll/useInfiniteScroll.tsindex 8962f7e1c9..7fa0aa936c 100644--- a/autogpt_platform/frontend/src/components/contextual/InfiniteScroll/useInfiniteScroll.ts+++ b/autogpt_platform/frontend/src/components/contextual/InfiniteScroll/useInfiniteScroll.ts@@ -1,4 +1,4 @@-import { isServerSide } from "@/lib/utils/is-server-side";+import { environment } from "@/services/environment";import { useCallback, useEffect, useRef, useState } from "react";interface useInfiniteScrollProps {@@ -34,7 +34,8 @@ export const useInfiniteScroll = ({}, [hasNextPage, isFetchingNextPage, fetchNextPage, onLoadMore]);useEffect(() => {- if (!hasNextPage || !endOfListRef.current || isServerSide()) return;+ if (!hasNextPage || !endOfListRef.current || environment.isServerSide())+ return;const observer = new IntersectionObserver((entries) => {diff --git a/autogpt_platform/frontend/src/hooks/useTurnstile.ts b/autogpt_platform/frontend/src/hooks/useTurnstile.tsindex c6e7d85bcc..86f2b93c9f 100644--- a/autogpt_platform/frontend/src/hooks/useTurnstile.ts+++ b/autogpt_platform/frontend/src/hooks/useTurnstile.ts@@ -1,7 +1,6 @@import { useState, useCallback, useEffect } from "react";import { verifyTurnstileToken } from "@/lib/turnstile";-import { BehaveAs, getBehaveAs } from "@/lib/utils";-import { isServerSide } from "@/lib/utils/is-server-side";+import { environment } from "@/services/environment";interface UseTurnstileOptions {action?: string;@@ -46,17 +45,15 @@ export function useTurnstile({const [widgetId, setWidgetId] = useState<string | null>(null);useEffect(() => {- const behaveAs = getBehaveAs();+ const isCloud = environment.isCloud();const hasTurnstileKey = !!TURNSTILE_SITE_KEY;const turnstileDisabled = process.env.NEXT_PUBLIC_TURNSTILE !== "enabled";// Only render Turnstile in cloud environment if not explicitly disabled- setShouldRender(- behaveAs === BehaveAs.CLOUD && hasTurnstileKey && !turnstileDisabled,- );+ setShouldRender(isCloud && hasTurnstileKey && !turnstileDisabled);// Skip verification if disabled, in local development, or no key- if (turnstileDisabled || behaveAs !== BehaveAs.CLOUD || !hasTurnstileKey) {+ if (turnstileDisabled || !isCloud || !hasTurnstileKey) {setVerified(true);}}, []);@@ -80,7 +77,12 @@ export function useTurnstile({setError(null);// Only reset the actual Turnstile widget if it exists and shouldRender is true- if (shouldRender && !isServerSide() && window.turnstile && widgetId) {+ if (+ shouldRender &&+ !environment.isServerSide() &&+ window.turnstile &&+ widgetId+ ) {try {window.turnstile.reset(widgetId);} catch (err) {diff --git a/autogpt_platform/frontend/src/lib/autogpt-server-api/client.ts b/autogpt_platform/frontend/src/lib/autogpt-server-api/client.tsindex dc99ee2b44..08e5c05f63 100644--- a/autogpt_platform/frontend/src/lib/autogpt-server-api/client.ts+++ b/autogpt_platform/frontend/src/lib/autogpt-server-api/client.ts@@ -3,12 +3,6 @@ import { getServerSupabase } from "@/lib/supabase/server/getServerSupabase";import { createBrowserClient } from "@supabase/ssr";import type { SupabaseClient } from "@supabase/supabase-js";import { Key, storage } from "@/services/storage/local-storage";-import {- getAgptServerApiUrl,- getAgptWsServerUrl,- getSupabaseUrl,- getSupabaseAnonKey,-} from "@/lib/env-config";import * as Sentry from "@sentry/nextjs";import type {AddUserCreditsResponse,@@ -73,9 +67,9 @@ import type {UserPasswordCredentials,UsersBalanceHistoryResponse,} from "./types";-import { isServerSide } from "../utils/is-server-side";+import { environment } from "@/services/environment";-const isClient = !isServerSide();+const isClient = environment.isClientSide();export default class BackendAPI {private baseUrl: string;@@ -93,8 +87,8 @@ export default class BackendAPI {heartbeatTimeoutID: number | null = null;constructor(- baseUrl: string = getAgptServerApiUrl(),- wsUrl: string = getAgptWsServerUrl(),+ baseUrl: string = environment.getAGPTServerApiUrl(),+ wsUrl: string = environment.getAGPTWsServerUrl(),) {this.baseUrl = baseUrl;this.wsUrl = wsUrl;@@ -102,9 +96,13 @@ export default class BackendAPI {private async getSupabaseClient(): Promise<SupabaseClient | null> {return isClient- ? createBrowserClient(getSupabaseUrl(), getSupabaseAnonKey(), {- isSingleton: true,- })+ ? createBrowserClient(+ environment.getSupabaseUrl(),+ environment.getSupabaseAnonKey(),+ {+ isSingleton: true,+ },+ ): await getServerSupabase();}diff --git a/autogpt_platform/frontend/src/lib/autogpt-server-api/context.tsx b/autogpt_platform/frontend/src/lib/autogpt-server-api/context.tsxindex 21bff08454..7e8920e176 100644--- a/autogpt_platform/frontend/src/lib/autogpt-server-api/context.tsx+++ b/autogpt_platform/frontend/src/lib/autogpt-server-api/context.tsx@@ -1,6 +1,6 @@"use client";-import { isServerSide } from "../utils/is-server-side";+import { environment } from "@/services/environment";import BackendAPI from "./client";import React, { createContext, useMemo } from "react";@@ -20,7 +20,7 @@ export function BackendAPIProvider({}): React.ReactNode {const api = useMemo(() => new BackendAPI(), []);- if (process.env.NEXT_PUBLIC_BEHAVE_AS == "LOCAL" && !isServerSide()) {+ if (environment.isLocal() && !environment.isServerSide()) {window.api = api; // Expose the API globally for debugging purposes}diff --git a/autogpt_platform/frontend/src/lib/autogpt-server-api/helpers.ts b/autogpt_platform/frontend/src/lib/autogpt-server-api/helpers.tsindex 56a41f135b..b56912b0e8 100644--- a/autogpt_platform/frontend/src/lib/autogpt-server-api/helpers.ts+++ b/autogpt_platform/frontend/src/lib/autogpt-server-api/helpers.ts@@ -1,7 +1,6 @@import { getServerSupabase } from "@/lib/supabase/server/getServerSupabase";import { Key, storage } from "@/services/storage/local-storage";-import { getAgptServerApiUrl } from "@/lib/env-config";-import { isServerSide } from "../utils/is-server-side";+import { environment } from "@/services/environment";import { GraphValidationErrorResponse } from "./types";@@ -57,7 +56,7 @@ export function buildClientUrl(path: string): string {}export function buildServerUrl(path: string): string {- return `${getAgptServerApiUrl()}${path}`;+ return `${environment.getAGPTServerApiUrl()}${path}`;}export function buildUrlWithQuery(@@ -197,7 +196,7 @@ function isAuthenticationError(}function isLogoutInProgress(): boolean {- if (isServerSide()) return false;+ if (environment.isServerSide()) return false;try {// Check if logout was recently triggereddiff --git a/autogpt_platform/frontend/src/lib/env-config.ts b/autogpt_platform/frontend/src/lib/env-config.tsdeleted file mode 100644index 33b07530b7..0000000000--- a/autogpt_platform/frontend/src/lib/env-config.ts+++ /dev/null@@ -1,65 +0,0 @@-/**- * Environment configuration helper- *- * Provides unified access to environment variables with server-side priority.- * Server-side code uses Docker service names, client-side falls back to localhost.- */--import { isServerSide } from "./utils/is-server-side";--/**- * Gets the AGPT server URL with server-side priority- * Server-side: Uses AGPT_SERVER_URL (http://rest_server:8006/api)- * Client-side: Falls back to NEXT_PUBLIC_AGPT_SERVER_URL (http://localhost:8006/api)- */-export function getAgptServerApiUrl(): string {- // If server-side and server URL exists, use it- if (isServerSide() && process.env.AGPT_SERVER_URL) {- return process.env.AGPT_SERVER_URL;- }-- // Otherwise use the public URL- return process.env.NEXT_PUBLIC_AGPT_SERVER_URL || "http://localhost:8006/api";-}--export function getAgptServerBaseUrl(): string {- return getAgptServerApiUrl().replace("/api", "");-}--/**- * Gets the AGPT WebSocket URL with server-side priority- * Server-side: Uses AGPT_WS_SERVER_URL (ws://websocket_server:8001/ws)- * Client-side: Falls back to NEXT_PUBLIC_AGPT_WS_SERVER_URL (ws://localhost:8001/ws)- */-export function getAgptWsServerUrl(): string {- // If server-side and server URL exists, use it- if (isServerSide() && process.env.AGPT_WS_SERVER_URL) {- return process.env.AGPT_WS_SERVER_URL;- }-- // Otherwise use the public URL- return process.env.NEXT_PUBLIC_AGPT_WS_SERVER_URL || "ws://localhost:8001/ws";-}--/**- * Gets the Supabase URL with server-side priority- * Server-side: Uses SUPABASE_URL (http://kong:8000)- * Client-side: Falls back to NEXT_PUBLIC_SUPABASE_URL (http://localhost:8000)- */-export function getSupabaseUrl(): string {- // If server-side and server URL exists, use it- if (isServerSide() && process.env.SUPABASE_URL) {- return process.env.SUPABASE_URL;- }-- // Otherwise use the public URL- return process.env.NEXT_PUBLIC_SUPABASE_URL || "http://localhost:8000";-}--/**- * Gets the Supabase anon key- * Uses NEXT_PUBLIC_SUPABASE_ANON_KEY since anon keys are public and same across environments- */-export function getSupabaseAnonKey(): string {- return process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY || "";-}diff --git a/autogpt_platform/frontend/src/lib/supabase/helpers.ts b/autogpt_platform/frontend/src/lib/supabase/helpers.tsindex 1ef5aabec2..cf89d96724 100644--- a/autogpt_platform/frontend/src/lib/supabase/helpers.ts+++ b/autogpt_platform/frontend/src/lib/supabase/helpers.ts@@ -1,7 +1,7 @@import { type CookieOptions } from "@supabase/ssr";import { SupabaseClient } from "@supabase/supabase-js";import { Key, storage } from "@/services/storage/local-storage";-import { isServerSide } from "../utils/is-server-side";+import { environment } from "@/services/environment";export const PROTECTED_PAGES = ["/monitor",@@ -83,7 +83,7 @@ export function setupSessionEventListeners(onFocus: () => void,onStorageChange: (e: StorageEvent) => void,): EventListeners {- if (isServerSide() || typeof document === "undefined") {+ if (environment.isServerSide()) {return { cleanup: () => {} };}diff --git a/autogpt_platform/frontend/src/lib/supabase/hooks/useSupabase.ts b/autogpt_platform/frontend/src/lib/supabase/hooks/useSupabase.tsindex 025919391e..3f12e52949 100644--- a/autogpt_platform/frontend/src/lib/supabase/hooks/useSupabase.ts+++ b/autogpt_platform/frontend/src/lib/supabase/hooks/useSupabase.ts@@ -4,7 +4,6 @@ import { User } from "@supabase/supabase-js";import { usePathname, useRouter } from "next/navigation";import { useEffect, useMemo, useRef, useState } from "react";import { useBackendAPI } from "@/lib/autogpt-server-api/context";-import { getSupabaseUrl, getSupabaseAnonKey } from "@/lib/env-config";import {getCurrentUser,refreshSession,@@ -20,6 +19,7 @@ import {setWebSocketDisconnectIntent,setupSessionEventListeners,} from "../helpers";+import { environment } from "@/services/environment";export function useSupabase() {const router = useRouter();@@ -33,12 +33,16 @@ export function useSupabase() {const supabase = useMemo(() => {try {- return createBrowserClient(getSupabaseUrl(), getSupabaseAnonKey(), {- isSingleton: true,- auth: {- persistSession: false, // Don't persist session on client with httpOnly cookies+ return createBrowserClient(+ environment.getSupabaseUrl(),+ environment.getSupabaseAnonKey(),+ {+ isSingleton: true,+ auth: {+ persistSession: false, // Don't persist session on client with httpOnly cookies+ },},- });+ );} catch (error) {console.error("Error creating Supabase client", error);return null;diff --git a/autogpt_platform/frontend/src/lib/supabase/middleware.ts b/autogpt_platform/frontend/src/lib/supabase/middleware.tsindex 05b911c7ef..3ac0aeec17 100644--- a/autogpt_platform/frontend/src/lib/supabase/middleware.ts+++ b/autogpt_platform/frontend/src/lib/supabase/middleware.ts@@ -1,15 +1,15 @@import { createServerClient } from "@supabase/ssr";import { NextResponse, type NextRequest } from "next/server";import { getCookieSettings, isAdminPage, isProtectedPage } from "./helpers";-import { getSupabaseUrl, getSupabaseAnonKey } from "../env-config";+import { environment } from "@/services/environment";export async function updateSession(request: NextRequest) {let supabaseResponse = NextResponse.next({request,});- const supabaseUrl = getSupabaseUrl();- const supabaseKey = getSupabaseAnonKey();+ const supabaseUrl = environment.getSupabaseUrl();+ const supabaseKey = environment.getSupabaseAnonKey();const isAvailable = Boolean(supabaseUrl && supabaseKey);if (!isAvailable) {diff --git a/autogpt_platform/frontend/src/lib/supabase/server/getServerSupabase.ts b/autogpt_platform/frontend/src/lib/supabase/server/getServerSupabase.tsindex 0faa8ec9b8..04ad5ecdc3 100644--- a/autogpt_platform/frontend/src/lib/supabase/server/getServerSupabase.ts+++ b/autogpt_platform/frontend/src/lib/supabase/server/getServerSupabase.ts@@ -1,6 +1,6 @@import { createServerClient, type CookieOptions } from "@supabase/ssr";import { getCookieSettings } from "../helpers";-import { getSupabaseUrl, getSupabaseAnonKey } from "../../env-config";+import { environment } from "@/services/environment";type Cookies = { name: string; value: string; options?: CookieOptions }[];@@ -12,8 +12,8 @@ export async function getServerSupabase() {try {const supabase = createServerClient(- getSupabaseUrl(),- getSupabaseAnonKey(),+ environment.getSupabaseUrl(),+ environment.getSupabaseAnonKey(),{cookies: {getAll() {diff --git a/autogpt_platform/frontend/src/lib/turnstile.ts b/autogpt_platform/frontend/src/lib/turnstile.tsindex 976348c713..faaa1f03e2 100644--- a/autogpt_platform/frontend/src/lib/turnstile.ts+++ b/autogpt_platform/frontend/src/lib/turnstile.ts@@ -1,35 +1,27 @@-/**- * Utility functions for working with Cloudflare Turnstile- */-import { BehaveAs, getBehaveAs } from "@/lib/utils";-import { getAgptServerApiUrl } from "@/lib/env-config";+import { environment } from "@/services/environment";export async function verifyTurnstileToken(token: string,action?: string,): Promise<boolean> {- // Skip verification unless explicitly enabled via environment variable- if (process.env.NEXT_PUBLIC_TURNSTILE !== "enabled") {- return true;- }-- // Skip verification in local development- const behaveAs = getBehaveAs();- if (behaveAs !== BehaveAs.CLOUD) {+ if (!environment.isCAPTCHAEnabled() || environment.isLocal()) {return true;}try {- const response = await fetch(`${getAgptServerApiUrl()}/turnstile/verify`, {- method: "POST",- headers: {- "Content-Type": "application/json",+ const response = await fetch(+ `${environment.getAGPTServerApiUrl()}/turnstile/verify`,+ {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ token,+ action,+ }),},- body: JSON.stringify({- token,- action,- }),- });+ );if (!response.ok) {console.error("Turnstile verification failed:", await response.text());diff --git a/autogpt_platform/frontend/src/lib/utils.ts b/autogpt_platform/frontend/src/lib/utils.tsindex aaf177156f..8fb3fed3d8 100644--- a/autogpt_platform/frontend/src/lib/utils.ts+++ b/autogpt_platform/frontend/src/lib/utils.ts@@ -228,36 +228,6 @@ export function getPrimaryCategoryColor(categories: Category[]): string {);}-export enum BehaveAs {- CLOUD = "CLOUD",- LOCAL = "LOCAL",-}--export function getBehaveAs(): BehaveAs {- return process.env.NEXT_PUBLIC_BEHAVE_AS === "CLOUD"- ? BehaveAs.CLOUD- : BehaveAs.LOCAL;-}--export enum AppEnv {- LOCAL = "local",- DEV = "dev",- PROD = "prod",-}--export function getAppEnv(): AppEnv {- const env = process.env.NEXT_PUBLIC_APP_ENV;- if (env === "dev") return AppEnv.DEV;- if (env === "prod") return AppEnv.PROD;- // Some places use prod and others production- if (env === "production") return AppEnv.PROD;- return AppEnv.LOCAL;-}--export function getEnvironmentStr(): string {- return `app:${getAppEnv().toLowerCase()}-behave:${getBehaveAs().toLowerCase()}`;-}-function rectanglesOverlap(rect1: { x: number; y: number; width: number; height?: number },rect2: { x: number; y: number; width: number; height?: number },diff --git a/autogpt_platform/frontend/src/lib/utils/is-server-side.ts b/autogpt_platform/frontend/src/lib/utils/is-server-side.tsdeleted file mode 100644index ec6f6bde60..0000000000--- a/autogpt_platform/frontend/src/lib/utils/is-server-side.ts+++ /dev/null@@ -1,3 +0,0 @@-export const isServerSide = (): boolean => {- return typeof window === "undefined";-};diff --git a/autogpt_platform/frontend/src/services/environment/index.ts b/autogpt_platform/frontend/src/services/environment/index.tsnew file mode 100644index 0000000000..e84e7e2e8d--- /dev/null+++ b/autogpt_platform/frontend/src/services/environment/index.ts@@ -0,0 +1,120 @@+export enum BehaveAs {+ CLOUD = "CLOUD",+ LOCAL = "LOCAL",+}++function getBehaveAs(): BehaveAs {+ return process.env.NEXT_PUBLIC_BEHAVE_AS === "CLOUD"+ ? BehaveAs.CLOUD+ : BehaveAs.LOCAL;+}++export enum AppEnv {+ LOCAL = "local",+ DEV = "dev",+ PROD = "prod",+}++function getAppEnv(): AppEnv {+ const env = process.env.NEXT_PUBLIC_APP_ENV;+ if (env === "dev") return AppEnv.DEV;+ if (env === "prod") return AppEnv.PROD;+ // Some places use prod and others production+ if (env === "production") return AppEnv.PROD;+ return AppEnv.LOCAL;+}++function getAGPTServerApiUrl() {+ if (environment.isServerSide() && process.env.AGPT_SERVER_URL) {+ return process.env.AGPT_SERVER_URL;+ }++ return process.env.NEXT_PUBLIC_AGPT_SERVER_URL || "http://localhost:8006/api";+}++function getAGPTServerBaseUrl() {+ return getAGPTServerApiUrl().replace("/api", "");+}++function getAGPTWsServerUrl() {+ if (environment.isServerSide() && process.env.AGPT_WS_SERVER_URL) {+ return process.env.AGPT_WS_SERVER_URL;+ }++ return process.env.NEXT_PUBLIC_AGPT_WS_SERVER_URL || "ws://localhost:8001/ws";+}++function getSupabaseUrl() {+ if (environment.isServerSide() && process.env.SUPABASE_URL) {+ return process.env.SUPABASE_URL;+ }++ return process.env.NEXT_PUBLIC_SUPABASE_URL || "http://localhost:8000";+}++function getSupabaseAnonKey() {+ return process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY || "";+}++function getEnvironmentStr() {+ return `app:${getAppEnv().toLowerCase()}-behave:${getBehaveAs().toLowerCase()}`;+}++function isProd() {+ return process.env.NODE_ENV === "production";+}++function isDev() {+ return process.env.NODE_ENV === "development";+}++function isCloud() {+ return getBehaveAs() === BehaveAs.CLOUD;+}++function isLocal() {+ return getBehaveAs() === BehaveAs.LOCAL;+}++function isServerSide() {+ return typeof window === "undefined";+}++function isClientSide() {+ return typeof window !== "undefined";+}++function isCAPTCHAEnabled() {+ return process.env.NEXT_PUBLIC_TURNSTILE === "enabled";+}++function areFeatureFlagsEnabled() {+ return process.env.NEXT_PUBLIC_LAUNCHDARKLY_ENABLED === "enabled";+}++function areAnalyticsEnabled(host: string) {+ return host.includes("platform.agpt.co");+}++export const environment = {+ // Generic+ getEnvironmentStr,+ // Get environment variables config+ getBehaveAs,+ getAppEnv,+ getAGPTServerApiUrl,+ getAGPTServerBaseUrl,+ getAGPTWsServerUrl,+ getSupabaseUrl,+ getSupabaseAnonKey,+ // Assertions+ isServerSide,+ isClientSide,+ isProd,+ isDev,+ isCloud,+ isLocal,+ isCAPTCHAEnabled,+ areAnalyticsEnabled,+ areFeatureFlagsEnabled,+};diff --git a/autogpt_platform/frontend/src/services/feature-flags/feature-flag-provider.tsx b/autogpt_platform/frontend/src/services/feature-flags/feature-flag-provider.tsxindex 69295cbb0f..a7bdb16dfc 100644--- a/autogpt_platform/frontend/src/services/feature-flags/feature-flag-provider.tsx+++ b/autogpt_platform/frontend/src/services/feature-flags/feature-flag-provider.tsx@@ -4,15 +4,15 @@ import { LDProvider } from "launchdarkly-react-client-sdk";import type { ReactNode } from "react";import { useMemo } from "react";import { useSupabase } from "@/lib/supabase/hooks/useSupabase";-import { BehaveAs, getBehaveAs } from "@/lib/utils";import * as Sentry from "@sentry/nextjs";+import { environment } from "../environment";const clientId = process.env.NEXT_PUBLIC_LAUNCHDARKLY_CLIENT_ID;const envEnabled = process.env.NEXT_PUBLIC_LAUNCHDARKLY_ENABLED === "true";export function LaunchDarklyProvider({ children }: { children: ReactNode }) {const { user, isUserLoading } = useSupabase();- const isCloud = getBehaveAs() === BehaveAs.CLOUD;+ const isCloud = environment.isCloud();const isLaunchDarklyConfigured = isCloud && envEnabled && clientId;const context = useMemo(() => {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.tsindex 4f15118dc2..c45c2f6f9e 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@@ -1,8 +1,8 @@"use client";import { DEFAULT_SEARCH_TERMS } from "@/app/(platform)/marketplace/components/HeroSection/helpers";-import { BehaveAs, getBehaveAs } from "@/lib/utils";import { useFlags } from "launchdarkly-react-client-sdk";+import { environment } from "../environment";export enum Flag {BETA_BLOCKS = "beta-blocks",@@ -51,7 +51,7 @@ const mockFlags = {export function useGetFlag<T extends Flag>(flag: T): FlagValues[T] | null {const currentFlags = useFlags<FlagValues>();const flagValue = currentFlags[flag];- const isCloud = getBehaveAs() === BehaveAs.CLOUD;+ const isCloud = environment.isCloud();if ((isPwMockEnabled && !isCloud) || flagValue === undefined) {return mockFlags[flag];diff --git a/autogpt_platform/frontend/src/services/storage/local-storage.ts b/autogpt_platform/frontend/src/services/storage/local-storage.tsindex 5c0eec085c..8134a7520c 100644--- a/autogpt_platform/frontend/src/services/storage/local-storage.ts+++ b/autogpt_platform/frontend/src/services/storage/local-storage.ts@@ -1,5 +1,5 @@-import { isServerSide } from "@/lib/utils/is-server-side";import * as Sentry from "@sentry/nextjs";+import { environment } from "../environment";export enum Key {LOGOUT = "supabase-logout",@@ -10,7 +10,7 @@ export enum Key {}function get(key: Key) {- if (isServerSide()) {+ if (environment.isServerSide()) {Sentry.captureException(new Error("Local storage is not available"));return;}@@ -23,7 +23,7 @@ function get(key: Key) {}function set(key: Key, value: string) {- if (isServerSide()) {+ if (environment.isServerSide()) {Sentry.captureException(new Error("Local storage is not available"));return;}@@ -31,7 +31,7 @@ function set(key: Key, value: string) {}function clean(key: Key) {- if (isServerSide()) {+ if (environment.isServerSide()) {Sentry.captureException(new Error("Local storage is not available"));return;}