Merge branch 'dev' into swiftyos/secrt-1045-ayrshare-integration

This commit is contained in:
Swifty
2025-06-16 12:01:00 +02:00
committed by GitHub
99 changed files with 2549 additions and 979 deletions

View File

@@ -127,6 +127,7 @@ TODOIST_CLIENT_SECRET=
# LLM
OPENAI_API_KEY=
ANTHROPIC_API_KEY=
AIML_API_KEY=
GROQ_API_KEY=
OPEN_ROUTER_API_KEY=
LLAMA_API_KEY=

View File

@@ -21,6 +21,7 @@ logger = logging.getLogger(__name__)
class FalModel(str, Enum):
MOCHI = "fal-ai/mochi-v1"
LUMA = "fal-ai/luma-dream-machine"
VEO3 = "fal-ai/veo3"
class AIVideoGeneratorBlock(Block):
@@ -102,6 +103,8 @@ class AIVideoGeneratorBlock(Block):
# Submit generation request
submit_url = f"{base_url}/{input_data.model.value}"
submit_data = {"prompt": input_data.prompt}
if input_data.model == FalModel.VEO3:
submit_data["generate_audio"] = True # type: ignore
seen_logs = set()

View File

@@ -31,6 +31,7 @@ logger = TruncatedLogger(logging.getLogger(__name__), "[LLM-Block]")
fmt = TextFormatter()
LLMProviderName = Literal[
ProviderName.AIML_API,
ProviderName.ANTHROPIC,
ProviderName.GROQ,
ProviderName.OLLAMA,
@@ -107,6 +108,12 @@ class LlmModel(str, Enum, metaclass=LlmModelMeta):
CLAUDE_3_5_SONNET = "claude-3-5-sonnet-latest"
CLAUDE_3_5_HAIKU = "claude-3-5-haiku-latest"
CLAUDE_3_HAIKU = "claude-3-haiku-20240307"
# AI/ML API models
AIML_API_QWEN2_5_72B = "Qwen/Qwen2.5-72B-Instruct-Turbo"
AIML_API_LLAMA3_1_70B = "nvidia/llama-3.1-nemotron-70b-instruct"
AIML_API_LLAMA3_3_70B = "meta-llama/Llama-3.3-70B-Instruct-Turbo"
AIML_API_META_LLAMA_3_1_70B = "meta-llama/Meta-Llama-3.1-70B-Instruct-Turbo"
AIML_API_LLAMA_3_2_3B = "meta-llama/Llama-3.2-3B-Instruct-Turbo"
# Groq models
GEMMA2_9B = "gemma2-9b-it"
LLAMA3_3_70B = "llama-3.3-70b-versatile"
@@ -204,6 +211,12 @@ MODEL_METADATA = {
LlmModel.CLAUDE_3_HAIKU: ModelMetadata(
"anthropic", 200000, 4096
), # claude-3-haiku-20240307
# https://docs.aimlapi.com/api-overview/model-database/text-models
LlmModel.AIML_API_QWEN2_5_72B: ModelMetadata("aiml_api", 32000, 8000),
LlmModel.AIML_API_LLAMA3_1_70B: ModelMetadata("aiml_api", 128000, 40000),
LlmModel.AIML_API_LLAMA3_3_70B: ModelMetadata("aiml_api", 128000, None),
LlmModel.AIML_API_META_LLAMA_3_1_70B: ModelMetadata("aiml_api", 131000, 2000),
LlmModel.AIML_API_LLAMA_3_2_3B: ModelMetadata("aiml_api", 128000, None),
# https://console.groq.com/docs/models
LlmModel.GEMMA2_9B: ModelMetadata("groq", 8192, None),
LlmModel.LLAMA3_3_70B: ModelMetadata("groq", 128000, 32768),
@@ -616,6 +629,29 @@ def llm_call(
prompt_tokens=response.usage.prompt_tokens if response.usage else 0,
completion_tokens=response.usage.completion_tokens if response.usage else 0,
)
elif provider == "aiml_api":
client = openai.OpenAI(
base_url="https://api.aimlapi.com/v2",
api_key=credentials.api_key.get_secret_value(),
default_headers={"X-Project": "AutoGPT"},
)
completion = client.chat.completions.create(
model=llm_model.value,
messages=prompt, # type: ignore
max_tokens=max_tokens,
)
return LLMResponse(
raw_response=completion.choices[0].message,
prompt=prompt,
response=completion.choices[0].message.content or "",
tool_calls=None,
prompt_tokens=completion.usage.prompt_tokens if completion.usage else 0,
completion_tokens=(
completion.usage.completion_tokens if completion.usage else 0
),
)
else:
raise ValueError(f"Unsupported LLM provider: {provider}")

View File

@@ -22,6 +22,7 @@ from backend.blocks.text_to_speech_block import UnrealTextToSpeechBlock
from backend.data.block import Block
from backend.data.cost import BlockCost, BlockCostType
from backend.integrations.credentials_store import (
aiml_api_credentials,
anthropic_credentials,
did_credentials,
groq_credentials,
@@ -38,7 +39,7 @@ from backend.integrations.credentials_store import (
# =============== Configure the cost for each LLM Model call =============== #
MODEL_COST: dict[LlmModel, int] = {
LlmModel.O3: 7,
LlmModel.O3: 4,
LlmModel.O3_MINI: 2, # $1.10 / $4.40
LlmModel.O1: 16, # $15 / $60
LlmModel.O1_PREVIEW: 16,
@@ -54,6 +55,11 @@ MODEL_COST: dict[LlmModel, int] = {
LlmModel.CLAUDE_3_5_SONNET: 4,
LlmModel.CLAUDE_3_5_HAIKU: 1, # $0.80 / $4.00
LlmModel.CLAUDE_3_HAIKU: 1,
LlmModel.AIML_API_QWEN2_5_72B: 1,
LlmModel.AIML_API_LLAMA3_1_70B: 1,
LlmModel.AIML_API_LLAMA3_3_70B: 1,
LlmModel.AIML_API_META_LLAMA_3_1_70B: 1,
LlmModel.AIML_API_LLAMA_3_2_3B: 1,
LlmModel.LLAMA3_8B: 1,
LlmModel.LLAMA3_70B: 1,
LlmModel.MIXTRAL_8X7B: 1,
@@ -178,6 +184,23 @@ LLM_COST = (
for model, cost in MODEL_COST.items()
if MODEL_METADATA[model].provider == "llama_api"
]
# AI/ML Api Models
+ [
BlockCost(
cost_type=BlockCostType.RUN,
cost_filter={
"model": model,
"credentials": {
"id": aiml_api_credentials.id,
"provider": aiml_api_credentials.provider,
"type": aiml_api_credentials.type,
},
},
cost_amount=cost,
)
for model, cost in MODEL_COST.items()
if MODEL_METADATA[model].provider == "aiml_api"
]
)
# =============== This is the exhaustive list of cost for each Block =============== #

View File

@@ -628,15 +628,11 @@ async def update_node_execution_stats(
data = stats.model_dump()
if isinstance(data["error"], Exception):
data["error"] = str(data["error"])
execution_status = ExecutionStatus.FAILED
else:
execution_status = ExecutionStatus.COMPLETED
res = await AgentNodeExecution.prisma().update(
where={"id": node_exec_id},
data={
"stats": Json(data),
"executionStatus": execution_status,
"endedTime": datetime.now(tz=timezone.utc),
},
include=EXECUTION_RESULT_INCLUDE,

View File

@@ -655,7 +655,10 @@ async def get_graphs(
graph_models = []
for graph in graphs:
try:
graph_models.append(GraphModel.from_db(graph))
graph_model = GraphModel.from_db(graph)
# Trigger serialization to validate that the graph is well formed.
graph_model.model_dump()
graph_models.append(graph_model)
except Exception as e:
logger.error(f"Error processing graph {graph.id}: {e}")
continue

View File

@@ -711,6 +711,44 @@ class Executor:
)
running_executions[output.node.id].add_output(output)
def drain_done_task(node_exec_id: str, result: object):
if not isinstance(result, NodeExecutionStats):
log_metadata.error(f"Unexpected result #{node_exec_id}: {type(result)}")
return
nonlocal execution_stats
execution_stats.node_count += 1
execution_stats.nodes_cputime += result.cputime
execution_stats.nodes_walltime += result.walltime
if (err := result.error) and isinstance(err, Exception):
execution_stats.node_error_count += 1
update_node_execution_status(
db_client=cls.db_client,
exec_id=node_exec_id,
status=ExecutionStatus.FAILED,
)
else:
update_node_execution_status(
db_client=cls.db_client,
exec_id=node_exec_id,
status=ExecutionStatus.COMPLETED,
)
if _graph_exec := cls.db_client.update_graph_execution_stats(
graph_exec_id=graph_exec.graph_exec_id,
status=execution_status,
stats=execution_stats,
):
send_execution_update(_graph_exec)
else:
logger.error(
"Callback for "
f"finished node execution #{node_exec_id} "
"could not update execution stats "
f"for graph execution #{graph_exec.graph_exec_id}; "
f"triggered while graph exec status = {execution_status}"
)
def cancel_handler():
nonlocal execution_status
@@ -744,38 +782,12 @@ class Executor:
execution_queue.add(node_exec.to_node_execution_entry())
running_executions: dict[str, NodeExecutionProgress] = defaultdict(
lambda: NodeExecutionProgress(drain_output_queue)
lambda: NodeExecutionProgress(
drain_output_queue=drain_output_queue,
drain_done_task=drain_done_task,
)
)
def make_exec_callback(exec_data: NodeExecutionEntry):
def callback(result: object):
if not isinstance(result, NodeExecutionStats):
return
nonlocal execution_stats
execution_stats.node_count += 1
execution_stats.nodes_cputime += result.cputime
execution_stats.nodes_walltime += result.walltime
if (err := result.error) and isinstance(err, Exception):
execution_stats.node_error_count += 1
if _graph_exec := cls.db_client.update_graph_execution_stats(
graph_exec_id=exec_data.graph_exec_id,
status=execution_status,
stats=execution_stats,
):
send_execution_update(_graph_exec)
else:
logger.error(
"Callback for "
f"finished node execution #{exec_data.node_exec_id} "
"could not update execution stats "
f"for graph execution #{exec_data.graph_exec_id}; "
f"triggered while graph exec status = {execution_status}"
)
return callback
while not execution_queue.empty():
if cancel.is_set():
execution_status = ExecutionStatus.TERMINATED
@@ -834,7 +846,6 @@ class Executor:
cls.executor.apply_async(
cls.on_node_execution,
(output_queue, queued_node_exec, node_creds_map),
callback=make_exec_callback(queued_node_exec),
),
)
@@ -850,9 +861,6 @@ class Executor:
execution_status = ExecutionStatus.TERMINATED
return execution_stats, execution_status, error
if not execution_queue.empty():
break # yield to parent loop to execute new queue items
log_metadata.debug(f"Waiting on execution of node {node_id}")
while output := execution.pop_output():
cls._process_node_output(
@@ -863,11 +871,20 @@ class Executor:
node_creds_map=node_creds_map,
execution_queue=execution_queue,
)
if not execution_queue.empty():
break # Prioritize executing next nodes than enqueuing outputs
if execution.is_done(1):
if execution.is_done():
running_executions.pop(node_id)
else:
time.sleep(0.1)
if not execution_queue.empty():
continue # Make sure each not is checked once
if execution_queue.empty() and running_executions:
log_metadata.debug(
"No more nodes to execute, waiting for outputs..."
)
time.sleep(0.1)
log_metadata.info(f"Finished graph execution {graph_exec.graph_exec_id}")
execution_status = ExecutionStatus.COMPLETED

View File

@@ -394,7 +394,8 @@ def validate_exec(
# Convert non-matching data types to the expected input schema.
for name, data_type in schema.__annotations__.items():
if (value := data.get(name)) and (type(value) is not data_type):
value = data.get(name)
if (value is not None) and (type(value) is not data_type):
data[name] = convert(value, data_type)
# Input data (without default values) should contain all required fields.
@@ -818,10 +819,15 @@ class ExecutionOutputEntry(BaseModel):
class NodeExecutionProgress:
def __init__(self, drain_output_queue: Callable[[], None]):
def __init__(
self,
drain_output_queue: Callable[[], None],
drain_done_task: Callable[[str, object], None],
):
self.output: dict[str, list[ExecutionOutputEntry]] = defaultdict(list)
self.tasks: dict[str, AsyncResult] = {}
self.drain_output_queue = drain_output_queue
self.drain_done_task = drain_done_task
def add_task(self, node_exec_id: str, task: AsyncResult):
self.tasks[node_exec_id] = task
@@ -868,7 +874,9 @@ class NodeExecutionProgress:
if self.output[exec_id]:
return False
self.tasks.pop(exec_id)
if task := self.tasks.pop(exec_id):
self.drain_done_task(exec_id, task.get())
return True
def _next_exec(self) -> str | None:

View File

@@ -61,6 +61,13 @@ openai_credentials = APIKeyCredentials(
title="Use Credits for OpenAI",
expires_at=None,
)
aiml_api_credentials = APIKeyCredentials(
id="aad82a89-9794-4ebb-977f-d736aa5260a3",
provider="aiml_api",
api_key=SecretStr(settings.secrets.aiml_api_key),
title="Use Credits for AI/ML API",
expires_at=None,
)
anthropic_credentials = APIKeyCredentials(
id="24e5d942-d9e3-4798-8151-90143ee55629",
provider="anthropic",
@@ -193,6 +200,7 @@ DEFAULT_CREDENTIALS = [
ideogram_credentials,
replicate_credentials,
openai_credentials,
aiml_api_credentials,
anthropic_credentials,
groq_credentials,
did_credentials,
@@ -256,6 +264,8 @@ class IntegrationCredentialsStore:
all_credentials.append(replicate_credentials)
if settings.secrets.openai_api_key:
all_credentials.append(openai_credentials)
if settings.secrets.aiml_api_key:
all_credentials.append(aiml_api_credentials)
if settings.secrets.anthropic_api_key:
all_credentials.append(anthropic_credentials)
if settings.secrets.did_api_key:

View File

@@ -3,6 +3,7 @@ from enum import Enum
# --8<-- [start:ProviderName]
class ProviderName(str, Enum):
AIML_API = "aiml_api"
ANTHROPIC = "anthropic"
APOLLO = "apollo"
COMPASS = "compass"

View File

@@ -126,9 +126,17 @@ def callback(
)
except Exception as e:
logger.error(f"Code->Token exchange failed for provider {provider.value}: {e}")
logger.exception(
"OAuth callback for provider %s failed during code exchange: %s. Confirm provider credentials.",
provider.value,
e,
)
raise HTTPException(
status_code=400, detail=f"Failed to exchange code for tokens: {str(e)}"
status_code=400,
detail={
"message": str(e),
"hint": "Verify OAuth configuration and try again.",
},
)
# TODO: Allow specifying `title` to set on `credentials`
@@ -297,9 +305,13 @@ async def webhook_ingress_generic(
try:
webhook = await get_webhook(webhook_id)
except NotFoundError as e:
logger.warning(f"Webhook payload received for unknown webhook: {e}")
logger.warning(
"Webhook payload received for unknown webhook %s. Confirm the webhook ID.",
webhook_id,
)
raise HTTPException(
status_code=HTTP_404_NOT_FOUND, detail=f"Webhook #{webhook_id} not found"
status_code=HTTP_404_NOT_FOUND,
detail={"message": str(e), "hint": "Check if the webhook ID is correct."},
) from e
logger.debug(f"Webhook #{webhook_id}: {webhook}")
payload, event_type = await webhook_manager.validate_payload(webhook, request)
@@ -409,11 +421,16 @@ def _get_provider_oauth_handler(
client_id = getattr(settings.secrets, f"{provider_name.value}_client_id")
client_secret = getattr(settings.secrets, f"{provider_name.value}_client_secret")
if not (client_id and client_secret):
logger.error(
"OAuth credentials for provider %s are missing. Check environment configuration.",
provider_name.value,
)
raise HTTPException(
status_code=501,
detail=(
f"Integration with provider '{provider_name.value}' is not configured"
),
detail={
"message": f"Integration with provider '{provider_name.value}' is not configured",
"hint": "Set client ID and secret in the environment.",
},
)
handler_class = HANDLERS_BY_NAME[provider_name]

View File

@@ -5,6 +5,7 @@ from typing import Any, Optional
import autogpt_libs.auth.models
import fastapi
import fastapi.responses
import pydantic
import starlette.middleware.cors
import uvicorn
from autogpt_libs.feature_flag.client import (
@@ -12,6 +13,7 @@ from autogpt_libs.feature_flag.client import (
shutdown_launchdarkly,
)
from autogpt_libs.logging.utils import generate_uvicorn_config
from fastapi.exceptions import RequestValidationError
import backend.data.block
import backend.data.db
@@ -86,11 +88,23 @@ app = fastapi.FastAPI(
def handle_internal_http_error(status_code: int = 500, log_error: bool = True):
def handler(request: fastapi.Request, exc: Exception):
if log_error:
logger.exception(f"{request.method} {request.url.path} failed: {exc}")
logger.exception(
"%s %s failed. Investigate and resolve the underlying issue: %s",
request.method,
request.url.path,
exc,
)
hint = (
"Adjust the request and retry."
if status_code < 500
else "Check server logs and dependent services."
)
return fastapi.responses.JSONResponse(
content={
"message": f"{request.method} {request.url.path} failed",
"message": f"Failed to process {request.method} {request.url.path}",
"detail": str(exc),
"hint": hint,
},
status_code=status_code,
)
@@ -98,6 +112,32 @@ def handle_internal_http_error(status_code: int = 500, log_error: bool = True):
return handler
async def validation_error_handler(
request: fastapi.Request, exc: Exception
) -> fastapi.responses.JSONResponse:
logger.error(
"Validation failed for %s %s: %s. Fix the request payload and try again.",
request.method,
request.url.path,
exc,
)
errors: list | str
if hasattr(exc, "errors"):
errors = exc.errors() # type: ignore[call-arg]
else:
errors = str(exc)
return fastapi.responses.JSONResponse(
status_code=422,
content={
"message": f"Invalid data for {request.method} {request.url.path}",
"detail": errors,
"hint": "Ensure the request matches the API schema.",
},
)
app.add_exception_handler(RequestValidationError, validation_error_handler)
app.add_exception_handler(pydantic.ValidationError, validation_error_handler)
app.add_exception_handler(ValueError, handle_internal_http_error(400))
app.add_exception_handler(Exception, handle_internal_http_error(500))
app.include_router(backend.server.routers.v1.v1_router, tags=["v1"], prefix="/api")

View File

@@ -1,5 +1,6 @@
"""Analytics API"""
import logging
from typing import Annotated
import fastapi
@@ -8,6 +9,7 @@ import backend.data.analytics
from backend.server.utils import get_user_id
router = fastapi.APIRouter()
logger = logging.getLogger(__name__)
@router.post(path="/log_raw_metric")
@@ -17,13 +19,25 @@ async def log_raw_metric(
metric_value: Annotated[float, fastapi.Body(..., embed=True)],
data_string: Annotated[str, fastapi.Body(..., embed=True)],
):
result = await backend.data.analytics.log_raw_metric(
user_id=user_id,
metric_name=metric_name,
metric_value=metric_value,
data_string=data_string,
)
return result.id
try:
result = await backend.data.analytics.log_raw_metric(
user_id=user_id,
metric_name=metric_name,
metric_value=metric_value,
data_string=data_string,
)
return result.id
except Exception as e:
logger.exception(
"Failed to log metric %s for user %s: %s", metric_name, user_id, e
)
raise fastapi.HTTPException(
status_code=500,
detail={
"message": str(e),
"hint": "Check analytics service connection and retry.",
},
)
@router.post("/log_raw_analytics")
@@ -43,7 +57,14 @@ async def log_raw_analytics(
),
],
):
result = await backend.data.analytics.log_raw_analytics(
user_id, type, data, data_index
)
return result.id
try:
result = await backend.data.analytics.log_raw_analytics(
user_id, type, data, data_index
)
return result.id
except Exception as e:
logger.exception("Failed to log analytics for user %s: %s", user_id, e)
raise fastapi.HTTPException(
status_code=500,
detail={"message": str(e), "hint": "Ensure analytics DB is reachable."},
)

View File

@@ -2,7 +2,7 @@ import logging
from typing import Annotated
from autogpt_libs.auth.middleware import APIKeyValidator
from fastapi import APIRouter, Body, Depends, Query
from fastapi import APIRouter, Body, Depends, HTTPException, Query
from fastapi.responses import JSONResponse
from backend.data.user import (
@@ -40,8 +40,11 @@ async def unsubscribe_via_one_click(token: Annotated[str, Query()]):
try:
await unsubscribe_user_by_token(token)
except Exception as e:
logger.error(f"Failed to unsubscribe user by token {token}: {e}")
raise e
logger.exception("Unsubscribe token %s failed: %s", token, e)
raise HTTPException(
status_code=500,
detail={"message": str(e), "hint": "Verify Postmark token settings."},
)
return JSONResponse(status_code=200, content={"status": "ok"})
@@ -67,7 +70,10 @@ async def postmark_webhook_handler(
case PostmarkSubscriptionChangeWebhook():
subscription_handler(webhook)
case _:
logger.warning(f"Unknown webhook type: {type(webhook)}")
logger.warning(
"Unhandled Postmark webhook type %s. Update handler mappings.",
type(webhook),
)
return
@@ -85,7 +91,10 @@ async def bounce_handler(event: PostmarkBounceWebhook):
logger.info(f"{event.Email=}")
user = await get_user_by_email(event.Email)
if not user:
logger.error(f"User not found for email: {event.Email}")
logger.warning(
"Received bounce for unknown email %s. Ensure user records are current.",
event.Email,
)
return
await set_user_email_verification(user.id, False)
logger.debug(f"Setting email verification to false for user: {user.id}")

View File

@@ -824,8 +824,15 @@ async def create_api_key(
)
return CreateAPIKeyResponse(api_key=api_key, plain_text_key=plain_text)
except APIKeyError as e:
logger.error(f"Failed to create API key: {str(e)}")
raise HTTPException(status_code=400, detail=str(e))
logger.error(
"Could not create API key for user %s: %s. Review input and permissions.",
user_id,
e,
)
raise HTTPException(
status_code=400,
detail={"message": str(e), "hint": "Verify request payload and try again."},
)
@v1_router.get(
@@ -841,8 +848,11 @@ async def get_api_keys(
try:
return await list_user_api_keys(user_id)
except APIKeyError as e:
logger.error(f"Failed to list API keys: {str(e)}")
raise HTTPException(status_code=400, detail=str(e))
logger.error("Failed to list API keys for user %s: %s", user_id, e)
raise HTTPException(
status_code=400,
detail={"message": str(e), "hint": "Check API key service availability."},
)
@v1_router.get(
@@ -861,8 +871,11 @@ async def get_api_key(
raise HTTPException(status_code=404, detail="API key not found")
return api_key
except APIKeyError as e:
logger.error(f"Failed to get API key: {str(e)}")
raise HTTPException(status_code=400, detail=str(e))
logger.error("Error retrieving API key %s for user %s: %s", key_id, user_id, e)
raise HTTPException(
status_code=400,
detail={"message": str(e), "hint": "Ensure the key ID is correct."},
)
@v1_router.delete(
@@ -883,8 +896,14 @@ async def delete_api_key(
except APIKeyPermissionError:
raise HTTPException(status_code=403, detail="Permission denied")
except APIKeyError as e:
logger.error(f"Failed to revoke API key: {str(e)}")
raise HTTPException(status_code=400, detail=str(e))
logger.error("Failed to revoke API key %s for user %s: %s", key_id, user_id, e)
raise HTTPException(
status_code=400,
detail={
"message": str(e),
"hint": "Verify permissions or try again later.",
},
)
@v1_router.post(
@@ -905,8 +924,11 @@ async def suspend_key(
except APIKeyPermissionError:
raise HTTPException(status_code=403, detail="Permission denied")
except APIKeyError as e:
logger.error(f"Failed to suspend API key: {str(e)}")
raise HTTPException(status_code=400, detail=str(e))
logger.error("Failed to suspend API key %s for user %s: %s", key_id, user_id, e)
raise HTTPException(
status_code=400,
detail={"message": str(e), "hint": "Check user permissions and retry."},
)
@v1_router.put(
@@ -929,5 +951,13 @@ async def update_permissions(
except APIKeyPermissionError:
raise HTTPException(status_code=403, detail="Permission denied")
except APIKeyError as e:
logger.error(f"Failed to update API key permissions: {str(e)}")
raise HTTPException(status_code=400, detail=str(e))
logger.error(
"Failed to update permissions for API key %s of user %s: %s",
key_id,
user_id,
e,
)
raise HTTPException(
status_code=400,
detail={"message": str(e), "hint": "Ensure permissions list is valid."},
)

View File

@@ -70,10 +70,10 @@ async def list_library_agents(
page_size=page_size,
)
except Exception as e:
logger.error(f"Could not fetch library agents: {e}")
logger.exception("Listing library agents failed for user %s: %s", user_id, e)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Failed to get library agents",
detail={"message": str(e), "hint": "Inspect database connectivity."},
) from e
@@ -102,10 +102,17 @@ async def get_library_agent_by_store_listing_version_id(
store_listing_version_id, user_id
)
except Exception as e:
logger.error(f"Could not fetch library agent from store version ID: {e}")
logger.exception(
"Retrieving library agent by store version failed for user %s: %s",
user_id,
e,
)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Failed to add agent to library",
detail={
"message": str(e),
"hint": "Check if the store listing ID is valid.",
},
) from e
@@ -143,22 +150,31 @@ async def add_marketplace_agent_to_library(
)
except store_exceptions.AgentNotFoundError:
logger.warning(f"Agent not found: {store_listing_version_id}")
logger.warning(
"Store listing version %s not found when adding to library",
store_listing_version_id,
)
raise HTTPException(
status_code=404,
detail=f"Store listing version {store_listing_version_id} not found",
detail={
"message": f"Store listing version {store_listing_version_id} not found",
"hint": "Confirm the ID provided.",
},
)
except store_exceptions.DatabaseError as e:
logger.error(f"Database error occurred whilst adding agent to library: {e}")
logger.exception("Database error whilst adding agent to library: %s", e)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Failed to add agent to library",
detail={"message": str(e), "hint": "Inspect DB logs for details."},
) from e
except Exception as e:
logger.error(f"Unexpected error while adding agent: {e}")
logger.exception("Unexpected error while adding agent to library: %s", e)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Failed to add agent to library",
detail={
"message": str(e),
"hint": "Check server logs for more information.",
},
) from e
@@ -203,16 +219,16 @@ async def update_library_agent(
content={"message": "Agent updated successfully"},
)
except store_exceptions.DatabaseError as e:
logger.exception(f"Database error while updating library agent: {e}")
logger.exception("Database error while updating library agent: %s", e)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Failed to update library agent",
detail={"message": str(e), "hint": "Verify DB connection."},
) from e
except Exception as e:
logger.exception(f"Unexpected error while updating library agent: {e}")
logger.exception("Unexpected error while updating library agent: %s", e)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Failed to update library agent",
detail={"message": str(e), "hint": "Check server logs."},
) from e

View File

@@ -47,10 +47,13 @@ async def list_presets(
page_size=page_size,
)
except Exception as e:
logger.exception(f"Exception occurred while getting presets: {e}")
logger.exception("Failed to list presets for user %s: %s", user_id, e)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Failed to get presets",
detail={
"message": str(e),
"hint": "Ensure the presets DB table is accessible.",
},
)
@@ -85,10 +88,12 @@ async def get_preset(
)
return preset
except Exception as e:
logger.exception(f"Exception occurred whilst getting preset: {e}")
logger.exception(
"Error retrieving preset %s for user %s: %s", preset_id, user_id, e
)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Failed to get preset",
detail={"message": str(e), "hint": "Validate preset ID and retry."},
)
@@ -125,10 +130,10 @@ async def create_preset(
except NotFoundError as e:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e))
except Exception as e:
logger.exception(f"Exception occurred while creating preset: {e}")
logger.exception("Preset creation failed for user %s: %s", user_id, e)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Failed to create preset",
detail={"message": str(e), "hint": "Check preset payload format."},
)
@@ -161,10 +166,10 @@ async def update_preset(
user_id=user_id, preset_id=preset_id, preset=preset
)
except Exception as e:
logger.exception(f"Exception occurred whilst updating preset: {e}")
logger.exception("Preset update failed for user %s: %s", user_id, e)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Failed to update preset",
detail={"message": str(e), "hint": "Check preset data and try again."},
)
@@ -191,10 +196,12 @@ async def delete_preset(
try:
await db.delete_preset(user_id, preset_id)
except Exception as e:
logger.exception(f"Exception occurred whilst deleting preset: {e}")
logger.exception(
"Error deleting preset %s for user %s: %s", preset_id, user_id, e
)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Failed to delete preset",
detail={"message": str(e), "hint": "Ensure preset exists before deleting."},
)
@@ -252,8 +259,11 @@ async def execute_preset(
except HTTPException:
raise
except Exception as e:
logger.exception(f"Exception occurred while executing preset: {e}")
logger.exception("Preset execution failed for user %s: %s", user_id, e)
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=str(e),
detail={
"message": str(e),
"hint": "Review preset configuration and graph ID.",
},
)

View File

@@ -1,7 +1,7 @@
import logging
from autogpt_libs.auth.middleware import auth_middleware
from fastapi import APIRouter, Depends
from fastapi import APIRouter, Depends, HTTPException
from backend.server.utils import get_user_id
@@ -23,4 +23,12 @@ async def proxy_otto_request(
Proxy requests to Otto API while adding necessary security headers and logging.
Requires an authenticated user.
"""
return await OttoService.ask(request, user_id)
logger.debug("Forwarding request to Otto for user %s", user_id)
try:
return await OttoService.ask(request, user_id)
except Exception as e:
logger.exception("Otto request failed for user %s: %s", user_id, e)
raise HTTPException(
status_code=502,
detail={"message": str(e), "hint": "Check Otto service status."},
)

View File

@@ -48,11 +48,14 @@ async def get_profile(
content={"detail": "Profile not found"},
)
return profile
except Exception:
logger.exception("Exception occurred whilst getting user profile")
except Exception as e:
logger.exception("Failed to fetch user profile for %s: %s", user_id, e)
return fastapi.responses.JSONResponse(
status_code=500,
content={"detail": "An error occurred while retrieving the user profile"},
content={
"detail": "Failed to retrieve user profile",
"hint": "Check database connection.",
},
)
@@ -86,11 +89,14 @@ async def update_or_create_profile(
user_id=user_id, profile=profile
)
return updated_profile
except Exception:
logger.exception("Exception occurred whilst updating profile")
except Exception as e:
logger.exception("Failed to update profile for user %s: %s", user_id, e)
return fastapi.responses.JSONResponse(
status_code=500,
content={"detail": "An error occurred while updating the user profile"},
content={
"detail": "Failed to update user profile",
"hint": "Validate request data.",
},
)
@@ -160,11 +166,14 @@ async def get_agents(
page_size=page_size,
)
return agents
except Exception:
logger.exception("Exception occured whilst getting store agents")
except Exception as e:
logger.exception("Failed to retrieve store agents: %s", e)
return fastapi.responses.JSONResponse(
status_code=500,
content={"detail": "An error occurred while retrieving the store agents"},
content={
"detail": "Failed to retrieve store agents",
"hint": "Check database or search parameters.",
},
)

View File

@@ -35,7 +35,9 @@ async def verify_token(request: TurnstileVerifyRequest) -> TurnstileVerifyRespon
turnstile_verify_url = settings.secrets.turnstile_verify_url
if not turnstile_secret_key:
logger.error("Turnstile secret key is not configured")
logger.error(
"Turnstile secret key missing. Set TURNSTILE_SECRET_KEY to enable verification."
)
return TurnstileVerifyResponse(
success=False,
error="CONFIGURATION_ERROR",

View File

@@ -3,6 +3,7 @@ import logging
from contextlib import asynccontextmanager
from typing import Protocol
import pydantic
import uvicorn
from autogpt_libs.auth import parse_jwt_token
from autogpt_libs.logging.utils import generate_uvicorn_config
@@ -51,7 +52,11 @@ async def event_broadcaster(manager: ConnectionManager):
async for event in event_queue.listen("*"):
await manager.send_execution_update(event)
except Exception as e:
logger.exception(f"Event broadcaster error: {e}")
logger.exception(
"Event broadcaster stopped due to error: %s. "
"Verify the Redis connection and restart the service.",
e,
)
raise
@@ -221,7 +226,22 @@ async def websocket_router(
try:
while True:
data = await websocket.receive_text()
message = WSMessage.model_validate_json(data)
try:
message = WSMessage.model_validate_json(data)
except pydantic.ValidationError as e:
logger.error(
"Invalid WebSocket message from user #%s: %s",
user_id,
e,
)
await websocket.send_text(
WSMessage(
method=WSMethod.ERROR,
success=False,
error=("Invalid message format. Review the schema and retry"),
).model_dump_json()
)
continue
try:
if message.method in _MSG_HANDLERS:
@@ -232,6 +252,21 @@ async def websocket_router(
message=message,
)
continue
except pydantic.ValidationError as e:
logger.error(
"Validation error while handling '%s' for user #%s: %s",
message.method.value,
user_id,
e,
)
await websocket.send_text(
WSMessage(
method=WSMethod.ERROR,
success=False,
error="Invalid message data. Refer to the API schema",
).model_dump_json()
)
continue
except Exception as e:
logger.error(
f"Error while handling '{message.method.value}' message "

View File

@@ -385,6 +385,7 @@ class Secrets(UpdateTrackingModel["Secrets"], BaseSettings):
)
openai_api_key: str = Field(default="", description="OpenAI API key")
aiml_api_key: str = Field(default="", description="'AI/ML API' key")
anthropic_api_key: str = Field(default="", description="Anthropic API key")
groq_api_key: str = Field(default="", description="Groq API key")
open_router_api_key: str = Field(default="", description="Open Router API Key")

View File

@@ -8,13 +8,14 @@ const config: StorybookConfig = {
"@storybook/addon-links",
"@storybook/addon-essentials",
"@storybook/addon-interactions",
"@storybook/addon-docs",
],
features: {
experimentalRSC: true,
},
framework: {
name: "@storybook/nextjs",
options: {},
options: { builder: { useSWC: true } },
},
staticDirs: ["../public"],
};

View File

@@ -0,0 +1,7 @@
import { addons } from "@storybook/manager-api";
import { theme } from "./theme";
addons.setConfig({
theme: theme,
});

View File

@@ -3,6 +3,16 @@ import type { Preview } from "@storybook/react";
import { initialize, mswLoader } from "msw-storybook-addon";
import "../src/app/globals.css";
import "../src/components/styles/fonts.css";
import {
Controls,
Description,
Primary,
Source,
Stories,
Subtitle,
Title,
} from "@storybook/blocks";
import { theme } from "./theme";
// Initialize MSW
initialize();
@@ -12,19 +22,27 @@ const preview: Preview = {
nextjs: {
appDirectory: true,
},
controls: {
matchers: {
color: /(background|color)$/i,
date: /Date$/i,
},
docs: {
theme,
page: () => (
<>
<Title />
<Subtitle />
<Description />
<Primary />
<Source />
<Stories />
<Controls />
</>
),
},
},
loaders: [mswLoader],
decorators: [
(Story) => (
<>
<div className="bg-background p-8">
<Story />
</>
</div>
),
],
};

View File

@@ -0,0 +1,9 @@
import { create } from "@storybook/theming/create";
export const theme = create({
base: "light",
brandTitle: "AutoGPT Platform",
brandUrl: "https://autogpt.com",
brandTarget: "_self",
brandImage: "/storybook/autogpt-logo-storybook.png",
});

View File

@@ -2,61 +2,64 @@
// 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 { getEnvironmentStr } from "@/lib/utils";
import { BehaveAs, getBehaveAs, getEnvironmentStr } from "@/lib/utils";
import * as Sentry from "@sentry/nextjs";
if (process.env.NODE_ENV === "production") {
Sentry.init({
dsn: "https://fe4e4aa4a283391808a5da396da20159@o4505260022104064.ingest.us.sentry.io/4507946746380288",
const isProductionCloud =
process.env.NODE_ENV === "production" && getBehaveAs() === BehaveAs.CLOUD;
environment: getEnvironmentStr(),
Sentry.init({
dsn: "https://fe4e4aa4a283391808a5da396da20159@o4505260022104064.ingest.us.sentry.io/4507946746380288",
// Add optional integrations for additional features
integrations: [
Sentry.replayIntegration(),
Sentry.httpClientIntegration(),
Sentry.replayCanvasIntegration(),
Sentry.reportingObserverIntegration(),
Sentry.browserProfilingIntegration(),
// Sentry.feedbackIntegration({
// // Additional SDK configuration goes in here, for example:
// colorScheme: "system",
// }),
],
environment: getEnvironmentStr(),
// Define how likely traces are sampled. Adjust this value in production, or use tracesSampler for greater control.
tracesSampleRate: 1,
enabled: isProductionCloud,
// Set `tracePropagationTargets` to control for which URLs trace propagation should be enabled
tracePropagationTargets: [
"localhost",
"localhost:8006",
/^https:\/\/dev\-builder\.agpt\.co\/api/,
/^https:\/\/.*\.agpt\.co\/api/,
],
// Add optional integrations for additional features
integrations: [
Sentry.replayIntegration(),
Sentry.httpClientIntegration(),
Sentry.replayCanvasIntegration(),
Sentry.reportingObserverIntegration(),
Sentry.browserProfilingIntegration(),
// Sentry.feedbackIntegration({
// // Additional SDK configuration goes in here, for example:
// colorScheme: "system",
// }),
],
// Define how likely Replay events are sampled.
// This sets the sample rate to be 10%. You may want this to be 100% while
// in development and sample at a lower rate in production
replaysSessionSampleRate: 0.1,
// Define how likely traces are sampled. Adjust this value in production, or use tracesSampler for greater control.
tracesSampleRate: 1,
// Define how likely Replay events are sampled when an error occurs.
replaysOnErrorSampleRate: 1.0,
// Set `tracePropagationTargets` to control for which URLs trace propagation should be enabled
tracePropagationTargets: [
"localhost",
"localhost:8006",
/^https:\/\/dev\-builder\.agpt\.co\/api/,
/^https:\/\/.*\.agpt\.co\/api/,
],
// Setting this option to true will print useful information to the console while you're setting up Sentry.
debug: false,
// Define how likely Replay events are sampled.
// This sets the sample rate to be 10%. You may want this to be 100% while
// in development and sample at a lower rate in production
replaysSessionSampleRate: 0.1,
// Set profilesSampleRate to 1.0 to profile every transaction.
// Since profilesSampleRate is relative to tracesSampleRate,
// the final profiling rate can be computed as tracesSampleRate * profilesSampleRate
// For example, a tracesSampleRate of 0.5 and profilesSampleRate of 0.5 would
// result in 25% of transactions being profiled (0.5*0.5=0.25)
profilesSampleRate: 1.0,
_experiments: {
// Enable logs to be sent to Sentry.
enableLogs: true,
},
});
}
// Define how likely Replay events are sampled when an error occurs.
replaysOnErrorSampleRate: 1.0,
// Setting this option to true will print useful information to the console while you're setting up Sentry.
debug: false,
// Set profilesSampleRate to 1.0 to profile every transaction.
// Since profilesSampleRate is relative to tracesSampleRate,
// the final profiling rate can be computed as tracesSampleRate * profilesSampleRate
// For example, a tracesSampleRate of 0.5 and profilesSampleRate of 0.5 would
// result in 25% of transactions being profiled (0.5*0.5=0.25)
profilesSampleRate: 1.0,
_experiments: {
// Enable logs to be sent to Sentry.
enableLogs: true,
},
});
export const onRouterTransitionStart = Sentry.captureRouterTransitionStart;

View File

@@ -25,7 +25,7 @@
],
"dependencies": {
"@faker-js/faker": "9.8.0",
"@hookform/resolvers": "3.10.0",
"@hookform/resolvers": "5.1.1",
"@next/third-parties": "15.3.3",
"@radix-ui/react-alert-dialog": "1.1.14",
"@radix-ui/react-avatar": "1.1.10",
@@ -46,9 +46,9 @@
"@radix-ui/react-tabs": "1.1.12",
"@radix-ui/react-toast": "1.2.14",
"@radix-ui/react-tooltip": "1.2.7",
"@sentry/nextjs": "9.26.0",
"@sentry/nextjs": "9.27.0",
"@supabase/ssr": "0.6.1",
"@supabase/supabase-js": "2.49.10",
"@supabase/supabase-js": "2.50.0",
"@tanstack/react-table": "8.21.3",
"@types/jaro-winkler": "0.2.4",
"@xyflow/react": "12.6.4",
@@ -86,25 +86,28 @@
"tailwind-merge": "2.6.0",
"tailwindcss-animate": "1.0.7",
"uuid": "11.1.0",
"zod": "3.25.51"
"zod": "3.25.56"
},
"devDependencies": {
"@chromatic-com/storybook": "3.2.4",
"@chromatic-com/storybook": "3.2.6",
"@playwright/test": "1.52.0",
"@storybook/addon-a11y": "8.6.14",
"@storybook/addon-docs": "8.6.14",
"@storybook/addon-essentials": "8.6.14",
"@storybook/addon-interactions": "8.6.14",
"@storybook/addon-links": "8.6.14",
"@storybook/addon-onboarding": "8.6.14",
"@storybook/blocks": "8.6.14",
"@storybook/manager-api": "8.6.14",
"@storybook/nextjs": "8.6.14",
"@storybook/react": "8.6.14",
"@storybook/test": "8.6.14",
"@storybook/test-runner": "0.22.0",
"@storybook/test-runner": "0.22.1",
"@storybook/theming": "8.6.14",
"@types/canvas-confetti": "1.9.0",
"@types/lodash": "4.17.17",
"@types/negotiator": "0.6.3",
"@types/node": "22.15.29",
"@types/negotiator": "0.6.4",
"@types/node": "22.15.30",
"@types/react": "18.3.17",
"@types/react-dom": "18.3.5",
"@types/react-modal": "3.16.3",
@@ -114,11 +117,13 @@
"eslint": "8.57.1",
"eslint-config-next": "15.3.3",
"eslint-plugin-storybook": "0.12.0",
"msw": "2.9.0",
"msw-storybook-addon": "2.0.4",
"import-in-the-middle": "1.14.0",
"msw": "2.10.2",
"msw-storybook-addon": "2.0.5",
"postcss": "8.5.4",
"prettier": "3.5.3",
"prettier-plugin-tailwindcss": "0.6.12",
"require-in-the-middle": "7.5.2",
"storybook": "8.6.14",
"tailwindcss": "3.4.17",
"typescript": "5.8.3"

File diff suppressed because it is too large Load Diff

Binary file not shown.

Before

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 374 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 51 KiB

View File

Before

Width:  |  Height:  |  Size: 2.3 KiB

After

Width:  |  Height:  |  Size: 2.3 KiB

View File

@@ -0,0 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" fill="none" viewBox="0 0 32 32">
<path fill="#1E88E5" d="M31.3313 8.44657C30.9633 7.08998 29.8791 6.02172 28.5022 5.65916C26.0067 5.00026 16 5.00026 16 5.00026C16 5.00026 5.99333 5.00026 3.4978 5.65916C2.12102 6.02172 1.03665 7.08998 0.668678 8.44657C0 10.9053 0 16.0353 0 16.0353C0 16.0353 0 21.1652 0.668678 23.6242C1.03665 24.9806 2.12102 26.0489 3.4978 26.4116C5.99333 27.0703 16 27.0703 16 27.0703C16 27.0703 26.0067 27.0703 28.5022 26.4116C29.8791 26.0489 30.9633 24.9806 31.3313 23.6242C32 21.1652 32 16.0353 32 16.0353C32 16.0353 32 10.9053 31.3313 8.44657Z"/>
<path fill="#fff" d="M11 10H20V22H11V10ZM13 12V13H18V12H13ZM13 15V16H18V15H13ZM13 18V19H18V18H13Z"/>
</svg>

After

Width:  |  Height:  |  Size: 743 B

View File

Before

Width:  |  Height:  |  Size: 2.7 KiB

After

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 300 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 284 KiB

View File

Before

Width:  |  Height:  |  Size: 716 B

After

Width:  |  Height:  |  Size: 716 B

View File

@@ -4,13 +4,18 @@
// https://docs.sentry.io/platforms/javascript/guides/nextjs/
import * as Sentry from "@sentry/nextjs";
import { getEnvironmentStr } from "./src/lib/utils";
import { BehaveAs, getBehaveAs, getEnvironmentStr } from "./src/lib/utils";
const isProductionCloud =
process.env.NODE_ENV === "production" && getBehaveAs() === BehaveAs.CLOUD;
Sentry.init({
dsn: "https://fe4e4aa4a283391808a5da396da20159@o4505260022104064.ingest.us.sentry.io/4507946746380288",
environment: getEnvironmentStr(),
enabled: isProductionCloud,
// Define how likely traces are sampled. Adjust this value in production, or use tracesSampler for greater control.
tracesSampleRate: 1,
tracePropagationTargets: [

View File

@@ -2,15 +2,20 @@
// The config you add here will be used whenever the server handles a request.
// https://docs.sentry.io/platforms/javascript/guides/nextjs/
import { getEnvironmentStr } from "@/lib/utils";
import { BehaveAs, getBehaveAs, getEnvironmentStr } from "@/lib/utils";
import * as Sentry from "@sentry/nextjs";
// import { NodeProfilingIntegration } from "@sentry/profiling-node";
const isProductionCloud =
process.env.NODE_ENV === "production" && getBehaveAs() === BehaveAs.CLOUD;
Sentry.init({
dsn: "https://fe4e4aa4a283391808a5da396da20159@o4505260022104064.ingest.us.sentry.io/4507946746380288",
environment: getEnvironmentStr(),
enabled: isProductionCloud,
// Define how likely traces are sampled. Adjust this value in production, or use tracesSampler for greater control.
tracesSampleRate: 1,
tracePropagationTargets: [

View File

@@ -1,4 +1,4 @@
import getServerSupabase from "@/lib/supabase/getServerSupabase";
import { getServerSupabase } from "@/lib/supabase/server/getServerSupabase";
import BackendAPI from "@/lib/autogpt-server-api";
import { NextResponse } from "next/server";
import { revalidatePath } from "next/cache";

View File

@@ -2,7 +2,7 @@ import { type EmailOtpType } from "@supabase/supabase-js";
import { type NextRequest } from "next/server";
import { redirect } from "next/navigation";
import getServerSupabase from "@/lib/supabase/getServerSupabase";
import { getServerSupabase } from "@/lib/supabase/server/getServerSupabase";
// Email confirmation route
export async function GET(request: NextRequest) {

View File

@@ -3,7 +3,7 @@ import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { z } from "zod";
import * as Sentry from "@sentry/nextjs";
import getServerSupabase from "@/lib/supabase/getServerSupabase";
import { getServerSupabase } from "@/lib/supabase/server/getServerSupabase";
import BackendAPI from "@/lib/autogpt-server-api";
import { loginFormSchema, LoginProvider } from "@/types/auth";
import { verifyTurnstileToken } from "@/lib/turnstile";

View File

@@ -1,5 +1,5 @@
import { useTurnstile } from "@/hooks/useTurnstile";
import useSupabase from "@/lib/supabase/useSupabase";
import { useSupabase } from "@/lib/supabase/hooks/useSupabase";
import { loginFormSchema, LoginProvider } from "@/types/auth";
import { zodResolver } from "@hookform/resolvers/zod";
import { useRouter } from "next/navigation";

View File

@@ -6,7 +6,7 @@ import { AgentsSection } from "@/components/agptui/composite/AgentsSection";
import { BecomeACreator } from "@/components/agptui/BecomeACreator";
import { Separator } from "@/components/ui/separator";
import { Metadata } from "next";
import getServerUser from "@/lib/supabase/getServerUser";
import { getServerUser } from "@/lib/supabase/server/getServerUser";
// Force dynamic rendering to avoid static generation issues with cookies
export const dynamic = "force-dynamic";

View File

@@ -11,7 +11,7 @@ import {
StoreSubmissionsResponse,
StoreSubmissionRequest,
} from "@/lib/autogpt-server-api/types";
import useSupabase from "@/lib/supabase/useSupabase";
import { useSupabase } from "@/lib/supabase/hooks/useSupabase";
import { useBackendAPI } from "@/lib/autogpt-server-api/context";
export default function Page({}: {}) {

View File

@@ -26,7 +26,7 @@ import {
AlertDialogHeader,
AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import useSupabase from "@/lib/supabase/useSupabase";
import { useSupabase } from "@/lib/supabase/hooks/useSupabase";
import LoadingBox from "@/components/ui/loading";
export default function UserIntegrationsPage() {
@@ -103,6 +103,7 @@ export default function UserIntegrationsPage() {
"6b9fc200-4726-4973-86c9-cd526f5ce5db", // Replicate
"53c25cb8-e3ee-465c-a4d1-e75a4c899c2a", // OpenAI
"24e5d942-d9e3-4798-8151-90143ee55629", // Anthropic
"aad82a89-9794-4ebb-977f-d736aa5260a3", // AI/ML
"4ec22295-8f97-4dd1-b42b-2c6957a02545", // Groq
"7f7b0654-c36b-4565-8fa7-9a52575dfae2", // D-ID
"7f26de70-ba0d-494e-ba76-238e65e7b45f", // Jina

View File

@@ -1,7 +1,7 @@
"use server";
import { revalidatePath } from "next/cache";
import getServerSupabase from "@/lib/supabase/getServerSupabase";
import { getServerSupabase } from "@/lib/supabase/server/getServerSupabase";
import BackendApi from "@/lib/autogpt-server-api";
import { NotificationPreferenceDTO } from "@/lib/autogpt-server-api/types";

View File

@@ -1,7 +1,7 @@
import * as React from "react";
import { Metadata } from "next";
import SettingsForm from "@/components/profile/settings/SettingsForm";
import getServerUser from "@/lib/supabase/getServerUser";
import { getServerUser } from "@/lib/supabase/server/getServerUser";
import { redirect } from "next/navigation";
import { getUserPreferences } from "./actions";

View File

@@ -1,5 +1,5 @@
"use server";
import getServerSupabase from "@/lib/supabase/getServerSupabase";
import { getServerSupabase } from "@/lib/supabase/server/getServerSupabase";
import { redirect } from "next/navigation";
import * as Sentry from "@sentry/nextjs";
import { verifyTurnstileToken } from "@/lib/turnstile";
@@ -64,7 +64,7 @@ export async function changePassword(password: string, turnstileToken: string) {
return error.message;
}
await supabase.auth.signOut();
await supabase.auth.signOut({ scope: "global" });
redirect("/login");
},
);

View File

@@ -17,7 +17,7 @@ import {
FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import useSupabase from "@/lib/supabase/useSupabase";
import { useSupabase } from "@/lib/supabase/hooks/useSupabase";
import { sendEmailFormSchema, changePasswordFormSchema } from "@/types/auth";
import { zodResolver } from "@hookform/resolvers/zod";
import { useCallback, useState } from "react";

View File

@@ -3,7 +3,7 @@ import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { z } from "zod";
import * as Sentry from "@sentry/nextjs";
import getServerSupabase from "@/lib/supabase/getServerSupabase";
import { getServerSupabase } from "@/lib/supabase/server/getServerSupabase";
import { signupFormSchema } from "@/types/auth";
import BackendAPI from "@/lib/autogpt-server-api";
import { verifyTurnstileToken } from "@/lib/turnstile";

View File

@@ -1,5 +1,5 @@
import { useTurnstile } from "@/hooks/useTurnstile";
import useSupabase from "@/lib/supabase/useSupabase";
import { useSupabase } from "@/lib/supabase/hooks/useSupabase";
import { signupFormSchema, LoginProvider } from "@/types/auth";
import { zodResolver } from "@hookform/resolvers/zod";
import { useRouter } from "next/navigation";

View File

@@ -1,5 +1,5 @@
// components/RoleBasedAccess.tsx
import useSupabase from "@/lib/supabase/useSupabase";
import { useSupabase } from "@/lib/supabase/hooks/useSupabase";
import React from "react";
interface RoleBasedAccessProps {

View File

@@ -0,0 +1,169 @@
import type { Meta, StoryObj } from "@storybook/react";
import { Text, textVariants, type TextVariant } from "./Text";
import { StoryCode } from "@/stories/helpers/StoryCode";
const meta: Meta<typeof Text> = {
title: "Design System/Atoms/Text",
component: Text,
tags: ["autodocs"],
parameters: {
layout: "fullscreen",
controls: { hideNoControlsWarning: true },
docs: {
description: {
component:
"A flexible Text component that supports all typography variants from our design system. Uses Poppins for headings and Geist Sans for body text.",
},
source: {
state: "open",
},
},
},
argTypes: {
variant: {
control: { type: "select" },
options: textVariants,
description: "Typography variant to apply",
},
as: {
control: { type: "select" },
options: ["h1", "h2", "h3", "h4", "h5", "h6", "p", "span", "div", "code"],
description: "HTML element to render as",
},
children: {
control: "text",
description: "Text content",
},
},
};
export default meta;
type Story = StoryObj<typeof Text>;
//=============================================================================
// All Variants Overview
//=============================================================================
export function AllVariants() {
return (
<div className="space-y-8">
{/* Headings */}
<div className="mb-19 mb-20 space-y-6">
<h2 className="mb-4 border-b border-border pb-2 text-xl text-zinc-500">
Headings
</h2>
<Text variant="h1">Heading 1</Text>
<Text variant="h2">Heading 2</Text>
<Text variant="h3">Heading 3</Text>
<Text variant="h4">Heading 4</Text>
<StoryCode
code={`<Text variant="h1">Heading 1</Text>
<Text variant="h2">Heading 2</Text>
<Text variant="h3">Heading 3</Text>
<Text variant="h4">Heading 4</Text>`}
/>
</div>
{/* Body Text */}
<h2 className="mb-4 border-b border-border pb-2 text-xl text-zinc-500">
Body Text
</h2>
<Text variant="lead">Lead</Text>
<StoryCode code={`<Text variant="lead">Lead</Text>`} />
<div className="flex flex-row gap-8">
<Text variant="large">Large</Text>
<Text variant="large-medium">Large Medium</Text>
<Text variant="large-semibold">Large Semibold</Text>
</div>
<StoryCode
code={`<Text variant="large">Large</Text>
<Text variant="large-medium">Large Medium</Text>
<Text variant="large-semibold">Large Semibold</Text>`}
/>
<div className="flex flex-row gap-8">
<Text variant="body">Body</Text>
<Text variant="body-medium">Body Medium</Text>
</div>
<StoryCode
code={`<Text variant="body">Body</Text>
<Text variant="body-medium">Body Medium</Text>`}
/>
<div className="flex flex-row gap-8">
<Text variant="small">Small</Text>
<Text variant="small-medium">Small Medium</Text>
</div>
<StoryCode
code={`<Text variant="small">Small</Text>
<Text variant="small-medium">Small Medium</Text>`}
/>
<Text variant="subtle">Subtle</Text>
<StoryCode code={`<Text variant="subtle">Subtle</Text>`} />
</div>
);
}
//=============================================================================
// Headings Only
//=============================================================================
export function Headings() {
return (
<div className="space-y-8">
<Text variant="h1">Heading 1</Text>
<Text variant="h2">Heading 2</Text>
<Text variant="h3">Heading 3</Text>
<Text variant="h4">Heading 4</Text>
</div>
);
}
//=============================================================================
// Body Text Only
//=============================================================================
export function BodyText() {
return (
<div className="space-y-8">
<Text variant="lead">Lead</Text>
<Text variant="large">Large</Text>
<Text variant="large-medium">Large Medium</Text>
<Text variant="large-semibold">Large Semibold</Text>
<Text variant="body">Body</Text>
<Text variant="body-medium">Body Medium</Text>
<Text variant="small">Small</Text>
<Text variant="small-medium">Small Medium</Text>
<Text variant="subtle">Subtle</Text>
</div>
);
}
//=============================================================================
// Interactive Playground
//=============================================================================
export const Playground: Story = {
args: {
variant: "body",
children:
"Edit this text and try different variants via the controls below",
},
parameters: {
controls: { include: ["variant", "as", "children"] },
},
render: (args) => (
<div className="space-y-8">
<Text {...args} />
</div>
),
};
//=============================================================================
// Custom Element
//=============================================================================
export function CustomElement() {
return (
<div className="space-y-8">
<Text variant="h3" as="div">
H3 size rendered as div
</Text>
<Text variant="body" as="h2">
Body size rendered as h2
</Text>
</div>
);
}

View File

@@ -0,0 +1,37 @@
import React from "react";
import { As, Variant, variantElementMap, variants } from "./helpers";
type CustomProps = {
variant: Variant;
as?: As;
className?: string;
};
export type TextProps = React.PropsWithChildren<
CustomProps & React.ComponentPropsWithoutRef<"p">
>;
export function Text({
children,
variant,
as: outerAs,
className = "",
...rest
}: TextProps) {
const variantClasses = variants[variant] || variants.body;
const Element = outerAs || variantElementMap[variant];
const combinedClassName = `${variantClasses} ${className}`.trim();
return React.createElement(
Element,
{
className: combinedClassName,
...rest,
},
children,
);
}
// Export variant names for use in stories
export const textVariants = Object.keys(variants) as Variant[];
export type TextVariant = Variant;

View File

@@ -0,0 +1,53 @@
export type As =
| "h1"
| "h2"
| "h3"
| "h4"
| "h5"
| "h6"
| "p"
| "span"
| "div"
| "code"
| "label"
| "kbd";
export const variants = {
// Headings
h1: "font-poppins text-5xl font-semibold leading-[56px] text-zinc-800",
h2: "font-poppins text-4xl font-normal leading-[52px] text-zinc-800",
h3: "font-poppins text-3xl font-medium leading-10 text-zinc-800",
h4: "font-poppins text-base font-medium leading-normal text-zinc-800",
// Body Text
lead: "font-sans text-xl font-normal leading-loose text-muted-zinc-800",
large: "font-sans text-base font-normal leading-normal text-zinc-800",
"large-medium":
"font-sans text-base font-medium leading-normal text-zinc-800",
"large-semibold":
"font-sans text-base font-semibold leading-normal text-zinc-800",
body: "font-sans text-sm font-normal leading-snug text-zinc-800",
"body-medium": "font-sans text-sm font-medium leading-snug text-zinc-800",
small: "font-sans text-xs font-normal leading-tight text-zinc-800",
"small-medium": "font-sans text-xs font-medium leading-tight text-zinc-800",
subtle:
"font-sans text-xs font-medium uppercase leading-tight tracking-wide text-zinc-800",
} as const;
export type Variant = keyof typeof variants;
export const variantElementMap: Record<Variant, As> = {
h1: "h1",
h2: "h2",
h3: "h3",
h4: "h4",
lead: "p",
large: "p",
"large-medium": "p",
"large-semibold": "p",
body: "p",
"body-medium": "p",
small: "p",
"small-medium": "p",
subtle: "p",
};

View File

@@ -40,7 +40,7 @@ export const FeaturedAgentCard: React.FC<FeaturedStoreCardProps> = ({
<CardContent className="flex-1 p-4">
<div className="relative aspect-[4/3] w-full overflow-hidden rounded-xl">
<Image
src={agent.agent_image || "/AUTOgpt_Logo_dark.png"}
src={agent.agent_image || "/autogpt-logo-dark-bg.png"}
alt={`${agent.agent_name} preview`}
fill
sizes="100%"

View File

@@ -7,8 +7,9 @@ import { Button } from "./Button";
import Wallet from "./Wallet";
import { ProfileDetails } from "@/lib/autogpt-server-api/types";
import { NavbarLink } from "./NavbarLink";
import getServerUser from "@/lib/supabase/getServerUser";
import BackendAPI from "@/lib/autogpt-server-api";
import { getServerUser } from "@/lib/supabase/server/getServerUser";
// Disable theme toggle for now
// import { ThemeToggle } from "./ThemeToggle";

View File

@@ -9,7 +9,7 @@ import { Button } from "./Button";
import { IconPersonFill } from "@/components/ui/icons";
import { ProfileDetails } from "@/lib/autogpt-server-api/types";
import { Separator } from "@/components/ui/separator";
import useSupabase from "@/lib/supabase/useSupabase";
import { useSupabase } from "@/lib/supabase/hooks/useSupabase";
import { useBackendAPI } from "@/lib/autogpt-server-api/context";
export const ProfileInfoForm = ({ profile }: { profile: ProfileDetails }) => {

View File

@@ -1,22 +1,57 @@
"use client";
import useSupabase from "@/lib/supabase/useSupabase";
import { useSupabase } from "@/lib/supabase/hooks/useSupabase";
import { IconLogOut } from "@/components/ui/icons";
import { useTransition } from "react";
import { LoadingSpinner } from "../ui/loading";
import { cn } from "@/lib/utils";
import { useRouter } from "next/navigation";
import { toast } from "../ui/use-toast";
import * as Sentry from "@sentry/nextjs";
export const ProfilePopoutMenuLogoutButton = () => {
export function ProfilePopoutMenuLogoutButton() {
const router = useRouter();
const [isPending, startTransition] = useTransition();
const supabase = useSupabase();
function handleLogout() {
startTransition(async () => {
try {
await supabase.logOut({ scope: "global" });
router.refresh();
} catch (e) {
Sentry.captureException(e);
toast({
title: "Error logging out",
description:
"Something went wrong when logging out. Please try again. If the problem persists, please contact support.",
variant: "destructive",
});
}
});
}
return (
<div
className="inline-flex w-full items-center justify-start gap-2.5"
onClick={() => supabase.logOut()}
className={cn(
"inline-flex w-full items-center justify-start gap-2.5",
isPending && "justify-center",
)}
onClick={handleLogout}
role="button"
tabIndex={0}
>
<div className="relative h-6 w-6">
<IconLogOut className="h-6 w-6" />
</div>
<div className="font-sans text-base font-medium leading-normal text-neutral-800 dark:text-neutral-200">
Log out
</div>
{isPending ? (
<LoadingSpinner className="size-5" />
) : (
<>
<div className="relative h-6 w-6">
<IconLogOut className="h-6 w-6" />
</div>
<div className="font-sans text-base font-medium leading-normal text-neutral-800 dark:text-neutral-200">
Log out
</div>
</>
)}
</div>
);
};
}

View File

@@ -32,7 +32,7 @@ export const StoreCard: React.FC<StoreCardProps> = ({
return (
<div
className="flex h-[27rem] w-full max-w-md cursor-pointer flex-col items-start rounded-3xl bg-white transition-all duration-300 hover:shadow-lg dark:bg-transparent dark:hover:shadow-gray-700"
className="flex h-[27rem] w-full max-w-md cursor-pointer flex-col items-start rounded-3xl bg-background transition-all duration-300 hover:shadow-lg dark:hover:shadow-gray-700"
onClick={handleClick}
data-testid="store-card"
role="button"

View File

@@ -5,6 +5,7 @@ import { SearchBar } from "@/components/agptui/SearchBar";
import { FilterChips } from "@/components/agptui/FilterChips";
import { useRouter } from "next/navigation";
import { useOnboarding } from "@/components/onboarding/onboarding-provider";
import { useSupabase } from "@/lib/supabase/hooks/useSupabase";
export const HeroSection: React.FC = () => {
const router = useRouter();

View File

@@ -56,6 +56,7 @@ export const providerIcons: Record<
CredentialsProviderName,
React.FC<{ className?: string }>
> = {
aiml_api: fallbackIcon,
anthropic: fallbackIcon,
apollo: fallbackIcon,
e2b: fallbackIcon,

View File

@@ -1,5 +1,5 @@
import { createContext, useCallback, useEffect, useState } from "react";
import useSupabase from "@/lib/supabase/useSupabase";
import { useSupabase } from "@/lib/supabase/hooks/useSupabase";
import {
APIKeyCredentials,
CredentialsDeleteNeedConfirmationResponse,
@@ -18,6 +18,7 @@ const CREDENTIALS_PROVIDER_NAMES = Object.values(
// --8<-- [start:CredentialsProviderNames]
const providerDisplayNames: Record<CredentialsProviderName, string> = {
aiml_api: "AI/ML",
anthropic: "Anthropic",
apollo: "Apollo",
discord: "Discord",

View File

@@ -1,5 +1,5 @@
"use client";
import useSupabase from "@/lib/supabase/useSupabase";
import { useSupabase } from "@/lib/supabase/hooks/useSupabase";
import { OnboardingStep, UserOnboarding } from "@/lib/autogpt-server-api";
import { useBackendAPI } from "@/lib/autogpt-server-api/context";
import { usePathname, useRouter } from "next/navigation";

View File

@@ -20,7 +20,7 @@ export function InputList({ blockInputs, onInputChange }: InputListProps) {
schema={block.inputSchema}
name={block.hardcodedValues.name}
description={block.hardcodedValues.description}
value={block.hardcodedValues.value || ""}
value={block.hardcodedValues.value ?? ""}
placeholder_values={block.hardcodedValues.placeholder_values}
onInputChange={onInputChange}
/>

View File

@@ -1,4 +1,4 @@
import getServerSupabase from "@/lib/supabase/getServerSupabase";
import { getServerSupabase } from "@/lib/supabase/server/getServerSupabase";
import { createBrowserClient } from "@supabase/ssr";
import type { SupabaseClient } from "@supabase/supabase-js";
import type {

View File

@@ -149,6 +149,7 @@ export type Credentials =
// --8<-- [start:BlockIOCredentialsSubSchema]
export const PROVIDER_NAMES = {
AIML_API: "aiml_api",
ANTHROPIC: "anthropic",
APOLLO: "apollo",
D_ID: "d_id",

View File

@@ -0,0 +1,83 @@
// Session management constants and utilities
export const PROTECTED_PAGES = [
"/monitor",
"/build",
"/onboarding",
"/profile",
"/library",
"/monitoring",
] as const;
export const ADMIN_PAGES = ["/admin"] as const;
export const STORAGE_KEYS = {
LOGOUT: "supabase-logout",
} as const;
// Page protection utilities
export function isProtectedPage(pathname: string): boolean {
return PROTECTED_PAGES.some((page) => pathname.startsWith(page));
}
export function isAdminPage(pathname: string): boolean {
return ADMIN_PAGES.some((page) => pathname.startsWith(page));
}
export function shouldRedirectOnLogout(pathname: string): boolean {
return isProtectedPage(pathname) || isAdminPage(pathname);
}
// Cross-tab logout utilities
export function broadcastLogout(): void {
if (typeof window !== "undefined") {
window.localStorage.setItem(STORAGE_KEYS.LOGOUT, Date.now().toString());
}
}
export function isLogoutEvent(event: StorageEvent): boolean {
return event.key === STORAGE_KEYS.LOGOUT;
}
// Redirect utilities
export function getRedirectPath(
pathname: string,
userRole?: string,
): string | null {
if (shouldRedirectOnLogout(pathname)) {
return "/login";
}
if (isAdminPage(pathname) && userRole !== "admin") {
return "/marketplace";
}
return null;
}
// Event listener management
export interface EventListeners {
cleanup: () => void;
}
export function setupSessionEventListeners(
onVisibilityChange: () => void,
onFocus: () => void,
onStorageChange: (e: StorageEvent) => void,
): EventListeners {
if (typeof window === "undefined" || typeof document === "undefined") {
return { cleanup: () => {} };
}
document.addEventListener("visibilitychange", onVisibilityChange);
window.addEventListener("focus", onFocus);
window.addEventListener("storage", onStorageChange);
return {
cleanup: () => {
document.removeEventListener("visibilitychange", onVisibilityChange);
window.removeEventListener("focus", onFocus);
window.removeEventListener("storage", onStorageChange);
},
};
}

View File

@@ -0,0 +1,158 @@
"use client";
import { useEffect, useMemo, useState, useRef } from "react";
import { createBrowserClient } from "@supabase/ssr";
import { SignOut, User } from "@supabase/supabase-js";
import { useRouter } from "next/navigation";
import {
broadcastLogout,
getRedirectPath,
isLogoutEvent,
setupSessionEventListeners,
} from "../helpers";
export function useSupabase() {
const router = useRouter();
const [user, setUser] = useState<User | null>(null);
const [isUserLoading, setIsUserLoading] = useState(true);
const lastValidationRef = useRef<number>(0);
const supabase = useMemo(() => {
try {
return createBrowserClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
{ isSingleton: true },
);
} catch (error) {
console.error("Error creating Supabase client", error);
return null;
}
}, []);
async function logOut(options?: SignOut) {
if (!supabase) return;
broadcastLogout();
const { error } = await supabase.auth.signOut({
scope: "global",
});
if (error) console.error("Error logging out:", error);
router.push("/login");
}
async function validateSession() {
if (!supabase) return false;
// Simple debounce - only validate if 2 seconds have passed
const now = Date.now();
if (now - lastValidationRef.current < 2000) {
return true;
}
lastValidationRef.current = now;
try {
const {
data: { user: apiUser },
error,
} = await supabase.auth.getUser();
if (error || !apiUser) {
// Session is invalid, clear local state
setUser(null);
const redirectPath = getRedirectPath(window.location.pathname);
if (redirectPath) {
router.push(redirectPath);
}
return false;
}
// Update local state if we have a valid user but no local user
if (apiUser && !user) {
setUser(apiUser);
}
return true;
} catch (error) {
console.error("Session validation error:", error);
setUser(null);
const redirectPath = getRedirectPath(window.location.pathname);
if (redirectPath) {
router.push(redirectPath);
}
return false;
}
}
function handleCrossTabLogout(e: StorageEvent) {
if (!isLogoutEvent(e)) return;
// Clear the Supabase session first
if (supabase) {
supabase.auth.signOut({ scope: "global" }).catch(console.error);
}
// Clear local state immediately
setUser(null);
router.refresh();
const redirectPath = getRedirectPath(window.location.pathname);
if (redirectPath) {
router.push(redirectPath);
}
}
function handleVisibilityChange() {
if (document.visibilityState === "visible") {
validateSession();
}
}
function handleFocus() {
validateSession();
}
useEffect(() => {
if (!supabase) {
setIsUserLoading(false);
return;
}
const {
data: { subscription },
} = supabase.auth.onAuthStateChange((event, session) => {
const newUser = session?.user ?? null;
// Only update if user actually changed to prevent unnecessary re-renders
setUser((currentUser) => {
if (currentUser?.id !== newUser?.id) {
return newUser;
}
return currentUser;
});
setIsUserLoading(false);
});
const eventListeners = setupSessionEventListeners(
handleVisibilityChange,
handleFocus,
handleCrossTabLogout,
);
return () => {
subscription.unsubscribe();
eventListeners.cleanup();
};
}, [supabase]);
return {
supabase,
user,
isLoggedIn: !isUserLoading ? !!user : null,
isUserLoading,
logOut,
validateSession,
};
}

View File

@@ -1,16 +1,11 @@
import { createServerClient } from "@supabase/ssr";
import { NextResponse, type NextRequest } from "next/server";
// TODO: Update the protected pages list
const PROTECTED_PAGES = [
"/monitor",
"/build",
"/onboarding",
"/profile",
"/library",
"/monitoring",
];
const ADMIN_PAGES = ["/admin"];
import {
PROTECTED_PAGES,
ADMIN_PAGES,
isProtectedPage,
isAdminPage,
} from "./helpers";
export async function updateSession(request: NextRequest) {
let supabaseResponse = NextResponse.next({
@@ -59,41 +54,26 @@ export async function updateSession(request: NextRequest) {
error,
} = await supabase.auth.getUser();
// Get the user role
const userRole = user?.role;
const url = request.nextUrl.clone();
const pathname = request.nextUrl.pathname;
// AUTH REDIRECTS
// 1. Check if user is not authenticated but trying to access protected content
if (!user) {
// Check if the user is trying to access either a protected page or an admin page
const isAttemptingProtectedPage = PROTECTED_PAGES.some((page) =>
request.nextUrl.pathname.startsWith(page),
);
const attemptingProtectedPage = isProtectedPage(pathname);
const attemptingAdminPage = isAdminPage(pathname);
const isAttemptingAdminPage = ADMIN_PAGES.some((page) =>
request.nextUrl.pathname.startsWith(page),
);
// If trying to access any protected content without being logged in,
// redirect to login page
if (isAttemptingProtectedPage || isAttemptingAdminPage) {
url.pathname = `/login`;
if (attemptingProtectedPage || attemptingAdminPage) {
url.pathname = "/login";
return NextResponse.redirect(url);
}
}
// 2. Check if user is authenticated but lacks admin role when accessing admin pages
if (user && userRole !== "admin") {
const isAttemptingAdminPage = ADMIN_PAGES.some((page) =>
request.nextUrl.pathname.startsWith(page),
);
// If a non-admin user is trying to access admin pages,
// redirect to marketplace
if (isAttemptingAdminPage) {
url.pathname = `/marketplace`;
return NextResponse.redirect(url);
}
if (user && userRole !== "admin" && isAdminPage(pathname)) {
url.pathname = "/marketplace";
return NextResponse.redirect(url);
}
// IMPORTANT: You *must* return the supabaseResponse object as it is. If you're

View File

@@ -1,7 +1,7 @@
import type { UnsafeUnwrappedCookies } from "next/headers";
import { createServerClient } from "@supabase/ssr";
export default async function getServerSupabase() {
export async function getServerSupabase() {
// Need require here, so Next.js doesn't complain about importing this on client side
const { cookies } = require("next/headers");
const cookieStore = await cookies();

View File

@@ -1,6 +1,6 @@
import getServerSupabase from "./getServerSupabase";
import { getServerSupabase } from "./getServerSupabase";
const getServerUser = async () => {
export async function getServerUser() {
const supabase = await getServerSupabase();
if (!supabase) {
@@ -10,7 +10,7 @@ const getServerUser = async () => {
try {
const {
data: { user },
error,
error: _,
} = await supabase.auth.getUser();
// if (error) {
// // FIX: Suppressing error for now. Need to stop the nav bar calling this all the time
@@ -30,6 +30,4 @@ const getServerUser = async () => {
error: `Unexpected error: ${(error as Error).message}`,
};
}
};
export default getServerUser;
}

View File

@@ -1,65 +0,0 @@
"use client";
import { useCallback, useEffect, useMemo, useState } from "react";
import { createBrowserClient } from "@supabase/ssr";
import { SignOut, User } from "@supabase/supabase-js";
import { useRouter } from "next/navigation";
export default function useSupabase() {
const router = useRouter();
const [user, setUser] = useState<User | null>(null);
const [isUserLoading, setIsUserLoading] = useState(true);
const supabase = useMemo(() => {
try {
return createBrowserClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
{ isSingleton: true },
);
} catch (error) {
console.error("Error creating Supabase client", error);
return null;
}
}, []);
useEffect(() => {
if (!supabase) {
setIsUserLoading(false);
return;
}
// Sync up the current state and listen for changes
const {
data: { subscription },
} = supabase.auth.onAuthStateChange((_event, session) => {
setUser(session?.user ?? null);
setIsUserLoading(false);
});
return () => {
subscription.unsubscribe();
};
}, [supabase]);
const logOut = useCallback(
async (options?: SignOut) => {
if (!supabase) return;
const { error } = await supabase.auth.signOut({
scope: options?.scope ?? "local",
});
if (error) console.error("Error logging out:", error);
router.push("/login");
},
[router, supabase],
);
if (!supabase || isUserLoading) {
return { supabase, user: null, isLoggedIn: null, isUserLoading, logOut };
}
if (!user) {
return { supabase, user, isLoggedIn: false, isUserLoading, logOut };
}
return { supabase, user, isLoggedIn: true, isUserLoading, logOut };
}

View File

@@ -1,7 +1,7 @@
import React from "react";
import * as Sentry from "@sentry/nextjs";
import { redirect } from "next/navigation";
import getServerUser from "./supabase/getServerUser";
import { getServerUser } from "./supabase/server/getServerUser";
export async function withRoleAccess(allowedRoles: string[]) {
"use server";

View File

@@ -1,451 +0,0 @@
import { Meta } from "@storybook/blocks";
import Image from "next/image";
import Github from "./assets/github.svg";
import Discord from "./assets/discord.svg";
import Youtube from "./assets/youtube.svg";
import Tutorials from "./assets/tutorials.svg";
import Styling from "./assets/styling.png";
import Context from "./assets/context.png";
import Assets from "./assets/assets.png";
import Docs from "./assets/docs.png";
import Share from "./assets/share.png";
import FigmaPlugin from "./assets/figma-plugin.png";
import Testing from "./assets/testing.png";
import Accessibility from "./assets/accessibility.png";
import Theming from "./assets/theming.png";
import AddonLibrary from "./assets/addon-library.png";
export const RightArrow = () => (
<svg
viewBox="0 0 14 14"
width="8px"
height="14px"
style={{
marginLeft: "4px",
display: "inline-block",
shapeRendering: "inherit",
verticalAlign: "middle",
fill: "currentColor",
"path fill": "currentColor",
}}
>
<path d="m11.1 7.35-5.5 5.5a.5.5 0 0 1-.7-.7L10.04 7 4.9 1.85a.5.5 0 1 1 .7-.7l5.5 5.5c.2.2.2.5 0 .7Z" />
</svg>
);
<Meta title="Configure your project" />
<div className="sb-container">
<div className='sb-section-title'>
# Configure your project
Because Storybook works separately from your app, you'll need to configure it for your specific stack and setup. Below, explore guides for configuring Storybook with popular frameworks and tools. If you get stuck, learn how you can ask for help from our community.
</div>
<div className="sb-section">
<div className="sb-section-item">
<Image
src={Styling}
alt="A wall of logos representing different styling technologies"
width={0}
height={0}
style={{ width: '100%', height: 'auto' }}
/>
<h4 className="sb-section-item-heading">Add styling and CSS</h4>
<p className="sb-section-item-paragraph">Like with web applications, there are many ways to include CSS within Storybook. Learn more about setting up styling within Storybook.</p>
<a
href="https://storybook.js.org/docs/configure/styling-and-css/?renderer=react"
target="_blank"
>Learn more<RightArrow /></a>
</div>
<div className="sb-section-item">
<Image
width={0}
height={0}
style={{ width: '100%', height: 'auto' }}
src={Context}
alt="An abstraction representing the composition of data for a component"
/>
<h4 className="sb-section-item-heading">Provide context and mocking</h4>
<p className="sb-section-item-paragraph">Often when a story doesn't render, it's because your component is expecting a specific environment or context (like a theme provider) to be available.</p>
<a
href="https://storybook.js.org/docs/writing-stories/decorators/?renderer=react#context-for-mocking"
target="_blank"
>Learn more<RightArrow /></a>
</div>
<div className="sb-section-item">
<Image
width={0}
height={0}
style={{ width: '100%', height: 'auto' }}
src={Assets}
alt="A representation of typography and image assets"
/>
<div>
<h4 className="sb-section-item-heading">Load assets and resources</h4>
<p className="sb-section-item-paragraph">To link static files (like fonts) to your projects and stories, use the
`staticDirs` configuration option to specify folders to load when
starting Storybook.</p>
<a
href="https://storybook.js.org/docs/configure/images-and-assets/?renderer=react"
target="_blank"
>Learn more<RightArrow /></a>
</div>
</div>
</div>
</div>
<div className="sb-container">
<div className='sb-section-title'>
# Do more with Storybook
Now that you know the basics, let's explore other parts of Storybook that will improve your experience. This list is just to get you started. You can customise Storybook in many ways to fit your needs.
</div>
<div className="sb-section">
<div className="sb-features-grid">
<div className="sb-grid-item">
<Image
width={0}
height={0}
style={{ width: '100%', height: 'auto' }}
src={Docs}
alt="A screenshot showing the autodocs tag being set, pointing a docs page being generated"
/>
<h4 className="sb-section-item-heading">Autodocs</h4>
<p className="sb-section-item-paragraph">Auto-generate living,
interactive reference documentation from your components and stories.</p>
<a
href="https://storybook.js.org/docs/writing-docs/autodocs/?renderer=react"
target="_blank"
>Learn more<RightArrow /></a>
</div>
<div className="sb-grid-item">
<Image
width={0}
height={0}
style={{ width: '100%', height: 'auto' }}
src={Share}
alt="A browser window showing a Storybook being published to a chromatic.com URL"
/>
<h4 className="sb-section-item-heading">Publish to Chromatic</h4>
<p className="sb-section-item-paragraph">Publish your Storybook to review and collaborate with your entire team.</p>
<a
href="https://storybook.js.org/docs/sharing/publish-storybook/?renderer=react#publish-storybook-with-chromatic"
target="_blank"
>Learn more<RightArrow /></a>
</div>
<div className="sb-grid-item">
<Image
width={0}
height={0}
style={{ width: '100%', height: 'auto' }}
src={FigmaPlugin}
alt="Windows showing the Storybook plugin in Figma"
/>
<h4 className="sb-section-item-heading">Figma Plugin</h4>
<p className="sb-section-item-paragraph">Embed your stories into Figma to cross-reference the design and live
implementation in one place.</p>
<a
href="https://storybook.js.org/docs/sharing/design-integrations/?renderer=react#embed-storybook-in-figma-with-the-plugin"
target="_blank"
>Learn more<RightArrow /></a>
</div>
<div className="sb-grid-item">
<Image
width={0}
height={0}
style={{ width: '100%', height: 'auto' }}
src={Testing}
alt="Screenshot of tests passing and failing"
/>
<h4 className="sb-section-item-heading">Testing</h4>
<p className="sb-section-item-paragraph">Use stories to test a component in all its variations, no matter how
complex.</p>
<a
href="https://storybook.js.org/docs/writing-tests/?renderer=react"
target="_blank"
>Learn more<RightArrow /></a>
</div>
<div className="sb-grid-item">
<Image
width={0}
height={0}
style={{ width: '100%', height: 'auto' }}
src={Accessibility}
alt="Screenshot of accessibility tests passing and failing"
/>
<h4 className="sb-section-item-heading">Accessibility</h4>
<p className="sb-section-item-paragraph">Automatically test your components for a11y issues as you develop.</p>
<a
href="https://storybook.js.org/docs/writing-tests/accessibility-testing/?renderer=react"
target="_blank"
>Learn more<RightArrow /></a>
</div>
<div className="sb-grid-item">
<Image
width={0}
height={0}
style={{ width: '100%', height: 'auto' }}
src={Theming}
alt="Screenshot of Storybook in light and dark mode"
/>
<h4 className="sb-section-item-heading">Theming</h4>
<p className="sb-section-item-paragraph">Theme Storybook's UI to personalize it to your project.</p>
<a
href="https://storybook.js.org/docs/configure/theming/?renderer=react"
target="_blank"
>Learn more<RightArrow /></a>
</div>
</div>
</div>
</div>
<div className='sb-addon'>
<div className='sb-addon-text'>
<h4>Addons</h4>
<p className="sb-section-item-paragraph">Integrate your tools with Storybook to connect workflows.</p>
<a
href="https://storybook.js.org/addons/"
target="_blank"
>Discover all addons<RightArrow /></a>
</div>
<div className='sb-addon-img'>
<Image
width={650}
height={347}
src={AddonLibrary}
alt="Integrate your tools with Storybook to connect workflows."
/>
</div>
</div>
<div className="sb-section sb-socials">
<div className="sb-section-item">
<Image
width={32}
height={32}
layout="fixed"
src={Github}
alt="Github logo"
className="sb-explore-image"
/>
Join our contributors building the future of UI development.
<a
href="https://github.com/storybookjs/storybook"
target="_blank"
>Star on GitHub<RightArrow /></a>
</div>
<div className="sb-section-item">
<Image
width={33}
height={32}
layout="fixed"
src={Discord}
alt="Discord logo"
className="sb-explore-image"
/>
<div>
Get support and chat with frontend developers.
<a
href="https://discord.gg/storybook"
target="_blank"
>Join Discord server<RightArrow /></a>
</div>
</div>
<div className="sb-section-item">
<Image
width={32}
height={32}
layout="fixed"
src={Youtube}
alt="Youtube logo"
className="sb-explore-image"
/>
<div>
Watch tutorials, feature previews and interviews.
<a
href="https://www.youtube.com/@chromaticui"
target="_blank"
>Watch on YouTube<RightArrow /></a>
</div>
</div>
<div className="sb-section-item">
<Image
width={33}
height={32}
layout="fixed"
src={Tutorials}
alt="A book"
className="sb-explore-image"
/>
<p>Follow guided walkthroughs on for key workflows.</p>
<a
href="https://storybook.js.org/tutorials/"
target="_blank"
>Discover tutorials<RightArrow /></a>
</div>
</div>
<style>
{`
.sb-container {
margin-bottom: 48px;
}
.sb-section {
width: 100%;
display: flex;
flex-direction: row;
gap: 20px;
}
img {
object-fit: cover;
}
.sb-section-title {
margin-bottom: 32px;
}
.sb-section a:not(h1 a, h2 a, h3 a) {
font-size: 14px;
}
.sb-section-item, .sb-grid-item {
flex: 1;
display: flex;
flex-direction: column;
}
.sb-section-item-heading {
padding-top: 20px !important;
padding-bottom: 5px !important;
margin: 0 !important;
}
.sb-section-item-paragraph {
margin: 0;
padding-bottom: 10px;
}
.sb-chevron {
margin-left: 5px;
}
.sb-features-grid {
display: grid;
grid-template-columns: repeat(2, 1fr);
grid-gap: 32px 20px;
}
.sb-socials {
display: grid;
grid-template-columns: repeat(4, 1fr);
}
.sb-socials p {
margin-bottom: 10px;
}
.sb-explore-image {
max-height: 32px;
align-self: flex-start;
}
.sb-addon {
width: 100%;
display: flex;
align-items: center;
position: relative;
background-color: #EEF3F8;
border-radius: 5px;
border: 1px solid rgba(0, 0, 0, 0.05);
background: #EEF3F8;
height: 180px;
margin-bottom: 48px;
overflow: hidden;
}
.sb-addon-text {
padding-left: 48px;
max-width: 240px;
}
.sb-addon-text h4 {
padding-top: 0px;
}
.sb-addon-img {
position: absolute;
left: 345px;
top: 0;
height: 100%;
width: 200%;
overflow: hidden;
}
.sb-addon-img img {
width: 650px;
transform: rotate(-15deg);
margin-left: 40px;
margin-top: -72px;
box-shadow: 0 0 1px rgba(255, 255, 255, 0);
backface-visibility: hidden;
}
@media screen and (max-width: 800px) {
.sb-addon-img {
left: 300px;
}
}
@media screen and (max-width: 600px) {
.sb-section {
flex-direction: column;
}
.sb-features-grid {
grid-template-columns: repeat(1, 1fr);
}
.sb-socials {
grid-template-columns: repeat(2, 1fr);
}
.sb-addon {
height: 280px;
align-items: flex-start;
padding-top: 32px;
overflow: hidden;
}
.sb-addon-text {
padding-left: 24px;
}
.sb-addon-img {
right: 0;
left: 0;
top: 130px;
bottom: 0;
overflow: hidden;
height: auto;
width: 124%;
}
.sb-addon-img img {
width: 1200px;
transform: rotate(-12deg);
margin-left: 0;
margin-top: 48px;
margin-bottom: -40px;
margin-left: -24px;
}
}
`}
</style>

View File

@@ -0,0 +1,466 @@
import type { Meta, StoryObj } from "@storybook/react";
import Image from "next/image";
function RightArrow() {
return (
<svg
viewBox="0 0 14 14"
width="8px"
height="14px"
className="ml-1 inline-block fill-current"
>
<path d="m11.1 7.35-5.5 5.5a.5.5 0 0 1-.7-.7L10.04 7 4.9 1.85a.5.5 0 1 1 .7-.7l5.5 5.5c.2.2.2.5 0 .7Z" />
</svg>
);
}
function OverviewComponent() {
const linkStyle = "font-bold text-blue-600 hover:text-blue-800";
return (
<div className="mx-auto max-w-6xl space-y-24 p-8">
{/* Header Section */}
<div className="space-y-8">
<div className="space-y-4">
<h1 className="text-4xl font-bold text-gray-900">
AutoGPT Design System
</h1>
<p className="text-xl leading-relaxed text-gray-600">
Welcome to the AutoGPT Design System - a comprehensive collection of
reusable components, design tokens, and guidelines that power the
AutoGPT Platform. This system ensures consistency, accessibility,
and efficiency across all our user interfaces.
</p>
<div className="inline-flex items-center">
<strong className="text-lg">
<a
href="https://www.figma.com/design/nO9NFynNuicLtkiwvOxrbz/AutoGPT-Design-System?node-id=3-2083&m=dev"
target="_blank"
rel="noopener noreferrer"
className={`${linkStyle} text-md`}
>
📋 Figma Reference
</a>
</strong>
</div>
</div>
{/* Foundation Cards */}
<div className="grid grid-cols-1 gap-6 md:grid-cols-3">
<div className="flex flex-col space-y-4">
<Image
src="/storybook/tokens.png"
alt="Design tokens representing colors, typography, and spacing"
width={0}
height={0}
className="h-auto w-4/5 rounded-lg"
/>
<h4 className="text-lg font-bold text-gray-900">Design Tokens</h4>
<p className="text-sm leading-relaxed text-gray-600">
The foundation of our design system. Tokens define colors,
typography, spacing, shadows, and other visual properties that
ensure consistency across all components and layouts.
</p>
<a
href="?path=/docs/design-tokens--docs"
className={`inline-flex items-center text-sm ${linkStyle}`}
>
Explore Tokens
<RightArrow />
</a>
</div>
<div className="flex flex-col space-y-4">
<Image
src="/storybook/atoms.png"
alt="Basic UI elements like buttons, inputs, and icons"
width={0}
height={0}
className="h-auto w-4/5 rounded-lg"
/>
<h4 className="text-lg font-bold text-gray-900">Atoms</h4>
<p className="text-sm leading-relaxed text-gray-600">
The smallest building blocks of our interface. Atoms include
buttons, inputs, icons, labels, and other fundamental UI elements
that cannot be broken down further.
</p>
<a
href="?path=/docs/atoms--docs"
className={`inline-flex items-center text-sm ${linkStyle}`}
>
View Atoms
<RightArrow />
</a>
</div>
<div className="flex flex-col space-y-4">
<Image
src="/storybook/molecules.png"
alt="Combined UI components like cards, dropdowns, and search bars"
width={0}
height={0}
className="h-auto w-4/5 rounded-lg"
/>
<h4 className="text-lg font-bold text-gray-900">Molecules</h4>
<p className="text-sm leading-relaxed text-gray-600">
Combinations of atoms that work together as a unit. Examples
include search bars, card components, dropdown menus, and other
composite UI elements.
</p>
<a
href="?path=/docs/molecules--docs"
className={`inline-flex items-center text-sm ${linkStyle}`}
>
Browse Molecules
<RightArrow />
</a>
</div>
</div>
</div>
{/* Technical Foundation */}
<div className="space-y-8">
<div className="space-y-4">
<h2 className="text-3xl font-bold text-gray-900">
Technical Foundation
</h2>
<p className="text-lg text-gray-600">
Our design system is built on proven technologies while maintaining
strict design consistency through custom tokens and components.
</p>
</div>
<div className="grid grid-cols-1 gap-12 md:grid-cols-3">
<div className="space-y-4">
<h4 className="text-lg font-semibold text-gray-900">
🎨 Built with Tailwind & shadcn/ui
</h4>
<p className="text-sm leading-relaxed text-gray-600">
The AutoGPT Design System leverages{" "}
<a
href="https://tailwindcss.com/"
target="_blank"
rel="noopener noreferrer"
className={linkStyle}
>
Tailwind CSS
</a>{" "}
for utility-first styling and{" "}
<a
href="https://ui.shadcn.com/"
target="_blank"
rel="noopener noreferrer"
className={linkStyle}
>
shadcn/ui
</a>{" "}
as a foundation for accessible, well-tested components.
</p>
</div>
<div className="space-y-4">
<h4 className="text-lg font-semibold text-gray-900">
🔧 Why This Matters
</h4>
<ul className="space-y-2 text-sm text-gray-600">
<li>
<strong>Visual Consistency:</strong> All interfaces look and
feel cohesive
</li>
<li>
<strong>Accessibility:</strong> Our tokens include proper
contrast ratios and focus states
</li>
<li>
<strong>Brand Compliance:</strong> All colors and styles match
AutoGPT&apos;s brand
</li>
</ul>
</div>
<div className="space-y-4">
<h4 className="text-lg font-semibold text-gray-900">
📚 Getting Started
</h4>
<ol className="list-decimal space-y-2 text-sm text-gray-600">
<li>
Review the Design Tokens, Atoms,Molecules and Contextual
Components for your use case
</li>
<li>
If you need something new,{" "}
<a
href="https://github.com/Significant-Gravitas/AutoGPT/issues/new?template=design-system.md"
target="_blank"
rel="noopener noreferrer"
className={linkStyle}
>
create an issue first
</a>{" "}
and get feedback
</li>
<li>
Always test your changes and ensure it renders well on all
screen sizes
</li>
</ol>
</div>
</div>
</div>
{/* Contributing Section */}
<div className="space-y-8">
<div className="space-y-4">
<h2 className="text-3xl font-bold text-gray-900">
Contributing to the Design System
</h2>
<p className="text-lg text-gray-600">
Help us improve and expand the AutoGPT Design System. Whether
you&apos;re fixing bugs, adding new components, or enhancing
existing ones, your contributions are valuable to the community.
</p>
</div>
<div className="relative rounded-xl bg-gradient-to-r from-blue-50 via-purple-50 to-pink-50 p-6">
<div className="absolute inset-0 rounded-xl bg-gradient-to-r from-blue-500 via-purple-500 to-pink-500 p-[2px]">
<div className="h-full w-full rounded-xl bg-white"></div>
</div>
<div className="relative space-y-6">
<div className="text-center">
<h4 className="bg-gradient-to-r from-blue-600 via-purple-600 to-pink-600 bg-clip-text text-xl font-bold text-transparent">
Design System Guidelines
</h4>
<p className="mt-2 text-gray-700">
Contributors must <strong>ONLY</strong> use the design tokens
and components defined in this system
</p>
</div>
<div className="grid gap-6 md:grid-cols-2">
<div className="space-y-4">
<h5 className="text-lg font-semibold text-red-600">
Don&apos;t Do This
</h5>
<div className="space-y-3">
<div>
<p className="mb-2 text-sm font-medium text-gray-700">
Default Tailwind classes:
</p>
<pre className="overflow-x-auto rounded-md bg-gray-100 p-3 text-sm">
<code className="text-red-600">{`className="text-blue-500 p-4 bg-gray-200"`}</code>
</pre>
</div>
<div>
<p className="mb-2 text-sm font-medium text-gray-700">
Arbitrary values:
</p>
<pre className="overflow-x-auto rounded-md bg-gray-100 p-3 text-sm">
<code className="text-red-600">{`className="text-[#1234ff] w-[420px]"`}</code>
</pre>
</div>
</div>
</div>
<div className="space-y-4">
<h5 className="text-lg font-semibold text-green-600">
Do This Instead
</h5>
<div className="space-y-3">
<div>
<p className="mb-2 text-sm font-medium text-gray-700">
Design tokens:
</p>
<pre className="overflow-x-auto rounded-md bg-gray-100 p-3 text-sm">
<code className="text-green-600">{`className="text-primary bg-surface space-4"`}</code>
</pre>
</div>
<div>
<p className="mb-2 text-sm font-medium text-gray-700">
System components:
</p>
<pre className="overflow-x-auto rounded-md bg-gray-100 p-3 text-sm">
<code className="text-green-600">{`<Button variant="primary" size="md">
Click me
</Button>`}</code>
</pre>
</div>
</div>
</div>
</div>
</div>
</div>
<div className="grid grid-cols-1 gap-6 md:grid-cols-2">
<div className="space-y-4">
<h4 className="text-lg font-semibold text-gray-900">
🧢 Development Workflow
</h4>
<p className="text-md leading-relaxed text-gray-600">
All design system changes should follow our established workflow
to ensure quality and consistency.
</p>
<div className="text-md space-y-4">
<div>
<strong className="text-gray-900">
For External Contributors:
</strong>
<ol className="mt-2 list-decimal space-y-1 pl-4 text-gray-600">
<li>
Create a GitHub issue first to discuss your proposed changes
</li>
<li>
Wait for maintainer approval before starting development
</li>
<li>Fork the repository and create a feature branch</li>
<li>Implement changes following our coding standards</li>
<li>Submit a pull request with detailed description</li>
</ol>
</div>
<div>
<strong className="text-gray-900">
For Internal Team Members:
</strong>
<ol className="mt-2 list-decimal space-y-1 pl-4 text-gray-600">
<li>Create a feature branch from main</li>
<li>Implement changes and update Storybook documentation</li>
<li>Test components across different scenarios</li>
<li>Submit pull request for team review</li>
</ol>
</div>
</div>
</div>
<div className="space-y-4">
<h4 className="text-lg font-semibold text-gray-900">
📋 Component Guidelines
</h4>
<p className="text-md leading-relaxed text-gray-600">
Follow these principles when creating or modifying components:
</p>
<ul className="text-md space-y-2 text-gray-600">
<li>
<strong className="text-gray-900">Accessibility First</strong>
<ul>
<li>
All components must meet{" "}
<a
href="https://www.w3.org/WAI/standards-guidelines/wcag/"
target="_blank"
rel="noopener noreferrer"
className={`${linkStyle} font-semibold`}
>
WCAG 2.1 AA standards
</a>
</li>
</ul>
</li>
<li>
<strong className="text-gray-900">Design Token Usage</strong>
<ul>
<li>Use design tokens for all styling properties</li>
</ul>
</li>
<li>
<strong className="text-gray-900">Responsive Design</strong>
<ul>
<li>Components should work across all screen sizes</li>
</ul>
</li>
<li>
<strong className="text-gray-900">TypeScript</strong>
<ul>
<li>All components must be fully typed</li>
</ul>
</li>
<li>
<strong className="text-gray-900">Documentation</strong>
<ul>
<li>
Include comprehensive Storybook stories and JSDoc comments
</li>
</ul>
</li>
<li>
<strong className="text-gray-900">Testing</strong>
<ul>
<li>Write unit tests for component logic and interactions</li>
</ul>
</li>
</ul>
</div>
</div>
</div>
{/* Social Links */}
<div className="space-y-8">
<h3 className="text-3xl font-bold text-gray-900">Get Involved</h3>
<p className="text-md leading-relaxed text-gray-600">
Join the AutoGPT community and help build the future of AI automation.
</p>
<div className="grid grid-cols-1 gap-6 md:grid-cols-4">
{[
{
icon: "/storybook/github.svg",
title:
"Contribute to the AutoGPT Platform and help build the future of AI automation.",
link: "https://github.com/Significant-Gravitas/AutoGPT",
linkText: "Star on GitHub",
},
{
icon: "/storybook/discord.svg",
title: "Get support and chat with the AutoGPT community.",
link: "https://discord.gg/autogpt",
linkText: "Join Discord",
},
{
icon: "/storybook/youtube.svg",
title: "Watch AutoGPT tutorials and feature demonstrations.",
link: "https://www.youtube.com/@AutoGPT-Official",
linkText: "Watch on YouTube",
},
{
icon: "/storybook/docs.svg",
title: "Read the complete platform documentation and guides.",
link: "https://docs.agpt.co",
linkText: "View Documentation",
},
].map((item, index) => (
<div key={index} className="space-y-4">
<Image
src={item.icon}
alt={`${item.linkText} logo`}
width={32}
height={32}
className="h-8 w-8"
/>
<p className="text-sm leading-relaxed text-gray-600">
{item.title}
</p>
<a
href={item.link}
target="_blank"
rel="noopener noreferrer"
className="inline-flex items-center text-sm text-blue-600 hover:text-blue-800"
>
{item.linkText}
<RightArrow />
</a>
</div>
))}
</div>
</div>
</div>
);
}
const meta: Meta<typeof OverviewComponent> = {
title: "Overview",
component: OverviewComponent,
parameters: {
layout: "fullscreen",
controls: { disable: true },
},
};
export default meta;
type Story = StoryObj<typeof meta>;
export const Default: Story = {};

View File

@@ -0,0 +1,275 @@
import type { Meta, StoryObj } from "@storybook/react";
import { Text } from "@/components/_new/Text/Text";
import { StoryCode } from "@/stories/helpers/StoryCode";
import { SquareArrowOutUpRight } from "lucide-react";
const meta: Meta = {
title: "Design System/ Tokens /Spacing",
parameters: {
layout: "fullscreen",
controls: { disable: true },
},
};
export default meta;
// Spacing scale data with rem and px values
// https://tailwindcss.com/docs/spacing
const spacingScale = [
{ name: "0", value: "0", rem: "0rem", px: "0px", class: "m-0" },
{ name: "px", value: "1px", rem: "0.0625rem", px: "1px", class: "m-px" },
{
name: "0.5",
value: "0.125rem",
rem: "0.125rem",
px: "2px",
class: "m-0.5",
},
{ name: "1", value: "0.25rem", rem: "0.25rem", px: "4px", class: "m-1" },
{
name: "1.5",
value: "0.375rem",
rem: "0.375rem",
px: "6px",
class: "m-1.5",
},
{ name: "2", value: "0.5rem", rem: "0.5rem", px: "8px", class: "m-2" },
{
name: "2.5",
value: "0.625rem",
rem: "0.625rem",
px: "10px",
class: "m-2.5",
},
{ name: "3", value: "0.75rem", rem: "0.75rem", px: "12px", class: "m-3" },
{
name: "3.5",
value: "0.875rem",
rem: "0.875rem",
px: "14px",
class: "m-3.5",
},
{ name: "4", value: "1rem", rem: "1rem", px: "16px", class: "m-4" },
{ name: "5", value: "1.25rem", rem: "1.25rem", px: "20px", class: "m-5" },
{ name: "6", value: "1.5rem", rem: "1.5rem", px: "24px", class: "m-6" },
{ name: "7", value: "1.75rem", rem: "1.75rem", px: "28px", class: "m-7" },
{ name: "8", value: "2rem", rem: "2rem", px: "32px", class: "m-8" },
{ name: "9", value: "2.25rem", rem: "2.25rem", px: "36px", class: "m-9" },
{ name: "10", value: "2.5rem", rem: "2.5rem", px: "40px", class: "m-10" },
{ name: "11", value: "2.75rem", rem: "2.75rem", px: "44px", class: "m-11" },
{ name: "12", value: "3rem", rem: "3rem", px: "48px", class: "m-12" },
{ name: "14", value: "3.5rem", rem: "3.5rem", px: "56px", class: "m-14" },
{ name: "16", value: "4rem", rem: "4rem", px: "64px", class: "m-16" },
{ name: "20", value: "5rem", rem: "5rem", px: "80px", class: "m-20" },
{ name: "24", value: "6rem", rem: "6rem", px: "96px", class: "m-24" },
{ name: "28", value: "7rem", rem: "7rem", px: "112px", class: "m-28" },
{ name: "32", value: "8rem", rem: "8rem", px: "128px", class: "m-32" },
{ name: "36", value: "9rem", rem: "9rem", px: "144px", class: "m-36" },
{ name: "40", value: "10rem", rem: "10rem", px: "160px", class: "m-40" },
{ name: "44", value: "11rem", rem: "11rem", px: "176px", class: "m-44" },
{ name: "48", value: "12rem", rem: "12rem", px: "192px", class: "m-48" },
{ name: "52", value: "13rem", rem: "13rem", px: "208px", class: "m-52" },
{ name: "56", value: "14rem", rem: "14rem", px: "224px", class: "m-56" },
{ name: "60", value: "15rem", rem: "15rem", px: "240px", class: "m-60" },
{ name: "64", value: "16rem", rem: "16rem", px: "256px", class: "m-64" },
{ name: "72", value: "18rem", rem: "18rem", px: "288px", class: "m-72" },
{ name: "80", value: "20rem", rem: "20rem", px: "320px", class: "m-80" },
{ name: "96", value: "24rem", rem: "24rem", px: "384px", class: "m-96" },
];
export function AllVariants() {
return (
<div className="space-y-12">
{/* Spacing System Documentation */}
<div className="space-y-8">
<div>
<Text variant="h1" className="mb-4 text-zinc-800">
Spacing System
</Text>
<Text variant="large" className="text-zinc-600">
Our spacing system uses a consistent scale based on rem units to
ensure proper spacing relationships across all components and
layouts. The spacing tokens are identical for both margin and
padding utilities.
</Text>
</div>
<div className="grid gap-8 md:grid-cols-2">
<div>
<Text
variant="h2"
className="mb-2 text-xl font-semibold text-zinc-800"
>
Tailwind utilities
</Text>
<div className="space-y-4">
<div className="rounded-lg border border-gray-200 p-4">
<a
href="https://tailwindcss.com/docs/margin"
target="_blank"
rel="noopener noreferrer"
className="mb-2 inline-flex flex-row items-center gap-1 text-base font-semibold text-blue-600 hover:underline"
>
Margin Classes{" "}
<SquareArrowOutUpRight className="inline-block h-3 w-3" />
</a>
<Text variant="body" className="mb-2 text-zinc-600">
Used for external spacing between elements
</Text>
<div className="font-mono text-sm text-zinc-800">
m-4 margin: 1rem (16px)
</div>
</div>
<div className="rounded-lg border border-gray-200 p-4">
<a
href="https://tailwindcss.com/docs/padding"
target="_blank"
rel="noopener noreferrer"
className="mb-2 inline-flex flex-row items-center gap-1 text-base font-semibold text-blue-600 hover:underline"
>
Padding Classes
<SquareArrowOutUpRight className="inline-block h-3 w-3" />
</a>
<Text variant="body" className="mb-2 text-zinc-600">
Used for internal spacing within elements (same scale as
margin)
</Text>
<div className="font-mono text-sm text-zinc-800">
p-4 padding: 1rem (16px)
</div>
</div>
<Text variant="body" className="mb-4 text-zinc-600">
We follow Tailwind CSS spacing system, which means you can use
any spacing token available in the default Tailwind theme for
margins and padding.
</Text>
</div>
</div>
<div>
<Text
variant="h2"
className="mb-2 text-xl font-semibold text-zinc-800"
>
FAQ
</Text>
<div className="space-y-4">
<Text
variant="h3"
className="mb-2 text-base font-semibold text-zinc-800"
>
🤔 Why use spacing tokens?
</Text>
<div className="space-y-3 text-zinc-600">
<Text variant="body">
Always use spacing classes instead of arbitrary values.
Reasons:
</Text>
<ul className="ml-4 list-disc space-y-1 text-sm">
<li>Ensures consistent spacing relationships</li>
<li>Makes responsive design easier with consistent ratios</li>
<li>Provides a harmonious visual rhythm</li>
<li>Easier to maintain and update globally</li>
<li>Prevents spacing inconsistencies across the app</li>
</ul>
</div>
<div>
<Text
variant="h3"
className="mb-2 text-base font-semibold text-zinc-800"
>
📏 How to choose spacing values?
</Text>
<div className="space-y-2 text-zinc-600">
<Text variant="body">
<strong>1-2:</strong> Tight spacing, form elements
</Text>
<Text variant="body">
<strong>3-4:</strong> Default component spacing
</Text>
<Text variant="body">
<strong>6-8:</strong> Section spacing
</Text>
<Text variant="body">
<strong>12+:</strong> Major layout divisions
</Text>
</div>
</div>
</div>
</div>
</div>
</div>
{/* Complete Spacing Scale */}
<div className="space-y-8">
<div>
<Text
variant="h2"
className="mb-2 text-xl font-semibold text-zinc-800"
>
Complete Spacing Scale
</Text>
<Text variant="body" className="mb-6 text-zinc-600">
All available spacing values in our design system. Each value works
for both margin and padding.
</Text>
</div>
<div className="space-y-4">
{spacingScale.map((space) => (
<div
key={space.name}
className="flex items-center rounded-lg border border-gray-200 p-4"
>
<div className="flex w-32 flex-col">
<Text variant="body-medium" className="font-mono text-zinc-800">
{space.name}
</Text>
<Text variant="small" className="font-mono text-zinc-500">
{space.class}
</Text>
</div>
<div className="flex w-32 flex-col text-right">
<p className="font-mono text-xs text-zinc-500">{space.rem}</p>
<p className="font-mono text-xs text-zinc-500">{space.px}</p>
</div>
<div className="ml-8 flex-1">
<div className="relative h-6 bg-gray-50">
<div
className="absolute left-0 top-0 h-full bg-blue-500"
style={{ width: space.value }}
></div>
</div>
</div>
</div>
))}
</div>
<StoryCode
code={`// Spacing scale examples
<div className="m-0">No margin (0px)</div>
<div className="m-px">1px margin</div>
<div className="m-1">0.25rem margin (4px)</div>
<div className="m-2">0.5rem margin (8px)</div>
<div className="m-4">1rem margin (16px)</div>
<div className="m-8">2rem margin (32px)</div>
<div className="m-16">4rem margin (64px)</div>
// Directional spacing
<div className="mt-4">Margin top</div>
<div className="mr-4">Margin right</div>
<div className="mb-4">Margin bottom</div>
<div className="ml-4">Margin left</div>
<div className="mx-4">Margin horizontal</div>
<div className="my-4">Margin vertical</div>
// Padding uses identical values
<div className="p-4 pt-8 px-6">Mixed padding</div>`}
/>
</div>
</div>
);
}
type Story = StoryObj<typeof meta>;

View File

@@ -0,0 +1,177 @@
import type { Meta, StoryObj } from "@storybook/react";
import { Text } from "@/components/_new/Text/Text";
import { StoryCode } from "@/stories/helpers/StoryCode";
const meta: Meta<typeof Text> = {
title: "Design System/ Tokens /Typography",
component: Text,
parameters: {
layout: "fullscreen",
controls: { disable: true },
},
};
export default meta;
export function AllVariants() {
return (
<div className="space-y-12">
{/* Typography System Documentation */}
<div className="space-y-8">
<div>
<h1 className="mb-4 text-4xl font-bold text-zinc-800">
Typography System
</h1>
<p className="text-lg leading-relaxed text-zinc-600">
Our typography system uses two carefully selected fonts to create a
clear hierarchy and excellent readability across all interfaces.
</p>
</div>
<div className="grid gap-8 md:grid-cols-2">
<div>
<h2 className="mb-4 text-2xl font-semibold text-zinc-800">
Font Families
</h2>
<div className="space-y-4">
<div className="rounded-lg border border-gray-200 p-4">
<h3 className="mb-2 font-semibold text-zinc-800">
<a
href="https://fonts.google.com/specimen/Poppins"
target="_blank"
rel="noopener noreferrer"
className="text-blue-600 hover:underline"
>
Poppins
</a>
</h3>
<p className="mb-2 text-sm text-zinc-600">
Used for all headings and display text
</p>
<div className="font-poppins text-2xl text-zinc-800">
The quick brown fox
</div>
</div>
<div className="rounded-lg border border-gray-200 p-4">
<h3 className="mb-2 font-semibold text-zinc-800">
<a
href="https://github.com/vercel/geist-font"
target="_blank"
rel="noopener noreferrer"
className="text-blue-600 hover:underline"
>
Geist Sans
</a>
</h3>
<p className="mb-2 text-sm text-zinc-600">
Used for all body text, labels, and UI elements
</p>
<div className="font-sans text-base text-zinc-800">
The quick brown fox jumps over the lazy dog
</div>
</div>
</div>
</div>
<div>
<h2 className="mb-4 text-2xl font-semibold text-zinc-800">FAQ</h2>
<div className="space-y-4">
<div className="rounded-lg border border-gray-200 p-4">
<h3 className="mb-2 font-semibold text-zinc-800">
🤔 Why can&apos;t I use &lt;p&gt; tags directly?
</h3>
<div className="space-y-3 text-zinc-600">
<p className="text-sm">
Always use the{" "}
<code className="rounded bg-gray-100 px-2 py-1 text-xs">
&lt;Text /&gt;
</code>{" "}
component instead of plain HTML elements like{" "}
<code className="rounded bg-gray-100 px-2 py-1 text-xs">
&lt;h1&gt;
</code>
,{" "}
<code className="rounded bg-gray-100 px-2 py-1 text-xs">
&lt;p&gt;
</code>
,{" "}
<code className="rounded bg-gray-100 px-2 py-1 text-xs">
&lt;span&gt;
</code>
, etc... Reasons:
</p>
<ul className="ml-4 list-inside list-disc space-y-1 text-sm">
<li>Ensures consistent typography across the entire app</li>
<li>
Makes future design updates easier (change once, update
everywhere)
</li>
<li>Provides TypeScript safety for typography variants</li>
<li>
Automatically maps to correct HTML elements for
accessibility
</li>
<li>Prevents styling inconsistencies and design drift</li>
</ul>
</div>
</div>
</div>
</div>
</div>
</div>
{/* Typography Examples */}
<div className="space-y-8">
<div className="mb-19 mb-20 space-y-6">
<h2 className="mb-4 border-b border-border pb-2 text-xl text-zinc-500">
Headings (Poppins)
</h2>
<Text variant="h1">Heading 1</Text>
<Text variant="h2">Heading 2</Text>
<Text variant="h3">Heading 3</Text>
<Text variant="h4">Heading 4</Text>
<StoryCode
code={`<Text variant="h1">Heading 1</Text>
<Text variant="h2">Heading 2</Text>
<Text variant="h3">Heading 3</Text>
<Text variant="h4">Heading 4</Text>`}
/>
</div>
<h2 className="mb-4 border-b border-border pb-2 text-xl text-zinc-500">
Body Text (Geist Sans)
</h2>
<Text variant="lead">Lead</Text>
<StoryCode code="<Text variant='lead'>Lead</Text>" />
<div className="flex flex-row gap-8">
<Text variant="large">Large</Text>
<Text variant="large-medium">Large Medium</Text>
<Text variant="large-semibold">Large Semibold</Text>
</div>
<StoryCode
code={`<Text variant="large">Large</Text>
<Text variant="large-medium">Large Medium</Text>
<Text variant="large-semibold">Large Semibold</Text>`}
/>
<div className="flex flex-row gap-8">
<Text variant="body">Body</Text>
<Text variant="body-medium">Body Medium</Text>
</div>
<StoryCode
code={`<Text variant="body">Body</Text>
<Text variant="body-medium">Body Medium</Text>`}
/>
<div className="flex flex-row gap-8">
<Text variant="small">Small</Text>
<Text variant="small-medium">Small Medium</Text>
</div>
<StoryCode
code={`<Text variant="small">Small</Text>
<Text variant="small-medium">Small Medium</Text>`}
/>
<Text variant="subtle">Subtle</Text>
<StoryCode code={`<Text variant="subtle">Subtle</Text>`} />
</div>
</div>
);
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 41 KiB

View File

@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" fill="none" viewBox="0 0 48 48"><title>Accessibility</title><circle cx="24.334" cy="24" r="24" fill="#A849FF" fill-opacity=".3"/><path fill="#A470D5" fill-rule="evenodd" d="M27.8609 11.585C27.8609 9.59506 26.2497 7.99023 24.2519 7.99023C22.254 7.99023 20.6429 9.65925 20.6429 11.585C20.6429 13.575 22.254 15.1799 24.2519 15.1799C26.2497 15.1799 27.8609 13.575 27.8609 11.585ZM21.8922 22.6473C21.8467 23.9096 21.7901 25.4788 21.5897 26.2771C20.9853 29.0462 17.7348 36.3314 17.3325 37.2275C17.1891 37.4923 17.1077 37.7955 17.1077 38.1178C17.1077 39.1519 17.946 39.9902 18.9802 39.9902C19.6587 39.9902 20.253 39.6293 20.5814 39.0889L20.6429 38.9874L24.2841 31.22C24.2841 31.22 27.5529 37.9214 27.9238 38.6591C28.2948 39.3967 28.8709 39.9902 29.7168 39.9902C30.751 39.9902 31.5893 39.1519 31.5893 38.1178C31.5893 37.7951 31.3639 37.2265 31.3639 37.2265C30.9581 36.3258 27.698 29.0452 27.0938 26.2771C26.8975 25.4948 26.847 23.9722 26.8056 22.7236C26.7927 22.333 26.7806 21.9693 26.7653 21.6634C26.7008 21.214 27.0231 20.8289 27.4097 20.7005L35.3366 18.3253C36.3033 18.0685 36.8834 16.9773 36.6256 16.0144C36.3678 15.0515 35.2722 14.4737 34.3055 14.7305C34.3055 14.7305 26.8619 17.1057 24.2841 17.1057C21.7062 17.1057 14.456 14.7947 14.456 14.7947C13.4893 14.5379 12.3937 14.9873 12.0715 15.9502C11.7493 16.9131 12.3293 18.0044 13.3604 18.3253L21.2873 20.7005C21.674 20.8289 21.9318 21.214 21.9318 21.6634C21.9174 21.9493 21.9053 22.2857 21.8922 22.6473Z" clip-rule="evenodd"/></svg>

Before

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 456 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 829 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 43 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 48 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 43 KiB

View File

@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" width="33" height="32" fill="none" viewBox="0 0 33 32"><g clip-path="url(#clip0_10031_177597)"><path fill="#B7F0EF" fill-rule="evenodd" d="M17 7.87059C17 6.48214 17.9812 5.28722 19.3431 5.01709L29.5249 2.99755C31.3238 2.64076 33 4.01717 33 5.85105V22.1344C33 23.5229 32.0188 24.7178 30.6569 24.9879L20.4751 27.0074C18.6762 27.3642 17 25.9878 17 24.1539L17 7.87059Z" clip-rule="evenodd" opacity=".7"/><path fill="#87E6E5" fill-rule="evenodd" d="M1 5.85245C1 4.01857 2.67623 2.64215 4.47507 2.99895L14.6569 5.01848C16.0188 5.28861 17 6.48354 17 7.87198V24.1553C17 25.9892 15.3238 27.3656 13.5249 27.0088L3.34311 24.9893C1.98119 24.7192 1 23.5242 1 22.1358V5.85245Z" clip-rule="evenodd"/><path fill="#61C1FD" fill-rule="evenodd" d="M15.543 5.71289C15.543 5.71289 16.8157 5.96289 17.4002 6.57653C17.9847 7.19016 18.4521 9.03107 18.4521 9.03107C18.4521 9.03107 18.4521 25.1106 18.4521 26.9629C18.4521 28.8152 19.3775 31.4174 19.3775 31.4174L17.4002 28.8947L16.2575 31.4174C16.2575 31.4174 15.543 29.0765 15.543 27.122C15.543 25.1674 15.543 5.71289 15.543 5.71289Z" clip-rule="evenodd"/></g><defs><clipPath id="clip0_10031_177597"><rect width="32" height="32" fill="#fff" transform="translate(0.5)"/></clipPath></defs></svg>

Before

Width:  |  Height:  |  Size: 1.2 KiB

View File

@@ -0,0 +1,252 @@
import type { Meta, StoryObj } from "@storybook/react";
import { Text } from "@/components/_new/Text/Text";
import { StoryCode } from "@/stories/helpers/StoryCode";
import { SquareArrowOutUpRight } from "lucide-react";
const meta: Meta = {
title: "Design System/ Tokens /Border Radius",
parameters: {
layout: "fullscreen",
controls: { disable: true },
},
};
export default meta;
// Border radius scale data with rem and px values
// https://tailwindcss.com/docs/border-radius
const borderRadiusScale = [
{ name: "none", value: "0px", rem: "0rem", px: "0px", class: "rounded-none" },
{
name: "sm",
value: "0.125rem",
rem: "0.125rem",
px: "2px",
class: "rounded-sm",
},
{
name: "DEFAULT",
value: "0.25rem",
rem: "0.25rem",
px: "4px",
class: "rounded",
},
{
name: "md",
value: "0.375rem",
rem: "0.375rem",
px: "6px",
class: "rounded-md",
},
{
name: "lg",
value: "0.5rem",
rem: "0.5rem",
px: "8px",
class: "rounded-lg",
},
{
name: "xl",
value: "0.75rem",
rem: "0.75rem",
px: "12px",
class: "rounded-xl",
},
{ name: "2xl", value: "1rem", rem: "1rem", px: "16px", class: "rounded-2xl" },
{
name: "3xl",
value: "1.5rem",
rem: "1.5rem",
px: "24px",
class: "rounded-3xl",
},
{
name: "full",
value: "9999px",
rem: "9999px",
px: "9999px",
class: "rounded-full",
},
];
export function AllVariants() {
return (
<div className="space-y-12">
{/* Border Radius System Documentation */}
<div className="space-y-8">
<div>
<Text variant="h1" className="mb-4 text-zinc-800">
Border Radius
</Text>
<Text variant="large" className="text-zinc-600">
Our border radius system uses a consistent scale to create visual
hierarchy and maintain design consistency across all components.
From subtle rounded corners to fully circular elements.
</Text>
</div>
<div className="grid gap-8 md:grid-cols-2">
<div>
<Text
variant="h2"
className="mb-2 text-xl font-semibold text-zinc-800"
>
Tailwind utilities
</Text>
<div className="space-y-4">
<div className="rounded-lg border border-gray-200 p-4">
<a
href="https://tailwindcss.com/docs/border-radius"
target="_blank"
rel="noopener noreferrer"
className="mb-2 inline-flex flex-row items-center gap-1 text-base font-semibold text-blue-600 hover:underline"
>
Border Radius Classes{" "}
<SquareArrowOutUpRight className="inline-block h-3 w-3" />
</a>
<Text variant="body" className="mb-2 text-zinc-600">
Used to round the corners of elements
</Text>
<div className="font-mono text-sm text-zinc-800">
rounded-lg border-radius: 0.5rem (8px)
</div>
</div>
<div className="rounded-lg border border-gray-200 p-4">
<Text
variant="body-medium"
className="mb-2 font-semibold text-zinc-800"
>
Directional Classes
</Text>
<Text variant="body" className="mb-2 text-zinc-600">
Apply radius to specific corners or sides
</Text>
<div className="space-y-1 font-mono text-sm text-zinc-800">
<div>rounded-t-lg top corners</div>
<div>rounded-r-lg right corners</div>
<div>rounded-b-lg bottom corners</div>
<div>rounded-l-lg left corners</div>
</div>
</div>
<Text variant="body" className="mb-4 text-zinc-600">
We follow Tailwind CSS border radius system, which provides a
comprehensive set of radius values for different use cases.
</Text>
</div>
</div>
<div>
<Text
variant="h2"
className="mb-2 text-xl font-semibold text-zinc-800"
>
FAQ
</Text>
<div className="space-y-4">
<Text
variant="h3"
className="mb-2 text-base font-semibold text-zinc-800"
>
🤔 Why use border radius tokens?
</Text>
<div className="space-y-3 text-zinc-600">
<Text variant="body">
Always use radius classes instead of arbitrary values.
Reasons:
</Text>
<ul className="ml-4 list-disc space-y-1 text-sm">
<li>Ensures consistent corner rounding across components</li>
<li>Creates visual hierarchy through systematic scaling</li>
<li>Maintains design cohesion and brand consistency</li>
<li>Easier to maintain and update globally</li>
<li>Prevents inconsistent corner treatments</li>
</ul>
</div>
</div>
</div>
</div>
</div>
{/* Complete Border Radius Scale */}
<div className="space-y-8">
<div>
<Text
variant="h2"
className="mb-2 text-xl font-semibold text-zinc-800"
>
Complete Border Radius Scale
</Text>
<Text variant="body" className="mb-6 text-zinc-600">
All available border radius values in our design system. Each value
can be applied to all corners or specific corners/sides.
</Text>
</div>
<div className="space-y-4">
{borderRadiusScale.map((radius) => (
<div
key={radius.name}
className="flex items-center rounded-lg border border-gray-200 p-4"
>
<div className="flex w-32 flex-col">
<Text variant="body-medium" className="font-mono text-zinc-800">
{radius.name}
</Text>
<Text variant="small" className="font-mono text-zinc-500">
{radius.class}
</Text>
</div>
<div className="flex w-32 flex-col text-right">
<p className="font-mono text-xs text-zinc-500">{radius.rem}</p>
<p className="font-mono text-xs text-zinc-500">{radius.px}</p>
</div>
<div className="ml-8 flex-1">
<div className="flex items-center gap-4">
<div
className="h-16 w-16 bg-blue-500"
style={{ borderRadius: radius.value }}
></div>
<div
className="h-12 w-24 bg-green-500"
style={{ borderRadius: radius.value }}
></div>
<div
className="h-8 w-32 bg-purple-500"
style={{ borderRadius: radius.value }}
></div>
</div>
</div>
</div>
))}
</div>
<StoryCode
code={`// Border radius examples
<div className="rounded-none">No rounding (0px)</div>
<div className="rounded-sm">Small rounding (2px)</div>
<div className="rounded">Default rounding (4px)</div>
<div className="rounded-md">Medium rounding (6px)</div>
<div className="rounded-lg">Large rounding (8px)</div>
<div className="rounded-xl">Extra large rounding (12px)</div>
<div className="rounded-2xl">2X large rounding (16px)</div>
<div className="rounded-3xl">3X large rounding (24px)</div>
<div className="rounded-full">Fully rounded (circular)</div>
// Directional rounding
<div className="rounded-t-lg">Top corners only</div>
<div className="rounded-r-lg">Right corners only</div>
<div className="rounded-b-lg">Bottom corners only</div>
<div className="rounded-l-lg">Left corners only</div>
// Individual corners
<div className="rounded-tl-lg">Top-left corner</div>
<div className="rounded-tr-lg">Top-right corner</div>
<div className="rounded-bl-lg">Bottom-left corner</div>
<div className="rounded-br-lg">Bottom-right corner</div>`}
/>
</div>
</div>
);
}
type Story = StoryObj<typeof meta>;

View File

@@ -0,0 +1,11 @@
type Props = {
code: string;
};
export function StoryCode(props: Props) {
return (
<pre className="block rounded border bg-zinc-100 px-3 py-2 font-mono text-xs text-indigo-800 shadow-sm">
{props.code}
</pre>
);
}

View File

@@ -66,6 +66,7 @@ The platform comes pre-integrated with cutting-edge LLM providers:
- OpenAI
- Anthropic
- AI/ML API
- Groq
- Llama