Skip to content

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

feat(chat): implement AI SDK integration with custom streaming response handling (#11901)

Abhimanyu Yadav7d4c020a9bd6
diff --git a/.github/workflows/platform-fullstack-ci.yml b/.github/workflows/platform-fullstack-ci.yml
index 67be0ae939..ab483b98af 100644
--- a/.github/workflows/platform-fullstack-ci.yml
+++ b/.github/workflows/platform-fullstack-ci.yml
@@ -56,7 +56,7 @@ jobs:
run: pnpm install --frozen-lockfile
types:
- runs-on: ubuntu-latest
+ runs-on: big-boi
needs: setup
strategy:
fail-fast: false
@@ -85,7 +85,7 @@ jobs:
- name: Run docker compose
run: |
- docker compose -f ../docker-compose.yml --profile local --profile deps_backend up -d
+ docker compose -f ../docker-compose.yml --profile local up -d deps_backend
- name: Restore dependencies cache
uses: actions/cache@v5
diff --git a/autogpt_platform/backend/backend/api/features/chat/response_model.py b/autogpt_platform/backend/backend/api/features/chat/response_model.py
index f627a42fcc..1ae836f7d1 100644
--- a/autogpt_platform/backend/backend/api/features/chat/response_model.py
+++ b/autogpt_platform/backend/backend/api/features/chat/response_model.py
@@ -18,6 +18,10 @@ class ResponseType(str, Enum):
START = "start"
FINISH = "finish"
+ # Step lifecycle (one LLM API call within a message)
+ START_STEP = "start-step"
+ FINISH_STEP = "finish-step"
+
# Text streaming
TEXT_START = "text-start"
TEXT_DELTA = "text-delta"
@@ -57,6 +61,16 @@ class StreamStart(StreamBaseResponse):
description="Task ID for SSE reconnection. Clients can reconnect using GET /tasks/{taskId}/stream",
)
+ def to_sse(self) -> str:
+ """Convert to SSE format, excluding non-protocol fields like taskId."""
+ import json
+
+ data: dict[str, Any] = {
+ "type": self.type.value,
+ "messageId": self.messageId,
+ }
+ return f"data: {json.dumps(data)}\n\n"
+
class StreamFinish(StreamBaseResponse):
"""End of message/stream."""
@@ -64,6 +78,26 @@ class StreamFinish(StreamBaseResponse):
type: ResponseType = ResponseType.FINISH
+class StreamStartStep(StreamBaseResponse):
+ """Start of a step (one LLM API call within a message).
+
+ The AI SDK uses this to add a step-start boundary to message.parts,
+ enabling visual separation between multiple LLM calls in a single message.
+ """
+
+ type: ResponseType = ResponseType.START_STEP
+
+
+class StreamFinishStep(StreamBaseResponse):
+ """End of a step (one LLM API call within a message).
+
+ The AI SDK uses this to reset activeTextParts and activeReasoningParts,
+ so the next LLM call in a tool-call continuation starts with clean state.
+ """
+
+ type: ResponseType = ResponseType.FINISH_STEP
+
+
# ========== Text Streaming ==========
@@ -117,7 +151,7 @@ class StreamToolOutputAvailable(StreamBaseResponse):
type: ResponseType = ResponseType.TOOL_OUTPUT_AVAILABLE
toolCallId: str = Field(..., description="Tool call ID this responds to")
output: str | dict[str, Any] = Field(..., description="Tool execution output")
- # Additional fields for internal use (not part of AI SDK spec but useful)
+ # Keep these for internal backend use
toolName: str | None = Field(
default=None, description="Name of the tool that was executed"
)
@@ -125,6 +159,17 @@ class StreamToolOutputAvailable(StreamBaseResponse):
default=True, description="Whether the tool execution succeeded"
)
+ def to_sse(self) -> str:
+ """Convert to SSE format, excluding non-spec fields."""
+ import json
+
+ data = {
+ "type": self.type.value,
+ "toolCallId": self.toolCallId,
+ "output": self.output,
+ }
+ return f"data: {json.dumps(data)}\n\n"
+
# ========== Other ==========
diff --git a/autogpt_platform/backend/backend/api/features/chat/routes.py b/autogpt_platform/backend/backend/api/features/chat/routes.py
index 74e6e8ba1e..c6f37569b7 100644
--- a/autogpt_platform/backend/backend/api/features/chat/routes.py
+++ b/autogpt_platform/backend/backend/api/features/chat/routes.py
@@ -6,7 +6,7 @@ from collections.abc import AsyncGenerator
from typing import Annotated
from autogpt_libs import auth
-from fastapi import APIRouter, Depends, Header, HTTPException, Query, Security
+from fastapi import APIRouter, Depends, Header, HTTPException, Query, Response, Security
from fastapi.responses import StreamingResponse
from pydantic import BaseModel
@@ -17,7 +17,29 @@ from . import stream_registry
from .completion_handler import process_operation_failure, process_operation_success
from .config import ChatConfig
from .model import ChatSession, create_chat_session, get_chat_session, get_user_sessions
-from .response_model import StreamFinish, StreamHeartbeat, StreamStart
+from .response_model import StreamFinish, StreamHeartbeat
+from .tools.models import (
+ AgentDetailsResponse,
+ AgentOutputResponse,
+ AgentPreviewResponse,
+ AgentSavedResponse,
+ AgentsFoundResponse,
+ BlockListResponse,
+ BlockOutputResponse,
+ ClarificationNeededResponse,
+ DocPageResponse,
+ DocSearchResultsResponse,
+ ErrorResponse,
+ ExecutionStartedResponse,
+ InputValidationErrorResponse,
+ NeedLoginResponse,
+ NoResultsResponse,
+ OperationInProgressResponse,
+ OperationPendingResponse,
+ OperationStartedResponse,
+ SetupRequirementsResponse,
+ UnderstandingUpdatedResponse,
+)
config = ChatConfig()
@@ -269,8 +291,6 @@ async def stream_chat_post(
import time
stream_start_time = time.perf_counter()
-
- # Base log metadata (task_id added after creation)
log_meta = {"component": "ChatStream", "session_id": session_id}
if user_id:
log_meta["user_id"] = user_id
@@ -328,24 +348,6 @@ async def stream_chat_post(
first_chunk_time, ttfc = None, None
chunk_count = 0
try:
- # Emit a start event with task_id for reconnection
- start_chunk = StreamStart(messageId=task_id, taskId=task_id)
- await stream_registry.publish_chunk(task_id, start_chunk)
- logger.info(
- f"[TIMING] StreamStart published at {(time_module.perf_counter() - gen_start_time)*1000:.1f}ms",
- extra={
- "json_fields": {
- **log_meta,
- "elapsed_ms": (time_module.perf_counter() - gen_start_time)
- * 1000,
- }
- },
- )
-
- logger.info(
- "[TIMING] Calling stream_chat_completion",
- extra={"json_fields": log_meta},
- )
async for chunk in chat_service.stream_chat_completion(
session_id,
request.message,
@@ -353,6 +355,7 @@ async def stream_chat_post(
user_id=user_id,
session=session, # Pass pre-fetched session to avoid double-fetch
context=request.context,
+ _task_id=task_id, # Pass task_id so service emits start with taskId for reconnection
):
chunk_count += 1
if first_chunk_time is None:
@@ -388,7 +391,6 @@ async def stream_chat_post(
}
},
)
-
await stream_registry.mark_task_completed(task_id, "completed")
except Exception as e:
elapsed = time_module.perf_counter() - gen_start_time
@@ -428,34 +430,13 @@ async def stream_chat_post(
chunks_yielded = 0
try:
# Subscribe to the task stream (this replays existing messages + live updates)
- subscribe_start = time_module.perf_counter()
- logger.info(
- "[TIMING] Calling subscribe_to_task",
- extra={"json_fields": log_meta},
- )
subscriber_queue = await stream_registry.subscribe_to_task(
task_id=task_id,
user_id=user_id,
last_message_id="0-0", # Get all messages from the beginning
)
- subscribe_time = (time_module.perf_counter() - subscribe_start) * 1000
- logger.info(
- f"[TIMING] subscribe_to_task completed in {subscribe_time:.1f}ms, "
- f"queue_ok={subscriber_queue is not None}",
- extra={
- "json_fields": {
- **log_meta,
- "duration_ms": subscribe_time,
- "queue_obtained": subscriber_queue is not None,
- }
- },
- )
if subscriber_queue is None:
- logger.info(
- "[TIMING] subscriber_queue is None, yielding finish",
- extra={"json_fields": log_meta},
- )
yield StreamFinish().to_sse()
yield "data: [DONE]\n\n"
return
@@ -467,11 +448,7 @@ async def stream_chat_post(
)
while True:
try:
- queue_wait_start = time_module.perf_counter()
chunk = await asyncio.wait_for(subscriber_queue.get(), timeout=30.0)
- queue_wait_time = (
- time_module.perf_counter() - queue_wait_start
- ) * 1000
chunks_yielded += 1
if not first_chunk_yielded:
@@ -479,26 +456,12 @@ async def stream_chat_post(
elapsed = time_module.perf_counter() - event_gen_start
logger.info(
f"[TIMING] FIRST CHUNK from queue at {elapsed:.2f}s, "
- f"type={type(chunk).__name__}, "
- f"wait={queue_wait_time:.1f}ms",
- extra={
- "json_fields": {
- **log_meta,
- "chunk_type": type(chunk).__name__,
- "elapsed_ms": elapsed * 1000,
- "queue_wait_ms": queue_wait_time,
- }
- },
- )
- elif chunks_yielded % 50 == 0:
- logger.info(
- f"[TIMING] Chunk #{chunks_yielded}, "
f"type={type(chunk).__name__}",
extra={
"json_fields": {
**log_meta,
- "chunk_number": chunks_yielded,
"chunk_type": type(chunk).__name__,
+ "elapsed_ms": elapsed * 1000,
}
},
)
@@ -521,13 +484,6 @@ async def stream_chat_post(
)
break
except asyncio.TimeoutError:
- # Send heartbeat to keep connection alive
- logger.info(
- f"[TIMING] Heartbeat timeout, chunks_so_far={chunks_yielded}",
- extra={
- "json_fields": {**log_meta, "chunks_so_far": chunks_yielded}
- },
- )
yield StreamHeartbeat().to_sse()
except GeneratorExit:
@@ -592,63 +548,90 @@ async def stream_chat_post(
@router.get(
"/sessions/{session_id}/stream",
)
-async def stream_chat_get(
+async def resume_session_stream(
session_id: str,
- message: Annotated[str, Query(min_length=1, max_length=10000)],
user_id: str | None = Depends(auth.get_user_id),
- is_user_message: bool = Query(default=True),
):
"""
- Stream chat responses for a session (GET - legacy endpoint).
+ Resume an active stream for a session.
- Streams the AI/completion responses in real time over Server-Sent Events (SSE), including:
- - Text fragments as they are generated
- - Tool call UI elements (if invoked)
- - Tool execution results
+ Called by the AI SDK's ``useChat(resume: true)`` on page load.
+ Checks for an active (in-progress) task on the session and either replays
+ the full SSE stream or returns 204 No Content if nothing is running.
Args:
- session_id: The chat session identifier to associate with the streamed messages.
- message: The user's new message to process.
+ session_id: The chat session identifier.
user_id: Optional authenticated user ID.
- is_user_message: Whether the message is a user message.
- Returns:
- StreamingResponse: SSE-formatted response chunks.
+ Returns:
+ StreamingResponse (SSE) when an active stream exists,
+ or 204 No Content when there is nothing to resume.
"""
- session = await _validate_and_get_session(session_id, user_id)
+ import asyncio
+
+ active_task, _last_id = await stream_registry.get_active_task_for_session(
+ session_id, user_id
+ )
+
+ if not active_task:
+ return Response(status_code=204)
+
+ subscriber_queue = await stream_registry.subscribe_to_task(
+ task_id=active_task.task_id,
+ user_id=user_id,
+ last_message_id="0-0", # Full replay so useChat rebuilds the message
+ )
+
+ if subscriber_queue is None:
+ return Response(status_code=204)
async def event_generator() -> AsyncGenerator[str, None]:
chunk_count = 0
first_chunk_type: str | None = None
- async for chunk in chat_service.stream_chat_completion(
- session_id,
- message,
- is_user_message=is_user_message,
- user_id=user_id,
- session=session, # Pass pre-fetched session to avoid double-fetch
- ):
- if chunk_count < 3:
- logger.info(
- "Chat stream chunk",
- extra={
- "session_id": session_id,
- "chunk_type": str(chunk.type),
- },
+ try:
+ while True:
+ try:
+ chunk = await asyncio.wait_for(subscriber_queue.get(), timeout=30.0)
+ if chunk_count < 3:
+ logger.info(
+ "Resume stream chunk",
+ extra={
+ "session_id": session_id,
+ "chunk_type": str(chunk.type),
+ },
+ )
+ if not first_chunk_type:
+ first_chunk_type = str(chunk.type)
+ chunk_count += 1
+ yield chunk.to_sse()
+
+ if isinstance(chunk, StreamFinish):
+ break
+ except asyncio.TimeoutError:
+ yield StreamHeartbeat().to_sse()
+ except GeneratorExit:
+ pass
+ except Exception as e:
+ logger.error(f"Error in resume stream for session {session_id}: {e}")
+ finally:
+ try:
+ await stream_registry.unsubscribe_from_task(
+ active_task.task_id, subscriber_queue
)
- if not first_chunk_type:
- first_chunk_type = str(chunk.type)
- chunk_count += 1
- yield chunk.to_sse()
- logger.info(
- "Chat stream completed",
- extra={
- "session_id": session_id,
- "n_chunks": chunk_count,
- "first_chunk_type": first_chunk_type,
- },
- )
- # AI SDK protocol termination
- yield "data: [DONE]\n\n"
+ except Exception as unsub_err:
+ logger.error(
+ f"Error unsubscribing from task {active_task.task_id}: {unsub_err}",
+ exc_info=True,
+ )
+ logger.info(
+ "Resume stream completed",
+ extra={
+ "session_id": session_id,
+ "n_chunks": chunk_count,
+ "first_chunk_type": first_chunk_type,
+ },
+ )
+ yield "data: [DONE]\n\n"
return StreamingResponse(
event_generator(),
@@ -656,8 +639,8 @@ async def stream_chat_get(
headers={
"Cache-Control": "no-cache",
"Connection": "keep-alive",
- "X-Accel-Buffering": "no", # Disable nginx buffering
- "x-vercel-ai-ui-message-stream": "v1", # AI SDK protocol header
+ "X-Accel-Buffering": "no",
+ "x-vercel-ai-ui-message-stream": "v1",
},
)
@@ -969,3 +952,42 @@ async def health_check() -> dict:
"service": "chat",
"version": "0.1.0",
}
+
+
+# ========== Schema Export (for OpenAPI / Orval codegen) ==========
+
+ToolResponseUnion = (
+ AgentsFoundResponse
+ | NoResultsResponse
+ | AgentDetailsResponse
+ | SetupRequirementsResponse
+ | ExecutionStartedResponse
+ | NeedLoginResponse
+ | ErrorResponse
+ | InputValidationErrorResponse
+ | AgentOutputResponse
+ | UnderstandingUpdatedResponse
+ | AgentPreviewResponse
+ | AgentSavedResponse
+ | ClarificationNeededResponse
+ | BlockListResponse
+ | BlockOutputResponse
+ | DocSearchResultsResponse
+ | DocPageResponse
+ | OperationStartedResponse
+ | OperationPendingResponse
+ | OperationInProgressResponse
+)
+
+
+ "/schema/tool-responses",
+ response_model=ToolResponseUnion,
+ include_in_schema=True,
+ summary="[Dummy] Tool response type export for codegen",
+ description="This endpoint is not meant to be called. It exists solely to "
+ "expose tool response models in the OpenAPI schema for frontend codegen.",
+)
+async def _tool_response_schema() -> ToolResponseUnion: # type: ignore[return]
+ """Never called at runtime. Exists only so Orval generates TS types."""
+ raise HTTPException(status_code=501, detail="Schema-only endpoint")
diff --git a/autogpt_platform/backend/backend/api/features/chat/service.py b/autogpt_platform/backend/backend/api/features/chat/service.py
index da18421b98..49e70265fa 100644
--- a/autogpt_platform/backend/backend/api/features/chat/service.py
+++ b/autogpt_platform/backend/backend/api/features/chat/service.py
@@ -52,8 +52,10 @@ from .response_model import (
StreamBaseResponse,
StreamError,
StreamFinish,
+ StreamFinishStep,
StreamHeartbeat,
StreamStart,
+ StreamStartStep,
StreamTextDelta,
StreamTextEnd,
StreamTextStart,
@@ -351,6 +353,10 @@ async def stream_chat_completion(
retry_count: int = 0,
session: ChatSession | None = None,
context: dict[str, str] | None = None, # {url: str, content: str}
+ _continuation_message_id: (
+ str | None
+ ) = None, # Internal: reuse message ID for tool call continuations
+ _task_id: str | None = None, # Internal: task ID for SSE reconnection support
) -> AsyncGenerator[StreamBaseResponse, None]:
"""Main entry point for streaming chat completions with database handling.
@@ -517,16 +523,21 @@ async def stream_chat_completion(
# Generate unique IDs for AI SDK protocol
import uuid as uuid_module
- message_id = str(uuid_module.uuid4())
+ is_continuation = _continuation_message_id is not None
+ message_id = _continuation_message_id or str(uuid_module.uuid4())
text_block_id = str(uuid_module.uuid4())
- # Yield message start
+ # Only yield message start for the initial call, not for continuations.
setup_time = (time.monotonic() - completion_start) * 1000
logger.info(
f"[TIMING] Setup complete, yielding StreamStart at {setup_time:.1f}ms",
extra={"json_fields": {**log_meta, "setup_time_ms": setup_time}},
)
- yield StreamStart(messageId=message_id)
+ if not is_continuation:
+ yield StreamStart(messageId=message_id, taskId=_task_id)
+
+ # Emit start-step before each LLM call (AI SDK uses this to add step boundaries)
+ yield StreamStartStep()
try:
logger.info(
@@ -632,6 +643,10 @@ async def stream_chat_completion(
)
yield chunk
elif isinstance(chunk, StreamFinish):
+ if has_done_tool_call:
+ # Tool calls happened — close the step but don't send message-level finish.
+ # The continuation will open a new step, and finish will come at the end.
+ yield StreamFinishStep()
if not has_done_tool_call:
# Emit text-end before finish if we received text but haven't closed it
if has_received_text and not text_streaming_ended:
@@ -663,6 +678,8 @@ async def stream_chat_completion(
has_saved_assistant_message = True
has_yielded_end = True
+ # Emit finish-step before finish (resets AI SDK text/reasoning state)
+ yield StreamFinishStep()
yield chunk
elif isinstance(chunk, StreamError):
has_yielded_error = True
@@ -712,6 +729,10 @@ async def stream_chat_completion(
logger.info(
f"Retryable error encountered. Attempt {retry_count + 1}/{config.max_retries}"
)
+ # Close the current step before retrying so the recursive call's
+ # StreamStartStep doesn't produce unbalanced step events.
+ if not has_yielded_end:
+ yield StreamFinishStep()
should_retry = True
else:
# Non-retryable error or max retries exceeded
@@ -747,6 +768,7 @@ async def stream_chat_completion(
error_response = StreamError(errorText=error_message)
yield error_response
if not has_yielded_end:
+ yield StreamFinishStep()
yield StreamFinish()
return
@@ -761,6 +783,8 @@ async def stream_chat_completion(
retry_count=retry_count + 1,
session=session,
context=context,
+ _continuation_message_id=message_id, # Reuse message ID since start was already sent
+ _task_id=_task_id,
):
yield chunk
return # Exit after retry to avoid double-saving in finally block
@@ -830,6 +854,8 @@ async def stream_chat_completion(
session=session, # Pass session object to avoid Redis refetch
context=context,
tool_call_response=str(tool_response_messages),
+ _continuation_message_id=message_id, # Reuse message ID to avoid duplicates
+ _task_id=_task_id,
):
yield chunk
@@ -1686,6 +1712,7 @@ async def _execute_long_running_tool_with_streaming(
task_id,
StreamError(errorText=str(e)),
)
+ await stream_registry.publish_chunk(task_id, StreamFinishStep())
await stream_registry.publish_chunk(task_id, StreamFinish())
await _update_pending_operation(
@@ -1943,6 +1970,7 @@ async def _generate_llm_continuation_with_streaming(
# Publish start event
await stream_registry.publish_chunk(task_id, StreamStart(messageId=message_id))
+ await stream_registry.publish_chunk(task_id, StreamStartStep())
await stream_registry.publish_chunk(task_id, StreamTextStart(id=text_block_id))
# Stream the response
@@ -1966,6 +1994,7 @@ async def _generate_llm_continuation_with_streaming(
# Publish end events
await stream_registry.publish_chunk(task_id, StreamTextEnd(id=text_block_id))
+ await stream_registry.publish_chunk(task_id, StreamFinishStep())
if assistant_content:
# Reload session from DB to avoid race condition with user messages
@@ -2007,4 +2036,5 @@ async def _generate_llm_continuation_with_streaming(
task_id,
StreamError(errorText=f"Failed to generate response: {e}"),
)
+ await stream_registry.publish_chunk(task_id, StreamFinishStep())
await stream_registry.publish_chunk(task_id, StreamFinish())
diff --git a/autogpt_platform/backend/backend/api/features/chat/stream_registry.py b/autogpt_platform/backend/backend/api/features/chat/stream_registry.py
index 509d20d9f4..abc34b1fc9 100644
--- a/autogpt_platform/backend/backend/api/features/chat/stream_registry.py
+++ b/autogpt_platform/backend/backend/api/features/chat/stream_registry.py
@@ -857,8 +857,10 @@ def _reconstruct_chunk(chunk_data: dict) -> StreamBaseResponse | None:
ResponseType,
StreamError,
StreamFinish,
+ StreamFinishStep,
StreamHeartbeat,
StreamStart,
+ StreamStartStep,
StreamTextDelta,
StreamTextEnd,
StreamTextStart,
@@ -872,6 +874,8 @@ def _reconstruct_chunk(chunk_data: dict) -> StreamBaseResponse | None:
type_to_class: dict[str, type[StreamBaseResponse]] = {
ResponseType.START.value: StreamStart,
ResponseType.FINISH.value: StreamFinish,
+ ResponseType.START_STEP.value: StreamStartStep,
+ ResponseType.FINISH_STEP.value: StreamFinishStep,
ResponseType.TEXT_START.value: StreamTextStart,
ResponseType.TEXT_DELTA.value: StreamTextDelta,
ResponseType.TEXT_END.value: StreamTextEnd,
diff --git a/autogpt_platform/frontend/Dockerfile b/autogpt_platform/frontend/Dockerfile
index 2b120af5e1..ab2708f1f9 100644
--- a/autogpt_platform/frontend/Dockerfile
+++ b/autogpt_platform/frontend/Dockerfile
@@ -25,8 +25,12 @@ RUN if [ -f .env.production ]; then \
cp .env.default .env; \
fi
RUN pnpm run generate:api
+# Disable source-map generation in Docker builds to halve webpack memory usage.
+# Source maps are only useful when SENTRY_AUTH_TOKEN is set (Vercel deploys);
+# the Docker image never uploads them, so generating them just wastes RAM.
+ENV NEXT_PUBLIC_SOURCEMAPS="false"
# In CI, we want NEXT_PUBLIC_PW_TEST=true during build so Next.js inlines it
-RUN if [ "$NEXT_PUBLIC_PW_TEST" = "true" ]; then NEXT_PUBLIC_PW_TEST=true NODE_OPTIONS="--max-old-space-size=4096" pnpm build; else NODE_OPTIONS="--max-old-space-size=4096" pnpm build; fi
+RUN if [ "$NEXT_PUBLIC_PW_TEST" = "true" ]; then NEXT_PUBLIC_PW_TEST=true NODE_OPTIONS="--max-old-space-size=8192" pnpm build; else NODE_OPTIONS="--max-old-space-size=8192" pnpm build; fi
# Prod stage - based on NextJS reference Dockerfile https://github.com/vercel/next.js/blob/64271354533ed16da51be5dce85f0dbd15f17517/examples/with-docker/Dockerfile
FROM node:21-alpine AS prod
diff --git a/autogpt_platform/frontend/next.config.mjs b/autogpt_platform/frontend/next.config.mjs
index bb4410039d..9bb5983801 100644
--- a/autogpt_platform/frontend/next.config.mjs
+++ b/autogpt_platform/frontend/next.config.mjs
@@ -1,8 +1,12 @@
import { withSentryConfig } from "@sentry/nextjs";
+// Allow Docker builds to skip source-map generation (halves memory usage).
+// Defaults to true so Vercel/local builds are unaffected.
+const enableSourceMaps = process.env.NEXT_PUBLIC_SOURCEMAPS !== "false";
+
/** @type {import('next').NextConfig} */
const nextConfig = {
- productionBrowserSourceMaps: true,
+ productionBrowserSourceMaps: enableSourceMaps,
// Externalize OpenTelemetry packages to fix Turbopack HMR issues
serverExternalPackages: [
"@opentelemetry/instrumentation",
@@ -14,9 +18,37 @@ const nextConfig = {
serverActions: {
bodySizeLimit: "256mb",
},
- // Increase body size limit for API routes (file uploads) - 256MB to match backend limit
- proxyClientMaxBodySize: "256mb",
middlewareClientMaxBodySize: "256mb",
+ // Limit parallel webpack workers to reduce peak memory during builds.
+ cpus: 2,
+ },
+ // Work around cssnano "Invalid array length" bug in Next.js's bundled
+ // cssnano-simple comment parser when processing very large CSS chunks.
+ // CSS is still bundled correctly; gzip handles most of the size savings anyway.
+ webpack: (config, { dev }) => {
+ if (!dev) {
+ // Next.js adds CssMinimizerPlugin internally (after user config), so we
+ // can't filter it from config.plugins. Instead, intercept the webpack
+ // compilation hooks and replace the buggy plugin's tap with a no-op.
+ config.plugins.push({
+ apply(compiler) {
+ compiler.hooks.compilation.tap(
+ "DisableCssMinimizer",
+ (compilation) => {
+ compilation.hooks.processAssets.intercept({
+ register: (tap) => {
+ if (tap.name === "CssMinimizerPlugin") {
+ return { ...tap, fn: async () => {} };
+ }
+ return tap;
+ },
+ });
+ },
+ );
+ },
+ });
+ }
+ return config;
},
images: {
domains: [
@@ -54,9 +86,16 @@ const nextConfig = {
transpilePackages: ["geist"],
};
-const isDevelopmentBuild = process.env.NODE_ENV !== "production";
+// Only run the Sentry webpack plugin when we can actually upload source maps
+// (i.e. on Vercel with SENTRY_AUTH_TOKEN set). The Sentry *runtime* SDK
+// (imported in app code) still captures errors without the plugin.
+// Skipping the plugin saves ~1 GB of peak memory during `next build`.
+const skipSentryPlugin =
+ process.env.NODE_ENV !== "production" ||
+ !enableSourceMaps ||
+ !process.env.SENTRY_AUTH_TOKEN;
-export default isDevelopmentBuild
+export default skipSentryPlugin
? nextConfig
: withSentryConfig(nextConfig, {
// For all available options, see:
@@ -96,7 +135,7 @@ export default isDevelopmentBuild
// This helps Sentry with sourcemaps... https://docs.sentry.io/platforms/javascript/guides/nextjs/sourcemaps/
sourcemaps: {
- disable: false,
+ disable: !enableSourceMaps,
assets: [".next/**/*.js", ".next/**/*.js.map"],
ignore: ["**/node_modules/**"],
deleteSourcemapsAfterUpload: false, // Source is public anyway :)
diff --git a/autogpt_platform/frontend/package.json b/autogpt_platform/frontend/package.json
index e8c9871a72..5988e59c90 100644
--- a/autogpt_platform/frontend/package.json
+++ b/autogpt_platform/frontend/package.json
@@ -7,7 +7,7 @@
},
"scripts": {
"dev": "pnpm run generate:api:force && next dev --turbo",
- "build": "next build",
+ "build": "cross-env NODE_OPTIONS=--max-old-space-size=16384 next build",
"start": "next start",
"start:standalone": "cd .next/standalone && node server.js",
"lint": "next lint && prettier --check .",
@@ -30,6 +30,7 @@
"defaults"
],
"dependencies": {
+ "@ai-sdk/react": "3.0.61",
"@faker-js/faker": "10.0.0",
"@hookform/resolvers": "5.2.2",
"@next/third-parties": "15.4.6",
@@ -60,6 +61,10 @@
"@rjsf/utils": "6.1.2",
"@rjsf/validator-ajv8": "6.1.2",
"@sentry/nextjs": "10.27.0",
+ "@streamdown/cjk": "1.0.1",
+ "@streamdown/code": "1.0.1",
+ "@streamdown/math": "1.0.1",
+ "@streamdown/mermaid": "1.0.1",
"@supabase/ssr": "0.7.0",
"@supabase/supabase-js": "2.78.0",
"@tanstack/react-query": "5.90.6",
@@ -68,6 +73,7 @@
"@vercel/analytics": "1.5.0",
"@vercel/speed-insights": "1.2.0",
"@xyflow/react": "12.9.2",
+ "ai": "6.0.59",
"boring-avatars": "1.11.2",
"class-variance-authority": "0.7.1",
"clsx": "2.1.1",
@@ -87,7 +93,6 @@
"launchdarkly-react-client-sdk": "3.9.0",
"lodash": "4.17.21",
"lucide-react": "0.552.0",
- "moment": "2.30.1",
"next": "15.4.10",
"next-themes": "0.4.6",
"nuqs": "2.7.2",
@@ -112,9 +117,11 @@
"remark-math": "6.0.0",
"shepherd.js": "14.5.1",
"sonner": "2.0.7",
+ "streamdown": "2.1.0",
"tailwind-merge": "2.6.0",
"tailwind-scrollbar": "3.1.0",
"tailwindcss-animate": "1.0.7",
+ "use-stick-to-bottom": "1.1.2",
"uuid": "11.1.0",
"vaul": "1.1.2",
"zod": "3.25.76",
@@ -172,7 +179,8 @@
},
"pnpm": {
"overrides": {
- "@opentelemetry/instrumentation": "0.209.0"
+ "@opentelemetry/instrumentation": "0.209.0",
+ "lodash-es": "4.17.23"
}
},
"packageManager": "[email protected]+sha512.cf9998222162dd85864d0a8102e7892e7ba4ceadebbf5a31f9c2fce48dfce317a9c53b9f6464d1ef9042cba2e02ae02a9f7c143a2b438cd93c91840f0192b9dd"
diff --git a/autogpt_platform/frontend/pnpm-lock.yaml b/autogpt_platform/frontend/pnpm-lock.yaml
index 377a298564..468e2f312d 100644
--- a/autogpt_platform/frontend/pnpm-lock.yaml
+++ b/autogpt_platform/frontend/pnpm-lock.yaml
@@ -6,11 +6,15 @@ settings:
overrides:
'@opentelemetry/instrumentation': 0.209.0
+ lodash-es: 4.17.23
importers:
.:
dependencies:
+ '@ai-sdk/react':
+ specifier: 3.0.61
'@faker-js/faker':
specifier: 10.0.0
version: 10.0.0
@@ -101,6 +105,18 @@ importers:
'@sentry/nextjs':
specifier: 10.27.0
+ '@streamdown/cjk':
+ specifier: 1.0.1
+ '@streamdown/code':
+ specifier: 1.0.1
+ version: 1.0.1([email protected])
+ '@streamdown/math':
+ specifier: 1.0.1
+ version: 1.0.1([email protected])
+ '@streamdown/mermaid':
+ specifier: 1.0.1
+ version: 1.0.1([email protected])
'@supabase/ssr':
specifier: 0.7.0
version: 0.7.0(@supabase/[email protected])
@@ -125,6 +141,9 @@ importers:
'@xyflow/react':
specifier: 12.9.2
+ ai:
+ specifier: 6.0.59
+ version: 6.0.59([email protected])
boring-avatars:
specifier: 1.11.2
version: 1.11.2
@@ -182,9 +201,6 @@ importers:
lucide-react:
specifier: 0.552.0
version: 0.552.0([email protected])
- moment:
- specifier: 2.30.1
- version: 2.30.1
next:
specifier: 15.4.10
@@ -257,6 +273,9 @@ importers:
sonner:
specifier: 2.0.7
+ streamdown:
+ specifier: 2.1.0
+ version: 2.1.0([email protected])
tailwind-merge:
specifier: 2.6.0
version: 2.6.0
@@ -266,6 +285,9 @@ importers:
tailwindcss-animate:
specifier: 1.0.7
version: 1.0.7([email protected])
+ use-stick-to-bottom:
+ specifier: 1.1.2
+ version: 1.1.2([email protected])
uuid:
specifier: 11.1.0
version: 11.1.0
@@ -417,10 +439,35 @@ packages:
resolution: {integrity: sha512-Elp+iwUx5rN5+Y8xLt5/GRoG20WGoDCQ/1Fb+1LiGtvwbDavuSk0jhD/eZdckHAuzcDzccnkv+rEjyWfRx18gg==}
+ '@ai-sdk/[email protected]':
+ resolution: {integrity: sha512-Pr+ApS9k6/jcR3kNltJNxo60OdYvnVU4DeRhzVtxUAYTXCHx4qO+qTMG9nNRn+El1acJnNRA//Su47srjXkT/w==}
+ engines: {node: '>=18'}
+ peerDependencies:
+ zod: ^3.25.76 || ^4.1.8
+
+ '@ai-sdk/[email protected]':
+ resolution: {integrity: sha512-VeDAiCH+ZK8Xs4hb9Cw7pHlujWNL52RKe8TExOkrw6Ir1AmfajBZTb9XUdKOZO08RwQElIKA8+Ltm+Gqfo8djQ==}
+ engines: {node: '>=18'}
+ peerDependencies:
+ zod: ^3.25.76 || ^4.1.8
+
+ '@ai-sdk/[email protected]':
+ resolution: {integrity: sha512-2Xmoq6DBJqmSl80U6V9z5jJSJP7ehaJJQMy2iFUqTay06wdCqTnPVBBQbtEL8RCChenL+q5DC5H5WzU3vV3v8w==}
+ engines: {node: '>=18'}
+
+ '@ai-sdk/[email protected]':
+ resolution: {integrity: sha512-vCjZBnY2+TawFBXamSKt6elAt9n1MXMfcjSd9DSgT9peCJN27qNGVSXgaGNh/B3cUgeOktFfhB2GVmIqOjvmLQ==}
+ engines: {node: '>=18'}
+ peerDependencies:
+ react: ^18 || ~19.0.1 || ~19.1.2 || ^19.2.1
+
resolution: {integrity: sha512-UrcABB+4bUrFABwbluTIBErXwvbsU/V7TZWfmbgJfbkwiBuziS9gxdODUyuiecfdGQ85jglMW6juS3+z5TsKLw==}
engines: {node: '>=10'}
+ '@antfu/[email protected]':
+ resolution: {integrity: sha512-MGQsmw10ZyI+EJo45CdSER4zEb+p31LpDAFp2Z3gkSd1yqVZGi0Ebx++YTEMonJy4oChEMLsxZ64j8FH6sSqtQ==}
+
'@apidevtools/[email protected]':
resolution: {integrity: sha512-Oc96zvmxx1fqoSEdUmfmvvb59/KDOnUoJ7s2t7bISyAn0XEz57LCCw8k2Y4Pf3mwKaZLMciESALORLgfe2frCw==}
engines: {node: '>= 16'}
@@ -1032,6 +1079,24 @@ packages:
resolution: {integrity: sha512-qQ5m48eI/MFLQ5PxQj4PFaprjyCTLI37ElWMmNs0K8Lk3dVeOdNpB3ks8jc7yM5CDmVC73eMVk/trk3fgmrUpA==}
engines: {node: '>=6.9.0'}
+ '@braintree/[email protected]':
+ resolution: {integrity: sha512-jigsZK+sMF/cuiB7sERuo9V7N9jx+dhmHHnQyDSVdpZwVutaBu7WvNYqMDLSgFgfB30n452TP3vjDAvFC973mA==}
+
+ '@chevrotain/[email protected]':
+ resolution: {integrity: sha512-BvIKpRLeS/8UbfxXxgC33xOumsacaeCKAjAeLyOn7Pcp95HiRbrpl14S+9vaZLolnbssPIUuiUd8IvgkRyt6NQ==}
+
+ '@chevrotain/[email protected]':
+ resolution: {integrity: sha512-+qNfcoNk70PyS/uxmj3li5NiECO+2YKZZQMbmjTqRI3Qchu8Hig/Q9vgkHpI3alNjr7M+a2St5pw5w5F6NL5/Q==}
+
+ '@chevrotain/[email protected]':
+ resolution: {integrity: sha512-1fMHaBZxLFvWI067AVbGJav1eRY7N8DDvYCTwGBiE/ytKBgP8azTdgyrKyWZ9Mfh09eHWb5PgTSO8wi7U824RA==}
+
+ '@chevrotain/[email protected]':
+ resolution: {integrity: sha512-gsiM3G8b58kZC2HaWR50gu6Y1440cHiJ+i3JUvcp/35JchYejb2+5MVeJK0iKThYpAa/P2PYFV4hoi44HD+aHQ==}
+
+ '@chevrotain/[email protected]':
+ resolution: {integrity: sha512-YslZMgtJUyuMbZ+aKvfF3x1f5liK4mWNxghFRv7jqRR9C3R3fAOGTTKvxXDa2Y1s9zSbcpuO0cAxDYsc9SrXoQ==}
+
'@chromatic-com/[email protected]':
resolution: {integrity: sha512-QAWGtHwib0qsP5CcO64aJCF75zpFgpKK3jNpxILzQiPK3sVo4EmnVGJVdwcZWpWrGdH8E4YkncGoitw4EXzKMg==}
engines: {node: '>=20.0.0', yarn: '>=1.22.18'}
@@ -1486,6 +1551,12 @@ packages:
resolution: {integrity: sha512-oT8USsTulFAA8FiBN0lA2rJqQI2lIt+HP2pdakGQXo3EviL2vqJTgpSCRwjl6mLJL158f1BVcdQUOEFGxomK3w==}
engines: {node: '>=16.0.0'}
+ '@iconify/[email protected]':
+ resolution: {integrity: sha512-+wluvCrRhXrhyOmRDJ3q8mux9JkKy5SJ/v8ol2tu4FVjyYvtEzkc/3pK15ET6RKg4b4w4BmTk1+gsCUhf21Ykg==}
+
+ '@iconify/[email protected]':
+ resolution: {integrity: sha512-Zlzem1ZXhI1iHeeERabLNzBHdOa4VhQbqAcOQaMKuTuyZCpwKbC2R4Dd0Zo3g9EAc+Y4fiarO8HIHRAth7+skw==}
+
resolution: {integrity: sha512-A5P/LfWGFSl6nsckYtjw9da+19jB8hkJ6ACTGcDfEJ0aE+l2n2El7dsVM7UVHZQ9s2lmYMWlrS21YLy2IR1LUw==}
engines: {node: '>=18'}
@@ -1705,6 +1776,9 @@ packages:
'@types/react': '>=16'
react: '>=16'
+ '@mermaid-js/[email protected]':
+ resolution: {integrity: sha512-lnjOhe7zyHjc+If7yT4zoedx2vo4sHaTmtkl1+or8BRTnCtDmcTpAjpzDSfCZrshM5bCoz0GyidzadJAH1xobA==}
+
resolution: {integrity: sha512-EFd6cVbHsgLa6wa4RljGj6Wk75qoHxUSyc5asLyyPSyuhIcdS2Q3Phw6ImS1q+CkALthJRShiYfKANcQMuMqsQ==}
engines: {node: '>=18'}
@@ -3019,6 +3093,12 @@ packages:
peerDependencies:
webpack: '>=4.40.0'
+ '@shikijs/[email protected]':
+ resolution: {integrity: sha512-AXSQu/2n1UIQekY8euBJlvFYZIw0PHY63jUzGbrOma4wPxzznJXTXkri+QcHeBNaFxiiOljKxxJkVSoB3PjbyA==}
+
+ '@shikijs/[email protected]':
+ resolution: {integrity: sha512-ATwv86xlbmfD9n9gKRiwuPpWgPENAWCLwYCGz9ugTJlsO2kOzhOkvoyV/UD+tJ0uT7YRyD530x6ugNSffmvIiQ==}
+
'@shikijs/[email protected]':
resolution: {integrity: sha512-OYknTCct6qiwpQDqDdf3iedRdzj6hFlOPv5hMvI+hkWfCKs5mlJ4TXziBG9nyabLwGulrUjHiCq3xCspSzErYQ==}
@@ -3222,6 +3302,26 @@ packages:
typescript:
optional: true
+ '@streamdown/[email protected]':
+ resolution: {integrity: sha512-ElDoEfad2u8iFzmgmEEab15N4mt19r47xeUIPJtHaHVyEF5baojamGo+xw3MywMj2qUsAY3LnTnKbrUtL5tGkg==}
+ peerDependencies:
+ react: ^18.0.0 || ^19.0.0
+
+ '@streamdown/[email protected]':
+ resolution: {integrity: sha512-U9LITfQ28tZYAoY922jdtw1ryg4kgRBdURopqK9hph7G2fBUwPeHthjH7SvaV0fvFv7EqjqCzARJuWUljLe9Ag==}
+ peerDependencies:
+ react: ^18.0.0 || ^19.0.0
+
+ '@streamdown/[email protected]':
+ resolution: {integrity: sha512-R9WdHbpERiRU7WeO7oT1aIbnLJ/jraDr89F7X9x2OM//Y8G8UMATRnLD/RUwg4VLr8Nu7QSIJ0Pa8lXd2meM4Q==}
+ peerDependencies:
+ react: ^18.0.0 || ^19.0.0
+
+ '@streamdown/[email protected]':
+ resolution: {integrity: sha512-LVGbxYd6t1DKMCMqm3cpbfsdD4/EKpQelanOlJaBMKv83kbrl8syZJhVBsd/jka+CawhpeR9xsGQJzSJEpjoVw==}
+ peerDependencies:
+ react: ^18.0.0 || ^19.0.0
+
'@supabase/[email protected]':
resolution: {integrity: sha512-cXDtu1U0LeZj/xfnFoV7yCze37TcbNo8FCxy1FpqhMbB9u9QxxDSW6pA5gm/07Ei7m260Lof4CZx67Cu6DPeig==}
@@ -3344,21 +3444,69 @@ packages:
resolution: {integrity: sha512-hOLWVbm7uRza0BYXpIIW5pxfrKe0W+D5lrFiAEYR+pb6w3N2SwSMaJbXdUfSEv+dT4MfHBLtn5js0LAWaO6otw==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-pYeijfZuBd87T0hGn0FO1vQ/cgLk6E1ALJjfkC0oJ8cbwkZl3TpgS8bVBLZN+2jjGgg38epgxb2zmoGtSfvgMw==}
+
+ '@types/[email protected]':
+ resolution: {integrity: sha512-nH60IZNNxEcrh6L1ZSMNA28rj27ut/2ZmI3r96Zd+1jrZD++zD3LsMIjWlvg4AYrHn/Pqz4CF3veCxGjtbqt7A==}
+
+ '@types/[email protected]':
+ resolution: {integrity: sha512-LFYWWd8nwfwEmTZG9PfQxd17HbNPksHBiJHaKuY1XeqscXacsS2tyoo6OdRsjf+NQYeB6XrNL3a25E3gH69lcg==}
+
resolution: {integrity: sha512-iO90scth9WAbmgv7ogoq57O9YpKmFBbmoEoCHDB2xMBY0+/KVrqAaCDyCE16dUspeOvIxFFRI+0sEtqDqy2b4A==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-BjzLgXGnCWjUSYGfH1cpdo41/hgdWETu4YxpezoztawmqsvCeep+8QGfiY6YbDvfgHz/DkjeIkkZVJavB4a3rg==}
+
+ '@types/[email protected]':
+ resolution: {integrity: sha512-ZMaSKu4THYCU6sV64Lhg6qjf1orxBthaC161plr5KuPHo3CNm8DTHiLw/5Eq2b6TsNP0W0iJrUOFscY6Q450Hw==}
+
+ '@types/[email protected]':
+ resolution: {integrity: sha512-5o9OIAdKkhN1QItV2oqaE5KMIiXAvDWBDPrD85e58Qlz1c1kI/J0NcqbEG88CoTwJrYe7ntUCVfeUl2UJKbWgA==}
+
resolution: {integrity: sha512-HE3jVKlzU9AaMazNufooRJ5ZpWmLIoc90A37WU2JMmeq28w1FQqCZswHZ3xR+SuxYftzHq6WU6KJHvqxKzTxxQ==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-n6QBF9/+XASqcKK6waudgL0pf/S5XHPPI8APyMLLUHd8NqouBGLsU8MgtO7NINGtPBtk9Kko/W4ea0oAspwh9g==}
+
resolution: {integrity: sha512-NcV1JjO5oDzoK26oMzbILE6HW7uVXOHLQvHshBUW4UMdZGfiY6v5BeQwh9a9tCzv+CeefZQHJt5SRgK154RtiA==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-fTAfNmxSb9SOWNB9IoG5c8Hg6R+AzUHDRlsXsDZsNp6sxAEOP0tkP3gKkNSO/qmHPoBFTxNrjDprVHDQDvo5aA==}
+
+ '@types/[email protected]':
+ resolution: {integrity: sha512-ZYeSaCF3p73RdOKcjj+swRlZfnYpK1EbaDiYICEEp5Q6sUiqFaFQ9qgoshp5CzIyyb/yD09kD9o2zEltCexlgw==}
+
+ '@types/[email protected]':
+ resolution: {integrity: sha512-fALi2aI6shfg7vM5KiR1wNJnZ7r6UuggVqtDA+xiEdPZQwy/trcQaHnwShLuLdta2rTymCNpxYTiMZX/e09F4g==}
+
+ '@types/[email protected]':
+ resolution: {integrity: sha512-856sckF0oP/diXtS4jNsiQw/UuK5fQG8l/a9VVLeSouf1/PPbBE1i1W852zVwKwYCBkFJJB7nCFTbk6UMEXBOQ==}
+
+ '@types/[email protected]':
+ resolution: {integrity: sha512-tJFtNoYBtRtkNysX1Xq4sxtjK8YgoWUNpIiUee0/jHGRwqvzYxkq0hGVbbOGSz+JgFxxRu4K8nb3YpG3CMARtg==}
+
resolution: {integrity: sha512-mgLPETlrpVV1YRJIglr4Ez47g7Yxjl1lj7YKsiMCb27VJH9W8NVM6Bb9d8kkpG/uAQS5AmbA48q2IAolKKo1MA==}
resolution: {integrity: sha512-VMZBYyQvbGmWyWVea0EHs/BwLgxc+MKi1zLDCONksozI4YJMcTt8ZEuIR4Sb1MMTE8MMW49v0IwI5+b7RmfWlg==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-ZuWOtMaHCkN9xoeEMr1ubW2nGWsp4nIql+OPQRstu4ypeZ+zk3YKqQT0CXVe/PYqrKpZAi+J9mTs05TKwjXSRA==}
+
+ '@types/[email protected]':
+ resolution: {integrity: sha512-oUzyO1/Zm6rsxKRHA1vH0NEDG58HrT5icx/azi9MF1TWdtttWl0UIUsjEQBBh+SIkrpd21ZjEv7ptxWys1ncsg==}
+
+ '@types/[email protected]':
+ resolution: {integrity: sha512-Imagg1vJ3y76Y2ea0871wpabqp613+8/r0mCLEBfdtqC7xMSfj9idOnmBYyMoULfHePJyxMAw3nWhJxzc+LFwQ==}
+
+ '@types/[email protected]':
+ resolution: {integrity: sha512-iWMJgwkK7yTRmWqRB5plb1kadXyQ5Sj8V/zYlFGMUBbIPKQScw+Dku9cAAMgJG+z5GYDoMjWGLVOvjghDEFnKQ==}
+
resolution: {integrity: sha512-dLmtwB8zkAeO/juAMfnV+sItKjlsw2lKdZVVy6LRr0cBmegxSABiLEpGVmSJJ8O08i4+sGR6qQtb6WtuwJdvVw==}
@@ -3368,6 +3516,9 @@ packages:
resolution: {integrity: sha512-VLvUQ33C+3J+8p+Daf+nYSOsjB4GXp19/S/aGo60m9h1v6XaxjiT82lKVWJCfzhtuZ3yD7i/TPeC/fuKLLOSmg==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-5xg9rC+wWL8kdDj153qZcsJ0FWiFt0J5RB6LYUNZjwSnesfblqrI/bJ1wBdJ8OQfncgbJG5+2F+qfqnqyzYxyg==}
+
resolution: {integrity: sha512-yuzZug1nkAAaBlBBikKZTgzCeA+k1uy4ZFwWANOfKw5z5LRhV0gNA7gNkKm7HoK+HRN0wX3EkxGk0fpbWhmB7g==}
@@ -3380,6 +3531,9 @@ packages:
resolution: {integrity: sha512-iqMC4/YlFCSlO8+2Ii1GGGliCAY4XdeG748w5vQUbevlbDu0zSjH/+jojorQVBK/se0j6DUFNPBGSqD3YWYnDw==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-lZXZ9ckh5R8uiFVt8ogUNf+pIrK4EsWrx2Np75WvF/eTpJ0FMHNhjXk8CKEx/+gpHbNQyJWehbFaTvqmHWB3ww==}
+
resolution: {integrity: sha512-vIChWdVG3LG1SMxEvI/AK+FWJthlrqlTu7fbrlywTkkaONwk/UAGaULXRlf8vkzFBLVm0zkMdCquhL5aOjhXPQ==}
@@ -3404,6 +3558,9 @@ packages:
resolution: {integrity: sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-6C8nqWur3j98U6+lXDfTUWIfgvZU+EumvpHKcYjujKH7woYyLj2sUmff0tRhrqM7BohUw7Pz3ZB1jj2gW9Fvmg==}
+
resolution: {integrity: sha512-WPs+bbQw5aCj+x6laNGWLH3wviHtoCv/P3+otBhbOhJgG8qtpdAMlTCxLtsTWA7LH1Oh/bFCHsBn0TPS5m30EQ==}
@@ -3692,6 +3849,10 @@ packages:
vue-router:
optional: true
+ '@vercel/[email protected]':
+ resolution: {integrity: sha512-Fw28YZpRnA3cAHHDlkt7xQHiJ0fcL+NRcIqsocZQUSmbzeIKRpwttJjik5ZGanXP+vlA4SbTg+AbA3bP363l+w==}
+ engines: {node: '>= 20'}
+
'@vercel/[email protected]':
resolution: {integrity: sha512-y9GVzrUJ2xmgtQlzFP2KhVRoCglwfRQgjyfY607aU0hh0Un6d0OUyrJkjuAlsV18qR4zfoFPs/BiIj9YDS6Wzw==}
peerDependencies:
@@ -3873,6 +4034,12 @@ packages:
resolution: {integrity: sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==}
engines: {node: '>= 14'}
+ resolution: {integrity: sha512-9SfCvcr4kVk4t8ZzIuyHpuL1hFYKsYMQfBSbBq3dipXPa+MphARvI8wHEjNaRqYl3JOsJbWxEBIMqHL0L92mUA==}
+ engines: {node: '>=18'}
+ peerDependencies:
+ zod: ^3.25.76 || ^4.1.8
+
resolution: {integrity: sha512-mv00Te6nmYbRp5DCwclxtt7yV/joXJPGS7nM+97GdxvuttCOfgI3K4U25zboyeX0O+myI8ERluxQe5wljMmVIw==}
peerDependencies:
@@ -4227,6 +4394,14 @@ packages:
resolution: {integrity: sha512-PAJdDJusoxnwm1VwW07VWwUN1sl7smmC3OKggvndJFadxxDRyFJBX/ggnu/KE4kQAB7a3Dp8f/YXC1FlUprWmA==}
engines: {node: '>= 16'}
+ resolution: {integrity: sha512-b7g+y9A0v4mxCW1qUhf3BSVPg+/NvGErk/dOkrDaHA0nQIQGAtrOjlX//9OQtRlSCy+x9rfB5N8yC71lH1nvMw==}
+ peerDependencies:
+ chevrotain: ^11.0.0
+
+ resolution: {integrity: sha512-ci2iJH6LeIkvP9eJW6gpueU8cnZhv85ELY8w8WiFtNjMHA5ad6pQLaJo9mEly/9qUyCpvqX8/POVUTf18/HFdw==}
+
resolution: {integrity: sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==}
engines: {node: '>= 8.10.0'}
@@ -4325,6 +4500,10 @@ packages:
resolution: {integrity: sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA==}
engines: {node: '>= 6'}
+ resolution: {integrity: sha512-QrWXB+ZQSVPmIWIhtEO9H+gwHaMGYiF5ChvoJ+K9ZGHG/sVsa6yiesAD1GC/x46sET00Xlwo1u49RVVVzvcSkw==}
+ engines: {node: '>= 10'}
+
resolution: {integrity: sha512-OkTL9umf+He2DZkUq8f8J9of7yL6RJKI24dVITBmNfZBmri9zYZQrKkuXiKhyfPSu8tUhnVBB1iKXevvnlR4Ww==}
engines: {node: '>= 12'}
@@ -4346,6 +4525,9 @@ packages:
engines: {node: '>=18'}
hasBin: true
+ resolution: {integrity: sha512-RMtmw0iFkeR4YV+fUOSucriAQNb9g8zFR52MWCtl+cCZOFRNL6zeB395vPzFhEjjn4fMxXudmELnl/KF/WrK6w==}
+
resolution: {integrity: sha512-ZMkYO/LkF17QvCPqM0gxw8yUzigAOZOSWSHg91FH6orS7vcEj5dVZTidN2fQ14yBSdg97RqhSNwLUXInd52OTA==}
@@ -4374,6 +4556,12 @@ packages:
resolution: {integrity: sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==}
+ resolution: {integrity: sha512-s9whTXInMSgAp/NVXVNuVxVKzGH2qck3aQlVHxDCdAEPgtMKwc4Wq6/QKhgdEdgbLSi9rBTAcPoRa6JpiG4ksg==}
+
+ resolution: {integrity: sha512-AzlgcsCbUMymkADOJtQm3wO9S3ltPfYOFD5033keQn9NJzIbtnZj+UdBJe7DYml/8TdbtHJW3j58SOnKhWY/5g==}
+
resolution: {integrity: sha512-AdmX6xUzdNASswsFtmwSt7Vj8po9IuqXm0UXz7QKPuEUmPB4XyjGfaAr2PSuELMwkRMVH1EpIkX5bTZGRB3eCA==}
engines: {node: '>=10'}
@@ -4447,14 +4635,51 @@ packages:
resolution: {integrity: sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==}
+ resolution: {integrity: sha512-wgQlVIUJF13Quxiv5e1gstZ08rnZj2XaLHGoFMYXz7SkNfCDOOteKBE6SYRfA9WxxI/iBc3ajfDoc6hb/MRAHQ==}
+ peerDependencies:
+ cytoscape: ^3.2.0
+
+ resolution: {integrity: sha512-ki1/VuRIHFCzxWNrsshHYPs6L7TvLu3DL+TyIGEsRcvVERmxokbf5Gdk7mFxZnTdiGtnA4cfSmjZJMviqSuZrQ==}
+ peerDependencies:
+ cytoscape: ^3.2.0
+
+ resolution: {integrity: sha512-iJc4TwyANnOGR1OmWhsS9ayRS3s+XQ185FmuHObThD+5AeJCakAAbWv8KimMTt08xCCLNgneQwFp+JRJOr9qGQ==}
+ engines: {node: '>=0.10'}
+
+ resolution: {integrity: sha512-B0ErZK/66mHtEsR1TkPEEkwdy+WDesimkM5gpZr5Dsg54BiTA5RXtYW5qTLIAcekaS9xfZrzBLF/OAkB3Qn1YQ==}
+
resolution: {integrity: sha512-tdQAmyA18i4J7wprpYq8ClcxZy3SC31QMeByyCFyRt7BVHdREQZ5lpzoe5mFEYZUWe+oq8HBvk9JjpibyEV4Jg==}
engines: {node: '>=12'}
+ resolution: {integrity: sha512-IH5tgjV4jE/GhHkRV0HiVYPDtvfjHQlQfJHs0usq7M30XcSBvOotpmH1IgkcXsO/5gEQZD43B//fc7SRT5S+xw==}
+ engines: {node: '>=12'}
+
+ resolution: {integrity: sha512-ALnjWlVYkXsVIGlOsuWH1+3udkYFI48Ljihfnh8FZPF2QS9o+PzGLBslO0PjzVoHLZ2KCVgAM8NVkXPJB2aNnQ==}
+ engines: {node: '>=12'}
+
+ resolution: {integrity: sha512-VE5S6TNa+j8msksl7HwjxMHDM2yNK3XCkusIlpX5kwauBfXuyLAtNg9jCp/iHH61tgI4sb6R/EIMWCqEIdjT/g==}
+ engines: {node: '>=12'}
+
resolution: {integrity: sha512-zg/chbXyeBtMQ1LbD/WSoW2DpC3I0mpmPdW+ynRTj/x2DAWYrIY7qeZIHidozwV24m4iavr15lNwIwLxRmOxhA==}
engines: {node: '>=12'}
+ resolution: {integrity: sha512-4EzFTRIikzs47RGmdxbeUvLWtGedDUNkTcmzoeyg4sP/dvCexO47AaQL7VKy/gul85TOxw+IBgA8US2xwbToNA==}
+ engines: {node: '>=12'}
+
+ resolution: {integrity: sha512-mdjtIZ1XLAM8bm/hx3WwjfHt6Sggek7qH043O8KEjDXN40xi3vx/6pYSVTwLjEgiXQTbvaouWKynLBiUZ6SK6A==}
+ engines: {node: '>=12'}
+
resolution: {integrity: sha512-rzUyPU/S7rwUflMyLc1ETDeBj0NRuHKKAcvukozwhshr6g6c5d8zh4c2gQjY2bZ0dXeGLWc1PF174P2tVvKhfg==}
engines: {node: '>=12'}
@@ -4463,22 +4688,65 @@ packages:
resolution: {integrity: sha512-pWbUJLdETVA8lQNJecMxoXfH6x+mO2UQo8rSmZ+QqxcbyA3hfeprFgIT//HW2nlHChWeIIMwS2Fq+gEARkhTkg==}
engines: {node: '>=12'}
+ resolution: {integrity: sha512-UG6OvdI5afDIFP9w4G0mNq50dSOsXHJaRE8arAS5o9ApWnIElp8GZw1Dun8vP8OyHOZ/QJUKUJwxiiCCnUwm+Q==}
+ engines: {node: '>=12'}
+ hasBin: true
+
resolution: {integrity: sha512-wR/XK3D3XcLIZwpbvQwQ5fK+8Ykds1ip7A2Txe0yxncXSdq1L9skcG7blcedkOX+ZcgxGAmLX1FrRGbADwzi0w==}
engines: {node: '>=12'}
+ resolution: {integrity: sha512-kpkQIM20n3oLVBKGg6oHrUchHM3xODkTzjMoj7aWQFq5QEM+R6E4WkzT5+tojDY7yjez8KgCBRoj4aEr99Fdqw==}
+ engines: {node: '>=12'}
+
+ resolution: {integrity: sha512-zxV/SsA+U4yte8051P4ECydjD/S+qeYtnaIyAs9tgHCqfguma/aAQDjo85A9Z6EKhBirHRJHXIgJUlffT4wdLg==}
+ engines: {node: '>=12'}
+
resolution: {integrity: sha512-YyUI6AEuY/Wpt8KWLgZHsIU86atmikuoOmCfommt0LYHiQSPjvX2AcFc38PX0CBpr2RCyZhjex+NS/LPOv6YqA==}
engines: {node: '>=12'}
+ resolution: {integrity: sha512-637ln3gXKXOwhalDzinUgY83KzNWZRKbYubaG+fGVuc/dxO64RRljtCTnf5ecMyE1RIdtqpkVcq0IbtU2S8j2Q==}
+ engines: {node: '>=12'}
+
+ resolution: {integrity: sha512-FX/9frcub54beBdugHjDCdikxThEqjnR93Qt7PvQTOHxyiNCAlvMrHhclk3cD5VeAaq9fxmfRp+CnWw9rEMBuA==}
+ engines: {node: '>=12'}
+
resolution: {integrity: sha512-3bYs1rOD33uo8aqJfKP3JWPAibgw8Zm2+L9vBKEHJ2Rg+viTR7o5Mmv5mZcieN+FRYaAOWX5SJATX6k1PWz72g==}
engines: {node: '>=12'}
+ resolution: {integrity: sha512-VLaYcn81dtHVTjEHd8B+pbe9yHWpXKZUC87PzoFmsFrJqgFwDe/qxfp5MlfsfM1V5E/iVt0MmEbWQ7FVIXh/bg==}
+
resolution: {integrity: sha512-p3KP5HCf/bvjBSSKuXid6Zqijx7wIfNW+J/maPs+iwR35at5JCbLUT0LzF1cnjbCHWhqzQTIN2Jpe8pRebIEFQ==}
engines: {node: '>=12'}
+ resolution: {integrity: sha512-3vbA7vXYwfe1SYhED++fPUQlWSYTTGmFmQiany/gdbiWgU/iEyQzyymwL9SkJjFFuCS4902BSzewVGsHHmHtXg==}
+ engines: {node: '>=12'}
+
+ resolution: {integrity: sha512-04xDrxQTDTCFwP5H6hRhsRcb9xxv2RzkcsygFzmkSIOJy3PeRJP7sNk3VRIbKXcog561P9oU0/rVH6vDROAgUw==}
+ engines: {node: '>=12'}
+
+ resolution: {integrity: sha512-FXMe9GfxTxqd5D6jFsQ+DJ8BJS4E/fT5mqqdjovykEB2oFbTMDVdg1MGFxfQW+FBOGoB++k8swBrgwSHT1cUXQ==}
+ engines: {node: '>=12'}
+
+ resolution: {integrity: sha512-nQhsBRmM19Ax5xEIPLMY9ZmJ/cDvd1BG3UVvt5h3WRxKg5zGRbvnteTyWAbzeSvlh3tW7ZEmq4VwR5mB3tutmQ==}
+
+ resolution: {integrity: sha512-A3s5PWiZ9YCXFye1o246KoscMWqf8BsD9eRiJ3He7C9OBaxKhAd5TFCdEx/7VbKtxxTsu//1mMJFrEt572cEyQ==}
+ engines: {node: '>=12'}
+
resolution: {integrity: sha512-GZW464g1SH7ag3Y7hXjf8RoUuAFIqklOAq3MRl4OaWabTFJY9PN/E1YklhXLh+OQ3fM9yS2nOkCoS+WLZ6kvxQ==}
engines: {node: '>=12'}
@@ -4487,6 +4755,9 @@ packages:
resolution: {integrity: sha512-fmTRWbNMmsmWq6xJV8D19U/gw/bwrHfNXxrIN+HfZgnzqTHp9jOmKMhsTUjXOJnZOdZY9Q28y4yebKzqDKlxlQ==}
engines: {node: '>=12'}
+ resolution: {integrity: sha512-EUkvKjqPFUAZyOlhY5gzCxCeI0Aep04LwIRpsZ/mLFelJiUfnK56jo5JMDSE7yyP2kLSb6LtF+S5chMk7uqPqw==}
+
resolution: {integrity: sha512-SaLBuwGm3MOViRq2ABk3eLoxwZELpH6zhl3FbAoJ7Vm1gofKx6El1Ib5z23NUEhF9AsGl7y+dzLe5Cw2AArGTA==}
engines: {node: '>=12'}
@@ -4513,6 +4784,13 @@ packages:
resolution: {integrity: sha512-b8AmV3kfQaqWAuacbPuNbL6vahnOJflOhexLzMMNLga62+/nh0JzvJ0aO/5a5MVgUFGS7Hu1P9P03o3fJkDCyw==}
engines: {node: '>=12'}
+ resolution: {integrity: sha512-e1U46jVP+w7Iut8Jt8ri1YsPOvFpg46k+K8TpCb0P+zjCkjkPnV7WzfDJzMHy1LnA+wj5pLT1wjO901gLXeEhA==}
+ engines: {node: '>=12'}
+
+ resolution: {integrity: sha512-efEhnxpSuwpYOKRm/L5KbqoZmNNukHa/Flty4Wp62JRvgH2ojwVgPgdYyr4twpieZnyRDdIH7PY2mopX26+j2Q==}
+
resolution: {integrity: sha512-sdQSFB7+llfUcQHUQO3+B8ERRj0Oa4w9POWMI/puGtuf7gFywGmkaLCElnudfTiKZV+NvHqL0ifzdrI8Ro7ESA==}
@@ -4538,6 +4816,9 @@ packages:
resolution: {integrity: sha512-Ukq0owbQXxa/U3EGtsdVBkR1w7KOQ5gIBqdH2hkvknzZPYvBxb/aa6E8L7tmjFtkwZBu3UXBbjIgPo/Ez4xaNg==}
+ resolution: {integrity: sha512-t5EcLVS6QPBNqM2z8fakk/NKel+Xzshgt8FFKAn+qwlD1pzZWxh0nVCrvFK7ZDb6XucZeF9z8C7CBWTRIVApAw==}
+
resolution: {integrity: sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==}
peerDependencies:
@@ -4594,6 +4875,9 @@ packages:
resolution: {integrity: sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg==}
engines: {node: '>= 0.4'}
+ resolution: {integrity: sha512-8nvh+XBe96aCESrGOqMp/84b13H9cdKbG5P2ejQCh4d4sK9RL4371qou9drQjMhvnPmhWl5hnmqbEE0fXr9Xnw==}
+
resolution: {integrity: sha512-JeMq7fEshyepOWDfcfHK06N3MhyPhz++vtqWhMT5O9A3K42rdsEDpfdVqjaqaAhsw6a+ZqeDvQVtD0hFHQWrzg==}
engines: {node: '>= 0.6.0'}
@@ -4974,6 +5258,10 @@ packages:
resolution: {integrity: sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==}
engines: {node: '>=0.8.x'}
+ resolution: {integrity: sha512-Vo1ab+QXPzZ4tCa8SwIHJFaSzy4R6SHf7BY79rFBDf0idraZWAkYrDjDj8uWaSm3S2TK+hJ7/t1CEmZ7jXw+pg==}
+ engines: {node: '>=18.0.0'}
+
resolution: {integrity: sha512-/f2Go4TognH/KvCISP7OUsHn85hT9nUkxxA9BEWxFn+Oj9o8ZNLm/40hdlgSLyuOimsrTKLUMEorQexp/aPQeA==}
@@ -5174,6 +5462,10 @@ packages:
resolution: {integrity: sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==}
engines: {node: 6.* || 8.* || >= 10.*}
+ resolution: {integrity: sha512-QZjmEOC+IT1uk6Rx0sX22V6uHWVwbdbxf1faPqJ1QhLdGgsRGCZoyaQBm/piRdJy/D2um6hM1UP7ZEeQ4EkP+Q==}
+ engines: {node: '>=18'}
+
resolution: {integrity: sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==}
engines: {node: '>= 0.4'}
@@ -5213,11 +5505,12 @@ packages:
resolution: {integrity: sha512-DfXN8DfhJ7NH3Oe7cFmu3NCu1wKbkReJ8TorzSAFbSKrlNaQSKfIzqYqVY8zlbs2NLBbWpRiU52GX2PbaBVNkg==}
+ deprecated: Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting [email protected]
hasBin: true
resolution: {integrity: sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==}
- deprecated: Glob versions prior to v9 are no longer supported
+ deprecated: Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting [email protected]
resolution: {integrity: sha512-AhO5QUcj8llrbG09iWhPU2B204J1xnPeL8kQmVorSsy+Sjj1sk8gIyh6cUocGmH4L0UuhAJy+hJMRA4mgA4mFQ==}
@@ -5248,6 +5541,9 @@ packages:
resolution: {integrity: sha512-DKKrynuQRne0PNpEbzuEdHlYOMksHSUI8Zc9Unei5gTsMNA2/vMpoMz/yKba50pejK56qj98qM0SjYxAKi13gQ==}
engines: {node: ^12.22.0 || ^14.16.0 || ^16.0.0 || >=17.0.0}
+ resolution: {integrity: sha512-3GKBOn+m2LX9iq+JC1064cSFprJY4jL1jCXTcpnfER5HYE2l/4EfWSGzkPa/ZDBmYI0ZOEj5VHV/eKnPGkHuOg==}
+
resolution: {integrity: sha512-rfbiwB6OKxZFIFQ7SRnCPB2WL9WhyXsFoTfecYgeCeFSOBxvkWLaXsdv5ehzJrfqwXQmDephAKWLRQoFoJwrew==}
engines: {node: '>=20.0.0'}
@@ -5311,9 +5607,21 @@ packages:
resolution: {integrity: sha512-wkQCkSYoOGCRKERFWcxMVMOcYE2K1AaNLU8DXS9arxnLOUEWbOXKXiJUNzEpqZ3JOKpnha3jkFrumEjVliDe7A==}
+ resolution: {integrity: sha512-Y8/SBAHkZGoNkpzqqfCldijcuUKh7/su31kEBp67cFY09Wy0mTRgtsLYsiIxMJxlu0f6AA5SUTbDR8K0rxnbUw==}
+
+ resolution: {integrity: sha512-3yTWghByc50aGS7JlGhk61SPenfE/p1oaFeNwkOOyrscaOkMGrcW9+Cy/QAIOBpZxP1yqDIzFMR0+Np0i0+usg==}
+
+ resolution: {integrity: sha512-OguPdidb+fbHQSU4Q4ZiLKnzWo8Wwsf5bZfbvu7//a9oTYoqD/fWpe96NuHkoS9h0ccGOTe0C4NGXdtS0iObOw==}
+
resolution: {integrity: sha512-zl6s8LwNyo1P9uw+XJGvZtdFF1GdAkOg8ujOw+4Pyb76874fLps4ueHXDhXWdk6YHQ6OgUtinliG7RsYvCbbBg==}
+ resolution: {integrity: sha512-MlWT6Pjt4CG9lFCjiz4BH7l9wmrMkfkJYCxFwKQic8+RTZgWPuWxwAfjJElsXkex7DJjfSJsQIt931ilUgmwdA==}
+
resolution: {integrity: sha512-XelQVTDWvqcl3axRfI0xSeoVKzyIFPwsAGSLIsKdJKQMXDYJS4WYrBNF/8J7RdhIcFI2BOHgAifggsvsxp/3+A==}
@@ -5358,6 +5666,9 @@ packages:
resolution: {integrity: sha512-ol6UPyBWqsrO6EJySPz2O7ZSr856WDrEzM5zMqp+FJJLGMW35cLYmmZnl0vztAZxRUoNZJFTCohfjuIJ8I4QBQ==}
+ resolution: {integrity: sha512-bEqo66MRXsUGxWHV5IP0PUiAWwoEjba4VCzg0LjFJBpchPaTfyfCKTG6bc5F8ucKec3q5y6qOdGyYTSBEvhCrg==}
+
resolution: {integrity: sha512-4xynFbKNNk+WlzXeQQ+6YYsH2g7mpfPszQZUi3ovKlj+pDmngQ7vRXjrrmGROabmKwyQkcgcX5hqfOwHbFmK5g==}
engines: {node: '>=10.13.0'}
@@ -5395,6 +5706,10 @@ packages:
resolution: {integrity: sha512-B4FFZ6q/T2jhhksgkbEW3HBvWIfDW85snkQgawt07S7J5QXTk6BkNV+0yAeZrM5QpMAdYlocGoljn0sJ/WQkFw==}
engines: {node: '>=10.17.0'}
+ resolution: {integrity: sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==}
+ engines: {node: '>=0.10.0'}
+
resolution: {integrity: sha512-soFhflCVWLfRNOPU3iv5Z9VUdT44xFRbzjLsEzSr5AQmgqPMTHdU3PMT1Cf1ssx8fLNJDA1juftYl+PUcv3MqA==}
engines: {node: ^10 || ^12 || >= 14}
@@ -5458,6 +5773,9 @@ packages:
resolution: {integrity: sha512-4gd7VpWNQNB4UKKCFFVcp1AVv+FMOgs9NKzjHKusc8jTMhd5eL1NqQqOpE0KzMds804/yHlglp3uxgluOqAPLw==}
engines: {node: '>= 0.4'}
+ resolution: {integrity: sha512-lDB5YccMydFBtasVtxnZ3MRBHuaoE8GKsppq+EchKL2U4nK/DmEpPHNH8MZe5HkMtpSiTSOZwfN0tzYjO/lJEw==}
+
resolution: {integrity: sha512-5Hh7Y1wQbvY5ooGgPbDaL5iYLAPzMTUrjMulskHLH6wnv/A+1q5rgEaiuqEjB+oxGXIVZs1FF+R/KPN3ZSQYYg==}
engines: {node: '>=12'}
@@ -5698,6 +6016,9 @@ packages:
resolution: {integrity: sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==}
+ resolution: {integrity: sha512-es94M3nTIfsEPisRafak+HDLfHXnKBhV3vU5eqPcS3flIWqcxJWgXHXiey3YrpaNsanY5ei1VoYEbOzijuq9BA==}
+
resolution: {integrity: sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==}
@@ -5740,9 +6061,20 @@ packages:
resolution: {integrity: sha512-woHRUZ/iF23GBP1dkDQMh1QBad9dmr8/PAwNA54VrSOVYgI12MAcE14TqnDdQOdzyEonGzMepYnqBMYdsoAr8Q==}
hasBin: true
+ resolution: {integrity: sha512-YHzO7721WbmAL6Ov1uzN/l5mY5WWWhJBSW+jq4tkfZfsxmo1hu6frS0EOswvjBUnWE6NtjEs48SFn5CQESRLZg==}
+ hasBin: true
+
resolution: {integrity: sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==}
+ resolution: {integrity: sha512-Ls993zuzfayK269Svk9hzpeGUKob/sIgZzyHYdjQoAdQetRKpOLj+k/QQQ/6Qi0Yz65mlROrfd+Ev+1+7dz9Kw==}
+
+ resolution: {integrity: sha512-QJv/h939gDpvT+9SiLVlY7tZC3xB2qK57v0J04Sh9wpMb6MP1q8gB21L3WIo8T5P1MSMg3Ep14L7KkDCFG3y4w==}
+ engines: {node: '>=16.0.0'}
+
resolution: {integrity: sha512-0K65Lea881pHotoGEa5gDlMxt3pctLi2RplBb7Ezh4rRdLEOtgi7n4EwK9lamnUCkKBqaeKRVebTq6BAxSkpXQ==}
@@ -5762,6 +6094,12 @@ packages:
react: ^16.6.3 || ^17.0.0 || ^18.0.0 || ^19.0.0
react-dom: ^16.8.4 || ^17.0.0 || ^18.0.0 || ^19.0.0
+ resolution: {integrity: sha512-8h2oVEZNktL4BH2JCOI90iD1yXwL6iNW7KcCKT2QZgQJR2vbqDsldCTPRU9NifTCqHZci57XvQQ15YTu+sTYPg==}
+
+ resolution: {integrity: sha512-dp3s92+uNI1hWIpPGH3jK2kxE2lMjdXdr+DH8ynZHpd6PUlH6x6cbuXnoMmiNumznqaNO31xu9e79F0uuZ0JFg==}
+
resolution: {integrity: sha512-qsda+H8jTaUaN/x5vzW2rzc+8Rw4TAQ/4KjB46IwK5VH+IlVeeeje/EoZRpiXvIqjFgK84QffqPztGI3VBLG1A==}
engines: {node: '>=6'}
@@ -5804,8 +6142,8 @@ packages:
resolution: {integrity: sha512-gvVijfZvn7R+2qyPX8mAuKcFGDf6Nc61GdvGafQsHL0sBIxfKzA+usWn4GFC/bk+QdwPUD4kWFJLhElipq+0VA==}
engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0}
- resolution: {integrity: sha512-XEawp1t0gxSi9x01glktRZ5HDy0HXqrM0x5pXQM98EaI0NxO6jVM7omDOxsuEo5UIASAnm2bRp1Jt/e0a2XU8Q==}
+ resolution: {integrity: sha512-kVI48u3PZr38HdYz98UmfPnXl2DXrpdctLrFLCd3kOx1xUkOmpFPx7gCWWM5MPkL/fD8zb+Ph0QzjGFs4+hHWg==}
resolution: {integrity: sha512-TwuEnCnxbc3rAvhf/LbG7tJUDzhqXyFnv3dtzLOPgCG/hODL7WFnsbwktkD7yUV0RrreP/l1PALq/YSg6VvjlA==}
@@ -5912,6 +6250,16 @@ packages:
react:
optional: true
+ resolution: {integrity: sha512-TI3V8YYWvkVf3KJe1dRkpnjs68JUPyEa5vjKrp1XEEJUAOaQc+Qj+L1qWbPd0SJuAdQkFU0h73sXXqwDYxsiDA==}
+ engines: {node: '>= 20'}
+ hasBin: true
+
+ resolution: {integrity: sha512-boeBdiS0ghpWcSwoNm/jJBwdpFaMnZWRzjA6SkUMYb40SVaN1x7mmfGKp0jvexGcx+7y2La5zRZsYFZI6Qpypg==}
+ engines: {node: '>= 20'}
+ hasBin: true
+
resolution: {integrity: sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==}
engines: {node: '>= 0.4'}
@@ -5984,9 +6332,41 @@ packages:
resolution: {integrity: sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==}
engines: {node: '>= 8'}
+ resolution: {integrity: sha512-n34QPDPEKmaeCG4WDMGy0OT6PSyxKCfy2pJgShP+Qow2KLrvWjclwbc3yXfSIf4BanqWEhQEpngWwNp/XhZt6w==}
+
resolution: {integrity: sha512-RDBrHEMSxVFLg6xvnXmb1Ayr2WzLAWjeSATAoxwKYJV94TeNavgoIdA0a9ytzDSVzBy2YKFK+emCPOEibLeCrg==}
+ resolution: {integrity: sha512-gSPnxgHDDqXYOBvQRq6lerrq9mjDhdtKn+7XETuXjxWcL62yZEfUdA28Ml1I2vDIPfAOIKLa0h2XDSGkInGHFQ==}
+ engines: {node: '>=16'}
+ peerDependencies:
+ micromark: ^4.0.0
+ micromark-util-types: ^2.0.0
+ peerDependenciesMeta:
+ micromark-util-types:
+ optional: true
+
+ resolution: {integrity: sha512-egs6+12JU2yutskHY55FyR48ZiEcFOJFyk9rsiyIhcJ6IvWB6ABBqVrBw8IobqJTDZ/wdSr9eoXDPb5S2nW1bg==}
+ engines: {node: '>=16'}
+ peerDependencies:
+ micromark-util-types: '*'
+ peerDependenciesMeta:
+ micromark-util-types:
+ optional: true
+
+ resolution: {integrity: sha512-gRzVLUdjXBLX6zNPSnHGDoo+ZTp5zy+MZm0g3sv+3chPXY7l9gW+DnrcHcZh/jiPR6MjPKO4AEJNp4Aw6V9z5Q==}
+ engines: {node: '>=16'}
+ peerDependencies:
+ micromark: ^4.0.0
+ micromark-util-types: ^2.0.0
+ peerDependenciesMeta:
+ micromark-util-types:
+ optional: true
+
resolution: {integrity: sha512-oOg7knzhicgQ3t4QCjCWgTmfNhvQbDDnJeVu9v81r7NltNCVmhPy1fJRX27pISafdjL+SVc4d3l48Gb6pbRypw==}
@@ -6119,12 +6499,12 @@ packages:
resolution: {integrity: sha512-qOOzS1cBTWYF4BH8fVePDBOO9iptMnGUEZwNc/cMWnTV2nVLZ7VoNWEPHkYczZA0pdoA7dl6e7FL659nX9S2aw==}
engines: {node: '>=16 || 14 >=14.17'}
+ resolution: {integrity: sha512-l8D9ODSRWLe2KHJSifWGwBqpTZXIXTeo8mlKjY+E2HAakaTeNpqAyBZ8GSqLzHgw4XmHmC8whvpjJNMbFZN7/g==}
+
resolution: {integrity: sha512-EGWKgxALGMgzvxYF1UyGTy0HXX/2vHLkw6+NvDKW2jypWbHpjQuj4UMcqQWXHERJhVGKikolT06G3bcKe4fi7w==}
- resolution: {integrity: sha512-uEmtNhbDOrWPFS+hdjFCBfy9f2YoyzRpwcl+DqpC6taX21FzsTLQVbMV/W7PzNSX6x/bhC1zA3c2UQ5NzH6how==}
-
resolution: {integrity: sha512-wX64WITk6gKOhaTqhsFqmIkayLAAx45SVFiMnJIxIrH5uqyrwrxjrfo8WX9Kh8CaUAixjeMn82iH0W0QT9wD5w==}
@@ -6339,6 +6719,12 @@ packages:
resolution: {integrity: sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==}
engines: {node: '>=6'}
+ resolution: {integrity: sha512-8Unqkvk1RYc6yq2WBYRj4hdnsAxVze8i7iPfQr8e4uSP3tRv0rpZcbGUDvxfQQcdwHt/e9PrMvGCsa8OqG9X3w==}
+
+ resolution: {integrity: sha512-3VhUGN3w2eYxnTzHn+ikMI+fp/96KoRSVK9/kMTcFqj1NRDh2IhQCKvYxDnWePKRXY/AqH+Fuiyb7VHSzBjHfA==}
+
resolution: {integrity: sha512-7x81NCL719oNbsq/3mh+hVrAWmFuEYUqrq/Iw3kUzH8ReypT9QQ0BLoJS7/G9k6N81XjW4qHWtjWwe/9eLy1EQ==}
engines: {node: '>=12'}
@@ -6398,6 +6784,9 @@ packages:
resolution: {integrity: sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw==}
+ resolution: {integrity: sha512-61A5ThoTiDG/C8s8UMZwSorAGwMJ0ERVGj2OjoW5pAalsNOg15+iQiPzrLJ4jhZ1HJzmC2PIHT2oEiH3R5fzNA==}
+
resolution: {integrity: sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw==}
@@ -6434,6 +6823,9 @@ packages:
resolution: {integrity: sha512-b7uo2UCUOYZcnF/3ID0lulOJi/bafxa1xPe7ZPsammBSpjSWQkjNxlt635YGS2MiR9GjvuXCtz2emr3jbsz98g==}
+ resolution: {integrity: sha512-NOnmBpt5Y2RWbuv0LMzsayp3lVylAHLPUTut412ZA3l+C4uw4ZVkQbjShYCQ8TCpUMdPapr4YjUqLYD6v68j+w==}
+
resolution: {integrity: sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==}
engines: {node: '>=8'}
@@ -6513,6 +6905,9 @@ packages:
resolution: {integrity: sha512-Ie9z/WINcxxLp27BKOCHGde4ITq9UklYKDzVo1nhk5sqGEXU3FpkwP5GM2voTGJkGd9B3Otl+Q4uwSOeSUtOBA==}
engines: {node: '>=14.16'}
+ resolution: {integrity: sha512-/Jm5M4RvtBFVkKWRu2BLUTNP8/M2a+UwuAX+ae4770q1qVGtfjG+WTCupoZixokjmHiry8uI+dlY8KXYV5HVVQ==}
+
resolution: {integrity: sha512-hutraynyn31F+Bifme+Ps9Vq59hKuUCz7H1kDOcBs+2oGguKkWTU50bBWrtz34OUWmIwpBTWDxaRPXrIXkgvmQ==}
engines: {node: '>=18'}
@@ -6523,6 +6918,12 @@ packages:
engines: {node: '>=18'}
hasBin: true
+ resolution: {integrity: sha512-0mYKnYYe9ZcqMCWhUjItv/oHjvgEsfKvnUTg8sAtnHr3GVy7rGkXCb6d5cSyqrWqL4k81b9CPg3urd+T7aop3A==}
+
+ resolution: {integrity: sha512-25ClnWWuw7JbWZcgqY/gJ4FQWadKxGWk+3kR/7kD0tCaDtPPMj7oHu2ToLaVhfpnHrZzYby2w6tUA0eOIuUg8g==}
+
resolution: {integrity: sha512-PxkIc/2ZpLiEzQXu5YRDOUgBlfGYBY8156HY5ZcRAwwonMk5W/MrJP2LLkG/hF7GEQzaHo2aS7ho6ZLCOvf+6g==}
engines: {node: '>=12.0.0'}
@@ -6962,6 +7363,15 @@ packages:
resolution: {integrity: sha512-yXLRqatcCuKtVHsWrNg0JL3l1zGfdXeEvDa0bdu4tCDQw0RpMDZsqbkyRTUnKMR0tXF627V2oEWjBEaEdqTwtQ==}
+ resolution: {integrity: sha512-0YCaSCq2VRIebiaUviZNs0cBz1kg5kVS2UKUfNIx8YVs1cN3AV7NTctO5FOKBA+UT2BPJIWZauYHPqJODG50cg==}
+
+ resolution: {integrity: sha512-8VhliFJAWRaUiVvREIiW2NXXTmHs4vMNnSzuJVhscgmGav3g9VDxLrQndI3dZZVVdp0ZO/5v0xmX516/7M9cng==}
+
+ resolution: {integrity: sha512-6VwtthbV4o/7+OaAF9I5L5V3llLEsoPyq9P1JVXkedTP33c7MfCG0/5NOPcSJn0TzXcG9YUrR0gQSWioew3LDg==}
+
resolution: {integrity: sha512-dYqgNSZbDwkaJ2ceRd9ojCGjBq+mOm9LmtXnAnEGyHhN/5R7iDW2TRw3h+o/jCFxus3P2LfWIIiwowAjANm7IA==}
engines: {node: '>= 0.4'}
@@ -6980,12 +7390,21 @@ packages:
resolution: {integrity: sha512-rItO/pSdvnvsP4QRB1pmPiNHUskikqtPojZKJPPPAVx9Hj8i8TwMBhofrrAYRhYOOBZH9tgmG5lPqDLuIWPWmw==}
+ resolution: {integrity: sha512-j5DY0YSK2YavvNGV+qBHma15J9m0WZmRe8posT5AtKDS6TNWtMVTo6RiqF8SidfcASYz8f3k2J/1RWmq5zTXUw==}
+
resolution: {integrity: sha512-k158pK7wdC2qL3M5NcZROZ2tR/l7zOzjxXd5VGdcfIyoijjQqpHd3JKtYSBDpDZ38UI2WJWuFAtkMDxmx5kstA==}
resolution: {integrity: sha512-OiM2wrZ/wuhKkigASodFoo8wimG3H12LWQaH8qSPVJn9apWKFSH3YOCtbKpBorTVw/eI7cuT21XBbvwEswbIOA==}
+ resolution: {integrity: sha512-/aE8hCfKlQeA8LmyeyQvQF3eBiLRGNlfBJEvWH7ivp9sBqs7TNqBL5X3v157rM4IFETqDnIOO+z5M/biZbo9Ww==}
+
+ resolution: {integrity: sha512-CsnhKNsyI8Tub6L4sm5ZFsme4puGfc6pYylvXo1AeqaGbjOYyzNv3qZPwvs0oMJ39eryyeOdmxwUIo94IpEhqg==}
+
resolution: {integrity: sha512-lWyvf/jwu+oS5+hL5eClVd3hNdmwM1kAC0BUvEGD19pajQMIzcNUd/k9GsfQ+FfECvX+JE+e9/btsKH0EjJT6A==}
@@ -6993,6 +7412,26 @@ packages:
resolution: {integrity: sha512-G08Dxvm4iDN3MLM0EsP62EDV9IuhXPR6blNz6Utcp7zyV3tr4HVNINt6MpaRWbxoOHT3Q7YN2P+jaHX8vUbgog==}
engines: {node: '>= 0.10'}
+ resolution: {integrity: sha512-bXfMZtsaomK6ysNN/UGRIcasQAYkC10NtPmP0oOHOV8YOhA2TXmwRXCku4qOzjIFxAPfish5+XS0eIug2PzNZA==}
+ engines: {node: '>=16'}
+ peerDependencies:
+ '@types/mdast': ^4.0.0
+ unified: ^11.0.0
+ peerDependenciesMeta:
+ '@types/mdast':
+ optional: true
+
+ resolution: {integrity: sha512-UvAgxwlNk+l9Oqgl/9MWK2eWRS7zgBW/nXX9AthV7nd/3lNejF138E7Xbmk9Zs4WjTJGs721r7fAEc7tNFoH7g==}
+ engines: {node: '>=16'}
+ peerDependencies:
+ '@types/mdast': ^4.0.0
+ unified: ^11.0.0
+ peerDependenciesMeta:
+ '@types/mdast':
+ optional: true
+
resolution: {integrity: sha512-1quofZ2RQ9EWdeN34S79+KExV1764+wCUGop5CPL1WGdD0ocPpu91lzPGbwWMECpEpd42kJGQwzRfyov9j4yNg==}
@@ -7008,6 +7447,9 @@ packages:
resolution: {integrity: sha512-1OSmLd3awB/t8qdoEOMazZkNsfVTeY4fTsgzcQFdXNq8ToTN4ZGwrMnlda4K6smTFKD+GRV6O48i6Z4iKgPPpw==}
+ resolution: {integrity: sha512-JENGyuIhTwzUfCarW43X4r9cehoqTo9QyYxfNDZSud2AmqeuWjZ5pfybasTa4q0dxTJAj5m8NB+wR+YueAFpxQ==}
+
resolution: {integrity: sha512-q/7VIQA8lmM1hF+jn+sFSPWGlMkSAeNYcPLmDQx2zzuiDfaLrOmumR8iaUKlenFgh0XRPIUeSPlH3A+AW3Z5pg==}
@@ -7066,14 +7508,23 @@ packages:
resolution: {integrity: sha512-5Di9UC0+8h1L6ZD2d7awM7E/T4uA1fJRlx6zk/NvdCCVEoAnFqvHmCuNeIKoCeIixBX/q8uM+6ycDvF8woqosA==}
engines: {node: '>= 0.8'}
+ resolution: {integrity: sha512-IXgzBWvWQwE6PrDI05OvmXUIruQTcoMDzRsOd5CDvHCVLcLHMTSYvOK5Cm46kWqlV3yAbuSpBZdJ5oP5OUoStg==}
+
resolution: {integrity: sha512-wDv/Ht1BNHB4upNbK74s9usvl7hObDnvVzknxqY/E/O3X6rW1U1rV1aENEfJ54eFZDTNo7zv1f5N4edCluH7+A==}
engines: {node: '>=18.0.0', npm: '>=8.0.0'}
hasBin: true
+ resolution: {integrity: sha512-ZUz/69+SYpFN/g/lUlo2FXcIjRkSu3nDarreVdGGndHEBJ6cXPdKguS8JGxwj5HA5xIbVKSmLgr5b3AWxtRfvQ==}
+
resolution: {integrity: sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==}
+ resolution: {integrity: sha512-PdhdWy89SiZogBLaw42zdeqtRJ//zFd2PgQavcICDUgJT5oW10QCRKbJ6bg4r0/UY2M6BWd5tkxuGFRvCkgfHQ==}
+
resolution: {integrity: sha512-dhKf903U/PQZY6boNNtAGdWbG85WAbjT/1xYoZIC7FAY0yWapOBQVsVrDl58W86//e1VpMNBtRV4MaXfdMySFA==}
@@ -7098,6 +7549,9 @@ packages:
resolution: {integrity: sha512-ERq4hUjKDbJfE4+XtZLFPCDi8Vb1JqaxAPTxWFLBx8XcAlf9Bda/ZJdVezs/NAfsMQScyIlUMx+Yeu7P7rx5jw==}
+ resolution: {integrity: sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==}
+
resolution: {integrity: sha512-sglGzId5gmlfxNs4gK2U3h7HlVRfx278YK6Ono5lwzuvi1jxig80YiuHkaDBVsYIKFhx8wN7XSCI0M2IDS/3qA==}
engines: {node: '>= 18.12.0'}
@@ -7186,6 +7640,9 @@ packages:
resolution: {integrity: sha512-VuvPvLG1QjNOLP7AIm2HGyfmxEIz8QdskvWOHwUcxLDibYWjLRBmCWd8LSL5FlwhBW7D/GU+3gNVC/ASxAWdxg==}
engines: {node: 18.* || >= 20}
+ resolution: {integrity: sha512-N65B/3bqL/TI2crrXr+4UivctrAGEjmsib5rPMMPpFp1xAx/w03v8WZ9RDDFYteXoEgY7qZ4HGgl5KBIu1153w==}
+
resolution: {integrity: sha512-ZP36TMrK9euEuWQYBig9W55WPC7uo37qzAEmbjHz4gfyuXrEUgF8cUvQVO+w+d3OMfPvSRQJ22lSm8MQJ43LTA==}
@@ -7301,6 +7758,11 @@ packages:
resolution: {integrity: sha512-Oq1bLqisTyK3TSCXpPbT4sdeYNdmyZJv1LxpEm2vu1ZhK89kSE5YXwZc3cWk0MagGaKriBh9mCFbVGtO+vY29A==}
+ resolution: {integrity: sha512-u9gWd0AmjKg1d+74P44XaPlGrMeC21oDOSIhjGNEYMAttDMzCzlJO6lpTyJ9JkSinQQF65YcK4eOd3q9iTvULw==}
+ peerDependencies:
+ react: ^18.0.0 || ^19.0.0
+
resolution: {integrity: sha512-vMgjE/GGEPEFnhFub6pa4FmJBRBVOLpIII2hvCZ8Kzb7K0hlHo7mQv6xYrBvCL2LtAIBwFUK8wvuJgTVSQ5MFQ==}
@@ -7414,6 +7876,9 @@ packages:
babel-plugin-macros:
optional: true
+ resolution: {integrity: sha512-yQ3rwFWRfwNUY7H5vpU0wfdkNSnvnJinhF9830Swlaxl03zsOjCfmX0ugac+3LtK0lYSgwL/KXc8oYL3mG4YFQ==}
+
resolution: {integrity: sha512-DhuTmvZWux4H1UOnWMB3sk0sbaCVOoQZjv8u1rDoTV0HTdGem9hkAZtl4JZy8P2z4Bg0nT+YMeOFyVr4zcG5Tw==}
engines: {node: '>=16 || 14 >=14.17'}
@@ -7435,12 +7900,20 @@ packages:
resolution: {integrity: sha512-upi/0ZGkYgEcLeGieoz8gT74oWHA0E7JivX7aN9mAf+Tc7BQoRBvnIGHoPDw+f9TXTW4s6kGYCZJtauP6OYp7g==}
hasBin: true
+ resolution: {integrity: sha512-gaCPRVoMq8WGDcWj9p4YWzCMPHzE0WNl6W8ADIx9c3JBEIdMkJGMzW+uzXvxHMltwcYACr9jP+32H8/hgwMR7w==}
+ peerDependencies:
+ react: ^16.11.0 || ^17.0.0 || ^18.0.0 || ^19.0.0
+
resolution: {integrity: sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==}
resolution: {integrity: sha512-P+Vu1qXfzediirmHOC3xKGAYeZtPcV9g76X+xg2FD4tYgR71ewMA35Y3sCz3zhiN/dwefRpJX0yBcgwi1fXNQA==}
+ resolution: {integrity: sha512-uSaO4gnW+b3Y2aWoWfFpX62vn2sR3skfhbjsEnaBI81WD1wBLlHZe5sWf0AqjksNdYTbGBEd0UasQMT3SNV15g==}
+
resolution: {integrity: sha512-pmrtDIZeHyu2idTejfV59SbaJyvp1VRjYxAjZBH0jnyrPRo6HL1kD5Glz8VPagasqr6oAx6M05+Tuw429Z8jxg==}
engines: {node: '>=12.13.0'}
@@ -7495,6 +7968,10 @@ packages:
resolution: {integrity: sha512-oB7yIimd8SuGptespDAZnNkzIz+NWaJCu2RMsbs4Wmp9zSDUM8Nhi3s2OOcqYuv3mN4hitXc8DVx+LyUmbUDiA==}
+ resolution: {integrity: sha512-nt6AMGKW1p/70DF/hGBdJB57B8Tspmbp5gfJ8ilhLnt7kkr2ye7hzD6NVG8GGErk2HWF34igrL2CXmNIkzKqKw==}
+ engines: {node: '>=18'}
+
resolution: {integrity: sha512-9phl76Cqm6FhSX9Xe1ZUAMLtm1BLkKj2Qd5ApyWkXzsMRaA7dgr81kf4wJmQf/hAvg8EEyJxDo3du/0KlhPiKQ==}
engines: {node: '>=0.6.0'}
@@ -7677,6 +8154,9 @@ packages:
resolution: {integrity: sha512-ARDJmphmdvUk6Glw7y9DQ2bFkKBHwQHLi2lsaH6PPmz/Ka9sFOBsBluozhDltWmnv9u/cF6Rt87znRTPV+yp/A==}
+ resolution: {integrity: sha512-yDJTmhydvl5lJzBmy/hyOAA0d+aqCBuwl818haVdYCRrWV84o7YyeVm4QlVHStqNrrJSTb6jKuFAVqAFsr+K3Q==}
+
resolution: {integrity: sha512-nWJ91DjeOkej/TA8pXQ3myruKpKEYgqvpw9lz4OPHj/NWFNluYrjbz9j01CJ8yKQd2g4jFoOkINCTW2I5LEEyw==}
engines: {node: '>= 0.4'}
@@ -7781,6 +8261,11 @@ packages:
'@types/react':
optional: true
+ resolution: {integrity: sha512-ssUfMNvfH8a8hGLoAt5kcOsjbsVORknon2tbkECuf3EsVucFFBbyXl+Xnv3b58P8ZRuZelzO81fgb6M0eRo8cg==}
+ peerDependencies:
+ react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0
+
resolution: {integrity: sha512-Pp6GSwGP/NrPIrxVFAIkOQeyw8lFenOHijQWkUTrDvrF4ALqylP2C/KCkeS9dpUM3KvYRQhna5vt7IL95+ZQ9w==}
peerDependencies:
@@ -7918,6 +8403,26 @@ packages:
resolution: {integrity: sha512-2ham8XPWTONajOR0ohOKOHXkm3+gaBmGut3SRuu75xLd/RRaY6vqgh8NBYYk7+RW3u5AtzPQZG8F10LHkl0lAQ==}
+ resolution: {integrity: sha512-C+r0eKJUIfiDIfwJhria30+TYWPtuHJXHtI7J0YlOmKAo7ogxP20T0zxB7HZQIFhIyvoBPwWskjxrvAtfjyZfA==}
+ engines: {node: '>=14.0.0'}
+
+ resolution: {integrity: sha512-mb1bvRJN8SVznADSGWM9u/b07H7Ecg0I3OgXDuLdn307rl/J3A9YD6/eYOssqhecL27hK1IPZAsaqh00i/Jljg==}
+
+ resolution: {integrity: sha512-cxWNPesCnQCcMPeenjKKsOCKQZ/L6Tv19DTRIGuLWe32lyzWhihGVJ/rcckZXJxfdKCFvRLS3fpBIsV/ZGX4zA==}
+
+ resolution: {integrity: sha512-Ld1VelNuX9pdF39h2Hgaeb5hEZM2Z3jUrrMgWQAu82jMtZp7p3vJT3BzToKtZI7NgQssZje5o0zryOrhQvzQAg==}
+
+ resolution: {integrity: sha512-woByF3PDpkHFUreUa7Hos7+pUWdeWMXRd26+ZX2A8cFx6v/JPTtd4/uN0/jB6XQHYaOlHbio03NTHCqrgG5n7g==}
+ hasBin: true
+
+ resolution: {integrity: sha512-AyFQ0EVmsOZOlAnxoFOGOq1SQDWAB7C6aqMGS23svWAllfOaxbuFvcT8D1i8z3Gyn8fraVeZNNmN6e9bxxXkKw==}
+
resolution: {integrity: sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA==}
engines: {node: '>=18'}
@@ -8147,8 +8652,41 @@ snapshots:
'@adobe/[email protected]': {}
+ dependencies:
+ '@ai-sdk/provider': 3.0.5
+ '@ai-sdk/provider-utils': 4.0.10([email protected])
+ '@vercel/oidc': 3.1.0
+ zod: 3.25.76
+
+ dependencies:
+ '@ai-sdk/provider': 3.0.5
+ '@standard-schema/spec': 1.1.0
+ eventsource-parser: 3.0.6
+ zod: 3.25.76
+
+ '@ai-sdk/[email protected]':
+ dependencies:
+ json-schema: 0.4.0
+
+ dependencies:
+ '@ai-sdk/provider-utils': 4.0.10([email protected])
+ ai: 6.0.59([email protected])
+ react: 18.3.1
+ swr: 2.3.8([email protected])
+ throttleit: 2.1.0
+ transitivePeerDependencies:
+ - zod
+
'@alloc/[email protected]': {}
+ '@antfu/[email protected]':
+ dependencies:
+ package-manager-detector: 1.6.0
+ tinyexec: 1.0.2
+
'@apidevtools/[email protected]':
dependencies:
'@types/json-schema': 7.0.15
@@ -8962,6 +9500,25 @@ snapshots:
'@babel/helper-string-parser': 7.27.1
'@babel/helper-validator-identifier': 7.28.5
+ '@braintree/[email protected]': {}
+
+ '@chevrotain/[email protected]':
+ dependencies:
+ '@chevrotain/gast': 11.0.3
+ '@chevrotain/types': 11.0.3
+ lodash-es: 4.17.23
+
+ '@chevrotain/[email protected]':
+ dependencies:
+ '@chevrotain/types': 11.0.3
+ lodash-es: 4.17.23
+
+ '@chevrotain/[email protected]': {}
+
+ '@chevrotain/[email protected]': {}
+
+ '@chevrotain/[email protected]': {}
+
dependencies:
'@neoconfetti/react': 1.0.0
@@ -9281,6 +9838,14 @@ snapshots:
transitivePeerDependencies:
- encoding
+ '@iconify/[email protected]': {}
+
+ '@iconify/[email protected]':
+ dependencies:
+ '@antfu/install-pkg': 1.1.0
+ '@iconify/types': 2.0.0
+ mlly: 1.8.0
+
optional: true
@@ -9457,6 +10022,10 @@ snapshots:
'@types/react': 18.3.17
react: 18.3.1
+ '@mermaid-js/[email protected]':
+ dependencies:
+ langium: 3.3.1
+
dependencies:
'@open-draft/deferred-promise': 2.2.0
@@ -10608,7 +11177,7 @@ snapshots:
dependencies:
'@rjsf/utils': 6.1.2([email protected])
lodash: 4.17.21
- lodash-es: 4.17.22
+ lodash-es: 4.17.23
markdown-to-jsx: 8.0.0([email protected])
prop-types: 15.8.1
react: 18.3.1
@@ -10619,7 +11188,7 @@ snapshots:
fast-uri: 3.1.0
jsonpointer: 5.0.1
lodash: 4.17.21
- lodash-es: 4.17.22
+ lodash-es: 4.17.23
react: 18.3.1
react-is: 18.3.1
@@ -10629,7 +11198,7 @@ snapshots:
ajv: 8.17.1
ajv-formats: 2.1.1([email protected])
lodash: 4.17.21
- lodash-es: 4.17.22
+ lodash-es: 4.17.23
'@rolldown/[email protected]': {}
@@ -10936,6 +11505,19 @@ snapshots:
- encoding
- supports-color
+ '@shikijs/[email protected]':
+ dependencies:
+ '@shikijs/types': 3.21.0
+ '@shikijs/vscode-textmate': 10.0.2
+ '@types/hast': 3.0.4
+ hast-util-to-html: 9.0.5
+
+ '@shikijs/[email protected]':
+ dependencies:
+ '@shikijs/types': 3.21.0
+ '@shikijs/vscode-textmate': 10.0.2
+ oniguruma-to-es: 4.3.4
+
'@shikijs/[email protected]':
dependencies:
'@shikijs/types': 3.21.0
@@ -11313,6 +11895,37 @@ snapshots:
optionalDependencies:
typescript: 5.9.3
+ dependencies:
+ react: 18.3.1
+ remark-cjk-friendly-gfm-strikethrough: 1.2.3(@types/[email protected])([email protected])([email protected])([email protected])
+ unist-util-visit: 5.0.0
+ transitivePeerDependencies:
+ - '@types/mdast'
+ - micromark
+ - micromark-util-types
+ - unified
+
+ dependencies:
+ react: 18.3.1
+ shiki: 3.21.0
+
+ dependencies:
+ katex: 0.16.28
+ react: 18.3.1
+ rehype-katex: 7.0.1
+ remark-math: 6.0.0
+ transitivePeerDependencies:
+ - supports-color
+
+ dependencies:
+ mermaid: 11.12.2
+ react: 18.3.1
+
'@supabase/[email protected]':
dependencies:
'@supabase/node-fetch': 2.6.15
@@ -11475,20 +12088,63 @@ snapshots:
'@types/[email protected]': {}
+ '@types/[email protected]':
+ dependencies:
+ '@types/d3-selection': 3.0.11
+
+ '@types/[email protected]':
+ dependencies:
+ '@types/d3-selection': 3.0.11
+
+ '@types/[email protected]': {}
+
'@types/[email protected]': {}
+ '@types/[email protected]':
+ dependencies:
+ '@types/d3-array': 3.2.2
+ '@types/geojson': 7946.0.16
+
+ '@types/[email protected]': {}
+
+ '@types/[email protected]': {}
+
dependencies:
'@types/d3-selection': 3.0.11
+ '@types/[email protected]': {}
+
'@types/[email protected]': {}
+ '@types/[email protected]':
+ dependencies:
+ '@types/d3-dsv': 3.0.7
+
+ '@types/[email protected]': {}
+
+ '@types/[email protected]': {}
+
+ '@types/[email protected]':
+ dependencies:
+ '@types/geojson': 7946.0.16
+
+ '@types/[email protected]': {}
+
dependencies:
'@types/d3-color': 3.1.3
'@types/[email protected]': {}
+ '@types/[email protected]': {}
+
+ '@types/[email protected]': {}
+
+ '@types/[email protected]': {}
+
+ '@types/[email protected]': {}
+
dependencies:
'@types/d3-time': 3.0.4
@@ -11499,6 +12155,8 @@ snapshots:
dependencies:
'@types/d3-path': 3.1.1
+ '@types/[email protected]': {}
+
'@types/[email protected]': {}
'@types/[email protected]': {}
@@ -11512,6 +12170,39 @@ snapshots:
'@types/d3-interpolate': 3.0.4
'@types/d3-selection': 3.0.11
+ '@types/[email protected]':
+ dependencies:
+ '@types/d3-array': 3.2.2
+ '@types/d3-axis': 3.0.6
+ '@types/d3-brush': 3.0.6
+ '@types/d3-chord': 3.0.6
+ '@types/d3-color': 3.1.3
+ '@types/d3-contour': 3.0.6
+ '@types/d3-delaunay': 6.0.4
+ '@types/d3-dispatch': 3.0.7
+ '@types/d3-drag': 3.0.7
+ '@types/d3-dsv': 3.0.7
+ '@types/d3-ease': 3.0.2
+ '@types/d3-fetch': 3.0.7
+ '@types/d3-force': 3.0.10
+ '@types/d3-format': 3.0.4
+ '@types/d3-geo': 3.1.0
+ '@types/d3-hierarchy': 3.1.7
+ '@types/d3-interpolate': 3.0.4
+ '@types/d3-path': 3.1.1
+ '@types/d3-polygon': 3.0.2
+ '@types/d3-quadtree': 3.0.6
+ '@types/d3-random': 3.0.3
+ '@types/d3-scale': 4.0.9
+ '@types/d3-scale-chromatic': 3.1.0
+ '@types/d3-selection': 3.0.11
+ '@types/d3-shape': 3.1.7
+ '@types/d3-time': 3.0.4
+ '@types/d3-time-format': 4.0.3
+ '@types/d3-timer': 3.0.2
+ '@types/d3-transition': 3.0.9
+ '@types/d3-zoom': 3.0.8
+
dependencies:
'@types/ms': 2.1.0
@@ -11540,6 +12231,8 @@ snapshots:
'@types/[email protected]': {}
+ '@types/[email protected]': {}
+
dependencies:
'@types/unist': 3.0.3
@@ -11796,6 +12489,8 @@ snapshots:
react: 18.3.1
+ '@vercel/[email protected]': {}
+
optionalDependencies:
@@ -12023,6 +12718,14 @@ snapshots:
optional: true
+ dependencies:
+ '@ai-sdk/gateway': 3.0.27([email protected])
+ '@ai-sdk/provider': 3.0.5
+ '@ai-sdk/provider-utils': 4.0.10([email protected])
+ '@opentelemetry/api': 1.9.0
+ zod: 3.25.76
+
optionalDependencies:
ajv: 8.17.1
@@ -12411,6 +13114,20 @@ snapshots:
+ dependencies:
+ chevrotain: 11.0.3
+ lodash-es: 4.17.23
+
+ dependencies:
+ '@chevrotain/cst-dts-gen': 11.0.3
+ '@chevrotain/gast': 11.0.3
+ '@chevrotain/regexp-to-ast': 11.0.3
+ '@chevrotain/types': 11.0.3
+ '@chevrotain/utils': 11.0.3
+ lodash-es: 4.17.23
+
dependencies:
anymatch: 3.1.3
@@ -12491,6 +13208,8 @@ snapshots:
+
@@ -12510,6 +13229,8 @@ snapshots:
tree-kill: 1.2.2
yargs: 17.7.2
+
@@ -12530,6 +13251,14 @@ snapshots:
+ dependencies:
+ layout-base: 1.0.2
+
+ dependencies:
+ layout-base: 2.0.1
+
dependencies:
'@types/parse-json': 4.0.2
@@ -12638,12 +13367,50 @@ snapshots:
+ dependencies:
+ cose-base: 1.0.3
+ cytoscape: 3.33.1
+
+ dependencies:
+ cose-base: 2.2.0
+ cytoscape: 3.33.1
+
+
+ dependencies:
+ internmap: 1.0.1
+
dependencies:
internmap: 2.0.3
+
+ dependencies:
+ d3-dispatch: 3.0.1
+ d3-drag: 3.0.0
+ d3-interpolate: 3.0.1
+ d3-selection: 3.0.0
+ d3-transition: 3.0.1([email protected])
+
+ dependencies:
+ d3-path: 3.1.0
+
+ dependencies:
+ d3-array: 3.2.4
+
+ dependencies:
+ delaunator: 5.0.1
+
@@ -12651,16 +13418,56 @@ snapshots:
d3-dispatch: 3.0.1
d3-selection: 3.0.0
+ dependencies:
+ commander: 7.2.0
+ iconv-lite: 0.6.3
+ rw: 1.3.3
+
+ dependencies:
+ d3-dsv: 3.0.1
+
+ dependencies:
+ d3-dispatch: 3.0.1
+ d3-quadtree: 3.0.1
+ d3-timer: 3.0.1
+
+ dependencies:
+ d3-array: 3.2.4
+
+
dependencies:
d3-color: 3.1.0
+
+
+
+
+ dependencies:
+ d3-array: 2.12.1
+ d3-shape: 1.3.7
+
+ dependencies:
+ d3-color: 3.1.0
+ d3-interpolate: 3.0.1
+
dependencies:
d3-array: 3.2.4
@@ -12671,6 +13478,10 @@ snapshots:
+ dependencies:
+ d3-path: 1.0.9
+
dependencies:
d3-path: 3.1.0
@@ -12702,6 +13513,44 @@ snapshots:
d3-selection: 3.0.0
d3-transition: 3.0.1([email protected])
+ dependencies:
+ d3-array: 3.2.4
+ d3-axis: 3.0.0
+ d3-brush: 3.0.0
+ d3-chord: 3.0.1
+ d3-color: 3.1.0
+ d3-contour: 4.0.2
+ d3-delaunay: 6.0.4
+ d3-dispatch: 3.0.1
+ d3-drag: 3.0.0
+ d3-dsv: 3.0.1
+ d3-ease: 3.0.1
+ d3-fetch: 3.0.1
+ d3-force: 3.0.0
+ d3-format: 3.1.0
+ d3-geo: 3.1.1
+ d3-hierarchy: 3.1.2
+ d3-interpolate: 3.0.1
+ d3-path: 3.1.0
+ d3-polygon: 3.0.1
+ d3-quadtree: 3.0.1
+ d3-random: 3.0.1
+ d3-scale: 4.0.2
+ d3-scale-chromatic: 3.1.0
+ d3-selection: 3.0.0
+ d3-shape: 3.2.0
+ d3-time: 3.1.0
+ d3-time-format: 4.1.0
+ d3-timer: 3.0.1
+ d3-transition: 3.0.1([email protected])
+ d3-zoom: 3.0.0
+
+ dependencies:
+ d3: 7.9.0
+ lodash-es: 4.17.23
+
@@ -12732,6 +13581,8 @@ snapshots:
+
dependencies:
ms: 2.1.3
@@ -12773,6 +13624,10 @@ snapshots:
has-property-descriptors: 1.0.2
object-keys: 1.1.1
+ dependencies:
+ robust-predicates: 3.0.2
+
@@ -13347,6 +14202,8 @@ snapshots:
+
dependencies:
md5.js: 1.3.5
@@ -13553,6 +14410,8 @@ snapshots:
+
dependencies:
call-bind-apply-helpers: 1.0.2
@@ -13643,6 +14502,8 @@ snapshots:
+
dependencies:
'@types/node': 24.10.0
@@ -13739,6 +14600,42 @@ snapshots:
dependencies:
'@types/hast': 3.0.4
+ dependencies:
+ '@types/hast': 3.0.4
+ '@types/unist': 3.0.3
+ '@ungap/structured-clone': 1.3.0
+ hast-util-from-parse5: 8.0.3
+ hast-util-to-parse5: 8.0.1
+ html-void-elements: 3.0.0
+ mdast-util-to-hast: 13.2.1
+ parse5: 7.3.0
+ unist-util-position: 5.0.0
+ unist-util-visit: 5.0.0
+ vfile: 6.0.3
+ web-namespaces: 2.0.1
+ zwitch: 2.0.4
+
+ dependencies:
+ '@types/hast': 3.0.4
+ '@ungap/structured-clone': 1.3.0
+ unist-util-position: 5.0.0
+
+ dependencies:
+ '@types/hast': 3.0.4
+ '@types/unist': 3.0.3
+ ccount: 2.0.1
+ comma-separated-tokens: 2.0.3
+ hast-util-whitespace: 3.0.0
+ html-void-elements: 3.0.0
+ mdast-util-to-hast: 13.2.1
+ property-information: 7.1.0
+ space-separated-tokens: 2.0.2
+ stringify-entities: 4.0.4
+ zwitch: 2.0.4
+
dependencies:
'@types/estree': 1.0.8
@@ -13759,6 +14656,16 @@ snapshots:
transitivePeerDependencies:
- supports-color
+ dependencies:
+ '@types/hast': 3.0.4
+ comma-separated-tokens: 2.0.3
+ devlop: 1.1.0
+ property-information: 7.1.0
+ space-separated-tokens: 2.0.2
+ web-namespaces: 2.0.1
+ zwitch: 2.0.4
+
dependencies:
'@types/hast': 3.0.4
@@ -13819,6 +14726,8 @@ snapshots:
+
dependencies:
'@types/html-minifier-terser': 6.1.0
@@ -13865,6 +14774,10 @@ snapshots:
+ dependencies:
+ safer-buffer: 2.1.2
+
dependencies:
postcss: 8.5.6
@@ -13916,6 +14829,8 @@ snapshots:
hasown: 2.0.2
side-channel: 1.1.0
+
@@ -14164,6 +15079,8 @@ snapshots:
+
@@ -14207,10 +15124,24 @@ snapshots:
dependencies:
commander: 8.3.0
+ dependencies:
+ commander: 8.3.0
+
dependencies:
json-buffer: 3.0.1
+
+ dependencies:
+ chevrotain: 11.0.3
+ chevrotain-allstar: 0.3.1([email protected])
+ vscode-languageserver: 9.0.1
+ vscode-languageserver-textdocument: 1.0.12
+ vscode-uri: 3.0.8
+
@@ -14236,6 +15167,10 @@ snapshots:
react: 18.3.1
react-dom: 18.3.1([email protected])
+
+
@@ -14273,7 +15208,7 @@ snapshots:
dependencies:
p-locate: 6.0.0
@@ -14363,6 +15298,10 @@ snapshots:
optionalDependencies:
react: 18.3.1
+
+
@@ -14549,6 +15488,29 @@ snapshots:
+ dependencies:
+ '@braintree/sanitize-url': 7.1.2
+ '@iconify/utils': 3.1.0
+ '@mermaid-js/parser': 0.6.3
+ '@types/d3': 7.4.3
+ cytoscape: 3.33.1
+ cytoscape-cose-bilkent: 4.1.0([email protected])
+ cytoscape-fcose: 2.2.0([email protected])
+ d3: 7.9.0
+ d3-sankey: 0.12.3
+ dagre-d3-es: 7.0.13
+ dayjs: 1.11.19
+ dompurify: 3.3.1
+ katex: 0.16.25
+ khroma: 2.1.0
+ lodash-es: 4.17.23
+ marked: 16.4.2
+ roughjs: 4.6.6
+ stylis: 4.3.6
+ ts-dedent: 2.2.0
+ uuid: 11.1.0
+
dependencies:
decode-named-character-reference: 1.2.0
@@ -14568,6 +15530,38 @@ snapshots:
micromark-util-symbol: 2.0.1
micromark-util-types: 2.0.2
+ dependencies:
+ devlop: 1.1.0
+ get-east-asian-width: 1.4.0
+ micromark: 4.0.2
+ micromark-extension-cjk-friendly-util: 2.1.1([email protected])
+ micromark-util-character: 2.1.1
+ micromark-util-chunked: 2.0.1
+ micromark-util-resolve-all: 2.0.1
+ micromark-util-symbol: 2.0.1
+ optionalDependencies:
+ micromark-util-types: 2.0.2
+
+ dependencies:
+ get-east-asian-width: 1.4.0
+ micromark-util-character: 2.1.1
+ micromark-util-symbol: 2.0.1
+ optionalDependencies:
+ micromark-util-types: 2.0.2
+
+ dependencies:
+ devlop: 1.1.0
+ micromark: 4.0.2
+ micromark-extension-cjk-friendly-util: 2.1.1([email protected])
+ micromark-util-chunked: 2.0.1
+ micromark-util-resolve-all: 2.0.1
+ micromark-util-symbol: 2.0.1
+ optionalDependencies:
+ micromark-util-types: 2.0.2
+
dependencies:
micromark-util-character: 2.1.1
@@ -14790,9 +15784,14 @@ snapshots:
+ dependencies:
+ acorn: 8.15.0
+ pathe: 2.0.3
+ pkg-types: 1.3.1
+ ufo: 1.6.3
dependencies:
@@ -15049,6 +16048,14 @@ snapshots:
dependencies:
mimic-fn: 2.1.0
+
+ dependencies:
+ oniguruma-parser: 0.12.1
+ regex: 6.1.0
+ regex-recursion: 6.0.2
+
dependencies:
define-lazy-prop: 2.0.0
@@ -15143,6 +16150,8 @@ snapshots:
+
@@ -15197,6 +16206,8 @@ snapshots:
+
@@ -15259,6 +16270,12 @@ snapshots:
dependencies:
find-up: 6.3.0
+ dependencies:
+ confbox: 0.1.8
+ mlly: 1.8.0
+ pathe: 2.0.3
+
@@ -15267,6 +16284,13 @@ snapshots:
optionalDependencies:
fsevents: 2.3.2
+
+ dependencies:
+ path-data-parser: 0.1.0
+ points-on-curve: 0.2.0
+
@@ -15693,6 +16717,16 @@ snapshots:
+ dependencies:
+ regex-utilities: 2.3.0
+
+
+ dependencies:
+ regex-utilities: 2.3.0
+
dependencies:
call-bind: 1.0.8
@@ -15726,6 +16760,10 @@ snapshots:
unified: 11.0.5
unist-util-visit: 5.0.0
+ dependencies:
+ unist-util-visit: 5.0.0
+
dependencies:
'@types/hast': 3.0.4
@@ -15744,6 +16782,17 @@ snapshots:
unist-util-visit-parents: 6.0.2
vfile: 6.0.3
+ dependencies:
+ '@types/hast': 3.0.4
+ hast-util-raw: 9.1.0
+ vfile: 6.0.3
+
+ dependencies:
+ '@types/hast': 3.0.4
+ hast-util-sanitize: 5.0.2
+
dependencies:
'@types/hast': 3.0.4
@@ -15754,6 +16803,26 @@ snapshots:
+ dependencies:
+ micromark-extension-cjk-friendly-gfm-strikethrough: 1.2.3([email protected])([email protected])
+ unified: 11.0.5
+ optionalDependencies:
+ '@types/mdast': 4.0.4
+ transitivePeerDependencies:
+ - micromark
+ - micromark-util-types
+
+ dependencies:
+ micromark-extension-cjk-friendly: 1.2.3([email protected])([email protected])
+ unified: 11.0.5
+ optionalDependencies:
+ '@types/mdast': 4.0.4
+ transitivePeerDependencies:
+ - micromark
+ - micromark-util-types
+
dependencies:
'@types/mdast': 4.0.4
@@ -15797,6 +16866,8 @@ snapshots:
mdast-util-to-markdown: 2.1.2
unified: 11.0.5
+
dependencies:
css-select: 4.3.0
@@ -15861,6 +16932,8 @@ snapshots:
hash-base: 3.1.2
inherits: 2.0.4
+
dependencies:
'@types/estree': 1.0.8
@@ -15892,10 +16965,19 @@ snapshots:
'@rollup/rollup-win32-x64-msvc': 4.55.1
fsevents: 2.3.3
+ dependencies:
+ hachure-fill: 0.5.2
+ path-data-parser: 0.1.0
+ points-on-curve: 0.2.0
+ points-on-path: 0.2.1
+
dependencies:
queue-microtask: 1.2.3
+
dependencies:
tslib: 2.8.1
@@ -15925,6 +17007,8 @@ snapshots:
+
dependencies:
neo-async: 2.6.2
@@ -16037,6 +17121,17 @@ snapshots:
'@scarf/scarf': 1.4.0
deepmerge-ts: 7.1.5
+ dependencies:
+ '@shikijs/core': 3.21.0
+ '@shikijs/engine-javascript': 3.21.0
+ '@shikijs/engine-oniguruma': 3.21.0
+ '@shikijs/langs': 3.21.0
+ '@shikijs/themes': 3.21.0
+ '@shikijs/types': 3.21.0
+ '@shikijs/vscode-textmate': 10.0.2
+ '@types/hast': 3.0.4
+
dependencies:
should-type: 1.4.0
@@ -16176,6 +17271,26 @@ snapshots:
readable-stream: 3.6.2
xtend: 4.0.2
+ dependencies:
+ clsx: 2.1.1
+ hast-util-to-jsx-runtime: 2.3.6
+ html-url-attributes: 3.0.1
+ marked: 17.0.1
+ react: 18.3.1
+ rehype-harden: 1.1.7
+ rehype-raw: 7.0.0
+ rehype-sanitize: 6.0.0
+ remark-gfm: 4.0.1
+ remark-parse: 11.0.0
+ remark-rehype: 11.1.2
+ remend: 1.1.0
+ tailwind-merge: 3.4.0
+ unified: 11.0.5
+ unist-util-visit: 5.0.0
+ transitivePeerDependencies:
+ - supports-color
+
@@ -16301,6 +17416,8 @@ snapshots:
optionalDependencies:
'@babel/core': 7.28.5
+
dependencies:
'@jridgewell/gen-mapping': 0.3.13
@@ -16337,11 +17454,19 @@ snapshots:
transitivePeerDependencies:
- encoding
+ dependencies:
+ dequal: 2.0.3
+ react: 18.3.1
+ use-sync-external-store: 1.6.0([email protected])
+
optional: true
+
dependencies:
tailwindcss: 3.4.17
@@ -16409,6 +17534,8 @@ snapshots:
+
dependencies:
setimmediate: 1.0.5
@@ -16571,6 +17698,8 @@ snapshots:
+
dependencies:
call-bound: 1.0.4
@@ -16708,6 +17837,10 @@ snapshots:
optionalDependencies:
'@types/react': 18.3.17
+ dependencies:
+ react: 18.3.1
+
dependencies:
react: 18.3.1
@@ -16843,6 +17976,23 @@ snapshots:
+
+ dependencies:
+ vscode-jsonrpc: 8.2.0
+ vscode-languageserver-types: 3.17.5
+
+
+
+ dependencies:
+ vscode-languageserver-protocol: 3.17.5
+
+
dependencies:
xml-name-validator: 5.0.0
diff --git a/autogpt_platform/frontend/src/app/(platform)/build/components/NewControlPanel/NewBlockMenu/BlockMenuSearchBar/useBlockMenuSearchBar.ts b/autogpt_platform/frontend/src/app/(platform)/build/components/NewControlPanel/NewBlockMenu/BlockMenuSearchBar/useBlockMenuSearchBar.ts
index ab1af16584..e98d240215 100644
--- a/autogpt_platform/frontend/src/app/(platform)/build/components/NewControlPanel/NewBlockMenu/BlockMenuSearchBar/useBlockMenuSearchBar.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/build/components/NewControlPanel/NewBlockMenu/BlockMenuSearchBar/useBlockMenuSearchBar.ts
@@ -1,4 +1,4 @@
-import { debounce } from "lodash";
+import debounce from "lodash/debounce";
import { useCallback, useEffect, useRef, useState } from "react";
import { useBlockMenuStore } from "../../../../stores/blockMenuStore";
import { getQueryClient } from "@/lib/react-query/queryClient";
diff --git a/autogpt_platform/frontend/src/app/(platform)/build/components/NewControlPanel/NewBlockMenu/HorizontalScroll.tsx b/autogpt_platform/frontend/src/app/(platform)/build/components/NewControlPanel/NewBlockMenu/HorizontalScroll.tsx
index 0f953394e6..bee0b85721 100644
--- a/autogpt_platform/frontend/src/app/(platform)/build/components/NewControlPanel/NewBlockMenu/HorizontalScroll.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/build/components/NewControlPanel/NewBlockMenu/HorizontalScroll.tsx
@@ -70,10 +70,10 @@ export const HorizontalScroll: React.FC<HorizontalScrollAreaProps> = ({
{children}
</div>
{canScrollLeft && (
- <div className="pointer-events-none absolute inset-y-0 left-0 w-8 bg-gradient-to-r from-white via-white/80 to-white/0" />
+ <div className="pointer-events-none absolute inset-y-0 left-0 w-8 bg-gradient-to-r from-background via-background/80 to-background/0" />
)}
{canScrollRight && (
- <div className="pointer-events-none absolute inset-y-0 right-0 w-8 bg-gradient-to-l from-white via-white/80 to-white/0" />
+ <div className="pointer-events-none absolute inset-y-0 right-0 w-8 bg-gradient-to-l from-background via-background/80 to-background/0" />
)}
{canScrollLeft && (
<button
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/CopilotPage.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/CopilotPage.tsx
new file mode 100644
index 0000000000..cd1033f535
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/CopilotPage.tsx
@@ -0,0 +1,76 @@
+"use client";
+
+import { LoadingSpinner } from "@/components/atoms/LoadingSpinner/LoadingSpinner";
+import { SidebarProvider } from "@/components/ui/sidebar";
+import { ChatContainer } from "./components/ChatContainer/ChatContainer";
+import { ChatSidebar } from "./components/ChatSidebar/ChatSidebar";
+import { MobileDrawer } from "./components/MobileDrawer/MobileDrawer";
+import { MobileHeader } from "./components/MobileHeader/MobileHeader";
+import { useCopilotPage } from "./useCopilotPage";
+
+export function CopilotPage() {
+ const {
+ sessionId,
+ messages,
+ status,
+ error,
+ stop,
+ createSession,
+ onSend,
+ isLoadingSession,
+ isCreatingSession,
+ isUserLoading,
+ isLoggedIn,
+ // Mobile drawer
+ isMobile,
+ isDrawerOpen,
+ sessions,
+ isLoadingSessions,
+ handleOpenDrawer,
+ handleCloseDrawer,
+ handleDrawerOpenChange,
+ handleSelectSession,
+ handleNewChat,
+ } = useCopilotPage();
+
+ if (isUserLoading || !isLoggedIn) {
+ return <LoadingSpinner size="large" cover />;
+ }
+
+ return (
+ <SidebarProvider
+ defaultOpen={true}
+ className="h-[calc(100vh-72px)] min-h-0"
+ >
+ {!isMobile && <ChatSidebar />}
+ <div className="relative flex h-full w-full flex-col overflow-hidden bg-[#f8f8f9] px-0">
+ {isMobile && <MobileHeader onOpenDrawer={handleOpenDrawer} />}
+ <div className="flex-1 overflow-hidden">
+ <ChatContainer
+ messages={messages}
+ status={status}
+ error={error}
+ sessionId={sessionId}
+ isLoadingSession={isLoadingSession}
+ isCreatingSession={isCreatingSession}
+ onCreateSession={createSession}
+ onSend={onSend}
+ onStop={stop}
+ />
+ </div>
+ </div>
+ {isMobile && (
+ <MobileDrawer
+ isOpen={isDrawerOpen}
+ sessions={sessions}
+ currentSessionId={sessionId}
+ isLoading={isLoadingSessions}
+ onSelectSession={handleSelectSession}
+ onNewChat={handleNewChat}
+ onClose={handleCloseDrawer}
+ onOpenChange={handleDrawerOpenChange}
+ />
+ )}
+ </SidebarProvider>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/ChatContainer.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/ChatContainer.tsx
new file mode 100644
index 0000000000..5074741095
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/ChatContainer.tsx
@@ -0,0 +1,74 @@
+"use client";
+import { ChatInput } from "@/app/(platform)/copilot/components/ChatInput/ChatInput";
+import { UIDataTypes, UIMessage, UITools } from "ai";
+import { LayoutGroup, motion } from "framer-motion";
+import { ChatMessagesContainer } from "../ChatMessagesContainer/ChatMessagesContainer";
+import { CopilotChatActionsProvider } from "../CopilotChatActionsProvider/CopilotChatActionsProvider";
+import { EmptySession } from "../EmptySession/EmptySession";
+
+export interface ChatContainerProps {
+ messages: UIMessage<unknown, UIDataTypes, UITools>[];
+ status: string;
+ error: Error | undefined;
+ sessionId: string | null;
+ isLoadingSession: boolean;
+ isCreatingSession: boolean;
+ onCreateSession: () => void | Promise<string>;
+ onSend: (message: string) => void | Promise<void>;
+ onStop: () => void;
+}
+export const ChatContainer = ({
+ messages,
+ status,
+ error,
+ sessionId,
+ isLoadingSession,
+ isCreatingSession,
+ onCreateSession,
+ onSend,
+ onStop,
+}: ChatContainerProps) => {
+ const inputLayoutId = "copilot-2-chat-input";
+
+ return (
+ <CopilotChatActionsProvider onSend={onSend}>
+ <LayoutGroup id="copilot-2-chat-layout">
+ <div className="flex h-full min-h-0 w-full flex-col bg-[#f8f8f9] px-2 lg:px-0">
+ {sessionId ? (
+ <div className="mx-auto flex h-full min-h-0 w-full max-w-3xl flex-col">
+ <ChatMessagesContainer
+ messages={messages}
+ status={status}
+ error={error}
+ isLoading={isLoadingSession}
+ />
+ <motion.div
+ initial={{ opacity: 0 }}
+ animate={{ opacity: 1 }}
+ transition={{ duration: 0.3 }}
+ className="relative px-3 pb-2 pt-2"
+ >
+ <div className="pointer-events-none absolute left-0 right-0 top-[-18px] z-10 h-6 bg-gradient-to-b from-transparent to-[#f8f8f9]" />
+ <ChatInput
+ inputId="chat-input-session"
+ onSend={onSend}
+ disabled={status === "streaming"}
+ isStreaming={status === "streaming"}
+ onStop={onStop}
+ placeholder="What else can I help with?"
+ />
+ </motion.div>
+ </div>
+ ) : (
+ <EmptySession
+ inputLayoutId={inputLayoutId}
+ isCreatingSession={isCreatingSession}
+ onCreateSession={onCreateSession}
+ onSend={onSend}
+ />
+ )}
+ </div>
+ </LayoutGroup>
+ </CopilotChatActionsProvider>
+ );
+};
diff --git a/autogpt_platform/frontend/src/components/contextual/Chat/components/ChatInput/ChatInput.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/ChatInput.tsx
similarity index 93%
rename from autogpt_platform/frontend/src/components/contextual/Chat/components/ChatInput/ChatInput.tsx
rename to autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/ChatInput.tsx
index bac004f6ed..af44232a4a 100644
--- a/autogpt_platform/frontend/src/components/contextual/Chat/components/ChatInput/ChatInput.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/ChatInput.tsx
@@ -6,17 +6,19 @@ import {
MicrophoneIcon,
StopIcon,
} from "@phosphor-icons/react";
+import { ChangeEvent, useCallback } from "react";
import { RecordingIndicator } from "./components/RecordingIndicator";
import { useChatInput } from "./useChatInput";
import { useVoiceRecording } from "./useVoiceRecording";
export interface Props {
- onSend: (message: string) => void;
+ onSend: (message: string) => void | Promise<void>;
disabled?: boolean;
isStreaming?: boolean;
onStop?: () => void;
placeholder?: string;
className?: string;
+ inputId?: string;
}
export function ChatInput({
@@ -26,14 +28,14 @@ export function ChatInput({
onStop,
placeholder = "Type your message...",
className,
+ inputId = "chat-input",
}: Props) {
- const inputId = "chat-input";
const {
value,
setValue,
handleKeyDown: baseHandleKeyDown,
handleSubmit,
- handleChange,
+ handleChange: baseHandleChange,
hasMultipleLines,
} = useChatInput({
onSend,
@@ -60,6 +62,15 @@ export function ChatInput({
inputId,
});
+ // Block text changes when recording
+ const handleChange = useCallback(
+ (e: ChangeEvent<HTMLTextAreaElement>) => {
+ if (isRecording) return;
+ baseHandleChange(e);
+ },
+ [isRecording, baseHandleChange],
+ );
+
return (
<form onSubmit={handleSubmit} className={cn("relative flex-1", className)}>
<div className="relative">
diff --git a/autogpt_platform/frontend/src/components/contextual/Chat/components/ChatInput/components/AudioWaveform.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/AudioWaveform.tsx
similarity index 100%
rename from autogpt_platform/frontend/src/components/contextual/Chat/components/ChatInput/components/AudioWaveform.tsx
rename to autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/AudioWaveform.tsx
diff --git a/autogpt_platform/frontend/src/components/contextual/Chat/components/ChatInput/components/RecordingIndicator.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/RecordingIndicator.tsx
similarity index 100%
rename from autogpt_platform/frontend/src/components/contextual/Chat/components/ChatInput/components/RecordingIndicator.tsx
rename to autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/RecordingIndicator.tsx
diff --git a/autogpt_platform/frontend/src/components/contextual/Chat/components/ChatInput/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/helpers.ts
similarity index 100%
rename from autogpt_platform/frontend/src/components/contextual/Chat/components/ChatInput/helpers.ts
rename to autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/helpers.ts
diff --git a/autogpt_platform/frontend/src/components/contextual/Chat/components/ChatInput/useChatInput.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/useChatInput.ts
similarity index 83%
rename from autogpt_platform/frontend/src/components/contextual/Chat/components/ChatInput/useChatInput.ts
rename to autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/useChatInput.ts
index a053e6080f..64b39c3817 100644
--- a/autogpt_platform/frontend/src/components/contextual/Chat/components/ChatInput/useChatInput.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/useChatInput.ts
@@ -21,6 +21,7 @@ export function useChatInput({
}: Args) {
const [value, setValue] = useState("");
const [hasMultipleLines, setHasMultipleLines] = useState(false);
+ const [isSending, setIsSending] = useState(false);
useEffect(
function focusOnMount() {
@@ -100,34 +101,40 @@ export function useChatInput({
}
}, [value, maxRows, inputId]);
- const handleSend = () => {
- if (disabled || !value.trim()) return;
- onSend(value.trim());
- setValue("");
- setHasMultipleLines(false);
- const textarea = document.getElementById(inputId) as HTMLTextAreaElement;
- const wrapper = document.getElementById(
- `${inputId}-wrapper`,
- ) as HTMLDivElement;
- if (textarea) {
- textarea.style.height = "auto";
- }
- if (wrapper) {
- wrapper.style.height = "";
- wrapper.style.maxHeight = "";
+ async function handleSend() {
+ if (disabled || isSending || !value.trim()) return;
+
+ setIsSending(true);
+ try {
+ await onSend(value.trim());
+ setValue("");
+ setHasMultipleLines(false);
+ const textarea = document.getElementById(inputId) as HTMLTextAreaElement;
+ const wrapper = document.getElementById(
+ `${inputId}-wrapper`,
+ ) as HTMLDivElement;
+ if (textarea) {
+ textarea.style.height = "auto";
+ }
+ if (wrapper) {
+ wrapper.style.height = "";
+ wrapper.style.maxHeight = "";
+ }
+ } finally {
+ setIsSending(false);
}
- };
+ }
function handleKeyDown(event: KeyboardEvent<HTMLTextAreaElement>) {
if (event.key === "Enter" && !event.shiftKey) {
event.preventDefault();
- handleSend();
+ void handleSend();
}
}
function handleSubmit(e: FormEvent<HTMLFormElement>) {
e.preventDefault();
- handleSend();
+ void handleSend();
}
function handleChange(e: ChangeEvent<HTMLTextAreaElement>) {
@@ -142,5 +149,6 @@ export function useChatInput({
handleSubmit,
handleChange,
hasMultipleLines,
+ isSending,
};
}
diff --git a/autogpt_platform/frontend/src/components/contextual/Chat/components/ChatInput/useVoiceRecording.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/useVoiceRecording.ts
similarity index 86%
rename from autogpt_platform/frontend/src/components/contextual/Chat/components/ChatInput/useVoiceRecording.ts
rename to autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/useVoiceRecording.ts
index 4fd500d96a..0f9ee51736 100644
--- a/autogpt_platform/frontend/src/components/contextual/Chat/components/ChatInput/useVoiceRecording.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/useVoiceRecording.ts
@@ -38,9 +38,13 @@ export function useVoiceRecording({
const streamRef = useRef<MediaStream | null>(null);
const isRecordingRef = useRef(false);
- const isSupported =
- typeof window !== "undefined" &&
- !!(navigator.mediaDevices && navigator.mediaDevices.getUserMedia);
+ const [isSupported, setIsSupported] = useState(false);
+
+ useEffect(() => {
+ setIsSupported(
+ !!(navigator.mediaDevices && navigator.mediaDevices.getUserMedia),
+ );
+ }, []);
const clearTimer = useCallback(() => {
if (timerRef.current) {
@@ -214,17 +218,33 @@ export function useVoiceRecording({
const handleKeyDown = useCallback(
(event: KeyboardEvent<HTMLTextAreaElement>) => {
- if (event.key === " " && !value.trim() && !isTranscribing) {
+ // Allow space to toggle recording (start when empty, stop when recording)
+ if (event.key === " " && !isTranscribing) {
+ if (isRecordingRef.current) {
+ // Stop recording on space
+ event.preventDefault();
+ stopRecording();
+ return;
+ } else if (!value.trim()) {
+ // Start recording on space when input is empty
+ event.preventDefault();
+ void startRecording();
+ return;
+ }
+ }
+ // Block all key events when recording (except space handled above)
+ if (isRecordingRef.current) {
event.preventDefault();
- toggleRecording();
return;
}
baseHandleKeyDown(event);
},
- [value, isTranscribing, toggleRecording, baseHandleKeyDown],
+ [value, isTranscribing, stopRecording, startRecording, baseHandleKeyDown],
);
const showMicButton = isSupported;
+ // Don't include isRecording in disabled state - we need key events to work
+ // Text input is blocked via handleKeyDown instead
const isInputDisabled = disabled || isStreaming || isTranscribing;
// Cleanup on unmount
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/ChatMessagesContainer.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/ChatMessagesContainer.tsx
new file mode 100644
index 0000000000..0867ede5a4
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/ChatMessagesContainer.tsx
@@ -0,0 +1,274 @@
+import { getGetWorkspaceDownloadFileByIdUrl } from "@/app/api/__generated__/endpoints/workspace/workspace";
+import {
+ Conversation,
+ ConversationContent,
+ ConversationScrollButton,
+} from "@/components/ai-elements/conversation";
+import {
+ Message,
+ MessageContent,
+ MessageResponse,
+} from "@/components/ai-elements/message";
+import { LoadingSpinner } from "@/components/atoms/LoadingSpinner/LoadingSpinner";
+import { ToolUIPart, UIDataTypes, UIMessage, UITools } from "ai";
+import { useEffect, useState } from "react";
+import { CreateAgentTool } from "../../tools/CreateAgent/CreateAgent";
+import { EditAgentTool } from "../../tools/EditAgent/EditAgent";
+import { FindAgentsTool } from "../../tools/FindAgents/FindAgents";
+import { FindBlocksTool } from "../../tools/FindBlocks/FindBlocks";
+import { RunAgentTool } from "../../tools/RunAgent/RunAgent";
+import { RunBlockTool } from "../../tools/RunBlock/RunBlock";
+import { SearchDocsTool } from "../../tools/SearchDocs/SearchDocs";
+import { ViewAgentOutputTool } from "../../tools/ViewAgentOutput/ViewAgentOutput";
+
+// ---------------------------------------------------------------------------
+// Workspace media support
+// ---------------------------------------------------------------------------
+
+/**
+ * Resolve workspace:// URLs in markdown text to proxy download URLs.
+ * Detects MIME type from the hash fragment (e.g. workspace://id#video/mp4)
+ * and prefixes the alt text with "video:" so the custom img component can
+ * render a <video> element instead.
+ */
+function resolveWorkspaceUrls(text: string): string {
+ return text.replace(
+ /!\[([^\]]*)\]\(workspace:\/\/([^)#\s]+)(?:#([^)\s]*))?\)/g,
+ (_match, alt: string, fileId: string, mimeHint?: string) => {
+ const apiPath = getGetWorkspaceDownloadFileByIdUrl(fileId);
+ const url = `/api/proxy${apiPath}`;
+ if (mimeHint?.startsWith("video/")) {
+ return `![video:${alt || "Video"}](${url})`;
+ }
+ return `![${alt || "Image"}](${url})`;
+ },
+ );
+}
+
+/**
+ * Custom img component for Streamdown that renders <video> elements
+ * for workspace video files (detected via "video:" alt-text prefix).
+ * Falls back to <video> when an <img> fails to load for workspace files.
+ */
+function WorkspaceMediaImage(props: React.JSX.IntrinsicElements["img"]) {
+ const { src, alt, ...rest } = props;
+ const [imgFailed, setImgFailed] = useState(false);
+ const isWorkspace = src?.includes("/workspace/files/") ?? false;
+
+ if (!src) return null;
+
+ if (alt?.startsWith("video:") || (imgFailed && isWorkspace)) {
+ return (
+ <span className="my-2 inline-block">
+ <video
+ controls
+ className="h-auto max-w-full rounded-md border border-zinc-200"
+ preload="metadata"
+ >
+ <source src={src} />
+ Your browser does not support the video tag.
+ </video>
+ </span>
+ );
+ }
+
+ return (
+ // eslint-disable-next-line @next/next/no-img-element
+ <img
+ src={src}
+ alt={alt || "Image"}
+ className="h-auto max-w-full rounded-md border border-zinc-200"
+ loading="lazy"
+ onError={() => {
+ if (isWorkspace) setImgFailed(true);
+ }}
+ {...rest}
+ />
+ );
+}
+
+/** Stable components override for Streamdown (avoids re-creating on every render). */
+const STREAMDOWN_COMPONENTS = { img: WorkspaceMediaImage };
+
+const THINKING_PHRASES = [
+ "Thinking...",
+ "Considering this...",
+ "Working through this...",
+ "Analyzing your request...",
+ "Reasoning...",
+ "Looking into it...",
+ "Processing your request...",
+ "Mulling this over...",
+ "Piecing it together...",
+ "On it...",
+];
+
+function getRandomPhrase() {
+ return THINKING_PHRASES[Math.floor(Math.random() * THINKING_PHRASES.length)];
+}
+
+interface ChatMessagesContainerProps {
+ messages: UIMessage<unknown, UIDataTypes, UITools>[];
+ status: string;
+ error: Error | undefined;
+ isLoading: boolean;
+}
+
+export const ChatMessagesContainer = ({
+ messages,
+ status,
+ error,
+ isLoading,
+}: ChatMessagesContainerProps) => {
+ const [thinkingPhrase, setThinkingPhrase] = useState(getRandomPhrase);
+
+ useEffect(() => {
+ if (status === "submitted") {
+ setThinkingPhrase(getRandomPhrase());
+ }
+ }, [status]);
+
+ const lastMessage = messages[messages.length - 1];
+ const lastAssistantHasVisibleContent =
+ lastMessage?.role === "assistant" &&
+ lastMessage.parts.some(
+ (p) =>
+ (p.type === "text" && p.text.trim().length > 0) ||
+ p.type.startsWith("tool-"),
+ );
+
+ const showThinking =
+ status === "submitted" ||
+ (status === "streaming" && !lastAssistantHasVisibleContent);
+
+ return (
+ <Conversation className="min-h-0 flex-1">
+ <ConversationContent className="gap-6 px-3 py-6">
+ {isLoading && messages.length === 0 && (
+ <div className="flex flex-1 items-center justify-center">
+ <LoadingSpinner size="large" className="text-neutral-400" />
+ </div>
+ )}
+ {messages.map((message, messageIndex) => {
+ const isLastAssistant =
+ messageIndex === messages.length - 1 &&
+ message.role === "assistant";
+ const messageHasVisibleContent = message.parts.some(
+ (p) =>
+ (p.type === "text" && p.text.trim().length > 0) ||
+ p.type.startsWith("tool-"),
+ );
+
+ return (
+ <Message from={message.role} key={message.id}>
+ <MessageContent
+ className={
+ "text-[1rem] leading-relaxed " +
+ "group-[.is-user]:rounded-xl group-[.is-user]:bg-purple-100 group-[.is-user]:px-3 group-[.is-user]:py-2.5 group-[.is-user]:text-slate-900 group-[.is-user]:[border-bottom-right-radius:0] " +
+ "group-[.is-assistant]:bg-transparent group-[.is-assistant]:text-slate-900"
+ }
+ >
+ {message.parts.map((part, i) => {
+ switch (part.type) {
+ case "text":
+ return (
+ <MessageResponse
+ key={`${message.id}-${i}`}
+ components={STREAMDOWN_COMPONENTS}
+ >
+ {resolveWorkspaceUrls(part.text)}
+ </MessageResponse>
+ );
+ case "tool-find_block":
+ return (
+ <FindBlocksTool
+ key={`${message.id}-${i}`}
+ part={part as ToolUIPart}
+ />
+ );
+ case "tool-find_agent":
+ case "tool-find_library_agent":
+ return (
+ <FindAgentsTool
+ key={`${message.id}-${i}`}
+ part={part as ToolUIPart}
+ />
+ );
+ case "tool-search_docs":
+ case "tool-get_doc_page":
+ return (
+ <SearchDocsTool
+ key={`${message.id}-${i}`}
+ part={part as ToolUIPart}
+ />
+ );
+ case "tool-run_block":
+ return (
+ <RunBlockTool
+ key={`${message.id}-${i}`}
+ part={part as ToolUIPart}
+ />
+ );
+ case "tool-run_agent":
+ case "tool-schedule_agent":
+ return (
+ <RunAgentTool
+ key={`${message.id}-${i}`}
+ part={part as ToolUIPart}
+ />
+ );
+ case "tool-create_agent":
+ return (
+ <CreateAgentTool
+ key={`${message.id}-${i}`}
+ part={part as ToolUIPart}
+ />
+ );
+ case "tool-edit_agent":
+ return (
+ <EditAgentTool
+ key={`${message.id}-${i}`}
+ part={part as ToolUIPart}
+ />
+ );
+ case "tool-view_agent_output":
+ return (
+ <ViewAgentOutputTool
+ key={`${message.id}-${i}`}
+ part={part as ToolUIPart}
+ />
+ );
+ default:
+ return null;
+ }
+ })}
+ {isLastAssistant &&
+ !messageHasVisibleContent &&
+ showThinking && (
+ <span className="inline-block animate-shimmer bg-gradient-to-r from-neutral-400 via-neutral-600 to-neutral-400 bg-[length:200%_100%] bg-clip-text text-transparent">
+ {thinkingPhrase}
+ </span>
+ )}
+ </MessageContent>
+ </Message>
+ );
+ })}
+ {showThinking && lastMessage?.role !== "assistant" && (
+ <Message from="assistant">
+ <MessageContent className="text-[1rem] leading-relaxed">
+ <span className="inline-block animate-shimmer bg-gradient-to-r from-neutral-400 via-neutral-600 to-neutral-400 bg-[length:200%_100%] bg-clip-text text-transparent">
+ {thinkingPhrase}
+ </span>
+ </MessageContent>
+ </Message>
+ )}
+ {error && (
+ <div className="rounded-lg bg-red-50 p-3 text-red-600">
+ Error: {error.message}
+ </div>
+ )}
+ </ConversationContent>
+ <ConversationScrollButton />
+ </Conversation>
+ );
+};
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSidebar/ChatSidebar.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSidebar/ChatSidebar.tsx
new file mode 100644
index 0000000000..8a48cb66c2
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSidebar/ChatSidebar.tsx
@@ -0,0 +1,188 @@
+"use client";
+import { useGetV2ListSessions } from "@/app/api/__generated__/endpoints/chat/chat";
+import { Button } from "@/components/atoms/Button/Button";
+import { LoadingSpinner } from "@/components/atoms/LoadingSpinner/LoadingSpinner";
+import { Text } from "@/components/atoms/Text/Text";
+import {
+ Sidebar,
+ SidebarContent,
+ SidebarFooter,
+ SidebarHeader,
+ SidebarTrigger,
+ useSidebar,
+} from "@/components/ui/sidebar";
+import { cn } from "@/lib/utils";
+import { PlusCircleIcon, PlusIcon } from "@phosphor-icons/react";
+import { motion } from "framer-motion";
+import { parseAsString, useQueryState } from "nuqs";
+
+export function ChatSidebar() {
+ const { state } = useSidebar();
+ const isCollapsed = state === "collapsed";
+ const [sessionId, setSessionId] = useQueryState("sessionId", parseAsString);
+
+ const { data: sessionsResponse, isLoading: isLoadingSessions } =
+ useGetV2ListSessions({ limit: 50 });
+
+ const sessions =
+ sessionsResponse?.status === 200 ? sessionsResponse.data.sessions : [];
+
+ function handleNewChat() {
+ setSessionId(null);
+ }
+
+ function handleSelectSession(id: string) {
+ setSessionId(id);
+ }
+
+ function formatDate(dateString: string) {
+ const date = new Date(dateString);
+ const now = new Date();
+ const diffMs = now.getTime() - date.getTime();
+ const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));
+
+ if (diffDays === 0) return "Today";
+ if (diffDays === 1) return "Yesterday";
+ if (diffDays < 7) return `${diffDays} days ago`;
+
+ const day = date.getDate();
+ const ordinal =
+ day % 10 === 1 && day !== 11
+ ? "st"
+ : day % 10 === 2 && day !== 12
+ ? "nd"
+ : day % 10 === 3 && day !== 13
+ ? "rd"
+ : "th";
+ const month = date.toLocaleDateString("en-US", { month: "short" });
+ const year = date.getFullYear();
+
+ return `${day}${ordinal} ${month} ${year}`;
+ }
+
+ return (
+ <Sidebar
+ variant="inset"
+ collapsible="icon"
+ className="!top-[50px] !h-[calc(100vh-50px)] border-r border-zinc-100 px-0"
+ >
+ {isCollapsed && (
+ <SidebarHeader
+ className={cn(
+ "flex",
+ isCollapsed
+ ? "flex-row items-center justify-between gap-y-4 md:flex-col md:items-start md:justify-start"
+ : "flex-row items-center justify-between",
+ )}
+ >
+ <motion.div
+ key={isCollapsed ? "header-collapsed" : "header-expanded"}
+ className="flex flex-col items-center gap-3 pt-4"
+ initial={{ opacity: 0, filter: "blur(3px)" }}
+ animate={{ opacity: 1, filter: "blur(0px)" }}
+ transition={{ type: "spring", bounce: 0.2 }}
+ >
+ <div className="flex flex-col items-center gap-2">
+ <SidebarTrigger />
+ <Button
+ variant="ghost"
+ onClick={handleNewChat}
+ style={{ minWidth: "auto", width: "auto" }}
+ >
+ <PlusCircleIcon className="!size-5" />
+ <span className="sr-only">New Chat</span>
+ </Button>
+ </div>
+ </motion.div>
+ </SidebarHeader>
+ )}
+ <SidebarContent className="gap-4 overflow-y-auto px-4 py-4 [-ms-overflow-style:none] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
+ {!isCollapsed && (
+ <motion.div
+ initial={{ opacity: 0 }}
+ animate={{ opacity: 1 }}
+ transition={{ duration: 0.2, delay: 0.1 }}
+ className="flex items-center justify-between px-3"
+ >
+ <Text variant="h3" size="body-medium">
+ Your chats
+ </Text>
+ <div className="relative left-6">
+ <SidebarTrigger />
+ </div>
+ </motion.div>
+ )}
+
+ {!isCollapsed && (
+ <motion.div
+ initial={{ opacity: 0 }}
+ animate={{ opacity: 1 }}
+ transition={{ duration: 0.2, delay: 0.15 }}
+ className="mt-4 flex flex-col gap-1"
+ >
+ {isLoadingSessions ? (
+ <div className="flex items-center justify-center py-4">
+ <LoadingSpinner size="small" className="text-neutral-400" />
+ </div>
+ ) : sessions.length === 0 ? (
+ <p className="py-4 text-center text-sm text-neutral-500">
+ No conversations yet
+ </p>
+ ) : (
+ sessions.map((session) => (
+ <button
+ key={session.id}
+ onClick={() => handleSelectSession(session.id)}
+ className={cn(
+ "w-full rounded-lg px-3 py-2.5 text-left transition-colors",
+ session.id === sessionId
+ ? "bg-zinc-100"
+ : "hover:bg-zinc-50",
+ )}
+ >
+ <div className="flex min-w-0 max-w-full flex-col overflow-hidden">
+ <div className="min-w-0 max-w-full">
+ <Text
+ variant="body"
+ className={cn(
+ "truncate font-normal",
+ session.id === sessionId
+ ? "text-zinc-600"
+ : "text-zinc-800",
+ )}
+ >
+ {session.title || `Untitled chat`}
+ </Text>
+ </div>
+ <Text variant="small" className="text-neutral-400">
+ {formatDate(session.updated_at)}
+ </Text>
+ </div>
+ </button>
+ ))
+ )}
+ </motion.div>
+ )}
+ </SidebarContent>
+ {!isCollapsed && sessionId && (
+ <SidebarFooter className="shrink-0 bg-zinc-50 p-3 pb-1 shadow-[0_-4px_6px_-1px_rgba(0,0,0,0.05)]">
+ <motion.div
+ initial={{ opacity: 0 }}
+ animate={{ opacity: 1 }}
+ transition={{ duration: 0.2, delay: 0.2 }}
+ >
+ <Button
+ variant="primary"
+ size="small"
+ onClick={handleNewChat}
+ className="w-full"
+ leftIcon={<PlusIcon className="h-4 w-4" weight="bold" />}
+ >
+ New Chat
+ </Button>
+ </motion.div>
+ </SidebarFooter>
+ )}
+ </Sidebar>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotChatActionsProvider/CopilotChatActionsProvider.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotChatActionsProvider/CopilotChatActionsProvider.tsx
new file mode 100644
index 0000000000..5c80348e8c
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotChatActionsProvider/CopilotChatActionsProvider.tsx
@@ -0,0 +1,16 @@
+"use client";
+
+import { CopilotChatActionsContext } from "./useCopilotChatActions";
+
+interface Props {
+ onSend: (message: string) => void | Promise<void>;
+ children: React.ReactNode;
+}
+
+export function CopilotChatActionsProvider({ onSend, children }: Props) {
+ return (
+ <CopilotChatActionsContext.Provider value={{ onSend }}>
+ {children}
+ </CopilotChatActionsContext.Provider>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotChatActionsProvider/useCopilotChatActions.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotChatActionsProvider/useCopilotChatActions.ts
new file mode 100644
index 0000000000..31b27c0f6e
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotChatActionsProvider/useCopilotChatActions.ts
@@ -0,0 +1,23 @@
+"use client";
+
+import { createContext, useContext } from "react";
+
+interface CopilotChatActions {
+ onSend: (message: string) => void | Promise<void>;
+}
+
+const CopilotChatActionsContext = createContext<CopilotChatActions | null>(
+ null,
+);
+
+export function useCopilotChatActions(): CopilotChatActions {
+ const ctx = useContext(CopilotChatActionsContext);
+ if (!ctx) {
+ throw new Error(
+ "useCopilotChatActions must be used within CopilotChatActionsProvider",
+ );
+ }
+ return ctx;
+}
+
+export { CopilotChatActionsContext };
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotShell/CopilotShell.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotShell/CopilotShell.tsx
deleted file mode 100644
index 3f695da5ed..0000000000
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotShell/CopilotShell.tsx
+++ /dev/null
@@ -1,99 +0,0 @@
-"use client";
-
-import { ChatLoader } from "@/components/contextual/Chat/components/ChatLoader/ChatLoader";
-import { Text } from "@/components/atoms/Text/Text";
-import { NAVBAR_HEIGHT_PX } from "@/lib/constants";
-import type { ReactNode } from "react";
-import { DesktopSidebar } from "./components/DesktopSidebar/DesktopSidebar";
-import { MobileDrawer } from "./components/MobileDrawer/MobileDrawer";
-import { MobileHeader } from "./components/MobileHeader/MobileHeader";
-import { useCopilotShell } from "./useCopilotShell";
-
-interface Props {
- children: ReactNode;
-}
-
-export function CopilotShell({ children }: Props) {
- const {
- isMobile,
- isDrawerOpen,
- isLoading,
- isCreatingSession,
- isLoggedIn,
- hasActiveSession,
- sessions,
- currentSessionId,
- handleOpenDrawer,
- handleCloseDrawer,
- handleDrawerOpenChange,
- handleNewChatClick,
- handleSessionClick,
- hasNextPage,
- isFetchingNextPage,
- fetchNextPage,
- } = useCopilotShell();
-
- if (!isLoggedIn) {
- return (
- <div className="flex h-full items-center justify-center">
- <ChatLoader />
- </div>
- );
- }
-
- return (
- <div
- className="flex overflow-hidden bg-[#EFEFF0]"
- style={{ height: `calc(100vh - ${NAVBAR_HEIGHT_PX}px)` }}
- >
- {!isMobile && (
- <DesktopSidebar
- sessions={sessions}
- currentSessionId={currentSessionId}
- isLoading={isLoading}
- hasNextPage={hasNextPage}
- isFetchingNextPage={isFetchingNextPage}
- onSelectSession={handleSessionClick}
- onFetchNextPage={fetchNextPage}
- onNewChat={handleNewChatClick}
- hasActiveSession={Boolean(hasActiveSession)}
- />
- )}
-
- <div className="relative flex min-h-0 flex-1 flex-col">
- {isMobile && <MobileHeader onOpenDrawer={handleOpenDrawer} />}
- <div className="flex min-h-0 flex-1 flex-col">
- {isCreatingSession ? (
- <div className="flex h-full flex-1 flex-col items-center justify-center bg-[#f8f8f9]">
- <div className="flex flex-col items-center gap-4">
- <ChatLoader />
- <Text variant="body" className="text-zinc-500">
- Creating your chat...
- </Text>
- </div>
- </div>
- ) : (
- children
- )}
- </div>
- </div>
-
- {isMobile && (
- <MobileDrawer
- isOpen={isDrawerOpen}
- sessions={sessions}
- currentSessionId={currentSessionId}
- isLoading={isLoading}
- hasNextPage={hasNextPage}
- isFetchingNextPage={isFetchingNextPage}
- onSelectSession={handleSessionClick}
- onFetchNextPage={fetchNextPage}
- onNewChat={handleNewChatClick}
- onClose={handleCloseDrawer}
- onOpenChange={handleDrawerOpenChange}
- hasActiveSession={Boolean(hasActiveSession)}
- />
- )}
- </div>
- );
-}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotShell/components/DesktopSidebar/DesktopSidebar.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotShell/components/DesktopSidebar/DesktopSidebar.tsx
deleted file mode 100644
index 122a09a02f..0000000000
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotShell/components/DesktopSidebar/DesktopSidebar.tsx
+++ /dev/null
@@ -1,70 +0,0 @@
-import type { SessionSummaryResponse } from "@/app/api/__generated__/models/sessionSummaryResponse";
-import { Button } from "@/components/atoms/Button/Button";
-import { Text } from "@/components/atoms/Text/Text";
-import { scrollbarStyles } from "@/components/styles/scrollbars";
-import { cn } from "@/lib/utils";
-import { Plus } from "@phosphor-icons/react";
-import { SessionsList } from "../SessionsList/SessionsList";
-
-interface Props {
- sessions: SessionSummaryResponse[];
- currentSessionId: string | null;
- isLoading: boolean;
- hasNextPage: boolean;
- isFetchingNextPage: boolean;
- onSelectSession: (sessionId: string) => void;
- onFetchNextPage: () => void;
- onNewChat: () => void;
- hasActiveSession: boolean;
-}
-
-export function DesktopSidebar({
- sessions,
- currentSessionId,
- isLoading,
- hasNextPage,
- isFetchingNextPage,
- onSelectSession,
- onFetchNextPage,
- onNewChat,
- hasActiveSession,
-}: Props) {
- return (
- <aside className="flex h-full w-80 flex-col border-r border-zinc-100 bg-zinc-50">
- <div className="shrink-0 px-6 py-4">
- <Text variant="h3" size="body-medium">
- Your chats
- </Text>
- </div>
- <div
- className={cn(
- "flex min-h-0 flex-1 flex-col overflow-y-auto px-3 py-3",
- scrollbarStyles,
- )}
- >
- <SessionsList
- sessions={sessions}
- currentSessionId={currentSessionId}
- isLoading={isLoading}
- hasNextPage={hasNextPage}
- isFetchingNextPage={isFetchingNextPage}
- onSelectSession={onSelectSession}
- onFetchNextPage={onFetchNextPage}
- />
- </div>
- {hasActiveSession && (
- <div className="shrink-0 bg-zinc-50 p-3 shadow-[0_-4px_6px_-1px_rgba(0,0,0,0.05)]">
- <Button
- variant="primary"
- size="small"
- onClick={onNewChat}
- className="w-full"
- leftIcon={<Plus width="1rem" height="1rem" />}
- >
- New Chat
- </Button>
- </div>
- )}
- </aside>
- );
-}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotShell/components/MobileDrawer/MobileDrawer.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotShell/components/MobileDrawer/MobileDrawer.tsx
deleted file mode 100644
index ea3b39f829..0000000000
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotShell/components/MobileDrawer/MobileDrawer.tsx
+++ /dev/null
@@ -1,91 +0,0 @@
-import type { SessionSummaryResponse } from "@/app/api/__generated__/models/sessionSummaryResponse";
-import { Button } from "@/components/atoms/Button/Button";
-import { scrollbarStyles } from "@/components/styles/scrollbars";
-import { cn } from "@/lib/utils";
-import { PlusIcon, X } from "@phosphor-icons/react";
-import { Drawer } from "vaul";
-import { SessionsList } from "../SessionsList/SessionsList";
-
-interface Props {
- isOpen: boolean;
- sessions: SessionSummaryResponse[];
- currentSessionId: string | null;
- isLoading: boolean;
- hasNextPage: boolean;
- isFetchingNextPage: boolean;
- onSelectSession: (sessionId: string) => void;
- onFetchNextPage: () => void;
- onNewChat: () => void;
- onClose: () => void;
- onOpenChange: (open: boolean) => void;
- hasActiveSession: boolean;
-}
-
-export function MobileDrawer({
- isOpen,
- sessions,
- currentSessionId,
- isLoading,
- hasNextPage,
- isFetchingNextPage,
- onSelectSession,
- onFetchNextPage,
- onNewChat,
- onClose,
- onOpenChange,
- hasActiveSession,
-}: Props) {
- return (
- <Drawer.Root open={isOpen} onOpenChange={onOpenChange} direction="left">
- <Drawer.Portal>
- <Drawer.Overlay className="fixed inset-0 z-[60] bg-black/10 backdrop-blur-sm" />
- <Drawer.Content className="fixed left-0 top-0 z-[70] flex h-full w-80 flex-col border-r border-zinc-200 bg-zinc-50">
- <div className="shrink-0 border-b border-zinc-200 p-4">
- <div className="flex items-center justify-between">
- <Drawer.Title className="text-lg font-semibold text-zinc-800">
- Your chats
- </Drawer.Title>
- <Button
- variant="icon"
- size="icon"
- aria-label="Close sessions"
- onClick={onClose}
- >
- <X width="1.25rem" height="1.25rem" />
- </Button>
- </div>
- </div>
- <div
- className={cn(
- "flex min-h-0 flex-1 flex-col overflow-y-auto px-3 py-3",
- scrollbarStyles,
- )}
- >
- <SessionsList
- sessions={sessions}
- currentSessionId={currentSessionId}
- isLoading={isLoading}
- hasNextPage={hasNextPage}
- isFetchingNextPage={isFetchingNextPage}
- onSelectSession={onSelectSession}
- onFetchNextPage={onFetchNextPage}
- />
- </div>
- {hasActiveSession && (
- <div className="shrink-0 bg-white p-3 shadow-[0_-4px_6px_-1px_rgba(0,0,0,0.05)]">
- <Button
- variant="primary"
- size="small"
- onClick={onNewChat}
- className="w-full"
- leftIcon={<PlusIcon width="1rem" height="1rem" />}
- >
- New Chat
- </Button>
- </div>
- )}
- </Drawer.Content>
- </Drawer.Portal>
- </Drawer.Root>
- );
-}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotShell/components/MobileDrawer/useMobileDrawer.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotShell/components/MobileDrawer/useMobileDrawer.ts
deleted file mode 100644
index 2ef63a4422..0000000000
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotShell/components/MobileDrawer/useMobileDrawer.ts
+++ /dev/null
@@ -1,24 +0,0 @@
-import { useState } from "react";
-
-export function useMobileDrawer() {
- const [isDrawerOpen, setIsDrawerOpen] = useState(false);
-
- const handleOpenDrawer = () => {
- setIsDrawerOpen(true);
- };
-
- const handleCloseDrawer = () => {
- setIsDrawerOpen(false);
- };
-
- const handleDrawerOpenChange = (open: boolean) => {
- setIsDrawerOpen(open);
- };
-
- return {
- isDrawerOpen,
- handleOpenDrawer,
- handleCloseDrawer,
- handleDrawerOpenChange,
- };
-}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotShell/components/SessionsList/SessionsList.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotShell/components/SessionsList/SessionsList.tsx
deleted file mode 100644
index ef63e1aff4..0000000000
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotShell/components/SessionsList/SessionsList.tsx
+++ /dev/null
@@ -1,80 +0,0 @@
-import type { SessionSummaryResponse } from "@/app/api/__generated__/models/sessionSummaryResponse";
-import { Skeleton } from "@/components/__legacy__/ui/skeleton";
-import { Text } from "@/components/atoms/Text/Text";
-import { InfiniteList } from "@/components/molecules/InfiniteList/InfiniteList";
-import { cn } from "@/lib/utils";
-import { getSessionTitle } from "../../helpers";
-
-interface Props {
- sessions: SessionSummaryResponse[];
- currentSessionId: string | null;
- isLoading: boolean;
- hasNextPage: boolean;
- isFetchingNextPage: boolean;
- onSelectSession: (sessionId: string) => void;
- onFetchNextPage: () => void;
-}
-
-export function SessionsList({
- sessions,
- currentSessionId,
- isLoading,
- hasNextPage,
- isFetchingNextPage,
- onSelectSession,
- onFetchNextPage,
-}: Props) {
- if (isLoading) {
- return (
- <div className="space-y-1">
- {Array.from({ length: 5 }).map((_, i) => (
- <div key={i} className="rounded-lg px-3 py-2.5">
- <Skeleton className="h-5 w-full" />
- </div>
- ))}
- </div>
- );
- }
-
- if (sessions.length === 0) {
- return (
- <div className="flex h-full items-center justify-center">
- <Text variant="body" className="text-zinc-500">
- You don&apos;t have previous chats
- </Text>
- </div>
- );
- }
-
- return (
- <InfiniteList
- items={sessions}
- hasMore={hasNextPage}
- isFetchingMore={isFetchingNextPage}
- onEndReached={onFetchNextPage}
- className="space-y-1"
- renderItem={(session) => {
- const isActive = session.id === currentSessionId;
- return (
- <button
- onClick={() => onSelectSession(session.id)}
- className={cn(
- "w-full rounded-lg px-3 py-2.5 text-left transition-colors",
- isActive ? "bg-zinc-100" : "hover:bg-zinc-50",
- )}
- >
- <Text
- variant="body"
- className={cn(
- "font-normal",
- isActive ? "text-zinc-600" : "text-zinc-800",
- )}
- >
- {getSessionTitle(session)}
- </Text>
- </button>
- );
- }}
- />
- );
-}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotShell/components/SessionsList/useSessionsPagination.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotShell/components/SessionsList/useSessionsPagination.ts
deleted file mode 100644
index 61e3e6f37f..0000000000
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotShell/components/SessionsList/useSessionsPagination.ts
+++ /dev/null
@@ -1,91 +0,0 @@
-import { useGetV2ListSessions } from "@/app/api/__generated__/endpoints/chat/chat";
-import type { SessionSummaryResponse } from "@/app/api/__generated__/models/sessionSummaryResponse";
-import { okData } from "@/app/api/helpers";
-import { useEffect, useState } from "react";
-
-const PAGE_SIZE = 50;
-
-export interface UseSessionsPaginationArgs {
- enabled: boolean;
-}
-
-export function useSessionsPagination({ enabled }: UseSessionsPaginationArgs) {
- const [offset, setOffset] = useState(0);
-
- const [accumulatedSessions, setAccumulatedSessions] = useState<
- SessionSummaryResponse[]
- >([]);
-
- const [totalCount, setTotalCount] = useState<number | null>(null);
-
- const { data, isLoading, isFetching, isError } = useGetV2ListSessions(
- { limit: PAGE_SIZE, offset },
- {
- query: {
- enabled: enabled && offset >= 0,
- },
- },
- );
-
- useEffect(() => {
- const responseData = okData(data);
- if (responseData) {
- const newSessions = responseData.sessions;
- const total = responseData.total;
- setTotalCount(total);
-
- if (offset === 0) {
- setAccumulatedSessions(newSessions);
- } else {
- setAccumulatedSessions((prev) => [...prev, ...newSessions]);
- }
- } else if (!enabled) {
- setAccumulatedSessions([]);
- setTotalCount(null);
- }
- }, [data, offset, enabled]);
-
- const hasNextPage =
- totalCount !== null && accumulatedSessions.length < totalCount;
-
- const areAllSessionsLoaded =
- totalCount !== null &&
- accumulatedSessions.length >= totalCount &&
- !isFetching &&
- !isLoading;
-
- useEffect(() => {
- if (
- hasNextPage &&
- !isFetching &&
- !isLoading &&
- !isError &&
- totalCount !== null
- ) {
- setOffset((prev) => prev + PAGE_SIZE);
- }
- }, [hasNextPage, isFetching, isLoading, isError, totalCount]);
-
- const fetchNextPage = () => {
- if (hasNextPage && !isFetching) {
- setOffset((prev) => prev + PAGE_SIZE);
- }
- };
-
- const reset = () => {
- // Only reset the offset - keep existing sessions visible during refetch
- // The effect will replace sessions when new data arrives at offset 0
- setOffset(0);
- };
-
- return {
- sessions: accumulatedSessions,
- isLoading,
- isFetching,
- hasNextPage,
- areAllSessionsLoaded,
- totalCount,
- fetchNextPage,
- reset,
- };
-}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotShell/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotShell/helpers.ts
deleted file mode 100644
index ef0d414edf..0000000000
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotShell/helpers.ts
+++ /dev/null
@@ -1,106 +0,0 @@
-import type { SessionDetailResponse } from "@/app/api/__generated__/models/sessionDetailResponse";
-import type { SessionSummaryResponse } from "@/app/api/__generated__/models/sessionSummaryResponse";
-import { format, formatDistanceToNow, isToday } from "date-fns";
-
-export function convertSessionDetailToSummary(session: SessionDetailResponse) {
- return {
- id: session.id,
- created_at: session.created_at,
- updated_at: session.updated_at,
- title: undefined,
- };
-}
-
-export function filterVisibleSessions(sessions: SessionSummaryResponse[]) {
- const fiveMinutesAgo = Date.now() - 5 * 60 * 1000;
- return sessions.filter((session) => {
- const hasBeenUpdated = session.updated_at !== session.created_at;
-
- if (hasBeenUpdated) return true;
-
- const isRecentlyCreated =
- new Date(session.created_at).getTime() > fiveMinutesAgo;
-
- return isRecentlyCreated;
- });
-}
-
-export function getSessionTitle(session: SessionSummaryResponse) {
- if (session.title) return session.title;
-
- const isNewSession = session.updated_at === session.created_at;
-
- if (isNewSession) {
- const createdDate = new Date(session.created_at);
- if (isToday(createdDate)) {
- return "Today";
- }
- return format(createdDate, "MMM d, yyyy");
- }
-
- return "Untitled Chat";
-}
-
-export function getSessionUpdatedLabel(session: SessionSummaryResponse) {
- if (!session.updated_at) return "";
- return formatDistanceToNow(new Date(session.updated_at), { addSuffix: true });
-}
-
-export function mergeCurrentSessionIntoList(
- accumulatedSessions: SessionSummaryResponse[],
- currentSessionId: string | null,
- currentSessionData: SessionDetailResponse | null | undefined,
- recentlyCreatedSessions?: Map<string, SessionSummaryResponse>,
-) {
- const filteredSessions: SessionSummaryResponse[] = [];
- const addedIds = new Set<string>();
-
- if (accumulatedSessions.length > 0) {
- const visibleSessions = filterVisibleSessions(accumulatedSessions);
-
- if (currentSessionId) {
- const currentInAll = accumulatedSessions.find(
- (s) => s.id === currentSessionId,
- );
- if (currentInAll) {
- const isInVisible = visibleSessions.some(
- (s) => s.id === currentSessionId,
- );
- if (!isInVisible) {
- filteredSessions.push(currentInAll);
- addedIds.add(currentInAll.id);
- }
- }
- }
-
- for (const session of visibleSessions) {
- if (!addedIds.has(session.id)) {
- filteredSessions.push(session);
- addedIds.add(session.id);
- }
- }
- }
-
- if (currentSessionId && currentSessionData) {
- if (!addedIds.has(currentSessionId)) {
- const summarySession = convertSessionDetailToSummary(currentSessionData);
- filteredSessions.unshift(summarySession);
- addedIds.add(currentSessionId);
- }
- }
-
- if (recentlyCreatedSessions) {
- for (const [sessionId, sessionData] of recentlyCreatedSessions) {
- if (!addedIds.has(sessionId)) {
- filteredSessions.unshift(sessionData);
- addedIds.add(sessionId);
- }
- }
- }
-
- return filteredSessions;
-}
-
-export function getCurrentSessionId(searchParams: URLSearchParams) {
- return searchParams.get("sessionId");
-}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotShell/useCopilotShell.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotShell/useCopilotShell.ts
deleted file mode 100644
index 913c4d7ded..0000000000
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotShell/useCopilotShell.ts
+++ /dev/null
@@ -1,124 +0,0 @@
-"use client";
-
-import {
- getGetV2GetSessionQueryKey,
- getGetV2ListSessionsQueryKey,
- useGetV2GetSession,
-} from "@/app/api/__generated__/endpoints/chat/chat";
-import { okData } from "@/app/api/helpers";
-import { useChatStore } from "@/components/contextual/Chat/chat-store";
-import { useBreakpoint } from "@/lib/hooks/useBreakpoint";
-import { useSupabase } from "@/lib/supabase/hooks/useSupabase";
-import { useQueryClient } from "@tanstack/react-query";
-import { usePathname, useSearchParams } from "next/navigation";
-import { useCopilotStore } from "../../copilot-page-store";
-import { useCopilotSessionId } from "../../useCopilotSessionId";
-import { useMobileDrawer } from "./components/MobileDrawer/useMobileDrawer";
-import { getCurrentSessionId } from "./helpers";
-import { useShellSessionList } from "./useShellSessionList";
-
-export function useCopilotShell() {
- const pathname = usePathname();
- const searchParams = useSearchParams();
- const queryClient = useQueryClient();
- const breakpoint = useBreakpoint();
- const { isLoggedIn } = useSupabase();
- const isMobile =
- breakpoint === "base" || breakpoint === "sm" || breakpoint === "md";
-
- const { urlSessionId, setUrlSessionId } = useCopilotSessionId();
-
- const isOnHomepage = pathname === "/copilot";
- const paramSessionId = searchParams.get("sessionId");
-
- const {
- isDrawerOpen,
- handleOpenDrawer,
- handleCloseDrawer,
- handleDrawerOpenChange,
- } = useMobileDrawer();
-
- const paginationEnabled = !isMobile || isDrawerOpen || !!paramSessionId;
-
- const currentSessionId = getCurrentSessionId(searchParams);
-
- const { data: currentSessionData } = useGetV2GetSession(
- currentSessionId || "",
- {
- query: {
- enabled: !!currentSessionId,
- select: okData,
- },
- },
- );
-
- const {
- sessions,
- isLoading,
- isSessionsFetching,
- hasNextPage,
- fetchNextPage,
- resetPagination,
- recentlyCreatedSessionsRef,
- } = useShellSessionList({
- paginationEnabled,
- currentSessionId,
- currentSessionData,
- isOnHomepage,
- paramSessionId,
- });
-
- const stopStream = useChatStore((s) => s.stopStream);
- const isCreatingSession = useCopilotStore((s) => s.isCreatingSession);
-
- function handleSessionClick(sessionId: string) {
- if (sessionId === currentSessionId) return;
-
- // Stop current stream - SSE reconnection allows resuming later
- if (currentSessionId) {
- stopStream(currentSessionId);
- }
-
- if (recentlyCreatedSessionsRef.current.has(sessionId)) {
- queryClient.invalidateQueries({
- queryKey: getGetV2GetSessionQueryKey(sessionId),
- });
- }
- setUrlSessionId(sessionId, { shallow: false });
- if (isMobile) handleCloseDrawer();
- }
-
- function handleNewChatClick() {
- // Stop current stream - SSE reconnection allows resuming later
- if (currentSessionId) {
- stopStream(currentSessionId);
- }
-
- resetPagination();
- queryClient.invalidateQueries({
- queryKey: getGetV2ListSessionsQueryKey(),
- });
- setUrlSessionId(null, { shallow: false });
- if (isMobile) handleCloseDrawer();
- }
-
- return {
- isMobile,
- isDrawerOpen,
- isLoggedIn,
- hasActiveSession:
- Boolean(currentSessionId) && (!isOnHomepage || Boolean(paramSessionId)),
- isLoading: isLoading || isCreatingSession,
- isCreatingSession,
- sessions,
- currentSessionId: urlSessionId,
- handleOpenDrawer,
- handleCloseDrawer,
- handleDrawerOpenChange,
- handleNewChatClick,
- handleSessionClick,
- hasNextPage,
- isFetchingNextPage: isSessionsFetching,
- fetchNextPage,
- };
-}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotShell/useShellSessionList.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotShell/useShellSessionList.ts
deleted file mode 100644
index fb39a11096..0000000000
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotShell/useShellSessionList.ts
+++ /dev/null
@@ -1,113 +0,0 @@
-import { getGetV2ListSessionsQueryKey } from "@/app/api/__generated__/endpoints/chat/chat";
-import type { SessionDetailResponse } from "@/app/api/__generated__/models/sessionDetailResponse";
-import type { SessionSummaryResponse } from "@/app/api/__generated__/models/sessionSummaryResponse";
-import { useChatStore } from "@/components/contextual/Chat/chat-store";
-import { useQueryClient } from "@tanstack/react-query";
-import { useEffect, useMemo, useRef } from "react";
-import { useSessionsPagination } from "./components/SessionsList/useSessionsPagination";
-import {
- convertSessionDetailToSummary,
- filterVisibleSessions,
- mergeCurrentSessionIntoList,
-} from "./helpers";
-
-interface UseShellSessionListArgs {
- paginationEnabled: boolean;
- currentSessionId: string | null;
- currentSessionData: SessionDetailResponse | null | undefined;
- isOnHomepage: boolean;
- paramSessionId: string | null;
-}
-
-export function useShellSessionList({
- paginationEnabled,
- currentSessionId,
- currentSessionData,
- isOnHomepage,
- paramSessionId,
-}: UseShellSessionListArgs) {
- const queryClient = useQueryClient();
- const onStreamComplete = useChatStore((s) => s.onStreamComplete);
-
- const {
- sessions: accumulatedSessions,
- isLoading: isSessionsLoading,
- isFetching: isSessionsFetching,
- hasNextPage,
- fetchNextPage,
- reset: resetPagination,
- } = useSessionsPagination({
- enabled: paginationEnabled,
- });
-
- const recentlyCreatedSessionsRef = useRef<
- Map<string, SessionSummaryResponse>
- >(new Map());
-
- useEffect(() => {
- if (isOnHomepage && !paramSessionId) {
- queryClient.invalidateQueries({
- queryKey: getGetV2ListSessionsQueryKey(),
- });
- }
- }, [isOnHomepage, paramSessionId, queryClient]);
-
- useEffect(() => {
- if (currentSessionId && currentSessionData) {
- const isNewSession =
- currentSessionData.updated_at === currentSessionData.created_at;
- const isNotInAccumulated = !accumulatedSessions.some(
- (s) => s.id === currentSessionId,
- );
- if (isNewSession || isNotInAccumulated) {
- const summary = convertSessionDetailToSummary(currentSessionData);
- recentlyCreatedSessionsRef.current.set(currentSessionId, summary);
- }
- }
- }, [currentSessionId, currentSessionData, accumulatedSessions]);
-
- useEffect(() => {
- for (const sessionId of recentlyCreatedSessionsRef.current.keys()) {
- if (accumulatedSessions.some((s) => s.id === sessionId)) {
- recentlyCreatedSessionsRef.current.delete(sessionId);
- }
- }
- }, [accumulatedSessions]);
-
- useEffect(() => {
- const unsubscribe = onStreamComplete(() => {
- queryClient.invalidateQueries({
- queryKey: getGetV2ListSessionsQueryKey(),
- });
- });
- return unsubscribe;
- }, [onStreamComplete, queryClient]);
-
- const sessions = useMemo(
- () =>
- mergeCurrentSessionIntoList(
- accumulatedSessions,
- currentSessionId,
- currentSessionData,
- recentlyCreatedSessionsRef.current,
- ),
- [accumulatedSessions, currentSessionId, currentSessionData],
- );
-
- const visibleSessions = useMemo(
- () => filterVisibleSessions(sessions),
- [sessions],
- );
-
- const isLoading = isSessionsLoading && accumulatedSessions.length === 0;
-
- return {
- sessions: visibleSessions,
- isLoading,
- isSessionsFetching,
- hasNextPage,
- fetchNextPage,
- resetPagination,
- recentlyCreatedSessionsRef,
- };
-}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/EmptySession/EmptySession.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/EmptySession/EmptySession.tsx
new file mode 100644
index 0000000000..cbbe6c570e
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/EmptySession/EmptySession.tsx
@@ -0,0 +1,111 @@
+"use client";
+
+import { ChatInput } from "@/app/(platform)/copilot/components/ChatInput/ChatInput";
+import { Button } from "@/components/atoms/Button/Button";
+import { Text } from "@/components/atoms/Text/Text";
+import { useSupabase } from "@/lib/supabase/hooks/useSupabase";
+import { SpinnerGapIcon } from "@phosphor-icons/react";
+import { motion } from "framer-motion";
+import { useEffect, useState } from "react";
+import {
+ getGreetingName,
+ getInputPlaceholder,
+ getQuickActions,
+} from "./helpers";
+
+interface Props {
+ inputLayoutId: string;
+ isCreatingSession: boolean;
+ onCreateSession: () => void | Promise<string>;
+ onSend: (message: string) => void | Promise<void>;
+}
+
+export function EmptySession({
+ inputLayoutId,
+ isCreatingSession,
+ onSend,
+}: Props) {
+ const { user } = useSupabase();
+ const greetingName = getGreetingName(user);
+ const quickActions = getQuickActions();
+ const [loadingAction, setLoadingAction] = useState<string | null>(null);
+ const [inputPlaceholder, setInputPlaceholder] = useState(
+ getInputPlaceholder(),
+ );
+
+ useEffect(() => {
+ setInputPlaceholder(getInputPlaceholder(window.innerWidth));
+ }, [window.innerWidth]);
+
+ async function handleQuickActionClick(action: string) {
+ if (isCreatingSession || loadingAction) return;
+
+ setLoadingAction(action);
+ try {
+ await onSend(action);
+ } finally {
+ setLoadingAction(null);
+ }
+ }
+
+ return (
+ <div className="flex h-full flex-1 items-center justify-center overflow-y-auto bg-[#f8f8f9] px-0 py-5 md:px-6 md:py-10">
+ <motion.div
+ className="w-full max-w-3xl text-center"
+ initial={{ opacity: 0 }}
+ animate={{ opacity: 1 }}
+ transition={{ duration: 0.3 }}
+ >
+ <div className="mx-auto max-w-3xl">
+ <Text variant="h3" className="mb-1 !text-[1.375rem] text-zinc-700">
+ Hey, <span className="text-violet-600">{greetingName}</span>
+ </Text>
+ <Text variant="h3" className="mb-8 !font-normal">
+ Tell me about your work — I&apos;ll find what to automate.
+ </Text>
+
+ <div className="mb-6">
+ <motion.div
+ layoutId={inputLayoutId}
+ transition={{ type: "spring", bounce: 0.2, duration: 0.65 }}
+ className="w-full px-2"
+ >
+ <ChatInput
+ inputId="chat-input-empty"
+ onSend={onSend}
+ disabled={isCreatingSession}
+ placeholder={inputPlaceholder}
+ className="w-full"
+ />
+ </motion.div>
+ </div>
+ </div>
+
+ <div className="flex flex-wrap items-center justify-center gap-3 overflow-x-auto [-ms-overflow-style:none] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
+ {quickActions.map((action) => (
+ <Button
+ key={action}
+ type="button"
+ variant="outline"
+ size="small"
+ onClick={() => void handleQuickActionClick(action)}
+ disabled={isCreatingSession || loadingAction !== null}
+ aria-busy={loadingAction === action}
+ leftIcon={
+ loadingAction === action ? (
+ <SpinnerGapIcon
+ className="h-4 w-4 animate-spin"
+ weight="bold"
+ />
+ ) : null
+ }
+ className="h-auto shrink-0 border-zinc-300 px-3 py-2 text-[.9rem] text-zinc-600"
+ >
+ {action}
+ </Button>
+ ))}
+ </div>
+ </motion.div>
+ </div>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/EmptySession/helpers.ts
similarity index 72%
rename from autogpt_platform/frontend/src/app/(platform)/copilot/helpers.ts
rename to autogpt_platform/frontend/src/app/(platform)/copilot/components/EmptySession/helpers.ts
index c6e479f896..f6f8980fd4 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/helpers.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/EmptySession/helpers.ts
@@ -1,6 +1,26 @@
-import type { User } from "@supabase/supabase-js";
+import { User } from "@supabase/supabase-js";
-export function getGreetingName(user?: User | null): string {
+export function getInputPlaceholder(width?: number) {
+ if (!width) return "What's your role and what eats up most of your day?";
+
+ if (width < 500) {
+ return "I'm a chef and I hate...";
+ }
+ if (width <= 1080) {
+ return "What's your role and what eats up most of your day?";
+ }
+ return "What's your role and what eats up most of your day? e.g. 'I'm a recruiter and I hate...'";
+}
+
+export function getQuickActions() {
+ return [
+ "I don't know where to start, just ask me stuff",
+ "I do the same thing every week and it's killing me",
+ "Help me find where I'm wasting my time",
+ ];
+}
+
+export function getGreetingName(user?: User | null) {
if (!user) return "there";
const metadata = user.user_metadata as Record<string, unknown> | undefined;
const fullName = metadata?.full_name;
@@ -16,30 +36,3 @@ export function getGreetingName(user?: User | null): string {
}
return "there";
}
-
-export function buildCopilotChatUrl(prompt: string): string {
- const trimmed = prompt.trim();
- if (!trimmed) return "/copilot/chat";
- const encoded = encodeURIComponent(trimmed);
- return `/copilot/chat?prompt=${encoded}`;
-}
-
-export function getQuickActions(): string[] {
- return [
- "I don't know where to start, just ask me stuff",
- "I do the same thing every week and it's killing me",
- "Help me find where I'm wasting my time",
- ];
-}
-
-export function getInputPlaceholder(width?: number) {
- if (!width) return "What's your role and what eats up most of your day?";
-
- if (width < 500) {
- return "I'm a chef and I hate...";
- }
- if (width <= 1080) {
- return "What's your role and what eats up most of your day?";
- }
- return "What's your role and what eats up most of your day? e.g. 'I'm a recruiter and I hate...'";
-}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/MobileDrawer/MobileDrawer.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/MobileDrawer/MobileDrawer.tsx
new file mode 100644
index 0000000000..80ccfc9c03
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/MobileDrawer/MobileDrawer.tsx
@@ -0,0 +1,140 @@
+import type { SessionSummaryResponse } from "@/app/api/__generated__/models/sessionSummaryResponse";
+import { Button } from "@/components/atoms/Button/Button";
+import { Text } from "@/components/atoms/Text/Text";
+import { scrollbarStyles } from "@/components/styles/scrollbars";
+import { cn } from "@/lib/utils";
+import { PlusIcon, SpinnerGapIcon, X } from "@phosphor-icons/react";
+import { Drawer } from "vaul";
+
+interface Props {
+ isOpen: boolean;
+ sessions: SessionSummaryResponse[];
+ currentSessionId: string | null;
+ isLoading: boolean;
+ onSelectSession: (sessionId: string) => void;
+ onNewChat: () => void;
+ onClose: () => void;
+ onOpenChange: (open: boolean) => void;
+}
+
+function formatDate(dateString: string) {
+ const date = new Date(dateString);
+ const now = new Date();
+ const diffMs = now.getTime() - date.getTime();
+ const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));
+
+ if (diffDays === 0) return "Today";
+ if (diffDays === 1) return "Yesterday";
+ if (diffDays < 7) return `${diffDays} days ago`;
+
+ const day = date.getDate();
+ const ordinal =
+ day % 10 === 1 && day !== 11
+ ? "st"
+ : day % 10 === 2 && day !== 12
+ ? "nd"
+ : day % 10 === 3 && day !== 13
+ ? "rd"
+ : "th";
+ const month = date.toLocaleDateString("en-US", { month: "short" });
+ const year = date.getFullYear();
+
+ return `${day}${ordinal} ${month} ${year}`;
+}
+
+export function MobileDrawer({
+ isOpen,
+ sessions,
+ currentSessionId,
+ isLoading,
+ onSelectSession,
+ onNewChat,
+ onClose,
+ onOpenChange,
+}: Props) {
+ return (
+ <Drawer.Root open={isOpen} onOpenChange={onOpenChange} direction="left">
+ <Drawer.Portal>
+ <Drawer.Overlay className="fixed inset-0 z-[60] bg-black/10 backdrop-blur-sm" />
+ <Drawer.Content className="fixed left-0 top-0 z-[70] flex h-full w-80 flex-col border-r border-zinc-200 bg-zinc-50">
+ <div className="shrink-0 border-b border-zinc-200 px-4 py-2">
+ <div className="flex items-center justify-between">
+ <Drawer.Title className="text-lg font-semibold text-zinc-800">
+ Your chats
+ </Drawer.Title>
+ <Button
+ variant="icon"
+ size="icon"
+ aria-label="Close sessions"
+ onClick={onClose}
+ >
+ <X width="1rem" height="1rem" />
+ </Button>
+ </div>
+ </div>
+ <div
+ className={cn(
+ "flex min-h-0 flex-1 flex-col gap-1 overflow-y-auto px-3 py-3",
+ scrollbarStyles,
+ )}
+ >
+ {isLoading ? (
+ <div className="flex items-center justify-center py-4">
+ <SpinnerGapIcon className="h-5 w-5 animate-spin text-neutral-400" />
+ </div>
+ ) : sessions.length === 0 ? (
+ <p className="py-4 text-center text-sm text-neutral-500">
+ No conversations yet
+ </p>
+ ) : (
+ sessions.map((session) => (
+ <button
+ key={session.id}
+ onClick={() => onSelectSession(session.id)}
+ className={cn(
+ "w-full rounded-lg px-3 py-2.5 text-left transition-colors",
+ session.id === currentSessionId
+ ? "bg-zinc-100"
+ : "hover:bg-zinc-50",
+ )}
+ >
+ <div className="flex min-w-0 max-w-full flex-col overflow-hidden">
+ <div className="min-w-0 max-w-full">
+ <Text
+ variant="body"
+ className={cn(
+ "truncate font-normal",
+ session.id === currentSessionId
+ ? "text-zinc-600"
+ : "text-zinc-800",
+ )}
+ >
+ {session.title || "Untitled chat"}
+ </Text>
+ </div>
+ <Text variant="small" className="text-neutral-400">
+ {formatDate(session.updated_at)}
+ </Text>
+ </div>
+ </button>
+ ))
+ )}
+ </div>
+ {currentSessionId && (
+ <div className="shrink-0 bg-white p-3 shadow-[0_-4px_6px_-1px_rgba(0,0,0,0.05)]">
+ <Button
+ variant="primary"
+ size="small"
+ onClick={onNewChat}
+ className="w-full"
+ leftIcon={<PlusIcon width="1rem" height="1rem" />}
+ >
+ New Chat
+ </Button>
+ </div>
+ )}
+ </Drawer.Content>
+ </Drawer.Portal>
+ </Drawer.Root>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotShell/components/MobileHeader/MobileHeader.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/MobileHeader/MobileHeader.tsx
similarity index 100%
rename from autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotShell/components/MobileHeader/MobileHeader.tsx
rename to autogpt_platform/frontend/src/app/(platform)/copilot/components/MobileHeader/MobileHeader.tsx
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/MorphingTextAnimation/MorphingTextAnimation.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/MorphingTextAnimation/MorphingTextAnimation.tsx
new file mode 100644
index 0000000000..aac615bb2b
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/MorphingTextAnimation/MorphingTextAnimation.tsx
@@ -0,0 +1,54 @@
+import { cn } from "@/lib/utils";
+import { AnimatePresence, motion } from "framer-motion";
+
+interface Props {
+ text: string;
+ className?: string;
+}
+
+export function MorphingTextAnimation({ text, className }: Props) {
+ const letters = text.split("");
+
+ return (
+ <div className={cn(className)}>
+ <AnimatePresence mode="popLayout" initial={false}>
+ <motion.div key={text} className="whitespace-nowrap">
+ <motion.span className="inline-flex overflow-hidden">
+ {letters.map((char, index) => (
+ <motion.span
+ key={`${text}-${index}`}
+ initial={{
+ opacity: 0,
+ y: 8,
+ rotateX: "80deg",
+ filter: "blur(6px)",
+ }}
+ animate={{
+ opacity: 1,
+ y: 0,
+ rotateX: "0deg",
+ filter: "blur(0px)",
+ }}
+ exit={{
+ opacity: 0,
+ y: -8,
+ rotateX: "-80deg",
+ filter: "blur(6px)",
+ }}
+ style={{ willChange: "transform" }}
+ transition={{
+ delay: 0.015 * index,
+ type: "spring",
+ bounce: 0.5,
+ }}
+ className="inline-block"
+ >
+ {char === " " ? "\u00A0" : char}
+ </motion.span>
+ ))}
+ </motion.span>
+ </motion.div>
+ </AnimatePresence>
+ </div>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/OrbitLoader/OrbitLoader.module.css b/autogpt_platform/frontend/src/app/(platform)/copilot/components/OrbitLoader/OrbitLoader.module.css
new file mode 100644
index 0000000000..cd04402348
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/OrbitLoader/OrbitLoader.module.css
@@ -0,0 +1,69 @@
+.loader {
+ position: relative;
+ animation: rotate 1s infinite;
+}
+
+.loader::before,
+.loader::after {
+ border-radius: 50%;
+ content: "";
+ display: block;
+ /* 40% of container size */
+ height: 40%;
+ width: 40%;
+}
+
+.loader::before {
+ animation: ball1 1s infinite;
+ background-color: #a1a1aa; /* zinc-400 */
+ box-shadow: calc(var(--spacing)) 0 0 #18181b; /* zinc-900 */
+ margin-bottom: calc(var(--gap));
+}
+
+.loader::after {
+ animation: ball2 1s infinite;
+ background-color: #18181b; /* zinc-900 */
+ box-shadow: calc(var(--spacing)) 0 0 #a1a1aa; /* zinc-400 */
+}
+
+@keyframes rotate {
+ 0% {
+ transform: rotate(0deg) scale(0.8);
+ }
+ 50% {
+ transform: rotate(360deg) scale(1.2);
+ }
+ 100% {
+ transform: rotate(720deg) scale(0.8);
+ }
+}
+
+@keyframes ball1 {
+ 0% {
+ box-shadow: calc(var(--spacing)) 0 0 #18181b;
+ }
+ 50% {
+ box-shadow: 0 0 0 #18181b;
+ margin-bottom: 0;
+ transform: translate(calc(var(--spacing) / 2), calc(var(--spacing) / 2));
+ }
+ 100% {
+ box-shadow: calc(var(--spacing)) 0 0 #18181b;
+ margin-bottom: calc(var(--gap));
+ }
+}
+
+@keyframes ball2 {
+ 0% {
+ box-shadow: calc(var(--spacing)) 0 0 #a1a1aa;
+ }
+ 50% {
+ box-shadow: 0 0 0 #a1a1aa;
+ margin-top: calc(var(--ball-size) * -1);
+ transform: translate(calc(var(--spacing) / 2), calc(var(--spacing) / 2));
+ }
+ 100% {
+ box-shadow: calc(var(--spacing)) 0 0 #a1a1aa;
+ margin-top: 0;
+ }
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/OrbitLoader/OrbitLoader.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/OrbitLoader/OrbitLoader.tsx
new file mode 100644
index 0000000000..cc47c16132
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/OrbitLoader/OrbitLoader.tsx
@@ -0,0 +1,28 @@
+import { cn } from "@/lib/utils";
+import styles from "./OrbitLoader.module.css";
+
+interface Props {
+ size?: number;
+ className?: string;
+}
+
+export function OrbitLoader({ size = 24, className }: Props) {
+ const ballSize = Math.round(size * 0.4);
+ const spacing = Math.round(size * 0.6);
+ const gap = Math.round(size * 0.2);
+
+ return (
+ <div
+ className={cn(styles.loader, className)}
+ style={
+ {
+ width: size,
+ height: size,
+ "--ball-size": `${ballSize}px`,
+ "--spacing": `${spacing}px`,
+ "--gap": `${gap}px`,
+ } as React.CSSProperties
+ }
+ />
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ProgressBar/ProgressBar.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ProgressBar/ProgressBar.tsx
new file mode 100644
index 0000000000..d251b08640
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ProgressBar/ProgressBar.tsx
@@ -0,0 +1,26 @@
+import { cn } from "@/lib/utils";
+
+interface Props {
+ value: number;
+ label?: string;
+ className?: string;
+}
+
+export function ProgressBar({ value, label, className }: Props) {
+ const clamped = Math.min(100, Math.max(0, value));
+
+ return (
+ <div className={cn("flex flex-col gap-1.5", className)}>
+ <div className="flex items-center justify-between text-xs text-neutral-500">
+ <span>{label ?? "Working on it..."}</span>
+ <span>{Math.round(clamped)}%</span>
+ </div>
+ <div className="h-2 w-full overflow-hidden rounded-full bg-neutral-200">
+ <div
+ className="h-full rounded-full bg-neutral-900 transition-[width] duration-300 ease-out"
+ style={{ width: `${clamped}%` }}
+ />
+ </div>
+ </div>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/PulseLoader/PulseLoader.module.css b/autogpt_platform/frontend/src/app/(platform)/copilot/components/PulseLoader/PulseLoader.module.css
new file mode 100644
index 0000000000..77ab5ae931
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/PulseLoader/PulseLoader.module.css
@@ -0,0 +1,34 @@
+.loader {
+ position: relative;
+ display: inline-block;
+ flex-shrink: 0;
+}
+
+.loader::before,
+.loader::after {
+ content: "";
+ box-sizing: border-box;
+ width: 100%;
+ height: 100%;
+ border-radius: 50%;
+ background: currentColor;
+ position: absolute;
+ left: 0;
+ top: 0;
+ animation: ripple 2s linear infinite;
+}
+
+.loader::after {
+ animation-delay: 1s;
+}
+
+@keyframes ripple {
+ 0% {
+ transform: scale(0);
+ opacity: 1;
+ }
+ 100% {
+ transform: scale(1);
+ opacity: 0;
+ }
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/PulseLoader/PulseLoader.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/PulseLoader/PulseLoader.tsx
new file mode 100644
index 0000000000..599874daaa
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/PulseLoader/PulseLoader.tsx
@@ -0,0 +1,16 @@
+import { cn } from "@/lib/utils";
+import styles from "./PulseLoader.module.css";
+
+interface Props {
+ size?: number;
+ className?: string;
+}
+
+export function PulseLoader({ size = 24, className }: Props) {
+ return (
+ <div
+ className={cn(styles.loader, className)}
+ style={{ width: size, height: size }}
+ />
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/SpinnerLoader/SpinnerLoader.module.css b/autogpt_platform/frontend/src/app/(platform)/copilot/components/SpinnerLoader/SpinnerLoader.module.css
new file mode 100644
index 0000000000..ee456bfac4
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/SpinnerLoader/SpinnerLoader.module.css
@@ -0,0 +1,57 @@
+.loader {
+ position: relative;
+ display: inline-block;
+ flex-shrink: 0;
+ transform: rotateZ(45deg);
+ perspective: 1000px;
+ border-radius: 50%;
+ color: currentColor;
+}
+
+.loader::before,
+.loader::after {
+ content: "";
+ display: block;
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: inherit;
+ height: inherit;
+ border-radius: 50%;
+ transform: rotateX(70deg);
+ animation: spin 1s linear infinite;
+}
+
+.loader::after {
+ color: var(--spinner-accent, #a855f7);
+ transform: rotateY(70deg);
+ animation-delay: 0.4s;
+}
+
+@keyframes spin {
+ 0%,
+ 100% {
+ box-shadow: 0.2em 0 0 0 currentColor;
+ }
+ 12% {
+ box-shadow: 0.2em 0.2em 0 0 currentColor;
+ }
+ 25% {
+ box-shadow: 0 0.2em 0 0 currentColor;
+ }
+ 37% {
+ box-shadow: -0.2em 0.2em 0 0 currentColor;
+ }
+ 50% {
+ box-shadow: -0.2em 0 0 0 currentColor;
+ }
+ 62% {
+ box-shadow: -0.2em -0.2em 0 0 currentColor;
+ }
+ 75% {
+ box-shadow: 0 -0.2em 0 0 currentColor;
+ }
+ 87% {
+ box-shadow: 0.2em -0.2em 0 0 currentColor;
+ }
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/SpinnerLoader/SpinnerLoader.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/SpinnerLoader/SpinnerLoader.tsx
new file mode 100644
index 0000000000..d921b5f778
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/SpinnerLoader/SpinnerLoader.tsx
@@ -0,0 +1,16 @@
+import { cn } from "@/lib/utils";
+import styles from "./SpinnerLoader.module.css";
+
+interface Props {
+ size?: number;
+ className?: string;
+}
+
+export function SpinnerLoader({ size = 24, className }: Props) {
+ return (
+ <div
+ className={cn(styles.loader, className)}
+ style={{ width: size, height: size }}
+ />
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolAccordion/AccordionContent.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolAccordion/AccordionContent.tsx
new file mode 100644
index 0000000000..987941eee1
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolAccordion/AccordionContent.tsx
@@ -0,0 +1,235 @@
+import { Link } from "@/components/atoms/Link/Link";
+import { Text } from "@/components/atoms/Text/Text";
+import { cn } from "@/lib/utils";
+
+/* ------------------------------------------------------------------ */
+/* Layout */
+/* ------------------------------------------------------------------ */
+
+export function ContentGrid({
+ children,
+ className,
+}: {
+ children: React.ReactNode;
+ className?: string;
+}) {
+ return <div className={cn("grid gap-2", className)}>{children}</div>;
+}
+
+/* ------------------------------------------------------------------ */
+/* Card */
+/* ------------------------------------------------------------------ */
+
+export function ContentCard({
+ children,
+ className,
+}: {
+ children: React.ReactNode;
+ className?: string;
+}) {
+ return (
+ <div
+ className={cn(
+ "rounded-lg bg-gradient-to-r from-purple-500/30 to-blue-500/30 p-[1px]",
+ className,
+ )}
+ >
+ <div className="rounded-lg bg-neutral-100 p-3">{children}</div>
+ </div>
+ );
+}
+
+/** Flex row with a left content area (`children`) and an optional right‑side `action`. */
+export function ContentCardHeader({
+ children,
+ action,
+ className,
+}: {
+ children: React.ReactNode;
+ action?: React.ReactNode;
+ className?: string;
+}) {
+ return (
+ <div className={cn("flex items-start justify-between gap-2", className)}>
+ <div className="min-w-0">{children}</div>
+ {action}
+ </div>
+ );
+}
+
+export function ContentCardTitle({
+ children,
+ className,
+}: {
+ children: React.ReactNode;
+ className?: string;
+}) {
+ return (
+ <Text
+ variant="body-medium"
+ className={cn("truncate text-zinc-800", className)}
+ >
+ {children}
+ </Text>
+ );
+}
+
+export function ContentCardSubtitle({
+ children,
+ className,
+}: {
+ children: React.ReactNode;
+ className?: string;
+}) {
+ return (
+ <Text
+ variant="small"
+ className={cn("mt-0.5 truncate font-mono text-zinc-800", className)}
+ >
+ {children}
+ </Text>
+ );
+}
+
+export function ContentCardDescription({
+ children,
+ className,
+}: {
+ children: React.ReactNode;
+ className?: string;
+}) {
+ return (
+ <Text variant="body" className={cn("mt-2 text-zinc-800", className)}>
+ {children}
+ </Text>
+ );
+}
+
+/* ------------------------------------------------------------------ */
+/* Text */
+/* ------------------------------------------------------------------ */
+
+export function ContentMessage({
+ children,
+ className,
+}: {
+ children: React.ReactNode;
+ className?: string;
+}) {
+ return (
+ <Text variant="body" className={cn("text-zinc-800", className)}>
+ {children}
+ </Text>
+ );
+}
+
+export function ContentHint({
+ children,
+ className,
+}: {
+ children: React.ReactNode;
+ className?: string;
+}) {
+ return (
+ <Text variant="small" className={cn("text-neutral-500", className)}>
+ {children}
+ </Text>
+ );
+}
+
+/* ------------------------------------------------------------------ */
+/* Code / data */
+/* ------------------------------------------------------------------ */
+
+export function ContentCodeBlock({
+ children,
+ className,
+}: {
+ children: React.ReactNode;
+ className?: string;
+}) {
+ return (
+ <pre
+ className={cn(
+ "whitespace-pre-wrap rounded-lg border bg-black p-3 text-xs text-neutral-200",
+ className,
+ )}
+ >
+ {children}
+ </pre>
+ );
+}
+
+/* ------------------------------------------------------------------ */
+/* Inline elements */
+/* ------------------------------------------------------------------ */
+
+export function ContentBadge({
+ children,
+ className,
+}: {
+ children: React.ReactNode;
+ className?: string;
+}) {
+ return (
+ <Text
+ variant="small"
+ as="span"
+ className={cn(
+ "shrink-0 rounded-full border bg-muted px-2 py-0.5 text-[11px] text-zinc-800",
+ className,
+ )}
+ >
+ {children}
+ </Text>
+ );
+}
+
+export function ContentLink({
+ href,
+ children,
+ className,
+ ...rest
+}: Omit<React.ComponentProps<typeof Link>, "className"> & {
+ className?: string;
+}) {
+ return (
+ <Link
+ variant="primary"
+ isExternal
+ href={href}
+ className={cn("shrink-0 text-xs text-purple-500", className)}
+ {...rest}
+ >
+ {children}
+ </Link>
+ );
+}
+
+/* ------------------------------------------------------------------ */
+/* Lists */
+/* ------------------------------------------------------------------ */
+
+export function ContentSuggestionsList({
+ items,
+ max = 5,
+ className,
+}: {
+ items: string[];
+ max?: number;
+ className?: string;
+}) {
+ if (items.length === 0) return null;
+ return (
+ <ul
+ className={cn(
+ "mt-2 list-disc space-y-1 pl-5 font-sans text-[0.75rem] leading-[1.125rem] text-zinc-800",
+ className,
+ )}
+ >
+ {items.slice(0, max).map((s) => (
+ <li key={s}>{s}</li>
+ ))}
+ </ul>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolAccordion/ToolAccordion.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolAccordion/ToolAccordion.tsx
new file mode 100644
index 0000000000..e53df15e6c
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolAccordion/ToolAccordion.tsx
@@ -0,0 +1,102 @@
+"use client";
+
+import { cn } from "@/lib/utils";
+import { CaretDownIcon } from "@phosphor-icons/react";
+import { AnimatePresence, motion, useReducedMotion } from "framer-motion";
+import { useId } from "react";
+import { useToolAccordion } from "./useToolAccordion";
+
+interface Props {
+ icon: React.ReactNode;
+ title: React.ReactNode;
+ titleClassName?: string;
+ description?: React.ReactNode;
+ children: React.ReactNode;
+ className?: string;
+ defaultExpanded?: boolean;
+ expanded?: boolean;
+ onExpandedChange?: (expanded: boolean) => void;
+}
+
+export function ToolAccordion({
+ icon,
+ title,
+ titleClassName,
+ description,
+ children,
+ className,
+ defaultExpanded,
+ expanded,
+ onExpandedChange,
+}: Props) {
+ const shouldReduceMotion = useReducedMotion();
+ const contentId = useId();
+ const { isExpanded, toggle } = useToolAccordion({
+ expanded,
+ defaultExpanded,
+ onExpandedChange,
+ });
+
+ return (
+ <div
+ className={cn(
+ "mt-2 w-full rounded-lg border border-slate-200 bg-slate-100 px-3 py-2",
+ className,
+ )}
+ >
+ <button
+ type="button"
+ aria-expanded={isExpanded}
+ aria-controls={contentId}
+ onClick={toggle}
+ className="flex w-full items-center justify-between gap-3 py-1 text-left"
+ >
+ <div className="flex min-w-0 items-center gap-3">
+ <span className="flex shrink-0 items-center text-gray-800">
+ {icon}
+ </span>
+ <div className="min-w-0">
+ <p
+ className={cn(
+ "truncate text-sm font-medium text-gray-800",
+ titleClassName,
+ )}
+ >
+ {title}
+ </p>
+ {description && (
+ <p className="truncate text-xs text-slate-800">{description}</p>
+ )}
+ </div>
+ </div>
+ <CaretDownIcon
+ className={cn(
+ "h-4 w-4 shrink-0 text-slate-500 transition-transform",
+ isExpanded && "rotate-180",
+ )}
+ weight="bold"
+ />
+ </button>
+
+ <AnimatePresence initial={false}>
+ {isExpanded && (
+ <motion.div
+ id={contentId}
+ initial={{ height: 0, opacity: 0, filter: "blur(10px)" }}
+ animate={{ height: "auto", opacity: 1, filter: "blur(0px)" }}
+ exit={{ height: 0, opacity: 0, filter: "blur(10px)" }}
+ transition={
+ shouldReduceMotion
+ ? { duration: 0 }
+ : { type: "spring", bounce: 0.35, duration: 0.55 }
+ }
+ className="overflow-hidden"
+ style={{ willChange: "height, opacity, filter" }}
+ >
+ <div className="pb-2 pt-3">{children}</div>
+ </motion.div>
+ )}
+ </AnimatePresence>
+ </div>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolAccordion/useToolAccordion.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolAccordion/useToolAccordion.ts
new file mode 100644
index 0000000000..bc2a177e8d
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolAccordion/useToolAccordion.ts
@@ -0,0 +1,32 @@
+import { useState } from "react";
+
+interface UseToolAccordionOptions {
+ expanded?: boolean;
+ defaultExpanded?: boolean;
+ onExpandedChange?: (expanded: boolean) => void;
+}
+
+interface UseToolAccordionResult {
+ isExpanded: boolean;
+ toggle: () => void;
+}
+
+export function useToolAccordion({
+ expanded,
+ defaultExpanded = false,
+ onExpandedChange,
+}: UseToolAccordionOptions): UseToolAccordionResult {
+ const [uncontrolledExpanded, setUncontrolledExpanded] =
+ useState(defaultExpanded);
+
+ const isControlled = typeof expanded === "boolean";
+ const isExpanded = isControlled ? expanded : uncontrolledExpanded;
+
+ function toggle() {
+ const next = !isExpanded;
+ if (!isControlled) setUncontrolledExpanded(next);
+ onExpandedChange?.(next);
+ }
+
+ return { isExpanded, toggle };
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/copilot-page-store.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/copilot-page-store.ts
deleted file mode 100644
index 9fc97a14e3..0000000000
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/copilot-page-store.ts
+++ /dev/null
@@ -1,56 +0,0 @@
-"use client";
-
-import { create } from "zustand";
-
-interface CopilotStoreState {
- isStreaming: boolean;
- isSwitchingSession: boolean;
- isCreatingSession: boolean;
- isInterruptModalOpen: boolean;
- pendingAction: (() => void) | null;
-}
-
-interface CopilotStoreActions {
- setIsStreaming: (isStreaming: boolean) => void;
- setIsSwitchingSession: (isSwitchingSession: boolean) => void;
- setIsCreatingSession: (isCreating: boolean) => void;
- openInterruptModal: (onConfirm: () => void) => void;
- confirmInterrupt: () => void;
- cancelInterrupt: () => void;
-}
-
-type CopilotStore = CopilotStoreState & CopilotStoreActions;
-
-export const useCopilotStore = create<CopilotStore>((set, get) => ({
- isStreaming: false,
- isSwitchingSession: false,
- isCreatingSession: false,
- isInterruptModalOpen: false,
- pendingAction: null,
-
- setIsStreaming(isStreaming) {
- set({ isStreaming });
- },
-
- setIsSwitchingSession(isSwitchingSession) {
- set({ isSwitchingSession });
- },
-
- setIsCreatingSession(isCreatingSession) {
- set({ isCreatingSession });
- },
-
- openInterruptModal(onConfirm) {
- set({ isInterruptModalOpen: true, pendingAction: onConfirm });
- },
-
- confirmInterrupt() {
- const { pendingAction } = get();
- set({ isInterruptModalOpen: false, pendingAction: null });
- if (pendingAction) pendingAction();
- },
-
- cancelInterrupt() {
- set({ isInterruptModalOpen: false, pendingAction: null });
- },
-}));
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/convertChatSessionToUiMessages.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/convertChatSessionToUiMessages.ts
new file mode 100644
index 0000000000..a3f2bc28bf
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/convertChatSessionToUiMessages.ts
@@ -0,0 +1,128 @@
+import type { UIMessage, UIDataTypes, UITools } from "ai";
+
+interface SessionChatMessage {
+ role: string;
+ content: string | null;
+ tool_call_id: string | null;
+ tool_calls: unknown[] | null;
+}
+
+function coerceSessionChatMessages(
+ rawMessages: unknown[],
+): SessionChatMessage[] {
+ return rawMessages
+ .map((m) => {
+ if (!m || typeof m !== "object") return null;
+ const msg = m as Record<string, unknown>;
+
+ const role = typeof msg.role === "string" ? msg.role : null;
+ if (!role) return null;
+
+ return {
+ role,
+ content:
+ typeof msg.content === "string"
+ ? msg.content
+ : msg.content == null
+ ? null
+ : String(msg.content),
+ tool_call_id:
+ typeof msg.tool_call_id === "string"
+ ? msg.tool_call_id
+ : msg.tool_call_id == null
+ ? null
+ : String(msg.tool_call_id),
+ tool_calls: Array.isArray(msg.tool_calls) ? msg.tool_calls : null,
+ };
+ })
+ .filter((m): m is SessionChatMessage => m !== null);
+}
+
+function safeJsonParse(value: string): unknown {
+ try {
+ return JSON.parse(value) as unknown;
+ } catch {
+ return value;
+ }
+}
+
+function toToolInput(rawArguments: unknown): unknown {
+ if (typeof rawArguments === "string") {
+ const trimmed = rawArguments.trim();
+ return trimmed ? safeJsonParse(trimmed) : {};
+ }
+ if (rawArguments && typeof rawArguments === "object") return rawArguments;
+ return {};
+}
+
+export function convertChatSessionMessagesToUiMessages(
+ sessionId: string,
+ rawMessages: unknown[],
+): UIMessage<unknown, UIDataTypes, UITools>[] {
+ const messages = coerceSessionChatMessages(rawMessages);
+ const toolOutputsByCallId = new Map<string, unknown>();
+
+ for (const msg of messages) {
+ if (msg.role !== "tool") continue;
+ if (!msg.tool_call_id) continue;
+ if (msg.content == null) continue;
+ toolOutputsByCallId.set(msg.tool_call_id, msg.content);
+ }
+
+ const uiMessages: UIMessage<unknown, UIDataTypes, UITools>[] = [];
+
+ messages.forEach((msg, index) => {
+ if (msg.role === "tool") return;
+ if (msg.role !== "user" && msg.role !== "assistant") return;
+
+ const parts: UIMessage<unknown, UIDataTypes, UITools>["parts"] = [];
+
+ if (typeof msg.content === "string" && msg.content.trim()) {
+ parts.push({ type: "text", text: msg.content, state: "done" });
+ }
+
+ if (msg.role === "assistant" && Array.isArray(msg.tool_calls)) {
+ for (const rawToolCall of msg.tool_calls) {
+ if (!rawToolCall || typeof rawToolCall !== "object") continue;
+ const toolCall = rawToolCall as {
+ id?: unknown;
+ function?: { name?: unknown; arguments?: unknown };
+ };
+
+ const toolCallId = String(toolCall.id ?? "").trim();
+ const toolName = String(toolCall.function?.name ?? "").trim();
+ if (!toolCallId || !toolName) continue;
+
+ const input = toToolInput(toolCall.function?.arguments);
+ const output = toolOutputsByCallId.get(toolCallId);
+
+ if (output !== undefined) {
+ parts.push({
+ type: `tool-${toolName}`,
+ toolCallId,
+ state: "output-available",
+ input,
+ output: typeof output === "string" ? safeJsonParse(output) : output,
+ });
+ } else {
+ parts.push({
+ type: `tool-${toolName}`,
+ toolCallId,
+ state: "input-available",
+ input,
+ });
+ }
+ }
+ }
+
+ if (parts.length === 0) return;
+
+ uiMessages.push({
+ id: `${sessionId}-${index}`,
+ role: msg.role,
+ parts,
+ });
+ });
+
+ return uiMessages;
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotSessionId.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/hooks/Untitled
similarity index 99%
rename from autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotSessionId.ts
rename to autogpt_platform/frontend/src/app/(platform)/copilot/hooks/Untitled
index 87f9b7d3ae..13769eb726 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotSessionId.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/hooks/Untitled
@@ -7,4 +7,4 @@ export function useCopilotSessionId() {
);
return { urlSessionId, setUrlSessionId };
-}
+}
\ No newline at end of file
diff --git a/autogpt_platform/frontend/src/components/contextual/Chat/components/ToolCallMessage/useAsymptoticProgress.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/hooks/useAsymptoticProgress.ts
similarity index 83%
rename from autogpt_platform/frontend/src/components/contextual/Chat/components/ToolCallMessage/useAsymptoticProgress.ts
rename to autogpt_platform/frontend/src/app/(platform)/copilot/hooks/useAsymptoticProgress.ts
index cf1b89e7c4..408ec74175 100644
--- a/autogpt_platform/frontend/src/components/contextual/Chat/components/ToolCallMessage/useAsymptoticProgress.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/hooks/useAsymptoticProgress.ts
@@ -5,17 +5,16 @@ import { useEffect, useRef, useState } from "react";
* asymptotically approaching but never reaching the max value.
*
* Uses a half-life formula: progress = max * (1 - 0.5^(time/halfLife))
- * This creates the "game loading bar" effect where:
+ * This creates a "loading bar" effect where:
* - 50% is reached at halfLifeSeconds
* - 75% is reached at 2 * halfLifeSeconds
* - 87.5% is reached at 3 * halfLifeSeconds
- * - and so on...
*
* @param isActive - Whether the progress should be animating
* @param halfLifeSeconds - Time in seconds to reach 50% progress (default: 30)
* @param maxProgress - Maximum progress value to approach (default: 100)
* @param intervalMs - Update interval in milliseconds (default: 100)
- * @returns Current progress value (0-maxProgress)
+ * @returns Current progress value (0–maxProgress)
*/
export function useAsymptoticProgress(
isActive: boolean,
@@ -35,8 +34,6 @@ export function useAsymptoticProgress(
const interval = setInterval(() => {
elapsedTimeRef.current += intervalMs / 1000;
- // Half-life approach: progress = max * (1 - 0.5^(time/halfLife))
- // At t=halfLife: 50%, at t=2*halfLife: 75%, at t=3*halfLife: 87.5%, etc.
const newProgress =
maxProgress *
(1 - Math.pow(0.5, elapsedTimeRef.current / halfLifeSeconds));
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/layout.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/layout.tsx
deleted file mode 100644
index 876e5accfb..0000000000
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/layout.tsx
+++ /dev/null
@@ -1,13 +0,0 @@
-"use client";
-import { FeatureFlagPage } from "@/services/feature-flags/FeatureFlagPage";
-import { Flag } from "@/services/feature-flags/use-get-flag";
-import { type ReactNode } from "react";
-import { CopilotShell } from "./components/CopilotShell/CopilotShell";
-
-export default function CopilotLayout({ children }: { children: ReactNode }) {
- return (
- <FeatureFlagPage flag={Flag.CHAT} whenDisabled="/library">
- <CopilotShell>{children}</CopilotShell>
- </FeatureFlagPage>
- );
-}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/page.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/page.tsx
index 542173a99c..3e4a81dd51 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/page.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/page.tsx
@@ -1,149 +1,13 @@
"use client";
-import { Button } from "@/components/atoms/Button/Button";
-import { Skeleton } from "@/components/atoms/Skeleton/Skeleton";
-import { Text } from "@/components/atoms/Text/Text";
-import { Chat } from "@/components/contextual/Chat/Chat";
-import { ChatInput } from "@/components/contextual/Chat/components/ChatInput/ChatInput";
-import { Dialog } from "@/components/molecules/Dialog/Dialog";
-import { useEffect, useState } from "react";
-import { useCopilotStore } from "./copilot-page-store";
-import { getInputPlaceholder } from "./helpers";
-import { useCopilotPage } from "./useCopilotPage";
-
-export default function CopilotPage() {
- const { state, handlers } = useCopilotPage();
- const isInterruptModalOpen = useCopilotStore((s) => s.isInterruptModalOpen);
- const confirmInterrupt = useCopilotStore((s) => s.confirmInterrupt);
- const cancelInterrupt = useCopilotStore((s) => s.cancelInterrupt);
-
- const [inputPlaceholder, setInputPlaceholder] = useState(
- getInputPlaceholder(),
- );
-
- useEffect(() => {
- const handleResize = () => {
- setInputPlaceholder(getInputPlaceholder(window.innerWidth));
- };
-
- handleResize();
-
- window.addEventListener("resize", handleResize);
- return () => window.removeEventListener("resize", handleResize);
- }, []);
-
- const { greetingName, quickActions, isLoading, hasSession, initialPrompt } =
- state;
-
- const {
- handleQuickAction,
- startChatWithPrompt,
- handleSessionNotFound,
- handleStreamingChange,
- } = handlers;
-
- if (hasSession) {
- return (
- <div className="flex h-full flex-col">
- <Chat
- className="flex-1"
- initialPrompt={initialPrompt}
- onSessionNotFound={handleSessionNotFound}
- onStreamingChange={handleStreamingChange}
- />
- <Dialog
- title="Interrupt current chat?"
- styling={{ maxWidth: 300, width: "100%" }}
- controlled={{
- isOpen: isInterruptModalOpen,
- set: (open) => {
- if (!open) cancelInterrupt();
- },
- }}
- onClose={cancelInterrupt}
- >
- <Dialog.Content>
- <div className="flex flex-col gap-4">
- <Text variant="body">
- The current chat response will be interrupted. Are you sure you
- want to continue?
- </Text>
- <Dialog.Footer>
- <Button
- type="button"
- variant="outline"
- onClick={cancelInterrupt}
- >
- Cancel
- </Button>
- <Button
- type="button"
- variant="primary"
- onClick={confirmInterrupt}
- >
- Continue
- </Button>
- </Dialog.Footer>
- </div>
- </Dialog.Content>
- </Dialog>
- </div>
- );
- }
+import { FeatureFlagPage } from "@/services/feature-flags/FeatureFlagPage";
+import { Flag } from "@/services/feature-flags/use-get-flag";
+import { CopilotPage } from "./CopilotPage";
+export default function Page() {
return (
- <div className="flex h-full flex-1 items-center justify-center overflow-y-auto bg-[#f8f8f9] px-3 py-5 md:px-6 md:py-10">
- <div className="w-full text-center">
- {isLoading ? (
- <div className="mx-auto max-w-2xl">
- <Skeleton className="mx-auto mb-3 h-8 w-64" />
- <Skeleton className="mx-auto mb-8 h-6 w-80" />
- <div className="mb-8">
- <Skeleton className="mx-auto h-14 w-full rounded-lg" />
- </div>
- <div className="flex flex-wrap items-center justify-center gap-3">
- {Array.from({ length: 4 }).map((_, i) => (
- <Skeleton key={i} className="h-9 w-48 rounded-md" />
- ))}
- </div>
- </div>
- ) : (
- <>
- <div className="mx-auto max-w-3xl">
- <Text
- variant="h3"
- className="mb-1 !text-[1.375rem] text-zinc-700"
- >
- Hey, <span className="text-violet-600">{greetingName}</span>
- </Text>
- <Text variant="h3" className="mb-8 !font-normal">
- Tell me about your work — I&apos;ll find what to automate.
- </Text>
-
- <div className="mb-6">
- <ChatInput
- onSend={startChatWithPrompt}
- placeholder={inputPlaceholder}
- />
- </div>
- </div>
- <div className="flex flex-wrap items-center justify-center gap-3 overflow-x-auto [-ms-overflow-style:none] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
- {quickActions.map((action) => (
- <Button
- key={action}
- type="button"
- variant="outline"
- size="small"
- onClick={() => handleQuickAction(action)}
- className="h-auto shrink-0 border-zinc-300 px-3 py-2 text-[.9rem] text-zinc-600"
- >
- {action}
- </Button>
- ))}
- </div>
- </>
- )}
- </div>
- </div>
+ <FeatureFlagPage flag={Flag.CHAT} whenDisabled="/library">
+ <CopilotPage />
+ </FeatureFlagPage>
);
}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/styleguide/page.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/styleguide/page.tsx
new file mode 100644
index 0000000000..6030665f1c
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/styleguide/page.tsx
@@ -0,0 +1,1533 @@
+"use client";
+
+import { ResponseType } from "@/app/api/__generated__/models/responseType";
+import {
+ Conversation,
+ ConversationContent,
+} from "@/components/ai-elements/conversation";
+import {
+ Message,
+ MessageContent,
+ MessageResponse,
+} from "@/components/ai-elements/message";
+import { Text } from "@/components/atoms/Text/Text";
+import { CopilotChatActionsProvider } from "../components/CopilotChatActionsProvider/CopilotChatActionsProvider";
+import { CreateAgentTool } from "../tools/CreateAgent/CreateAgent";
+import { EditAgentTool } from "../tools/EditAgent/EditAgent";
+import { FindAgentsTool } from "../tools/FindAgents/FindAgents";
+import { FindBlocksTool } from "../tools/FindBlocks/FindBlocks";
+import { RunAgentTool } from "../tools/RunAgent/RunAgent";
+import { RunBlockTool } from "../tools/RunBlock/RunBlock";
+import { SearchDocsTool } from "../tools/SearchDocs/SearchDocs";
+import { ViewAgentOutputTool } from "../tools/ViewAgentOutput/ViewAgentOutput";
+
+// ---------------------------------------------------------------------------
+// Helpers
+// ---------------------------------------------------------------------------
+
+function slugify(text: string) {
+ return text
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, "-")
+ .replace(/(^-|-$)/g, "");
+}
+
+const SECTIONS = [
+ "Messages",
+ "Tool: Find Blocks",
+ "Tool: Find Agents (Marketplace)",
+ "Tool: Find Agents (Library)",
+ "Tool: Search Docs",
+ "Tool: Get Doc Page",
+ "Tool: Run Block",
+ "Tool: Run Agent",
+ "Tool: Schedule Agent",
+ "Tool: Create Agent",
+ "Tool: Edit Agent",
+ "Tool: View Agent Output",
+ "Full Conversation Example",
+] as const;
+
+function Section({
+ title,
+ children,
+}: {
+ title: string;
+ children: React.ReactNode;
+}) {
+ return (
+ <div id={slugify(title)} className="mb-10 scroll-mt-6">
+ <h2 className="mb-4 border-b border-neutral-200 pb-2 font-mono text-xl font-semibold text-neutral-800">
+ {title}
+ </h2>
+ <div className="space-y-4">{children}</div>
+ </div>
+ );
+}
+
+function SubSection({
+ label,
+ children,
+}: {
+ label: string;
+ children: React.ReactNode;
+}) {
+ return (
+ <div className="rounded-lg border border-dashed border-blue-200 p-3">
+ <p className="mb-2 text-xs font-medium uppercase tracking-wide text-neutral-500">
+ {label}
+ </p>
+ {children}
+ </div>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Mock data factories
+// ---------------------------------------------------------------------------
+
+let _id = 0;
+function uid() {
+ return `sg-${++_id}`;
+}
+
+// ---------------------------------------------------------------------------
+// Page
+// ---------------------------------------------------------------------------
+
+export default function StyleguidePage() {
+ return (
+ <CopilotChatActionsProvider onSend={(msg) => alert(`onSend: ${msg}`)}>
+ <div className="flex h-[calc(100vh-72px)] bg-[#f8f8f9]">
+ {/* Sidebar */}
+ <nav className="sticky top-0 hidden h-full w-56 shrink-0 overflow-y-auto border-r border-neutral-200 bg-white px-3 py-6 lg:block">
+ <p className="mb-3 px-2 text-[11px] font-semibold uppercase tracking-wider text-neutral-400">
+ Sections
+ </p>
+ <ul className="space-y-0.5">
+ {SECTIONS.map((title) => (
+ <li key={title}>
+ <a
+ href={`#${slugify(title)}`}
+ className="block rounded-md px-2 py-1.5 text-[13px] text-neutral-600 transition-colors hover:bg-neutral-100 hover:text-neutral-900"
+ >
+ {title.replace(/^Tool: /, "")}
+ </a>
+ </li>
+ ))}
+ </ul>
+ </nav>
+
+ {/* Content */}
+ <div className="flex-1 overflow-y-auto">
+ <div className="mx-auto max-w-3xl px-4 py-10">
+ <Text variant="h1">Copilot Styleguide</Text>
+ <p className="mb-8 text-sm text-neutral-500">
+ Static showcase of all chat message types, tool states &amp;
+ variants.
+ </p>
+
+ {/* ============================================================= */}
+ {/* MESSAGE TYPES */}
+ {/* ============================================================= */}
+
+ <Section title="Messages">
+ <SubSection label="User message">
+ <Message from="user">
+ <MessageContent className="text-[1rem] leading-relaxed group-[.is-user]:rounded-xl group-[.is-user]:bg-purple-100 group-[.is-user]:px-3 group-[.is-user]:py-2.5 group-[.is-user]:text-slate-900 group-[.is-user]:[border-bottom-right-radius:0]">
+ <MessageResponse>
+ Find me an agent that can summarize YouTube videos
+ </MessageResponse>
+ </MessageContent>
+ </Message>
+ </SubSection>
+
+ <SubSection label="Assistant message (text)">
+ <Message from="assistant">
+ <MessageContent className="text-[1rem] leading-relaxed group-[.is-assistant]:bg-transparent group-[.is-assistant]:text-slate-900">
+ <MessageResponse>
+ I found a few agents that can help with YouTube video
+ summarization. Let me search for the best options for you.
+ </MessageResponse>
+ </MessageContent>
+ </Message>
+ </SubSection>
+
+ <SubSection label="Assistant message (markdown)">
+ <Message from="assistant">
+ <MessageContent className="text-[1rem] leading-relaxed group-[.is-assistant]:bg-transparent group-[.is-assistant]:text-slate-900">
+ <MessageResponse>
+ {`Here's what I found:\n\n1. **YouTube Summarizer** — Extracts key points from any YouTube video\n2. **Video Digest** — Creates bullet-point summaries with timestamps\n\n> Both agents support videos up to 2 hours long.\n\n\`\`\`python\n# Example usage\nresult = agent.run(url="https://youtube.com/watch?v=...")\nprint(result.summary)\n\`\`\``}
+ </MessageResponse>
+ </MessageContent>
+ </Message>
+ </SubSection>
+
+ <SubSection label="Thinking state">
+ <Message from="assistant">
+ <MessageContent className="text-[1rem] leading-relaxed">
+ <span className="inline-block animate-shimmer bg-gradient-to-r from-neutral-400 via-neutral-600 to-neutral-400 bg-[length:200%_100%] bg-clip-text text-transparent">
+ Thinking...
+ </span>
+ </MessageContent>
+ </Message>
+ </SubSection>
+
+ <SubSection label="Error state">
+ <div className="rounded-lg bg-red-50 p-3 text-red-600">
+ Error: Connection timed out. Please try again.
+ </div>
+ </SubSection>
+ </Section>
+
+ {/* ============================================================= */}
+ {/* FIND BLOCKS */}
+ {/* ============================================================= */}
+
+ <Section title="Tool: Find Blocks">
+ <SubSection label="Input streaming">
+ <FindBlocksTool
+ part={{
+ type: "tool-find_block",
+ toolCallId: uid(),
+ state: "input-streaming",
+ input: { query: "weather" },
+ }}
+ />
+ </SubSection>
+
+ <SubSection label="Input available">
+ <FindBlocksTool
+ part={{
+ type: "tool-find_block",
+ toolCallId: uid(),
+ state: "input-available",
+ input: { query: "weather" },
+ }}
+ />
+ </SubSection>
+
+ <SubSection label="Output available (with results)">
+ <FindBlocksTool
+ part={{
+ type: "tool-find_block",
+ toolCallId: uid(),
+ state: "output-available",
+ input: { query: "weather" },
+ output: {
+ type: ResponseType.block_list,
+ blocks: [
+ {
+ id: "block-1",
+ name: "Get Weather",
+ description:
+ "Fetches current weather data for a given city using the OpenWeatherMap API.",
+ categories: [],
+ },
+ {
+ id: "block-2",
+ name: "Weather Forecast",
+ description:
+ "Returns a 5-day weather forecast for any location worldwide.",
+ categories: [],
+ },
+ {
+ id: "block-3",
+ name: "Historical Weather",
+ description:
+ "Retrieves historical weather data for the past 30 days.",
+ categories: [],
+ },
+ ],
+ count: 3,
+ },
+ }}
+ />
+ </SubSection>
+
+ <SubSection label="Output error">
+ <FindBlocksTool
+ part={{
+ type: "tool-find_block",
+ toolCallId: uid(),
+ state: "output-error",
+ input: { query: "weather" },
+ }}
+ />
+ </SubSection>
+ </Section>
+
+ {/* ============================================================= */}
+ {/* FIND AGENTS (Marketplace) */}
+ {/* ============================================================= */}
+
+ <Section title="Tool: Find Agents (Marketplace)">
+ <SubSection label="Input streaming">
+ <FindAgentsTool
+ part={{
+ type: "tool-find_agent",
+ toolCallId: uid(),
+ state: "input-streaming",
+ input: { query: "youtube summarizer" },
+ }}
+ />
+ </SubSection>
+
+ <SubSection label="Output available (agents found)">
+ <FindAgentsTool
+ part={{
+ type: "tool-find_agent",
+ toolCallId: uid(),
+ state: "output-available",
+ input: { query: "youtube summarizer" },
+ output: {
+ type: ResponseType.agents_found,
+ agents: [
+ {
+ id: "creator/youtube-summarizer",
+ name: "YouTube Summarizer",
+ description:
+ "Summarizes YouTube videos into concise bullet points with key insights.",
+ source: "marketplace",
+ },
+ {
+ id: "creator/video-digest",
+ name: "Video Digest Pro",
+ description:
+ "Creates detailed summaries with timestamps from any YouTube video.",
+ source: "marketplace",
+ },
+ ],
+ count: 2,
+ },
+ }}
+ />
+ </SubSection>
+
+ <SubSection label="Output available (no results)">
+ <FindAgentsTool
+ part={{
+ type: "tool-find_agent",
+ toolCallId: uid(),
+ state: "output-available",
+ input: { query: "quantum computing simulator" },
+ output: {
+ type: ResponseType.no_results,
+ message: "No agents found matching your query.",
+ suggestions: [
+ "Try broader search terms",
+ "Check the marketplace for related agents",
+ ],
+ },
+ }}
+ />
+ </SubSection>
+
+ <SubSection label="Output error">
+ <FindAgentsTool
+ part={{
+ type: "tool-find_agent",
+ toolCallId: uid(),
+ state: "output-error",
+ input: { query: "youtube summarizer" },
+ }}
+ />
+ </SubSection>
+ </Section>
+
+ {/* ============================================================= */}
+ {/* FIND AGENTS (Library) */}
+ {/* ============================================================= */}
+
+ <Section title="Tool: Find Agents (Library)">
+ <SubSection label="Input streaming">
+ <FindAgentsTool
+ part={{
+ type: "tool-find_library_agent",
+ toolCallId: uid(),
+ state: "input-streaming",
+ input: { query: "social media" },
+ }}
+ />
+ </SubSection>
+
+ <SubSection label="Output available (agents found)">
+ <FindAgentsTool
+ part={{
+ type: "tool-find_library_agent",
+ toolCallId: uid(),
+ state: "output-available",
+ input: { query: "social media" },
+ output: {
+ type: ResponseType.agents_found,
+ agents: [
+ {
+ id: "lib-agent-1",
+ name: "Twitter Post Scheduler",
+ description:
+ "Schedules and posts tweets at optimal times for engagement.",
+ source: "library",
+ },
+ ],
+ count: 1,
+ },
+ }}
+ />
+ </SubSection>
+ </Section>
+
+ {/* ============================================================= */}
+ {/* SEARCH DOCS */}
+ {/* ============================================================= */}
+
+ <Section title="Tool: Search Docs">
+ <SubSection label="Input streaming">
+ <SearchDocsTool
+ part={{
+ type: "tool-search_docs",
+ toolCallId: uid(),
+ state: "input-streaming",
+ input: { query: "webhooks" },
+ }}
+ />
+ </SubSection>
+
+ <SubSection label="Output available (search results)">
+ <SearchDocsTool
+ part={{
+ type: "tool-search_docs",
+ toolCallId: uid(),
+ state: "output-available",
+ input: { query: "webhooks" },
+ output: {
+ type: ResponseType.doc_search_results,
+ query: "webhooks",
+ count: 2,
+ results: [
+ {
+ title: "Webhook Configuration Guide",
+ path: "platform/webhooks/configuration.md",
+ section: "Setup",
+ snippet:
+ "Webhooks allow you to receive real-time notifications when events occur in your AutoGPT workspace. Configure webhook endpoints to integrate with external services.",
+ doc_url:
+ "https://docs.agpt.co/platform/webhooks/configuration",
+ },
+ {
+ title: "Webhook Events Reference",
+ path: "platform/webhooks/events.md",
+ section: "Event Types",
+ snippet:
+ "A complete reference of all webhook event types including agent.completed, execution.started, and execution.failed events.",
+ doc_url:
+ "https://docs.agpt.co/platform/webhooks/events",
+ },
+ ],
+ },
+ }}
+ />
+ </SubSection>
+
+ <SubSection label="Output available (no results)">
+ <SearchDocsTool
+ part={{
+ type: "tool-search_docs",
+ toolCallId: uid(),
+ state: "output-available",
+ input: { query: "foobar" },
+ output: {
+ type: ResponseType.no_results,
+ message: "No documentation found for this query.",
+ suggestions: [
+ "Try different keywords",
+ "Check the documentation index",
+ ],
+ },
+ }}
+ />
+ </SubSection>
+
+ <SubSection label="Output error">
+ <SearchDocsTool
+ part={{
+ type: "tool-search_docs",
+ toolCallId: uid(),
+ state: "output-error",
+ input: { query: "webhooks" },
+ }}
+ />
+ </SubSection>
+ </Section>
+
+ {/* ============================================================= */}
+ {/* GET DOC PAGE */}
+ {/* ============================================================= */}
+
+ <Section title="Tool: Get Doc Page">
+ <SubSection label="Input streaming">
+ <SearchDocsTool
+ part={{
+ type: "tool-get_doc_page",
+ toolCallId: uid(),
+ state: "input-streaming",
+ input: { path: "platform/getting-started.md" },
+ }}
+ />
+ </SubSection>
+
+ <SubSection label="Output available (page loaded)">
+ <SearchDocsTool
+ part={{
+ type: "tool-get_doc_page",
+ toolCallId: uid(),
+ state: "output-available",
+ input: { path: "platform/getting-started.md" },
+ output: {
+ type: ResponseType.doc_page,
+ title: "Getting Started with AutoGPT Platform",
+ path: "platform/getting-started.md",
+ content:
+ "Welcome to AutoGPT Platform! This guide will walk you through setting up your first agent.\n\n## Prerequisites\n- An AutoGPT account\n- Basic understanding of automation workflows\n\n## Quick Start\n1. Navigate to the Builder\n2. Create a new agent\n3. Add blocks to your workflow\n4. Test and deploy",
+ doc_url: "https://docs.agpt.co/platform/getting-started",
+ },
+ }}
+ />
+ </SubSection>
+ </Section>
+
+ {/* ============================================================= */}
+ {/* RUN BLOCK */}
+ {/* ============================================================= */}
+
+ <Section title="Tool: Run Block">
+ <SubSection label="Input streaming">
+ <RunBlockTool
+ part={{
+ type: "tool-run_block",
+ toolCallId: uid(),
+ state: "input-streaming",
+ input: { block_id: "weather-block-123" },
+ }}
+ />
+ </SubSection>
+
+ <SubSection label="Input available">
+ <RunBlockTool
+ part={{
+ type: "tool-run_block",
+ toolCallId: uid(),
+ state: "input-available",
+ input: {
+ block_id: "weather-block-123",
+ input_data: { city: "San Francisco" },
+ },
+ }}
+ />
+ </SubSection>
+
+ <SubSection label="Output available (block output)">
+ <RunBlockTool
+ part={{
+ type: "tool-run_block",
+ toolCallId: uid(),
+ state: "output-available",
+ input: { block_id: "weather-block-123" },
+ output: {
+ type: ResponseType.block_output,
+ block_id: "weather-block-123",
+ block_name: "Get Weather",
+ message:
+ "Successfully fetched weather data for San Francisco.",
+ outputs: {
+ temperature: ["72°F"],
+ condition: ["Partly Cloudy"],
+ humidity: ["65%"],
+ },
+ },
+ }}
+ />
+ </SubSection>
+
+ <SubSection label="Output available (setup requirements)">
+ <RunBlockTool
+ part={{
+ type: "tool-run_block",
+ toolCallId: uid(),
+ state: "output-available",
+ input: { block_id: "weather-block-123" },
+ output: {
+ type: ResponseType.setup_requirements,
+ message:
+ "This block requires API credentials to run. Please configure them below.",
+ setup_info: {
+ agent_name: "Weather Agent",
+ requirements: {
+ inputs: [
+ {
+ name: "city",
+ title: "City",
+ type: "string",
+ required: true,
+ description: "The city to get weather for",
+ },
+ ],
+ },
+ user_readiness: {
+ missing_credentials: {
+ openweathermap: {
+ provider: "openweathermap",
+ credentials_type: "api_key",
+ title: "OpenWeatherMap API Key",
+ description:
+ "Required to access weather data. Get your key at openweathermap.org",
+ },
+ },
+ },
+ },
+ },
+ }}
+ />
+ </SubSection>
+
+ <SubSection label="Output available (error)">
+ <RunBlockTool
+ part={{
+ type: "tool-run_block",
+ toolCallId: uid(),
+ state: "output-available",
+ input: { block_id: "weather-block-123" },
+ output: {
+ type: ResponseType.error,
+ message: "Failed to run the block.",
+ error: "Block execution timed out after 30 seconds.",
+ details: {
+ block_id: "weather-block-123",
+ timeout_ms: 30000,
+ },
+ },
+ }}
+ />
+ </SubSection>
+
+ <SubSection label="Output available (JSON object output — interactive viewer)">
+ <RunBlockTool
+ part={{
+ type: "tool-run_block",
+ toolCallId: uid(),
+ state: "output-available",
+ input: { block_id: "api-block-456" },
+ output: {
+ type: ResponseType.block_output,
+ block_id: "api-block-456",
+ block_name: "API Request",
+ message: "Successfully fetched user profile data.",
+ outputs: {
+ response: [
+ {
+ id: 42,
+ name: "Jane Doe",
+ email: "[email protected]",
+ roles: ["admin", "editor"],
+ settings: {
+ theme: "dark",
+ notifications: true,
+ language: "en",
+ },
+ },
+ ],
+ },
+ },
+ }}
+ />
+ </SubSection>
+
+ <SubSection label="Output available (image URL — ImageRenderer)">
+ <RunBlockTool
+ part={{
+ type: "tool-run_block",
+ toolCallId: uid(),
+ state: "output-available",
+ input: { block_id: "image-gen-789" },
+ output: {
+ type: ResponseType.block_output,
+ block_id: "image-gen-789",
+ block_name: "Image Generator",
+ message: "Generated image successfully.",
+ outputs: {
+ image: [
+ "https://picsum.photos/seed/styleguide/600/400",
+ ],
+ },
+ },
+ }}
+ />
+ </SubSection>
+
+ <SubSection label="Output available (markdown text — MarkdownRenderer)">
+ <RunBlockTool
+ part={{
+ type: "tool-run_block",
+ toolCallId: uid(),
+ state: "output-available",
+ input: { block_id: "summarizer-101" },
+ output: {
+ type: ResponseType.block_output,
+ block_id: "summarizer-101",
+ block_name: "Text Summarizer",
+ message: "Document summarized successfully.",
+ outputs: {
+ summary: [
+ "## Executive Summary\n\nThe quarterly report shows **strong growth** across all departments:\n\n- Revenue increased by *23%* compared to Q3\n- Customer satisfaction score: `4.8/5.0`\n- New user sign-ups doubled\n\n### Key Takeaways\n\n1. **Product launches** drove the majority of growth\n2. **Marketing campaigns** exceeded ROI targets\n3. **Infrastructure costs** remained flat despite scaling\n\n> Overall, this was our strongest quarter to date.\n\n| Metric | Q3 | Q4 | Change |\n|--------|-----|-----|--------|\n| Revenue | $2.1M | $2.6M | +23% |\n| Users | 10k | 20k | +100% |\n| NPS | 72 | 78 | +6 |",
+ ],
+ },
+ },
+ }}
+ />
+ </SubSection>
+
+ <SubSection label="Output available (plain text — TextRenderer)">
+ <RunBlockTool
+ part={{
+ type: "tool-run_block",
+ toolCallId: uid(),
+ state: "output-available",
+ input: { block_id: "translate-202" },
+ output: {
+ type: ResponseType.block_output,
+ block_id: "translate-202",
+ block_name: "Translate Text",
+ message: "Translation completed.",
+ outputs: {
+ translated_text: [
+ "Bonjour le monde! Ceci est un exemple de texte traduit du bloc de traduction.",
+ ],
+ },
+ },
+ }}
+ />
+ </SubSection>
+
+ <SubSection label="Output available (multiple items with expand)">
+ <RunBlockTool
+ part={{
+ type: "tool-run_block",
+ toolCallId: uid(),
+ state: "output-available",
+ input: { block_id: "scraper-303" },
+ output: {
+ type: ResponseType.block_output,
+ block_id: "scraper-303",
+ block_name: "Web Scraper",
+ message: "Scraped 6 articles from the feed.",
+ outputs: {
+ articles: [
+ {
+ title: "AI Advances in 2026",
+ url: "https://example.com/1",
+ score: 142,
+ },
+ {
+ title: "New Framework Released",
+ url: "https://example.com/2",
+ score: 98,
+ },
+ {
+ title: "Open Source Milestone",
+ url: "https://example.com/3",
+ score: 87,
+ },
+ {
+ title: "Cloud Computing Trends",
+ url: "https://example.com/4",
+ score: 76,
+ },
+ {
+ title: "Developer Survey Results",
+ url: "https://example.com/5",
+ score: 64,
+ },
+ {
+ title: "Security Best Practices",
+ url: "https://example.com/6",
+ score: 51,
+ },
+ ],
+ },
+ },
+ }}
+ />
+ </SubSection>
+
+ <SubSection label="Output error">
+ <RunBlockTool
+ part={{
+ type: "tool-run_block",
+ toolCallId: uid(),
+ state: "output-error",
+ input: { block_id: "weather-block-123" },
+ }}
+ />
+ </SubSection>
+ </Section>
+
+ {/* ============================================================= */}
+ {/* RUN AGENT */}
+ {/* ============================================================= */}
+
+ <Section title="Tool: Run Agent">
+ <SubSection label="Input streaming">
+ <RunAgentTool
+ part={{
+ type: "tool-run_agent",
+ toolCallId: uid(),
+ state: "input-streaming",
+ input: { username_agent_slug: "creator/my-agent" },
+ }}
+ />
+ </SubSection>
+
+ <SubSection label="Output available (execution started)">
+ <RunAgentTool
+ part={{
+ type: "tool-run_agent",
+ toolCallId: uid(),
+ state: "output-available",
+ input: { username_agent_slug: "creator/my-agent" },
+ output: {
+ type: ResponseType.execution_started,
+ execution_id: "exec-abc-123-def-456",
+ graph_name: "YouTube Summarizer",
+ message:
+ "Agent execution started. You can track progress in your library.",
+ status: "running",
+ library_agent_link: "/library/agents/lib-123",
+ },
+ }}
+ />
+ </SubSection>
+
+ <SubSection label="Output available (agent details / inputs needed)">
+ <RunAgentTool
+ part={{
+ type: "tool-run_agent",
+ toolCallId: uid(),
+ state: "output-available",
+ input: { username_agent_slug: "creator/my-agent" },
+ output: {
+ type: ResponseType.agent_details,
+ agent: {
+ name: "YouTube Summarizer",
+ description:
+ "Summarizes YouTube videos into key points.",
+ inputs: [
+ {
+ name: "video_url",
+ title: "Video URL",
+ type: "string",
+ required: true,
+ description: "The YouTube video URL to summarize",
+ },
+ {
+ name: "language",
+ title: "Output Language",
+ type: "string",
+ required: false,
+ description:
+ "Language for the summary (default: English)",
+ },
+ ],
+ },
+ message: "This agent requires inputs to run.",
+ },
+ }}
+ />
+ </SubSection>
+
+ <SubSection label="Output available (setup requirements)">
+ <RunAgentTool
+ part={{
+ type: "tool-run_agent",
+ toolCallId: uid(),
+ state: "output-available",
+ input: { username_agent_slug: "creator/my-agent" },
+ output: {
+ type: ResponseType.setup_requirements,
+ message: "This agent requires additional setup.",
+ setup_info: {
+ agent_name: "YouTube Summarizer",
+ requirements: {},
+ user_readiness: {
+ missing_credentials: {
+ youtube_api: {
+ provider: "youtube",
+ credentials_type: "api_key",
+ title: "YouTube Data API Key",
+ description:
+ "Required to access YouTube video data.",
+ },
+ },
+ },
+ },
+ },
+ }}
+ />
+ </SubSection>
+
+ <SubSection label="Output available (need login)">
+ <RunAgentTool
+ part={{
+ type: "tool-run_agent",
+ toolCallId: uid(),
+ state: "output-available",
+ input: { username_agent_slug: "creator/my-agent" },
+ output: {
+ type: ResponseType.need_login,
+ message:
+ "You need to sign in to run this agent. Please log in and try again.",
+ },
+ }}
+ />
+ </SubSection>
+
+ <SubSection label="Output available (error)">
+ <RunAgentTool
+ part={{
+ type: "tool-run_agent",
+ toolCallId: uid(),
+ state: "output-available",
+ input: { username_agent_slug: "creator/my-agent" },
+ output: {
+ type: ResponseType.error,
+ message: "Failed to start the agent.",
+ error: "Agent not found or has been deleted.",
+ },
+ }}
+ />
+ </SubSection>
+
+ <SubSection label="Output error">
+ <RunAgentTool
+ part={{
+ type: "tool-run_agent",
+ toolCallId: uid(),
+ state: "output-error",
+ input: { username_agent_slug: "creator/my-agent" },
+ }}
+ />
+ </SubSection>
+ </Section>
+
+ {/* ============================================================= */}
+ {/* SCHEDULE AGENT */}
+ {/* ============================================================= */}
+
+ <Section title="Tool: Schedule Agent">
+ <SubSection label="Input streaming (schedule)">
+ <RunAgentTool
+ part={{
+ type: "tool-schedule_agent",
+ toolCallId: uid(),
+ state: "input-streaming",
+ input: {
+ username_agent_slug: "creator/daily-digest",
+ schedule_name: "Morning Digest",
+ cron: "0 8 * * *",
+ timezone: "America/Los_Angeles",
+ },
+ }}
+ />
+ </SubSection>
+
+ <SubSection label="Output available (execution started — scheduled)">
+ <RunAgentTool
+ part={{
+ type: "tool-schedule_agent",
+ toolCallId: uid(),
+ state: "output-available",
+ input: {
+ username_agent_slug: "creator/daily-digest",
+ schedule_name: "Morning Digest",
+ cron: "0 8 * * *",
+ },
+ output: {
+ type: ResponseType.execution_started,
+ execution_id: "sched-abc-123",
+ graph_name: "Daily Digest",
+ message:
+ "Agent scheduled successfully. It will run daily at 8:00 AM.",
+ status: "scheduled",
+ library_agent_link: "/library/agents/lib-456",
+ },
+ }}
+ />
+ </SubSection>
+ </Section>
+
+ {/* ============================================================= */}
+ {/* CREATE AGENT */}
+ {/* ============================================================= */}
+
+ <Section title="Tool: Create Agent">
+ <SubSection label="Input streaming">
+ <CreateAgentTool
+ part={{
+ type: "tool-create_agent",
+ toolCallId: uid(),
+ state: "input-streaming",
+ }}
+ />
+ </SubSection>
+
+ <SubSection label="Output available (operation started)">
+ <CreateAgentTool
+ part={{
+ type: "tool-create_agent",
+ toolCallId: uid(),
+ state: "output-available",
+ output: {
+ type: ResponseType.operation_started,
+ operation_id: "op-create-123",
+ tool_name: "create_agent",
+ message:
+ "Agent creation has been started. This may take a moment.",
+ },
+ }}
+ />
+ </SubSection>
+
+ <SubSection label="Output available (operation pending)">
+ <CreateAgentTool
+ part={{
+ type: "tool-create_agent",
+ toolCallId: uid(),
+ state: "output-available",
+ output: {
+ type: ResponseType.operation_pending,
+ operation_id: "op-create-123",
+ tool_name: "create_agent",
+ message:
+ "Agent creation is queued and will begin shortly.",
+ },
+ }}
+ />
+ </SubSection>
+
+ <SubSection label="Output available (operation in progress)">
+ <CreateAgentTool
+ part={{
+ type: "tool-create_agent",
+ toolCallId: uid(),
+ state: "output-available",
+ output: {
+ type: ResponseType.operation_in_progress,
+ tool_call_id: "tc-456",
+ message:
+ "An agent creation operation is already in progress. Please wait for it to finish.",
+ },
+ }}
+ />
+ </SubSection>
+
+ <SubSection label="Output available (agent preview)">
+ <CreateAgentTool
+ part={{
+ type: "tool-create_agent",
+ toolCallId: uid(),
+ state: "output-available",
+ output: {
+ type: ResponseType.agent_preview,
+ agent_name: "Email Summarizer",
+ description:
+ "An agent that summarizes your unread emails into a daily digest.",
+ node_count: 4,
+ message:
+ "Here's a preview of the agent. Would you like me to save it?",
+ agent_json: {
+ name: "Email Summarizer",
+ nodes: [
+ { id: "1", type: "gmail_reader" },
+ { id: "2", type: "text_summarizer" },
+ { id: "3", type: "formatter" },
+ { id: "4", type: "output" },
+ ],
+ },
+ },
+ }}
+ />
+ </SubSection>
+
+ <SubSection label="Output available (agent saved)">
+ <CreateAgentTool
+ part={{
+ type: "tool-create_agent",
+ toolCallId: uid(),
+ state: "output-available",
+ output: {
+ type: ResponseType.agent_saved,
+ agent_id: "agent-789",
+ agent_name: "Email Summarizer",
+ library_agent_id: "lib-agent-789",
+ library_agent_link: "/library/agents/lib-agent-789",
+ agent_page_link: "/build?agent=agent-789",
+ message:
+ "Agent 'Email Summarizer' has been saved to your library!",
+ },
+ }}
+ />
+ </SubSection>
+
+ <SubSection label="Output available (clarification needed)">
+ <CreateAgentTool
+ part={{
+ type: "tool-create_agent",
+ toolCallId: uid(),
+ state: "output-available",
+ output: {
+ type: ResponseType.clarification_needed,
+ message:
+ "I need a bit more information before creating this agent.",
+ questions: [
+ {
+ question:
+ "Which email provider should the agent connect to?",
+ keyword: "email_provider",
+ example: "Gmail, Outlook, Yahoo",
+ },
+ {
+ question:
+ "How frequently should the digest be generated?",
+ keyword: "frequency",
+ example: "Daily, Twice a day, Weekly",
+ },
+ ],
+ },
+ }}
+ />
+ </SubSection>
+
+ <SubSection label="Output available (error)">
+ <CreateAgentTool
+ part={{
+ type: "tool-create_agent",
+ toolCallId: uid(),
+ state: "output-available",
+ output: {
+ type: ResponseType.error,
+ message: "Failed to create the agent.",
+ error:
+ "The requested blocks are not compatible with each other.",
+ details: {
+ incompatible: ["gmail_reader", "slack_writer"],
+ },
+ },
+ }}
+ />
+ </SubSection>
+
+ <SubSection label="Output error">
+ <CreateAgentTool
+ part={{
+ type: "tool-create_agent",
+ toolCallId: uid(),
+ state: "output-error",
+ }}
+ />
+ </SubSection>
+ </Section>
+
+ {/* ============================================================= */}
+ {/* EDIT AGENT */}
+ {/* ============================================================= */}
+
+ <Section title="Tool: Edit Agent">
+ <SubSection label="Input streaming">
+ <EditAgentTool
+ part={{
+ type: "tool-edit_agent",
+ toolCallId: uid(),
+ state: "input-streaming",
+ }}
+ />
+ </SubSection>
+
+ <SubSection label="Output available (operation started)">
+ <EditAgentTool
+ part={{
+ type: "tool-edit_agent",
+ toolCallId: uid(),
+ state: "output-available",
+ output: {
+ type: ResponseType.operation_started,
+ operation_id: "op-edit-456",
+ tool_name: "edit_agent",
+ message: "Agent editing has started.",
+ },
+ }}
+ />
+ </SubSection>
+
+ <SubSection label="Output available (agent preview)">
+ <EditAgentTool
+ part={{
+ type: "tool-edit_agent",
+ toolCallId: uid(),
+ state: "output-available",
+ output: {
+ type: ResponseType.agent_preview,
+ agent_name: "Email Summarizer v2",
+ description:
+ "Updated agent with improved summarization and Slack integration.",
+ node_count: 6,
+ message:
+ "Here's the updated agent. Shall I save these changes?",
+ agent_json: {
+ name: "Email Summarizer v2",
+ nodes: [
+ { id: "1", type: "gmail_reader" },
+ { id: "2", type: "text_summarizer" },
+ { id: "3", type: "formatter" },
+ { id: "4", type: "slack_writer" },
+ { id: "5", type: "scheduler" },
+ { id: "6", type: "output" },
+ ],
+ },
+ },
+ }}
+ />
+ </SubSection>
+
+ <SubSection label="Output available (agent saved)">
+ <EditAgentTool
+ part={{
+ type: "tool-edit_agent",
+ toolCallId: uid(),
+ state: "output-available",
+ output: {
+ type: ResponseType.agent_saved,
+ agent_id: "agent-789",
+ agent_name: "Email Summarizer v2",
+ library_agent_id: "lib-agent-789",
+ library_agent_link: "/library/agents/lib-agent-789",
+ agent_page_link: "/build?agent=agent-789",
+ message:
+ "Agent 'Email Summarizer v2' has been saved successfully!",
+ },
+ }}
+ />
+ </SubSection>
+
+ <SubSection label="Output available (clarification needed)">
+ <EditAgentTool
+ part={{
+ type: "tool-edit_agent",
+ toolCallId: uid(),
+ state: "output-available",
+ output: {
+ type: ResponseType.clarification_needed,
+ message:
+ "I need to clarify a few things about the edits you want.",
+ questions: [
+ {
+ question:
+ "Should the Slack notification replace the email output or be in addition to it?",
+ keyword: "notification_mode",
+ example: "Replace, Add alongside",
+ },
+ ],
+ },
+ }}
+ />
+ </SubSection>
+
+ <SubSection label="Output error">
+ <EditAgentTool
+ part={{
+ type: "tool-edit_agent",
+ toolCallId: uid(),
+ state: "output-error",
+ }}
+ />
+ </SubSection>
+ </Section>
+
+ {/* ============================================================= */}
+ {/* VIEW AGENT OUTPUT */}
+ {/* ============================================================= */}
+
+ <Section title="Tool: View Agent Output">
+ <SubSection label="Input streaming">
+ <ViewAgentOutputTool
+ part={{
+ type: "tool-view_agent_output",
+ toolCallId: uid(),
+ state: "input-streaming",
+ input: {
+ agent_name: "YouTube Summarizer",
+ execution_id: "exec-abc-123",
+ },
+ }}
+ />
+ </SubSection>
+
+ <SubSection label="Output available (with execution data)">
+ <ViewAgentOutputTool
+ part={{
+ type: "tool-view_agent_output",
+ toolCallId: uid(),
+ state: "output-available",
+ input: {
+ agent_name: "YouTube Summarizer",
+ execution_id: "exec-abc-123",
+ },
+ output: {
+ type: ResponseType.agent_output,
+ agent_id: "agent-123",
+ agent_name: "YouTube Summarizer",
+ message: "Here are the results from the last execution.",
+ library_agent_link: "/library/agents/lib-agent-123",
+ execution: {
+ execution_id: "exec-abc-123",
+ status: "completed",
+ inputs_summary: {
+ video_url: "https://youtube.com/watch?v=dQw4w9WgXcQ",
+ },
+ outputs: {
+ summary: [
+ "Key Points:\n1. Introduction to the topic\n2. Main arguments presented\n3. Conclusion and takeaways",
+ ],
+ keywords: ["music", "classic", "80s"],
+ },
+ },
+ },
+ }}
+ />
+ </SubSection>
+
+ <SubSection label="Output available (rich outputs — JSON + markdown + image)">
+ <ViewAgentOutputTool
+ part={{
+ type: "tool-view_agent_output",
+ toolCallId: uid(),
+ state: "output-available",
+ input: {
+ agent_name: "Research Agent",
+ execution_id: "exec-rich-456",
+ },
+ output: {
+ type: ResponseType.agent_output,
+ agent_id: "agent-456",
+ agent_name: "Research Agent",
+ message: "Research completed with multiple output types.",
+ library_agent_link: "/library/agents/lib-agent-456",
+ execution: {
+ execution_id: "exec-rich-456",
+ status: "completed",
+ inputs_summary: {
+ topic: "Artificial Intelligence in Healthcare",
+ depth: "comprehensive",
+ format: "report",
+ },
+ outputs: {
+ report: [
+ "## AI in Healthcare: 2026 Landscape\n\n### Key Findings\n\n- **Diagnostic accuracy** improved by 34% with AI-assisted imaging\n- Drug discovery timelines reduced from *10 years to 3 years*\n- Patient outcomes improved across `87%` of pilot programs\n\n> AI is not replacing doctors — it's augmenting their capabilities.\n\n### Adoption by Region\n\n| Region | Adoption Rate | Growth |\n|--------|--------------|--------|\n| North America | 78% | +15% |\n| Europe | 62% | +22% |\n| Asia Pacific | 71% | +31% |",
+ ],
+ metadata: [
+ {
+ sources_analyzed: 142,
+ confidence_score: 0.94,
+ processing_time_ms: 3420,
+ model_version: "v2.3.1",
+ categories: [
+ "healthcare",
+ "machine-learning",
+ "diagnostics",
+ ],
+ },
+ ],
+ chart: [
+ "https://picsum.photos/seed/chart-demo/500/300",
+ ],
+ },
+ },
+ },
+ }}
+ />
+ </SubSection>
+
+ <SubSection label="Output available (no execution selected)">
+ <ViewAgentOutputTool
+ part={{
+ type: "tool-view_agent_output",
+ toolCallId: uid(),
+ state: "output-available",
+ input: { agent_name: "YouTube Summarizer" },
+ output: {
+ type: ResponseType.agent_output,
+ agent_id: "agent-123",
+ agent_name: "YouTube Summarizer",
+ message:
+ "Agent found but no specific execution selected.",
+ library_agent_link: "/library/agents/lib-agent-123",
+ },
+ }}
+ />
+ </SubSection>
+
+ <SubSection label="Output available (no results)">
+ <ViewAgentOutputTool
+ part={{
+ type: "tool-view_agent_output",
+ toolCallId: uid(),
+ state: "output-available",
+ input: { agent_name: "Nonexistent Agent" },
+ output: {
+ type: ResponseType.no_results,
+ message:
+ "No outputs found for this agent. It may not have been run yet.",
+ suggestions: [
+ "Try running the agent first",
+ "Check the agent name is correct",
+ ],
+ },
+ }}
+ />
+ </SubSection>
+
+ <SubSection label="Output available (error)">
+ <ViewAgentOutputTool
+ part={{
+ type: "tool-view_agent_output",
+ toolCallId: uid(),
+ state: "output-available",
+ input: { agent_name: "YouTube Summarizer" },
+ output: {
+ type: ResponseType.error,
+ message: "Failed to retrieve agent output.",
+ error: "Execution data is corrupted or unavailable.",
+ },
+ }}
+ />
+ </SubSection>
+
+ <SubSection label="Output error">
+ <ViewAgentOutputTool
+ part={{
+ type: "tool-view_agent_output",
+ toolCallId: uid(),
+ state: "output-error",
+ input: { agent_name: "YouTube Summarizer" },
+ }}
+ />
+ </SubSection>
+ </Section>
+
+ {/* ============================================================= */}
+ {/* FULL CONVERSATION EXAMPLE */}
+ {/* ============================================================= */}
+
+ <Section title="Full Conversation Example">
+ <Conversation className="min-h-0 rounded-lg border bg-white">
+ <ConversationContent className="gap-6 px-3 py-6">
+ <Message from="user">
+ <MessageContent className="text-[1rem] leading-relaxed group-[.is-user]:rounded-xl group-[.is-user]:bg-purple-100 group-[.is-user]:px-3 group-[.is-user]:py-2.5 group-[.is-user]:text-slate-900 group-[.is-user]:[border-bottom-right-radius:0]">
+ <MessageResponse>
+ Find me a block that can fetch weather data
+ </MessageResponse>
+ </MessageContent>
+ </Message>
+
+ <Message from="assistant">
+ <MessageContent className="text-[1rem] leading-relaxed group-[.is-assistant]:bg-transparent group-[.is-assistant]:text-slate-900">
+ <MessageResponse>
+ Let me search for weather-related blocks for you.
+ </MessageResponse>
+
+ <FindBlocksTool
+ part={{
+ type: "tool-find_block",
+ toolCallId: uid(),
+ state: "output-available",
+ input: { query: "weather" },
+ output: {
+ type: ResponseType.block_list,
+ blocks: [
+ {
+ id: "block-1",
+ name: "Get Weather",
+ description:
+ "Fetches current weather data for a given city.",
+ categories: [],
+ },
+ {
+ id: "block-2",
+ name: "Weather Forecast",
+ description:
+ "Returns a 5-day weather forecast for any location.",
+ categories: [],
+ },
+ ],
+ count: 2,
+ },
+ }}
+ />
+
+ <MessageResponse>
+ I found 2 blocks related to weather. The **Get Weather**
+ block fetches current conditions, while **Weather
+ Forecast** provides a 5-day outlook. Would you like me
+ to run one of these?
+ </MessageResponse>
+ </MessageContent>
+ </Message>
+
+ <Message from="user">
+ <MessageContent className="text-[1rem] leading-relaxed group-[.is-user]:rounded-xl group-[.is-user]:bg-purple-100 group-[.is-user]:px-3 group-[.is-user]:py-2.5 group-[.is-user]:text-slate-900 group-[.is-user]:[border-bottom-right-radius:0]">
+ <MessageResponse>
+ Yes, run the Get Weather block for San Francisco
+ </MessageResponse>
+ </MessageContent>
+ </Message>
+
+ <Message from="assistant">
+ <MessageContent className="text-[1rem] leading-relaxed group-[.is-assistant]:bg-transparent group-[.is-assistant]:text-slate-900">
+ <RunBlockTool
+ part={{
+ type: "tool-run_block",
+ toolCallId: uid(),
+ state: "output-available",
+ input: {
+ block_id: "block-1",
+ input_data: { city: "San Francisco" },
+ },
+ output: {
+ type: ResponseType.block_output,
+ block_id: "block-1",
+ block_name: "Get Weather",
+ message:
+ "Successfully fetched weather for San Francisco.",
+ outputs: {
+ temperature: ["68°F"],
+ condition: ["Foggy"],
+ humidity: ["85%"],
+ wind: ["12 mph W"],
+ },
+ },
+ }}
+ />
+
+ <MessageResponse>
+ The current weather in San Francisco is **68°F** and
+ **Foggy** with 85% humidity and winds from the west at
+ 12 mph.
+ </MessageResponse>
+ </MessageContent>
+ </Message>
+ </ConversationContent>
+ </Conversation>
+ </Section>
+ </div>
+ </div>
+ </div>
+ </CopilotChatActionsProvider>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/CreateAgent/CreateAgent.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/CreateAgent/CreateAgent.tsx
new file mode 100644
index 0000000000..5dc2f40dfe
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/CreateAgent/CreateAgent.tsx
@@ -0,0 +1,237 @@
+"use client";
+
+import { WarningDiamondIcon } from "@phosphor-icons/react";
+import type { ToolUIPart } from "ai";
+import { useCopilotChatActions } from "../../components/CopilotChatActionsProvider/useCopilotChatActions";
+import { MorphingTextAnimation } from "../../components/MorphingTextAnimation/MorphingTextAnimation";
+import { OrbitLoader } from "../../components/OrbitLoader/OrbitLoader";
+import { ProgressBar } from "../../components/ProgressBar/ProgressBar";
+import {
+ ContentCardDescription,
+ ContentCodeBlock,
+ ContentGrid,
+ ContentHint,
+ ContentLink,
+ ContentMessage,
+} from "../../components/ToolAccordion/AccordionContent";
+import { ToolAccordion } from "../../components/ToolAccordion/ToolAccordion";
+import { useAsymptoticProgress } from "../../hooks/useAsymptoticProgress";
+import {
+ ClarificationQuestionsCard,
+ ClarifyingQuestion,
+} from "./components/ClarificationQuestionsCard";
+import {
+ AccordionIcon,
+ formatMaybeJson,
+ getAnimationText,
+ getCreateAgentToolOutput,
+ isAgentPreviewOutput,
+ isAgentSavedOutput,
+ isClarificationNeededOutput,
+ isErrorOutput,
+ isOperationInProgressOutput,
+ isOperationPendingOutput,
+ isOperationStartedOutput,
+ ToolIcon,
+ truncateText,
+ type CreateAgentToolOutput,
+} from "./helpers";
+
+export interface CreateAgentToolPart {
+ type: string;
+ toolCallId: string;
+ state: ToolUIPart["state"];
+ input?: unknown;
+ output?: unknown;
+}
+
+interface Props {
+ part: CreateAgentToolPart;
+}
+
+function getAccordionMeta(output: CreateAgentToolOutput): {
+ icon: React.ReactNode;
+ title: React.ReactNode;
+ titleClassName?: string;
+ description?: string;
+} {
+ const icon = <AccordionIcon />;
+
+ if (isAgentSavedOutput(output)) {
+ return { icon, title: output.agent_name };
+ }
+ if (isAgentPreviewOutput(output)) {
+ return {
+ icon,
+ title: output.agent_name,
+ description: `${output.node_count} block${output.node_count === 1 ? "" : "s"}`,
+ };
+ }
+ if (isClarificationNeededOutput(output)) {
+ const questions = output.questions ?? [];
+ return {
+ icon,
+ title: "Needs clarification",
+ description: `${questions.length} question${questions.length === 1 ? "" : "s"}`,
+ };
+ }
+ if (
+ isOperationStartedOutput(output) ||
+ isOperationPendingOutput(output) ||
+ isOperationInProgressOutput(output)
+ ) {
+ return {
+ icon: <OrbitLoader size={32} />,
+ title: "Creating agent, this may take a few minutes. Sit back and relax.",
+ };
+ }
+ return {
+ icon: (
+ <WarningDiamondIcon size={32} weight="light" className="text-red-500" />
+ ),
+ title: "Error",
+ titleClassName: "text-red-500",
+ };
+}
+
+export function CreateAgentTool({ part }: Props) {
+ const text = getAnimationText(part);
+ const { onSend } = useCopilotChatActions();
+ const isStreaming =
+ part.state === "input-streaming" || part.state === "input-available";
+
+ const output = getCreateAgentToolOutput(part);
+ const isError =
+ part.state === "output-error" || (!!output && isErrorOutput(output));
+ const isOperating =
+ !!output &&
+ (isOperationStartedOutput(output) ||
+ isOperationPendingOutput(output) ||
+ isOperationInProgressOutput(output));
+ const progress = useAsymptoticProgress(isOperating);
+ const hasExpandableContent =
+ part.state === "output-available" &&
+ !!output &&
+ (isOperationStartedOutput(output) ||
+ isOperationPendingOutput(output) ||
+ isOperationInProgressOutput(output) ||
+ isAgentPreviewOutput(output) ||
+ isAgentSavedOutput(output) ||
+ isClarificationNeededOutput(output) ||
+ isErrorOutput(output));
+
+ function handleClarificationAnswers(answers: Record<string, string>) {
+ const questions =
+ output && isClarificationNeededOutput(output)
+ ? (output.questions ?? [])
+ : [];
+
+ const contextMessage = questions
+ .map((q) => {
+ const answer = answers[q.keyword] || "";
+ return `> ${q.question}\n\n${answer}`;
+ })
+ .join("\n\n");
+
+ onSend(
+ `**Here are my answers:**\n\n${contextMessage}\n\nPlease proceed with creating the agent.`,
+ );
+ }
+
+ return (
+ <div className="py-2">
+ <div className="flex items-center gap-2 text-sm text-muted-foreground">
+ <ToolIcon isStreaming={isStreaming} isError={isError} />
+ <MorphingTextAnimation
+ text={text}
+ className={isError ? "text-red-500" : undefined}
+ />
+ </div>
+
+ {hasExpandableContent && output && (
+ <ToolAccordion
+ {...getAccordionMeta(output)}
+ defaultExpanded={isOperating || isClarificationNeededOutput(output)}
+ >
+ {isOperating && (
+ <ContentGrid>
+ <ProgressBar value={progress} className="max-w-[280px]" />
+ <ContentHint>
+ This could take a few minutes, grab a coffee ☕
+ </ContentHint>
+ </ContentGrid>
+ )}
+
+ {isAgentSavedOutput(output) && (
+ <ContentGrid>
+ <ContentMessage>{output.message}</ContentMessage>
+ <div className="flex flex-wrap gap-2">
+ <ContentLink href={output.library_agent_link}>
+ Open in library
+ </ContentLink>
+ <ContentLink href={output.agent_page_link}>
+ Open in builder
+ </ContentLink>
+ </div>
+ <ContentCodeBlock>
+ {truncateText(
+ formatMaybeJson({ agent_id: output.agent_id }),
+ 800,
+ )}
+ </ContentCodeBlock>
+ </ContentGrid>
+ )}
+
+ {isAgentPreviewOutput(output) && (
+ <ContentGrid>
+ <ContentMessage>{output.message}</ContentMessage>
+ {output.description?.trim() && (
+ <ContentCardDescription>
+ {output.description}
+ </ContentCardDescription>
+ )}
+ <ContentCodeBlock>
+ {truncateText(formatMaybeJson(output.agent_json), 1600)}
+ </ContentCodeBlock>
+ </ContentGrid>
+ )}
+
+ {isClarificationNeededOutput(output) && (
+ <ClarificationQuestionsCard
+ questions={(output.questions ?? []).map((q) => {
+ const item: ClarifyingQuestion = {
+ question: q.question,
+ keyword: q.keyword,
+ };
+ const example =
+ typeof q.example === "string" && q.example.trim()
+ ? q.example.trim()
+ : null;
+ if (example) item.example = example;
+ return item;
+ })}
+ message={output.message}
+ onSubmitAnswers={handleClarificationAnswers}
+ />
+ )}
+
+ {isErrorOutput(output) && (
+ <ContentGrid>
+ <ContentMessage>{output.message}</ContentMessage>
+ {output.error && (
+ <ContentCodeBlock>
+ {formatMaybeJson(output.error)}
+ </ContentCodeBlock>
+ )}
+ {output.details && (
+ <ContentCodeBlock>
+ {formatMaybeJson(output.details)}
+ </ContentCodeBlock>
+ )}
+ </ContentGrid>
+ )}
+ </ToolAccordion>
+ )}
+ </div>
+ );
+}
diff --git a/autogpt_platform/frontend/src/components/contextual/Chat/components/ClarificationQuestionsWidget/ClarificationQuestionsWidget.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/CreateAgent/components/ClarificationQuestionsCard.tsx
similarity index 98%
rename from autogpt_platform/frontend/src/components/contextual/Chat/components/ClarificationQuestionsWidget/ClarificationQuestionsWidget.tsx
rename to autogpt_platform/frontend/src/app/(platform)/copilot/tools/CreateAgent/components/ClarificationQuestionsCard.tsx
index 3b225d1ef1..abcb04731e 100644
--- a/autogpt_platform/frontend/src/components/contextual/Chat/components/ClarificationQuestionsWidget/ClarificationQuestionsWidget.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/CreateAgent/components/ClarificationQuestionsCard.tsx
@@ -6,7 +6,7 @@ import { Input } from "@/components/atoms/Input/Input";
import { Text } from "@/components/atoms/Text/Text";
import { cn } from "@/lib/utils";
import { CheckCircleIcon, QuestionIcon } from "@phosphor-icons/react";
-import { useState, useEffect, useRef } from "react";
+import { useEffect, useRef, useState } from "react";
export interface ClarifyingQuestion {
question: string;
@@ -24,12 +24,7 @@ interface Props {
className?: string;
}
-function getStorageKey(sessionId?: string): string | null {
- if (!sessionId) return null;
- return `clarification_answers_${sessionId}`;
-}
-
-export function ClarificationQuestionsWidget({
+export function ClarificationQuestionsCard({
questions,
message,
sessionId,
@@ -241,3 +236,8 @@ export function ClarificationQuestionsWidget({
</div>
);
}
+
+function getStorageKey(sessionId?: string): string | null {
+ if (!sessionId) return null;
+ return `clarification_answers_${sessionId}`;
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/CreateAgent/helpers.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/CreateAgent/helpers.tsx
new file mode 100644
index 0000000000..bd47eac051
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/CreateAgent/helpers.tsx
@@ -0,0 +1,186 @@
+import type { AgentPreviewResponse } from "@/app/api/__generated__/models/agentPreviewResponse";
+import type { AgentSavedResponse } from "@/app/api/__generated__/models/agentSavedResponse";
+import type { ClarificationNeededResponse } from "@/app/api/__generated__/models/clarificationNeededResponse";
+import type { ErrorResponse } from "@/app/api/__generated__/models/errorResponse";
+import type { OperationInProgressResponse } from "@/app/api/__generated__/models/operationInProgressResponse";
+import type { OperationPendingResponse } from "@/app/api/__generated__/models/operationPendingResponse";
+import type { OperationStartedResponse } from "@/app/api/__generated__/models/operationStartedResponse";
+import { ResponseType } from "@/app/api/__generated__/models/responseType";
+import {
+ PlusCircleIcon,
+ PlusIcon,
+ WarningDiamondIcon,
+} from "@phosphor-icons/react";
+import type { ToolUIPart } from "ai";
+import { OrbitLoader } from "../../components/OrbitLoader/OrbitLoader";
+
+export type CreateAgentToolOutput =
+ | OperationStartedResponse
+ | OperationPendingResponse
+ | OperationInProgressResponse
+ | AgentPreviewResponse
+ | AgentSavedResponse
+ | ClarificationNeededResponse
+ | ErrorResponse;
+
+function parseOutput(output: unknown): CreateAgentToolOutput | null {
+ if (!output) return null;
+ if (typeof output === "string") {
+ const trimmed = output.trim();
+ if (!trimmed) return null;
+ try {
+ return parseOutput(JSON.parse(trimmed) as unknown);
+ } catch {
+ return null;
+ }
+ }
+ if (typeof output === "object") {
+ const type = (output as { type?: unknown }).type;
+ if (
+ type === ResponseType.operation_started ||
+ type === ResponseType.operation_pending ||
+ type === ResponseType.operation_in_progress ||
+ type === ResponseType.agent_preview ||
+ type === ResponseType.agent_saved ||
+ type === ResponseType.clarification_needed ||
+ type === ResponseType.error
+ ) {
+ return output as CreateAgentToolOutput;
+ }
+ if ("operation_id" in output && "tool_name" in output)
+ return output as OperationStartedResponse | OperationPendingResponse;
+ if ("tool_call_id" in output) return output as OperationInProgressResponse;
+ if ("agent_json" in output && "agent_name" in output)
+ return output as AgentPreviewResponse;
+ if ("agent_id" in output && "library_agent_id" in output)
+ return output as AgentSavedResponse;
+ if ("questions" in output) return output as ClarificationNeededResponse;
+ if ("error" in output || "details" in output)
+ return output as ErrorResponse;
+ }
+ return null;
+}
+
+export function getCreateAgentToolOutput(
+ part: unknown,
+): CreateAgentToolOutput | null {
+ if (!part || typeof part !== "object") return null;
+ return parseOutput((part as { output?: unknown }).output);
+}
+
+export function isOperationStartedOutput(
+ output: CreateAgentToolOutput,
+): output is OperationStartedResponse {
+ return (
+ output.type === ResponseType.operation_started ||
+ ("operation_id" in output && "tool_name" in output)
+ );
+}
+
+export function isOperationPendingOutput(
+ output: CreateAgentToolOutput,
+): output is OperationPendingResponse {
+ return output.type === ResponseType.operation_pending;
+}
+
+export function isOperationInProgressOutput(
+ output: CreateAgentToolOutput,
+): output is OperationInProgressResponse {
+ return (
+ output.type === ResponseType.operation_in_progress ||
+ "tool_call_id" in output
+ );
+}
+
+export function isAgentPreviewOutput(
+ output: CreateAgentToolOutput,
+): output is AgentPreviewResponse {
+ return output.type === ResponseType.agent_preview || "agent_json" in output;
+}
+
+export function isAgentSavedOutput(
+ output: CreateAgentToolOutput,
+): output is AgentSavedResponse {
+ return (
+ output.type === ResponseType.agent_saved || "agent_page_link" in output
+ );
+}
+
+export function isClarificationNeededOutput(
+ output: CreateAgentToolOutput,
+): output is ClarificationNeededResponse {
+ return (
+ output.type === ResponseType.clarification_needed || "questions" in output
+ );
+}
+
+export function isErrorOutput(
+ output: CreateAgentToolOutput,
+): output is ErrorResponse {
+ return output.type === ResponseType.error || "error" in output;
+}
+
+export function getAnimationText(part: {
+ state: ToolUIPart["state"];
+ input?: unknown;
+ output?: unknown;
+}): string {
+ switch (part.state) {
+ case "input-streaming":
+ case "input-available":
+ return "Creating a new agent";
+ case "output-available": {
+ const output = parseOutput(part.output);
+ if (!output) return "Creating a new agent";
+ if (isOperationStartedOutput(output)) return "Agent creation started";
+ if (isOperationPendingOutput(output)) return "Agent creation in progress";
+ if (isOperationInProgressOutput(output))
+ return "Agent creation already in progress";
+ if (isAgentSavedOutput(output)) return `Saved "${output.agent_name}"`;
+ if (isAgentPreviewOutput(output)) return `Preview "${output.agent_name}"`;
+ if (isClarificationNeededOutput(output)) return "Needs clarification";
+ return "Error creating agent";
+ }
+ case "output-error":
+ return "Error creating agent";
+ default:
+ return "Creating a new agent";
+ }
+}
+
+export function ToolIcon({
+ isStreaming,
+ isError,
+}: {
+ isStreaming?: boolean;
+ isError?: boolean;
+}) {
+ if (isError) {
+ return (
+ <WarningDiamondIcon size={14} weight="regular" className="text-red-500" />
+ );
+ }
+ if (isStreaming) {
+ return <OrbitLoader size={24} />;
+ }
+ return <PlusIcon size={14} weight="regular" className="text-neutral-400" />;
+}
+
+export function AccordionIcon() {
+ return <PlusCircleIcon size={32} weight="light" />;
+}
+
+export function formatMaybeJson(value: unknown): string {
+ if (typeof value === "string") return value;
+ try {
+ return JSON.stringify(value, null, 2);
+ } catch {
+ return String(value);
+ }
+}
+
+export function truncateText(text: string, maxChars: number): string {
+ const trimmed = text.trim();
+ if (trimmed.length <= maxChars) return trimmed;
+ return `${trimmed.slice(0, maxChars).trimEnd()}…`;
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/EditAgent/EditAgent.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/EditAgent/EditAgent.tsx
new file mode 100644
index 0000000000..3beb9e7e1e
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/EditAgent/EditAgent.tsx
@@ -0,0 +1,234 @@
+"use client";
+
+import { WarningDiamondIcon } from "@phosphor-icons/react";
+import type { ToolUIPart } from "ai";
+import { useCopilotChatActions } from "../../components/CopilotChatActionsProvider/useCopilotChatActions";
+import { MorphingTextAnimation } from "../../components/MorphingTextAnimation/MorphingTextAnimation";
+import { OrbitLoader } from "../../components/OrbitLoader/OrbitLoader";
+import { ProgressBar } from "../../components/ProgressBar/ProgressBar";
+import {
+ ContentCardDescription,
+ ContentCodeBlock,
+ ContentGrid,
+ ContentHint,
+ ContentLink,
+ ContentMessage,
+} from "../../components/ToolAccordion/AccordionContent";
+import { ToolAccordion } from "../../components/ToolAccordion/ToolAccordion";
+import { useAsymptoticProgress } from "../../hooks/useAsymptoticProgress";
+import {
+ ClarificationQuestionsCard,
+ ClarifyingQuestion,
+} from "../CreateAgent/components/ClarificationQuestionsCard";
+import {
+ AccordionIcon,
+ formatMaybeJson,
+ getAnimationText,
+ getEditAgentToolOutput,
+ isAgentPreviewOutput,
+ isAgentSavedOutput,
+ isClarificationNeededOutput,
+ isErrorOutput,
+ isOperationInProgressOutput,
+ isOperationPendingOutput,
+ isOperationStartedOutput,
+ ToolIcon,
+ truncateText,
+ type EditAgentToolOutput,
+} from "./helpers";
+
+export interface EditAgentToolPart {
+ type: string;
+ toolCallId: string;
+ state: ToolUIPart["state"];
+ input?: unknown;
+ output?: unknown;
+}
+
+interface Props {
+ part: EditAgentToolPart;
+}
+
+function getAccordionMeta(output: EditAgentToolOutput): {
+ icon: React.ReactNode;
+ title: string;
+ titleClassName?: string;
+ description?: string;
+} {
+ const icon = <AccordionIcon />;
+
+ if (isAgentSavedOutput(output)) {
+ return { icon, title: output.agent_name };
+ }
+ if (isAgentPreviewOutput(output)) {
+ return {
+ icon,
+ title: output.agent_name,
+ description: `${output.node_count} block${output.node_count === 1 ? "" : "s"}`,
+ };
+ }
+ if (isClarificationNeededOutput(output)) {
+ const questions = output.questions ?? [];
+ return {
+ icon,
+ title: "Needs clarification",
+ description: `${questions.length} question${questions.length === 1 ? "" : "s"}`,
+ };
+ }
+ if (
+ isOperationStartedOutput(output) ||
+ isOperationPendingOutput(output) ||
+ isOperationInProgressOutput(output)
+ ) {
+ return { icon: <OrbitLoader size={32} />, title: "Editing agent" };
+ }
+ return {
+ icon: (
+ <WarningDiamondIcon size={32} weight="light" className="text-red-500" />
+ ),
+ title: "Error",
+ titleClassName: "text-red-500",
+ };
+}
+
+export function EditAgentTool({ part }: Props) {
+ const text = getAnimationText(part);
+ const { onSend } = useCopilotChatActions();
+ const isStreaming =
+ part.state === "input-streaming" || part.state === "input-available";
+
+ const output = getEditAgentToolOutput(part);
+ const isError =
+ part.state === "output-error" || (!!output && isErrorOutput(output));
+ const isOperating =
+ !!output &&
+ (isOperationStartedOutput(output) ||
+ isOperationPendingOutput(output) ||
+ isOperationInProgressOutput(output));
+ const progress = useAsymptoticProgress(isOperating);
+ const hasExpandableContent =
+ part.state === "output-available" &&
+ !!output &&
+ (isOperationStartedOutput(output) ||
+ isOperationPendingOutput(output) ||
+ isOperationInProgressOutput(output) ||
+ isAgentPreviewOutput(output) ||
+ isAgentSavedOutput(output) ||
+ isClarificationNeededOutput(output) ||
+ isErrorOutput(output));
+
+ function handleClarificationAnswers(answers: Record<string, string>) {
+ const questions =
+ output && isClarificationNeededOutput(output)
+ ? (output.questions ?? [])
+ : [];
+
+ const contextMessage = questions
+ .map((q) => {
+ const answer = answers[q.keyword] || "";
+ return `> ${q.question}\n\n${answer}`;
+ })
+ .join("\n\n");
+
+ onSend(
+ `**Here are my answers:**\n\n${contextMessage}\n\nPlease proceed with editing the agent.`,
+ );
+ }
+
+ return (
+ <div className="py-2">
+ <div className="flex items-center gap-2 text-sm text-muted-foreground">
+ <ToolIcon isStreaming={isStreaming} isError={isError} />
+ <MorphingTextAnimation
+ text={text}
+ className={isError ? "text-red-500" : undefined}
+ />
+ </div>
+
+ {hasExpandableContent && output && (
+ <ToolAccordion
+ {...getAccordionMeta(output)}
+ defaultExpanded={isOperating || isClarificationNeededOutput(output)}
+ >
+ {isOperating && (
+ <ContentGrid>
+ <ProgressBar value={progress} className="max-w-[280px]" />
+ <ContentHint>
+ This could take a few minutes, grab a coffee ☕
+ </ContentHint>
+ </ContentGrid>
+ )}
+
+ {isAgentSavedOutput(output) && (
+ <ContentGrid>
+ <ContentMessage>{output.message}</ContentMessage>
+ <div className="flex flex-wrap gap-2">
+ <ContentLink href={output.library_agent_link}>
+ Open in library
+ </ContentLink>
+ <ContentLink href={output.agent_page_link}>
+ Open in builder
+ </ContentLink>
+ </div>
+ <ContentCodeBlock>
+ {truncateText(
+ formatMaybeJson({ agent_id: output.agent_id }),
+ 800,
+ )}
+ </ContentCodeBlock>
+ </ContentGrid>
+ )}
+
+ {isAgentPreviewOutput(output) && (
+ <ContentGrid>
+ <ContentMessage>{output.message}</ContentMessage>
+ {output.description?.trim() && (
+ <ContentCardDescription>
+ {output.description}
+ </ContentCardDescription>
+ )}
+ <ContentCodeBlock>
+ {truncateText(formatMaybeJson(output.agent_json), 1600)}
+ </ContentCodeBlock>
+ </ContentGrid>
+ )}
+
+ {isClarificationNeededOutput(output) && (
+ <ClarificationQuestionsCard
+ questions={(output.questions ?? []).map((q) => {
+ const item: ClarifyingQuestion = {
+ question: q.question,
+ keyword: q.keyword,
+ };
+ const example =
+ typeof q.example === "string" && q.example.trim()
+ ? q.example.trim()
+ : null;
+ if (example) item.example = example;
+ return item;
+ })}
+ message={output.message}
+ onSubmitAnswers={handleClarificationAnswers}
+ />
+ )}
+
+ {isErrorOutput(output) && (
+ <ContentGrid>
+ <ContentMessage>{output.message}</ContentMessage>
+ {output.error && (
+ <ContentCodeBlock>
+ {formatMaybeJson(output.error)}
+ </ContentCodeBlock>
+ )}
+ {output.details && (
+ <ContentCodeBlock>
+ {formatMaybeJson(output.details)}
+ </ContentCodeBlock>
+ )}
+ </ContentGrid>
+ )}
+ </ToolAccordion>
+ )}
+ </div>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/EditAgent/helpers.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/EditAgent/helpers.tsx
new file mode 100644
index 0000000000..a0db50cddc
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/EditAgent/helpers.tsx
@@ -0,0 +1,188 @@
+import type { AgentPreviewResponse } from "@/app/api/__generated__/models/agentPreviewResponse";
+import type { AgentSavedResponse } from "@/app/api/__generated__/models/agentSavedResponse";
+import type { ClarificationNeededResponse } from "@/app/api/__generated__/models/clarificationNeededResponse";
+import type { ErrorResponse } from "@/app/api/__generated__/models/errorResponse";
+import type { OperationInProgressResponse } from "@/app/api/__generated__/models/operationInProgressResponse";
+import type { OperationPendingResponse } from "@/app/api/__generated__/models/operationPendingResponse";
+import type { OperationStartedResponse } from "@/app/api/__generated__/models/operationStartedResponse";
+import { ResponseType } from "@/app/api/__generated__/models/responseType";
+import {
+ NotePencilIcon,
+ PencilLineIcon,
+ WarningDiamondIcon,
+} from "@phosphor-icons/react";
+import type { ToolUIPart } from "ai";
+import { OrbitLoader } from "../../components/OrbitLoader/OrbitLoader";
+
+export type EditAgentToolOutput =
+ | OperationStartedResponse
+ | OperationPendingResponse
+ | OperationInProgressResponse
+ | AgentPreviewResponse
+ | AgentSavedResponse
+ | ClarificationNeededResponse
+ | ErrorResponse;
+
+function parseOutput(output: unknown): EditAgentToolOutput | null {
+ if (!output) return null;
+ if (typeof output === "string") {
+ const trimmed = output.trim();
+ if (!trimmed) return null;
+ try {
+ return parseOutput(JSON.parse(trimmed) as unknown);
+ } catch {
+ return null;
+ }
+ }
+ if (typeof output === "object") {
+ const type = (output as { type?: unknown }).type;
+ if (
+ type === ResponseType.operation_started ||
+ type === ResponseType.operation_pending ||
+ type === ResponseType.operation_in_progress ||
+ type === ResponseType.agent_preview ||
+ type === ResponseType.agent_saved ||
+ type === ResponseType.clarification_needed ||
+ type === ResponseType.error
+ ) {
+ return output as EditAgentToolOutput;
+ }
+ if ("operation_id" in output && "tool_name" in output)
+ return output as OperationStartedResponse | OperationPendingResponse;
+ if ("tool_call_id" in output) return output as OperationInProgressResponse;
+ if ("agent_json" in output && "agent_name" in output)
+ return output as AgentPreviewResponse;
+ if ("agent_id" in output && "library_agent_id" in output)
+ return output as AgentSavedResponse;
+ if ("questions" in output) return output as ClarificationNeededResponse;
+ if ("error" in output || "details" in output)
+ return output as ErrorResponse;
+ }
+ return null;
+}
+
+export function getEditAgentToolOutput(
+ part: unknown,
+): EditAgentToolOutput | null {
+ if (!part || typeof part !== "object") return null;
+ return parseOutput((part as { output?: unknown }).output);
+}
+
+export function isOperationStartedOutput(
+ output: EditAgentToolOutput,
+): output is OperationStartedResponse {
+ return (
+ output.type === ResponseType.operation_started ||
+ ("operation_id" in output && "tool_name" in output)
+ );
+}
+
+export function isOperationPendingOutput(
+ output: EditAgentToolOutput,
+): output is OperationPendingResponse {
+ return output.type === ResponseType.operation_pending;
+}
+
+export function isOperationInProgressOutput(
+ output: EditAgentToolOutput,
+): output is OperationInProgressResponse {
+ return (
+ output.type === ResponseType.operation_in_progress ||
+ "tool_call_id" in output
+ );
+}
+
+export function isAgentPreviewOutput(
+ output: EditAgentToolOutput,
+): output is AgentPreviewResponse {
+ return output.type === ResponseType.agent_preview || "agent_json" in output;
+}
+
+export function isAgentSavedOutput(
+ output: EditAgentToolOutput,
+): output is AgentSavedResponse {
+ return (
+ output.type === ResponseType.agent_saved || "agent_page_link" in output
+ );
+}
+
+export function isClarificationNeededOutput(
+ output: EditAgentToolOutput,
+): output is ClarificationNeededResponse {
+ return (
+ output.type === ResponseType.clarification_needed || "questions" in output
+ );
+}
+
+export function isErrorOutput(
+ output: EditAgentToolOutput,
+): output is ErrorResponse {
+ return output.type === ResponseType.error || "error" in output;
+}
+
+export function getAnimationText(part: {
+ state: ToolUIPart["state"];
+ input?: unknown;
+ output?: unknown;
+}): string {
+ switch (part.state) {
+ case "input-streaming":
+ case "input-available":
+ return "Editing the agent";
+ case "output-available": {
+ const output = parseOutput(part.output);
+ if (!output) return "Editing the agent";
+ if (isOperationStartedOutput(output)) return "Agent update started";
+ if (isOperationPendingOutput(output)) return "Agent update in progress";
+ if (isOperationInProgressOutput(output))
+ return "Agent update already in progress";
+ if (isAgentSavedOutput(output)) return `Saved "${output.agent_name}"`;
+ if (isAgentPreviewOutput(output)) return `Preview "${output.agent_name}"`;
+ if (isClarificationNeededOutput(output)) return "Needs clarification";
+ return "Error editing agent";
+ }
+ case "output-error":
+ return "Error editing agent";
+ default:
+ return "Editing the agent";
+ }
+}
+
+export function ToolIcon({
+ isStreaming,
+ isError,
+}: {
+ isStreaming?: boolean;
+ isError?: boolean;
+}) {
+ if (isError) {
+ return (
+ <WarningDiamondIcon size={14} weight="regular" className="text-red-500" />
+ );
+ }
+ if (isStreaming) {
+ return <OrbitLoader size={24} />;
+ }
+ return (
+ <PencilLineIcon size={14} weight="regular" className="text-neutral-400" />
+ );
+}
+
+export function AccordionIcon() {
+ return <NotePencilIcon size={32} weight="light" />;
+}
+
+export function formatMaybeJson(value: unknown): string {
+ if (typeof value === "string") return value;
+ try {
+ return JSON.stringify(value, null, 2);
+ } catch {
+ return String(value);
+ }
+}
+
+export function truncateText(text: string, maxChars: number): string {
+ const trimmed = text.trim();
+ if (trimmed.length <= maxChars) return trimmed;
+ return `${trimmed.slice(0, maxChars).trimEnd()}…`;
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/FindAgents/FindAgents.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/FindAgents/FindAgents.tsx
new file mode 100644
index 0000000000..4f0068b2c5
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/FindAgents/FindAgents.tsx
@@ -0,0 +1,127 @@
+"use client";
+
+import { ToolUIPart } from "ai";
+import { MorphingTextAnimation } from "../../components/MorphingTextAnimation/MorphingTextAnimation";
+import {
+ ContentBadge,
+ ContentCard,
+ ContentCardDescription,
+ ContentCardHeader,
+ ContentCardTitle,
+ ContentGrid,
+ ContentLink,
+} from "../../components/ToolAccordion/AccordionContent";
+import { ToolAccordion } from "../../components/ToolAccordion/ToolAccordion";
+import {
+ AccordionIcon,
+ getAgentHref,
+ getAnimationText,
+ getFindAgentsOutput,
+ getSourceLabelFromToolType,
+ isAgentsFoundOutput,
+ isErrorOutput,
+ ToolIcon,
+} from "./helpers";
+
+export interface FindAgentsToolPart {
+ type: string;
+ toolCallId: string;
+ state: ToolUIPart["state"];
+ input?: unknown;
+ output?: unknown;
+}
+
+interface Props {
+ part: FindAgentsToolPart;
+}
+
+export function FindAgentsTool({ part }: Props) {
+ const text = getAnimationText(part);
+ const output = getFindAgentsOutput(part);
+ const isStreaming =
+ part.state === "input-streaming" || part.state === "input-available";
+ const isError =
+ part.state === "output-error" || (!!output && isErrorOutput(output));
+
+ const query =
+ typeof part.input === "object" && part.input !== null
+ ? String((part.input as { query?: unknown }).query ?? "").trim()
+ : "";
+
+ const agentsFoundOutput =
+ part.state === "output-available" && output && isAgentsFoundOutput(output)
+ ? output
+ : null;
+
+ const hasAgents =
+ !!agentsFoundOutput &&
+ agentsFoundOutput.agents.length > 0 &&
+ (typeof agentsFoundOutput.count !== "number" ||
+ agentsFoundOutput.count > 0);
+ const totalCount = agentsFoundOutput ? agentsFoundOutput.count : 0;
+ const { source } = getSourceLabelFromToolType(part.type);
+ const scopeText =
+ source === "library"
+ ? "in your library"
+ : source === "marketplace"
+ ? "in marketplace"
+ : "";
+ const accordionDescription = `Found ${totalCount}${scopeText ? ` ${scopeText}` : ""}${
+ query ? ` for "${query}"` : ""
+ }`;
+
+ return (
+ <div className="py-2">
+ <div className="flex items-center gap-2 text-sm text-muted-foreground">
+ <ToolIcon
+ toolType={part.type}
+ isStreaming={isStreaming}
+ isError={isError}
+ />
+ <MorphingTextAnimation
+ text={text}
+ className={isError ? "text-red-500" : undefined}
+ />
+ </div>
+
+ {hasAgents && agentsFoundOutput && (
+ <ToolAccordion
+ icon={<AccordionIcon toolType={part.type} />}
+ title="Agent results"
+ description={accordionDescription}
+ >
+ <ContentGrid className="sm:grid-cols-2">
+ {agentsFoundOutput.agents.map((agent) => {
+ const href = getAgentHref(agent);
+ const agentSource =
+ agent.source === "library"
+ ? "Library"
+ : agent.source === "marketplace"
+ ? "Marketplace"
+ : null;
+ return (
+ <ContentCard key={agent.id}>
+ <ContentCardHeader
+ action={
+ href ? <ContentLink href={href}>Open</ContentLink> : null
+ }
+ >
+ <div className="flex items-center gap-2">
+ <ContentCardTitle>{agent.name}</ContentCardTitle>
+ {agentSource && (
+ <ContentBadge>{agentSource}</ContentBadge>
+ )}
+ </div>
+ <ContentCardDescription className="mt-1 line-clamp-2">
+ {agent.description}
+ </ContentCardDescription>
+ </ContentCardHeader>
+ </ContentCard>
+ );
+ })}
+ </ContentGrid>
+ </ToolAccordion>
+ )}
+ </div>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/FindAgents/helpers.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/FindAgents/helpers.tsx
new file mode 100644
index 0000000000..f253947953
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/FindAgents/helpers.tsx
@@ -0,0 +1,187 @@
+import type { AgentInfo } from "@/app/api/__generated__/models/agentInfo";
+import type { AgentsFoundResponse } from "@/app/api/__generated__/models/agentsFoundResponse";
+import type { ErrorResponse } from "@/app/api/__generated__/models/errorResponse";
+import type { NoResultsResponse } from "@/app/api/__generated__/models/noResultsResponse";
+import { ResponseType } from "@/app/api/__generated__/models/responseType";
+import {
+ FolderOpenIcon,
+ MagnifyingGlassIcon,
+ SquaresFourIcon,
+ StorefrontIcon,
+} from "@phosphor-icons/react";
+import { ToolUIPart } from "ai";
+
+export interface FindAgentInput {
+ query: string;
+}
+
+export type FindAgentsOutput =
+ | AgentsFoundResponse
+ | NoResultsResponse
+ | ErrorResponse;
+
+export type FindAgentsToolType =
+ | "tool-find_agent"
+ | "tool-find_library_agent"
+ | (string & {});
+
+function parseOutput(output: unknown): FindAgentsOutput | null {
+ if (!output) return null;
+ if (typeof output === "string") {
+ const trimmed = output.trim();
+ if (!trimmed) return null;
+ try {
+ return parseOutput(JSON.parse(trimmed) as unknown);
+ } catch {
+ return null;
+ }
+ }
+ if (typeof output === "object") {
+ const type = (output as { type?: unknown }).type;
+ if (
+ type === ResponseType.agents_found ||
+ type === ResponseType.no_results ||
+ type === ResponseType.error
+ ) {
+ return output as FindAgentsOutput;
+ }
+ if ("agents" in output && "count" in output)
+ return output as AgentsFoundResponse;
+ if ("suggestions" in output && !("error" in output))
+ return output as NoResultsResponse;
+ if ("error" in output || "details" in output)
+ return output as ErrorResponse;
+ }
+ return null;
+}
+
+export function getFindAgentsOutput(part: unknown): FindAgentsOutput | null {
+ if (!part || typeof part !== "object") return null;
+ return parseOutput((part as { output?: unknown }).output);
+}
+
+export function isAgentsFoundOutput(
+ output: FindAgentsOutput,
+): output is AgentsFoundResponse {
+ return output.type === ResponseType.agents_found || "agents" in output;
+}
+
+export function isNoResultsOutput(
+ output: FindAgentsOutput,
+): output is NoResultsResponse {
+ return (
+ output.type === ResponseType.no_results ||
+ ("suggestions" in output && !("error" in output))
+ );
+}
+
+export function isErrorOutput(
+ output: FindAgentsOutput,
+): output is ErrorResponse {
+ return output.type === ResponseType.error || "error" in output;
+}
+
+export function getSourceLabelFromToolType(toolType?: FindAgentsToolType): {
+ source: "marketplace" | "library" | "unknown";
+ label: string;
+} {
+ if (toolType === "tool-find_library_agent") {
+ return { source: "library", label: "Library" };
+ }
+ if (toolType === "tool-find_agent") {
+ return { source: "marketplace", label: "Marketplace" };
+ }
+ return { source: "unknown", label: "Agents" };
+}
+
+export function getAnimationText(part: {
+ type?: FindAgentsToolType;
+ state: ToolUIPart["state"];
+ input?: unknown;
+ output?: unknown;
+}): string {
+ const { source } = getSourceLabelFromToolType(part.type);
+ const query = (part.input as FindAgentInput | undefined)?.query?.trim();
+
+ // Action phrase matching legacy ToolCallMessage
+ const actionPhrase =
+ source === "library"
+ ? "Looking for library agents"
+ : "Looking for agents in the marketplace";
+
+ const queryText = query ? ` matching "${query}"` : "";
+
+ switch (part.state) {
+ case "input-streaming":
+ case "input-available":
+ return `${actionPhrase}${queryText}`;
+
+ case "output-available": {
+ const output = parseOutput(part.output);
+ if (!output) {
+ return `${actionPhrase}${queryText}`;
+ }
+ if (isNoResultsOutput(output)) {
+ return `No agents found${queryText}`;
+ }
+ if (isAgentsFoundOutput(output)) {
+ const count = output.count ?? output.agents?.length ?? 0;
+ return `Found ${count} agent${count === 1 ? "" : "s"}${queryText}`;
+ }
+ if (isErrorOutput(output)) {
+ return `Error finding agents${queryText}`;
+ }
+ return `${actionPhrase}${queryText}`;
+ }
+
+ case "output-error":
+ return `Error finding agents${queryText}`;
+
+ default:
+ return actionPhrase;
+ }
+}
+
+export function getAgentHref(agent: AgentInfo): string | null {
+ if (agent.source === "library") {
+ return `/library/agents/${encodeURIComponent(agent.id)}`;
+ }
+
+ const [creator, slug, ...rest] = agent.id.split("/");
+ if (!creator || !slug || rest.length > 0) return null;
+ return `/marketplace/agent/${encodeURIComponent(creator)}/${encodeURIComponent(slug)}`;
+}
+
+export function ToolIcon({
+ toolType,
+ isStreaming,
+ isError,
+}: {
+ toolType?: FindAgentsToolType;
+ isStreaming?: boolean;
+ isError?: boolean;
+}) {
+ const { source } = getSourceLabelFromToolType(toolType);
+ const IconComponent =
+ source === "library" ? MagnifyingGlassIcon : SquaresFourIcon;
+
+ return (
+ <IconComponent
+ size={14}
+ weight="regular"
+ className={
+ isError
+ ? "text-red-500"
+ : isStreaming
+ ? "text-neutral-500"
+ : "text-neutral-400"
+ }
+ />
+ );
+}
+
+export function AccordionIcon({ toolType }: { toolType?: FindAgentsToolType }) {
+ const { source } = getSourceLabelFromToolType(toolType);
+ const IconComponent = source === "library" ? FolderOpenIcon : StorefrontIcon;
+ return <IconComponent size={32} weight="light" />;
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/FindBlocks/FindBlocks.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/FindBlocks/FindBlocks.tsx
new file mode 100644
index 0000000000..3684a2da14
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/FindBlocks/FindBlocks.tsx
@@ -0,0 +1,92 @@
+"use client";
+
+import { MorphingTextAnimation } from "../../components/MorphingTextAnimation/MorphingTextAnimation";
+import { ToolAccordion } from "../../components/ToolAccordion/ToolAccordion";
+import {
+ ContentCard,
+ ContentCardDescription,
+ ContentCardTitle,
+} from "../../components/ToolAccordion/AccordionContent";
+import type { BlockListResponse } from "@/app/api/__generated__/models/blockListResponse";
+import type { BlockInfoSummary } from "@/app/api/__generated__/models/blockInfoSummary";
+import { ToolUIPart } from "ai";
+import { HorizontalScroll } from "@/app/(platform)/build/components/NewControlPanel/NewBlockMenu/HorizontalScroll";
+import {
+ AccordionIcon,
+ getAnimationText,
+ parseOutput,
+ ToolIcon,
+} from "./helpers";
+
+export interface FindBlockInput {
+ query: string;
+}
+
+export type FindBlockOutput = BlockListResponse;
+
+export interface FindBlockToolPart {
+ type: string;
+ toolName?: string;
+ toolCallId: string;
+ state: ToolUIPart["state"];
+ input?: FindBlockInput | unknown;
+ output?: string | FindBlockOutput | unknown;
+ title?: string;
+}
+
+interface Props {
+ part: FindBlockToolPart;
+}
+
+function BlockCard({ block }: { block: BlockInfoSummary }) {
+ return (
+ <ContentCard className="w-48 shrink-0">
+ <ContentCardTitle>{block.name}</ContentCardTitle>
+ <ContentCardDescription className="mt-1 line-clamp-2">
+ {block.description}
+ </ContentCardDescription>
+ </ContentCard>
+ );
+}
+
+export function FindBlocksTool({ part }: Props) {
+ const text = getAnimationText(part);
+ const isStreaming =
+ part.state === "input-streaming" || part.state === "input-available";
+ const isError = part.state === "output-error";
+
+ const parsed =
+ part.state === "output-available" ? parseOutput(part.output) : null;
+ const hasBlocks = !!parsed && parsed.blocks.length > 0;
+
+ const query = (part.input as FindBlockInput | undefined)?.query?.trim();
+ const accordionDescription = parsed
+ ? `Found ${parsed.count} block${parsed.count === 1 ? "" : "s"}${query ? ` for "${query}"` : ""}`
+ : undefined;
+
+ return (
+ <div className="py-2">
+ <div className="flex items-center gap-2 text-sm text-muted-foreground">
+ <ToolIcon isStreaming={isStreaming} isError={isError} />
+ <MorphingTextAnimation
+ text={text}
+ className={isError ? "text-red-500" : undefined}
+ />
+ </div>
+
+ {hasBlocks && parsed && (
+ <ToolAccordion
+ icon={<AccordionIcon />}
+ title="Block results"
+ description={accordionDescription}
+ >
+ <HorizontalScroll dependencyList={[parsed.blocks.length]}>
+ {parsed.blocks.map((block) => (
+ <BlockCard key={block.id} block={block} />
+ ))}
+ </HorizontalScroll>
+ </ToolAccordion>
+ )}
+ </div>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/FindBlocks/helpers.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/FindBlocks/helpers.tsx
new file mode 100644
index 0000000000..eaebe98ea5
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/FindBlocks/helpers.tsx
@@ -0,0 +1,75 @@
+import type { BlockListResponse } from "@/app/api/__generated__/models/blockListResponse";
+import { ResponseType } from "@/app/api/__generated__/models/responseType";
+import { CubeIcon, PackageIcon } from "@phosphor-icons/react";
+import { FindBlockInput, FindBlockToolPart } from "./FindBlocks";
+
+export function parseOutput(output: unknown): BlockListResponse | null {
+ if (!output) return null;
+ if (typeof output === "string") {
+ const trimmed = output.trim();
+ if (!trimmed) return null;
+ try {
+ return parseOutput(JSON.parse(trimmed) as unknown);
+ } catch {
+ return null;
+ }
+ }
+ if (typeof output === "object") {
+ const type = (output as { type?: unknown }).type;
+ if (type === ResponseType.block_list || "blocks" in output) {
+ return output as BlockListResponse;
+ }
+ }
+ return null;
+}
+
+export function getAnimationText(part: FindBlockToolPart): string {
+ const query = (part.input as FindBlockInput | undefined)?.query?.trim();
+ const queryText = query ? ` matching "${query}"` : "";
+
+ switch (part.state) {
+ case "input-streaming":
+ case "input-available":
+ return `Searching for blocks${queryText}`;
+
+ case "output-available": {
+ const parsed = parseOutput(part.output);
+ if (parsed) {
+ return `Found ${parsed.count} block${parsed.count === 1 ? "" : "s"}${queryText}`;
+ }
+ return `Searching for blocks${queryText}`;
+ }
+
+ case "output-error":
+ return `Error finding blocks${queryText}`;
+
+ default:
+ return "Searching for blocks";
+ }
+}
+
+export function ToolIcon({
+ isStreaming,
+ isError,
+}: {
+ isStreaming?: boolean;
+ isError?: boolean;
+}) {
+ return (
+ <PackageIcon
+ size={14}
+ weight="regular"
+ className={
+ isError
+ ? "text-red-500"
+ : isStreaming
+ ? "text-neutral-500"
+ : "text-neutral-400"
+ }
+ />
+ );
+}
+
+export function AccordionIcon() {
+ return <CubeIcon size={32} weight="light" />;
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunAgent/RunAgent.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunAgent/RunAgent.tsx
new file mode 100644
index 0000000000..51044848b9
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunAgent/RunAgent.tsx
@@ -0,0 +1,93 @@
+"use client";
+
+import type { ToolUIPart } from "ai";
+import { MorphingTextAnimation } from "../../components/MorphingTextAnimation/MorphingTextAnimation";
+import { ToolAccordion } from "../../components/ToolAccordion/ToolAccordion";
+import { ContentMessage } from "../../components/ToolAccordion/AccordionContent";
+import {
+ getAccordionMeta,
+ getAnimationText,
+ getRunAgentToolOutput,
+ isRunAgentAgentDetailsOutput,
+ isRunAgentErrorOutput,
+ isRunAgentExecutionStartedOutput,
+ isRunAgentNeedLoginOutput,
+ isRunAgentSetupRequirementsOutput,
+ ToolIcon,
+} from "./helpers";
+import { ExecutionStartedCard } from "./components/ExecutionStartedCard/ExecutionStartedCard";
+import { AgentDetailsCard } from "./components/AgentDetailsCard/AgentDetailsCard";
+import { SetupRequirementsCard } from "./components/SetupRequirementsCard/SetupRequirementsCard";
+import { ErrorCard } from "./components/ErrorCard/ErrorCard";
+
+export interface RunAgentToolPart {
+ type: string;
+ toolCallId: string;
+ state: ToolUIPart["state"];
+ input?: unknown;
+ output?: unknown;
+}
+
+interface Props {
+ part: RunAgentToolPart;
+}
+
+export function RunAgentTool({ part }: Props) {
+ const text = getAnimationText(part);
+ const isStreaming =
+ part.state === "input-streaming" || part.state === "input-available";
+
+ const output = getRunAgentToolOutput(part);
+ const isError =
+ part.state === "output-error" ||
+ (!!output && isRunAgentErrorOutput(output));
+ const hasExpandableContent =
+ part.state === "output-available" &&
+ !!output &&
+ (isRunAgentExecutionStartedOutput(output) ||
+ isRunAgentAgentDetailsOutput(output) ||
+ isRunAgentSetupRequirementsOutput(output) ||
+ isRunAgentNeedLoginOutput(output) ||
+ isRunAgentErrorOutput(output));
+
+ return (
+ <div className="py-2">
+ <div className="flex items-center gap-2 text-sm text-muted-foreground">
+ <ToolIcon isStreaming={isStreaming} isError={isError} />
+ <MorphingTextAnimation
+ text={text}
+ className={isError ? "text-red-500" : undefined}
+ />
+ </div>
+
+ {hasExpandableContent && output && (
+ <ToolAccordion
+ {...getAccordionMeta(output)}
+ defaultExpanded={
+ isRunAgentExecutionStartedOutput(output) ||
+ isRunAgentSetupRequirementsOutput(output) ||
+ isRunAgentAgentDetailsOutput(output)
+ }
+ >
+ {isRunAgentExecutionStartedOutput(output) && (
+ <ExecutionStartedCard output={output} />
+ )}
+
+ {isRunAgentAgentDetailsOutput(output) && (
+ <AgentDetailsCard output={output} />
+ )}
+
+ {isRunAgentSetupRequirementsOutput(output) && (
+ <SetupRequirementsCard output={output} />
+ )}
+
+ {isRunAgentNeedLoginOutput(output) && (
+ <ContentMessage>{output.message}</ContentMessage>
+ )}
+
+ {isRunAgentErrorOutput(output) && <ErrorCard output={output} />}
+ </ToolAccordion>
+ )}
+ </div>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunAgent/components/AgentDetailsCard/AgentDetailsCard.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunAgent/components/AgentDetailsCard/AgentDetailsCard.tsx
new file mode 100644
index 0000000000..f18568faec
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunAgent/components/AgentDetailsCard/AgentDetailsCard.tsx
@@ -0,0 +1,116 @@
+"use client";
+
+import type { AgentDetailsResponse } from "@/app/api/__generated__/models/agentDetailsResponse";
+import { Button } from "@/components/atoms/Button/Button";
+import { Text } from "@/components/atoms/Text/Text";
+import { FormRenderer } from "@/components/renderers/InputRenderer/FormRenderer";
+import { AnimatePresence, motion } from "framer-motion";
+import { useState } from "react";
+import { useCopilotChatActions } from "../../../../components/CopilotChatActionsProvider/useCopilotChatActions";
+import { ContentMessage } from "../../../../components/ToolAccordion/AccordionContent";
+import { buildInputSchema } from "./helpers";
+
+interface Props {
+ output: AgentDetailsResponse;
+}
+
+export function AgentDetailsCard({ output }: Props) {
+ const { onSend } = useCopilotChatActions();
+ const [showInputForm, setShowInputForm] = useState(false);
+ const [inputValues, setInputValues] = useState<Record<string, unknown>>({});
+
+ function handleRunWithExamples() {
+ onSend(
+ `Run the agent "${output.agent.name}" with placeholder/example values so I can test it.`,
+ );
+ }
+
+ function handleRunWithInputs() {
+ const nonEmpty = Object.fromEntries(
+ Object.entries(inputValues).filter(
+ ([, v]) => v !== undefined && v !== null && v !== "",
+ ),
+ );
+ onSend(
+ `Run the agent "${output.agent.name}" with these inputs: ${JSON.stringify(nonEmpty, null, 2)}`,
+ );
+ setShowInputForm(false);
+ setInputValues({});
+ }
+
+ return (
+ <div className="grid gap-2">
+ <ContentMessage>
+ Run this agent with example values or your own inputs.
+ </ContentMessage>
+
+ <div className="flex gap-2 pt-4">
+ <Button size="small" className="w-fit" onClick={handleRunWithExamples}>
+ Run with example values
+ </Button>
+ <Button
+ variant="outline"
+ size="small"
+ className="w-fit"
+ onClick={() => setShowInputForm((prev) => !prev)}
+ >
+ Run with my inputs
+ </Button>
+ </div>
+
+ <AnimatePresence initial={false}>
+ {showInputForm && buildInputSchema(output.agent.inputs) && (
+ <motion.div
+ initial={{ height: 0, opacity: 0, filter: "blur(6px)" }}
+ animate={{ height: "auto", opacity: 1, filter: "blur(0px)" }}
+ exit={{ height: 0, opacity: 0, filter: "blur(6px)" }}
+ transition={{
+ height: { type: "spring", bounce: 0.15, duration: 0.5 },
+ opacity: { duration: 0.25 },
+ filter: { duration: 0.2 },
+ }}
+ className="overflow-hidden"
+ style={{ willChange: "height, opacity, filter" }}
+ >
+ <div className="mt-4 rounded-2xl border bg-background p-3 pt-4">
+ <Text variant="body-medium">Enter your inputs</Text>
+ <FormRenderer
+ jsonSchema={buildInputSchema(output.agent.inputs)!}
+ handleChange={(v) => setInputValues(v.formData ?? {})}
+ uiSchema={{
+ "ui:submitButtonOptions": { norender: true },
+ }}
+ initialValues={inputValues}
+ formContext={{
+ showHandles: false,
+ size: "small",
+ }}
+ />
+ <div className="-mt-8 flex gap-2">
+ <Button
+ variant="primary"
+ size="small"
+ className="w-fit"
+ onClick={handleRunWithInputs}
+ >
+ Run
+ </Button>
+ <Button
+ variant="secondary"
+ size="small"
+ className="w-fit"
+ onClick={() => {
+ setShowInputForm(false);
+ setInputValues({});
+ }}
+ >
+ Cancel
+ </Button>
+ </div>
+ </div>
+ </motion.div>
+ )}
+ </AnimatePresence>
+ </div>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunAgent/components/AgentDetailsCard/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunAgent/components/AgentDetailsCard/helpers.ts
new file mode 100644
index 0000000000..635b8d20d7
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunAgent/components/AgentDetailsCard/helpers.ts
@@ -0,0 +1,8 @@
+import type { RJSFSchema } from "@rjsf/utils";
+
+export function buildInputSchema(inputs: unknown): RJSFSchema | null {
+ if (!inputs || typeof inputs !== "object") return null;
+ const properties = inputs as RJSFSchema["properties"];
+ if (!properties || Object.keys(properties).length === 0) return null;
+ return inputs as RJSFSchema;
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunAgent/components/ErrorCard/ErrorCard.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunAgent/components/ErrorCard/ErrorCard.tsx
new file mode 100644
index 0000000000..7990428947
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunAgent/components/ErrorCard/ErrorCard.tsx
@@ -0,0 +1,27 @@
+"use client";
+
+import type { ErrorResponse } from "@/app/api/__generated__/models/errorResponse";
+import {
+ ContentCodeBlock,
+ ContentGrid,
+ ContentMessage,
+} from "../../../../components/ToolAccordion/AccordionContent";
+import { formatMaybeJson } from "../../helpers";
+
+interface Props {
+ output: ErrorResponse;
+}
+
+export function ErrorCard({ output }: Props) {
+ return (
+ <ContentGrid>
+ <ContentMessage>{output.message}</ContentMessage>
+ {output.error && (
+ <ContentCodeBlock>{formatMaybeJson(output.error)}</ContentCodeBlock>
+ )}
+ {output.details && (
+ <ContentCodeBlock>{formatMaybeJson(output.details)}</ContentCodeBlock>
+ )}
+ </ContentGrid>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunAgent/components/ExecutionStartedCard/ExecutionStartedCard.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunAgent/components/ExecutionStartedCard/ExecutionStartedCard.tsx
new file mode 100644
index 0000000000..f98656e5ff
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunAgent/components/ExecutionStartedCard/ExecutionStartedCard.tsx
@@ -0,0 +1,39 @@
+"use client";
+
+import type { ExecutionStartedResponse } from "@/app/api/__generated__/models/executionStartedResponse";
+import { Button } from "@/components/atoms/Button/Button";
+import { useRouter } from "next/navigation";
+import {
+ ContentCard,
+ ContentCardDescription,
+ ContentCardSubtitle,
+ ContentCardTitle,
+ ContentGrid,
+} from "../../../../components/ToolAccordion/AccordionContent";
+
+interface Props {
+ output: ExecutionStartedResponse;
+}
+
+export function ExecutionStartedCard({ output }: Props) {
+ const router = useRouter();
+
+ return (
+ <ContentGrid>
+ <ContentCard>
+ <ContentCardTitle>Execution started</ContentCardTitle>
+ <ContentCardSubtitle>{output.execution_id}</ContentCardSubtitle>
+ <ContentCardDescription>{output.message}</ContentCardDescription>
+ {output.library_agent_link && (
+ <Button
+ size="small"
+ className="mt-3"
+ onClick={() => router.push(output.library_agent_link!)}
+ >
+ View Execution
+ </Button>
+ )}
+ </ContentCard>
+ </ContentGrid>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunAgent/components/SetupRequirementsCard/SetupRequirementsCard.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunAgent/components/SetupRequirementsCard/SetupRequirementsCard.tsx
new file mode 100644
index 0000000000..c6d116e62a
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunAgent/components/SetupRequirementsCard/SetupRequirementsCard.tsx
@@ -0,0 +1,105 @@
+"use client";
+
+import { useState } from "react";
+import { CredentialsGroupedView } from "@/components/contextual/CredentialsInput/components/CredentialsGroupedView/CredentialsGroupedView";
+import { Button } from "@/components/atoms/Button/Button";
+import type { CredentialsMetaInput } from "@/lib/autogpt-server-api/types";
+import type { SetupRequirementsResponse } from "@/app/api/__generated__/models/setupRequirementsResponse";
+import { useCopilotChatActions } from "../../../../components/CopilotChatActionsProvider/useCopilotChatActions";
+import {
+ ContentBadge,
+ ContentCardDescription,
+ ContentCardTitle,
+ ContentMessage,
+} from "../../../../components/ToolAccordion/AccordionContent";
+import { coerceCredentialFields, coerceExpectedInputs } from "./helpers";
+
+interface Props {
+ output: SetupRequirementsResponse;
+}
+
+export function SetupRequirementsCard({ output }: Props) {
+ const { onSend } = useCopilotChatActions();
+
+ const [inputCredentials, setInputCredentials] = useState<
+ Record<string, CredentialsMetaInput | undefined>
+ >({});
+ const [hasSent, setHasSent] = useState(false);
+
+ const { credentialFields, requiredCredentials } = coerceCredentialFields(
+ output.setup_info.user_readiness?.missing_credentials,
+ );
+
+ const expectedInputs = coerceExpectedInputs(
+ (output.setup_info.requirements as Record<string, unknown>)?.inputs,
+ );
+
+ function handleCredentialChange(key: string, value?: CredentialsMetaInput) {
+ setInputCredentials((prev) => ({ ...prev, [key]: value }));
+ }
+
+ const isAllComplete =
+ credentialFields.length > 0 &&
+ [...requiredCredentials].every((key) => !!inputCredentials[key]);
+
+ function handleProceed() {
+ setHasSent(true);
+ onSend(
+ "I've configured the required credentials. Please check if everything is ready and proceed with running the agent.",
+ );
+ }
+
+ return (
+ <div className="grid gap-2">
+ <ContentMessage>{output.message}</ContentMessage>
+
+ {credentialFields.length > 0 && (
+ <div className="rounded-2xl border bg-background p-3">
+ <CredentialsGroupedView
+ credentialFields={credentialFields}
+ requiredCredentials={requiredCredentials}
+ inputCredentials={inputCredentials}
+ inputValues={{}}
+ onCredentialChange={handleCredentialChange}
+ />
+ {isAllComplete && !hasSent && (
+ <Button
+ variant="primary"
+ size="small"
+ className="mt-3 w-full"
+ onClick={handleProceed}
+ >
+ Proceed
+ </Button>
+ )}
+ </div>
+ )}
+
+ {expectedInputs.length > 0 && (
+ <div className="rounded-2xl border bg-background p-3">
+ <ContentCardTitle className="text-xs">
+ Expected inputs
+ </ContentCardTitle>
+ <div className="mt-2 grid gap-2">
+ {expectedInputs.map((input) => (
+ <div key={input.name} className="rounded-xl border p-2">
+ <div className="flex items-center justify-between gap-2">
+ <ContentCardTitle className="text-xs">
+ {input.title}
+ </ContentCardTitle>
+ <ContentBadge>
+ {input.required ? "Required" : "Optional"}
+ </ContentBadge>
+ </div>
+ <ContentCardDescription className="mt-1">
+ {input.name} &bull; {input.type}
+ {input.description ? ` \u2022 ${input.description}` : ""}
+ </ContentCardDescription>
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunAgent/components/SetupRequirementsCard/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunAgent/components/SetupRequirementsCard/helpers.ts
new file mode 100644
index 0000000000..6bb10751f0
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunAgent/components/SetupRequirementsCard/helpers.ts
@@ -0,0 +1,116 @@
+import type { CredentialField } from "@/components/contextual/CredentialsInput/components/CredentialsGroupedView/helpers";
+
+const VALID_CREDENTIAL_TYPES = new Set([
+ "api_key",
+ "oauth2",
+ "user_password",
+ "host_scoped",
+]);
+
+/**
+ * Transforms raw missing_credentials from SetupRequirementsResponse
+ * into CredentialField[] tuples compatible with CredentialsGroupedView.
+ *
+ * Each CredentialField is [key, schema] where schema matches
+ * BlockIOCredentialsSubSchema shape.
+ */
+export function coerceCredentialFields(rawMissingCredentials: unknown): {
+ credentialFields: CredentialField[];
+ requiredCredentials: Set<string>;
+} {
+ const missing =
+ rawMissingCredentials && typeof rawMissingCredentials === "object"
+ ? (rawMissingCredentials as Record<string, unknown>)
+ : {};
+
+ const credentialFields: CredentialField[] = [];
+ const requiredCredentials = new Set<string>();
+
+ Object.entries(missing).forEach(([key, value]) => {
+ if (!value || typeof value !== "object") return;
+ const cred = value as Record<string, unknown>;
+
+ const provider =
+ typeof cred.provider === "string" ? cred.provider.trim() : "";
+ if (!provider) return;
+
+ const types =
+ Array.isArray(cred.types) && cred.types.length > 0
+ ? cred.types
+ : typeof cred.type === "string"
+ ? [cred.type]
+ : [];
+
+ const credentialTypes = types
+ .map((t) => (typeof t === "string" ? t.trim() : ""))
+ .filter((t) => VALID_CREDENTIAL_TYPES.has(t));
+
+ if (credentialTypes.length === 0) return;
+
+ const scopes = Array.isArray(cred.scopes)
+ ? cred.scopes.filter((s): s is string => typeof s === "string")
+ : undefined;
+
+ const schema = {
+ type: "object" as const,
+ properties: {},
+ credentials_provider: [provider],
+ credentials_types: credentialTypes,
+ credentials_scopes: scopes,
+ };
+
+ credentialFields.push([key, schema]);
+ requiredCredentials.add(key);
+ });
+
+ return { credentialFields, requiredCredentials };
+}
+
+export function coerceExpectedInputs(rawInputs: unknown): Array<{
+ name: string;
+ title: string;
+ type: string;
+ description?: string;
+ required: boolean;
+}> {
+ if (!Array.isArray(rawInputs)) return [];
+ const results: Array<{
+ name: string;
+ title: string;
+ type: string;
+ description?: string;
+ required: boolean;
+ }> = [];
+
+ rawInputs.forEach((value, index) => {
+ if (!value || typeof value !== "object") return;
+ const input = value as Record<string, unknown>;
+
+ const name =
+ typeof input.name === "string" && input.name.trim()
+ ? input.name.trim()
+ : `input-${index}`;
+ const title =
+ typeof input.title === "string" && input.title.trim()
+ ? input.title.trim()
+ : name;
+ const type = typeof input.type === "string" ? input.type : "unknown";
+ const description =
+ typeof input.description === "string" && input.description.trim()
+ ? input.description.trim()
+ : undefined;
+ const required = Boolean(input.required);
+
+ const item: {
+ name: string;
+ title: string;
+ type: string;
+ description?: string;
+ required: boolean;
+ } = { name, title, type, required };
+ if (description) item.description = description;
+ results.push(item);
+ });
+
+ return results;
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunAgent/helpers.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunAgent/helpers.tsx
new file mode 100644
index 0000000000..0a117a71f2
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunAgent/helpers.tsx
@@ -0,0 +1,248 @@
+import type { AgentDetailsResponse } from "@/app/api/__generated__/models/agentDetailsResponse";
+import type { ErrorResponse } from "@/app/api/__generated__/models/errorResponse";
+import type { ExecutionStartedResponse } from "@/app/api/__generated__/models/executionStartedResponse";
+import type { NeedLoginResponse } from "@/app/api/__generated__/models/needLoginResponse";
+import { ResponseType } from "@/app/api/__generated__/models/responseType";
+import type { SetupRequirementsResponse } from "@/app/api/__generated__/models/setupRequirementsResponse";
+import {
+ PlayIcon,
+ RocketLaunchIcon,
+ WarningDiamondIcon,
+} from "@phosphor-icons/react";
+import type { ToolUIPart } from "ai";
+import { SpinnerLoader } from "../../components/SpinnerLoader/SpinnerLoader";
+
+export interface RunAgentInput {
+ username_agent_slug?: string;
+ library_agent_id?: string;
+ inputs?: Record<string, unknown>;
+ use_defaults?: boolean;
+ schedule_name?: string;
+ cron?: string;
+ timezone?: string;
+}
+
+export type RunAgentToolOutput =
+ | SetupRequirementsResponse
+ | ExecutionStartedResponse
+ | AgentDetailsResponse
+ | NeedLoginResponse
+ | ErrorResponse;
+
+const RUN_AGENT_OUTPUT_TYPES = new Set<string>([
+ ResponseType.setup_requirements,
+ ResponseType.execution_started,
+ ResponseType.agent_details,
+ ResponseType.need_login,
+ ResponseType.error,
+]);
+
+export function isRunAgentSetupRequirementsOutput(
+ output: RunAgentToolOutput,
+): output is SetupRequirementsResponse {
+ return (
+ output.type === ResponseType.setup_requirements ||
+ ("setup_info" in output && typeof output.setup_info === "object")
+ );
+}
+
+export function isRunAgentExecutionStartedOutput(
+ output: RunAgentToolOutput,
+): output is ExecutionStartedResponse {
+ return (
+ output.type === ResponseType.execution_started || "execution_id" in output
+ );
+}
+
+export function isRunAgentAgentDetailsOutput(
+ output: RunAgentToolOutput,
+): output is AgentDetailsResponse {
+ return output.type === ResponseType.agent_details || "agent" in output;
+}
+
+export function isRunAgentNeedLoginOutput(
+ output: RunAgentToolOutput,
+): output is NeedLoginResponse {
+ return output.type === ResponseType.need_login;
+}
+
+export function isRunAgentErrorOutput(
+ output: RunAgentToolOutput,
+): output is ErrorResponse {
+ return output.type === ResponseType.error || "error" in output;
+}
+
+function parseOutput(output: unknown): RunAgentToolOutput | null {
+ if (!output) return null;
+ if (typeof output === "string") {
+ const trimmed = output.trim();
+ if (!trimmed) return null;
+ try {
+ return parseOutput(JSON.parse(trimmed) as unknown);
+ } catch {
+ return null;
+ }
+ }
+ if (typeof output === "object") {
+ const type = (output as { type?: unknown }).type;
+ if (typeof type === "string" && RUN_AGENT_OUTPUT_TYPES.has(type)) {
+ return output as RunAgentToolOutput;
+ }
+ if ("execution_id" in output) return output as ExecutionStartedResponse;
+ if ("setup_info" in output) return output as SetupRequirementsResponse;
+ if ("agent" in output) return output as AgentDetailsResponse;
+ if ("error" in output || "details" in output)
+ return output as ErrorResponse;
+ if (type === ResponseType.need_login) return output as NeedLoginResponse;
+ }
+ return null;
+}
+
+export function getRunAgentToolOutput(
+ part: unknown,
+): RunAgentToolOutput | null {
+ if (!part || typeof part !== "object") return null;
+ return parseOutput((part as { output?: unknown }).output);
+}
+
+function getAgentIdentifierText(
+ input: RunAgentInput | undefined,
+): string | null {
+ if (!input) return null;
+ const slug = input.username_agent_slug?.trim();
+ if (slug) return slug;
+ const libraryId = input.library_agent_id?.trim();
+ if (libraryId) return `Library agent ${libraryId}`;
+ return null;
+}
+
+export function getAnimationText(part: {
+ state: ToolUIPart["state"];
+ input?: unknown;
+ output?: unknown;
+}): string {
+ const input = part.input as RunAgentInput | undefined;
+ const agentIdentifier = getAgentIdentifierText(input);
+ const isSchedule = Boolean(
+ input?.schedule_name?.trim() || input?.cron?.trim(),
+ );
+ const actionPhrase = isSchedule
+ ? "Scheduling the agent to run"
+ : "Running the agent";
+ const identifierText = agentIdentifier ? ` "${agentIdentifier}"` : "";
+
+ switch (part.state) {
+ case "input-streaming":
+ case "input-available":
+ return `${actionPhrase}${identifierText}`;
+ case "output-available": {
+ const output = parseOutput(part.output);
+ if (!output) return `${actionPhrase}${identifierText}`;
+ if (isRunAgentExecutionStartedOutput(output)) {
+ return `Started "${output.graph_name}"`;
+ }
+ if (isRunAgentAgentDetailsOutput(output)) {
+ return `Agent inputs needed for "${output.agent.name}"`;
+ }
+ if (isRunAgentSetupRequirementsOutput(output)) {
+ return `Setup needed for "${output.setup_info.agent_name}"`;
+ }
+ if (isRunAgentNeedLoginOutput(output))
+ return "Sign in required to run agent";
+ return "Error running agent";
+ }
+ case "output-error":
+ return "Error running agent";
+ default:
+ return actionPhrase;
+ }
+}
+
+export function ToolIcon({
+ isStreaming,
+ isError,
+}: {
+ isStreaming?: boolean;
+ isError?: boolean;
+}) {
+ if (isError) {
+ return (
+ <WarningDiamondIcon size={14} weight="regular" className="text-red-500" />
+ );
+ }
+ if (isStreaming) {
+ return <SpinnerLoader size={40} className="text-neutral-700" />;
+ }
+ return <PlayIcon size={14} weight="regular" className="text-neutral-400" />;
+}
+
+export function AccordionIcon() {
+ return <RocketLaunchIcon size={28} weight="light" />;
+}
+
+export function formatMaybeJson(value: unknown): string {
+ if (typeof value === "string") return value;
+ try {
+ return JSON.stringify(value, null, 2);
+ } catch {
+ return String(value);
+ }
+}
+
+export function getAccordionMeta(output: RunAgentToolOutput): {
+ icon: React.ReactNode;
+ title: string;
+ titleClassName?: string;
+ description?: string;
+} {
+ const icon = <AccordionIcon />;
+
+ if (isRunAgentExecutionStartedOutput(output)) {
+ const statusText =
+ typeof output.status === "string" && output.status.trim()
+ ? output.status.trim()
+ : "started";
+ return {
+ icon: <SpinnerLoader size={28} className="text-neutral-700" />,
+ title: output.graph_name,
+ description: `Status: ${statusText}`,
+ };
+ }
+
+ if (isRunAgentAgentDetailsOutput(output)) {
+ return {
+ icon,
+ title: output.agent.name,
+ description: "Inputs required",
+ };
+ }
+
+ if (isRunAgentSetupRequirementsOutput(output)) {
+ const missingCredsCount = Object.keys(
+ (output.setup_info.user_readiness?.missing_credentials ?? {}) as Record<
+ string,
+ unknown
+ >,
+ ).length;
+ return {
+ icon,
+ title: output.setup_info.agent_name,
+ description:
+ missingCredsCount > 0
+ ? `Missing ${missingCredsCount} credential${missingCredsCount === 1 ? "" : "s"}`
+ : output.message,
+ };
+ }
+
+ if (isRunAgentNeedLoginOutput(output)) {
+ return { icon, title: "Sign in required" };
+ }
+
+ return {
+ icon: (
+ <WarningDiamondIcon size={28} weight="light" className="text-red-500" />
+ ),
+ title: "Error",
+ titleClassName: "text-red-500",
+ };
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunBlock/RunBlock.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunBlock/RunBlock.tsx
new file mode 100644
index 0000000000..ded344efa2
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunBlock/RunBlock.tsx
@@ -0,0 +1,76 @@
+"use client";
+
+import type { ToolUIPart } from "ai";
+import { MorphingTextAnimation } from "../../components/MorphingTextAnimation/MorphingTextAnimation";
+import { ToolAccordion } from "../../components/ToolAccordion/ToolAccordion";
+import { BlockOutputCard } from "./components/BlockOutputCard/BlockOutputCard";
+import { ErrorCard } from "./components/ErrorCard/ErrorCard";
+import { SetupRequirementsCard } from "./components/SetupRequirementsCard/SetupRequirementsCard";
+import {
+ getAccordionMeta,
+ getAnimationText,
+ getRunBlockToolOutput,
+ isRunBlockBlockOutput,
+ isRunBlockErrorOutput,
+ isRunBlockSetupRequirementsOutput,
+ ToolIcon,
+} from "./helpers";
+
+export interface RunBlockToolPart {
+ type: string;
+ toolCallId: string;
+ state: ToolUIPart["state"];
+ input?: unknown;
+ output?: unknown;
+}
+
+interface Props {
+ part: RunBlockToolPart;
+}
+
+export function RunBlockTool({ part }: Props) {
+ const text = getAnimationText(part);
+ const isStreaming =
+ part.state === "input-streaming" || part.state === "input-available";
+
+ const output = getRunBlockToolOutput(part);
+ const isError =
+ part.state === "output-error" ||
+ (!!output && isRunBlockErrorOutput(output));
+ const hasExpandableContent =
+ part.state === "output-available" &&
+ !!output &&
+ (isRunBlockBlockOutput(output) ||
+ isRunBlockSetupRequirementsOutput(output) ||
+ isRunBlockErrorOutput(output));
+
+ return (
+ <div className="py-2">
+ <div className="flex items-center gap-2 text-sm text-muted-foreground">
+ <ToolIcon isStreaming={isStreaming} isError={isError} />
+ <MorphingTextAnimation
+ text={text}
+ className={isError ? "text-red-500" : undefined}
+ />
+ </div>
+
+ {hasExpandableContent && output && (
+ <ToolAccordion
+ {...getAccordionMeta(output)}
+ defaultExpanded={
+ isRunBlockBlockOutput(output) ||
+ isRunBlockSetupRequirementsOutput(output)
+ }
+ >
+ {isRunBlockBlockOutput(output) && <BlockOutputCard output={output} />}
+
+ {isRunBlockSetupRequirementsOutput(output) && (
+ <SetupRequirementsCard output={output} />
+ )}
+
+ {isRunBlockErrorOutput(output) && <ErrorCard output={output} />}
+ </ToolAccordion>
+ )}
+ </div>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunBlock/components/BlockOutputCard/BlockOutputCard.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunBlock/components/BlockOutputCard/BlockOutputCard.tsx
new file mode 100644
index 0000000000..4051927653
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunBlock/components/BlockOutputCard/BlockOutputCard.tsx
@@ -0,0 +1,133 @@
+"use client";
+
+import React, { useState } from "react";
+import { getGetWorkspaceDownloadFileByIdUrl } from "@/app/api/__generated__/endpoints/workspace/workspace";
+import { Button } from "@/components/atoms/Button/Button";
+import type { BlockOutputResponse } from "@/app/api/__generated__/models/blockOutputResponse";
+import {
+ globalRegistry,
+ OutputItem,
+} from "@/components/contextual/OutputRenderers";
+import type { OutputMetadata } from "@/components/contextual/OutputRenderers";
+import {
+ ContentBadge,
+ ContentCard,
+ ContentCardTitle,
+ ContentGrid,
+ ContentMessage,
+} from "../../../../components/ToolAccordion/AccordionContent";
+
+interface Props {
+ output: BlockOutputResponse;
+}
+
+const COLLAPSED_LIMIT = 3;
+
+function isWorkspaceRef(value: unknown): value is string {
+ return typeof value === "string" && value.startsWith("workspace://");
+}
+
+function resolveForRenderer(value: unknown): {
+ value: unknown;
+ metadata?: OutputMetadata;
+} {
+ if (!isWorkspaceRef(value)) return { value };
+
+ const withoutPrefix = value.replace("workspace://", "");
+ const fileId = withoutPrefix.split("#")[0];
+ const apiPath = getGetWorkspaceDownloadFileByIdUrl(fileId);
+ const url = `/api/proxy${apiPath}`;
+
+ const hashIndex = value.indexOf("#");
+ const mimeHint =
+ hashIndex !== -1 ? value.slice(hashIndex + 1) || undefined : undefined;
+
+ const metadata: OutputMetadata = {};
+ if (mimeHint) {
+ metadata.mimeType = mimeHint;
+ if (mimeHint.startsWith("image/")) metadata.type = "image";
+ else if (mimeHint.startsWith("video/")) metadata.type = "video";
+ }
+
+ return { value: url, metadata };
+}
+
+function RenderOutputValue({ value }: { value: unknown }) {
+ const resolved = resolveForRenderer(value);
+ const renderer = globalRegistry.getRenderer(
+ resolved.value,
+ resolved.metadata,
+ );
+
+ if (renderer) {
+ return (
+ <OutputItem
+ value={resolved.value}
+ metadata={resolved.metadata}
+ renderer={renderer}
+ />
+ );
+ }
+
+ // Fallback for audio workspace refs
+ if (
+ isWorkspaceRef(value) &&
+ resolved.metadata?.mimeType?.startsWith("audio/")
+ ) {
+ return (
+ <audio controls src={String(resolved.value)} className="mt-2 w-full" />
+ );
+ }
+
+ return null;
+}
+
+function OutputKeySection({
+ outputKey,
+ items,
+}: {
+ outputKey: string;
+ items: unknown[];
+}) {
+ const [expanded, setExpanded] = useState(false);
+ const hasMoreItems = items.length > COLLAPSED_LIMIT;
+ const visibleItems = expanded ? items : items.slice(0, COLLAPSED_LIMIT);
+
+ return (
+ <ContentCard>
+ <div className="flex items-center justify-between gap-2">
+ <ContentCardTitle className="text-xs">{outputKey}</ContentCardTitle>
+ <ContentBadge>
+ {items.length} item{items.length === 1 ? "" : "s"}
+ </ContentBadge>
+ </div>
+ <div className="mt-2">
+ {visibleItems.map((item, i) => (
+ <RenderOutputValue key={i} value={item} />
+ ))}
+ </div>
+ {hasMoreItems && (
+ <Button
+ variant="ghost"
+ size="small"
+ className="mt-1 h-auto px-0 py-0.5 text-[11px] text-muted-foreground"
+ onClick={() => setExpanded((prev) => !prev)}
+ >
+ {expanded ? "Show less" : `Show all ${items.length} items`}
+ </Button>
+ )}
+ </ContentCard>
+ );
+}
+
+export function BlockOutputCard({ output }: Props) {
+ return (
+ <ContentGrid>
+ <ContentMessage>{output.message}</ContentMessage>
+
+ {Object.entries(output.outputs ?? {}).map(([key, items]) => (
+ <OutputKeySection key={key} outputKey={key} items={items} />
+ ))}
+ </ContentGrid>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunBlock/components/ErrorCard/ErrorCard.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunBlock/components/ErrorCard/ErrorCard.tsx
new file mode 100644
index 0000000000..7990428947
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunBlock/components/ErrorCard/ErrorCard.tsx
@@ -0,0 +1,27 @@
+"use client";
+
+import type { ErrorResponse } from "@/app/api/__generated__/models/errorResponse";
+import {
+ ContentCodeBlock,
+ ContentGrid,
+ ContentMessage,
+} from "../../../../components/ToolAccordion/AccordionContent";
+import { formatMaybeJson } from "../../helpers";
+
+interface Props {
+ output: ErrorResponse;
+}
+
+export function ErrorCard({ output }: Props) {
+ return (
+ <ContentGrid>
+ <ContentMessage>{output.message}</ContentMessage>
+ {output.error && (
+ <ContentCodeBlock>{formatMaybeJson(output.error)}</ContentCodeBlock>
+ )}
+ {output.details && (
+ <ContentCodeBlock>{formatMaybeJson(output.details)}</ContentCodeBlock>
+ )}
+ </ContentGrid>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunBlock/components/SetupRequirementsCard/SetupRequirementsCard.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunBlock/components/SetupRequirementsCard/SetupRequirementsCard.tsx
new file mode 100644
index 0000000000..e98fea2850
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunBlock/components/SetupRequirementsCard/SetupRequirementsCard.tsx
@@ -0,0 +1,197 @@
+"use client";
+
+import type { SetupRequirementsResponse } from "@/app/api/__generated__/models/setupRequirementsResponse";
+import { Button } from "@/components/atoms/Button/Button";
+import { Text } from "@/components/atoms/Text/Text";
+import { CredentialsGroupedView } from "@/components/contextual/CredentialsInput/components/CredentialsGroupedView/CredentialsGroupedView";
+import { FormRenderer } from "@/components/renderers/InputRenderer/FormRenderer";
+import type { CredentialsMetaInput } from "@/lib/autogpt-server-api/types";
+import { AnimatePresence, motion } from "framer-motion";
+import { useState } from "react";
+import { useCopilotChatActions } from "../../../../components/CopilotChatActionsProvider/useCopilotChatActions";
+import {
+ ContentBadge,
+ ContentCardDescription,
+ ContentCardTitle,
+ ContentMessage,
+} from "../../../../components/ToolAccordion/AccordionContent";
+import {
+ buildExpectedInputsSchema,
+ coerceCredentialFields,
+ coerceExpectedInputs,
+} from "./helpers";
+
+interface Props {
+ output: SetupRequirementsResponse;
+}
+
+export function SetupRequirementsCard({ output }: Props) {
+ const { onSend } = useCopilotChatActions();
+
+ const [inputCredentials, setInputCredentials] = useState<
+ Record<string, CredentialsMetaInput | undefined>
+ >({});
+ const [hasSentCredentials, setHasSentCredentials] = useState(false);
+
+ const [showInputForm, setShowInputForm] = useState(false);
+ const [inputValues, setInputValues] = useState<Record<string, unknown>>({});
+
+ const { credentialFields, requiredCredentials } = coerceCredentialFields(
+ output.setup_info.user_readiness?.missing_credentials,
+ );
+
+ const expectedInputs = coerceExpectedInputs(
+ (output.setup_info.requirements as Record<string, unknown>)?.inputs,
+ );
+
+ const inputSchema = buildExpectedInputsSchema(expectedInputs);
+
+ function handleCredentialChange(key: string, value?: CredentialsMetaInput) {
+ setInputCredentials((prev) => ({ ...prev, [key]: value }));
+ }
+
+ const isAllCredentialsComplete =
+ credentialFields.length > 0 &&
+ [...requiredCredentials].every((key) => !!inputCredentials[key]);
+
+ function handleProceedCredentials() {
+ setHasSentCredentials(true);
+ onSend(
+ "I've configured the required credentials. Please re-run the block now.",
+ );
+ }
+
+ function handleRunWithInputs() {
+ const nonEmpty = Object.fromEntries(
+ Object.entries(inputValues).filter(
+ ([, v]) => v !== undefined && v !== null && v !== "",
+ ),
+ );
+ onSend(
+ `Run the block with these inputs: ${JSON.stringify(nonEmpty, null, 2)}`,
+ );
+ setShowInputForm(false);
+ setInputValues({});
+ }
+
+ return (
+ <div className="grid gap-2">
+ <ContentMessage>{output.message}</ContentMessage>
+
+ {credentialFields.length > 0 && (
+ <div className="rounded-2xl border bg-background p-3">
+ <CredentialsGroupedView
+ credentialFields={credentialFields}
+ requiredCredentials={requiredCredentials}
+ inputCredentials={inputCredentials}
+ inputValues={{}}
+ onCredentialChange={handleCredentialChange}
+ />
+ {isAllCredentialsComplete && !hasSentCredentials && (
+ <Button
+ variant="primary"
+ size="small"
+ className="mt-3 w-full"
+ onClick={handleProceedCredentials}
+ >
+ Proceed
+ </Button>
+ )}
+ </div>
+ )}
+
+ {inputSchema && (
+ <div className="flex gap-2 pt-2">
+ <Button
+ variant="outline"
+ size="small"
+ className="w-fit"
+ onClick={() => setShowInputForm((prev) => !prev)}
+ >
+ {showInputForm ? "Hide inputs" : "Fill in inputs"}
+ </Button>
+ </div>
+ )}
+
+ <AnimatePresence initial={false}>
+ {showInputForm && inputSchema && (
+ <motion.div
+ initial={{ height: 0, opacity: 0, filter: "blur(6px)" }}
+ animate={{ height: "auto", opacity: 1, filter: "blur(0px)" }}
+ exit={{ height: 0, opacity: 0, filter: "blur(6px)" }}
+ transition={{
+ height: { type: "spring", bounce: 0.15, duration: 0.5 },
+ opacity: { duration: 0.25 },
+ filter: { duration: 0.2 },
+ }}
+ className="overflow-hidden"
+ style={{ willChange: "height, opacity, filter" }}
+ >
+ <div className="rounded-2xl border bg-background p-3 pt-4">
+ <Text variant="body-medium">Block inputs</Text>
+ <FormRenderer
+ jsonSchema={inputSchema}
+ handleChange={(v) => setInputValues(v.formData ?? {})}
+ uiSchema={{
+ "ui:submitButtonOptions": { norender: true },
+ }}
+ initialValues={inputValues}
+ formContext={{
+ showHandles: false,
+ size: "small",
+ }}
+ />
+ <div className="-mt-8 flex gap-2">
+ <Button
+ variant="primary"
+ size="small"
+ className="w-fit"
+ onClick={handleRunWithInputs}
+ >
+ Run
+ </Button>
+ <Button
+ variant="secondary"
+ size="small"
+ className="w-fit"
+ onClick={() => {
+ setShowInputForm(false);
+ setInputValues({});
+ }}
+ >
+ Cancel
+ </Button>
+ </div>
+ </div>
+ </motion.div>
+ )}
+ </AnimatePresence>
+
+ {expectedInputs.length > 0 && !inputSchema && (
+ <div className="rounded-2xl border bg-background p-3">
+ <ContentCardTitle className="text-xs">
+ Expected inputs
+ </ContentCardTitle>
+ <div className="mt-2 grid gap-2">
+ {expectedInputs.map((input) => (
+ <div key={input.name} className="rounded-xl border p-2">
+ <div className="flex items-center justify-between gap-2">
+ <ContentCardTitle className="text-xs">
+ {input.title}
+ </ContentCardTitle>
+ <ContentBadge>
+ {input.required ? "Required" : "Optional"}
+ </ContentBadge>
+ </div>
+ <ContentCardDescription className="mt-1">
+ {input.name} &bull; {input.type}
+ {input.description ? ` \u2022 ${input.description}` : ""}
+ </ContentCardDescription>
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunBlock/components/SetupRequirementsCard/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunBlock/components/SetupRequirementsCard/helpers.ts
new file mode 100644
index 0000000000..bacc0bac55
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunBlock/components/SetupRequirementsCard/helpers.ts
@@ -0,0 +1,156 @@
+import type { CredentialField } from "@/components/contextual/CredentialsInput/components/CredentialsGroupedView/helpers";
+import type { RJSFSchema } from "@rjsf/utils";
+
+const VALID_CREDENTIAL_TYPES = new Set([
+ "api_key",
+ "oauth2",
+ "user_password",
+ "host_scoped",
+]);
+
+export function coerceCredentialFields(rawMissingCredentials: unknown): {
+ credentialFields: CredentialField[];
+ requiredCredentials: Set<string>;
+} {
+ const missing =
+ rawMissingCredentials && typeof rawMissingCredentials === "object"
+ ? (rawMissingCredentials as Record<string, unknown>)
+ : {};
+
+ const credentialFields: CredentialField[] = [];
+ const requiredCredentials = new Set<string>();
+
+ Object.entries(missing).forEach(([key, value]) => {
+ if (!value || typeof value !== "object") return;
+ const cred = value as Record<string, unknown>;
+
+ const provider =
+ typeof cred.provider === "string" ? cred.provider.trim() : "";
+ if (!provider) return;
+
+ const types =
+ Array.isArray(cred.types) && cred.types.length > 0
+ ? cred.types
+ : typeof cred.type === "string"
+ ? [cred.type]
+ : [];
+
+ const credentialTypes = types
+ .map((t) => (typeof t === "string" ? t.trim() : ""))
+ .filter((t) => VALID_CREDENTIAL_TYPES.has(t));
+
+ if (credentialTypes.length === 0) return;
+
+ const scopes = Array.isArray(cred.scopes)
+ ? cred.scopes.filter((s): s is string => typeof s === "string")
+ : undefined;
+
+ const schema = {
+ type: "object" as const,
+ properties: {},
+ credentials_provider: [provider],
+ credentials_types: credentialTypes,
+ credentials_scopes: scopes,
+ };
+
+ credentialFields.push([key, schema]);
+ requiredCredentials.add(key);
+ });
+
+ return { credentialFields, requiredCredentials };
+}
+
+export function coerceExpectedInputs(rawInputs: unknown): Array<{
+ name: string;
+ title: string;
+ type: string;
+ description?: string;
+ required: boolean;
+}> {
+ if (!Array.isArray(rawInputs)) return [];
+ const results: Array<{
+ name: string;
+ title: string;
+ type: string;
+ description?: string;
+ required: boolean;
+ }> = [];
+
+ rawInputs.forEach((value, index) => {
+ if (!value || typeof value !== "object") return;
+ const input = value as Record<string, unknown>;
+
+ const name =
+ typeof input.name === "string" && input.name.trim()
+ ? input.name.trim()
+ : `input-${index}`;
+ const title =
+ typeof input.title === "string" && input.title.trim()
+ ? input.title.trim()
+ : name;
+ const type = typeof input.type === "string" ? input.type : "unknown";
+ const description =
+ typeof input.description === "string" && input.description.trim()
+ ? input.description.trim()
+ : undefined;
+ const required = Boolean(input.required);
+
+ const item: {
+ name: string;
+ title: string;
+ type: string;
+ description?: string;
+ required: boolean;
+ } = { name, title, type, required };
+ if (description) item.description = description;
+ results.push(item);
+ });
+
+ return results;
+}
+
+/**
+ * Build an RJSF schema from expected inputs so they can be rendered
+ * as a dynamic form via FormRenderer.
+ */
+export function buildExpectedInputsSchema(
+ expectedInputs: Array<{
+ name: string;
+ title: string;
+ type: string;
+ description?: string;
+ required: boolean;
+ }>,
+): RJSFSchema | null {
+ if (expectedInputs.length === 0) return null;
+
+ const TYPE_MAP: Record<string, string> = {
+ string: "string",
+ str: "string",
+ text: "string",
+ number: "number",
+ int: "integer",
+ integer: "integer",
+ float: "number",
+ boolean: "boolean",
+ bool: "boolean",
+ };
+
+ const properties: Record<string, Record<string, unknown>> = {};
+ const required: string[] = [];
+
+ for (const input of expectedInputs) {
+ properties[input.name] = {
+ type: TYPE_MAP[input.type.toLowerCase()] ?? "string",
+ title: input.title,
+ ...(input.description ? { description: input.description } : {}),
+ };
+ if (input.required) required.push(input.name);
+ }
+
+ return {
+ type: "object",
+ properties,
+ ...(required.length > 0 ? { required } : {}),
+ };
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunBlock/helpers.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunBlock/helpers.tsx
new file mode 100644
index 0000000000..61ba65e74e
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunBlock/helpers.tsx
@@ -0,0 +1,185 @@
+import type { BlockOutputResponse } from "@/app/api/__generated__/models/blockOutputResponse";
+import type { ErrorResponse } from "@/app/api/__generated__/models/errorResponse";
+import { ResponseType } from "@/app/api/__generated__/models/responseType";
+import type { SetupRequirementsResponse } from "@/app/api/__generated__/models/setupRequirementsResponse";
+import {
+ PlayCircleIcon,
+ PlayIcon,
+ WarningDiamondIcon,
+} from "@phosphor-icons/react";
+import type { ToolUIPart } from "ai";
+import { SpinnerLoader } from "../../components/SpinnerLoader/SpinnerLoader";
+
+export interface RunBlockInput {
+ block_id?: string;
+ input_data?: Record<string, unknown>;
+}
+
+export type RunBlockToolOutput =
+ | SetupRequirementsResponse
+ | BlockOutputResponse
+ | ErrorResponse;
+
+const RUN_BLOCK_OUTPUT_TYPES = new Set<string>([
+ ResponseType.setup_requirements,
+ ResponseType.block_output,
+ ResponseType.error,
+]);
+
+export function isRunBlockSetupRequirementsOutput(
+ output: RunBlockToolOutput,
+): output is SetupRequirementsResponse {
+ return (
+ output.type === ResponseType.setup_requirements ||
+ ("setup_info" in output && typeof output.setup_info === "object")
+ );
+}
+
+export function isRunBlockBlockOutput(
+ output: RunBlockToolOutput,
+): output is BlockOutputResponse {
+ return output.type === ResponseType.block_output || "block_id" in output;
+}
+
+export function isRunBlockErrorOutput(
+ output: RunBlockToolOutput,
+): output is ErrorResponse {
+ return output.type === ResponseType.error || "error" in output;
+}
+
+function parseOutput(output: unknown): RunBlockToolOutput | null {
+ if (!output) return null;
+ if (typeof output === "string") {
+ const trimmed = output.trim();
+ if (!trimmed) return null;
+ try {
+ return parseOutput(JSON.parse(trimmed) as unknown);
+ } catch {
+ return null;
+ }
+ }
+ if (typeof output === "object") {
+ const type = (output as { type?: unknown }).type;
+ if (typeof type === "string" && RUN_BLOCK_OUTPUT_TYPES.has(type)) {
+ return output as RunBlockToolOutput;
+ }
+ if ("block_id" in output) return output as BlockOutputResponse;
+ if ("setup_info" in output) return output as SetupRequirementsResponse;
+ if ("error" in output || "details" in output)
+ return output as ErrorResponse;
+ }
+ return null;
+}
+
+export function getRunBlockToolOutput(
+ part: unknown,
+): RunBlockToolOutput | null {
+ if (!part || typeof part !== "object") return null;
+ return parseOutput((part as { output?: unknown }).output);
+}
+
+export function getAnimationText(part: {
+ state: ToolUIPart["state"];
+ input?: unknown;
+ output?: unknown;
+}): string {
+ const input = part.input as RunBlockInput | undefined;
+ const blockId = input?.block_id?.trim();
+ const blockText = blockId ? ` "${blockId}"` : "";
+
+ switch (part.state) {
+ case "input-streaming":
+ case "input-available":
+ return `Running the block${blockText}`;
+ case "output-available": {
+ const output = parseOutput(part.output);
+ if (!output) return `Running the block${blockText}`;
+ if (isRunBlockBlockOutput(output)) return `Ran "${output.block_name}"`;
+ if (isRunBlockSetupRequirementsOutput(output)) {
+ return `Setup needed for "${output.setup_info.agent_name}"`;
+ }
+ return "Error running block";
+ }
+ case "output-error":
+ return "Error running block";
+ default:
+ return "Running the block";
+ }
+}
+
+export function ToolIcon({
+ isStreaming,
+ isError,
+}: {
+ isStreaming?: boolean;
+ isError?: boolean;
+}) {
+ if (isError) {
+ return (
+ <WarningDiamondIcon size={14} weight="regular" className="text-red-500" />
+ );
+ }
+ if (isStreaming) {
+ return <SpinnerLoader size={40} className="text-neutral-700" />;
+ }
+ return <PlayIcon size={14} weight="regular" className="text-neutral-400" />;
+}
+
+export function AccordionIcon() {
+ return <PlayCircleIcon size={32} weight="light" />;
+}
+
+export function formatMaybeJson(value: unknown): string {
+ if (typeof value === "string") return value;
+ try {
+ return JSON.stringify(value, null, 2);
+ } catch {
+ return String(value);
+ }
+}
+
+export function getAccordionMeta(output: RunBlockToolOutput): {
+ icon: React.ReactNode;
+ title: string;
+ titleClassName?: string;
+ description?: string;
+} {
+ const icon = <AccordionIcon />;
+
+ if (isRunBlockBlockOutput(output)) {
+ const keys = Object.keys(output.outputs ?? {});
+ return {
+ icon: <SpinnerLoader size={32} className="text-neutral-700" />,
+ title: output.block_name,
+ description:
+ keys.length > 0
+ ? `${keys.length} output key${keys.length === 1 ? "" : "s"}`
+ : output.message,
+ };
+ }
+
+ if (isRunBlockSetupRequirementsOutput(output)) {
+ const missingCredsCount = Object.keys(
+ (output.setup_info.user_readiness?.missing_credentials ?? {}) as Record<
+ string,
+ unknown
+ >,
+ ).length;
+ return {
+ icon,
+ title: output.setup_info.agent_name,
+ description:
+ missingCredsCount > 0
+ ? `Missing ${missingCredsCount} credential${missingCredsCount === 1 ? "" : "s"}`
+ : output.message,
+ };
+ }
+
+ return {
+ icon: (
+ <WarningDiamondIcon size={32} weight="light" className="text-red-500" />
+ ),
+ title: "Error",
+ titleClassName: "text-red-500",
+ };
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/SearchDocs/SearchDocs.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/SearchDocs/SearchDocs.tsx
new file mode 100644
index 0000000000..d3fb793d14
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/SearchDocs/SearchDocs.tsx
@@ -0,0 +1,186 @@
+"use client";
+
+import type { ToolUIPart } from "ai";
+import { useMemo } from "react";
+
+import { MorphingTextAnimation } from "../../components/MorphingTextAnimation/MorphingTextAnimation";
+import {
+ ContentCard,
+ ContentCardDescription,
+ ContentCardHeader,
+ ContentCardSubtitle,
+ ContentCardTitle,
+ ContentGrid,
+ ContentLink,
+ ContentMessage,
+ ContentSuggestionsList,
+} from "../../components/ToolAccordion/AccordionContent";
+import { ToolAccordion } from "../../components/ToolAccordion/ToolAccordion";
+import {
+ AccordionIcon,
+ getAnimationText,
+ getDocsToolOutput,
+ getDocsToolTitle,
+ getToolLabel,
+ isDocPageOutput,
+ isDocSearchResultsOutput,
+ isErrorOutput,
+ isNoResultsOutput,
+ toDocsUrl,
+ ToolIcon,
+ type DocsToolType,
+} from "./helpers";
+
+export interface DocsToolPart {
+ type: DocsToolType;
+ toolCallId: string;
+ state: ToolUIPart["state"];
+ input?: unknown;
+ output?: unknown;
+}
+
+interface Props {
+ part: DocsToolPart;
+}
+
+function truncate(text: string, maxChars: number): string {
+ const trimmed = text.trim();
+ if (trimmed.length <= maxChars) return trimmed;
+ return `${trimmed.slice(0, maxChars).trimEnd()}…`;
+}
+
+export function SearchDocsTool({ part }: Props) {
+ const output = getDocsToolOutput(part);
+ const text = getAnimationText(part);
+ const isStreaming =
+ part.state === "input-streaming" || part.state === "input-available";
+ const isError =
+ part.state === "output-error" || (!!output && isErrorOutput(output));
+
+ const normalized = useMemo(() => {
+ if (!output) return null;
+ const title = getDocsToolTitle(part.type, output);
+ const label = getToolLabel(part.type);
+ return { title, label };
+ }, [output, part.type]);
+
+ const isOutputAvailable = part.state === "output-available" && !!output;
+
+ const docSearchOutput =
+ isOutputAvailable && output && isDocSearchResultsOutput(output)
+ ? output
+ : null;
+ const docPageOutput =
+ isOutputAvailable && output && isDocPageOutput(output) ? output : null;
+ const noResultsOutput =
+ isOutputAvailable && output && isNoResultsOutput(output) ? output : null;
+ const errorOutput =
+ isOutputAvailable && output && isErrorOutput(output) ? output : null;
+
+ const hasExpandableContent =
+ isOutputAvailable &&
+ ((!!docSearchOutput && docSearchOutput.count > 0) ||
+ !!docPageOutput ||
+ !!noResultsOutput ||
+ !!errorOutput);
+
+ const accordionDescription =
+ hasExpandableContent && docSearchOutput
+ ? `Found ${docSearchOutput.count} result${docSearchOutput.count === 1 ? "" : "s"} for "${docSearchOutput.query}"`
+ : hasExpandableContent && docPageOutput
+ ? docPageOutput.path
+ : hasExpandableContent && (noResultsOutput || errorOutput)
+ ? ((noResultsOutput ?? errorOutput)?.message ?? null)
+ : null;
+
+ return (
+ <div className="py-2">
+ <div className="flex items-center gap-2 text-sm text-muted-foreground">
+ <ToolIcon
+ toolType={part.type}
+ isStreaming={isStreaming}
+ isError={isError}
+ />
+ <MorphingTextAnimation
+ text={text}
+ className={isError ? "text-red-500" : undefined}
+ />
+ </div>
+
+ {hasExpandableContent && normalized && (
+ <ToolAccordion
+ icon={<AccordionIcon toolType={part.type} />}
+ title={normalized.title}
+ description={accordionDescription}
+ >
+ {docSearchOutput && (
+ <ContentGrid>
+ {docSearchOutput.results.map((r) => {
+ const href = r.doc_url ?? toDocsUrl(r.path);
+ return (
+ <ContentCard key={r.path}>
+ <ContentCardHeader
+ action={<ContentLink href={href}>Open</ContentLink>}
+ >
+ <ContentCardTitle>{r.title}</ContentCardTitle>
+ <ContentCardSubtitle>
+ {r.path}
+ {r.section ? ` • ${r.section}` : ""}
+ </ContentCardSubtitle>
+ <ContentCardDescription>
+ {truncate(r.snippet, 240)}
+ </ContentCardDescription>
+ </ContentCardHeader>
+ </ContentCard>
+ );
+ })}
+ </ContentGrid>
+ )}
+
+ {docPageOutput && (
+ <div>
+ <ContentCardHeader
+ action={
+ <ContentLink
+ href={
+ docPageOutput.doc_url ?? toDocsUrl(docPageOutput.path)
+ }
+ >
+ Open
+ </ContentLink>
+ }
+ >
+ <ContentCardTitle>{docPageOutput.title}</ContentCardTitle>
+ <ContentCardSubtitle>{docPageOutput.path}</ContentCardSubtitle>
+ </ContentCardHeader>
+ <ContentCardDescription className="whitespace-pre-wrap">
+ {truncate(docPageOutput.content, 800)}
+ </ContentCardDescription>
+ </div>
+ )}
+
+ {noResultsOutput && (
+ <div>
+ <ContentMessage>{noResultsOutput.message}</ContentMessage>
+ {noResultsOutput.suggestions &&
+ noResultsOutput.suggestions.length > 0 && (
+ <ContentSuggestionsList items={noResultsOutput.suggestions} />
+ )}
+ </div>
+ )}
+
+ {errorOutput && (
+ <div>
+ <ContentMessage>{errorOutput.message}</ContentMessage>
+ {errorOutput.error && (
+ <ContentCardDescription>
+ {errorOutput.error}
+ </ContentCardDescription>
+ )}
+ </div>
+ )}
+ </ToolAccordion>
+ )}
+ </div>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/SearchDocs/helpers.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/SearchDocs/helpers.tsx
new file mode 100644
index 0000000000..50a84edceb
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/SearchDocs/helpers.tsx
@@ -0,0 +1,215 @@
+import type { DocPageResponse } from "@/app/api/__generated__/models/docPageResponse";
+import type { DocSearchResultsResponse } from "@/app/api/__generated__/models/docSearchResultsResponse";
+import type { ErrorResponse } from "@/app/api/__generated__/models/errorResponse";
+import type { NoResultsResponse } from "@/app/api/__generated__/models/noResultsResponse";
+import { ResponseType } from "@/app/api/__generated__/models/responseType";
+import {
+ ArticleIcon,
+ FileMagnifyingGlassIcon,
+ FileTextIcon,
+} from "@phosphor-icons/react";
+import { ToolUIPart } from "ai";
+
+export interface SearchDocsInput {
+ query: string;
+}
+
+export interface GetDocPageInput {
+ path: string;
+}
+
+export type DocsToolOutput =
+ | DocSearchResultsResponse
+ | DocPageResponse
+ | NoResultsResponse
+ | ErrorResponse;
+
+export type DocsToolType = "tool-search_docs" | "tool-get_doc_page" | string;
+
+export function getToolLabel(toolType: DocsToolType): string {
+ switch (toolType) {
+ case "tool-search_docs":
+ return "Docs";
+ case "tool-get_doc_page":
+ return "Docs page";
+ default:
+ return "Docs";
+ }
+}
+
+function parseOutput(output: unknown): DocsToolOutput | null {
+ if (!output) return null;
+ if (typeof output === "string") {
+ const trimmed = output.trim();
+ if (!trimmed) return null;
+ try {
+ return parseOutput(JSON.parse(trimmed) as unknown);
+ } catch {
+ return null;
+ }
+ }
+ if (typeof output === "object") {
+ const type = (output as { type?: unknown }).type;
+ if (
+ type === ResponseType.doc_search_results ||
+ type === ResponseType.doc_page ||
+ type === ResponseType.no_results ||
+ type === ResponseType.error
+ ) {
+ return output as DocsToolOutput;
+ }
+ if ("results" in output && "query" in output)
+ return output as DocSearchResultsResponse;
+ if ("content" in output && "path" in output)
+ return output as DocPageResponse;
+ if ("suggestions" in output && !("error" in output))
+ return output as NoResultsResponse;
+ if ("error" in output || "details" in output)
+ return output as ErrorResponse;
+ }
+ return null;
+}
+
+export function getDocsToolOutput(part: unknown): DocsToolOutput | null {
+ if (!part || typeof part !== "object") return null;
+ return parseOutput((part as { output?: unknown }).output);
+}
+
+export function isDocSearchResultsOutput(
+ output: DocsToolOutput,
+): output is DocSearchResultsResponse {
+ return output.type === ResponseType.doc_search_results || "results" in output;
+}
+
+export function isDocPageOutput(
+ output: DocsToolOutput,
+): output is DocPageResponse {
+ return output.type === ResponseType.doc_page || "content" in output;
+}
+
+export function isNoResultsOutput(
+ output: DocsToolOutput,
+): output is NoResultsResponse {
+ return (
+ output.type === ResponseType.no_results ||
+ ("suggestions" in output && !("error" in output))
+ );
+}
+
+export function isErrorOutput(output: DocsToolOutput): output is ErrorResponse {
+ return output.type === ResponseType.error || "error" in output;
+}
+
+export function getDocsToolTitle(
+ toolType: DocsToolType,
+ output: DocsToolOutput,
+): string {
+ if (toolType === "tool-search_docs") {
+ if (isDocSearchResultsOutput(output)) return "Documentation results";
+ if (isNoResultsOutput(output)) return "No documentation found";
+ return "Documentation search error";
+ }
+
+ if (isDocPageOutput(output)) return "Documentation page";
+ if (isNoResultsOutput(output)) return "No documentation found";
+ return "Documentation page error";
+}
+
+export function getAnimationText(part: {
+ type: DocsToolType;
+ state: ToolUIPart["state"];
+ input?: unknown;
+ output?: unknown;
+}): string {
+ switch (part.type) {
+ case "tool-search_docs": {
+ const query = (part.input as SearchDocsInput | undefined)?.query?.trim();
+ const queryText = query ? ` for "${query}"` : "";
+
+ switch (part.state) {
+ case "input-streaming":
+ case "input-available":
+ return `Searching documentation${queryText}`;
+ case "output-available": {
+ const output = parseOutput(part.output);
+ if (!output) return `Searching documentation${queryText}`;
+ if (isDocSearchResultsOutput(output)) {
+ const count = output.count ?? output.results.length;
+ return `Found ${count} result${count === 1 ? "" : "s"}${queryText}`;
+ }
+ if (isNoResultsOutput(output)) {
+ return `No results found${queryText}`;
+ }
+ return `Error searching documentation${queryText}`;
+ }
+ case "output-error":
+ return `Error searching documentation${queryText}`;
+ default:
+ return "Searching documentation";
+ }
+ }
+ case "tool-get_doc_page": {
+ const path = (part.input as GetDocPageInput | undefined)?.path?.trim();
+ const pathText = path ? ` "${path}"` : "";
+
+ switch (part.state) {
+ case "input-streaming":
+ case "input-available":
+ return `Loading documentation page${pathText}`;
+ case "output-available": {
+ const output = parseOutput(part.output);
+ if (!output) return `Loading documentation page${pathText}`;
+ if (isDocPageOutput(output)) return `Loaded "${output.title}"`;
+ if (isNoResultsOutput(output)) return "Documentation page not found";
+ return "Error loading documentation page";
+ }
+ case "output-error":
+ return "Error loading documentation page";
+ default:
+ return "Loading documentation page";
+ }
+ }
+ }
+
+ return "Processing";
+}
+
+export function ToolIcon({
+ toolType,
+ isStreaming,
+ isError,
+}: {
+ toolType: DocsToolType;
+ isStreaming?: boolean;
+ isError?: boolean;
+}) {
+ const IconComponent =
+ toolType === "tool-get_doc_page" ? FileTextIcon : FileMagnifyingGlassIcon;
+
+ return (
+ <IconComponent
+ size={14}
+ weight="regular"
+ className={
+ isError
+ ? "text-red-500"
+ : isStreaming
+ ? "text-neutral-500"
+ : "text-neutral-400"
+ }
+ />
+ );
+}
+
+export function AccordionIcon({ toolType }: { toolType: DocsToolType }) {
+ const IconComponent =
+ toolType === "tool-get_doc_page" ? ArticleIcon : FileTextIcon;
+ return <IconComponent size={32} weight="light" />;
+}
+
+export function toDocsUrl(path: string): string {
+ const urlPath = path.includes(".")
+ ? path.slice(0, path.lastIndexOf("."))
+ : path;
+ return `https://docs.agpt.co/${urlPath}`;
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/ViewAgentOutput/ViewAgentOutput.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/ViewAgentOutput/ViewAgentOutput.tsx
new file mode 100644
index 0000000000..e7265ac7cb
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/ViewAgentOutput/ViewAgentOutput.tsx
@@ -0,0 +1,261 @@
+"use client";
+
+import type { ToolUIPart } from "ai";
+import React from "react";
+import { getGetWorkspaceDownloadFileByIdUrl } from "@/app/api/__generated__/endpoints/workspace/workspace";
+import {
+ globalRegistry,
+ OutputItem,
+} from "@/components/contextual/OutputRenderers";
+import type { OutputMetadata } from "@/components/contextual/OutputRenderers";
+import { MorphingTextAnimation } from "../../components/MorphingTextAnimation/MorphingTextAnimation";
+import { ToolAccordion } from "../../components/ToolAccordion/ToolAccordion";
+import {
+ ContentBadge,
+ ContentCard,
+ ContentCardHeader,
+ ContentCardSubtitle,
+ ContentCardTitle,
+ ContentCodeBlock,
+ ContentGrid,
+ ContentLink,
+ ContentMessage,
+ ContentSuggestionsList,
+} from "../../components/ToolAccordion/AccordionContent";
+import {
+ formatMaybeJson,
+ getAnimationText,
+ getViewAgentOutputToolOutput,
+ isAgentOutputResponse,
+ isErrorResponse,
+ isNoResultsResponse,
+ AccordionIcon,
+ ToolIcon,
+ type ViewAgentOutputToolOutput,
+} from "./helpers";
+
+export interface ViewAgentOutputToolPart {
+ type: string;
+ toolCallId: string;
+ state: ToolUIPart["state"];
+ input?: unknown;
+ output?: unknown;
+}
+
+interface Props {
+ part: ViewAgentOutputToolPart;
+}
+
+function isWorkspaceRef(value: unknown): value is string {
+ return typeof value === "string" && value.startsWith("workspace://");
+}
+
+function resolveForRenderer(value: unknown): {
+ value: unknown;
+ metadata?: OutputMetadata;
+} {
+ if (!isWorkspaceRef(value)) return { value };
+
+ const withoutPrefix = value.replace("workspace://", "");
+ const fileId = withoutPrefix.split("#")[0];
+ const apiPath = getGetWorkspaceDownloadFileByIdUrl(fileId);
+ const url = `/api/proxy${apiPath}`;
+
+ const hashIndex = value.indexOf("#");
+ const mimeHint =
+ hashIndex !== -1 ? value.slice(hashIndex + 1) || undefined : undefined;
+
+ const metadata: OutputMetadata = {};
+ if (mimeHint) {
+ metadata.mimeType = mimeHint;
+ if (mimeHint.startsWith("image/")) metadata.type = "image";
+ else if (mimeHint.startsWith("video/")) metadata.type = "video";
+ }
+
+ return { value: url, metadata };
+}
+
+function RenderOutputValue({ value }: { value: unknown }) {
+ const resolved = resolveForRenderer(value);
+ const renderer = globalRegistry.getRenderer(
+ resolved.value,
+ resolved.metadata,
+ );
+
+ if (renderer) {
+ return (
+ <OutputItem
+ value={resolved.value}
+ metadata={resolved.metadata}
+ renderer={renderer}
+ />
+ );
+ }
+
+ // Fallback for audio workspace refs
+ if (
+ isWorkspaceRef(value) &&
+ resolved.metadata?.mimeType?.startsWith("audio/")
+ ) {
+ return (
+ <audio controls src={String(resolved.value)} className="mt-2 w-full" />
+ );
+ }
+
+ return null;
+}
+
+function getAccordionMeta(output: ViewAgentOutputToolOutput): {
+ icon: React.ReactNode;
+ title: string;
+ description?: string;
+} {
+ const icon = <AccordionIcon />;
+
+ if (isAgentOutputResponse(output)) {
+ const status = output.execution?.status;
+ return {
+ icon,
+ title: output.agent_name,
+ description: status ? `Status: ${status}` : output.message,
+ };
+ }
+ if (isNoResultsResponse(output)) {
+ return { icon, title: "No results" };
+ }
+ return { icon, title: "Error" };
+}
+
+export function ViewAgentOutputTool({ part }: Props) {
+ const text = getAnimationText(part);
+ const isStreaming =
+ part.state === "input-streaming" || part.state === "input-available";
+
+ const output = getViewAgentOutputToolOutput(part);
+ const isError =
+ part.state === "output-error" || (!!output && isErrorResponse(output));
+ const hasExpandableContent =
+ part.state === "output-available" &&
+ !!output &&
+ (isAgentOutputResponse(output) ||
+ isNoResultsResponse(output) ||
+ isErrorResponse(output));
+
+ return (
+ <div className="py-2">
+ <div className="flex items-center gap-2 text-sm text-muted-foreground">
+ <ToolIcon isStreaming={isStreaming} isError={isError} />
+ <MorphingTextAnimation
+ text={text}
+ className={isError ? "text-red-500" : undefined}
+ />
+ </div>
+
+ {hasExpandableContent && output && (
+ <ToolAccordion {...getAccordionMeta(output)}>
+ {isAgentOutputResponse(output) && (
+ <ContentGrid>
+ <ContentCardHeader
+ className="gap-3"
+ action={
+ output.library_agent_link ? (
+ <ContentLink href={output.library_agent_link}>
+ Open
+ </ContentLink>
+ ) : null
+ }
+ >
+ <ContentMessage>{output.message}</ContentMessage>
+ </ContentCardHeader>
+
+ {output.execution ? (
+ <ContentGrid>
+ <ContentCard>
+ <ContentCardTitle className="text-xs">
+ Execution
+ </ContentCardTitle>
+ <ContentCardSubtitle className="mt-1">
+ {output.execution.execution_id}
+ </ContentCardSubtitle>
+ <ContentCardSubtitle className="mt-1">
+ Status: {output.execution.status}
+ </ContentCardSubtitle>
+ </ContentCard>
+
+ {output.execution.inputs_summary && (
+ <ContentCard>
+ <ContentCardTitle className="text-xs">
+ Inputs summary
+ </ContentCardTitle>
+ <div className="mt-2">
+ <RenderOutputValue
+ value={output.execution.inputs_summary}
+ />
+ </div>
+ </ContentCard>
+ )}
+
+ {Object.entries(output.execution.outputs ?? {}).map(
+ ([key, items]) => (
+ <ContentCard key={key}>
+ <div className="flex items-center justify-between gap-2">
+ <ContentCardTitle className="text-xs">
+ {key}
+ </ContentCardTitle>
+ <ContentBadge>
+ {items.length} item
+ {items.length === 1 ? "" : "s"}
+ </ContentBadge>
+ </div>
+ <div className="mt-2">
+ {items.slice(0, 3).map((item, i) => (
+ <RenderOutputValue key={i} value={item} />
+ ))}
+ </div>
+ </ContentCard>
+ ),
+ )}
+ </ContentGrid>
+ ) : (
+ <ContentCard>
+ <ContentMessage>No execution selected.</ContentMessage>
+ <ContentCardSubtitle className="mt-1">
+ Try asking for a specific run or execution_id.
+ </ContentCardSubtitle>
+ </ContentCard>
+ )}
+ </ContentGrid>
+ )}
+
+ {isNoResultsResponse(output) && (
+ <ContentGrid>
+ <ContentMessage>{output.message}</ContentMessage>
+ {output.suggestions && output.suggestions.length > 0 && (
+ <ContentSuggestionsList
+ items={output.suggestions}
+ className="mt-1"
+ />
+ )}
+ </ContentGrid>
+ )}
+
+ {isErrorResponse(output) && (
+ <ContentGrid>
+ <ContentMessage>{output.message}</ContentMessage>
+ {output.error && (
+ <ContentCodeBlock>
+ {formatMaybeJson(output.error)}
+ </ContentCodeBlock>
+ )}
+ {output.details && (
+ <ContentCodeBlock>
+ {formatMaybeJson(output.details)}
+ </ContentCodeBlock>
+ )}
+ </ContentGrid>
+ )}
+ </ToolAccordion>
+ )}
+ </div>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/ViewAgentOutput/helpers.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/ViewAgentOutput/helpers.tsx
new file mode 100644
index 0000000000..1ff2e64ec7
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/ViewAgentOutput/helpers.tsx
@@ -0,0 +1,158 @@
+import type { AgentOutputResponse } from "@/app/api/__generated__/models/agentOutputResponse";
+import type { ErrorResponse } from "@/app/api/__generated__/models/errorResponse";
+import type { NoResultsResponse } from "@/app/api/__generated__/models/noResultsResponse";
+import { ResponseType } from "@/app/api/__generated__/models/responseType";
+import { EyeIcon, MonitorIcon } from "@phosphor-icons/react";
+import type { ToolUIPart } from "ai";
+
+export interface ViewAgentOutputInput {
+ agent_name?: string;
+ library_agent_id?: string;
+ store_slug?: string;
+ execution_id?: string;
+ run_time?: string;
+}
+
+export type ViewAgentOutputToolOutput =
+ | AgentOutputResponse
+ | NoResultsResponse
+ | ErrorResponse;
+
+function parseOutput(output: unknown): ViewAgentOutputToolOutput | null {
+ if (!output) return null;
+ if (typeof output === "string") {
+ const trimmed = output.trim();
+ if (!trimmed) return null;
+ try {
+ return parseOutput(JSON.parse(trimmed) as unknown);
+ } catch {
+ return null;
+ }
+ }
+ if (typeof output === "object") {
+ const type = (output as { type?: unknown }).type;
+ if (
+ type === ResponseType.agent_output ||
+ type === ResponseType.no_results ||
+ type === ResponseType.error
+ ) {
+ return output as ViewAgentOutputToolOutput;
+ }
+ if ("agent_id" in output && "agent_name" in output) {
+ return output as AgentOutputResponse;
+ }
+ if ("suggestions" in output && !("error" in output)) {
+ return output as NoResultsResponse;
+ }
+ if ("error" in output || "details" in output)
+ return output as ErrorResponse;
+ }
+ return null;
+}
+
+export function isAgentOutputResponse(
+ output: ViewAgentOutputToolOutput,
+): output is AgentOutputResponse {
+ return output.type === ResponseType.agent_output || "agent_id" in output;
+}
+
+export function isNoResultsResponse(
+ output: ViewAgentOutputToolOutput,
+): output is NoResultsResponse {
+ return (
+ output.type === ResponseType.no_results ||
+ ("suggestions" in output && !("error" in output))
+ );
+}
+
+export function isErrorResponse(
+ output: ViewAgentOutputToolOutput,
+): output is ErrorResponse {
+ return output.type === ResponseType.error || "error" in output;
+}
+
+export function getViewAgentOutputToolOutput(
+ part: unknown,
+): ViewAgentOutputToolOutput | null {
+ if (!part || typeof part !== "object") return null;
+ return parseOutput((part as { output?: unknown }).output);
+}
+
+function getAgentIdentifierText(
+ input: ViewAgentOutputInput | undefined,
+): string | null {
+ if (!input) return null;
+ const libraryId = input.library_agent_id?.trim();
+ if (libraryId) return `Library agent ${libraryId}`;
+ const slug = input.store_slug?.trim();
+ if (slug) return slug;
+ const name = input.agent_name?.trim();
+ if (name) return name;
+ return null;
+}
+
+export function getAnimationText(part: {
+ state: ToolUIPart["state"];
+ input?: unknown;
+ output?: unknown;
+}): string {
+ const input = part.input as ViewAgentOutputInput | undefined;
+ const agent = getAgentIdentifierText(input);
+ const agentText = agent ? ` "${agent}"` : "";
+
+ switch (part.state) {
+ case "input-streaming":
+ case "input-available":
+ return `Retrieving agent output${agentText}`;
+ case "output-available": {
+ const output = parseOutput(part.output);
+ if (!output) return `Retrieving agent output${agentText}`;
+ if (isAgentOutputResponse(output)) {
+ if (output.execution)
+ return `Retrieved output (${output.execution.status})`;
+ return "Retrieved agent output";
+ }
+ if (isNoResultsResponse(output)) return "No outputs found";
+ return "Error loading agent output";
+ }
+ case "output-error":
+ return "Error loading agent output";
+ default:
+ return "Retrieving agent output";
+ }
+}
+
+export function ToolIcon({
+ isStreaming,
+ isError,
+}: {
+ isStreaming?: boolean;
+ isError?: boolean;
+}) {
+ return (
+ <EyeIcon
+ size={14}
+ weight="regular"
+ className={
+ isError
+ ? "text-red-500"
+ : isStreaming
+ ? "text-neutral-500"
+ : "text-neutral-400"
+ }
+ />
+ );
+}
+
+export function AccordionIcon() {
+ return <MonitorIcon size={32} weight="light" />;
+}
+
+export function formatMaybeJson(value: unknown): string {
+ if (typeof value === "string") return value;
+ try {
+ return JSON.stringify(value, null, 2);
+ } catch {
+ return String(value);
+ }
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useChatSession.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useChatSession.ts
new file mode 100644
index 0000000000..ac9213e119
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useChatSession.ts
@@ -0,0 +1,109 @@
+import {
+ getGetV2GetSessionQueryKey,
+ getGetV2ListSessionsQueryKey,
+ useGetV2GetSession,
+ usePostV2CreateSession,
+} from "@/app/api/__generated__/endpoints/chat/chat";
+import { toast } from "@/components/molecules/Toast/use-toast";
+import * as Sentry from "@sentry/nextjs";
+import { useQueryClient } from "@tanstack/react-query";
+import { parseAsString, useQueryState } from "nuqs";
+import { useEffect, useMemo, useRef } from "react";
+import { convertChatSessionMessagesToUiMessages } from "./helpers/convertChatSessionToUiMessages";
+
+export function useChatSession() {
+ const [sessionId, setSessionId] = useQueryState("sessionId", parseAsString);
+ const queryClient = useQueryClient();
+
+ const sessionQuery = useGetV2GetSession(sessionId ?? "", {
+ query: {
+ enabled: !!sessionId,
+ staleTime: Infinity,
+ refetchOnWindowFocus: false,
+ refetchOnReconnect: false,
+ },
+ });
+
+ // When the user navigates away from a session, invalidate its query cache.
+ // useChat destroys its Chat instance on id change, so messages are lost.
+ // Invalidating ensures the next visit fetches fresh data from the API
+ // instead of hydrating from stale cache that's missing recent messages.
+ const prevSessionIdRef = useRef(sessionId);
+
+ useEffect(() => {
+ const prev = prevSessionIdRef.current;
+ prevSessionIdRef.current = sessionId;
+ if (prev && prev !== sessionId) {
+ queryClient.invalidateQueries({
+ queryKey: getGetV2GetSessionQueryKey(prev),
+ });
+ }
+ }, [sessionId, queryClient]);
+
+ // Memoize so the effect in useCopilotPage doesn't infinite-loop on a new
+ // array reference every render. Re-derives only when query data changes.
+ const hydratedMessages = useMemo(() => {
+ if (sessionQuery.data?.status !== 200 || !sessionId) return undefined;
+ return convertChatSessionMessagesToUiMessages(
+ sessionId,
+ sessionQuery.data.data.messages ?? [],
+ );
+ }, [sessionQuery.data, sessionId]);
+
+ const { mutateAsync: createSessionMutation, isPending: isCreatingSession } =
+ usePostV2CreateSession({
+ mutation: {
+ onSuccess: (response) => {
+ if (response.status === 200 && response.data?.id) {
+ setSessionId(response.data.id);
+ queryClient.invalidateQueries({
+ queryKey: getGetV2ListSessionsQueryKey(),
+ });
+ }
+ },
+ },
+ });
+
+ async function createSession() {
+ if (sessionId) return sessionId;
+ try {
+ const response = await createSessionMutation();
+ if (response.status !== 200 || !response.data?.id) {
+ const error = new Error("Failed to create session");
+ Sentry.captureException(error, {
+ extra: { status: response.status },
+ });
+ toast({
+ variant: "destructive",
+ title: "Could not start a new chat session",
+ description: "Please try again.",
+ });
+ throw error;
+ }
+ return response.data.id;
+ } catch (error) {
+ if (
+ error instanceof Error &&
+ error.message === "Failed to create session"
+ ) {
+ throw error; // already handled above
+ }
+ Sentry.captureException(error);
+ toast({
+ variant: "destructive",
+ title: "Could not start a new chat session",
+ description: "Please try again.",
+ });
+ throw error;
+ }
+ }
+
+ return {
+ sessionId,
+ setSessionId,
+ hydratedMessages,
+ isLoadingSession: sessionQuery.isLoading,
+ createSession,
+ isCreatingSession,
+ };
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPage.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPage.ts
index 9d99f8e7bd..3dbba6e790 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPage.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPage.ts
@@ -1,127 +1,142 @@
-import {
- getGetV2ListSessionsQueryKey,
- postV2CreateSession,
-} from "@/app/api/__generated__/endpoints/chat/chat";
-import { useToast } from "@/components/molecules/Toast/use-toast";
+import { useGetV2ListSessions } from "@/app/api/__generated__/endpoints/chat/chat";
+import { useBreakpoint } from "@/lib/hooks/useBreakpoint";
import { useSupabase } from "@/lib/supabase/hooks/useSupabase";
-import { useOnboarding } from "@/providers/onboarding/onboarding-provider";
-import { SessionKey, sessionStorage } from "@/services/storage/session-storage";
-import * as Sentry from "@sentry/nextjs";
-import { useQueryClient } from "@tanstack/react-query";
-import { useRouter } from "next/navigation";
-import { useEffect } from "react";
-import { useCopilotStore } from "./copilot-page-store";
-import { getGreetingName, getQuickActions } from "./helpers";
-import { useCopilotSessionId } from "./useCopilotSessionId";
+import { useChat } from "@ai-sdk/react";
+import { DefaultChatTransport } from "ai";
+import { useEffect, useMemo, useState } from "react";
+import { useChatSession } from "./useChatSession";
export function useCopilotPage() {
- const router = useRouter();
- const queryClient = useQueryClient();
- const { user, isLoggedIn, isUserLoading } = useSupabase();
- const { toast } = useToast();
- const { completeStep } = useOnboarding();
+ const { isUserLoading, isLoggedIn } = useSupabase();
+ const [isDrawerOpen, setIsDrawerOpen] = useState(false);
+ const [pendingMessage, setPendingMessage] = useState<string | null>(null);
+
+ const {
+ sessionId,
+ setSessionId,
+ hydratedMessages,
+ isLoadingSession,
+ createSession,
+ isCreatingSession,
+ } = useChatSession();
+
+ const breakpoint = useBreakpoint();
+ const isMobile =
+ breakpoint === "base" || breakpoint === "sm" || breakpoint === "md";
+
+ const transport = useMemo(
+ () =>
+ sessionId
+ ? new DefaultChatTransport({
+ api: `/api/chat/sessions/${sessionId}/stream`,
+ prepareSendMessagesRequest: ({ messages }) => {
+ const last = messages[messages.length - 1];
+ return {
+ body: {
+ message: (
+ last.parts?.map((p) => (p.type === "text" ? p.text : "")) ??
+ []
+ ).join(""),
+ is_user_message: last.role === "user",
+ context: null,
+ },
+ };
+ },
+ })
+ : null,
+ [sessionId],
+ );
+
+ const { messages, sendMessage, stop, status, error, setMessages } = useChat({
+ id: sessionId ?? undefined,
+ transport: transport ?? undefined,
+ });
- const { urlSessionId, setUrlSessionId } = useCopilotSessionId();
- const setIsStreaming = useCopilotStore((s) => s.setIsStreaming);
- const isCreating = useCopilotStore((s) => s.isCreatingSession);
- const setIsCreating = useCopilotStore((s) => s.setIsCreatingSession);
-
- const greetingName = getGreetingName(user);
- const quickActions = getQuickActions();
-
- const hasSession = Boolean(urlSessionId);
- const initialPrompt = urlSessionId
- ? getInitialPrompt(urlSessionId)
- : undefined;
+ useEffect(() => {
+ if (!hydratedMessages || hydratedMessages.length === 0) return;
+ setMessages((prev) => {
+ if (prev.length >= hydratedMessages.length) return prev;
+ return hydratedMessages;
+ });
+ }, [hydratedMessages, setMessages]);
+
+ // Clear messages when session is null
+ useEffect(() => {
+ if (!sessionId) setMessages([]);
+ }, [sessionId, setMessages]);
useEffect(() => {
- if (isLoggedIn) completeStep("VISIT_COPILOT");
- }, [completeStep, isLoggedIn]);
-
- async function startChatWithPrompt(prompt: string) {
- if (!prompt?.trim()) return;
- if (isCreating) return;
-
- const trimmedPrompt = prompt.trim();
- setIsCreating(true);
-
- try {
- const sessionResponse = await postV2CreateSession({
- body: JSON.stringify({}),
- });
-
- if (sessionResponse.status !== 200 || !sessionResponse.data?.id) {
- throw new Error("Failed to create session");
- }
-
- const sessionId = sessionResponse.data.id;
- setInitialPrompt(sessionId, trimmedPrompt);
-
- await queryClient.invalidateQueries({
- queryKey: getGetV2ListSessionsQueryKey(),
- });
-
- await setUrlSessionId(sessionId, { shallow: true });
- } catch (error) {
- console.error("[CopilotPage] Failed to start chat:", error);
- toast({ title: "Failed to start chat", variant: "destructive" });
- Sentry.captureException(error);
- } finally {
- setIsCreating(false);
+ if (!sessionId || !pendingMessage) return;
+ const msg = pendingMessage;
+ setPendingMessage(null);
+ sendMessage({ text: msg });
+ }, [sessionId, pendingMessage, sendMessage]);
+
+ async function onSend(message: string) {
+ const trimmed = message.trim();
+ if (!trimmed) return;
+
+ if (sessionId) {
+ sendMessage({ text: trimmed });
+ return;
}
- }
- function handleQuickAction(action: string) {
- startChatWithPrompt(action);
+ setPendingMessage(trimmed);
+ await createSession();
}
- function handleSessionNotFound() {
- router.replace("/copilot");
+ const { data: sessionsResponse, isLoading: isLoadingSessions } =
+ useGetV2ListSessions(
+ { limit: 50 },
+ { query: { enabled: !isUserLoading && isLoggedIn } },
+ );
+
+ const sessions =
+ sessionsResponse?.status === 200 ? sessionsResponse.data.sessions : [];
+
+ function handleOpenDrawer() {
+ setIsDrawerOpen(true);
}
- function handleStreamingChange(isStreamingValue: boolean) {
- setIsStreaming(isStreamingValue);
+ function handleCloseDrawer() {
+ setIsDrawerOpen(false);
}
- return {
- state: {
- greetingName,
- quickActions,
- isLoading: isUserLoading,
- hasSession,
- initialPrompt,
- },
- handlers: {
- handleQuickAction,
- startChatWithPrompt,
- handleSessionNotFound,
- handleStreamingChange,
- },
- };
-}
+ function handleDrawerOpenChange(open: boolean) {
+ setIsDrawerOpen(open);
+ }
-function getInitialPrompt(sessionId: string): string | undefined {
- try {
- const prompts = JSON.parse(
- sessionStorage.get(SessionKey.CHAT_INITIAL_PROMPTS) || "{}",
- );
- return prompts[sessionId];
- } catch {
- return undefined;
+ function handleSelectSession(id: string) {
+ setSessionId(id);
+ if (isMobile) setIsDrawerOpen(false);
}
-}
-function setInitialPrompt(sessionId: string, prompt: string): void {
- try {
- const prompts = JSON.parse(
- sessionStorage.get(SessionKey.CHAT_INITIAL_PROMPTS) || "{}",
- );
- prompts[sessionId] = prompt;
- sessionStorage.set(
- SessionKey.CHAT_INITIAL_PROMPTS,
- JSON.stringify(prompts),
- );
- } catch {
- // Ignore storage errors
+ function handleNewChat() {
+ setSessionId(null);
+ if (isMobile) setIsDrawerOpen(false);
}
+
+ return {
+ sessionId,
+ messages,
+ status,
+ error,
+ stop,
+ isLoadingSession,
+ isCreatingSession,
+ isUserLoading,
+ isLoggedIn,
+ createSession,
+ onSend,
+ // Mobile drawer
+ isMobile,
+ isDrawerOpen,
+ sessions,
+ isLoadingSessions,
+ handleOpenDrawer,
+ handleCloseDrawer,
+ handleDrawerOpenChange,
+ handleSelectSession,
+ handleNewChat,
+ };
}
diff --git a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/selected-views/RunDetailHeader/RunDetailHeader.tsx b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/selected-views/RunDetailHeader/RunDetailHeader.tsx
index 3d04234bb3..4e98c70de5 100644
--- a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/selected-views/RunDetailHeader/RunDetailHeader.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/selected-views/RunDetailHeader/RunDetailHeader.tsx
@@ -2,7 +2,7 @@ import { GraphExecution } from "@/app/api/__generated__/models/graphExecution";
import { LibraryAgent } from "@/app/api/__generated__/models/libraryAgent";
import { Text } from "@/components/atoms/Text/Text";
import { ClockClockwiseIcon } from "@phosphor-icons/react";
-import moment from "moment";
+import { formatDistanceToNow, formatDistanceStrict } from "date-fns";
import { AGENT_LIBRARY_SECTION_PADDING_X } from "../../../helpers";
import { RunStatusBadge } from "../SelectedRunView/components/RunStatusBadge";
@@ -43,7 +43,10 @@ export function RunDetailHeader({ agent, run, scheduleRecurrence }: Props) {
{run ? (
<div className="mt-1 flex flex-wrap items-center gap-2 gap-y-1 text-zinc-400">
<Text variant="small" className="text-zinc-500">
- Started {moment(run.started_at).fromNow()}
+ Started{" "}
+ {run.started_at
+ ? formatDistanceToNow(run.started_at, { addSuffix: true })
+ : "—"}
</Text>
<span className="mx-1 inline-block text-zinc-200">|</span>
<Text variant="small" className="text-zinc-500">
@@ -62,7 +65,7 @@ export function RunDetailHeader({ agent, run, scheduleRecurrence }: Props) {
<span className="mx-1 inline-block text-zinc-200">|</span>
<Text variant="small" className="text-zinc-500">
Duration:{" "}
- {moment.duration(run.stats.duration, "seconds").humanize()}
+ {formatDistanceStrict(0, run.stats.duration * 1000)}
</Text>
</>
)}
diff --git a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/sidebar/SidebarRunsList/components/ScheduleListItem.tsx b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/sidebar/SidebarRunsList/components/ScheduleListItem.tsx
index a389fb4fc8..1ad40fcef4 100644
--- a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/sidebar/SidebarRunsList/components/ScheduleListItem.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/sidebar/SidebarRunsList/components/ScheduleListItem.tsx
@@ -3,7 +3,7 @@
import { GraphExecutionJobInfo } from "@/app/api/__generated__/models/graphExecutionJobInfo";
import { LibraryAgent } from "@/app/api/__generated__/models/libraryAgent";
import { ClockClockwiseIcon } from "@phosphor-icons/react";
-import moment from "moment";
+import { formatDistanceToNow } from "date-fns";
import { IconWrapper } from "./IconWrapper";
import { ScheduleActionsDropdown } from "./ScheduleActionsDropdown";
import { SidebarItemCard } from "./SidebarItemCard";
@@ -26,7 +26,9 @@ export function ScheduleListItem({
return (
<SidebarItemCard
title={schedule.name}
- description={moment(schedule.next_run_time).fromNow()}
+ description={formatDistanceToNow(schedule.next_run_time, {
+ addSuffix: true,
+ })}
onClick={onClick}
selected={selected}
icon={
diff --git a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/sidebar/SidebarRunsList/components/TaskListItem.tsx b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/sidebar/SidebarRunsList/components/TaskListItem.tsx
index 2e2871e15e..8970e82b64 100644
--- a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/sidebar/SidebarRunsList/components/TaskListItem.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/sidebar/SidebarRunsList/components/TaskListItem.tsx
@@ -11,7 +11,7 @@ import {
WarningCircleIcon,
XCircleIcon,
} from "@phosphor-icons/react";
-import moment from "moment";
+import { formatDistanceToNow } from "date-fns";
import React from "react";
import { IconWrapper } from "./IconWrapper";
import { SidebarItemCard } from "./SidebarItemCard";
@@ -76,7 +76,11 @@ export function TaskListItem({
<SidebarItemCard
icon={statusIconMap[run.status]}
title={title}
- description={moment(run.started_at).fromNow()}
+ description={
+ run.started_at
+ ? formatDistanceToNow(run.started_at, { addSuffix: true })
+ : "—"
+ }
onClick={onClick}
selected={selected}
actions={
diff --git a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/sidebar/SidebarRunsList/components/TemplateListItem.tsx b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/sidebar/SidebarRunsList/components/TemplateListItem.tsx
index c970cd1522..2cc3cbe203 100644
--- a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/sidebar/SidebarRunsList/components/TemplateListItem.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/sidebar/SidebarRunsList/components/TemplateListItem.tsx
@@ -3,7 +3,7 @@
import { LibraryAgent } from "@/app/api/__generated__/models/libraryAgent";
import { LibraryAgentPreset } from "@/app/api/__generated__/models/libraryAgentPreset";
import { FileTextIcon } from "@phosphor-icons/react";
-import moment from "moment";
+import { formatDistanceToNow } from "date-fns";
import { IconWrapper } from "./IconWrapper";
import { SidebarItemCard } from "./SidebarItemCard";
import { TemplateActionsDropdown } from "./TemplateActionsDropdown";
@@ -31,7 +31,9 @@ export function TemplateListItem({
</IconWrapper>
}
title={template.name}
- description={moment(template.updated_at).fromNow()}
+ description={formatDistanceToNow(template.updated_at, {
+ addSuffix: true,
+ })}
onClick={onClick}
selected={selected}
actions={
diff --git a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/sidebar/SidebarRunsList/components/TriggerListItem.tsx b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/sidebar/SidebarRunsList/components/TriggerListItem.tsx
index 4c399e640a..c7b0473a9b 100644
--- a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/sidebar/SidebarRunsList/components/TriggerListItem.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/sidebar/SidebarRunsList/components/TriggerListItem.tsx
@@ -3,7 +3,7 @@
import { LibraryAgent } from "@/app/api/__generated__/models/libraryAgent";
import { LibraryAgentPreset } from "@/app/api/__generated__/models/libraryAgentPreset";
import { LightningIcon } from "@phosphor-icons/react";
-import moment from "moment";
+import { formatDistanceToNow } from "date-fns";
import { IconWrapper } from "./IconWrapper";
import { SidebarItemCard } from "./SidebarItemCard";
import { TriggerActionsDropdown } from "./TriggerActionsDropdown";
@@ -31,7 +31,7 @@ export function TriggerListItem({
</IconWrapper>
}
title={trigger.name}
- description={moment(trigger.updated_at).fromNow()}
+ description={formatDistanceToNow(trigger.updated_at, { addSuffix: true })}
onClick={onClick}
selected={selected}
actions={
diff --git a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/OldAgentLibraryView/components/agent-run-details-view.tsx b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/OldAgentLibraryView/components/agent-run-details-view.tsx
index f51c44c243..eb5224c958 100644
--- a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/OldAgentLibraryView/components/agent-run-details-view.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/OldAgentLibraryView/components/agent-run-details-view.tsx
@@ -1,5 +1,5 @@
"use client";
-import moment from "moment";
+import { format, formatDistanceToNow, formatDistanceStrict } from "date-fns";
import React, { useCallback, useMemo, useEffect } from "react";
import {
@@ -90,13 +90,15 @@ export function AgentRunDetailsView({
},
{
label: "Started",
- value: `${moment(run.started_at).fromNow()}, ${moment(run.started_at).format("HH:mm")}`,
+ value: run.started_at
+ ? `${formatDistanceToNow(run.started_at, { addSuffix: true })}, ${format(run.started_at, "HH:mm")}`
+ : "—",
},
...(run.stats
? [
{
label: "Duration",
- value: moment.duration(run.stats.duration, "seconds").humanize(),
+ value: formatDistanceStrict(0, run.stats.duration * 1000),
},
{ label: "Steps", value: run.stats.node_exec_count },
{ label: "Cost", value: formatCredits(run.stats.cost) },
diff --git a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/OldAgentLibraryView/components/agent-run-summary-card.tsx b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/OldAgentLibraryView/components/agent-run-summary-card.tsx
index 423495878b..6f7d7865bc 100644
--- a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/OldAgentLibraryView/components/agent-run-summary-card.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/OldAgentLibraryView/components/agent-run-summary-card.tsx
@@ -1,5 +1,5 @@
import React from "react";
-import moment from "moment";
+import { formatDistanceToNow, isPast } from "date-fns";
import { cn } from "@/lib/utils";
@@ -118,10 +118,10 @@ export function AgentRunSummaryCard({
{timestamp && (
<p
className="mt-1 text-sm font-normal text-neutral-500"
- title={moment(timestamp).toString()}
+ title={new Date(timestamp).toString()}
>
- {moment(timestamp).isBefore() ? "Ran" : "Runs in"}{" "}
- {moment(timestamp).fromNow()}
+ {isPast(timestamp) ? "Ran" : "Runs in"}{" "}
+ {formatDistanceToNow(timestamp, { addSuffix: true })}
</p>
)}
</CardContent>
diff --git a/autogpt_platform/frontend/src/app/(platform)/library/components/LibrarySearchBar/useLibrarySearchbar.tsx b/autogpt_platform/frontend/src/app/(platform)/library/components/LibrarySearchBar/useLibrarySearchbar.tsx
index 74b8e9874c..efeb654ed5 100644
--- a/autogpt_platform/frontend/src/app/(platform)/library/components/LibrarySearchBar/useLibrarySearchbar.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/library/components/LibrarySearchBar/useLibrarySearchbar.tsx
@@ -1,4 +1,4 @@
-import { debounce } from "lodash";
+import debounce from "lodash/debounce";
import { useCallback, useEffect } from "react";
interface Props {
diff --git a/autogpt_platform/frontend/src/app/(platform)/monitoring/components/AgentFlowList.tsx b/autogpt_platform/frontend/src/app/(platform)/monitoring/components/AgentFlowList.tsx
index badba61bf1..a306275f10 100644
--- a/autogpt_platform/frontend/src/app/(platform)/monitoring/components/AgentFlowList.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/monitoring/components/AgentFlowList.tsx
@@ -30,7 +30,7 @@ import {
TableHeader,
TableRow,
} from "@/components/__legacy__/ui/table";
-import moment from "moment/moment";
+import { formatDistanceToNow } from "date-fns";
import { DialogTitle } from "@/components/__legacy__/ui/dialog";
import { AgentImportForm } from "./AgentImportForm";
@@ -161,8 +161,12 @@ export const AgentFlowList = ({
(!lastRun ? (
<TableCell />
) : (
- <TableCell title={moment(lastRun.started_at).toString()}>
- {moment(lastRun.started_at).fromNow()}
+ <TableCell title={lastRun.started_at?.toString() ?? ""}>
+ {lastRun.started_at
+ ? formatDistanceToNow(lastRun.started_at, {
+ addSuffix: true,
+ })
+ : "—"}
</TableCell>
))}
</TableRow>
diff --git a/autogpt_platform/frontend/src/app/(platform)/monitoring/components/FlowRunInfo.tsx b/autogpt_platform/frontend/src/app/(platform)/monitoring/components/FlowRunInfo.tsx
index e619c2fd3d..0fdf39e8d9 100644
--- a/autogpt_platform/frontend/src/app/(platform)/monitoring/components/FlowRunInfo.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/monitoring/components/FlowRunInfo.tsx
@@ -10,7 +10,7 @@ import Link from "next/link";
import { Button, buttonVariants } from "@/components/__legacy__/ui/button";
import { IconSquare } from "@/components/__legacy__/ui/icons";
import { ExitIcon, Pencil2Icon } from "@radix-ui/react-icons";
-import moment from "moment/moment";
+import { format } from "date-fns";
import { FlowRunStatusBadge } from "@/app/(platform)/monitoring/components/FlowRunStatusBadge";
import { useBackendAPI } from "@/lib/autogpt-server-api/context";
import RunnerOutputUI, {
@@ -111,11 +111,15 @@ export const FlowRunInfo: React.FC<
</div>
<p>
<strong>Started:</strong>{" "}
- {moment(execution.started_at).format("YYYY-MM-DD HH:mm:ss")}
+ {execution.started_at
+ ? format(execution.started_at, "yyyy-MM-dd HH:mm:ss")
+ : "—"}
</p>
<p>
<strong>Finished:</strong>{" "}
- {moment(execution.ended_at).format("YYYY-MM-DD HH:mm:ss")}
+ {execution.ended_at
+ ? format(execution.ended_at, "yyyy-MM-dd HH:mm:ss")
+ : "—"}
</p>
{execution.stats && (
<p>
diff --git a/autogpt_platform/frontend/src/app/(platform)/monitoring/components/FlowRunsList.tsx b/autogpt_platform/frontend/src/app/(platform)/monitoring/components/FlowRunsList.tsx
index a99d9309b5..c4a2a40447 100644
--- a/autogpt_platform/frontend/src/app/(platform)/monitoring/components/FlowRunsList.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/monitoring/components/FlowRunsList.tsx
@@ -14,7 +14,7 @@ import {
TableHeader,
TableRow,
} from "@/components/__legacy__/ui/table";
-import moment from "moment/moment";
+import { format } from "date-fns";
import { FlowRunStatusBadge } from "@/app/(platform)/monitoring/components/FlowRunStatusBadge";
import { TextRenderer } from "../../../../components/__legacy__/ui/render";
@@ -59,7 +59,9 @@ export const FlowRunsList: React.FC<{
/>
</TableCell>
<TableCell>
- {moment(execution.started_at).format("HH:mm")}
+ {execution.started_at
+ ? format(execution.started_at, "HH:mm")
+ : "—"}
</TableCell>
<TableCell>
<FlowRunStatusBadge
diff --git a/autogpt_platform/frontend/src/app/(platform)/monitoring/components/FlowRunsTimeline.tsx b/autogpt_platform/frontend/src/app/(platform)/monitoring/components/FlowRunsTimeline.tsx
index ee01d67234..c54209e1df 100644
--- a/autogpt_platform/frontend/src/app/(platform)/monitoring/components/FlowRunsTimeline.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/monitoring/components/FlowRunsTimeline.tsx
@@ -10,7 +10,7 @@ import {
XAxis,
YAxis,
} from "recharts";
-import moment from "moment/moment";
+import { differenceInHours, format } from "date-fns";
import { Card } from "@/components/__legacy__/ui/card";
import { cn, hashString } from "@/lib/utils";
import React from "react";
@@ -43,11 +43,11 @@ export const FlowRunsTimeline = ({
]}
allowDataOverflow={true}
tickFormatter={(unixTime) => {
- const now = moment();
- const time = moment(unixTime);
- return now.diff(time, "hours") < 24
- ? time.format("HH:mm")
- : time.format("YYYY-MM-DD HH:mm");
+ const now = new Date();
+ const time = new Date(unixTime);
+ return differenceInHours(now, time) < 24
+ ? format(time, "HH:mm")
+ : format(time, "yyyy-MM-dd HH:mm");
}}
name="Time"
scale="time"
@@ -79,7 +79,9 @@ export const FlowRunsTimeline = ({
</div>
<p>
<strong>Started:</strong>{" "}
- {moment(data.started_at).format("YYYY-MM-DD HH:mm:ss")}
+ {data.started_at
+ ? format(data.started_at, "yyyy-MM-dd HH:mm:ss")
+ : "—"}
</p>
{data.stats && (
<p>
diff --git a/autogpt_platform/frontend/src/app/api/chat/sessions/[sessionId]/stream/route.ts b/autogpt_platform/frontend/src/app/api/chat/sessions/[sessionId]/stream/route.ts
index d63eed0ca2..6facf80c58 100644
--- a/autogpt_platform/frontend/src/app/api/chat/sessions/[sessionId]/stream/route.ts
+++ b/autogpt_platform/frontend/src/app/api/chat/sessions/[sessionId]/stream/route.ts
@@ -88,39 +88,27 @@ export async function POST(
}
/**
- * Legacy GET endpoint for backward compatibility
+ * Resume an active stream for a session.
+ *
+ * Called by the AI SDK's `useChat(resume: true)` on page load.
+ * Proxies to the backend which checks for an active stream and either
+ * replays it (200 + SSE) or returns 204 No Content.
*/
export async function GET(
- request: NextRequest,
+ _request: NextRequest,
{ params }: { params: Promise<{ sessionId: string }> },
) {
const { sessionId } = await params;
- const searchParams = request.nextUrl.searchParams;
- const message = searchParams.get("message");
- const isUserMessage = searchParams.get("is_user_message");
-
- if (!message) {
- return new Response("Missing message parameter", { status: 400 });
- }
try {
- // Get auth token from server-side session
const token = await getServerAuthToken();
- // Build backend URL
const backendUrl = environment.getAGPTServerBaseUrl();
const streamUrl = new URL(
`/api/chat/sessions/${sessionId}/stream`,
backendUrl,
);
- streamUrl.searchParams.set("message", message);
-
- // Pass is_user_message parameter if provided
- if (isUserMessage !== null) {
- streamUrl.searchParams.set("is_user_message", isUserMessage);
- }
- // Forward request to backend with auth header
const headers: Record<string, string> = {
Accept: "text/event-stream",
"Cache-Control": "no-cache",
@@ -136,6 +124,11 @@ export async function GET(
headers,
});
+ // 204 = no active stream to resume
+ if (response.status === 204) {
+ return new Response(null, { status: 204 });
+ }
+
if (!response.ok) {
const error = await response.text();
return new Response(error, {
@@ -144,17 +137,17 @@ export async function GET(
});
}
- // Return the SSE stream directly
return new Response(response.body, {
headers: {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache, no-transform",
Connection: "keep-alive",
"X-Accel-Buffering": "no",
+ "x-vercel-ai-ui-message-stream": "v1",
},
});
} catch (error) {
- console.error("SSE proxy error:", error);
+ console.error("Resume stream proxy error:", error);
return new Response(
JSON.stringify({
error: "Failed to connect to chat service",
diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.json
index ccf5ad3e34..172419d27e 100644
--- a/autogpt_platform/frontend/src/app/api/openapi.json
+++ b/autogpt_platform/frontend/src/app/api/openapi.json
@@ -1018,6 +1018,58 @@
}
}
},
+ "/api/chat/schema/tool-responses": {
+ "get": {
+ "tags": ["v2", "chat", "chat"],
+ "summary": "[Dummy] Tool response type export for codegen",
+ "description": "This endpoint is not meant to be called. It exists solely to expose tool response models in the OpenAPI schema for frontend codegen.",
+ "operationId": "getV2[dummy] tool response type export for codegen",
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "anyOf": [
+ { "$ref": "#/components/schemas/AgentsFoundResponse" },
+ { "$ref": "#/components/schemas/NoResultsResponse" },
+ { "$ref": "#/components/schemas/AgentDetailsResponse" },
+ {
+ "$ref": "#/components/schemas/SetupRequirementsResponse"
+ },
+ { "$ref": "#/components/schemas/ExecutionStartedResponse" },
+ { "$ref": "#/components/schemas/NeedLoginResponse" },
+ { "$ref": "#/components/schemas/ErrorResponse" },
+ {
+ "$ref": "#/components/schemas/InputValidationErrorResponse"
+ },
+ { "$ref": "#/components/schemas/AgentOutputResponse" },
+ {
+ "$ref": "#/components/schemas/UnderstandingUpdatedResponse"
+ },
+ { "$ref": "#/components/schemas/AgentPreviewResponse" },
+ { "$ref": "#/components/schemas/AgentSavedResponse" },
+ {
+ "$ref": "#/components/schemas/ClarificationNeededResponse"
+ },
+ { "$ref": "#/components/schemas/BlockListResponse" },
+ { "$ref": "#/components/schemas/BlockOutputResponse" },
+ { "$ref": "#/components/schemas/DocSearchResultsResponse" },
+ { "$ref": "#/components/schemas/DocPageResponse" },
+ { "$ref": "#/components/schemas/OperationStartedResponse" },
+ { "$ref": "#/components/schemas/OperationPendingResponse" },
+ {
+ "$ref": "#/components/schemas/OperationInProgressResponse"
+ }
+ ],
+ "title": "Response Getv2[Dummy] Tool Response Type Export For Codegen"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/api/chat/sessions": {
"get": {
"tags": ["v2", "chat", "chat"],
@@ -1182,9 +1234,9 @@
"/api/chat/sessions/{session_id}/stream": {
"get": {
"tags": ["v2", "chat", "chat"],
- "summary": "Stream Chat Get",
- "description": "Stream chat responses for a session (GET - legacy endpoint).\n\nStreams the AI/completion responses in real time over Server-Sent Events (SSE), including:\n - Text fragments as they are generated\n - Tool call UI elements (if invoked)\n - Tool execution results\n\nArgs:\n session_id: The chat session identifier to associate with the streamed messages.\n message: The user's new message to process.\n user_id: Optional authenticated user ID.\n is_user_message: Whether the message is a user message.\nReturns:\n StreamingResponse: SSE-formatted response chunks.",
- "operationId": "getV2StreamChatGet",
+ "summary": "Resume Session Stream",
+ "description": "Resume an active stream for a session.\n\nCalled by the AI SDK's ``useChat(resume: true)`` on page load.\nChecks for an active (in-progress) task on the session and either replays\nthe full SSE stream or returns 204 No Content if nothing is running.\n\nArgs:\n session_id: The chat session identifier.\n user_id: Optional authenticated user ID.\n\nReturns:\n StreamingResponse (SSE) when an active stream exists,\n or 204 No Content when there is nothing to resume.",
+ "operationId": "getV2ResumeSessionStream",
"security": [{ "HTTPBearerJWT": [] }],
"parameters": [
{
@@ -1192,27 +1244,6 @@
"in": "path",
"required": true,
"schema": { "type": "string", "title": "Session Id" }
- },
- {
- "name": "message",
- "in": "query",
- "required": true,
- "schema": {
- "type": "string",
- "minLength": 1,
- "maxLength": 10000,
- "title": "Message"
- }
- },
- {
- "name": "is_user_message",
- "in": "query",
- "required": false,
- "schema": {
- "type": "boolean",
- "default": true,
- "title": "Is User Message"
- }
}
],
"responses": {
@@ -6358,6 +6389,75 @@
"required": ["new_balance", "transaction_key"],
"title": "AddUserCreditsResponse"
},
+ "AgentDetails": {
+ "properties": {
+ "id": { "type": "string", "title": "Id" },
+ "name": { "type": "string", "title": "Name" },
+ "description": { "type": "string", "title": "Description" },
+ "in_library": {
+ "type": "boolean",
+ "title": "In Library",
+ "default": false
+ },
+ "inputs": {
+ "additionalProperties": true,
+ "type": "object",
+ "title": "Inputs",
+ "default": {}
+ },
+ "credentials": {
+ "items": { "$ref": "#/components/schemas/CredentialsMetaInput" },
+ "type": "array",
+ "title": "Credentials",
+ "default": []
+ },
+ "execution_options": {
+ "$ref": "#/components/schemas/ExecutionOptions"
+ },
+ "trigger_info": {
+ "anyOf": [
+ { "additionalProperties": true, "type": "object" },
+ { "type": "null" }
+ ],
+ "title": "Trigger Info"
+ }
+ },
+ "type": "object",
+ "required": ["id", "name", "description"],
+ "title": "AgentDetails",
+ "description": "Detailed agent information."
+ },
+ "AgentDetailsResponse": {
+ "properties": {
+ "type": {
+ "$ref": "#/components/schemas/ResponseType",
+ "default": "agent_details"
+ },
+ "message": { "type": "string", "title": "Message" },
+ "session_id": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Session Id"
+ },
+ "agent": { "$ref": "#/components/schemas/AgentDetails" },
+ "user_authenticated": {
+ "type": "boolean",
+ "title": "User Authenticated",
+ "default": false
+ },
+ "graph_id": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Graph Id"
+ },
+ "graph_version": {
+ "anyOf": [{ "type": "integer" }, { "type": "null" }],
+ "title": "Graph Version"
+ }
+ },
+ "type": "object",
+ "required": ["message", "agent"],
+ "title": "AgentDetailsResponse",
+ "description": "Response for get_details action."
+ },
"AgentExecutionStatus": {
"type": "string",
"enum": [
@@ -6371,6 +6471,224 @@
],
"title": "AgentExecutionStatus"
},
+ "AgentInfo": {
+ "properties": {
+ "id": { "type": "string", "title": "Id" },
+ "name": { "type": "string", "title": "Name" },
+ "description": { "type": "string", "title": "Description" },
+ "source": {
+ "type": "string",
+ "title": "Source",
+ "description": "marketplace or library"
+ },
+ "in_library": {
+ "type": "boolean",
+ "title": "In Library",
+ "default": false
+ },
+ "creator": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Creator"
+ },
+ "category": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Category"
+ },
+ "rating": {
+ "anyOf": [{ "type": "number" }, { "type": "null" }],
+ "title": "Rating"
+ },
+ "runs": {
+ "anyOf": [{ "type": "integer" }, { "type": "null" }],
+ "title": "Runs"
+ },
+ "is_featured": {
+ "anyOf": [{ "type": "boolean" }, { "type": "null" }],
+ "title": "Is Featured"
+ },
+ "status": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Status"
+ },
+ "can_access_graph": {
+ "anyOf": [{ "type": "boolean" }, { "type": "null" }],
+ "title": "Can Access Graph"
+ },
+ "has_external_trigger": {
+ "anyOf": [{ "type": "boolean" }, { "type": "null" }],
+ "title": "Has External Trigger"
+ },
+ "new_output": {
+ "anyOf": [{ "type": "boolean" }, { "type": "null" }],
+ "title": "New Output"
+ },
+ "graph_id": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Graph Id"
+ },
+ "inputs": {
+ "anyOf": [
+ { "additionalProperties": true, "type": "object" },
+ { "type": "null" }
+ ],
+ "title": "Inputs",
+ "description": "Input schema for the agent, including field names, types, and defaults"
+ }
+ },
+ "type": "object",
+ "required": ["id", "name", "description", "source"],
+ "title": "AgentInfo",
+ "description": "Information about an agent."
+ },
+ "AgentOutputResponse": {
+ "properties": {
+ "type": {
+ "$ref": "#/components/schemas/ResponseType",
+ "default": "agent_output"
+ },
+ "message": { "type": "string", "title": "Message" },
+ "session_id": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Session Id"
+ },
+ "agent_name": { "type": "string", "title": "Agent Name" },
+ "agent_id": { "type": "string", "title": "Agent Id" },
+ "library_agent_id": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Library Agent Id"
+ },
+ "library_agent_link": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Library Agent Link"
+ },
+ "execution": {
+ "anyOf": [
+ { "$ref": "#/components/schemas/ExecutionOutputInfo" },
+ { "type": "null" }
+ ]
+ },
+ "available_executions": {
+ "anyOf": [
+ {
+ "items": { "additionalProperties": true, "type": "object" },
+ "type": "array"
+ },
+ { "type": "null" }
+ ],
+ "title": "Available Executions"
+ },
+ "total_executions": {
+ "type": "integer",
+ "title": "Total Executions",
+ "default": 0
+ }
+ },
+ "type": "object",
+ "required": ["message", "agent_name", "agent_id"],
+ "title": "AgentOutputResponse",
+ "description": "Response for agent_output tool."
+ },
+ "AgentPreviewResponse": {
+ "properties": {
+ "type": {
+ "$ref": "#/components/schemas/ResponseType",
+ "default": "agent_preview"
+ },
+ "message": { "type": "string", "title": "Message" },
+ "session_id": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Session Id"
+ },
+ "agent_json": {
+ "additionalProperties": true,
+ "type": "object",
+ "title": "Agent Json"
+ },
+ "agent_name": { "type": "string", "title": "Agent Name" },
+ "description": { "type": "string", "title": "Description" },
+ "node_count": { "type": "integer", "title": "Node Count" },
+ "link_count": {
+ "type": "integer",
+ "title": "Link Count",
+ "default": 0
+ }
+ },
+ "type": "object",
+ "required": [
+ "message",
+ "agent_json",
+ "agent_name",
+ "description",
+ "node_count"
+ ],
+ "title": "AgentPreviewResponse",
+ "description": "Response for previewing a generated agent before saving."
+ },
+ "AgentSavedResponse": {
+ "properties": {
+ "type": {
+ "$ref": "#/components/schemas/ResponseType",
+ "default": "agent_saved"
+ },
+ "message": { "type": "string", "title": "Message" },
+ "session_id": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Session Id"
+ },
+ "agent_id": { "type": "string", "title": "Agent Id" },
+ "agent_name": { "type": "string", "title": "Agent Name" },
+ "library_agent_id": { "type": "string", "title": "Library Agent Id" },
+ "library_agent_link": {
+ "type": "string",
+ "title": "Library Agent Link"
+ },
+ "agent_page_link": { "type": "string", "title": "Agent Page Link" }
+ },
+ "type": "object",
+ "required": [
+ "message",
+ "agent_id",
+ "agent_name",
+ "library_agent_id",
+ "library_agent_link",
+ "agent_page_link"
+ ],
+ "title": "AgentSavedResponse",
+ "description": "Response when an agent is saved to the library."
+ },
+ "AgentsFoundResponse": {
+ "properties": {
+ "type": {
+ "$ref": "#/components/schemas/ResponseType",
+ "default": "agents_found"
+ },
+ "message": { "type": "string", "title": "Message" },
+ "session_id": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Session Id"
+ },
+ "title": {
+ "type": "string",
+ "title": "Title",
+ "default": "Available Agents"
+ },
+ "agents": {
+ "items": { "$ref": "#/components/schemas/AgentInfo" },
+ "type": "array",
+ "title": "Agents"
+ },
+ "count": { "type": "integer", "title": "Count" },
+ "name": {
+ "type": "string",
+ "title": "Name",
+ "default": "agents_found"
+ }
+ },
+ "type": "object",
+ "required": ["message", "agents", "count"],
+ "title": "AgentsFoundResponse",
+ "description": "Response for find_agent tool."
+ },
"ApiResponse": {
"properties": {
"answer": { "type": "string", "title": "Answer" },
@@ -6691,23 +7009,137 @@
],
"title": "BlockInfo"
},
- "BlockResponse": {
+ "BlockInfoSummary": {
"properties": {
- "blocks": {
- "items": { "$ref": "#/components/schemas/BlockInfo" },
+ "id": { "type": "string", "title": "Id" },
+ "name": { "type": "string", "title": "Name" },
+ "description": { "type": "string", "title": "Description" },
+ "categories": {
+ "items": { "type": "string" },
"type": "array",
- "title": "Blocks"
+ "title": "Categories"
},
- "pagination": { "$ref": "#/components/schemas/Pagination" }
+ "input_schema": {
+ "additionalProperties": true,
+ "type": "object",
+ "title": "Input Schema"
+ },
+ "output_schema": {
+ "additionalProperties": true,
+ "type": "object",
+ "title": "Output Schema"
+ },
+ "required_inputs": {
+ "items": { "$ref": "#/components/schemas/BlockInputFieldInfo" },
+ "type": "array",
+ "title": "Required Inputs",
+ "description": "List of required input fields for this block"
+ }
},
"type": "object",
- "required": ["blocks", "pagination"],
- "title": "BlockResponse"
+ "required": [
+ "id",
+ "name",
+ "description",
+ "categories",
+ "input_schema",
+ "output_schema"
+ ],
+ "title": "BlockInfoSummary",
+ "description": "Summary of a block for search results."
},
- "Body_patchOauthUpdateAppStatus": {
+ "BlockInputFieldInfo": {
"properties": {
- "is_active": {
- "type": "boolean",
+ "name": { "type": "string", "title": "Name" },
+ "type": { "type": "string", "title": "Type" },
+ "description": {
+ "type": "string",
+ "title": "Description",
+ "default": ""
+ },
+ "required": {
+ "type": "boolean",
+ "title": "Required",
+ "default": false
+ },
+ "default": { "anyOf": [{}, { "type": "null" }], "title": "Default" }
+ },
+ "type": "object",
+ "required": ["name", "type"],
+ "title": "BlockInputFieldInfo",
+ "description": "Information about a block input field."
+ },
+ "BlockListResponse": {
+ "properties": {
+ "type": {
+ "$ref": "#/components/schemas/ResponseType",
+ "default": "block_list"
+ },
+ "message": { "type": "string", "title": "Message" },
+ "session_id": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Session Id"
+ },
+ "blocks": {
+ "items": { "$ref": "#/components/schemas/BlockInfoSummary" },
+ "type": "array",
+ "title": "Blocks"
+ },
+ "count": { "type": "integer", "title": "Count" },
+ "query": { "type": "string", "title": "Query" },
+ "usage_hint": {
+ "type": "string",
+ "title": "Usage Hint",
+ "default": "To execute a block, call run_block with block_id set to the block's 'id' field and input_data containing the required fields from input_schema."
+ }
+ },
+ "type": "object",
+ "required": ["message", "blocks", "count", "query"],
+ "title": "BlockListResponse",
+ "description": "Response for find_block tool."
+ },
+ "BlockOutputResponse": {
+ "properties": {
+ "type": {
+ "$ref": "#/components/schemas/ResponseType",
+ "default": "block_output"
+ },
+ "message": { "type": "string", "title": "Message" },
+ "session_id": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Session Id"
+ },
+ "block_id": { "type": "string", "title": "Block Id" },
+ "block_name": { "type": "string", "title": "Block Name" },
+ "outputs": {
+ "additionalProperties": { "items": {}, "type": "array" },
+ "type": "object",
+ "title": "Outputs"
+ },
+ "success": { "type": "boolean", "title": "Success", "default": true }
+ },
+ "type": "object",
+ "required": ["message", "block_id", "block_name", "outputs"],
+ "title": "BlockOutputResponse",
+ "description": "Response for run_block tool."
+ },
+ "BlockResponse": {
+ "properties": {
+ "blocks": {
+ "items": { "$ref": "#/components/schemas/BlockInfo" },
+ "type": "array",
+ "title": "Blocks"
+ },
+ "pagination": { "$ref": "#/components/schemas/Pagination" }
+ },
+ "type": "object",
+ "required": ["blocks", "pagination"],
+ "title": "BlockResponse"
+ },
+ "Body_patchOauthUpdateAppStatus": {
+ "properties": {
+ "is_active": {
+ "type": "boolean",
"title": "Is Active",
"description": "Whether the app should be active"
}
@@ -6937,6 +7369,42 @@
"required": ["query", "conversation_history", "message_id"],
"title": "ChatRequest"
},
+ "ClarificationNeededResponse": {
+ "properties": {
+ "type": {
+ "$ref": "#/components/schemas/ResponseType",
+ "default": "clarification_needed"
+ },
+ "message": { "type": "string", "title": "Message" },
+ "session_id": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Session Id"
+ },
+ "questions": {
+ "items": { "$ref": "#/components/schemas/ClarifyingQuestion" },
+ "type": "array",
+ "title": "Questions"
+ }
+ },
+ "type": "object",
+ "required": ["message"],
+ "title": "ClarificationNeededResponse",
+ "description": "Response when the LLM needs more information from the user."
+ },
+ "ClarifyingQuestion": {
+ "properties": {
+ "question": { "type": "string", "title": "Question" },
+ "keyword": { "type": "string", "title": "Keyword" },
+ "example": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Example"
+ }
+ },
+ "type": "object",
+ "required": ["question", "keyword"],
+ "title": "ClarifyingQuestion",
+ "description": "A question that needs user clarification."
+ },
"CountResponse": {
"properties": {
"all_blocks": { "type": "integer", "title": "All Blocks" },
@@ -7195,6 +7663,71 @@
"required": ["version_counts"],
"title": "DeleteGraphResponse"
},
+ "DocPageResponse": {
+ "properties": {
+ "type": {
+ "$ref": "#/components/schemas/ResponseType",
+ "default": "doc_page"
+ },
+ "message": { "type": "string", "title": "Message" },
+ "session_id": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Session Id"
+ },
+ "title": { "type": "string", "title": "Title" },
+ "path": { "type": "string", "title": "Path" },
+ "content": { "type": "string", "title": "Content" },
+ "doc_url": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Doc Url"
+ }
+ },
+ "type": "object",
+ "required": ["message", "title", "path", "content"],
+ "title": "DocPageResponse",
+ "description": "Response for get_doc_page tool."
+ },
+ "DocSearchResult": {
+ "properties": {
+ "title": { "type": "string", "title": "Title" },
+ "path": { "type": "string", "title": "Path" },
+ "section": { "type": "string", "title": "Section" },
+ "snippet": { "type": "string", "title": "Snippet" },
+ "score": { "type": "number", "title": "Score" },
+ "doc_url": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Doc Url"
+ }
+ },
+ "type": "object",
+ "required": ["title", "path", "section", "snippet", "score"],
+ "title": "DocSearchResult",
+ "description": "A single documentation search result."
+ },
+ "DocSearchResultsResponse": {
+ "properties": {
+ "type": {
+ "$ref": "#/components/schemas/ResponseType",
+ "default": "doc_search_results"
+ },
+ "message": { "type": "string", "title": "Message" },
+ "session_id": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Session Id"
+ },
+ "results": {
+ "items": { "$ref": "#/components/schemas/DocSearchResult" },
+ "type": "array",
+ "title": "Results"
+ },
+ "count": { "type": "integer", "title": "Count" },
+ "query": { "type": "string", "title": "Query" }
+ },
+ "type": "object",
+ "required": ["message", "results", "count", "query"],
+ "title": "DocSearchResultsResponse",
+ "description": "Response for search_docs tool."
+ },
"Document": {
"properties": {
"url": { "type": "string", "title": "Url" },
@@ -7204,6 +7737,34 @@
"required": ["url", "relevance_score"],
"title": "Document"
},
+ "ErrorResponse": {
+ "properties": {
+ "type": {
+ "$ref": "#/components/schemas/ResponseType",
+ "default": "error"
+ },
+ "message": { "type": "string", "title": "Message" },
+ "session_id": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Session Id"
+ },
+ "error": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Error"
+ },
+ "details": {
+ "anyOf": [
+ { "additionalProperties": true, "type": "object" },
+ { "type": "null" }
+ ],
+ "title": "Details"
+ }
+ },
+ "type": "object",
+ "required": ["message"],
+ "title": "ErrorResponse",
+ "description": "Response for errors."
+ },
"ExecutionAnalyticsConfig": {
"properties": {
"available_models": {
@@ -7380,6 +7941,85 @@
],
"title": "ExecutionAnalyticsResult"
},
+ "ExecutionOptions": {
+ "properties": {
+ "manual": { "type": "boolean", "title": "Manual", "default": true },
+ "scheduled": {
+ "type": "boolean",
+ "title": "Scheduled",
+ "default": true
+ },
+ "webhook": { "type": "boolean", "title": "Webhook", "default": false }
+ },
+ "type": "object",
+ "title": "ExecutionOptions",
+ "description": "Available execution options for an agent."
+ },
+ "ExecutionOutputInfo": {
+ "properties": {
+ "execution_id": { "type": "string", "title": "Execution Id" },
+ "status": { "type": "string", "title": "Status" },
+ "started_at": {
+ "anyOf": [
+ { "type": "string", "format": "date-time" },
+ { "type": "null" }
+ ],
+ "title": "Started At"
+ },
+ "ended_at": {
+ "anyOf": [
+ { "type": "string", "format": "date-time" },
+ { "type": "null" }
+ ],
+ "title": "Ended At"
+ },
+ "outputs": {
+ "additionalProperties": { "items": {}, "type": "array" },
+ "type": "object",
+ "title": "Outputs"
+ },
+ "inputs_summary": {
+ "anyOf": [
+ { "additionalProperties": true, "type": "object" },
+ { "type": "null" }
+ ],
+ "title": "Inputs Summary"
+ }
+ },
+ "type": "object",
+ "required": ["execution_id", "status", "outputs"],
+ "title": "ExecutionOutputInfo",
+ "description": "Summary of a single execution's outputs."
+ },
+ "ExecutionStartedResponse": {
+ "properties": {
+ "type": {
+ "$ref": "#/components/schemas/ResponseType",
+ "default": "execution_started"
+ },
+ "message": { "type": "string", "title": "Message" },
+ "session_id": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Session Id"
+ },
+ "execution_id": { "type": "string", "title": "Execution Id" },
+ "graph_id": { "type": "string", "title": "Graph Id" },
+ "graph_name": { "type": "string", "title": "Graph Name" },
+ "library_agent_id": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Library Agent Id"
+ },
+ "library_agent_link": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Library Agent Link"
+ },
+ "status": { "type": "string", "title": "Status", "default": "QUEUED" }
+ },
+ "type": "object",
+ "required": ["message", "execution_id", "graph_id", "graph_name"],
+ "title": "ExecutionStartedResponse",
+ "description": "Response for run/schedule actions."
+ },
"Graph": {
"properties": {
"id": { "type": "string", "title": "Id" },
@@ -8131,6 +8771,43 @@
"required": ["provider", "host"],
"title": "HostScopedCredentials"
},
+ "InputValidationErrorResponse": {
+ "properties": {
+ "type": {
+ "$ref": "#/components/schemas/ResponseType",
+ "default": "input_validation_error"
+ },
+ "message": { "type": "string", "title": "Message" },
+ "session_id": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Session Id"
+ },
+ "unrecognized_fields": {
+ "items": { "type": "string" },
+ "type": "array",
+ "title": "Unrecognized Fields",
+ "description": "List of input field names that were not recognized"
+ },
+ "inputs": {
+ "additionalProperties": true,
+ "type": "object",
+ "title": "Inputs",
+ "description": "The agent's valid input schema for reference"
+ },
+ "graph_id": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Graph Id"
+ },
+ "graph_version": {
+ "anyOf": [{ "type": "integer" }, { "type": "null" }],
+ "title": "Graph Version"
+ }
+ },
+ "type": "object",
+ "required": ["message", "unrecognized_fields", "inputs"],
+ "title": "InputValidationErrorResponse",
+ "description": "Response when run_agent receives unknown input fields."
+ },
"LibraryAgent": {
"properties": {
"id": { "type": "string", "title": "Id" },
@@ -8649,6 +9326,54 @@
"required": ["agents", "pagination"],
"title": "MyAgentsResponse"
},
+ "NeedLoginResponse": {
+ "properties": {
+ "type": {
+ "$ref": "#/components/schemas/ResponseType",
+ "default": "need_login"
+ },
+ "message": { "type": "string", "title": "Message" },
+ "session_id": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Session Id"
+ },
+ "agent_info": {
+ "anyOf": [
+ { "additionalProperties": true, "type": "object" },
+ { "type": "null" }
+ ],
+ "title": "Agent Info"
+ }
+ },
+ "type": "object",
+ "required": ["message"],
+ "title": "NeedLoginResponse",
+ "description": "Response when login is needed."
+ },
+ "NoResultsResponse": {
+ "properties": {
+ "type": {
+ "$ref": "#/components/schemas/ResponseType",
+ "default": "no_results"
+ },
+ "message": { "type": "string", "title": "Message" },
+ "session_id": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Session Id"
+ },
+ "suggestions": {
+ "items": { "type": "string" },
+ "type": "array",
+ "title": "Suggestions",
+ "default": []
+ },
+ "name": { "type": "string", "title": "Name", "default": "no_results" }
+ },
+ "type": "object",
+ "required": ["message"],
+ "title": "NoResultsResponse",
+ "description": "Response when no agents found."
+ },
"Node": {
"properties": {
"id": { "type": "string", "title": "Id" },
@@ -9058,6 +9783,66 @@
"title": "OperationCompleteRequest",
"description": "Request model for external completion webhook."
},
+ "OperationInProgressResponse": {
+ "properties": {
+ "type": {
+ "$ref": "#/components/schemas/ResponseType",
+ "default": "operation_in_progress"
+ },
+ "message": { "type": "string", "title": "Message" },
+ "session_id": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Session Id"
+ },
+ "tool_call_id": { "type": "string", "title": "Tool Call Id" }
+ },
+ "type": "object",
+ "required": ["message", "tool_call_id"],
+ "title": "OperationInProgressResponse",
+ "description": "Response when an operation is already in progress.\n\nReturned for idempotency when the same tool_call_id is requested again\nwhile the background task is still running."
+ },
+ "OperationPendingResponse": {
+ "properties": {
+ "type": {
+ "$ref": "#/components/schemas/ResponseType",
+ "default": "operation_pending"
+ },
+ "message": { "type": "string", "title": "Message" },
+ "session_id": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Session Id"
+ },
+ "operation_id": { "type": "string", "title": "Operation Id" },
+ "tool_name": { "type": "string", "title": "Tool Name" }
+ },
+ "type": "object",
+ "required": ["message", "operation_id", "tool_name"],
+ "title": "OperationPendingResponse",
+ "description": "Response stored in chat history while a long-running operation is executing.\n\nThis is persisted to the database so users see a pending state when they\nrefresh before the operation completes."
+ },
+ "OperationStartedResponse": {
+ "properties": {
+ "type": {
+ "$ref": "#/components/schemas/ResponseType",
+ "default": "operation_started"
+ },
+ "message": { "type": "string", "title": "Message" },
+ "session_id": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Session Id"
+ },
+ "operation_id": { "type": "string", "title": "Operation Id" },
+ "tool_name": { "type": "string", "title": "Tool Name" },
+ "task_id": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Task Id"
+ }
+ },
+ "type": "object",
+ "required": ["message", "operation_id", "tool_name"],
+ "title": "OperationStartedResponse",
+ "description": "Response when a long-running operation has been started in the background.\n\nThis is returned immediately to the client while the operation continues\nto execute. The user can close the tab and check back later.\n\nThe task_id can be used to reconnect to the SSE stream via\nGET /chat/tasks/{task_id}/stream?last_idx=0"
+ },
"Pagination": {
"properties": {
"total_items": {
@@ -9689,6 +10474,38 @@
"required": ["credit_amount"],
"title": "RequestTopUp"
},
+ "ResponseType": {
+ "type": "string",
+ "enum": [
+ "agents_found",
+ "agent_details",
+ "setup_requirements",
+ "execution_started",
+ "need_login",
+ "error",
+ "no_results",
+ "agent_output",
+ "understanding_updated",
+ "agent_preview",
+ "agent_saved",
+ "clarification_needed",
+ "block_list",
+ "block_output",
+ "doc_search_results",
+ "doc_page",
+ "workspace_file_list",
+ "workspace_file_content",
+ "workspace_file_metadata",
+ "workspace_file_written",
+ "workspace_file_deleted",
+ "operation_started",
+ "operation_pending",
+ "operation_in_progress",
+ "input_validation_error"
+ ],
+ "title": "ResponseType",
+ "description": "Types of tool responses."
+ },
"ReviewItem": {
"properties": {
"node_exec_id": {
@@ -9952,6 +10769,48 @@
"required": ["active_graph_version"],
"title": "SetGraphActiveVersion"
},
+ "SetupInfo": {
+ "properties": {
+ "agent_id": { "type": "string", "title": "Agent Id" },
+ "agent_name": { "type": "string", "title": "Agent Name" },
+ "requirements": {
+ "additionalProperties": { "items": {}, "type": "array" },
+ "type": "object",
+ "title": "Requirements"
+ },
+ "user_readiness": { "$ref": "#/components/schemas/UserReadiness" }
+ },
+ "type": "object",
+ "required": ["agent_id", "agent_name"],
+ "title": "SetupInfo",
+ "description": "Complete setup information."
+ },
+ "SetupRequirementsResponse": {
+ "properties": {
+ "type": {
+ "$ref": "#/components/schemas/ResponseType",
+ "default": "setup_requirements"
+ },
+ "message": { "type": "string", "title": "Message" },
+ "session_id": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Session Id"
+ },
+ "setup_info": { "$ref": "#/components/schemas/SetupInfo" },
+ "graph_id": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Graph Id"
+ },
+ "graph_version": {
+ "anyOf": [{ "type": "integer" }, { "type": "null" }],
+ "title": "Graph Version"
+ }
+ },
+ "type": "object",
+ "required": ["message", "setup_info"],
+ "title": "SetupRequirementsResponse",
+ "description": "Response for validate action."
+ },
"ShareRequest": {
"properties": {},
"type": "object",
@@ -11348,6 +12207,33 @@
"required": ["name", "graph_id", "graph_version", "trigger_config"],
"title": "TriggeredPresetSetupRequest"
},
+ "UnderstandingUpdatedResponse": {
+ "properties": {
+ "type": {
+ "$ref": "#/components/schemas/ResponseType",
+ "default": "understanding_updated"
+ },
+ "message": { "type": "string", "title": "Message" },
+ "session_id": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Session Id"
+ },
+ "updated_fields": {
+ "items": { "type": "string" },
+ "type": "array",
+ "title": "Updated Fields"
+ },
+ "current_understanding": {
+ "additionalProperties": true,
+ "type": "object",
+ "title": "Current Understanding"
+ }
+ },
+ "type": "object",
+ "required": ["message"],
+ "title": "UnderstandingUpdatedResponse",
+ "description": "Response for add_understanding tool."
+ },
"UnifiedSearchResponse": {
"properties": {
"results": {
@@ -12226,6 +13112,29 @@
"required": ["provider", "username", "password"],
"title": "UserPasswordCredentials"
},
+ "UserReadiness": {
+ "properties": {
+ "has_all_credentials": {
+ "type": "boolean",
+ "title": "Has All Credentials",
+ "default": false
+ },
+ "missing_credentials": {
+ "additionalProperties": true,
+ "type": "object",
+ "title": "Missing Credentials",
+ "default": {}
+ },
+ "ready_to_run": {
+ "type": "boolean",
+ "title": "Ready To Run",
+ "default": false
+ }
+ },
+ "type": "object",
+ "title": "UserReadiness",
+ "description": "User readiness status."
+ },
"UserTransaction": {
"properties": {
"transaction_key": {
diff --git a/autogpt_platform/frontend/src/app/globals.css b/autogpt_platform/frontend/src/app/globals.css
index 1f782f753b..dd1d17cde7 100644
--- a/autogpt_platform/frontend/src/app/globals.css
+++ b/autogpt_platform/frontend/src/app/globals.css
@@ -1,6 +1,7 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
+@source "../node_modules/streamdown/dist/*.js";
@layer base {
:root {
@@ -29,6 +30,14 @@
--chart-3: 197 37% 24%;
--chart-4: 43 74% 66%;
--chart-5: 27 87% 67%;
+ --sidebar-background: 0 0% 98%;
+ --sidebar-foreground: 240 5.3% 26.1%;
+ --sidebar-primary: 240 5.9% 10%;
+ --sidebar-primary-foreground: 0 0% 98%;
+ --sidebar-accent: 240 4.8% 95.9%;
+ --sidebar-accent-foreground: 240 5.9% 10%;
+ --sidebar-border: 220 13% 91%;
+ --sidebar-ring: 217.2 91.2% 59.8%;
}
.dark {
@@ -56,6 +65,14 @@
--chart-3: 30 80% 55%;
--chart-4: 280 65% 60%;
--chart-5: 340 75% 55%;
+ --sidebar-background: 240 5.9% 10%;
+ --sidebar-foreground: 240 4.8% 95.9%;
+ --sidebar-primary: 224.3 76.3% 48%;
+ --sidebar-primary-foreground: 0 0% 100%;
+ --sidebar-accent: 240 3.7% 15.9%;
+ --sidebar-accent-foreground: 240 4.8% 95.9%;
+ --sidebar-border: 240 3.7% 15.9%;
+ --sidebar-ring: 217.2 91.2% 59.8%;
}
* {
diff --git a/autogpt_platform/frontend/src/components/ai-elements/conversation.tsx b/autogpt_platform/frontend/src/components/ai-elements/conversation.tsx
new file mode 100644
index 0000000000..92e940c715
--- /dev/null
+++ b/autogpt_platform/frontend/src/components/ai-elements/conversation.tsx
@@ -0,0 +1,109 @@
+"use client";
+
+import { Button } from "@/components/ui/button";
+import { scrollbarStyles } from "@/components/styles/scrollbars";
+import { cn } from "@/lib/utils";
+import { ArrowDownIcon } from "lucide-react";
+import type { ComponentProps } from "react";
+import { useCallback } from "react";
+import { StickToBottom, useStickToBottomContext } from "use-stick-to-bottom";
+
+export type ConversationProps = ComponentProps<typeof StickToBottom>;
+
+export const Conversation = ({ className, ...props }: ConversationProps) => (
+ <StickToBottom
+ className={cn(
+ "relative flex-1 overflow-y-hidden",
+ scrollbarStyles,
+ className,
+ )}
+ initial="smooth"
+ resize="smooth"
+ role="log"
+ {...props}
+ />
+);
+
+export type ConversationContentProps = ComponentProps<
+ typeof StickToBottom.Content
+>;
+
+export const ConversationContent = ({
+ className,
+ ...props
+}: ConversationContentProps) => (
+ <StickToBottom.Content
+ className={cn("flex flex-col gap-8 p-4", className)}
+ {...props}
+ />
+);
+
+export type ConversationEmptyStateProps = ComponentProps<"div"> & {
+ title?: string;
+ description?: string;
+ icon?: React.ReactNode;
+};
+
+export const ConversationEmptyState = ({
+ className,
+ title = "No messages yet",
+ description = "Start a conversation to see messages here",
+ icon,
+ children,
+ ...props
+}: ConversationEmptyStateProps) => (
+ <div
+ className={cn(
+ "flex size-full flex-col items-center justify-center gap-3 p-8 text-center",
+ className,
+ )}
+ {...props}
+ >
+ {children ?? (
+ <>
+ {icon && (
+ <div className="text-neutral-500 dark:text-neutral-400">{icon}</div>
+ )}
+ <div className="space-y-1">
+ <h3 className="text-sm font-medium">{title}</h3>
+ {description && (
+ <p className="text-sm text-neutral-500 dark:text-neutral-400">
+ {description}
+ </p>
+ )}
+ </div>
+ </>
+ )}
+ </div>
+);
+
+export type ConversationScrollButtonProps = ComponentProps<typeof Button>;
+
+export const ConversationScrollButton = ({
+ className,
+ ...props
+}: ConversationScrollButtonProps) => {
+ const { isAtBottom, scrollToBottom } = useStickToBottomContext();
+
+ const handleScrollToBottom = useCallback(() => {
+ scrollToBottom();
+ }, [scrollToBottom]);
+
+ return (
+ !isAtBottom && (
+ <Button
+ className={cn(
+ "absolute bottom-4 left-[50%] translate-x-[-50%] rounded-full dark:bg-white dark:dark:bg-neutral-950 dark:dark:hover:bg-neutral-800 dark:hover:bg-neutral-100",
+ className,
+ )}
+ onClick={handleScrollToBottom}
+ size="icon"
+ type="button"
+ variant="outline"
+ {...props}
+ >
+ <ArrowDownIcon className="size-4" />
+ </Button>
+ )
+ );
+};
diff --git a/autogpt_platform/frontend/src/components/ai-elements/message.tsx b/autogpt_platform/frontend/src/components/ai-elements/message.tsx
new file mode 100644
index 0000000000..5cc330e57c
--- /dev/null
+++ b/autogpt_platform/frontend/src/components/ai-elements/message.tsx
@@ -0,0 +1,338 @@
+"use client";
+
+import { Button } from "@/components/ui/button";
+import { ButtonGroup, ButtonGroupText } from "@/components/ui/button-group";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
+import { cn } from "@/lib/utils";
+import { cjk } from "@streamdown/cjk";
+import { code } from "@streamdown/code";
+import { math } from "@streamdown/math";
+import { mermaid } from "@streamdown/mermaid";
+import type { UIMessage } from "ai";
+import { ChevronLeftIcon, ChevronRightIcon } from "lucide-react";
+import type { ComponentProps, HTMLAttributes, ReactElement } from "react";
+import { createContext, memo, useContext, useEffect, useState } from "react";
+import { Streamdown } from "streamdown";
+
+export type MessageProps = HTMLAttributes<HTMLDivElement> & {
+ from: UIMessage["role"];
+};
+
+export const Message = ({ className, from, ...props }: MessageProps) => (
+ <div
+ className={cn(
+ "group flex w-full max-w-[95%] flex-col gap-2",
+ from === "user" ? "is-user ml-auto justify-end" : "is-assistant",
+ className,
+ )}
+ {...props}
+ />
+);
+
+export type MessageContentProps = HTMLAttributes<HTMLDivElement>;
+
+export const MessageContent = ({
+ children,
+ className,
+ ...props
+}: MessageContentProps) => (
+ <div
+ className={cn(
+ "is-user:dark flex w-full min-w-0 max-w-full flex-col gap-2 overflow-hidden text-sm",
+ "group-[.is-user]:w-fit",
+ "group-[.is-user]:ml-auto group-[.is-user]:rounded-lg group-[.is-user]:bg-neutral-100 group-[.is-user]:px-4 group-[.is-user]:py-3 group-[.is-user]:text-neutral-950 dark:group-[.is-user]:bg-neutral-800 dark:group-[.is-user]:text-neutral-50",
+ "group-[.is-assistant]:text-neutral-950 dark:group-[.is-assistant]:text-neutral-50",
+ className,
+ )}
+ {...props}
+ >
+ {children}
+ </div>
+);
+
+export type MessageActionsProps = ComponentProps<"div">;
+
+export const MessageActions = ({
+ className,
+ children,
+ ...props
+}: MessageActionsProps) => (
+ <div className={cn("flex items-center gap-1", className)} {...props}>
+ {children}
+ </div>
+);
+
+export type MessageActionProps = ComponentProps<typeof Button> & {
+ tooltip?: string;
+ label?: string;
+};
+
+export const MessageAction = ({
+ tooltip,
+ children,
+ label,
+ variant = "ghost",
+ size = "icon-sm",
+ ...props
+}: MessageActionProps) => {
+ const button = (
+ <Button size={size} type="button" variant={variant} {...props}>
+ {children}
+ <span className="sr-only">{label || tooltip}</span>
+ </Button>
+ );
+
+ if (tooltip) {
+ return (
+ <TooltipProvider>
+ <Tooltip>
+ <TooltipTrigger asChild>{button}</TooltipTrigger>
+ <TooltipContent>
+ <p>{tooltip}</p>
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ );
+ }
+
+ return button;
+};
+
+interface MessageBranchContextType {
+ currentBranch: number;
+ totalBranches: number;
+ goToPrevious: () => void;
+ goToNext: () => void;
+ branches: ReactElement[];
+ setBranches: (branches: ReactElement[]) => void;
+}
+
+const MessageBranchContext = createContext<MessageBranchContextType | null>(
+ null,
+);
+
+const useMessageBranch = () => {
+ const context = useContext(MessageBranchContext);
+
+ if (!context) {
+ throw new Error("MessageBranch components must be used within");
+ }
+
+ return context;
+};
+
+export type MessageBranchProps = HTMLAttributes<HTMLDivElement> & {
+ defaultBranch?: number;
+ onBranchChange?: (branchIndex: number) => void;
+};
+
+export const MessageBranch = ({
+ defaultBranch = 0,
+ onBranchChange,
+ className,
+ ...props
+}: MessageBranchProps) => {
+ const [currentBranch, setCurrentBranch] = useState(defaultBranch);
+ const [branches, setBranches] = useState<ReactElement[]>([]);
+
+ const handleBranchChange = (newBranch: number) => {
+ setCurrentBranch(newBranch);
+ onBranchChange?.(newBranch);
+ };
+
+ const goToPrevious = () => {
+ const newBranch =
+ currentBranch > 0 ? currentBranch - 1 : branches.length - 1;
+ handleBranchChange(newBranch);
+ };
+
+ const goToNext = () => {
+ const newBranch =
+ currentBranch < branches.length - 1 ? currentBranch + 1 : 0;
+ handleBranchChange(newBranch);
+ };
+
+ const contextValue: MessageBranchContextType = {
+ currentBranch,
+ totalBranches: branches.length,
+ goToPrevious,
+ goToNext,
+ branches,
+ setBranches,
+ };
+
+ return (
+ <MessageBranchContext.Provider value={contextValue}>
+ <div
+ className={cn("grid w-full gap-2 [&>div]:pb-0", className)}
+ {...props}
+ />
+ </MessageBranchContext.Provider>
+ );
+};
+
+export type MessageBranchContentProps = HTMLAttributes<HTMLDivElement>;
+
+export const MessageBranchContent = ({
+ children,
+ ...props
+}: MessageBranchContentProps) => {
+ const { currentBranch, setBranches, branches } = useMessageBranch();
+ const childrenArray = Array.isArray(children) ? children : [children];
+
+ // Use useEffect to update branches when they change
+ useEffect(() => {
+ if (branches.length !== childrenArray.length) {
+ setBranches(childrenArray);
+ }
+ }, [childrenArray, branches, setBranches]);
+
+ return childrenArray.map((branch, index) => (
+ <div
+ className={cn(
+ "grid gap-2 overflow-hidden [&>div]:pb-0",
+ index === currentBranch ? "block" : "hidden",
+ )}
+ key={branch.key}
+ {...props}
+ >
+ {branch}
+ </div>
+ ));
+};
+
+export type MessageBranchSelectorProps = HTMLAttributes<HTMLDivElement> & {
+ from: UIMessage["role"];
+};
+
+export const MessageBranchSelector = ({
+ className,
+ from: _from,
+ ...props
+}: MessageBranchSelectorProps) => {
+ const { totalBranches } = useMessageBranch();
+
+ // Don't render if there's only one branch
+ if (totalBranches <= 1) {
+ return null;
+ }
+
+ return (
+ <ButtonGroup
+ className={cn(
+ "[&>*:not(:first-child)]:rounded-l-md [&>*:not(:last-child)]:rounded-r-md",
+ className,
+ )}
+ orientation="horizontal"
+ {...props}
+ />
+ );
+};
+
+export type MessageBranchPreviousProps = ComponentProps<typeof Button>;
+
+export const MessageBranchPrevious = ({
+ children,
+ ...props
+}: MessageBranchPreviousProps) => {
+ const { goToPrevious, totalBranches } = useMessageBranch();
+
+ return (
+ <Button
+ aria-label="Previous branch"
+ disabled={totalBranches <= 1}
+ onClick={goToPrevious}
+ size="icon-sm"
+ type="button"
+ variant="ghost"
+ {...props}
+ >
+ {children ?? <ChevronLeftIcon size={14} />}
+ </Button>
+ );
+};
+
+export type MessageBranchNextProps = ComponentProps<typeof Button>;
+
+export const MessageBranchNext = ({
+ children,
+ ...props
+}: MessageBranchNextProps) => {
+ const { goToNext, totalBranches } = useMessageBranch();
+
+ return (
+ <Button
+ aria-label="Next branch"
+ disabled={totalBranches <= 1}
+ onClick={goToNext}
+ size="icon-sm"
+ type="button"
+ variant="ghost"
+ {...props}
+ >
+ {children ?? <ChevronRightIcon size={14} />}
+ </Button>
+ );
+};
+
+export type MessageBranchPageProps = HTMLAttributes<HTMLSpanElement>;
+
+export const MessageBranchPage = ({
+ className,
+ ...props
+}: MessageBranchPageProps) => {
+ const { currentBranch, totalBranches } = useMessageBranch();
+
+ return (
+ <ButtonGroupText
+ className={cn(
+ "border-none bg-transparent text-neutral-500 shadow-none dark:text-neutral-400",
+ className,
+ )}
+ {...props}
+ >
+ {currentBranch + 1} of {totalBranches}
+ </ButtonGroupText>
+ );
+};
+
+export type MessageResponseProps = ComponentProps<typeof Streamdown>;
+
+export const MessageResponse = memo(
+ ({ className, ...props }: MessageResponseProps) => (
+ <Streamdown
+ className={cn(
+ "size-full [&>*:first-child]:mt-0 [&>*:last-child]:mb-0 [&_pre]:!bg-white",
+ className,
+ )}
+ plugins={{ code, mermaid, math, cjk }}
+ {...props}
+ />
+ ),
+ (prevProps, nextProps) => prevProps.children === nextProps.children,
+);
+
+MessageResponse.displayName = "MessageResponse";
+
+export type MessageToolbarProps = ComponentProps<"div">;
+
+export const MessageToolbar = ({
+ className,
+ children,
+ ...props
+}: MessageToolbarProps) => (
+ <div
+ className={cn(
+ "mt-4 flex w-full items-center justify-between gap-4",
+ className,
+ )}
+ {...props}
+ >
+ {children}
+ </div>
+);
diff --git a/autogpt_platform/frontend/src/components/atoms/OverflowText/OverflowText.tsx b/autogpt_platform/frontend/src/components/atoms/OverflowText/OverflowText.tsx
index efc345f79c..b118cc5aa0 100644
--- a/autogpt_platform/frontend/src/components/atoms/OverflowText/OverflowText.tsx
+++ b/autogpt_platform/frontend/src/components/atoms/OverflowText/OverflowText.tsx
@@ -77,7 +77,7 @@ export function OverflowText(props: Props) {
"block min-w-0 overflow-hidden text-ellipsis whitespace-nowrap",
)}
>
- <Text variant={variant} className={className} {...restProps}>
+ <Text variant={variant} as="span" className={className} {...restProps}>
{value}
</Text>
</span>
diff --git a/autogpt_platform/frontend/src/components/atoms/Text/Text.tsx b/autogpt_platform/frontend/src/components/atoms/Text/Text.tsx
index 8bae184e5b..86c39b6436 100644
--- a/autogpt_platform/frontend/src/components/atoms/Text/Text.tsx
+++ b/autogpt_platform/frontend/src/components/atoms/Text/Text.tsx
@@ -1,4 +1,5 @@
import React from "react";
+import { cn } from "@/lib/utils";
import { As, Variant, variantElementMap, variants } from "./helpers";
type CustomProps = {
@@ -22,7 +23,7 @@ export function Text({
}: TextProps) {
const variantClasses = variants[size || variant] || variants.body;
const Element = outerAs || variantElementMap[variant];
- const combinedClassName = `${variantClasses} ${className}`.trim();
+ const combinedClassName = cn(variantClasses, className);
return React.createElement(
Element,
diff --git a/autogpt_platform/frontend/src/components/contextual/Chat/Chat.tsx b/autogpt_platform/frontend/src/components/contextual/Chat/Chat.tsx
deleted file mode 100644
index da454150bf..0000000000
--- a/autogpt_platform/frontend/src/components/contextual/Chat/Chat.tsx
+++ /dev/null
@@ -1,114 +0,0 @@
-"use client";
-
-import { useCopilotSessionId } from "@/app/(platform)/copilot/useCopilotSessionId";
-import { LoadingSpinner } from "@/components/atoms/LoadingSpinner/LoadingSpinner";
-import { Text } from "@/components/atoms/Text/Text";
-import { cn } from "@/lib/utils";
-import { useEffect, useRef } from "react";
-import { ChatContainer } from "./components/ChatContainer/ChatContainer";
-import { ChatErrorState } from "./components/ChatErrorState/ChatErrorState";
-import { useChat } from "./useChat";
-
-export interface ChatProps {
- className?: string;
- initialPrompt?: string;
- onSessionNotFound?: () => void;
- onStreamingChange?: (isStreaming: boolean) => void;
-}
-
-export function Chat({
- className,
- initialPrompt,
- onSessionNotFound,
- onStreamingChange,
-}: ChatProps) {
- const { urlSessionId } = useCopilotSessionId();
- const hasHandledNotFoundRef = useRef(false);
- const {
- session,
- messages,
- isLoading,
- isCreating,
- error,
- isSessionNotFound,
- sessionId,
- createSession,
- showLoader,
- startPollingForOperation,
- } = useChat({ urlSessionId });
-
- // Extract active stream info for reconnection
- const activeStream = (
- session as {
- active_stream?: {
- task_id: string;
- last_message_id: string;
- operation_id: string;
- tool_name: string;
- };
- }
- )?.active_stream;
-
- useEffect(() => {
- if (!onSessionNotFound) return;
- if (!urlSessionId) return;
- if (!isSessionNotFound || isLoading || isCreating) return;
- if (hasHandledNotFoundRef.current) return;
- hasHandledNotFoundRef.current = true;
- onSessionNotFound();
- }, [
- onSessionNotFound,
- urlSessionId,
- isSessionNotFound,
- isLoading,
- isCreating,
- ]);
-
- const shouldShowLoader = showLoader && (isLoading || isCreating);
-
- return (
- <div className={cn("flex h-full flex-col", className)}>
- {/* Main Content */}
- <main className="flex min-h-0 w-full flex-1 flex-col overflow-hidden bg-[#f8f8f9]">
- {/* Loading State */}
- {shouldShowLoader && (
- <div className="flex flex-1 items-center justify-center">
- <div className="flex flex-col items-center gap-3">
- <LoadingSpinner size="large" className="text-neutral-400" />
- <Text variant="body" className="text-zinc-500">
- Loading your chat...
- </Text>
- </div>
- </div>
- )}
-
- {/* Error State */}
- {error && !isLoading && (
- <ChatErrorState error={error} onRetry={createSession} />
- )}
-
- {/* Session Content */}
- {sessionId && !isLoading && !error && (
- <ChatContainer
- sessionId={sessionId}
- initialMessages={messages}
- initialPrompt={initialPrompt}
- className="flex-1"
- onStreamingChange={onStreamingChange}
- onOperationStarted={startPollingForOperation}
- activeStream={
- activeStream
- ? {
- taskId: activeStream.task_id,
- lastMessageId: activeStream.last_message_id,
- operationId: activeStream.operation_id,
- toolName: activeStream.tool_name,
- }
- : undefined
- }
- />
- )}
- </main>
- </div>
- );
-}
diff --git a/autogpt_platform/frontend/src/components/contextual/Chat/SSE_RECONNECTION.md b/autogpt_platform/frontend/src/components/contextual/Chat/SSE_RECONNECTION.md
deleted file mode 100644
index 9e78679f4e..0000000000
--- a/autogpt_platform/frontend/src/components/contextual/Chat/SSE_RECONNECTION.md
+++ /dev/null
@@ -1,159 +0,0 @@
-# SSE Reconnection Contract for Long-Running Operations
-
-This document describes the client-side contract for handling SSE (Server-Sent Events) disconnections and reconnecting to long-running background tasks.
-
-## Overview
-
-When a user triggers a long-running operation (like agent generation), the backend:
-
-1. Spawns a background task that survives SSE disconnections
-2. Returns an `operation_started` response with a `task_id`
-3. Stores stream messages in Redis Streams for replay
-
-Clients can reconnect to the task stream at any time to receive missed messages.
-
-## Client-Side Flow
-
-### 1. Receiving Operation Started
-
-When you receive an `operation_started` tool response:
-
-```typescript
-// The response includes a task_id for reconnection
-{
- type: "operation_started",
- tool_name: "generate_agent",
- operation_id: "uuid-...",
- task_id: "task-uuid-...", // <-- Store this for reconnection
- message: "Operation started. You can close this tab."
-}
-```
-
-### 2. Storing Task Info
-
-Use the chat store to track the active task:
-
-```typescript
-import { useChatStore } from "./chat-store";
-
-// When operation_started is received:
-useChatStore.getState().setActiveTask(sessionId, {
- taskId: response.task_id,
- operationId: response.operation_id,
- toolName: response.tool_name,
- lastMessageId: "0",
-});
-```
-
-### 3. Reconnecting to a Task
-
-To reconnect (e.g., after page refresh or tab reopen):
-
-```typescript
-const { reconnectToTask, getActiveTask } = useChatStore.getState();
-
-// Check if there's an active task for this session
-const activeTask = getActiveTask(sessionId);
-
-if (activeTask) {
- // Reconnect to the task stream
- await reconnectToTask(
- sessionId,
- activeTask.taskId,
- activeTask.lastMessageId, // Resume from last position
- (chunk) => {
- // Handle incoming chunks
- console.log("Received chunk:", chunk);
- },
- );
-}
-```
-
-### 4. Tracking Message Position
-
-To enable precise replay, update the last message ID as chunks arrive:
-
-```typescript
-const { updateTaskLastMessageId } = useChatStore.getState();
-
-function handleChunk(chunk: StreamChunk) {
- // If chunk has an index/id, track it
- if (chunk.idx !== undefined) {
- updateTaskLastMessageId(sessionId, String(chunk.idx));
- }
-}
-```
-
-## API Endpoints
-
-### Task Stream Reconnection
-
-```
-GET /api/chat/tasks/{taskId}/stream?last_message_id={idx}
-```
-
-- `taskId`: The task ID from `operation_started`
-- `last_message_id`: Last received message index (default: "0" for full replay)
-
-Returns: SSE stream of missed messages + live updates
-
-## Chunk Types
-
-The reconnected stream follows the same Vercel AI SDK protocol:
-
-| Type | Description |
-| ----------------------- | ----------------------- |
-| `start` | Message lifecycle start |
-| `text-delta` | Streaming text content |
-| `text-end` | Text block completed |
-| `tool-output-available` | Tool result available |
-| `finish` | Stream completed |
-| `error` | Error occurred |
-
-## Error Handling
-
-If reconnection fails:
-
-1. Check if task still exists (may have expired - default TTL: 1 hour)
-2. Fall back to polling the session for final state
-3. Show appropriate UI message to user
-
-## Persistence Considerations
-
-For robust reconnection across browser restarts:
-
-```typescript
-// Store in localStorage/sessionStorage
-const ACTIVE_TASKS_KEY = "chat_active_tasks";
-
-function persistActiveTask(sessionId: string, task: ActiveTaskInfo) {
- const tasks = JSON.parse(localStorage.getItem(ACTIVE_TASKS_KEY) || "{}");
- tasks[sessionId] = task;
- localStorage.setItem(ACTIVE_TASKS_KEY, JSON.stringify(tasks));
-}
-
-function loadPersistedTasks(): Record<string, ActiveTaskInfo> {
- return JSON.parse(localStorage.getItem(ACTIVE_TASKS_KEY) || "{}");
-}
-```
-
-## Backend Configuration
-
-The following backend settings affect reconnection behavior:
-
-| Setting | Default | Description |
-| ------------------- | ------- | ---------------------------------- |
-| `stream_ttl` | 3600s | How long streams are kept in Redis |
-| `stream_max_length` | 1000 | Max messages per stream |
-
-## Testing
-
-To test reconnection locally:
-
-1. Start a long-running operation (e.g., agent generation)
-2. Note the `task_id` from the `operation_started` response
-3. Close the browser tab
-4. Reopen and call `reconnectToTask` with the saved `task_id`
-5. Verify that missed messages are replayed
-
-See the main README for full local development setup.
diff --git a/autogpt_platform/frontend/src/components/contextual/Chat/chat-constants.ts b/autogpt_platform/frontend/src/components/contextual/Chat/chat-constants.ts
deleted file mode 100644
index 8802de2155..0000000000
--- a/autogpt_platform/frontend/src/components/contextual/Chat/chat-constants.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-/**
- * Constants for the chat system.
- *
- * Centralizes magic strings and values used across chat components.
- */
-
-// LocalStorage keys
-export const STORAGE_KEY_ACTIVE_TASKS = "chat_active_tasks";
-
-// Redis Stream IDs
-export const INITIAL_MESSAGE_ID = "0";
-export const INITIAL_STREAM_ID = "0-0";
-
-// TTL values (in milliseconds)
-export const COMPLETED_STREAM_TTL_MS = 5 * 60 * 1000; // 5 minutes
-export const ACTIVE_TASK_TTL_MS = 60 * 60 * 1000; // 1 hour
diff --git a/autogpt_platform/frontend/src/components/contextual/Chat/chat-store.ts b/autogpt_platform/frontend/src/components/contextual/Chat/chat-store.ts
deleted file mode 100644
index 3083f65d2c..0000000000
--- a/autogpt_platform/frontend/src/components/contextual/Chat/chat-store.ts
+++ /dev/null
@@ -1,501 +0,0 @@
-"use client";
-
-import { create } from "zustand";
-import {
- ACTIVE_TASK_TTL_MS,
- COMPLETED_STREAM_TTL_MS,
- INITIAL_STREAM_ID,
- STORAGE_KEY_ACTIVE_TASKS,
-} from "./chat-constants";
-import type {
- ActiveStream,
- StreamChunk,
- StreamCompleteCallback,
- StreamResult,
- StreamStatus,
-} from "./chat-types";
-import { executeStream, executeTaskReconnect } from "./stream-executor";
-
-export interface ActiveTaskInfo {
- taskId: string;
- sessionId: string;
- operationId: string;
- toolName: string;
- lastMessageId: string;
- startedAt: number;
-}
-
-/** Load active tasks from localStorage */
-function loadPersistedTasks(): Map<string, ActiveTaskInfo> {
- if (typeof window === "undefined") return new Map();
- try {
- const stored = localStorage.getItem(STORAGE_KEY_ACTIVE_TASKS);
- if (!stored) return new Map();
- const parsed = JSON.parse(stored) as Record<string, ActiveTaskInfo>;
- const now = Date.now();
- const tasks = new Map<string, ActiveTaskInfo>();
- // Filter out expired tasks
- for (const [sessionId, task] of Object.entries(parsed)) {
- if (now - task.startedAt < ACTIVE_TASK_TTL_MS) {
- tasks.set(sessionId, task);
- }
- }
- return tasks;
- } catch {
- return new Map();
- }
-}
-
-/** Save active tasks to localStorage */
-function persistTasks(tasks: Map<string, ActiveTaskInfo>): void {
- if (typeof window === "undefined") return;
- try {
- const obj: Record<string, ActiveTaskInfo> = {};
- for (const [sessionId, task] of tasks) {
- obj[sessionId] = task;
- }
- localStorage.setItem(STORAGE_KEY_ACTIVE_TASKS, JSON.stringify(obj));
- } catch {
- // Ignore storage errors
- }
-}
-
-interface ChatStoreState {
- activeStreams: Map<string, ActiveStream>;
- completedStreams: Map<string, StreamResult>;
- activeSessions: Set<string>;
- streamCompleteCallbacks: Set<StreamCompleteCallback>;
- /** Active tasks for SSE reconnection - keyed by sessionId */
- activeTasks: Map<string, ActiveTaskInfo>;
-}
-
-interface ChatStoreActions {
- startStream: (
- sessionId: string,
- message: string,
- isUserMessage: boolean,
- context?: { url: string; content: string },
- onChunk?: (chunk: StreamChunk) => void,
- ) => Promise<void>;
- stopStream: (sessionId: string) => void;
- subscribeToStream: (
- sessionId: string,
- onChunk: (chunk: StreamChunk) => void,
- skipReplay?: boolean,
- ) => () => void;
- getStreamStatus: (sessionId: string) => StreamStatus;
- getCompletedStream: (sessionId: string) => StreamResult | undefined;
- clearCompletedStream: (sessionId: string) => void;
- isStreaming: (sessionId: string) => boolean;
- registerActiveSession: (sessionId: string) => void;
- unregisterActiveSession: (sessionId: string) => void;
- isSessionActive: (sessionId: string) => boolean;
- onStreamComplete: (callback: StreamCompleteCallback) => () => void;
- /** Track active task for SSE reconnection */
- setActiveTask: (
- sessionId: string,
- taskInfo: Omit<ActiveTaskInfo, "sessionId" | "startedAt">,
- ) => void;
- /** Get active task for a session */
- getActiveTask: (sessionId: string) => ActiveTaskInfo | undefined;
- /** Clear active task when operation completes */
- clearActiveTask: (sessionId: string) => void;
- /** Reconnect to an existing task stream */
- reconnectToTask: (
- sessionId: string,
- taskId: string,
- lastMessageId?: string,
- onChunk?: (chunk: StreamChunk) => void,
- ) => Promise<void>;
- /** Update last message ID for a task (for tracking replay position) */
- updateTaskLastMessageId: (sessionId: string, lastMessageId: string) => void;
-}
-
-type ChatStore = ChatStoreState & ChatStoreActions;
-
-function notifyStreamComplete(
- callbacks: Set<StreamCompleteCallback>,
- sessionId: string,
-) {
- for (const callback of callbacks) {
- try {
- callback(sessionId);
- } catch (err) {
- console.warn("[ChatStore] Stream complete callback error:", err);
- }
- }
-}
-
-function cleanupExpiredStreams(
- completedStreams: Map<string, StreamResult>,
-): Map<string, StreamResult> {
- const now = Date.now();
- const cleaned = new Map(completedStreams);
- for (const [sessionId, result] of cleaned) {
- if (now - result.completedAt > COMPLETED_STREAM_TTL_MS) {
- cleaned.delete(sessionId);
- }
- }
- return cleaned;
-}
-
-/**
- * Finalize a stream by moving it from activeStreams to completedStreams.
- * Also handles cleanup and notifications.
- */
-function finalizeStream(
- sessionId: string,
- stream: ActiveStream,
- onChunk: ((chunk: StreamChunk) => void) | undefined,
- get: () => ChatStoreState & ChatStoreActions,
- set: (state: Partial<ChatStoreState>) => void,
-): void {
- if (onChunk) stream.onChunkCallbacks.delete(onChunk);
-
- if (stream.status !== "streaming") {
- const currentState = get();
- const finalActiveStreams = new Map(currentState.activeStreams);
- let finalCompletedStreams = new Map(currentState.completedStreams);
-
- const storedStream = finalActiveStreams.get(sessionId);
- if (storedStream === stream) {
- const result: StreamResult = {
- sessionId,
- status: stream.status,
- chunks: stream.chunks,
- completedAt: Date.now(),
- error: stream.error,
- };
- finalCompletedStreams.set(sessionId, result);
- finalActiveStreams.delete(sessionId);
- finalCompletedStreams = cleanupExpiredStreams(finalCompletedStreams);
- set({
- activeStreams: finalActiveStreams,
- completedStreams: finalCompletedStreams,
- });
-
- if (stream.status === "completed" || stream.status === "error") {
- notifyStreamComplete(currentState.streamCompleteCallbacks, sessionId);
- }
- }
- }
-}
-
-/**
- * Clean up an existing stream for a session and move it to completed streams.
- * Returns updated maps for both active and completed streams.
- */
-function cleanupExistingStream(
- sessionId: string,
- activeStreams: Map<string, ActiveStream>,
- completedStreams: Map<string, StreamResult>,
- callbacks: Set<StreamCompleteCallback>,
-): {
- activeStreams: Map<string, ActiveStream>;
- completedStreams: Map<string, StreamResult>;
-} {
- const newActiveStreams = new Map(activeStreams);
- let newCompletedStreams = new Map(completedStreams);
-
- const existingStream = newActiveStreams.get(sessionId);
- if (existingStream) {
- existingStream.abortController.abort();
- const normalizedStatus =
- existingStream.status === "streaming"
- ? "completed"
- : existingStream.status;
- const result: StreamResult = {
- sessionId,
- status: normalizedStatus,
- chunks: existingStream.chunks,
- completedAt: Date.now(),
- error: existingStream.error,
- };
- newCompletedStreams.set(sessionId, result);
- newActiveStreams.delete(sessionId);
- newCompletedStreams = cleanupExpiredStreams(newCompletedStreams);
- if (normalizedStatus === "completed" || normalizedStatus === "error") {
- notifyStreamComplete(callbacks, sessionId);
- }
- }
-
- return {
- activeStreams: newActiveStreams,
- completedStreams: newCompletedStreams,
- };
-}
-
-/**
- * Create a new active stream with initial state.
- */
-function createActiveStream(
- sessionId: string,
- onChunk?: (chunk: StreamChunk) => void,
-): ActiveStream {
- const abortController = new AbortController();
- const initialCallbacks = new Set<(chunk: StreamChunk) => void>();
- if (onChunk) initialCallbacks.add(onChunk);
-
- return {
- sessionId,
- abortController,
- status: "streaming",
- startedAt: Date.now(),
- chunks: [],
- onChunkCallbacks: initialCallbacks,
- };
-}
-
-export const useChatStore = create<ChatStore>((set, get) => ({
- activeStreams: new Map(),
- completedStreams: new Map(),
- activeSessions: new Set(),
- streamCompleteCallbacks: new Set(),
- activeTasks: loadPersistedTasks(),
-
- startStream: async function startStream(
- sessionId,
- message,
- isUserMessage,
- context,
- onChunk,
- ) {
- const state = get();
- const callbacks = state.streamCompleteCallbacks;
-
- // Clean up any existing stream for this session
- const {
- activeStreams: newActiveStreams,
- completedStreams: newCompletedStreams,
- } = cleanupExistingStream(
- sessionId,
- state.activeStreams,
- state.completedStreams,
- callbacks,
- );
-
- // Create new stream
- const stream = createActiveStream(sessionId, onChunk);
- newActiveStreams.set(sessionId, stream);
- set({
- activeStreams: newActiveStreams,
- completedStreams: newCompletedStreams,
- });
-
- try {
- await executeStream(stream, message, isUserMessage, context);
- } finally {
- finalizeStream(sessionId, stream, onChunk, get, set);
- }
- },
-
- stopStream: function stopStream(sessionId) {
- const state = get();
- const stream = state.activeStreams.get(sessionId);
- if (!stream) return;
-
- stream.abortController.abort();
- stream.status = "completed";
-
- const newActiveStreams = new Map(state.activeStreams);
- let newCompletedStreams = new Map(state.completedStreams);
-
- const result: StreamResult = {
- sessionId,
- status: stream.status,
- chunks: stream.chunks,
- completedAt: Date.now(),
- error: stream.error,
- };
- newCompletedStreams.set(sessionId, result);
- newActiveStreams.delete(sessionId);
- newCompletedStreams = cleanupExpiredStreams(newCompletedStreams);
-
- set({
- activeStreams: newActiveStreams,
- completedStreams: newCompletedStreams,
- });
-
- notifyStreamComplete(state.streamCompleteCallbacks, sessionId);
- },
-
- subscribeToStream: function subscribeToStream(
- sessionId,
- onChunk,
- skipReplay = false,
- ) {
- const state = get();
- const stream = state.activeStreams.get(sessionId);
-
- if (stream) {
- if (!skipReplay) {
- for (const chunk of stream.chunks) {
- onChunk(chunk);
- }
- }
-
- stream.onChunkCallbacks.add(onChunk);
-
- return function unsubscribe() {
- stream.onChunkCallbacks.delete(onChunk);
- };
- }
-
- return function noop() {};
- },
-
- getStreamStatus: function getStreamStatus(sessionId) {
- const { activeStreams, completedStreams } = get();
-
- const active = activeStreams.get(sessionId);
- if (active) return active.status;
-
- const completed = completedStreams.get(sessionId);
- if (completed) return completed.status;
-
- return "idle";
- },
-
- getCompletedStream: function getCompletedStream(sessionId) {
- return get().completedStreams.get(sessionId);
- },
-
- clearCompletedStream: function clearCompletedStream(sessionId) {
- const state = get();
- if (!state.completedStreams.has(sessionId)) return;
-
- const newCompletedStreams = new Map(state.completedStreams);
- newCompletedStreams.delete(sessionId);
- set({ completedStreams: newCompletedStreams });
- },
-
- isStreaming: function isStreaming(sessionId) {
- const stream = get().activeStreams.get(sessionId);
- return stream?.status === "streaming";
- },
-
- registerActiveSession: function registerActiveSession(sessionId) {
- const state = get();
- if (state.activeSessions.has(sessionId)) return;
-
- const newActiveSessions = new Set(state.activeSessions);
- newActiveSessions.add(sessionId);
- set({ activeSessions: newActiveSessions });
- },
-
- unregisterActiveSession: function unregisterActiveSession(sessionId) {
- const state = get();
- if (!state.activeSessions.has(sessionId)) return;
-
- const newActiveSessions = new Set(state.activeSessions);
- newActiveSessions.delete(sessionId);
- set({ activeSessions: newActiveSessions });
- },
-
- isSessionActive: function isSessionActive(sessionId) {
- return get().activeSessions.has(sessionId);
- },
-
- onStreamComplete: function onStreamComplete(callback) {
- const state = get();
- const newCallbacks = new Set(state.streamCompleteCallbacks);
- newCallbacks.add(callback);
- set({ streamCompleteCallbacks: newCallbacks });
-
- return function unsubscribe() {
- const currentState = get();
- const cleanedCallbacks = new Set(currentState.streamCompleteCallbacks);
- cleanedCallbacks.delete(callback);
- set({ streamCompleteCallbacks: cleanedCallbacks });
- };
- },
-
- setActiveTask: function setActiveTask(sessionId, taskInfo) {
- const state = get();
- const newActiveTasks = new Map(state.activeTasks);
- newActiveTasks.set(sessionId, {
- ...taskInfo,
- sessionId,
- startedAt: Date.now(),
- });
- set({ activeTasks: newActiveTasks });
- persistTasks(newActiveTasks);
- },
-
- getActiveTask: function getActiveTask(sessionId) {
- return get().activeTasks.get(sessionId);
- },
-
- clearActiveTask: function clearActiveTask(sessionId) {
- const state = get();
- if (!state.activeTasks.has(sessionId)) return;
-
- const newActiveTasks = new Map(state.activeTasks);
- newActiveTasks.delete(sessionId);
- set({ activeTasks: newActiveTasks });
- persistTasks(newActiveTasks);
- },
-
- reconnectToTask: async function reconnectToTask(
- sessionId,
- taskId,
- lastMessageId = INITIAL_STREAM_ID,
- onChunk,
- ) {
- const state = get();
- const callbacks = state.streamCompleteCallbacks;
-
- // Clean up any existing stream for this session
- const {
- activeStreams: newActiveStreams,
- completedStreams: newCompletedStreams,
- } = cleanupExistingStream(
- sessionId,
- state.activeStreams,
- state.completedStreams,
- callbacks,
- );
-
- // Create new stream for reconnection
- const stream = createActiveStream(sessionId, onChunk);
- newActiveStreams.set(sessionId, stream);
- set({
- activeStreams: newActiveStreams,
- completedStreams: newCompletedStreams,
- });
-
- try {
- await executeTaskReconnect(stream, taskId, lastMessageId);
- } finally {
- finalizeStream(sessionId, stream, onChunk, get, set);
-
- // Clear active task on completion
- if (stream.status === "completed" || stream.status === "error") {
- const taskState = get();
- if (taskState.activeTasks.has(sessionId)) {
- const newActiveTasks = new Map(taskState.activeTasks);
- newActiveTasks.delete(sessionId);
- set({ activeTasks: newActiveTasks });
- persistTasks(newActiveTasks);
- }
- }
- }
- },
-
- updateTaskLastMessageId: function updateTaskLastMessageId(
- sessionId,
- lastMessageId,
- ) {
- const state = get();
- const task = state.activeTasks.get(sessionId);
- if (!task) return;
-
- const newActiveTasks = new Map(state.activeTasks);
- newActiveTasks.set(sessionId, {
- ...task,
- lastMessageId,
- });
- set({ activeTasks: newActiveTasks });
- persistTasks(newActiveTasks);
- },
-}));
diff --git a/autogpt_platform/frontend/src/components/contextual/Chat/chat-types.ts b/autogpt_platform/frontend/src/components/contextual/Chat/chat-types.ts
deleted file mode 100644
index 34813e17fe..0000000000
--- a/autogpt_platform/frontend/src/components/contextual/Chat/chat-types.ts
+++ /dev/null
@@ -1,163 +0,0 @@
-import type { ToolArguments, ToolResult } from "@/types/chat";
-
-export type StreamStatus = "idle" | "streaming" | "completed" | "error";
-
-export interface StreamChunk {
- type:
- | "stream_start"
- | "text_chunk"
- | "text_ended"
- | "tool_call"
- | "tool_call_start"
- | "tool_response"
- | "login_needed"
- | "need_login"
- | "credentials_needed"
- | "error"
- | "usage"
- | "stream_end";
- taskId?: string;
- timestamp?: string;
- content?: string;
- message?: string;
- code?: string;
- details?: Record<string, unknown>;
- tool_id?: string;
- tool_name?: string;
- arguments?: ToolArguments;
- result?: ToolResult;
- success?: boolean;
- idx?: number;
- session_id?: string;
- agent_info?: {
- graph_id: string;
- name: string;
- trigger_type: string;
- };
- provider?: string;
- provider_name?: string;
- credential_type?: string;
- scopes?: string[];
- title?: string;
- [key: string]: unknown;
-}
-
-export type VercelStreamChunk =
- | { type: "start"; messageId: string; taskId?: string }
- | { type: "finish" }
- | { type: "text-start"; id: string }
- | { type: "text-delta"; id: string; delta: string }
- | { type: "text-end"; id: string }
- | { type: "tool-input-start"; toolCallId: string; toolName: string }
- | {
- type: "tool-input-available";
- toolCallId: string;
- toolName: string;
- input: Record<string, unknown>;
- }
- | {
- type: "tool-output-available";
- toolCallId: string;
- toolName?: string;
- output: unknown;
- success?: boolean;
- }
- | {
- type: "usage";
- promptTokens: number;
- completionTokens: number;
- totalTokens: number;
- }
- | {
- type: "error";
- errorText: string;
- code?: string;
- details?: Record<string, unknown>;
- };
-
-export interface ActiveStream {
- sessionId: string;
- abortController: AbortController;
- status: StreamStatus;
- startedAt: number;
- chunks: StreamChunk[];
- error?: Error;
- onChunkCallbacks: Set<(chunk: StreamChunk) => void>;
-}
-
-export interface StreamResult {
- sessionId: string;
- status: StreamStatus;
- chunks: StreamChunk[];
- completedAt: number;
- error?: Error;
-}
-
-export type StreamCompleteCallback = (sessionId: string) => void;
-
-// Type guards for message types
-
-/**
- * Check if a message has a toolId property.
- */
-export function hasToolId<T extends { type: string }>(
- msg: T,
-): msg is T & { toolId: string } {
- return (
- "toolId" in msg &&
- typeof (msg as Record<string, unknown>).toolId === "string"
- );
-}
-
-/**
- * Check if a message has an operationId property.
- */
-export function hasOperationId<T extends { type: string }>(
- msg: T,
-): msg is T & { operationId: string } {
- return (
- "operationId" in msg &&
- typeof (msg as Record<string, unknown>).operationId === "string"
- );
-}
-
-/**
- * Check if a message has a toolCallId property.
- */
-export function hasToolCallId<T extends { type: string }>(
- msg: T,
-): msg is T & { toolCallId: string } {
- return (
- "toolCallId" in msg &&
- typeof (msg as Record<string, unknown>).toolCallId === "string"
- );
-}
-
-/**
- * Check if a message is an operation message type.
- */
-export function isOperationMessage<T extends { type: string }>(
- msg: T,
-): msg is T & {
- type: "operation_started" | "operation_pending" | "operation_in_progress";
-} {
- return (
- msg.type === "operation_started" ||
- msg.type === "operation_pending" ||
- msg.type === "operation_in_progress"
- );
-}
-
-/**
- * Get the tool ID from a message if available.
- * Checks toolId, operationId, and toolCallId properties.
- */
-export function getToolIdFromMessage<T extends { type: string }>(
- msg: T,
-): string | undefined {
- const record = msg as Record<string, unknown>;
- if (typeof record.toolId === "string") return record.toolId;
- if (typeof record.operationId === "string") return record.operationId;
- if (typeof record.toolCallId === "string") return record.toolCallId;
- return undefined;
-}
diff --git a/autogpt_platform/frontend/src/components/contextual/Chat/components/AIChatBubble/AIChatBubble.tsx b/autogpt_platform/frontend/src/components/contextual/Chat/components/AIChatBubble/AIChatBubble.tsx
deleted file mode 100644
index f5d56fcb15..0000000000
--- a/autogpt_platform/frontend/src/components/contextual/Chat/components/AIChatBubble/AIChatBubble.tsx
+++ /dev/null
@@ -1,15 +0,0 @@
-import { cn } from "@/lib/utils";
-import { ReactNode } from "react";
-
-export interface AIChatBubbleProps {
- children: ReactNode;
- className?: string;
-}
-
-export function AIChatBubble({ children, className }: AIChatBubbleProps) {
- return (
- <div className={cn("text-left text-[1rem] leading-relaxed", className)}>
- {children}
- </div>
- );
-}
diff --git a/autogpt_platform/frontend/src/components/contextual/Chat/components/AgentCarouselMessage/AgentCarouselMessage.tsx b/autogpt_platform/frontend/src/components/contextual/Chat/components/AgentCarouselMessage/AgentCarouselMessage.tsx
deleted file mode 100644
index 582b24de5e..0000000000
--- a/autogpt_platform/frontend/src/components/contextual/Chat/components/AgentCarouselMessage/AgentCarouselMessage.tsx
+++ /dev/null
@@ -1,119 +0,0 @@
-import { Button } from "@/components/atoms/Button/Button";
-import { Card } from "@/components/atoms/Card/Card";
-import { Text } from "@/components/atoms/Text/Text";
-import { cn } from "@/lib/utils";
-import { ArrowRight, List, Robot } from "@phosphor-icons/react";
-import Image from "next/image";
-
-export interface Agent {
- id: string;
- name: string;
- description: string;
- version?: number;
- image_url?: string;
-}
-
-export interface AgentCarouselMessageProps {
- agents: Agent[];
- totalCount?: number;
- onSelectAgent?: (agentId: string) => void;
- className?: string;
-}
-
-export function AgentCarouselMessage({
- agents,
- totalCount,
- onSelectAgent,
- className,
-}: AgentCarouselMessageProps) {
- const displayCount = totalCount ?? agents.length;
-
- return (
- <div
- className={cn(
- "mx-4 my-2 flex flex-col gap-4 rounded-lg border border-purple-200 bg-purple-50 p-6",
- className,
- )}
- >
- {/* Header */}
- <div className="flex items-center gap-3">
- <div className="flex h-10 w-10 items-center justify-center rounded-full bg-purple-500">
- <List size={24} weight="bold" className="text-white" />
- </div>
- <div>
- <Text variant="h3" className="text-purple-900">
- Found {displayCount} {displayCount === 1 ? "Agent" : "Agents"}
- </Text>
- <Text variant="small" className="text-purple-700">
- Select an agent to view details or run it
- </Text>
- </div>
- </div>
-
- {/* Agent Cards */}
- <div className="grid gap-3 sm:grid-cols-2">
- {agents.map((agent) => (
- <Card
- key={agent.id}
- className="border border-purple-200 bg-white p-4"
- >
- <div className="flex gap-3">
- <div className="relative h-10 w-10 flex-shrink-0 overflow-hidden rounded-lg bg-purple-100">
- {agent.image_url ? (
- <Image
- src={agent.image_url}
- alt={`${agent.name} preview image`}
- fill
- className="object-cover"
- />
- ) : (
- <div className="flex h-full w-full items-center justify-center">
- <Robot
- size={20}
- weight="bold"
- className="text-purple-600"
- />
- </div>
- )}
- </div>
- <div className="flex-1 space-y-2">
- <div>
- <Text
- variant="body"
- className="font-semibold text-purple-900"
- >
- {agent.name}
- </Text>
- {agent.version && (
- <Text variant="small" className="text-purple-600">
- v{agent.version}
- </Text>
- )}
- </div>
- <Text variant="small" className="line-clamp-2 text-purple-700">
- {agent.description}
- </Text>
- {onSelectAgent && (
- <Button
- onClick={() => onSelectAgent(agent.id)}
- variant="ghost"
- className="mt-2 flex items-center gap-1 p-0 text-sm text-purple-600 hover:text-purple-800"
- >
- View details
- <ArrowRight size={16} weight="bold" />
- </Button>
- )}
- </div>
- </div>
- </Card>
- ))}
- </div>
-
- {totalCount && totalCount > agents.length && (
- <Text variant="small" className="text-center text-purple-600">
- Showing {agents.length} of {totalCount} results
- </Text>
- )}
- </div>
- );
-}
diff --git a/autogpt_platform/frontend/src/components/contextual/Chat/components/AgentInputsSetup/AgentInputsSetup.tsx b/autogpt_platform/frontend/src/components/contextual/Chat/components/AgentInputsSetup/AgentInputsSetup.tsx
deleted file mode 100644
index 3ef71eca09..0000000000
--- a/autogpt_platform/frontend/src/components/contextual/Chat/components/AgentInputsSetup/AgentInputsSetup.tsx
+++ /dev/null
@@ -1,246 +0,0 @@
-"use client";
-
-import { Button } from "@/components/atoms/Button/Button";
-import { Card } from "@/components/atoms/Card/Card";
-import { Text } from "@/components/atoms/Text/Text";
-import { CredentialsInput } from "@/components/contextual/CredentialsInput/CredentialsInput";
-import { RunAgentInputs } from "@/components/contextual/RunAgentInputs/RunAgentInputs";
-
-import type { LibraryAgent } from "@/app/api/__generated__/models/libraryAgent";
-import {
- BlockIOCredentialsSubSchema,
- BlockIOSubSchema,
-} from "@/lib/autogpt-server-api/types";
-import { cn, isEmpty } from "@/lib/utils";
-import { PlayIcon, WarningIcon } from "@phosphor-icons/react";
-import { useMemo } from "react";
-import { useAgentInputsSetup } from "./useAgentInputsSetup";
-
-type LibraryAgentInputSchemaProperties = LibraryAgent["input_schema"] extends {
- properties: infer P;
-}
- ? P extends Record<string, BlockIOSubSchema>
- ? P
- : Record<string, BlockIOSubSchema>
- : Record<string, BlockIOSubSchema>;
-
-type LibraryAgentCredentialsInputSchemaProperties =
- LibraryAgent["credentials_input_schema"] extends {
- properties: infer P;
- }
- ? P extends Record<string, BlockIOCredentialsSubSchema>
- ? P
- : Record<string, BlockIOCredentialsSubSchema>
- : Record<string, BlockIOCredentialsSubSchema>;
-
-interface Props {
- agentName?: string;
- inputSchema: LibraryAgentInputSchemaProperties | Record<string, any>;
- credentialsSchema?:
- | LibraryAgentCredentialsInputSchemaProperties
- | Record<string, any>;
- message: string;
- requiredFields?: string[];
- onRun: (
- inputs: Record<string, any>,
- credentials: Record<string, any>,
- ) => void;
- onCancel?: () => void;
- className?: string;
-}
-
-export function AgentInputsSetup({
- agentName,
- inputSchema,
- credentialsSchema,
- message,
- requiredFields,
- onRun,
- onCancel,
- className,
-}: Props) {
- const { inputValues, setInputValue, credentialsValues, setCredentialsValue } =
- useAgentInputsSetup();
-
- const inputSchemaObj = useMemo(() => {
- if (!inputSchema) return { properties: {}, required: [] };
- if ("properties" in inputSchema && "type" in inputSchema) {
- return inputSchema as {
- properties: Record<string, any>;
- required?: string[];
- };
- }
- return { properties: inputSchema as Record<string, any>, required: [] };
- }, [inputSchema]);
-
- const credentialsSchemaObj = useMemo(() => {
- if (!credentialsSchema) return { properties: {}, required: [] };
- if ("properties" in credentialsSchema && "type" in credentialsSchema) {
- return credentialsSchema as {
- properties: Record<string, any>;
- required?: string[];
- };
- }
- return {
- properties: credentialsSchema as Record<string, any>,
- required: [],
- };
- }, [credentialsSchema]);
-
- const agentInputFields = useMemo(() => {
- const properties = inputSchemaObj.properties || {};
- return Object.fromEntries(
- Object.entries(properties).filter(
- ([_, subSchema]: [string, any]) => !subSchema.hidden,
- ),
- );
- }, [inputSchemaObj]);
-
- const agentCredentialsInputFields = useMemo(() => {
- return credentialsSchemaObj.properties || {};
- }, [credentialsSchemaObj]);
-
- const inputFields = Object.entries(agentInputFields);
- const credentialFields = Object.entries(agentCredentialsInputFields);
-
- const defaultsFromSchema = useMemo(() => {
- const defaults: Record<string, any> = {};
- Object.entries(agentInputFields).forEach(([key, schema]) => {
- if ("default" in schema && schema.default !== undefined) {
- defaults[key] = schema.default;
- }
- });
- return defaults;
- }, [agentInputFields]);
-
- const defaultsFromCredentialsSchema = useMemo(() => {
- const defaults: Record<string, any> = {};
- Object.entries(agentCredentialsInputFields).forEach(([key, schema]) => {
- if ("default" in schema && schema.default !== undefined) {
- defaults[key] = schema.default;
- }
- });
- return defaults;
- }, [agentCredentialsInputFields]);
-
- const mergedInputValues = useMemo(() => {
- return { ...defaultsFromSchema, ...inputValues };
- }, [defaultsFromSchema, inputValues]);
-
- const mergedCredentialsValues = useMemo(() => {
- return { ...defaultsFromCredentialsSchema, ...credentialsValues };
- }, [defaultsFromCredentialsSchema, credentialsValues]);
-
- const allRequiredInputsAreSet = useMemo(() => {
- const requiredInputs = new Set(
- requiredFields || (inputSchemaObj.required as string[]) || [],
- );
- const nonEmptyInputs = new Set(
- Object.keys(mergedInputValues).filter(
- (k) => !isEmpty(mergedInputValues[k]),
- ),
- );
- const missing = [...requiredInputs].filter(
- (input) => !nonEmptyInputs.has(input),
- );
- return missing.length === 0;
- }, [inputSchemaObj.required, mergedInputValues, requiredFields]);
-
- const allCredentialsAreSet = useMemo(() => {
- const requiredCredentials = new Set(
- (credentialsSchemaObj.required as string[]) || [],
- );
- if (requiredCredentials.size === 0) {
- return true;
- }
- const missing = [...requiredCredentials].filter((key) => {
- const cred = mergedCredentialsValues[key];
- return !cred || !cred.id;
- });
- return missing.length === 0;
- }, [credentialsSchemaObj.required, mergedCredentialsValues]);
-
- const canRun = allRequiredInputsAreSet && allCredentialsAreSet;
-
- function handleRun() {
- if (canRun) {
- onRun(mergedInputValues, mergedCredentialsValues);
- }
- }
-
- return (
- <Card
- className={cn(
- "mx-4 my-2 overflow-hidden border-blue-200 bg-blue-50",
- className,
- )}
- >
- <div className="flex items-start gap-4 p-6">
- <div className="flex h-12 w-12 flex-shrink-0 items-center justify-center rounded-full bg-blue-500">
- <WarningIcon size={24} weight="bold" className="text-white" />
- </div>
- <div className="flex-1">
- <Text variant="h3" className="mb-2 text-blue-900">
- {agentName ? `Configure ${agentName}` : "Agent Configuration"}
- </Text>
- <Text variant="body" className="mb-4 text-blue-700">
- {message}
- </Text>
-
- {inputFields.length > 0 && (
- <div className="mb-4 space-y-4">
- {inputFields.map(([key, inputSubSchema]) => (
- <RunAgentInputs
- key={key}
- schema={inputSubSchema}
- value={inputValues[key] ?? inputSubSchema.default}
- placeholder={inputSubSchema.description}
- onChange={(value) => setInputValue(key, value)}
- />
- ))}
- </div>
- )}
-
- {credentialFields.length > 0 && (
- <div className="mb-4 space-y-4">
- {credentialFields.map(([key, schema]) => {
- const requiredCredentials = new Set(
- (credentialsSchemaObj.required as string[]) || [],
- );
- return (
- <CredentialsInput
- key={key}
- schema={schema}
- selectedCredentials={credentialsValues[key]}
- onSelectCredentials={(value) =>
- setCredentialsValue(key, value)
- }
- siblingInputs={mergedInputValues}
- isOptional={!requiredCredentials.has(key)}
- />
- );
- })}
- </div>
- )}
-
- <div className="flex gap-2">
- <Button
- variant="primary"
- size="small"
- onClick={handleRun}
- disabled={!canRun}
- >
- <PlayIcon className="mr-2 h-4 w-4" weight="bold" />
- Run Agent
- </Button>
- {onCancel && (
- <Button variant="outline" size="small" onClick={onCancel}>
- Cancel
- </Button>
- )}
- </div>
- </div>
- </div>
- </Card>
- );
-}
diff --git a/autogpt_platform/frontend/src/components/contextual/Chat/components/AgentInputsSetup/useAgentInputsSetup.ts b/autogpt_platform/frontend/src/components/contextual/Chat/components/AgentInputsSetup/useAgentInputsSetup.ts
deleted file mode 100644
index e36a3f3c5d..0000000000
--- a/autogpt_platform/frontend/src/components/contextual/Chat/components/AgentInputsSetup/useAgentInputsSetup.ts
+++ /dev/null
@@ -1,38 +0,0 @@
-import type { CredentialsMetaInput } from "@/lib/autogpt-server-api/types";
-import { useState } from "react";
-
-export function useAgentInputsSetup() {
- const [inputValues, setInputValues] = useState<Record<string, any>>({});
- const [credentialsValues, setCredentialsValues] = useState<
- Record<string, CredentialsMetaInput>
- >({});
-
- function setInputValue(key: string, value: any) {
- setInputValues((prev) => ({
- ...prev,
- [key]: value,
- }));
- }
-
- function setCredentialsValue(key: string, value?: CredentialsMetaInput) {
- if (value) {
- setCredentialsValues((prev) => ({
- ...prev,
- [key]: value,
- }));
- } else {
- setCredentialsValues((prev) => {
- const next = { ...prev };
- delete next[key];
- return next;
- });
- }
- }
-
- return {
- inputValues,
- setInputValue,
- credentialsValues,
- setCredentialsValue,
- };
-}
diff --git a/autogpt_platform/frontend/src/components/contextual/Chat/components/AuthPromptWidget/AuthPromptWidget.tsx b/autogpt_platform/frontend/src/components/contextual/Chat/components/AuthPromptWidget/AuthPromptWidget.tsx
deleted file mode 100644
index b2cf92ec56..0000000000
--- a/autogpt_platform/frontend/src/components/contextual/Chat/components/AuthPromptWidget/AuthPromptWidget.tsx
+++ /dev/null
@@ -1,120 +0,0 @@
-"use client";
-
-import { Button } from "@/components/atoms/Button/Button";
-import { cn } from "@/lib/utils";
-import { ShieldIcon, SignInIcon, UserPlusIcon } from "@phosphor-icons/react";
-import { useRouter } from "next/navigation";
-
-export interface AuthPromptWidgetProps {
- message: string;
- sessionId: string;
- agentInfo?: {
- graph_id: string;
- name: string;
- trigger_type: string;
- };
- returnUrl?: string;
- className?: string;
-}
-
-export function AuthPromptWidget({
- message,
- sessionId,
- agentInfo,
- returnUrl = "/copilot/chat",
- className,
-}: AuthPromptWidgetProps) {
- const router = useRouter();
-
- function handleSignIn() {
- if (typeof window !== "undefined") {
- localStorage.setItem("pending_chat_session", sessionId);
- if (agentInfo) {
- localStorage.setItem("pending_agent_setup", JSON.stringify(agentInfo));
- }
- }
- const returnUrlWithSession = `${returnUrl}?session_id=${sessionId}`;
- const encodedReturnUrl = encodeURIComponent(returnUrlWithSession);
- router.push(`/login?returnUrl=${encodedReturnUrl}`);
- }
-
- function handleSignUp() {
- if (typeof window !== "undefined") {
- localStorage.setItem("pending_chat_session", sessionId);
- if (agentInfo) {
- localStorage.setItem("pending_agent_setup", JSON.stringify(agentInfo));
- }
- }
- const returnUrlWithSession = `${returnUrl}?session_id=${sessionId}`;
- const encodedReturnUrl = encodeURIComponent(returnUrlWithSession);
- router.push(`/signup?returnUrl=${encodedReturnUrl}`);
- }
-
- return (
- <div
- className={cn(
- "my-4 overflow-hidden rounded-lg border border-violet-200",
- "bg-gradient-to-br from-violet-50 to-purple-50",
- "duration-500 animate-in fade-in-50 slide-in-from-bottom-2",
- className,
- )}
- >
- <div className="px-6 py-5">
- <div className="mb-4 flex items-center gap-3">
- <div className="flex h-10 w-10 items-center justify-center rounded-full bg-violet-600">
- <ShieldIcon size={20} weight="fill" className="text-white" />
- </div>
- <div>
- <h3 className="text-lg font-semibold text-neutral-900">
- Authentication Required
- </h3>
- <p className="text-sm text-neutral-600">
- Sign in to set up and manage agents
- </p>
- </div>
- </div>
-
- <div className="mb-5 rounded-md bg-white/50 p-4">
- <p className="text-sm text-neutral-700">{message}</p>
- {agentInfo && (
- <div className="mt-3 text-xs text-neutral-600">
- <p>
- Ready to set up:{" "}
- <span className="font-medium">{agentInfo.name}</span>
- </p>
- <p>
- Type:{" "}
- <span className="font-medium">{agentInfo.trigger_type}</span>
- </p>
- </div>
- )}
- </div>
-
- <div className="flex gap-3">
- <Button
- onClick={handleSignIn}
- variant="primary"
- size="small"
- className="flex-1"
- >
- <SignInIcon size={16} weight="bold" className="mr-2" />
- Sign In
- </Button>
- <Button
- onClick={handleSignUp}
- variant="secondary"
- size="small"
- className="flex-1"
- >
- <UserPlusIcon size={16} weight="bold" className="mr-2" />
- Create Account
- </Button>
- </div>
-
- <div className="mt-4 text-center text-xs text-neutral-500">
- Your chat session will be preserved after signing in
- </div>
- </div>
- </div>
- );
-}
diff --git a/autogpt_platform/frontend/src/components/contextual/Chat/components/ChatContainer/ChatContainer.tsx b/autogpt_platform/frontend/src/components/contextual/Chat/components/ChatContainer/ChatContainer.tsx
deleted file mode 100644
index fbf2d5d143..0000000000
--- a/autogpt_platform/frontend/src/components/contextual/Chat/components/ChatContainer/ChatContainer.tsx
+++ /dev/null
@@ -1,130 +0,0 @@
-import type { SessionDetailResponse } from "@/app/api/__generated__/models/sessionDetailResponse";
-import { Button } from "@/components/atoms/Button/Button";
-import { Text } from "@/components/atoms/Text/Text";
-import { Dialog } from "@/components/molecules/Dialog/Dialog";
-import { cn } from "@/lib/utils";
-import { GlobeHemisphereEastIcon } from "@phosphor-icons/react";
-import { useEffect } from "react";
-import { ChatInput } from "../ChatInput/ChatInput";
-import { MessageList } from "../MessageList/MessageList";
-import { useChatContainer } from "./useChatContainer";
-
-export interface ChatContainerProps {
- sessionId: string | null;
- initialMessages: SessionDetailResponse["messages"];
- initialPrompt?: string;
- className?: string;
- onStreamingChange?: (isStreaming: boolean) => void;
- onOperationStarted?: () => void;
- /** Active stream info from the server for reconnection */
- activeStream?: {
- taskId: string;
- lastMessageId: string;
- operationId: string;
- toolName: string;
- };
-}
-
-export function ChatContainer({
- sessionId,
- initialMessages,
- initialPrompt,
- className,
- onStreamingChange,
- onOperationStarted,
- activeStream,
-}: ChatContainerProps) {
- const {
- messages,
- streamingChunks,
- isStreaming,
- stopStreaming,
- isRegionBlockedModalOpen,
- sendMessageWithContext,
- handleRegionModalOpenChange,
- handleRegionModalClose,
- } = useChatContainer({
- sessionId,
- initialMessages,
- initialPrompt,
- onOperationStarted,
- activeStream,
- });
-
- useEffect(() => {
- onStreamingChange?.(isStreaming);
- }, [isStreaming, onStreamingChange]);
-
- return (
- <div
- className={cn(
- "mx-auto flex h-full min-h-0 w-full max-w-3xl flex-col bg-[#f8f8f9]",
- className,
- )}
- >
- <Dialog
- title={
- <div className="flex items-center gap-2">
- <GlobeHemisphereEastIcon className="size-6" />
- <Text
- variant="body"
- className="text-md font-poppins leading-none md:text-lg"
- >
- Service unavailable
- </Text>
- </div>
- }
- controlled={{
- isOpen: isRegionBlockedModalOpen,
- set: handleRegionModalOpenChange,
- }}
- onClose={handleRegionModalClose}
- styling={{ maxWidth: 550, width: "100%", minWidth: "auto" }}
- >
- <Dialog.Content>
- <div className="flex flex-col gap-8">
- <Text variant="body">
- The Autogpt AI model is not available in your region or your
- connection is blocking it. Please try again with a different
- connection.
- </Text>
- <div className="flex justify-center">
- <Button
- type="button"
- variant="primary"
- onClick={handleRegionModalClose}
- className="w-full"
- >
- Got it
- </Button>
- </div>
- </div>
- </Dialog.Content>
- </Dialog>
- {/* Messages - Scrollable */}
- <div className="relative flex min-h-0 flex-1 flex-col">
- <div className="flex min-h-full flex-col justify-end">
- <MessageList
- messages={messages}
- streamingChunks={streamingChunks}
- isStreaming={isStreaming}
- onSendMessage={sendMessageWithContext}
- className="flex-1"
- />
- </div>
- </div>
-
- {/* Input - Fixed at bottom */}
- <div className="relative px-3 pb-6 pt-2">
- <div className="pointer-events-none absolute top-[-18px] z-10 h-6 w-full bg-gradient-to-b from-transparent to-[#f8f8f9]" />
- <ChatInput
- onSend={sendMessageWithContext}
- disabled={isStreaming || !sessionId}
- isStreaming={isStreaming}
- onStop={stopStreaming}
- placeholder="What else can I help with?"
- />
- </div>
- </div>
- );
-}
diff --git a/autogpt_platform/frontend/src/components/contextual/Chat/components/ChatContainer/createStreamEventDispatcher.ts b/autogpt_platform/frontend/src/components/contextual/Chat/components/ChatContainer/createStreamEventDispatcher.ts
deleted file mode 100644
index af3b3329b7..0000000000
--- a/autogpt_platform/frontend/src/components/contextual/Chat/components/ChatContainer/createStreamEventDispatcher.ts
+++ /dev/null
@@ -1,89 +0,0 @@
-import { toast } from "sonner";
-import type { StreamChunk } from "../../chat-types";
-import type { HandlerDependencies } from "./handlers";
-import {
- getErrorDisplayMessage,
- handleError,
- handleLoginNeeded,
- handleStreamEnd,
- handleTextChunk,
- handleTextEnded,
- handleToolCallStart,
- handleToolResponse,
- isRegionBlockedError,
-} from "./handlers";
-
-export function createStreamEventDispatcher(
- deps: HandlerDependencies,
-): (chunk: StreamChunk) => void {
- return function dispatchStreamEvent(chunk: StreamChunk): void {
- if (
- chunk.type === "text_chunk" ||
- chunk.type === "tool_call_start" ||
- chunk.type === "tool_response" ||
- chunk.type === "login_needed" ||
- chunk.type === "need_login" ||
- chunk.type === "error"
- ) {
- deps.hasResponseRef.current = true;
- }
-
- switch (chunk.type) {
- case "stream_start":
- // Store task ID for SSE reconnection
- if (chunk.taskId && deps.onActiveTaskStarted) {
- deps.onActiveTaskStarted({
- taskId: chunk.taskId,
- operationId: chunk.taskId,
- toolName: "chat",
- toolCallId: "chat_stream",
- });
- }
- break;
-
- case "text_chunk":
- handleTextChunk(chunk, deps);
- break;
-
- case "text_ended":
- handleTextEnded(chunk, deps);
- break;
-
- case "tool_call_start":
- handleToolCallStart(chunk, deps);
- break;
-
- case "tool_response":
- handleToolResponse(chunk, deps);
- break;
-
- case "login_needed":
- case "need_login":
- handleLoginNeeded(chunk, deps);
- break;
-
- case "stream_end":
- // Note: "finish" type from backend gets normalized to "stream_end" by normalizeStreamChunk
- handleStreamEnd(chunk, deps);
- break;
-
- case "error":
- const isRegionBlocked = isRegionBlockedError(chunk);
- handleError(chunk, deps);
- // Show toast at dispatcher level to avoid circular dependencies
- if (!isRegionBlocked) {
- toast.error("Chat Error", {
- description: getErrorDisplayMessage(chunk),
- });
- }
- break;
-
- case "usage":
- // TODO: Handle usage for display
- break;
-
- default:
- console.warn("Unknown stream chunk type:", chunk);
- }
- };
-}
diff --git a/autogpt_platform/frontend/src/components/contextual/Chat/components/ChatContainer/handlers.ts b/autogpt_platform/frontend/src/components/contextual/Chat/components/ChatContainer/handlers.ts
deleted file mode 100644
index 5aec5b9818..0000000000
--- a/autogpt_platform/frontend/src/components/contextual/Chat/components/ChatContainer/handlers.ts
+++ /dev/null
@@ -1,362 +0,0 @@
-import type { Dispatch, MutableRefObject, SetStateAction } from "react";
-import { StreamChunk } from "../../useChatStream";
-import type { ChatMessageData } from "../ChatMessage/useChatMessage";
-import {
- extractCredentialsNeeded,
- extractInputsNeeded,
- parseToolResponse,
-} from "./helpers";
-
-function isToolCallMessage(
- message: ChatMessageData,
-): message is Extract<ChatMessageData, { type: "tool_call" }> {
- return message.type === "tool_call";
-}
-
-export interface HandlerDependencies {
- setHasTextChunks: Dispatch<SetStateAction<boolean>>;
- setStreamingChunks: Dispatch<SetStateAction<string[]>>;
- streamingChunksRef: MutableRefObject<string[]>;
- hasResponseRef: MutableRefObject<boolean>;
- textFinalizedRef: MutableRefObject<boolean>;
- streamEndedRef: MutableRefObject<boolean>;
- setMessages: Dispatch<SetStateAction<ChatMessageData[]>>;
- setIsStreamingInitiated: Dispatch<SetStateAction<boolean>>;
- setIsRegionBlockedModalOpen: Dispatch<SetStateAction<boolean>>;
- sessionId: string;
- onOperationStarted?: () => void;
- onActiveTaskStarted?: (taskInfo: {
- taskId: string;
- operationId: string;
- toolName: string;
- toolCallId: string;
- }) => void;
-}
-
-export function isRegionBlockedError(chunk: StreamChunk): boolean {
- if (chunk.code === "MODEL_NOT_AVAILABLE_REGION") return true;
- const message = chunk.message || chunk.content;
- if (typeof message !== "string") return false;
- return message.toLowerCase().includes("not available in your region");
-}
-
-export function getUserFriendlyErrorMessage(
- code: string | undefined,
-): string | undefined {
- switch (code) {
- case "TASK_EXPIRED":
- return "This operation has expired. Please try again.";
- case "TASK_NOT_FOUND":
- return "Could not find the requested operation.";
- case "ACCESS_DENIED":
- return "You do not have access to this operation.";
- case "QUEUE_OVERFLOW":
- return "Connection was interrupted. Please refresh to continue.";
- case "MODEL_NOT_AVAILABLE_REGION":
- return "This model is not available in your region.";
- default:
- return undefined;
- }
-}
-
-export function handleTextChunk(chunk: StreamChunk, deps: HandlerDependencies) {
- if (!chunk.content) return;
- deps.setHasTextChunks(true);
- deps.setStreamingChunks((prev) => {
- const updated = [...prev, chunk.content!];
- deps.streamingChunksRef.current = updated;
- return updated;
- });
-}
-
-export function handleTextEnded(
- _chunk: StreamChunk,
- deps: HandlerDependencies,
-) {
- if (deps.textFinalizedRef.current) {
- return;
- }
-
- const completedText = deps.streamingChunksRef.current.join("");
- if (completedText.trim()) {
- deps.textFinalizedRef.current = true;
-
- deps.setMessages((prev) => {
- const exists = prev.some(
- (msg) =>
- msg.type === "message" &&
- msg.role === "assistant" &&
- msg.content === completedText,
- );
- if (exists) return prev;
-
- const assistantMessage: ChatMessageData = {
- type: "message",
- role: "assistant",
- content: completedText,
- timestamp: new Date(),
- };
- return [...prev, assistantMessage];
- });
- }
- deps.setStreamingChunks([]);
- deps.streamingChunksRef.current = [];
- deps.setHasTextChunks(false);
-}
-
-export function handleToolCallStart(
- chunk: StreamChunk,
- deps: HandlerDependencies,
-) {
- // Use deterministic fallback instead of Date.now() to ensure same ID on replay
- const toolId =
- chunk.tool_id ||
- `tool-${deps.sessionId}-${chunk.idx ?? "unknown"}-${chunk.tool_name || "unknown"}`;
-
- const toolCallMessage: Extract<ChatMessageData, { type: "tool_call" }> = {
- type: "tool_call",
- toolId,
- toolName: chunk.tool_name || "Executing",
- arguments: chunk.arguments || {},
- timestamp: new Date(),
- };
-
- function updateToolCallMessages(prev: ChatMessageData[]) {
- const existingIndex = prev.findIndex(function findToolCallIndex(msg) {
- return isToolCallMessage(msg) && msg.toolId === toolCallMessage.toolId;
- });
- if (existingIndex === -1) {
- return [...prev, toolCallMessage];
- }
- const nextMessages = [...prev];
- const existing = nextMessages[existingIndex];
- if (!isToolCallMessage(existing)) return prev;
- const nextArguments =
- toolCallMessage.arguments &&
- Object.keys(toolCallMessage.arguments).length > 0
- ? toolCallMessage.arguments
- : existing.arguments;
- nextMessages[existingIndex] = {
- ...existing,
- toolName: toolCallMessage.toolName || existing.toolName,
- arguments: nextArguments,
- timestamp: toolCallMessage.timestamp,
- };
- return nextMessages;
- }
-
- deps.setMessages(updateToolCallMessages);
-}
-
-const TOOL_RESPONSE_TYPES = new Set([
- "tool_response",
- "operation_started",
- "operation_pending",
- "operation_in_progress",
- "execution_started",
- "agent_carousel",
- "clarification_needed",
-]);
-
-function hasResponseForTool(
- messages: ChatMessageData[],
- toolId: string,
-): boolean {
- return messages.some((msg) => {
- if (!TOOL_RESPONSE_TYPES.has(msg.type)) return false;
- const msgToolId =
- (msg as { toolId?: string }).toolId ||
- (msg as { toolCallId?: string }).toolCallId;
- return msgToolId === toolId;
- });
-}
-
-export function handleToolResponse(
- chunk: StreamChunk,
- deps: HandlerDependencies,
-) {
- let toolName = chunk.tool_name || "unknown";
- if (!chunk.tool_name || chunk.tool_name === "unknown") {
- deps.setMessages((prev) => {
- const matchingToolCall = [...prev]
- .reverse()
- .find(
- (msg) => msg.type === "tool_call" && msg.toolId === chunk.tool_id,
- );
- if (matchingToolCall && matchingToolCall.type === "tool_call") {
- toolName = matchingToolCall.toolName;
- }
- return prev;
- });
- }
- const responseMessage = parseToolResponse(
- chunk.result!,
- chunk.tool_id!,
- toolName,
- new Date(),
- );
- if (!responseMessage) {
- let parsedResult: Record<string, unknown> | null = null;
- try {
- parsedResult =
- typeof chunk.result === "string"
- ? JSON.parse(chunk.result)
- : (chunk.result as Record<string, unknown>);
- } catch {
- parsedResult = null;
- }
- if (
- (chunk.tool_name === "run_agent" || chunk.tool_name === "run_block") &&
- chunk.success &&
- parsedResult?.type === "setup_requirements"
- ) {
- const inputsMessage = extractInputsNeeded(parsedResult, chunk.tool_name);
- if (inputsMessage) {
- deps.setMessages((prev) => {
- // Check for duplicate inputs_needed message
- const exists = prev.some((msg) => msg.type === "inputs_needed");
- if (exists) return prev;
- return [...prev, inputsMessage];
- });
- }
- const credentialsMessage = extractCredentialsNeeded(
- parsedResult,
- chunk.tool_name,
- );
- if (credentialsMessage) {
- deps.setMessages((prev) => {
- // Check for duplicate credentials_needed message
- const exists = prev.some((msg) => msg.type === "credentials_needed");
- if (exists) return prev;
- return [...prev, credentialsMessage];
- });
- }
- }
- return;
- }
- if (responseMessage.type === "operation_started") {
- deps.onOperationStarted?.();
- const taskId = (responseMessage as { taskId?: string }).taskId;
- if (taskId && deps.onActiveTaskStarted) {
- deps.onActiveTaskStarted({
- taskId,
- operationId:
- (responseMessage as { operationId?: string }).operationId || "",
- toolName: (responseMessage as { toolName?: string }).toolName || "",
- toolCallId: (responseMessage as { toolId?: string }).toolId || "",
- });
- }
- }
-
- deps.setMessages((prev) => {
- const toolCallIndex = prev.findIndex(
- (msg) => msg.type === "tool_call" && msg.toolId === chunk.tool_id,
- );
- if (hasResponseForTool(prev, chunk.tool_id!)) {
- return prev;
- }
- if (toolCallIndex !== -1) {
- const newMessages = [...prev];
- newMessages.splice(toolCallIndex + 1, 0, responseMessage);
- return newMessages;
- }
- return [...prev, responseMessage];
- });
-}
-
-export function handleLoginNeeded(
- chunk: StreamChunk,
- deps: HandlerDependencies,
-) {
- const loginNeededMessage: ChatMessageData = {
- type: "login_needed",
- toolName: "login_needed",
- message: chunk.message || "Please sign in to use chat and agent features",
- sessionId: chunk.session_id || deps.sessionId,
- agentInfo: chunk.agent_info,
- timestamp: new Date(),
- };
- deps.setMessages((prev) => {
- // Check for duplicate login_needed message
- const exists = prev.some((msg) => msg.type === "login_needed");
- if (exists) return prev;
- return [...prev, loginNeededMessage];
- });
-}
-
-export function handleStreamEnd(
- _chunk: StreamChunk,
- deps: HandlerDependencies,
-) {
- if (deps.streamEndedRef.current) {
- return;
- }
- deps.streamEndedRef.current = true;
-
- const completedContent = deps.streamingChunksRef.current.join("");
- if (!completedContent.trim() && !deps.hasResponseRef.current) {
- deps.setMessages((prev) => {
- const exists = prev.some(
- (msg) =>
- msg.type === "message" &&
- msg.role === "assistant" &&
- msg.content === "No response received. Please try again.",
- );
- if (exists) return prev;
- return [
- ...prev,
- {
- type: "message",
- role: "assistant",
- content: "No response received. Please try again.",
- timestamp: new Date(),
- },
- ];
- });
- }
- if (completedContent.trim() && !deps.textFinalizedRef.current) {
- deps.textFinalizedRef.current = true;
-
- deps.setMessages((prev) => {
- const exists = prev.some(
- (msg) =>
- msg.type === "message" &&
- msg.role === "assistant" &&
- msg.content === completedContent,
- );
- if (exists) return prev;
-
- const assistantMessage: ChatMessageData = {
- type: "message",
- role: "assistant",
- content: completedContent,
- timestamp: new Date(),
- };
- return [...prev, assistantMessage];
- });
- }
- deps.setStreamingChunks([]);
- deps.streamingChunksRef.current = [];
- deps.setHasTextChunks(false);
- deps.setIsStreamingInitiated(false);
-}
-
-export function handleError(chunk: StreamChunk, deps: HandlerDependencies) {
- if (isRegionBlockedError(chunk)) {
- deps.setIsRegionBlockedModalOpen(true);
- }
- deps.setIsStreamingInitiated(false);
- deps.setHasTextChunks(false);
- deps.setStreamingChunks([]);
- deps.streamingChunksRef.current = [];
- deps.textFinalizedRef.current = false;
- deps.streamEndedRef.current = true;
-}
-
-export function getErrorDisplayMessage(chunk: StreamChunk): string {
- const friendlyMessage = getUserFriendlyErrorMessage(chunk.code);
- if (friendlyMessage) {
- return friendlyMessage;
- }
- return chunk.message || chunk.content || "An error occurred";
-}
diff --git a/autogpt_platform/frontend/src/components/contextual/Chat/components/ChatContainer/helpers.ts b/autogpt_platform/frontend/src/components/contextual/Chat/components/ChatContainer/helpers.ts
deleted file mode 100644
index f1e94cea17..0000000000
--- a/autogpt_platform/frontend/src/components/contextual/Chat/components/ChatContainer/helpers.ts
+++ /dev/null
@@ -1,607 +0,0 @@
-import type { SessionDetailResponse } from "@/app/api/__generated__/models/sessionDetailResponse";
-import { SessionKey, sessionStorage } from "@/services/storage/session-storage";
-import type { ToolResult } from "@/types/chat";
-import type { ChatMessageData } from "../ChatMessage/useChatMessage";
-
-export function processInitialMessages(
- initialMessages: SessionDetailResponse["messages"],
-): ChatMessageData[] {
- const processedMessages: ChatMessageData[] = [];
- const toolCallMap = new Map<string, string>();
-
- for (const msg of initialMessages) {
- if (!isValidMessage(msg)) {
- console.warn("Invalid message structure from backend:", msg);
- continue;
- }
-
- let content = String(msg.content || "");
- const role = String(msg.role || "assistant").toLowerCase();
- const toolCalls = msg.tool_calls;
- const timestamp = msg.timestamp
- ? new Date(msg.timestamp as string)
- : undefined;
-
- if (role === "user") {
- content = removePageContext(content);
- if (!content.trim()) continue;
- processedMessages.push({
- type: "message",
- role: "user",
- content,
- timestamp,
- });
- continue;
- }
-
- if (role === "assistant") {
- content = content
- .replace(/<thinking>[\s\S]*?<\/thinking>/gi, "")
- .replace(/<internal_reasoning>[\s\S]*?<\/internal_reasoning>/gi, "")
- .trim();
-
- if (toolCalls && isToolCallArray(toolCalls) && toolCalls.length > 0) {
- for (const toolCall of toolCalls) {
- const toolName = toolCall.function.name;
- const toolId = toolCall.id;
- toolCallMap.set(toolId, toolName);
-
- try {
- const args = JSON.parse(toolCall.function.arguments || "{}");
- processedMessages.push({
- type: "tool_call",
- toolId,
- toolName,
- arguments: args,
- timestamp,
- });
- } catch (err) {
- console.warn("Failed to parse tool call arguments:", err);
- processedMessages.push({
- type: "tool_call",
- toolId,
- toolName,
- arguments: {},
- timestamp,
- });
- }
- }
- if (content.trim()) {
- processedMessages.push({
- type: "message",
- role: "assistant",
- content,
- timestamp,
- });
- }
- } else if (content.trim()) {
- processedMessages.push({
- type: "message",
- role: "assistant",
- content,
- timestamp,
- });
- }
- continue;
- }
-
- if (role === "tool") {
- const toolCallId = (msg.tool_call_id as string) || "";
- const toolName = toolCallMap.get(toolCallId) || "unknown";
- const toolResponse = parseToolResponse(
- content,
- toolCallId,
- toolName,
- timestamp,
- );
- if (toolResponse) {
- processedMessages.push(toolResponse);
- }
- continue;
- }
-
- if (content.trim()) {
- processedMessages.push({
- type: "message",
- role: role as "user" | "assistant" | "system",
- content,
- timestamp,
- });
- }
- }
-
- return processedMessages;
-}
-
-export function hasSentInitialPrompt(sessionId: string): boolean {
- try {
- const sent = JSON.parse(
- sessionStorage.get(SessionKey.CHAT_SENT_INITIAL_PROMPTS) || "{}",
- );
- return sent[sessionId] === true;
- } catch {
- return false;
- }
-}
-
-export function markInitialPromptSent(sessionId: string): void {
- try {
- const sent = JSON.parse(
- sessionStorage.get(SessionKey.CHAT_SENT_INITIAL_PROMPTS) || "{}",
- );
- sent[sessionId] = true;
- sessionStorage.set(
- SessionKey.CHAT_SENT_INITIAL_PROMPTS,
- JSON.stringify(sent),
- );
- } catch {
- // Ignore storage errors
- }
-}
-
-export function removePageContext(content: string): string {
- // Remove "Page URL: ..." pattern at start of line (case insensitive, handles various formats)
- let cleaned = content.replace(/^\s*Page URL:\s*[^\n\r]*/gim, "");
-
- // Find "User Message:" marker at start of line to preserve the actual user message
- const userMessageMatch = cleaned.match(/^\s*User Message:\s*([\s\S]*)$/im);
- if (userMessageMatch) {
- // If we found "User Message:", extract everything after it
- cleaned = userMessageMatch[1];
- } else {
- // If no "User Message:" marker, remove "Page Content:" and everything after it at start of line
- cleaned = cleaned.replace(/^\s*Page Content:[\s\S]*$/gim, "");
- }
-
- // Clean up extra whitespace and newlines
- cleaned = cleaned.replace(/\n\s*\n\s*\n+/g, "\n\n").trim();
- return cleaned;
-}
-
-export function createUserMessage(content: string): ChatMessageData {
- return {
- type: "message",
- role: "user",
- content,
- timestamp: new Date(),
- };
-}
-
-export function filterAuthMessages(
- messages: ChatMessageData[],
-): ChatMessageData[] {
- return messages.filter(
- (msg) => msg.type !== "credentials_needed" && msg.type !== "login_needed",
- );
-}
-
-export function isValidMessage(msg: unknown): msg is Record<string, unknown> {
- if (typeof msg !== "object" || msg === null) {
- return false;
- }
- const m = msg as Record<string, unknown>;
- if (typeof m.role !== "string") {
- return false;
- }
- if (m.content !== undefined && typeof m.content !== "string") {
- return false;
- }
- return true;
-}
-
-export function isToolCallArray(value: unknown): value is Array<{
- id: string;
- type: string;
- function: { name: string; arguments: string };
-}> {
- if (!Array.isArray(value)) {
- return false;
- }
- return value.every(
- (item) =>
- typeof item === "object" &&
- item !== null &&
- "id" in item &&
- typeof item.id === "string" &&
- "type" in item &&
- typeof item.type === "string" &&
- "function" in item &&
- typeof item.function === "object" &&
- item.function !== null &&
- "name" in item.function &&
- typeof item.function.name === "string" &&
- "arguments" in item.function &&
- typeof item.function.arguments === "string",
- );
-}
-
-export function isAgentArray(value: unknown): value is Array<{
- id: string;
- name: string;
- description: string;
- version?: number;
- image_url?: string;
-}> {
- if (!Array.isArray(value)) {
- return false;
- }
- return value.every(
- (item) =>
- typeof item === "object" &&
- item !== null &&
- "id" in item &&
- typeof item.id === "string" &&
- "name" in item &&
- typeof item.name === "string" &&
- "description" in item &&
- typeof item.description === "string" &&
- (!("version" in item) || typeof item.version === "number") &&
- (!("image_url" in item) || typeof item.image_url === "string"),
- );
-}
-
-export function extractJsonFromErrorMessage(
- message: string,
-): Record<string, unknown> | null {
- try {
- const start = message.indexOf("{");
- if (start === -1) {
- return null;
- }
- let depth = 0;
- let end = -1;
- for (let i = start; i < message.length; i++) {
- const ch = message[i];
- if (ch === "{") {
- depth++;
- } else if (ch === "}") {
- depth--;
- if (depth === 0) {
- end = i;
- break;
- }
- }
- }
- if (end === -1) {
- return null;
- }
- const jsonStr = message.slice(start, end + 1);
- return JSON.parse(jsonStr) as Record<string, unknown>;
- } catch {
- return null;
- }
-}
-
-export function parseToolResponse(
- result: ToolResult,
- toolId: string,
- toolName: string,
- timestamp?: Date,
-): ChatMessageData | null {
- let parsedResult: Record<string, unknown> | null = null;
- try {
- parsedResult =
- typeof result === "string"
- ? JSON.parse(result)
- : (result as Record<string, unknown>);
- } catch {
- parsedResult = null;
- }
- if (parsedResult && typeof parsedResult === "object") {
- const responseType = parsedResult.type as string | undefined;
- if (responseType === "no_results") {
- return {
- type: "tool_response",
- toolId,
- toolName,
- result: (parsedResult.message as string) || "No results found",
- success: true,
- timestamp: timestamp || new Date(),
- };
- }
- if (responseType === "agent_carousel") {
- const agentsData = parsedResult.agents;
- if (isAgentArray(agentsData)) {
- return {
- type: "agent_carousel",
- toolId,
- toolName: "agent_carousel",
- agents: agentsData,
- totalCount: parsedResult.total_count as number | undefined,
- timestamp: timestamp || new Date(),
- };
- } else {
- console.warn("Invalid agents array in agent_carousel response");
- }
- }
- if (responseType === "execution_started") {
- return {
- type: "execution_started",
- toolId,
- toolName: "execution_started",
- executionId: (parsedResult.execution_id as string) || "",
- agentName: (parsedResult.graph_name as string) || undefined,
- message: parsedResult.message as string | undefined,
- libraryAgentLink: parsedResult.library_agent_link as string | undefined,
- timestamp: timestamp || new Date(),
- };
- }
- if (responseType === "clarification_needed") {
- return {
- type: "clarification_needed",
- toolName,
- questions:
- (parsedResult.questions as Array<{
- question: string;
- keyword: string;
- example?: string;
- }>) || [],
- message:
- (parsedResult.message as string) ||
- "I need more information to proceed.",
- sessionId: (parsedResult.session_id as string) || "",
- timestamp: timestamp || new Date(),
- };
- }
- if (responseType === "operation_started") {
- return {
- type: "operation_started",
- toolName: (parsedResult.tool_name as string) || toolName,
- toolId,
- operationId: (parsedResult.operation_id as string) || "",
- taskId: (parsedResult.task_id as string) || undefined, // For SSE reconnection
- message:
- (parsedResult.message as string) ||
- "Operation started. You can close this tab.",
- timestamp: timestamp || new Date(),
- };
- }
- if (responseType === "operation_pending") {
- return {
- type: "operation_pending",
- toolName: (parsedResult.tool_name as string) || toolName,
- toolId,
- operationId: (parsedResult.operation_id as string) || "",
- message:
- (parsedResult.message as string) ||
- "Operation in progress. Please wait...",
- timestamp: timestamp || new Date(),
- };
- }
- if (responseType === "operation_in_progress") {
- return {
- type: "operation_in_progress",
- toolName: (parsedResult.tool_name as string) || toolName,
- toolCallId: (parsedResult.tool_call_id as string) || toolId,
- message:
- (parsedResult.message as string) ||
- "Operation already in progress. Please wait...",
- timestamp: timestamp || new Date(),
- };
- }
- if (responseType === "need_login") {
- return {
- type: "login_needed",
- toolName: "login_needed",
- message:
- (parsedResult.message as string) ||
- "Please sign in to use chat and agent features",
- sessionId: (parsedResult.session_id as string) || "",
- agentInfo: parsedResult.agent_info as
- | {
- graph_id: string;
- name: string;
- trigger_type: string;
- }
- | undefined,
- timestamp: timestamp || new Date(),
- };
- }
- if (responseType === "setup_requirements") {
- return null;
- }
- if (responseType === "understanding_updated") {
- return {
- type: "tool_response",
- toolId,
- toolName,
- result: (parsedResult || result) as ToolResult,
- success: true,
- timestamp: timestamp || new Date(),
- };
- }
- }
- return {
- type: "tool_response",
- toolId,
- toolName,
- result: parsedResult ? (parsedResult as ToolResult) : result,
- success: true,
- timestamp: timestamp || new Date(),
- };
-}
-
-export function isUserReadiness(
- value: unknown,
-): value is { missing_credentials?: Record<string, unknown> } {
- return (
- typeof value === "object" &&
- value !== null &&
- (!("missing_credentials" in value) ||
- typeof (value as any).missing_credentials === "object")
- );
-}
-
-export function isMissingCredentials(
- value: unknown,
-): value is Record<string, Record<string, unknown>> {
- if (typeof value !== "object" || value === null) {
- return false;
- }
- return Object.values(value).every((v) => typeof v === "object" && v !== null);
-}
-
-export function isSetupInfo(value: unknown): value is {
- user_readiness?: Record<string, unknown>;
- agent_name?: string;
-} {
- return (
- typeof value === "object" &&
- value !== null &&
- (!("user_readiness" in value) ||
- typeof (value as any).user_readiness === "object") &&
- (!("agent_name" in value) || typeof (value as any).agent_name === "string")
- );
-}
-
-export function extractCredentialsNeeded(
- parsedResult: Record<string, unknown>,
- toolName: string = "run_agent",
-): ChatMessageData | null {
- try {
- const setupInfo = parsedResult?.setup_info as
- | Record<string, unknown>
- | undefined;
- const userReadiness = setupInfo?.user_readiness as
- | Record<string, unknown>
- | undefined;
- const missingCreds = userReadiness?.missing_credentials as
- | Record<string, Record<string, unknown>>
- | undefined;
- if (missingCreds && Object.keys(missingCreds).length > 0) {
- const agentName = (setupInfo?.agent_name as string) || "this block";
- const credentials = Object.values(missingCreds).map((credInfo) => {
- // Normalize to array at boundary - prefer 'types' array, fall back to single 'type'
- const typesArray = credInfo.types as
- | Array<"api_key" | "oauth2" | "user_password" | "host_scoped">
- | undefined;
- const singleType =
- (credInfo.type as
- | "api_key"
- | "oauth2"
- | "user_password"
- | "host_scoped"
- | undefined) || "api_key";
- const credentialTypes =
- typesArray && typesArray.length > 0 ? typesArray : [singleType];
-
- return {
- provider: (credInfo.provider as string) || "unknown",
- providerName:
- (credInfo.provider_name as string) ||
- (credInfo.provider as string) ||
- "Unknown Provider",
- credentialTypes,
- title:
- (credInfo.title as string) ||
- `${(credInfo.provider_name as string) || (credInfo.provider as string)} credentials`,
- scopes: credInfo.scopes as string[] | undefined,
- };
- });
- return {
- type: "credentials_needed",
- toolName,
- credentials,
- message: `To run ${agentName}, you need to add ${credentials.length === 1 ? "credentials" : `${credentials.length} credentials`}.`,
- agentName,
- timestamp: new Date(),
- };
- }
- return null;
- } catch (err) {
- console.error("Failed to extract credentials from setup info:", err);
- return null;
- }
-}
-
-export function extractInputsNeeded(
- parsedResult: Record<string, unknown>,
- toolName: string = "run_agent",
-): ChatMessageData | null {
- try {
- const setupInfo = parsedResult?.setup_info as
- | Record<string, unknown>
- | undefined;
- const requirements = setupInfo?.requirements as
- | Record<string, unknown>
- | undefined;
- const inputs = requirements?.inputs as
- | Array<Record<string, unknown>>
- | undefined;
- const credentials = requirements?.credentials as
- | Array<Record<string, unknown>>
- | undefined;
-
- if (!inputs || inputs.length === 0) {
- return null;
- }
-
- const agentName = (setupInfo?.agent_name as string) || "this agent";
- const agentId = parsedResult?.graph_id as string | undefined;
- const graphVersion = parsedResult?.graph_version as number | undefined;
-
- const properties: Record<string, any> = {};
- const requiredProps: string[] = [];
- inputs.forEach((input) => {
- const name = input.name as string;
- if (name) {
- properties[name] = {
- title: input.name as string,
- description: (input.description as string) || "",
- type: (input.type as string) || "string",
- default: input.default,
- enum: input.options,
- format: input.format,
- };
- if ((input.required as boolean) === true) {
- requiredProps.push(name);
- }
- }
- });
-
- const inputSchema: Record<string, any> = {
- type: "object",
- properties,
- };
- if (requiredProps.length > 0) {
- inputSchema.required = requiredProps;
- }
-
- const credentialsSchema: Record<string, any> = {};
- if (credentials && credentials.length > 0) {
- credentials.forEach((cred) => {
- const id = cred.id as string;
- if (id) {
- const credentialTypes = Array.isArray(cred.types)
- ? cred.types
- : [(cred.type as string) || "api_key"];
- credentialsSchema[id] = {
- type: "object",
- properties: {},
- credentials_provider: [cred.provider as string],
- credentials_types: credentialTypes,
- credentials_scopes: cred.scopes as string[] | undefined,
- };
- }
- });
- }
-
- return {
- type: "inputs_needed",
- toolName,
- agentName,
- agentId,
- graphVersion,
- inputSchema,
- credentialsSchema:
- Object.keys(credentialsSchema).length > 0
- ? credentialsSchema
- : undefined,
- message: `Please provide the required inputs to run ${agentName}.`,
- timestamp: new Date(),
- };
- } catch (err) {
- console.error("Failed to extract inputs from setup info:", err);
- return null;
- }
-}
diff --git a/autogpt_platform/frontend/src/components/contextual/Chat/components/ChatContainer/useChatContainer.ts b/autogpt_platform/frontend/src/components/contextual/Chat/components/ChatContainer/useChatContainer.ts
deleted file mode 100644
index 248383df42..0000000000
--- a/autogpt_platform/frontend/src/components/contextual/Chat/components/ChatContainer/useChatContainer.ts
+++ /dev/null
@@ -1,517 +0,0 @@
-import type { SessionDetailResponse } from "@/app/api/__generated__/models/sessionDetailResponse";
-import { useEffect, useMemo, useRef, useState } from "react";
-import { INITIAL_STREAM_ID } from "../../chat-constants";
-import { useChatStore } from "../../chat-store";
-import { toast } from "sonner";
-import { useChatStream } from "../../useChatStream";
-import { usePageContext } from "../../usePageContext";
-import type { ChatMessageData } from "../ChatMessage/useChatMessage";
-import {
- getToolIdFromMessage,
- hasToolId,
- isOperationMessage,
- type StreamChunk,
-} from "../../chat-types";
-import { createStreamEventDispatcher } from "./createStreamEventDispatcher";
-import {
- createUserMessage,
- filterAuthMessages,
- hasSentInitialPrompt,
- markInitialPromptSent,
- processInitialMessages,
-} from "./helpers";
-
-const TOOL_RESULT_TYPES = new Set([
- "tool_response",
- "agent_carousel",
- "execution_started",
- "clarification_needed",
-]);
-
-// Helper to generate deduplication key for a message
-function getMessageKey(msg: ChatMessageData): string {
- if (msg.type === "message") {
- // Don't include timestamp - dedupe by role + content only
- // This handles the case where local and server timestamps differ
- // Server messages are authoritative, so duplicates from local state are filtered
- return `msg:${msg.role}:${msg.content}`;
- } else if (msg.type === "tool_call") {
- return `toolcall:${msg.toolId}`;
- } else if (TOOL_RESULT_TYPES.has(msg.type)) {
- // Unified key for all tool result types - same toolId with different types
- // (tool_response vs agent_carousel) should deduplicate to the same key
- const toolId = getToolIdFromMessage(msg);
- // If no toolId, fall back to content-based key to avoid empty key collisions
- if (!toolId) {
- return `toolresult:content:${JSON.stringify(msg).slice(0, 200)}`;
- }
- return `toolresult:${toolId}`;
- } else if (isOperationMessage(msg)) {
- const toolId = getToolIdFromMessage(msg) || "";
- return `op:${toolId}:${msg.toolName}`;
- } else {
- return `${msg.type}:${JSON.stringify(msg).slice(0, 100)}`;
- }
-}
-
-interface Args {
- sessionId: string | null;
- initialMessages: SessionDetailResponse["messages"];
- initialPrompt?: string;
- onOperationStarted?: () => void;
- /** Active stream info from the server for reconnection */
- activeStream?: {
- taskId: string;
- lastMessageId: string;
- operationId: string;
- toolName: string;
- };
-}
-
-export function useChatContainer({
- sessionId,
- initialMessages,
- initialPrompt,
- onOperationStarted,
- activeStream,
-}: Args) {
- const [messages, setMessages] = useState<ChatMessageData[]>([]);
- const [streamingChunks, setStreamingChunks] = useState<string[]>([]);
- const [hasTextChunks, setHasTextChunks] = useState(false);
- const [isStreamingInitiated, setIsStreamingInitiated] = useState(false);
- const [isRegionBlockedModalOpen, setIsRegionBlockedModalOpen] =
- useState(false);
- const hasResponseRef = useRef(false);
- const streamingChunksRef = useRef<string[]>([]);
- const textFinalizedRef = useRef(false);
- const streamEndedRef = useRef(false);
- const previousSessionIdRef = useRef<string | null>(null);
- const {
- error,
- sendMessage: sendStreamMessage,
- stopStreaming,
- } = useChatStream();
- const activeStreams = useChatStore((s) => s.activeStreams);
- const subscribeToStream = useChatStore((s) => s.subscribeToStream);
- const setActiveTask = useChatStore((s) => s.setActiveTask);
- const getActiveTask = useChatStore((s) => s.getActiveTask);
- const reconnectToTask = useChatStore((s) => s.reconnectToTask);
- const isStreaming = isStreamingInitiated || hasTextChunks;
- // Track whether we've already connected to this activeStream to avoid duplicate connections
- const connectedActiveStreamRef = useRef<string | null>(null);
- // Track if component is mounted to prevent state updates after unmount
- const isMountedRef = useRef(true);
- // Track current dispatcher to prevent multiple dispatchers from adding messages
- const currentDispatcherIdRef = useRef(0);
-
- // Set mounted flag - reset on every mount, cleanup on unmount
- useEffect(function trackMountedState() {
- isMountedRef.current = true;
- return function cleanup() {
- isMountedRef.current = false;
- };
- }, []);
-
- // Callback to store active task info for SSE reconnection
- function handleActiveTaskStarted(taskInfo: {
- taskId: string;
- operationId: string;
- toolName: string;
- toolCallId: string;
- }) {
- if (!sessionId) return;
- setActiveTask(sessionId, {
- taskId: taskInfo.taskId,
- operationId: taskInfo.operationId,
- toolName: taskInfo.toolName,
- lastMessageId: INITIAL_STREAM_ID,
- });
- }
-
- // Create dispatcher for stream events - stable reference for current sessionId
- // Each dispatcher gets a unique ID to prevent stale dispatchers from updating state
- function createDispatcher() {
- if (!sessionId) return () => {};
- // Increment dispatcher ID - only the most recent dispatcher should update state
- const dispatcherId = ++currentDispatcherIdRef.current;
-
- const baseDispatcher = createStreamEventDispatcher({
- setHasTextChunks,
- setStreamingChunks,
- streamingChunksRef,
- hasResponseRef,
- textFinalizedRef,
- streamEndedRef,
- setMessages,
- setIsRegionBlockedModalOpen,
- sessionId,
- setIsStreamingInitiated,
- onOperationStarted,
- onActiveTaskStarted: handleActiveTaskStarted,
- });
-
- // Wrap dispatcher to check if it's still the current one
- return function guardedDispatcher(chunk: StreamChunk) {
- // Skip if component unmounted or this is a stale dispatcher
- if (!isMountedRef.current) {
- return;
- }
- if (dispatcherId !== currentDispatcherIdRef.current) {
- return;
- }
- baseDispatcher(chunk);
- };
- }
-
- useEffect(
- function handleSessionChange() {
- const isSessionChange = sessionId !== previousSessionIdRef.current;
-
- // Handle session change - reset state
- if (isSessionChange) {
- const prevSession = previousSessionIdRef.current;
- if (prevSession) {
- stopStreaming(prevSession);
- }
- previousSessionIdRef.current = sessionId;
- connectedActiveStreamRef.current = null;
- setMessages([]);
- setStreamingChunks([]);
- streamingChunksRef.current = [];
- setHasTextChunks(false);
- setIsStreamingInitiated(false);
- hasResponseRef.current = false;
- textFinalizedRef.current = false;
- streamEndedRef.current = false;
- }
-
- if (!sessionId) return;
-
- // Priority 1: Check if server told us there's an active stream (most authoritative)
- if (activeStream) {
- const streamKey = `${sessionId}:${activeStream.taskId}`;
-
- if (connectedActiveStreamRef.current === streamKey) {
- return;
- }
-
- // Skip if there's already an active stream for this session in the store
- const existingStream = activeStreams.get(sessionId);
- if (existingStream && existingStream.status === "streaming") {
- connectedActiveStreamRef.current = streamKey;
- return;
- }
-
- connectedActiveStreamRef.current = streamKey;
-
- // Clear all state before reconnection to prevent duplicates
- // Server's initialMessages is authoritative; local state will be rebuilt from SSE replay
- setMessages([]);
- setStreamingChunks([]);
- streamingChunksRef.current = [];
- setHasTextChunks(false);
- textFinalizedRef.current = false;
- streamEndedRef.current = false;
- hasResponseRef.current = false;
-
- setIsStreamingInitiated(true);
- setActiveTask(sessionId, {
- taskId: activeStream.taskId,
- operationId: activeStream.operationId,
- toolName: activeStream.toolName,
- lastMessageId: activeStream.lastMessageId,
- });
- reconnectToTask(
- sessionId,
- activeStream.taskId,
- activeStream.lastMessageId,
- createDispatcher(),
- );
- // Don't return cleanup here - the guarded dispatcher handles stale events
- // and the stream will complete naturally. Cleanup would prematurely stop
- // the stream when effect re-runs due to activeStreams changing.
- return;
- }
-
- // Only check localStorage/in-memory on session change
- if (!isSessionChange) return;
-
- // Priority 2: Check localStorage for active task
- const activeTask = getActiveTask(sessionId);
- if (activeTask) {
- // Clear all state before reconnection to prevent duplicates
- // Server's initialMessages is authoritative; local state will be rebuilt from SSE replay
- setMessages([]);
- setStreamingChunks([]);
- streamingChunksRef.current = [];
- setHasTextChunks(false);
- textFinalizedRef.current = false;
- streamEndedRef.current = false;
- hasResponseRef.current = false;
-
- setIsStreamingInitiated(true);
- reconnectToTask(
- sessionId,
- activeTask.taskId,
- activeTask.lastMessageId,
- createDispatcher(),
- );
- // Don't return cleanup here - the guarded dispatcher handles stale events
- return;
- }
-
- // Priority 3: Check for an in-memory active stream (same-tab scenario)
- const inMemoryStream = activeStreams.get(sessionId);
- if (!inMemoryStream || inMemoryStream.status !== "streaming") {
- return;
- }
-
- setIsStreamingInitiated(true);
- const skipReplay = initialMessages.length > 0;
- return subscribeToStream(sessionId, createDispatcher(), skipReplay);
- },
- [
- sessionId,
- stopStreaming,
- activeStreams,
- subscribeToStream,
- onOperationStarted,
- getActiveTask,
- reconnectToTask,
- activeStream,
- setActiveTask,
- ],
- );
-
- // Collect toolIds from completed tool results in initialMessages
- // Used to filter out operation messages when their results arrive
- const completedToolIds = useMemo(() => {
- const processedInitial = processInitialMessages(initialMessages);
- const ids = new Set<string>();
- for (const msg of processedInitial) {
- if (
- msg.type === "tool_response" ||
- msg.type === "agent_carousel" ||
- msg.type === "execution_started"
- ) {
- const toolId = hasToolId(msg) ? msg.toolId : undefined;
- if (toolId) {
- ids.add(toolId);
- }
- }
- }
- return ids;
- }, [initialMessages]);
-
- // Clean up local operation messages when their completed results arrive from polling
- // This effect runs when completedToolIds changes (i.e., when polling brings new results)
- useEffect(
- function cleanupCompletedOperations() {
- if (completedToolIds.size === 0) return;
-
- setMessages((prev) => {
- const filtered = prev.filter((msg) => {
- if (isOperationMessage(msg)) {
- const toolId = getToolIdFromMessage(msg);
- if (toolId && completedToolIds.has(toolId)) {
- return false; // Remove - operation completed
- }
- }
- return true;
- });
- // Only update state if something was actually filtered
- return filtered.length === prev.length ? prev : filtered;
- });
- },
- [completedToolIds],
- );
-
- // Combine initial messages from backend with local streaming messages,
- // Server messages maintain correct order; only append truly new local messages
- const allMessages = useMemo(() => {
- const processedInitial = processInitialMessages(initialMessages);
-
- // Build a set of keys from server messages for deduplication
- const serverKeys = new Set<string>();
- for (const msg of processedInitial) {
- serverKeys.add(getMessageKey(msg));
- }
-
- // Filter local messages: remove duplicates and completed operation messages
- const newLocalMessages = messages.filter((msg) => {
- // Remove operation messages for completed tools
- if (isOperationMessage(msg)) {
- const toolId = getToolIdFromMessage(msg);
- if (toolId && completedToolIds.has(toolId)) {
- return false;
- }
- }
- // Remove messages that already exist in server data
- const key = getMessageKey(msg);
- return !serverKeys.has(key);
- });
-
- // Server messages first (correct order), then new local messages
- const combined = [...processedInitial, ...newLocalMessages];
-
- // Post-processing: Remove duplicate assistant messages that can occur during
- // race conditions (e.g., rapid screen switching during SSE reconnection).
- // Two assistant messages are considered duplicates if:
- // - They are both text messages with role "assistant"
- // - One message's content starts with the other's content (partial vs complete)
- // - Or they have very similar content (>80% overlap at the start)
- const deduplicated: ChatMessageData[] = [];
- for (let i = 0; i < combined.length; i++) {
- const current = combined[i];
-
- // Check if this is an assistant text message
- if (current.type !== "message" || current.role !== "assistant") {
- deduplicated.push(current);
- continue;
- }
-
- // Look for duplicate assistant messages in the rest of the array
- let dominated = false;
- for (let j = 0; j < combined.length; j++) {
- if (i === j) continue;
- const other = combined[j];
- if (other.type !== "message" || other.role !== "assistant") continue;
-
- const currentContent = current.content || "";
- const otherContent = other.content || "";
-
- // Skip empty messages
- if (!currentContent.trim() || !otherContent.trim()) continue;
-
- // Check if current is a prefix of other (current is incomplete version)
- if (
- otherContent.length > currentContent.length &&
- otherContent.startsWith(currentContent.slice(0, 100))
- ) {
- // Current is a shorter/incomplete version of other - skip it
- dominated = true;
- break;
- }
-
- // Check if messages are nearly identical (within a small difference)
- // This catches cases where content differs only slightly
- const minLen = Math.min(currentContent.length, otherContent.length);
- const compareLen = Math.min(minLen, 200); // Compare first 200 chars
- if (
- compareLen > 50 &&
- currentContent.slice(0, compareLen) ===
- otherContent.slice(0, compareLen)
- ) {
- // Same prefix - keep the longer one
- if (otherContent.length > currentContent.length) {
- dominated = true;
- break;
- }
- }
- }
-
- if (!dominated) {
- deduplicated.push(current);
- }
- }
-
- return deduplicated;
- }, [initialMessages, messages, completedToolIds]);
-
- async function sendMessage(
- content: string,
- isUserMessage: boolean = true,
- context?: { url: string; content: string },
- ) {
- if (!sessionId) return;
-
- setIsRegionBlockedModalOpen(false);
- if (isUserMessage) {
- const userMessage = createUserMessage(content);
- setMessages((prev) => [...filterAuthMessages(prev), userMessage]);
- } else {
- setMessages((prev) => filterAuthMessages(prev));
- }
- setStreamingChunks([]);
- streamingChunksRef.current = [];
- setHasTextChunks(false);
- setIsStreamingInitiated(true);
- hasResponseRef.current = false;
- textFinalizedRef.current = false;
- streamEndedRef.current = false;
-
- try {
- await sendStreamMessage(
- sessionId,
- content,
- createDispatcher(),
- isUserMessage,
- context,
- );
- } catch (err) {
- setIsStreamingInitiated(false);
- if (err instanceof Error && err.name === "AbortError") return;
-
- const errorMessage =
- err instanceof Error ? err.message : "Failed to send message";
- toast.error("Failed to send message", {
- description: errorMessage,
- });
- }
- }
-
- function handleStopStreaming() {
- stopStreaming();
- setStreamingChunks([]);
- streamingChunksRef.current = [];
- setHasTextChunks(false);
- setIsStreamingInitiated(false);
- }
-
- const { capturePageContext } = usePageContext();
- const sendMessageRef = useRef(sendMessage);
- sendMessageRef.current = sendMessage;
-
- useEffect(
- function handleInitialPrompt() {
- if (!initialPrompt || !sessionId) return;
- if (initialMessages.length > 0) return;
- if (hasSentInitialPrompt(sessionId)) return;
-
- markInitialPromptSent(sessionId);
- const context = capturePageContext();
- sendMessageRef.current(initialPrompt, true, context);
- },
- [initialPrompt, sessionId, initialMessages.length, capturePageContext],
- );
-
- async function sendMessageWithContext(
- content: string,
- isUserMessage: boolean = true,
- ) {
- const context = capturePageContext();
- await sendMessage(content, isUserMessage, context);
- }
-
- function handleRegionModalOpenChange(open: boolean) {
- setIsRegionBlockedModalOpen(open);
- }
-
- function handleRegionModalClose() {
- setIsRegionBlockedModalOpen(false);
- }
-
- return {
- messages: allMessages,
- streamingChunks,
- isStreaming,
- error,
- isRegionBlockedModalOpen,
- setIsRegionBlockedModalOpen,
- sendMessageWithContext,
- handleRegionModalOpenChange,
- handleRegionModalClose,
- sendMessage,
- stopStreaming: handleStopStreaming,
- };
-}
diff --git a/autogpt_platform/frontend/src/components/contextual/Chat/components/ChatCredentialsSetup/ChatCredentialsSetup.tsx b/autogpt_platform/frontend/src/components/contextual/Chat/components/ChatCredentialsSetup/ChatCredentialsSetup.tsx
deleted file mode 100644
index f0dfadd1f7..0000000000
--- a/autogpt_platform/frontend/src/components/contextual/Chat/components/ChatCredentialsSetup/ChatCredentialsSetup.tsx
+++ /dev/null
@@ -1,151 +0,0 @@
-import { Text } from "@/components/atoms/Text/Text";
-import { CredentialsInput } from "@/components/contextual/CredentialsInput/CredentialsInput";
-import type { BlockIOCredentialsSubSchema } from "@/lib/autogpt-server-api";
-import { cn } from "@/lib/utils";
-import { CheckIcon, RobotIcon, WarningIcon } from "@phosphor-icons/react";
-import { useEffect, useRef } from "react";
-import { useChatCredentialsSetup } from "./useChatCredentialsSetup";
-
-export interface CredentialInfo {
- provider: string;
- providerName: string;
- credentialTypes: Array<
- "api_key" | "oauth2" | "user_password" | "host_scoped"
- >;
- title: string;
- scopes?: string[];
-}
-
-interface Props {
- credentials: CredentialInfo[];
- agentName?: string;
- message: string;
- onAllCredentialsComplete: () => void;
- onCancel: () => void;
- className?: string;
-}
-
-function createSchemaFromCredentialInfo(
- credential: CredentialInfo,
-): BlockIOCredentialsSubSchema {
- return {
- type: "object",
- properties: {},
- credentials_provider: [credential.provider],
- credentials_types: credential.credentialTypes,
- credentials_scopes: credential.scopes,
- discriminator: undefined,
- discriminator_mapping: undefined,
- discriminator_values: undefined,
- };
-}
-
-export function ChatCredentialsSetup({
- credentials,
- agentName: _agentName,
- message,
- onAllCredentialsComplete,
- onCancel: _onCancel,
-}: Props) {
- const { selectedCredentials, isAllComplete, handleCredentialSelect } =
- useChatCredentialsSetup(credentials);
-
- // Track if we've already called completion to prevent double calls
- const hasCalledCompleteRef = useRef(false);
-
- // Reset the completion flag when credentials change (new credential setup flow)
- useEffect(
- function resetCompletionFlag() {
- hasCalledCompleteRef.current = false;
- },
- [credentials],
- );
-
- // Auto-call completion when all credentials are configured
- useEffect(
- function autoCompleteWhenReady() {
- if (isAllComplete && !hasCalledCompleteRef.current) {
- hasCalledCompleteRef.current = true;
- onAllCredentialsComplete();
- }
- },
- [isAllComplete, onAllCredentialsComplete],
- );
-
- return (
- <div className="group relative flex w-full justify-start gap-3 px-4 py-3">
- <div className="flex w-full max-w-3xl gap-3">
- <div className="flex-shrink-0">
- <div className="flex h-7 w-7 items-center justify-center rounded-lg bg-indigo-500">
- <RobotIcon className="h-4 w-4 text-indigo-50" />
- </div>
- </div>
-
- <div className="flex min-w-0 flex-1 flex-col">
- <div className="group relative min-w-20 overflow-hidden rounded-xl border border-slate-100 bg-slate-50/20 px-6 py-2.5 text-sm leading-relaxed backdrop-blur-xl">
- <div className="absolute inset-0 bg-gradient-to-br from-slate-200/20 via-slate-300/10 to-transparent" />
- <div className="relative z-10 space-y-3 text-slate-900">
- <div>
- <Text variant="h4" className="mb-1 text-slate-900">
- Credentials Required
- </Text>
- <Text variant="small" className="text-slate-600">
- {message}
- </Text>
- </div>
-
- <div className="space-y-3">
- {credentials.map((cred, index) => {
- const schema = createSchemaFromCredentialInfo(cred);
- const isSelected = !!selectedCredentials[cred.provider];
-
- return (
- <div
- key={`${cred.provider}-${index}`}
- className={cn(
- "relative rounded-lg border p-3",
- isSelected
- ? "border-green-500 bg-green-50/50"
- : "border-slate-200 bg-white/50",
- )}
- >
- <div className="mb-2 flex items-center gap-2">
- {isSelected ? (
- <CheckIcon
- size={16}
- className="text-green-500"
- weight="bold"
- />
- ) : (
- <WarningIcon
- size={16}
- className="text-slate-500"
- weight="bold"
- />
- )}
- <Text
- variant="small"
- className="font-semibold text-slate-900"
- >
- {cred.providerName}
- </Text>
- </div>
-
- <CredentialsInput
- schema={schema}
- selectedCredentials={selectedCredentials[cred.provider]}
- onSelectCredentials={(credMeta) =>
- handleCredentialSelect(cred.provider, credMeta)
- }
- />
- </div>
- );
- })}
- </div>
- </div>
- </div>
- </div>
- </div>
- </div>
- );
-}
diff --git a/autogpt_platform/frontend/src/components/contextual/Chat/components/ChatCredentialsSetup/useChatCredentialsSetup.ts b/autogpt_platform/frontend/src/components/contextual/Chat/components/ChatCredentialsSetup/useChatCredentialsSetup.ts
deleted file mode 100644
index 6b4b26e834..0000000000
--- a/autogpt_platform/frontend/src/components/contextual/Chat/components/ChatCredentialsSetup/useChatCredentialsSetup.ts
+++ /dev/null
@@ -1,36 +0,0 @@
-import { useState, useMemo } from "react";
-import type { CredentialInfo } from "./ChatCredentialsSetup";
-import type { CredentialsMetaInput } from "@/lib/autogpt-server-api";
-
-export function useChatCredentialsSetup(credentials: CredentialInfo[]) {
- const [selectedCredentials, setSelectedCredentials] = useState<
- Record<string, CredentialsMetaInput>
- >({});
-
- // Check if all credentials are configured
- const isAllComplete = useMemo(
- function checkAllComplete() {
- if (credentials.length === 0) return false;
- return credentials.every((cred) => selectedCredentials[cred.provider]);
- },
- [credentials, selectedCredentials],
- );
-
- function handleCredentialSelect(
- provider: string,
- credential?: CredentialsMetaInput,
- ) {
- if (credential) {
- setSelectedCredentials((prev) => ({
- ...prev,
- [provider]: credential,
- }));
- }
- }
-
- return {
- selectedCredentials,
- isAllComplete,
- handleCredentialSelect,
- };
-}
diff --git a/autogpt_platform/frontend/src/components/contextual/Chat/components/ChatErrorState/ChatErrorState.tsx b/autogpt_platform/frontend/src/components/contextual/Chat/components/ChatErrorState/ChatErrorState.tsx
deleted file mode 100644
index bac13d1b0c..0000000000
--- a/autogpt_platform/frontend/src/components/contextual/Chat/components/ChatErrorState/ChatErrorState.tsx
+++ /dev/null
@@ -1,30 +0,0 @@
-import React from "react";
-import { ErrorCard } from "@/components/molecules/ErrorCard/ErrorCard";
-import { cn } from "@/lib/utils";
-
-export interface ChatErrorStateProps {
- error: Error;
- onRetry?: () => void;
- className?: string;
-}
-
-export function ChatErrorState({
- error,
- onRetry,
- className,
-}: ChatErrorStateProps) {
- return (
- <div
- className={cn("flex flex-1 items-center justify-center p-6", className)}
- >
- <ErrorCard
- responseError={{
- message: error.message,
- }}
- context="chat session"
- onRetry={onRetry}
- className="max-w-md"
- />
- </div>
- );
-}
diff --git a/autogpt_platform/frontend/src/components/contextual/Chat/components/ChatLoader/ChatLoader.tsx b/autogpt_platform/frontend/src/components/contextual/Chat/components/ChatLoader/ChatLoader.tsx
deleted file mode 100644
index 76cee8dbae..0000000000
--- a/autogpt_platform/frontend/src/components/contextual/Chat/components/ChatLoader/ChatLoader.tsx
+++ /dev/null
@@ -1,7 +0,0 @@
-export function ChatLoader() {
- return (
- <div className="flex items-center gap-2">
- <div className="h-5 w-5 animate-loader rounded-full bg-black" />
- </div>
- );
-}
diff --git a/autogpt_platform/frontend/src/components/contextual/Chat/components/ChatLoadingState/ChatLoadingState.tsx b/autogpt_platform/frontend/src/components/contextual/Chat/components/ChatLoadingState/ChatLoadingState.tsx
deleted file mode 100644
index c0cdb33c50..0000000000
--- a/autogpt_platform/frontend/src/components/contextual/Chat/components/ChatLoadingState/ChatLoadingState.tsx
+++ /dev/null
@@ -1,19 +0,0 @@
-import { LoadingSpinner } from "@/components/atoms/LoadingSpinner/LoadingSpinner";
-import { cn } from "@/lib/utils";
-
-export interface ChatLoadingStateProps {
- message?: string;
- className?: string;
-}
-
-export function ChatLoadingState({ className }: ChatLoadingStateProps) {
- return (
- <div
- className={cn("flex flex-1 items-center justify-center p-6", className)}
- >
- <div className="flex flex-col items-center gap-4 text-center">
- <LoadingSpinner />
- </div>
- </div>
- );
-}
diff --git a/autogpt_platform/frontend/src/components/contextual/Chat/components/ChatMessage/ChatMessage.tsx b/autogpt_platform/frontend/src/components/contextual/Chat/components/ChatMessage/ChatMessage.tsx
deleted file mode 100644
index 44dae40eb4..0000000000
--- a/autogpt_platform/frontend/src/components/contextual/Chat/components/ChatMessage/ChatMessage.tsx
+++ /dev/null
@@ -1,448 +0,0 @@
-"use client";
-
-import { Button } from "@/components/atoms/Button/Button";
-import { useSupabase } from "@/lib/supabase/hooks/useSupabase";
-import { cn } from "@/lib/utils";
-import {
- ArrowsClockwiseIcon,
- CheckCircleIcon,
- CheckIcon,
-} from "@phosphor-icons/react";
-import { useRouter } from "next/navigation";
-import { useCallback, useState } from "react";
-import { AgentCarouselMessage } from "../AgentCarouselMessage/AgentCarouselMessage";
-import { AIChatBubble } from "../AIChatBubble/AIChatBubble";
-import { AuthPromptWidget } from "../AuthPromptWidget/AuthPromptWidget";
-import { ChatCredentialsSetup } from "../ChatCredentialsSetup/ChatCredentialsSetup";
-import { ClarificationQuestionsWidget } from "../ClarificationQuestionsWidget/ClarificationQuestionsWidget";
-import { ExecutionStartedMessage } from "../ExecutionStartedMessage/ExecutionStartedMessage";
-import { PendingOperationWidget } from "../PendingOperationWidget/PendingOperationWidget";
-import { MarkdownContent } from "../MarkdownContent/MarkdownContent";
-import { NoResultsMessage } from "../NoResultsMessage/NoResultsMessage";
-import { ToolCallMessage } from "../ToolCallMessage/ToolCallMessage";
-import { ToolResponseMessage } from "../ToolResponseMessage/ToolResponseMessage";
-import { UserChatBubble } from "../UserChatBubble/UserChatBubble";
-import { useChatMessage, type ChatMessageData } from "./useChatMessage";
-
-function stripInternalReasoning(content: string): string {
- const cleaned = content.replace(
- /<internal_reasoning>[\s\S]*?<\/internal_reasoning>/gi,
- "",
- );
- return cleaned.replace(/\n{3,}/g, "\n\n").trim();
-}
-
-function getDisplayContent(message: ChatMessageData, isUser: boolean): string {
- if (message.type !== "message") return "";
- if (isUser) return message.content;
- return stripInternalReasoning(message.content);
-}
-
-export interface ChatMessageProps {
- message: ChatMessageData;
- messages?: ChatMessageData[];
- index?: number;
- isStreaming?: boolean;
- className?: string;
- onDismissLogin?: () => void;
- onDismissCredentials?: () => void;
- onSendMessage?: (content: string, isUserMessage?: boolean) => void;
- agentOutput?: ChatMessageData;
- isFinalMessage?: boolean;
-}
-
-export function ChatMessage({
- message,
- messages = [],
- index = -1,
- isStreaming = false,
- className,
- onDismissCredentials,
- onSendMessage,
- agentOutput,
- isFinalMessage = true,
-}: ChatMessageProps) {
- const { user } = useSupabase();
- const router = useRouter();
- const [copied, setCopied] = useState(false);
- const {
- isUser,
- isToolCall,
- isToolResponse,
- isLoginNeeded,
- isCredentialsNeeded,
- isClarificationNeeded,
- isOperationStarted,
- isOperationPending,
- isOperationInProgress,
- } = useChatMessage(message);
- const displayContent = getDisplayContent(message, isUser);
-
- const handleAllCredentialsComplete = useCallback(
- function handleAllCredentialsComplete() {
- // Send a user message that explicitly asks to retry the setup
- // This ensures the LLM calls get_required_setup_info again and proceeds with execution
- if (onSendMessage) {
- onSendMessage(
- "I've configured the required credentials. Please check if everything is ready and proceed with setting up the agent.",
- );
- }
- // Optionally dismiss the credentials prompt
- if (onDismissCredentials) {
- onDismissCredentials();
- }
- },
- [onSendMessage, onDismissCredentials],
- );
-
- function handleCancelCredentials() {
- // Dismiss the credentials prompt
- if (onDismissCredentials) {
- onDismissCredentials();
- }
- }
-
- const handleCopy = useCallback(
- async function handleCopy() {
- if (message.type !== "message") return;
- if (!displayContent) return;
-
- try {
- await navigator.clipboard.writeText(displayContent);
- setCopied(true);
- setTimeout(() => setCopied(false), 2000);
- } catch (error) {
- console.error("Failed to copy:", error);
- }
- },
- [displayContent, message],
- );
-
- const handleTryAgain = useCallback(() => {
- if (message.type !== "message" || !onSendMessage) return;
- onSendMessage(message.content, message.role === "user");
- }, [message, onSendMessage]);
-
- const handleViewExecution = useCallback(() => {
- if (message.type === "execution_started" && message.libraryAgentLink) {
- router.push(message.libraryAgentLink);
- }
- }, [message, router]);
-
- // Render credentials needed messages
- if (isCredentialsNeeded && message.type === "credentials_needed") {
- return (
- <ChatCredentialsSetup
- credentials={message.credentials}
- agentName={message.agentName}
- message={message.message}
- onAllCredentialsComplete={handleAllCredentialsComplete}
- onCancel={handleCancelCredentials}
- className={className}
- />
- );
- }
-
- if (isClarificationNeeded && message.type === "clarification_needed") {
- const hasUserReplyAfter =
- index >= 0 &&
- messages
- .slice(index + 1)
- .some((m) => m.type === "message" && m.role === "user");
-
- const handleClarificationAnswers = (answers: Record<string, string>) => {
- if (onSendMessage) {
- // Iterate over questions (preserves original order) instead of answers
- const contextMessage = message.questions
- .map((q) => {
- const answer = answers[q.keyword] || "";
- return `> ${q.question}\n\n${answer}`;
- })
- .join("\n\n");
-
- onSendMessage(
- `**Here are my answers:**\n\n${contextMessage}\n\nPlease proceed with creating the agent.`,
- );
- }
- };
-
- return (
- <ClarificationQuestionsWidget
- questions={message.questions}
- message={message.message}
- sessionId={message.sessionId}
- onSubmitAnswers={handleClarificationAnswers}
- isAnswered={hasUserReplyAfter}
- className={className}
- />
- );
- }
-
- // Render login needed messages
- if (isLoginNeeded && message.type === "login_needed") {
- // If user is already logged in, show success message instead of auth prompt
- if (user) {
- return (
- <div className={cn("px-4 py-2", className)}>
- <div className="my-4 overflow-hidden rounded-lg border border-green-200 bg-gradient-to-br from-green-50 to-emerald-50">
- <div className="px-6 py-4">
- <div className="flex items-center gap-3">
- <div className="flex h-10 w-10 items-center justify-center rounded-full bg-green-600">
- <CheckCircleIcon
- size={20}
- weight="fill"
- className="text-white"
- />
- </div>
- <div>
- <h3 className="text-lg font-semibold text-neutral-900">
- Successfully Authenticated
- </h3>
- <p className="text-sm text-neutral-600">
- You&apos;re now signed in and ready to continue
- </p>
- </div>
- </div>
- </div>
- </div>
- </div>
- );
- }
-
- // Show auth prompt if not logged in
- return (
- <div className={cn("px-4 py-2", className)}>
- <AuthPromptWidget
- message={message.message}
- sessionId={message.sessionId}
- agentInfo={message.agentInfo}
- />
- </div>
- );
- }
-
- // Render tool call messages
- if (isToolCall && message.type === "tool_call") {
- // Check if this tool call is currently streaming
- // A tool call is streaming if:
- // 1. isStreaming is true
- // 2. This is the last tool_call message
- // 3. There's no tool_response for this tool call yet
- const isToolCallStreaming =
- isStreaming &&
- index >= 0 &&
- (() => {
- // Find the last tool_call index
- let lastToolCallIndex = -1;
- for (let i = messages.length - 1; i >= 0; i--) {
- if (messages[i].type === "tool_call") {
- lastToolCallIndex = i;
- break;
- }
- }
- // Check if this is the last tool_call and there's no response yet
- if (index === lastToolCallIndex) {
- // Check if there's a tool_response for this tool call
- const hasResponse = messages
- .slice(index + 1)
- .some(
- (msg) =>
- msg.type === "tool_response" && msg.toolId === message.toolId,
- );
- return !hasResponse;
- }
- return false;
- })();
-
- return (
- <div className={cn("px-4 py-2", className)}>
- <ToolCallMessage
- toolId={message.toolId}
- toolName={message.toolName}
- arguments={message.arguments}
- isStreaming={isToolCallStreaming}
- />
- </div>
- );
- }
-
- // Render no_results messages - use dedicated component, not ToolResponseMessage
- if (message.type === "no_results") {
- return (
- <div className={cn("px-4 py-2", className)}>
- <NoResultsMessage
- message={message.message}
- suggestions={message.suggestions}
- />
- </div>
- );
- }
-
- // Render agent_carousel messages - use dedicated component, not ToolResponseMessage
- if (message.type === "agent_carousel") {
- return (
- <div className={cn("px-4 py-2", className)}>
- <AgentCarouselMessage
- agents={message.agents}
- totalCount={message.totalCount}
- />
- </div>
- );
- }
-
- // Render execution_started messages - use dedicated component, not ToolResponseMessage
- if (message.type === "execution_started") {
- return (
- <div className={cn("px-4 py-2", className)}>
- <ExecutionStartedMessage
- executionId={message.executionId}
- agentName={message.agentName}
- message={message.message}
- onViewExecution={
- message.libraryAgentLink ? handleViewExecution : undefined
- }
- />
- </div>
- );
- }
-
- // Render operation_started messages (long-running background operations)
- if (isOperationStarted && message.type === "operation_started") {
- return (
- <PendingOperationWidget
- status="started"
- message={message.message}
- toolName={message.toolName}
- className={className}
- />
- );
- }
-
- // Render operation_pending messages (operations in progress when refreshing)
- if (isOperationPending && message.type === "operation_pending") {
- return (
- <PendingOperationWidget
- status="pending"
- message={message.message}
- toolName={message.toolName}
- className={className}
- />
- );
- }
-
- // Render operation_in_progress messages (duplicate request while operation running)
- if (isOperationInProgress && message.type === "operation_in_progress") {
- return (
- <PendingOperationWidget
- status="in_progress"
- message={message.message}
- toolName={message.toolName}
- className={className}
- />
- );
- }
-
- // Render tool response messages (but skip agent_output if it's being rendered inside assistant message)
- if (isToolResponse && message.type === "tool_response") {
- return (
- <div className={cn("px-4 py-2", className)}>
- <ToolResponseMessage
- toolId={message.toolId}
- toolName={message.toolName}
- result={message.result}
- onSendMessage={onSendMessage}
- />
- </div>
- );
- }
-
- // Render regular chat messages
- if (message.type === "message") {
- return (
- <div
- className={cn(
- "group relative flex w-full gap-3 px-4 py-3",
- isUser ? "justify-end" : "justify-start",
- className,
- )}
- >
- <div className="flex w-full max-w-3xl gap-3">
- <div
- className={cn(
- "flex min-w-0 flex-1 flex-col",
- isUser && "items-end",
- )}
- >
- {isUser ? (
- <UserChatBubble>
- <MarkdownContent content={displayContent} />
- </UserChatBubble>
- ) : (
- <AIChatBubble>
- <MarkdownContent content={displayContent} />
- {agentOutput && agentOutput.type === "tool_response" && (
- <div className="mt-4">
- <ToolResponseMessage
- toolId={agentOutput.toolId}
- toolName={agentOutput.toolName || "Agent Output"}
- result={agentOutput.result}
- />
- </div>
- )}
- </AIChatBubble>
- )}
- <div
- className={cn(
- "flex gap-0",
- isUser ? "justify-end" : "justify-start",
- )}
- >
- {isUser && onSendMessage && (
- <Button
- variant="ghost"
- size="icon"
- onClick={handleTryAgain}
- aria-label="Try again"
- >
- <ArrowsClockwiseIcon className="size-4 text-zinc-600" />
- </Button>
- )}
- {!isUser && isFinalMessage && !isStreaming && (
- <Button
- variant="ghost"
- size="icon"
- onClick={handleCopy}
- aria-label="Copy message"
- className="p-1"
- >
- {copied ? (
- <CheckIcon className="size-4 text-green-600" />
- ) : (
- <svg
- xmlns="http://www.w3.org/2000/svg"
- width="24"
- height="24"
- viewBox="0 0 24 24"
- fill="none"
- stroke="currentColor"
- strokeWidth="2"
- strokeLinecap="round"
- strokeLinejoin="round"
- className="size-3 text-zinc-600"
- >
- <rect width="14" height="14" x="8" y="8" rx="2" ry="2" />
- <path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2" />
- </svg>
- )}
- </Button>
- )}
- </div>
- </div>
- </div>
- </div>
- );
- }
-
- // Fallback for unknown message types
- return null;
-}
diff --git a/autogpt_platform/frontend/src/components/contextual/Chat/components/ChatMessage/useChatMessage.ts b/autogpt_platform/frontend/src/components/contextual/Chat/components/ChatMessage/useChatMessage.ts
deleted file mode 100644
index 6809497a93..0000000000
--- a/autogpt_platform/frontend/src/components/contextual/Chat/components/ChatMessage/useChatMessage.ts
+++ /dev/null
@@ -1,157 +0,0 @@
-import type { ToolArguments, ToolResult } from "@/types/chat";
-import { formatDistanceToNow } from "date-fns";
-
-export type ChatMessageData =
- | {
- type: "message";
- role: "user" | "assistant" | "system";
- content: string;
- timestamp?: string | Date;
- }
- | {
- type: "tool_call";
- toolId: string;
- toolName: string;
- arguments?: ToolArguments;
- timestamp?: string | Date;
- }
- | {
- type: "tool_response";
- toolId: string;
- toolName: string;
- result: ToolResult;
- success?: boolean;
- timestamp?: string | Date;
- }
- | {
- type: "login_needed";
- toolName: string;
- message: string;
- sessionId: string;
- agentInfo?: {
- graph_id: string;
- name: string;
- trigger_type: string;
- };
- timestamp?: string | Date;
- }
- | {
- type: "credentials_needed";
- toolName: string;
- credentials: Array<{
- provider: string;
- providerName: string;
- credentialTypes: Array<
- "api_key" | "oauth2" | "user_password" | "host_scoped"
- >;
- title: string;
- scopes?: string[];
- }>;
- message: string;
- agentName?: string;
- timestamp?: string | Date;
- }
- | {
- type: "no_results";
- toolName: string;
- message: string;
- suggestions?: string[];
- sessionId?: string;
- timestamp?: string | Date;
- }
- | {
- type: "agent_carousel";
- toolId: string;
- toolName: string;
- agents: Array<{
- id: string;
- name: string;
- description: string;
- version?: number;
- image_url?: string;
- }>;
- totalCount?: number;
- timestamp?: string | Date;
- }
- | {
- type: "execution_started";
- toolId: string;
- toolName: string;
- executionId: string;
- agentName?: string;
- message?: string;
- libraryAgentLink?: string;
- timestamp?: string | Date;
- }
- | {
- type: "inputs_needed";
- toolName: string;
- agentName?: string;
- agentId?: string;
- graphVersion?: number;
- inputSchema: Record<string, any>;
- credentialsSchema?: Record<string, any>;
- message: string;
- timestamp?: string | Date;
- }
- | {
- type: "clarification_needed";
- toolName: string;
- questions: Array<{
- question: string;
- keyword: string;
- example?: string;
- }>;
- message: string;
- sessionId: string;
- timestamp?: string | Date;
- }
- | {
- type: "operation_started";
- toolName: string;
- toolId: string;
- operationId: string;
- taskId?: string; // For SSE reconnection
- message: string;
- timestamp?: string | Date;
- }
- | {
- type: "operation_pending";
- toolName: string;
- toolId: string;
- operationId: string;
- message: string;
- timestamp?: string | Date;
- }
- | {
- type: "operation_in_progress";
- toolName: string;
- toolCallId: string;
- message: string;
- timestamp?: string | Date;
- };
-
-export function useChatMessage(message: ChatMessageData) {
- const formattedTimestamp = message.timestamp
- ? formatDistanceToNow(new Date(message.timestamp), { addSuffix: true })
- : "Just now";
-
- return {
- formattedTimestamp,
- isUser: message.type === "message" && message.role === "user",
- isAssistant: message.type === "message" && message.role === "assistant",
- isSystem: message.type === "message" && message.role === "system",
- isToolCall: message.type === "tool_call",
- isToolResponse: message.type === "tool_response",
- isLoginNeeded: message.type === "login_needed",
- isCredentialsNeeded: message.type === "credentials_needed",
- isNoResults: message.type === "no_results",
- isAgentCarousel: message.type === "agent_carousel",
- isExecutionStarted: message.type === "execution_started",
- isInputsNeeded: message.type === "inputs_needed",
- isClarificationNeeded: message.type === "clarification_needed",
- isOperationStarted: message.type === "operation_started",
- isOperationPending: message.type === "operation_pending",
- isOperationInProgress: message.type === "operation_in_progress",
- };
-}
diff --git a/autogpt_platform/frontend/src/components/contextual/Chat/components/ExecutionStartedMessage/ExecutionStartedMessage.tsx b/autogpt_platform/frontend/src/components/contextual/Chat/components/ExecutionStartedMessage/ExecutionStartedMessage.tsx
deleted file mode 100644
index 1ac3b440e0..0000000000
--- a/autogpt_platform/frontend/src/components/contextual/Chat/components/ExecutionStartedMessage/ExecutionStartedMessage.tsx
+++ /dev/null
@@ -1,90 +0,0 @@
-import { Button } from "@/components/atoms/Button/Button";
-import { Text } from "@/components/atoms/Text/Text";
-import { cn } from "@/lib/utils";
-import { ArrowSquareOut, CheckCircle, Play } from "@phosphor-icons/react";
-
-export interface ExecutionStartedMessageProps {
- executionId: string;
- agentName?: string;
- message?: string;
- onViewExecution?: () => void;
- className?: string;
-}
-
-export function ExecutionStartedMessage({
- executionId,
- agentName,
- message = "Agent execution started successfully",
- onViewExecution,
- className,
-}: ExecutionStartedMessageProps) {
- return (
- <div
- className={cn(
- "mx-4 my-2 flex flex-col gap-4 rounded-lg border border-green-200 bg-green-50 p-6",
- className,
- )}
- >
- {/* Icon & Header */}
- <div className="flex items-start gap-4">
- <div className="flex h-12 w-12 flex-shrink-0 items-center justify-center rounded-full bg-green-500">
- <CheckCircle size={24} weight="bold" className="text-white" />
- </div>
- <div className="flex-1">
- <Text variant="h3" className="mb-1 text-green-900">
- Execution Started
- </Text>
- <Text variant="body" className="text-green-700">
- {message}
- </Text>
- </div>
- </div>
-
- {/* Details */}
- <div className="rounded-md bg-green-100 p-4">
- <div className="space-y-2">
- {agentName && (
- <div className="flex items-center justify-between">
- <Text variant="small" className="font-semibold text-green-900">
- Agent:
- </Text>
- <Text variant="body" className="text-green-800">
- {agentName}
- </Text>
- </div>
- )}
- <div className="flex items-center justify-between">
- <Text variant="small" className="font-semibold text-green-900">
- Execution ID:
- </Text>
- <Text variant="small" className="font-mono text-green-800">
- {executionId.slice(0, 16)}...
- </Text>
- </div>
- </div>
- </div>
-
- {/* Action Buttons */}
- {onViewExecution && (
- <div className="flex gap-3">
- <Button
- onClick={onViewExecution}
- variant="primary"
- className="flex flex-1 items-center justify-center gap-2"
- >
- <ArrowSquareOut size={20} weight="bold" />
- View Execution
- </Button>
- </div>
- )}
-
- <div className="flex items-center gap-2 text-green-600">
- <Play size={16} weight="fill" />
- <Text variant="small">
- Your agent is now running. You can monitor its progress in the monitor
- page.
- </Text>
- </div>
- </div>
- );
-}
diff --git a/autogpt_platform/frontend/src/components/contextual/Chat/components/MarkdownContent/MarkdownContent.tsx b/autogpt_platform/frontend/src/components/contextual/Chat/components/MarkdownContent/MarkdownContent.tsx
deleted file mode 100644
index ecadbe938b..0000000000
--- a/autogpt_platform/frontend/src/components/contextual/Chat/components/MarkdownContent/MarkdownContent.tsx
+++ /dev/null
@@ -1,349 +0,0 @@
-"use client";
-
-import { getGetWorkspaceDownloadFileByIdUrl } from "@/app/api/__generated__/endpoints/workspace/workspace";
-import { cn } from "@/lib/utils";
-import { EyeSlash } from "@phosphor-icons/react";
-import React, { useState } from "react";
-import ReactMarkdown from "react-markdown";
-import remarkGfm from "remark-gfm";
-
-interface MarkdownContentProps {
- content: string;
- className?: string;
-}
-
-interface CodeProps extends React.HTMLAttributes<HTMLElement> {
- children?: React.ReactNode;
- className?: string;
-}
-
-interface ListProps extends React.HTMLAttributes<HTMLUListElement> {
- children?: React.ReactNode;
- className?: string;
-}
-
-interface ListItemProps extends React.HTMLAttributes<HTMLLIElement> {
- children?: React.ReactNode;
- className?: string;
-}
-
-interface InputProps extends React.InputHTMLAttributes<HTMLInputElement> {
- type?: string;
-}
-
-/**
- * Converts a workspace:// URL to a proxy URL that routes through Next.js to the backend.
- * workspace://abc123 -> /api/proxy/api/workspace/files/abc123/download
- *
- * Uses the generated API URL helper and routes through the Next.js proxy
- * which handles authentication and proper backend routing.
- */
-/**
- * URL transformer for ReactMarkdown.
- * Converts workspace:// URLs to proxy URLs that route through Next.js to the backend.
- * workspace://abc123 -> /api/proxy/api/workspace/files/abc123/download
- *
- * This is needed because ReactMarkdown sanitizes URLs and only allows
- * http, https, mailto, and tel protocols by default.
- */
-function resolveWorkspaceUrl(src: string): string {
- if (src.startsWith("workspace://")) {
- // Strip MIME type fragment if present (e.g., workspace://abc123#video/mp4 → abc123)
- const withoutPrefix = src.replace("workspace://", "");
- const fileId = withoutPrefix.split("#")[0];
- // Use the generated API URL helper to get the correct path
- const apiPath = getGetWorkspaceDownloadFileByIdUrl(fileId);
- // Route through the Next.js proxy (same pattern as customMutator for client-side)
- return `/api/proxy${apiPath}`;
- }
- return src;
-}
-
-/**
- * Check if the image URL is a workspace file (AI cannot see these yet).
- * After URL transformation, workspace files have URLs like /api/proxy/api/workspace/files/...
- */
-function isWorkspaceImage(src: string | undefined): boolean {
- return src?.includes("/workspace/files/") ?? false;
-}
-
-/**
- * Renders a workspace video with controls and an optional "AI cannot see" badge.
- */
-function WorkspaceVideo({
- src,
- aiCannotSee,
-}: {
- src: string;
- aiCannotSee: boolean;
-}) {
- return (
- <span className="relative my-2 inline-block">
- <video
- controls
- className="h-auto max-w-full rounded-md border border-zinc-200"
- preload="metadata"
- >
- <source src={src} />
- Your browser does not support the video tag.
- </video>
- {aiCannotSee && (
- <span
- className="absolute bottom-2 right-2 flex items-center gap-1 rounded bg-black/70 px-2 py-1 text-xs text-white"
- title="The AI cannot see this video"
- >
- <EyeSlash size={14} />
- <span>AI cannot see this video</span>
- </span>
- )}
- </span>
- );
-}
-
-/**
- * Custom image component that shows an indicator when the AI cannot see the image.
- * Also handles the "video:" alt-text prefix convention to render <video> elements.
- * For workspace files with unknown types, falls back to <video> if <img> fails.
- * Note: src is already transformed by urlTransform, so workspace:// is now /api/workspace/...
- */
-function MarkdownImage(props: Record<string, unknown>) {
- const src = props.src as string | undefined;
- const alt = props.alt as string | undefined;
- const [imgFailed, setImgFailed] = useState(false);
-
- const aiCannotSee = isWorkspaceImage(src);
-
- // If no src, show a placeholder
- if (!src) {
- return (
- <span className="my-2 inline-block rounded border border-amber-200 bg-amber-50 px-2 py-1 text-sm text-amber-700">
- [Image: {alt || "missing src"}]
- </span>
- );
- }
-
- // Detect video: prefix in alt text (set by formatOutputValue in helpers.ts)
- if (alt?.startsWith("video:")) {
- return <WorkspaceVideo src={src} aiCannotSee={aiCannotSee} />;
- }
-
- // If the <img> failed to load and this is a workspace file, try as video.
- // This handles generic output keys like "file_out" where the MIME type
- // isn't known from the key name alone.
- if (imgFailed && aiCannotSee) {
- return <WorkspaceVideo src={src} aiCannotSee={aiCannotSee} />;
- }
-
- return (
- <span className="relative my-2 inline-block">
- {/* eslint-disable-next-line @next/next/no-img-element */}
- <img
- src={src}
- alt={alt || "Image"}
- className="h-auto max-w-full rounded-md border border-zinc-200"
- loading="lazy"
- onError={() => {
- if (aiCannotSee) setImgFailed(true);
- }}
- />
- {aiCannotSee && (
- <span
- className="absolute bottom-2 right-2 flex items-center gap-1 rounded bg-black/70 px-2 py-1 text-xs text-white"
- title="The AI cannot see this image"
- >
- <EyeSlash size={14} />
- <span>AI cannot see this image</span>
- </span>
- )}
- </span>
- );
-}
-
-export function MarkdownContent({ content, className }: MarkdownContentProps) {
- return (
- <div className={cn("markdown-content", className)}>
- <ReactMarkdown
- skipHtml={true}
- remarkPlugins={[remarkGfm]}
- urlTransform={resolveWorkspaceUrl}
- components={{
- code: ({ children, className, ...props }: CodeProps) => {
- const isInline = !className?.includes("language-");
- if (isInline) {
- return (
- <code
- className="rounded bg-zinc-100 px-1.5 py-0.5 font-mono text-sm text-zinc-800"
- {...props}
- >
- {children}
- </code>
- );
- }
- return (
- <code className="font-mono text-sm text-zinc-100" {...props}>
- {children}
- </code>
- );
- },
- pre: ({ children, ...props }) => (
- <pre
- className="my-2 overflow-x-auto rounded-md bg-zinc-900 p-3"
- {...props}
- >
- {children}
- </pre>
- ),
- a: ({ children, href, ...props }) => (
- <a
- href={href}
- target="_blank"
- rel="noopener noreferrer"
- className="text-purple-600 underline decoration-1 underline-offset-2 hover:text-purple-700"
- {...props}
- >
- {children}
- </a>
- ),
- strong: ({ children, ...props }) => (
- <strong className="font-semibold" {...props}>
- {children}
- </strong>
- ),
- em: ({ children, ...props }) => (
- <em className="italic" {...props}>
- {children}
- </em>
- ),
- del: ({ children, ...props }) => (
- <del className="line-through opacity-70" {...props}>
- {children}
- </del>
- ),
- ul: ({ children, ...props }: ListProps) => (
- <ul
- className={cn(
- "my-2 space-y-1 pl-6",
- props.className?.includes("contains-task-list")
- ? "list-none pl-0"
- : "list-disc",
- )}
- {...props}
- >
- {children}
- </ul>
- ),
- ol: ({ children, ...props }) => (
- <ol className="my-2 list-decimal space-y-1 pl-6" {...props}>
- {children}
- </ol>
- ),
- li: ({ children, ...props }: ListItemProps) => (
- <li
- className={cn(
- props.className?.includes("task-list-item")
- ? "flex items-start"
- : "",
- )}
- {...props}
- >
- {children}
- </li>
- ),
- input: ({ ...props }: InputProps) => {
- if (props.type === "checkbox") {
- return (
- <input
- type="checkbox"
- className="mr-2 h-4 w-4 rounded border-zinc-300 text-purple-600 focus:ring-purple-500 disabled:cursor-not-allowed disabled:opacity-70"
- disabled
- {...props}
- />
- );
- }
- return <input {...props} />;
- },
- blockquote: ({ children, ...props }) => (
- <blockquote
- className="my-2 border-l-4 border-zinc-300 pl-3 italic text-zinc-700"
- {...props}
- >
- {children}
- </blockquote>
- ),
- h1: ({ children, ...props }) => (
- <h1 className="my-2 text-xl font-bold text-zinc-900" {...props}>
- {children}
- </h1>
- ),
- h2: ({ children, ...props }) => (
- <h2 className="my-2 text-lg font-semibold text-zinc-800" {...props}>
- {children}
- </h2>
- ),
- h3: ({ children, ...props }) => (
- <h3
- className="my-1 text-base font-semibold text-zinc-800"
- {...props}
- >
- {children}
- </h3>
- ),
- h4: ({ children, ...props }) => (
- <h4 className="my-1 text-sm font-medium text-zinc-700" {...props}>
- {children}
- </h4>
- ),
- h5: ({ children, ...props }) => (
- <h5 className="my-1 text-sm font-medium text-zinc-700" {...props}>
- {children}
- </h5>
- ),
- h6: ({ children, ...props }) => (
- <h6 className="my-1 text-xs font-medium text-zinc-600" {...props}>
- {children}
- </h6>
- ),
- p: ({ children, ...props }) => (
- <p className="my-2 leading-relaxed" {...props}>
- {children}
- </p>
- ),
- hr: ({ ...props }) => (
- <hr className="my-3 border-zinc-300" {...props} />
- ),
- table: ({ children, ...props }) => (
- <div className="my-2 overflow-x-auto">
- <table
- className="min-w-full divide-y divide-zinc-200 rounded border border-zinc-200"
- {...props}
- >
- {children}
- </table>
- </div>
- ),
- th: ({ children, ...props }) => (
- <th
- className="bg-zinc-50 px-3 py-2 text-left text-xs font-semibold text-zinc-700"
- {...props}
- >
- {children}
- </th>
- ),
- td: ({ children, ...props }) => (
- <td
- className="border-t border-zinc-200 px-3 py-2 text-sm"
- {...props}
- >
- {children}
- </td>
- ),
- img: ({ src, alt, ...props }) => (
- <MarkdownImage src={src} alt={alt} {...props} />
- ),
- }}
- >
- {content}
- </ReactMarkdown>
- </div>
- );
-}
diff --git a/autogpt_platform/frontend/src/components/contextual/Chat/components/MessageBubble/MessageBubble.tsx b/autogpt_platform/frontend/src/components/contextual/Chat/components/MessageBubble/MessageBubble.tsx
deleted file mode 100644
index 70d5d135a1..0000000000
--- a/autogpt_platform/frontend/src/components/contextual/Chat/components/MessageBubble/MessageBubble.tsx
+++ /dev/null
@@ -1,53 +0,0 @@
-import { cn } from "@/lib/utils";
-import { ReactNode } from "react";
-
-export interface MessageBubbleProps {
- children: ReactNode;
- variant: "user" | "assistant";
- className?: string;
-}
-
-export function MessageBubble({
- children,
- variant,
- className,
-}: MessageBubbleProps) {
- const userTheme = {
- bg: "bg-purple-100",
- border: "border-purple-100",
- text: "text-slate-900",
- };
-
- const assistantTheme = {
- bg: "bg-slate-50/20",
- border: "border-slate-100",
- gradient: "from-slate-200/20 via-slate-300/10 to-transparent",
- text: "text-slate-900",
- };
-
- const theme = variant === "user" ? userTheme : assistantTheme;
-
- return (
- <div
- className={cn(
- "group relative min-w-20 overflow-hidden rounded-xl border px-6 py-2.5 text-sm leading-relaxed backdrop-blur-xl transition-all duration-500 ease-in-out",
- theme.bg,
- theme.border,
- variant === "user" && "text-right",
- variant === "assistant" && "text-left",
- className,
- )}
- >
- {/* Gradient flare background */}
- <div className={cn("absolute inset-0 bg-gradient-to-br")} />
- <div
- className={cn(
- "relative z-10 transition-all duration-500 ease-in-out",
- theme.text,
- )}
- >
- {children}
- </div>
- </div>
- );
-}
diff --git a/autogpt_platform/frontend/src/components/contextual/Chat/components/MessageList/MessageList.tsx b/autogpt_platform/frontend/src/components/contextual/Chat/components/MessageList/MessageList.tsx
deleted file mode 100644
index d8478f1e82..0000000000
--- a/autogpt_platform/frontend/src/components/contextual/Chat/components/MessageList/MessageList.tsx
+++ /dev/null
@@ -1,115 +0,0 @@
-"use client";
-
-import { cn } from "@/lib/utils";
-import type { ChatMessageData } from "../ChatMessage/useChatMessage";
-import { StreamingMessage } from "../StreamingMessage/StreamingMessage";
-import { ThinkingMessage } from "../ThinkingMessage/ThinkingMessage";
-import { LastToolResponse } from "./components/LastToolResponse/LastToolResponse";
-import { MessageItem } from "./components/MessageItem/MessageItem";
-import { findLastMessageIndex, shouldSkipAgentOutput } from "./helpers";
-import { useMessageList } from "./useMessageList";
-
-export interface MessageListProps {
- messages: ChatMessageData[];
- streamingChunks?: string[];
- isStreaming?: boolean;
- className?: string;
- onStreamComplete?: () => void;
- onSendMessage?: (content: string) => void;
-}
-
-export function MessageList({
- messages,
- streamingChunks = [],
- isStreaming = false,
- className,
- onStreamComplete,
- onSendMessage,
-}: MessageListProps) {
- const { messagesEndRef, messagesContainerRef } = useMessageList({
- messageCount: messages.length,
- isStreaming,
- });
-
- return (
- <div className="relative flex min-h-0 flex-1 flex-col">
- {/* Top fade shadow */}
- <div className="pointer-events-none absolute top-0 z-10 h-8 w-full bg-gradient-to-b from-[#f8f8f9] to-transparent" />
-
- <div
- ref={messagesContainerRef}
- className={cn(
- "flex-1 overflow-y-auto overflow-x-hidden",
- "scrollbar-thin scrollbar-track-transparent scrollbar-thumb-zinc-300",
- className,
- )}
- >
- <div className="mx-auto flex min-w-0 flex-col hyphens-auto break-words py-4">
- {/* Render all persisted messages */}
- {(() => {
- const lastAssistantMessageIndex = findLastMessageIndex(
- messages,
- (msg) => msg.type === "message" && msg.role === "assistant",
- );
-
- const lastToolResponseIndex = findLastMessageIndex(
- messages,
- (msg) => msg.type === "tool_response",
- );
-
- return messages.map((message, index) => {
- // Skip agent_output tool_responses that should be rendered inside assistant messages
- if (shouldSkipAgentOutput(message, messages[index - 1])) {
- return null;
- }
-
- // Render last tool_response as AIChatBubble
- if (
- message.type === "tool_response" &&
- index === lastToolResponseIndex
- ) {
- return (
- <LastToolResponse
- key={index}
- message={message}
- prevMessage={messages[index - 1]}
- onSendMessage={onSendMessage}
- />
- );
- }
-
- return (
- <MessageItem
- key={index}
- message={message}
- messages={messages}
- index={index}
- lastAssistantMessageIndex={lastAssistantMessageIndex}
- isStreaming={isStreaming}
- onSendMessage={onSendMessage}
- />
- );
- });
- })()}
-
- {/* Render thinking message when streaming but no chunks yet */}
- {isStreaming && streamingChunks.length === 0 && <ThinkingMessage />}
-
- {/* Render streaming message if active */}
- {isStreaming && streamingChunks.length > 0 && (
- <StreamingMessage
- chunks={streamingChunks}
- onComplete={onStreamComplete}
- />
- )}
-
- {/* Invisible div to scroll to */}
- <div ref={messagesEndRef} />
- </div>
- </div>
-
- {/* Bottom fade shadow */}
- <div className="pointer-events-none absolute bottom-0 z-10 h-8 w-full bg-gradient-to-t from-[#f8f8f9] to-transparent" />
- </div>
- );
-}
diff --git a/autogpt_platform/frontend/src/components/contextual/Chat/components/MessageList/components/LastToolResponse/LastToolResponse.tsx b/autogpt_platform/frontend/src/components/contextual/Chat/components/MessageList/components/LastToolResponse/LastToolResponse.tsx
deleted file mode 100644
index 7c5a75bec5..0000000000
--- a/autogpt_platform/frontend/src/components/contextual/Chat/components/MessageList/components/LastToolResponse/LastToolResponse.tsx
+++ /dev/null
@@ -1,30 +0,0 @@
-import type { ChatMessageData } from "../../../ChatMessage/useChatMessage";
-import { ToolResponseMessage } from "../../../ToolResponseMessage/ToolResponseMessage";
-import { shouldSkipAgentOutput } from "../../helpers";
-
-export interface LastToolResponseProps {
- message: ChatMessageData;
- prevMessage: ChatMessageData | undefined;
- onSendMessage?: (content: string) => void;
-}
-
-export function LastToolResponse({
- message,
- prevMessage,
- onSendMessage,
-}: LastToolResponseProps) {
- if (message.type !== "tool_response") return null;
-
- if (shouldSkipAgentOutput(message, prevMessage)) return null;
-
- return (
- <div className="min-w-0 overflow-x-hidden hyphens-auto break-words px-4 py-2">
- <ToolResponseMessage
- toolId={message.toolId}
- toolName={message.toolName}
- result={message.result}
- onSendMessage={onSendMessage}
- />
- </div>
- );
-}
diff --git a/autogpt_platform/frontend/src/components/contextual/Chat/components/MessageList/components/MessageItem/MessageItem.tsx b/autogpt_platform/frontend/src/components/contextual/Chat/components/MessageList/components/MessageItem/MessageItem.tsx
deleted file mode 100644
index d455633b66..0000000000
--- a/autogpt_platform/frontend/src/components/contextual/Chat/components/MessageList/components/MessageItem/MessageItem.tsx
+++ /dev/null
@@ -1,40 +0,0 @@
-import { ChatMessage } from "../../../ChatMessage/ChatMessage";
-import type { ChatMessageData } from "../../../ChatMessage/useChatMessage";
-import { useMessageItem } from "./useMessageItem";
-
-export interface MessageItemProps {
- message: ChatMessageData;
- messages: ChatMessageData[];
- index: number;
- lastAssistantMessageIndex: number;
- isStreaming?: boolean;
- onSendMessage?: (content: string) => void;
-}
-
-export function MessageItem({
- message,
- messages,
- index,
- lastAssistantMessageIndex,
- isStreaming = false,
- onSendMessage,
-}: MessageItemProps) {
- const { messageToRender, agentOutput, isFinalMessage } = useMessageItem({
- message,
- messages,
- index,
- lastAssistantMessageIndex,
- });
-
- return (
- <ChatMessage
- message={messageToRender}
- messages={messages}
- index={index}
- isStreaming={isStreaming}
- onSendMessage={onSendMessage}
- agentOutput={agentOutput}
- isFinalMessage={isFinalMessage}
- />
- );
-}
diff --git a/autogpt_platform/frontend/src/components/contextual/Chat/components/MessageList/components/MessageItem/useMessageItem.ts b/autogpt_platform/frontend/src/components/contextual/Chat/components/MessageList/components/MessageItem/useMessageItem.ts
deleted file mode 100644
index 65c2e02cc8..0000000000
--- a/autogpt_platform/frontend/src/components/contextual/Chat/components/MessageList/components/MessageItem/useMessageItem.ts
+++ /dev/null
@@ -1,62 +0,0 @@
-import type { ChatMessageData } from "../../../ChatMessage/useChatMessage";
-import { isAgentOutputResult, isToolOutputPattern } from "../../helpers";
-
-export interface UseMessageItemArgs {
- message: ChatMessageData;
- messages: ChatMessageData[];
- index: number;
- lastAssistantMessageIndex: number;
-}
-
-export function useMessageItem({
- message,
- messages,
- index,
- lastAssistantMessageIndex,
-}: UseMessageItemArgs) {
- let agentOutput: ChatMessageData | undefined;
- let messageToRender: ChatMessageData = message;
-
- // Check if assistant message follows a tool_call and looks like a tool output
- if (message.type === "message" && message.role === "assistant") {
- const prevMessage = messages[index - 1];
-
- // Check if next message is an agent_output tool_response to include in current assistant message
- const nextMessage = messages[index + 1];
- if (
- nextMessage &&
- nextMessage.type === "tool_response" &&
- nextMessage.result
- ) {
- if (isAgentOutputResult(nextMessage.result)) {
- agentOutput = nextMessage;
- }
- }
-
- // Only convert to tool_response if it follows a tool_call AND looks like a tool output
- if (prevMessage && prevMessage.type === "tool_call") {
- if (isToolOutputPattern(message.content)) {
- // Convert this message to a tool_response format for rendering
- messageToRender = {
- type: "tool_response",
- toolId: prevMessage.toolId,
- toolName: prevMessage.toolName,
- result: message.content,
- success: true,
- timestamp: message.timestamp,
- } as ChatMessageData;
- }
- }
- }
-
- const isFinalMessage =
- messageToRender.type !== "message" ||
- messageToRender.role !== "assistant" ||
- index === lastAssistantMessageIndex;
-
- return {
- messageToRender,
- agentOutput,
- isFinalMessage,
- };
-}
diff --git a/autogpt_platform/frontend/src/components/contextual/Chat/components/MessageList/helpers.ts b/autogpt_platform/frontend/src/components/contextual/Chat/components/MessageList/helpers.ts
deleted file mode 100644
index f6731c66c7..0000000000
--- a/autogpt_platform/frontend/src/components/contextual/Chat/components/MessageList/helpers.ts
+++ /dev/null
@@ -1,68 +0,0 @@
-import type { ChatMessageData } from "../ChatMessage/useChatMessage";
-
-export function parseToolResult(
- result: unknown,
-): Record<string, unknown> | null {
- try {
- return typeof result === "string"
- ? JSON.parse(result)
- : (result as Record<string, unknown>);
- } catch {
- return null;
- }
-}
-
-export function isAgentOutputResult(result: unknown): boolean {
- const parsed = parseToolResult(result);
- return parsed?.type === "agent_output";
-}
-
-export function isToolOutputPattern(content: string): boolean {
- const normalizedContent = content.toLowerCase().trim();
-
- return (
- normalizedContent.startsWith("no agents found") ||
- normalizedContent.startsWith("no results found") ||
- normalizedContent.includes("no agents found matching") ||
- !!normalizedContent.match(/^no \w+ found/i) ||
- (content.length < 150 && normalizedContent.includes("try different")) ||
- (content.length < 200 &&
- !normalizedContent.includes("i'll") &&
- !normalizedContent.includes("let me") &&
- !normalizedContent.includes("i can") &&
- !normalizedContent.includes("i will"))
- );
-}
-
-export function formatToolResultValue(result: unknown): string {
- return typeof result === "string"
- ? result
- : result
- ? JSON.stringify(result, null, 2)
- : "";
-}
-
-export function findLastMessageIndex(
- messages: ChatMessageData[],
- predicate: (msg: ChatMessageData) => boolean,
-): number {
- for (let i = messages.length - 1; i >= 0; i--) {
- if (predicate(messages[i])) return i;
- }
- return -1;
-}
-
-export function shouldSkipAgentOutput(
- message: ChatMessageData,
- prevMessage: ChatMessageData | undefined,
-): boolean {
- if (message.type !== "tool_response" || !message.result) return false;
-
- const isAgentOutput = isAgentOutputResult(message.result);
- return (
- isAgentOutput &&
- !!prevMessage &&
- prevMessage.type === "message" &&
- prevMessage.role === "assistant"
- );
-}
diff --git a/autogpt_platform/frontend/src/components/contextual/Chat/components/MessageList/useMessageList.ts b/autogpt_platform/frontend/src/components/contextual/Chat/components/MessageList/useMessageList.ts
deleted file mode 100644
index 3dcc75df3c..0000000000
--- a/autogpt_platform/frontend/src/components/contextual/Chat/components/MessageList/useMessageList.ts
+++ /dev/null
@@ -1,28 +0,0 @@
-import { useEffect, useRef, useCallback } from "react";
-
-interface UseMessageListArgs {
- messageCount: number;
- isStreaming: boolean;
-}
-
-export function useMessageList({
- messageCount,
- isStreaming,
-}: UseMessageListArgs) {
- const messagesEndRef = useRef<HTMLDivElement>(null);
- const messagesContainerRef = useRef<HTMLDivElement>(null);
-
- const scrollToBottom = useCallback(() => {
- messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
- }, []);
-
- useEffect(() => {
- scrollToBottom();
- }, [messageCount, isStreaming, scrollToBottom]);
-
- return {
- messagesEndRef,
- messagesContainerRef,
- scrollToBottom,
- };
-}
diff --git a/autogpt_platform/frontend/src/components/contextual/Chat/components/NoResultsMessage/NoResultsMessage.tsx b/autogpt_platform/frontend/src/components/contextual/Chat/components/NoResultsMessage/NoResultsMessage.tsx
deleted file mode 100644
index b6adc8b93c..0000000000
--- a/autogpt_platform/frontend/src/components/contextual/Chat/components/NoResultsMessage/NoResultsMessage.tsx
+++ /dev/null
@@ -1,64 +0,0 @@
-import { Text } from "@/components/atoms/Text/Text";
-import { cn } from "@/lib/utils";
-import { MagnifyingGlass, X } from "@phosphor-icons/react";
-
-export interface NoResultsMessageProps {
- message: string;
- suggestions?: string[];
- className?: string;
-}
-
-export function NoResultsMessage({
- message,
- suggestions = [],
- className,
-}: NoResultsMessageProps) {
- return (
- <div
- className={cn(
- "mx-4 my-2 flex flex-col items-center gap-4 rounded-lg border border-gray-200 bg-gray-50 p-6",
- className,
- )}
- >
- {/* Icon */}
- <div className="relative flex h-16 w-16 items-center justify-center">
- <div className="flex h-16 w-16 items-center justify-center rounded-full bg-gray-200">
- <MagnifyingGlass size={32} weight="bold" className="text-gray-500" />
- </div>
- <div className="absolute -right-1 -top-1 flex h-8 w-8 items-center justify-center rounded-full bg-gray-400">
- <X size={20} weight="bold" className="text-white" />
- </div>
- </div>
-
- {/* Content */}
- <div className="text-center">
- <Text variant="h3" className="mb-2 text-gray-900">
- No Results Found
- </Text>
- <Text variant="body" className="text-gray-700">
- {message}
- </Text>
- </div>
-
- {/* Suggestions */}
- {suggestions.length > 0 && (
- <div className="w-full space-y-2">
- <Text variant="small" className="font-semibold text-gray-900">
- Try these suggestions:
- </Text>
- <ul className="space-y-1 rounded-md bg-gray-100 p-4">
- {suggestions.map((suggestion, index) => (
- <li
- key={index}
- className="flex items-start gap-2 text-sm text-gray-700"
- >
- <span className="mt-1 text-gray-500">•</span>
- <span>{suggestion}</span>
- </li>
- ))}
- </ul>
- </div>
- )}
- </div>
- );
-}
diff --git a/autogpt_platform/frontend/src/components/contextual/Chat/components/PendingOperationWidget/PendingOperationWidget.tsx b/autogpt_platform/frontend/src/components/contextual/Chat/components/PendingOperationWidget/PendingOperationWidget.tsx
deleted file mode 100644
index 6cfea7f327..0000000000
--- a/autogpt_platform/frontend/src/components/contextual/Chat/components/PendingOperationWidget/PendingOperationWidget.tsx
+++ /dev/null
@@ -1,109 +0,0 @@
-"use client";
-
-import { Card } from "@/components/atoms/Card/Card";
-import { Text } from "@/components/atoms/Text/Text";
-import { cn } from "@/lib/utils";
-import { CircleNotch, CheckCircle, XCircle } from "@phosphor-icons/react";
-
-type OperationStatus =
- | "pending"
- | "started"
- | "in_progress"
- | "completed"
- | "error";
-
-interface Props {
- status: OperationStatus;
- message: string;
- toolName?: string;
- className?: string;
-}
-
-function getOperationTitle(toolName?: string): string {
- if (!toolName) return "Operation";
- // Convert tool name to human-readable format
- // e.g., "create_agent" -> "Creating Agent", "edit_agent" -> "Editing Agent"
- if (toolName === "create_agent") return "Creating Agent";
- if (toolName === "edit_agent") return "Editing Agent";
- // Default: capitalize and format tool name
- return toolName
- .split("_")
- .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
- .join(" ");
-}
-
-export function PendingOperationWidget({
- status,
- message,
- toolName,
- className,
-}: Props) {
- const isPending =
- status === "pending" || status === "started" || status === "in_progress";
- const isCompleted = status === "completed";
- const isError = status === "error";
-
- const operationTitle = getOperationTitle(toolName);
-
- return (
- <div
- className={cn(
- "group relative flex w-full justify-start gap-3 px-4 py-3",
- className,
- )}
- >
- <div className="flex w-full max-w-3xl gap-3">
- <div className="flex-shrink-0">
- <div
- className={cn(
- "flex h-7 w-7 items-center justify-center rounded-lg",
- isPending && "bg-blue-500",
- isCompleted && "bg-green-500",
- isError && "bg-red-500",
- )}
- >
- {isPending && (
- <CircleNotch
- className="h-4 w-4 animate-spin text-white"
- weight="bold"
- />
- )}
- {isCompleted && (
- <CheckCircle className="h-4 w-4 text-white" weight="bold" />
- )}
- {isError && (
- <XCircle className="h-4 w-4 text-white" weight="bold" />
- )}
- </div>
- </div>
-
- <div className="flex min-w-0 flex-1 flex-col">
- <Card className="space-y-2 p-4">
- <div>
- <Text variant="h4" className="mb-1 text-slate-900">
- {isPending && operationTitle}
- {isCompleted && `${operationTitle} Complete`}
- {isError && `${operationTitle} Failed`}
- </Text>
- <Text variant="small" className="text-slate-600">
- {message}
- </Text>
- </div>
-
- {isPending && (
- <Text variant="small" className="italic text-slate-500">
- Check your library in a few minutes.
- </Text>
- )}
-
- {toolName && (
- <Text variant="small" className="text-slate-400">
- Tool: {toolName}
- </Text>
- )}
- </Card>
- </div>
- </div>
- </div>
- );
-}
diff --git a/autogpt_platform/frontend/src/components/contextual/Chat/components/QuickActionsWelcome/QuickActionsWelcome.tsx b/autogpt_platform/frontend/src/components/contextual/Chat/components/QuickActionsWelcome/QuickActionsWelcome.tsx
deleted file mode 100644
index dd76fd9fb6..0000000000
--- a/autogpt_platform/frontend/src/components/contextual/Chat/components/QuickActionsWelcome/QuickActionsWelcome.tsx
+++ /dev/null
@@ -1,94 +0,0 @@
-"use client";
-
-import { Text } from "@/components/atoms/Text/Text";
-import { cn } from "@/lib/utils";
-
-export interface QuickActionsWelcomeProps {
- title: string;
- description: string;
- actions: string[];
- onActionClick: (action: string) => void;
- disabled?: boolean;
- className?: string;
-}
-
-export function QuickActionsWelcome({
- title,
- description,
- actions,
- onActionClick,
- disabled = false,
- className,
-}: QuickActionsWelcomeProps) {
- return (
- <div
- className={cn("flex flex-1 items-center justify-center p-8", className)}
- >
- <div className="w-full max-w-3xl">
- <div className="mb-12 text-center">
- <Text
- variant="h2"
- className="mb-3 text-2xl font-semibold text-zinc-900"
- >
- {title}
- </Text>
- <Text variant="body" className="text-zinc-500">
- {description}
- </Text>
- </div>
- <div className="grid gap-3 sm:grid-cols-2">
- {actions.map((action) => {
- // Use slate theme for all cards
- const theme = {
- bg: "bg-slate-50/10",
- border: "border-slate-100",
- hoverBg: "hover:bg-slate-50/20",
- hoverBorder: "hover:border-slate-200",
- gradient: "from-slate-200/20 via-slate-300/10 to-transparent",
- text: "text-slate-900",
- hoverText: "group-hover:text-slate-900",
- };
-
- return (
- <button
- key={action}
- onClick={() => onActionClick(action)}
- disabled={disabled}
- className={cn(
- "group relative overflow-hidden rounded-xl border p-5 text-left backdrop-blur-xl",
- "transition-all duration-200",
- theme.bg,
- theme.border,
- theme.hoverBg,
- theme.hoverBorder,
- "hover:shadow-sm",
- "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-white/50 focus-visible:ring-offset-2",
- "disabled:cursor-not-allowed disabled:opacity-50 disabled:hover:shadow-none",
- )}
- >
- {/* Gradient flare background */}
- <div
- className={cn(
- "absolute inset-0 bg-gradient-to-br",
- theme.gradient,
- )}
- />
-
- <Text
- variant="body"
- className={cn(
- "relative z-10 font-medium",
- theme.text,
- theme.hoverText,
- )}
- >
- {action}
- </Text>
- </button>
- );
- })}
- </div>
- </div>
- </div>
- );
-}
diff --git a/autogpt_platform/frontend/src/components/contextual/Chat/components/SessionsDrawer/SessionsDrawer.tsx b/autogpt_platform/frontend/src/components/contextual/Chat/components/SessionsDrawer/SessionsDrawer.tsx
deleted file mode 100644
index ee2896f1e2..0000000000
--- a/autogpt_platform/frontend/src/components/contextual/Chat/components/SessionsDrawer/SessionsDrawer.tsx
+++ /dev/null
@@ -1,136 +0,0 @@
-"use client";
-
-import { useGetV2ListSessions } from "@/app/api/__generated__/endpoints/chat/chat";
-import { Text } from "@/components/atoms/Text/Text";
-import { scrollbarStyles } from "@/components/styles/scrollbars";
-import { cn } from "@/lib/utils";
-import { X } from "@phosphor-icons/react";
-import { formatDistanceToNow } from "date-fns";
-import { Drawer } from "vaul";
-
-interface SessionsDrawerProps {
- isOpen: boolean;
- onClose: () => void;
- onSelectSession: (sessionId: string) => void;
- currentSessionId?: string | null;
-}
-
-export function SessionsDrawer({
- isOpen,
- onClose,
- onSelectSession,
- currentSessionId,
-}: SessionsDrawerProps) {
- const { data, isLoading } = useGetV2ListSessions(
- { limit: 100 },
- {
- query: {
- enabled: isOpen,
- },
- },
- );
-
- const sessions =
- data?.status === 200
- ? data.data.sessions.filter((session) => {
- // Filter out sessions without messages (sessions that were never updated)
- // If updated_at equals created_at, the session was created but never had messages
- return session.updated_at !== session.created_at;
- })
- : [];
-
- function handleSelectSession(sessionId: string) {
- onSelectSession(sessionId);
- onClose();
- }
-
- return (
- <Drawer.Root
- open={isOpen}
- onOpenChange={(open) => !open && onClose()}
- direction="right"
- >
- <Drawer.Portal>
- <Drawer.Overlay className="fixed inset-0 z-[60] bg-black/10 backdrop-blur-sm" />
- <Drawer.Content
- className={cn(
- "fixed right-0 top-0 z-[70] flex h-full w-96 flex-col border-l border-zinc-200 bg-white",
- scrollbarStyles,
- )}
- >
- <div className="shrink-0 p-4">
- <div className="flex items-center justify-between">
- <Drawer.Title className="text-lg font-semibold">
- Chat Sessions
- </Drawer.Title>
- <button
- aria-label="Close"
- onClick={onClose}
- className="flex size-8 items-center justify-center rounded hover:bg-zinc-100"
- >
- <X width="1.25rem" height="1.25rem" />
- </button>
- </div>
- </div>
-
- <div className="flex-1 overflow-y-auto p-4">
- {isLoading ? (
- <div className="flex items-center justify-center py-8">
- <Text variant="body" className="text-zinc-500">
- Loading sessions...
- </Text>
- </div>
- ) : sessions.length === 0 ? (
- <div className="flex h-full items-center justify-center">
- <Text variant="body" className="text-zinc-500">
- You don&apos;t have previously started chats
- </Text>
- </div>
- ) : (
- <div className="space-y-2">
- {sessions.map((session) => {
- const isActive = session.id === currentSessionId;
- const updatedAt = session.updated_at
- ? formatDistanceToNow(new Date(session.updated_at), {
- addSuffix: true,
- })
- : "";
-
- return (
- <button
- key={session.id}
- onClick={() => handleSelectSession(session.id)}
- className={cn(
- "w-full rounded-lg border p-3 text-left transition-colors",
- isActive
- ? "border-indigo-500 bg-zinc-50"
- : "border-zinc-200 bg-zinc-100/50 hover:border-zinc-300 hover:bg-zinc-50",
- )}
- >
- <div className="flex flex-col gap-1">
- <Text
- variant="body"
- className={cn(
- "font-medium",
- isActive ? "text-indigo-900" : "text-zinc-900",
- )}
- >
- {session.title || "Untitled Chat"}
- </Text>
- <div className="flex items-center gap-2 text-xs text-zinc-500">
- <span>{session.id.slice(0, 8)}...</span>
- {updatedAt && <span>•</span>}
- <span>{updatedAt}</span>
- </div>
- </div>
- </button>
- );
- })}
- </div>
- )}
- </div>
- </Drawer.Content>
- </Drawer.Portal>
- </Drawer.Root>
- );
-}
diff --git a/autogpt_platform/frontend/src/components/contextual/Chat/components/StreamingMessage/StreamingMessage.tsx b/autogpt_platform/frontend/src/components/contextual/Chat/components/StreamingMessage/StreamingMessage.tsx
deleted file mode 100644
index 5b1f8b1617..0000000000
--- a/autogpt_platform/frontend/src/components/contextual/Chat/components/StreamingMessage/StreamingMessage.tsx
+++ /dev/null
@@ -1,35 +0,0 @@
-import { cn } from "@/lib/utils";
-import { AIChatBubble } from "../AIChatBubble/AIChatBubble";
-import { MarkdownContent } from "../MarkdownContent/MarkdownContent";
-import { useStreamingMessage } from "./useStreamingMessage";
-
-export interface StreamingMessageProps {
- chunks: string[];
- className?: string;
- onComplete?: () => void;
-}
-
-export function StreamingMessage({
- chunks,
- className,
- onComplete,
-}: StreamingMessageProps) {
- const { displayText } = useStreamingMessage({ chunks, onComplete });
-
- return (
- <div
- className={cn(
- "group relative flex w-full justify-start gap-3 px-4 py-3",
- className,
- )}
- >
- <div className="flex w-full max-w-3xl gap-3">
- <div className="flex min-w-0 flex-1 flex-col">
- <AIChatBubble>
- <MarkdownContent content={displayText} />
- </AIChatBubble>
- </div>
- </div>
- </div>
- );
-}
diff --git a/autogpt_platform/frontend/src/components/contextual/Chat/components/StreamingMessage/useStreamingMessage.ts b/autogpt_platform/frontend/src/components/contextual/Chat/components/StreamingMessage/useStreamingMessage.ts
deleted file mode 100644
index 5203762151..0000000000
--- a/autogpt_platform/frontend/src/components/contextual/Chat/components/StreamingMessage/useStreamingMessage.ts
+++ /dev/null
@@ -1,25 +0,0 @@
-import { useEffect, useState } from "react";
-
-interface UseStreamingMessageArgs {
- chunks: string[];
- onComplete?: () => void;
-}
-
-export function useStreamingMessage({
- chunks,
- onComplete,
-}: UseStreamingMessageArgs) {
- const [isComplete, _setIsComplete] = useState(false);
- const displayText = chunks.join("");
-
- useEffect(() => {
- if (isComplete && onComplete) {
- onComplete();
- }
- }, [isComplete, onComplete]);
-
- return {
- displayText,
- isComplete,
- };
-}
diff --git a/autogpt_platform/frontend/src/components/contextual/Chat/components/ThinkingMessage/ThinkingMessage.tsx b/autogpt_platform/frontend/src/components/contextual/Chat/components/ThinkingMessage/ThinkingMessage.tsx
deleted file mode 100644
index 2202705e65..0000000000
--- a/autogpt_platform/frontend/src/components/contextual/Chat/components/ThinkingMessage/ThinkingMessage.tsx
+++ /dev/null
@@ -1,82 +0,0 @@
-import { Progress } from "@/components/atoms/Progress/Progress";
-import { cn } from "@/lib/utils";
-import { useEffect, useRef, useState } from "react";
-import { AIChatBubble } from "../AIChatBubble/AIChatBubble";
-import { useAsymptoticProgress } from "../ToolCallMessage/useAsymptoticProgress";
-
-export interface ThinkingMessageProps {
- className?: string;
-}
-
-export function ThinkingMessage({ className }: ThinkingMessageProps) {
- const [showSlowLoader, setShowSlowLoader] = useState(false);
- const [showCoffeeMessage, setShowCoffeeMessage] = useState(false);
- const timerRef = useRef<NodeJS.Timeout | null>(null);
- const coffeeTimerRef = useRef<NodeJS.Timeout | null>(null);
- const progress = useAsymptoticProgress(showCoffeeMessage);
-
- useEffect(() => {
- if (timerRef.current === null) {
- timerRef.current = setTimeout(() => {
- setShowSlowLoader(true);
- }, 8000);
- }
-
- if (coffeeTimerRef.current === null) {
- coffeeTimerRef.current = setTimeout(() => {
- setShowCoffeeMessage(true);
- }, 10000);
- }
-
- return () => {
- if (timerRef.current) {
- clearTimeout(timerRef.current);
- timerRef.current = null;
- }
- if (coffeeTimerRef.current) {
- clearTimeout(coffeeTimerRef.current);
- coffeeTimerRef.current = null;
- }
- };
- }, []);
-
- return (
- <div
- className={cn(
- "group relative flex w-full justify-start gap-3 px-4 py-3",
- className,
- )}
- >
- <div className="flex w-full max-w-3xl gap-3">
- <div className="flex min-w-0 flex-1 flex-col">
- <AIChatBubble>
- <div className="transition-all duration-500 ease-in-out">
- {showCoffeeMessage ? (
- <div className="flex flex-col items-center gap-3">
- <div className="flex w-full max-w-[280px] flex-col gap-1.5">
- <div className="flex items-center justify-between text-xs text-neutral-500">
- <span>Working on it...</span>
- <span>{Math.round(progress)}%</span>
- </div>
- <Progress value={progress} className="h-2 w-full" />
- </div>
- <span className="inline-block animate-shimmer bg-gradient-to-r from-neutral-400 via-neutral-600 to-neutral-400 bg-[length:200%_100%] bg-clip-text text-transparent">
- This could take a few minutes, grab a coffee ☕️
- </span>
- </div>
- ) : showSlowLoader ? (
- <span className="inline-block animate-shimmer bg-gradient-to-r from-neutral-400 via-neutral-600 to-neutral-400 bg-[length:200%_100%] bg-clip-text text-transparent">
- Taking a bit more time...
- </span>
- ) : (
- <span className="inline-block animate-shimmer bg-gradient-to-r from-neutral-400 via-neutral-600 to-neutral-400 bg-[length:200%_100%] bg-clip-text text-transparent">
- Thinking...
- </span>
- )}
- </div>
- </AIChatBubble>
- </div>
- </div>
- </div>
- );
-}
diff --git a/autogpt_platform/frontend/src/components/contextual/Chat/components/ToolCallMessage/ToolCallMessage.tsx b/autogpt_platform/frontend/src/components/contextual/Chat/components/ToolCallMessage/ToolCallMessage.tsx
deleted file mode 100644
index 67aa975f15..0000000000
--- a/autogpt_platform/frontend/src/components/contextual/Chat/components/ToolCallMessage/ToolCallMessage.tsx
+++ /dev/null
@@ -1,55 +0,0 @@
-import { Text } from "@/components/atoms/Text/Text";
-import { cn } from "@/lib/utils";
-import type { ToolArguments } from "@/types/chat";
-import { AIChatBubble } from "../AIChatBubble/AIChatBubble";
-import {
- formatToolArguments,
- getToolActionPhrase,
- getToolIcon,
-} from "./helpers";
-
-export interface ToolCallMessageProps {
- toolId?: string;
- toolName: string;
- arguments?: ToolArguments;
- isStreaming?: boolean;
- className?: string;
-}
-
-export function ToolCallMessage({
- toolName,
- arguments: toolArguments,
- isStreaming = false,
- className,
-}: ToolCallMessageProps) {
- const actionPhrase = getToolActionPhrase(toolName);
- const argumentsText = formatToolArguments(toolName, toolArguments);
- const displayText = `${actionPhrase}${argumentsText}`;
- const IconComponent = getToolIcon(toolName);
-
- return (
- <AIChatBubble className={className}>
- <div className="flex items-center gap-2">
- <IconComponent
- size={14}
- weight={isStreaming ? "regular" : "regular"}
- className={cn(
- "shrink-0",
- isStreaming ? "text-neutral-500" : "text-neutral-400",
- )}
- />
- <Text
- variant="small"
- className={cn(
- "text-xs",
- isStreaming
- ? "bg-gradient-to-r from-neutral-600 via-neutral-500 to-neutral-600 bg-[length:200%_100%] bg-clip-text text-transparent [animation:shimmer_2s_ease-in-out_infinite]"
- : "text-neutral-500",
- )}
- >
- {displayText}
- </Text>
- </div>
- </AIChatBubble>
- );
-}
diff --git a/autogpt_platform/frontend/src/components/contextual/Chat/components/ToolCallMessage/helpers.ts b/autogpt_platform/frontend/src/components/contextual/Chat/components/ToolCallMessage/helpers.ts
deleted file mode 100644
index 2f9f50b455..0000000000
--- a/autogpt_platform/frontend/src/components/contextual/Chat/components/ToolCallMessage/helpers.ts
+++ /dev/null
@@ -1,184 +0,0 @@
-import type { ToolArguments } from "@/types/chat";
-import {
- BrainIcon,
- EyeIcon,
- FileMagnifyingGlassIcon,
- FileTextIcon,
- MagnifyingGlassIcon,
- PackageIcon,
- PencilLineIcon,
- PlayIcon,
- PlusIcon,
- SquaresFourIcon,
- type Icon,
-} from "@phosphor-icons/react";
-
-/**
- * Maps internal tool names to human-friendly action phrases (present continuous).
- * Used for tool call messages to indicate what action is currently happening.
- *
- * @param toolName - The internal tool name from the backend
- * @returns A human-friendly action phrase in present continuous tense
- */
-export function getToolActionPhrase(toolName: string): string {
- const normalizedName = toolName.trim();
- if (!normalizedName) return "Executing";
- if (normalizedName.toLowerCase().startsWith("executing")) {
- return normalizedName;
- }
- if (normalizedName.toLowerCase() === "unknown") return "Executing";
- const toolActionPhrases: Record<string, string> = {
- add_understanding: "Updating your business information",
- create_agent: "Creating a new agent",
- edit_agent: "Editing the agent",
- find_agent: "Looking for agents in the marketplace",
- find_block: "Searching for blocks",
- find_library_agent: "Looking for library agents",
- run_agent: "Running the agent",
- run_block: "Running the block",
- view_agent_output: "Retrieving agent output",
- search_docs: "Searching documentation",
- get_doc_page: "Loading documentation page",
- agent_carousel: "Looking for agents in the marketplace",
- execution_started: "Running the agent",
- get_required_setup_info: "Getting setup requirements",
- schedule_agent: "Scheduling the agent to run",
- };
-
- // Return mapped phrase or generate human-friendly fallback
- return (
- toolActionPhrases[toolName] ||
- toolName
- .replace(/_/g, " ")
- .replace(/\b\w/g, (l) => l.toUpperCase())
- .replace(/^/, "Executing ")
- );
-}
-
-/**
- * Formats tool call arguments into user-friendly text.
- * Handles different tool types and formats their arguments nicely.
- *
- * @param toolName - The tool name
- * @param args - The tool arguments
- * @returns Formatted user-friendly text to append to action phrase
- */
-export function formatToolArguments(
- toolName: string,
- args: ToolArguments | undefined,
-): string {
- if (!args || Object.keys(args).length === 0) {
- return "";
- }
-
- switch (toolName) {
- case "find_agent":
- case "find_library_agent":
- case "agent_carousel":
- if (args.query) {
- return ` matching "${args.query as string}"`;
- }
- break;
-
- case "find_block":
- if (args.query) {
- return ` matching "${args.query as string}"`;
- }
- break;
-
- case "search_docs":
- if (args.query) {
- return ` for "${args.query as string}"`;
- }
- break;
-
- case "get_doc_page":
- if (args.path) {
- return ` "${args.path as string}"`;
- }
- break;
-
- case "run_agent":
- if (args.username_agent_slug) {
- return ` "${args.username_agent_slug as string}"`;
- }
- if (args.library_agent_id) {
- return ` (library agent)`;
- }
- break;
-
- case "run_block":
- if (args.block_id) {
- return ` "${args.block_id as string}"`;
- }
- break;
-
- case "view_agent_output":
- if (args.library_agent_id) {
- return ` (library agent)`;
- }
- if (args.username_agent_slug) {
- return ` "${args.username_agent_slug as string}"`;
- }
- break;
-
- case "create_agent":
- case "edit_agent":
- if (args.name) {
- return ` "${args.name as string}"`;
- }
- break;
-
- case "add_understanding":
- const understandingFields = Object.entries(args)
- .filter(
- ([_, value]) => value !== null && value !== undefined && value !== "",
- )
- .map(([key, value]) => {
- if (key === "user_name" && typeof value === "string") {
- return `for ${value}`;
- }
- if (typeof value === "string") {
- return `${key}: ${value}`;
- }
- if (Array.isArray(value) && value.length > 0) {
- return `${key}: ${value.slice(0, 2).join(", ")}${value.length > 2 ? ` (+${value.length - 2} more)` : ""}`;
- }
- return key;
- });
- if (understandingFields.length > 0) {
- return ` ${understandingFields[0]}`;
- }
- break;
- }
-
- return "";
-}
-
-/**
- * Maps tool names to their corresponding Phosphor icon components.
- *
- * @param toolName - The tool name from the backend
- * @returns The Icon component for the tool
- */
-export function getToolIcon(toolName: string): Icon {
- const iconMap: Record<string, Icon> = {
- add_understanding: BrainIcon,
- create_agent: PlusIcon,
- edit_agent: PencilLineIcon,
- find_agent: SquaresFourIcon,
- find_library_agent: MagnifyingGlassIcon,
- find_block: PackageIcon,
- run_agent: PlayIcon,
- run_block: PlayIcon,
- view_agent_output: EyeIcon,
- search_docs: FileMagnifyingGlassIcon,
- get_doc_page: FileTextIcon,
- agent_carousel: MagnifyingGlassIcon,
- execution_started: PlayIcon,
- get_required_setup_info: SquaresFourIcon,
- schedule_agent: PlayIcon,
- };
-
- return iconMap[toolName] || SquaresFourIcon;
-}
diff --git a/autogpt_platform/frontend/src/components/contextual/Chat/components/ToolResponseMessage/AgentCreatedPrompt.tsx b/autogpt_platform/frontend/src/components/contextual/Chat/components/ToolResponseMessage/AgentCreatedPrompt.tsx
deleted file mode 100644
index 8494452eea..0000000000
--- a/autogpt_platform/frontend/src/components/contextual/Chat/components/ToolResponseMessage/AgentCreatedPrompt.tsx
+++ /dev/null
@@ -1,128 +0,0 @@
-"use client";
-
-import { useGetV2GetLibraryAgent } from "@/app/api/__generated__/endpoints/library/library";
-import { GraphExecutionJobInfo } from "@/app/api/__generated__/models/graphExecutionJobInfo";
-import { GraphExecutionMeta } from "@/app/api/__generated__/models/graphExecutionMeta";
-import { RunAgentModal } from "@/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/modals/RunAgentModal/RunAgentModal";
-import { Button } from "@/components/atoms/Button/Button";
-import { Text } from "@/components/atoms/Text/Text";
-import {
- CheckCircleIcon,
- PencilLineIcon,
- PlayIcon,
-} from "@phosphor-icons/react";
-import { AIChatBubble } from "../AIChatBubble/AIChatBubble";
-
-interface Props {
- agentName: string;
- libraryAgentId: string;
- onSendMessage?: (content: string) => void;
-}
-
-export function AgentCreatedPrompt({
- agentName,
- libraryAgentId,
- onSendMessage,
-}: Props) {
- // Fetch library agent eagerly so modal is ready when user clicks
- const { data: libraryAgentResponse, isLoading } = useGetV2GetLibraryAgent(
- libraryAgentId,
- {
- query: {
- enabled: !!libraryAgentId,
- },
- },
- );
-
- const libraryAgent =
- libraryAgentResponse?.status === 200 ? libraryAgentResponse.data : null;
-
- function handleRunWithPlaceholders() {
- onSendMessage?.(
- `Run the agent "${agentName}" with placeholder/example values so I can test it.`,
- );
- }
-
- function handleRunCreated(execution: GraphExecutionMeta) {
- onSendMessage?.(
- `I've started the agent "${agentName}". The execution ID is ${execution.id}. Please monitor its progress and let me know when it completes.`,
- );
- }
-
- function handleScheduleCreated(schedule: GraphExecutionJobInfo) {
- const scheduleInfo = schedule.cron
- ? `with cron schedule "${schedule.cron}"`
- : "to run on the specified schedule";
- onSendMessage?.(
- `I've scheduled the agent "${agentName}" ${scheduleInfo}. The schedule ID is ${schedule.id}.`,
- );
- }
-
- return (
- <AIChatBubble>
- <div className="flex flex-col gap-4">
- <div className="flex items-center gap-2">
- <div className="flex h-8 w-8 items-center justify-center rounded-full bg-green-100">
- <CheckCircleIcon
- size={18}
- weight="fill"
- className="text-green-600"
- />
- </div>
- <div>
- <Text variant="body-medium" className="text-neutral-900">
- Agent Created Successfully
- </Text>
- <Text variant="small" className="text-neutral-500">
- &quot;{agentName}&quot; is ready to test
- </Text>
- </div>
- </div>
-
- <div className="flex flex-col gap-2">
- <Text variant="small-medium" className="text-neutral-700">
- Ready to test?
- </Text>
- <div className="flex flex-wrap gap-2">
- <Button
- variant="outline"
- size="small"
- onClick={handleRunWithPlaceholders}
- className="gap-2"
- >
- <PlayIcon size={16} />
- Run with example values
- </Button>
- {libraryAgent ? (
- <RunAgentModal
- triggerSlot={
- <Button variant="outline" size="small" className="gap-2">
- <PencilLineIcon size={16} />
- Run with my inputs
- </Button>
- }
- agent={libraryAgent}
- onRunCreated={handleRunCreated}
- onScheduleCreated={handleScheduleCreated}
- />
- ) : (
- <Button
- variant="outline"
- size="small"
- loading={isLoading}
- disabled
- className="gap-2"
- >
- <PencilLineIcon size={16} />
- Run with my inputs
- </Button>
- )}
- </div>
- <Text variant="small" className="text-neutral-500">
- or just ask me
- </Text>
- </div>
- </div>
- </AIChatBubble>
- );
-}
diff --git a/autogpt_platform/frontend/src/components/contextual/Chat/components/ToolResponseMessage/ToolResponseMessage.tsx b/autogpt_platform/frontend/src/components/contextual/Chat/components/ToolResponseMessage/ToolResponseMessage.tsx
deleted file mode 100644
index 53d5f1ef96..0000000000
--- a/autogpt_platform/frontend/src/components/contextual/Chat/components/ToolResponseMessage/ToolResponseMessage.tsx
+++ /dev/null
@@ -1,69 +0,0 @@
-import { Text } from "@/components/atoms/Text/Text";
-import { cn } from "@/lib/utils";
-import type { ToolResult } from "@/types/chat";
-import { WarningCircleIcon } from "@phosphor-icons/react";
-import { AgentCreatedPrompt } from "./AgentCreatedPrompt";
-import { AIChatBubble } from "../AIChatBubble/AIChatBubble";
-import { MarkdownContent } from "../MarkdownContent/MarkdownContent";
-import {
- formatToolResponse,
- getErrorMessage,
- isAgentSavedResponse,
- isErrorResponse,
-} from "./helpers";
-
-export interface ToolResponseMessageProps {
- toolId?: string;
- toolName: string;
- result?: ToolResult;
- success?: boolean;
- className?: string;
- onSendMessage?: (content: string) => void;
-}
-
-export function ToolResponseMessage({
- toolId: _toolId,
- toolName,
- result,
- success: _success,
- className,
- onSendMessage,
-}: ToolResponseMessageProps) {
- if (isErrorResponse(result)) {
- const errorMessage = getErrorMessage(result);
- return (
- <AIChatBubble className={className}>
- <div className="flex items-center gap-2">
- <WarningCircleIcon
- size={14}
- weight="regular"
- className="shrink-0 text-neutral-400"
- />
- <Text variant="small" className={cn("text-xs text-neutral-500")}>
- {errorMessage}
- </Text>
- </div>
- </AIChatBubble>
- );
- }
-
- // Check for agent_saved response - show special prompt
- const agentSavedData = isAgentSavedResponse(result);
- if (agentSavedData.isSaved) {
- return (
- <AgentCreatedPrompt
- agentName={agentSavedData.agentName}
- libraryAgentId={agentSavedData.libraryAgentId}
- onSendMessage={onSendMessage}
- />
- );
- }
-
- const formattedText = formatToolResponse(result, toolName);
-
- return (
- <AIChatBubble className={className}>
- <MarkdownContent content={formattedText} />
- </AIChatBubble>
- );
-}
diff --git a/autogpt_platform/frontend/src/components/contextual/Chat/components/ToolResponseMessage/helpers.ts b/autogpt_platform/frontend/src/components/contextual/Chat/components/ToolResponseMessage/helpers.ts
deleted file mode 100644
index 63da171f54..0000000000
--- a/autogpt_platform/frontend/src/components/contextual/Chat/components/ToolResponseMessage/helpers.ts
+++ /dev/null
@@ -1,461 +0,0 @@
-function stripInternalReasoning(content: string): string {
- return content
- .replace(/<internal_reasoning>[\s\S]*?<\/internal_reasoning>/gi, "")
- .replace(/<thinking>[\s\S]*?<\/thinking>/gi, "")
- .replace(/\n{3,}/g, "\n\n")
- .trim();
-}
-
-export interface AgentSavedData {
- isSaved: boolean;
- agentName: string;
- agentId: string;
- libraryAgentId: string;
- libraryAgentLink: string;
-}
-
-export function isAgentSavedResponse(result: unknown): AgentSavedData {
- if (typeof result !== "object" || result === null) {
- return {
- isSaved: false,
- agentName: "",
- agentId: "",
- libraryAgentId: "",
- libraryAgentLink: "",
- };
- }
- const response = result as Record<string, unknown>;
- if (response.type === "agent_saved") {
- return {
- isSaved: true,
- agentName: (response.agent_name as string) || "Agent",
- agentId: (response.agent_id as string) || "",
- libraryAgentId: (response.library_agent_id as string) || "",
- libraryAgentLink: (response.library_agent_link as string) || "",
- };
- }
- return {
- isSaved: false,
- agentName: "",
- agentId: "",
- libraryAgentId: "",
- libraryAgentLink: "",
- };
-}
-
-export function isErrorResponse(result: unknown): boolean {
- if (typeof result === "string") {
- const lower = result.toLowerCase();
- return (
- lower.startsWith("error:") ||
- lower.includes("not found") ||
- lower.includes("does not exist") ||
- lower.includes("failed to") ||
- lower.includes("unable to")
- );
- }
- if (typeof result === "object" && result !== null) {
- const response = result as Record<string, unknown>;
- return response.type === "error" || response.error !== undefined;
- }
- return false;
-}
-
-export function getErrorMessage(result: unknown): string {
- if (typeof result === "string") {
- return stripInternalReasoning(result.replace(/^error:\s*/i, ""));
- }
- if (typeof result === "object" && result !== null) {
- const response = result as Record<string, unknown>;
- if (response.message)
- return stripInternalReasoning(String(response.message));
- if (response.error) return stripInternalReasoning(String(response.error));
- }
- return "An error occurred";
-}
-
-/**
- * Check if a value is a workspace file reference.
- * Format: workspace://{fileId} or workspace://{fileId}#{mimeType}
- */
-function isWorkspaceRef(value: unknown): value is string {
- return typeof value === "string" && value.startsWith("workspace://");
-}
-
-/**
- * Extract MIME type from a workspace reference fragment.
- * e.g., "workspace://abc123#video/mp4" → "video/mp4"
- * Returns undefined if no fragment is present.
- */
-function getWorkspaceMimeType(value: string): string | undefined {
- const hashIndex = value.indexOf("#");
- if (hashIndex === -1) return undefined;
- return value.slice(hashIndex + 1) || undefined;
-}
-
-/**
- * Determine the media category of a workspace ref or data URI.
- * Uses the MIME type fragment on workspace refs when available,
- * falls back to output key keyword matching for older refs without it.
- */
-function getMediaCategory(
- value: string,
- outputKey?: string,
-): "video" | "image" | "audio" | "unknown" {
- // Data URIs carry their own MIME type
- if (value.startsWith("data:video/")) return "video";
- if (value.startsWith("data:image/")) return "image";
- if (value.startsWith("data:audio/")) return "audio";
-
- // Workspace refs: prefer MIME type fragment
- if (isWorkspaceRef(value)) {
- const mime = getWorkspaceMimeType(value);
- if (mime) {
- if (mime.startsWith("video/")) return "video";
- if (mime.startsWith("image/")) return "image";
- if (mime.startsWith("audio/")) return "audio";
- return "unknown";
- }
-
- // Fallback: keyword matching on output key for older refs without fragment
- if (outputKey) {
- const lowerKey = outputKey.toLowerCase();
-
- const videoKeywords = [
- "video",
- "mp4",
- "mov",
- "avi",
- "webm",
- "movie",
- "clip",
- ];
- if (videoKeywords.some((kw) => lowerKey.includes(kw))) return "video";
-
- const imageKeywords = [
- "image",
- "img",
- "photo",
- "picture",
- "thumbnail",
- "avatar",
- "icon",
- "screenshot",
- ];
- if (imageKeywords.some((kw) => lowerKey.includes(kw))) return "image";
- }
-
- // Default to image for backward compatibility
- return "image";
- }
-
- return "unknown";
-}
-
-/**
- * Format a single output value, converting workspace refs to markdown images/videos.
- * Videos use a "video:" alt-text prefix so the MarkdownContent renderer can
- * distinguish them from images and render a <video> element.
- */
-function formatOutputValue(value: unknown, outputKey?: string): string {
- if (typeof value === "string") {
- const category = getMediaCategory(value, outputKey);
-
- if (category === "video") {
- // Format with "video:" prefix so MarkdownContent renders <video>
- return `![video:${outputKey || "Video"}](${value})`;
- }
-
- if (category === "image") {
- return `![${outputKey || "Generated image"}](${value})`;
- }
-
- // For audio, unknown workspace refs, data URIs, etc. - return as-is
- return value;
- }
-
- if (Array.isArray(value)) {
- return value
- .map((item, idx) => formatOutputValue(item, `${outputKey}_${idx}`))
- .join("\n\n");
- }
-
- if (typeof value === "object" && value !== null) {
- return JSON.stringify(value, null, 2);
- }
-
- return String(value);
-}
-
-function getToolCompletionPhrase(toolName: string): string {
- const toolCompletionPhrases: Record<string, string> = {
- add_understanding: "Updated your business information",
- create_agent: "Created the agent",
- edit_agent: "Updated the agent",
- find_agent: "Found agents in the marketplace",
- find_block: "Found blocks",
- find_library_agent: "Found library agents",
- run_agent: "Started agent execution",
- run_block: "Executed the block",
- view_agent_output: "Retrieved agent output",
- search_docs: "Found documentation",
- get_doc_page: "Loaded documentation page",
- };
-
- // Return mapped phrase or generate human-friendly fallback
- return (
- toolCompletionPhrases[toolName] ||
- `Completed ${toolName.replace(/_/g, " ").replace("...", "")}`
- );
-}
-
-export function formatToolResponse(result: unknown, toolName: string): string {
- if (typeof result === "string") {
- const trimmed = result.trim();
- if (trimmed.startsWith("{") && trimmed.endsWith("}")) {
- try {
- const parsed = JSON.parse(trimmed);
- return formatToolResponse(parsed, toolName);
- } catch {
- return stripInternalReasoning(trimmed);
- }
- }
- return stripInternalReasoning(result);
- }
-
- if (typeof result !== "object" || result === null) {
- return String(result);
- }
-
- const response = result as Record<string, unknown>;
-
- // Handle different response types
- const responseType = response.type as string | undefined;
-
- if (!responseType) {
- if (response.message) {
- return String(response.message);
- }
- return getToolCompletionPhrase(toolName);
- }
-
- switch (responseType) {
- case "agents_found":
- const agents = (response.agents as Array<{ name: string }>) || [];
- const count =
- typeof response.count === "number" && !isNaN(response.count)
- ? response.count
- : agents.length;
- if (count === 0) {
- return "No agents found matching your search.";
- }
- return `Found ${count} agent${count === 1 ? "" : "s"}: ${agents
- .slice(0, 3)
- .map((a) => a.name)
- .join(", ")}${count > 3 ? ` and ${count - 3} more` : ""}`;
-
- case "agent_details":
- const agent = response.agent as { name: string; description?: string };
- if (agent) {
- return `Agent: ${agent.name}${agent.description ? `\n\n${agent.description}` : ""}`;
- }
- break;
-
- case "block_list":
- const blocks = (response.blocks as Array<{ name: string }>) || [];
- const blockCount =
- typeof response.count === "number" && !isNaN(response.count)
- ? response.count
- : blocks.length;
- if (blockCount === 0) {
- return "No blocks found matching your search.";
- }
- return `Found ${blockCount} block${blockCount === 1 ? "" : "s"}: ${blocks
- .slice(0, 3)
- .map((b) => b.name)
- .join(", ")}${blockCount > 3 ? ` and ${blockCount - 3} more` : ""}`;
-
- case "block_output":
- const blockName = (response.block_name as string) || "Block";
- const outputs = response.outputs as Record<string, unknown[]> | undefined;
- if (outputs && Object.keys(outputs).length > 0) {
- const formattedOutputs: string[] = [];
-
- for (const [key, values] of Object.entries(outputs)) {
- if (!Array.isArray(values) || values.length === 0) continue;
-
- // Format each value in the output array
- for (const value of values) {
- const formatted = formatOutputValue(value, key);
- if (formatted) {
- formattedOutputs.push(formatted);
- }
- }
- }
-
- if (formattedOutputs.length > 0) {
- return `${blockName} executed successfully.\n\n${formattedOutputs.join("\n\n")}`;
- }
- return `${blockName} executed successfully.`;
- }
- return `${blockName} executed successfully.`;
-
- case "doc_search_results":
- const docResults = (response.results as Array<{ title: string }>) || [];
- const docCount =
- typeof response.count === "number" && !isNaN(response.count)
- ? response.count
- : docResults.length;
- if (docCount === 0) {
- return "No documentation found matching your search.";
- }
- return `Found ${docCount} documentation result${docCount === 1 ? "" : "s"}: ${docResults
- .slice(0, 3)
- .map((r) => r.title)
- .join(", ")}${docCount > 3 ? ` and ${docCount - 3} more` : ""}`;
-
- case "doc_page":
- const title = (response.title as string) || "Documentation";
- const content = (response.content as string) || "";
- if (content) {
- const preview = content.substring(0, 200).trim();
- return `${title}\n\n${preview}${content.length > 200 ? "..." : ""}`;
- }
- return title;
-
- case "understanding_updated":
- const currentUnderstanding = response.current_understanding as
- | Record<string, unknown>
- | undefined;
- const fields = (response.updated_fields as string[]) || [];
-
- if (response.message && typeof response.message === "string") {
- let message = response.message;
- if (currentUnderstanding) {
- for (const [key, value] of Object.entries(currentUnderstanding)) {
- if (value !== null && value !== undefined && value !== "") {
- const placeholder = key;
- const actualValue = String(value);
- message = message.replace(
- new RegExp(`\\b${placeholder}\\b`, "g"),
- actualValue,
- );
- }
- }
- }
- return message;
- }
-
- if (
- currentUnderstanding &&
- Object.keys(currentUnderstanding).length > 0
- ) {
- const understandingEntries = Object.entries(currentUnderstanding)
- .filter(
- ([_, value]) =>
- value !== null && value !== undefined && value !== "",
- )
- .map(([key, value]) => {
- if (key === "user_name" && typeof value === "string") {
- return `Updated information for ${value}`;
- }
- return `${key}: ${String(value)}`;
- });
- if (understandingEntries.length > 0) {
- return understandingEntries[0];
- }
- }
- if (fields.length > 0) {
- return `Updated business information: ${fields.join(", ")}`;
- }
- return "Updated your business information.";
-
- case "agent_saved":
- const agentName = (response.agent_name as string) || "Agent";
- return `Successfully saved "${agentName}" to your library.`;
-
- case "agent_preview":
- const previewAgentName = (response.agent_name as string) || "Agent";
- const nodeCount = (response.node_count as number) || 0;
- const linkCount = (response.link_count as number) || 0;
- const description = (response.description as string) || "";
- let previewText = `Preview: "${previewAgentName}"`;
- if (description) {
- previewText += `\n\n${description}`;
- }
- previewText += `\n\n${nodeCount} node${nodeCount === 1 ? "" : "s"}, ${linkCount} link${linkCount === 1 ? "" : "s"}`;
- return previewText;
-
- case "clarification_needed":
- const questions =
- (response.questions as Array<{ question: string }>) || [];
- if (questions.length === 0) {
- return response.message
- ? String(response.message)
- : "I need more information to proceed.";
- }
- if (questions.length === 1) {
- return questions[0].question;
- }
- return `I need clarification on ${questions.length} points:\n\n${questions
- .map((q, i) => `${i + 1}. ${q.question}`)
- .join("\n")}`;
-
- case "agent_output":
- if (response.message) {
- return String(response.message);
- }
- const outputAgentName = (response.agent_name as string) || "Agent";
- const execution = response.execution as
- | {
- status?: string;
- outputs?: Record<string, unknown>;
- }
- | undefined;
- if (execution) {
- const status = execution.status || "completed";
- const outputs = execution.outputs || {};
- const outputKeys = Object.keys(outputs);
- if (outputKeys.length > 0) {
- return `${outputAgentName} execution ${status}. Outputs: ${outputKeys.join(", ")}`;
- }
- return `${outputAgentName} execution ${status}.`;
- }
- return `${outputAgentName} output retrieved.`;
-
- case "execution_started":
- const execAgentName = (response.graph_name as string) || "Agent";
- if (response.message) {
- return String(response.message);
- }
- return `Started execution of "${execAgentName}".`;
-
- case "error":
- const errorMsg =
- (response.message as string) || response.error || "An error occurred";
- return stripInternalReasoning(String(errorMsg));
-
- case "no_results":
- const suggestions = (response.suggestions as string[]) || [];
- let noResultsText = (response.message as string) || "No results found.";
- if (suggestions.length > 0) {
- noResultsText += `\n\nSuggestions: ${suggestions.join(", ")}`;
- }
- return noResultsText;
-
- default:
- // Try to extract a message field
- if (response.message) {
- return String(response.message);
- }
- // Fallback: try to stringify nicely
- if (Object.keys(response).length === 0) {
- return getToolCompletionPhrase(toolName);
- }
- // If we have a response object but no recognized type, try to format it nicely
- // Don't return raw JSON - return a completion phrase instead
- return getToolCompletionPhrase(toolName);
- }
-
- return getToolCompletionPhrase(toolName);
-}
diff --git a/autogpt_platform/frontend/src/components/contextual/Chat/components/UserChatBubble/UserChatBubble.tsx b/autogpt_platform/frontend/src/components/contextual/Chat/components/UserChatBubble/UserChatBubble.tsx
deleted file mode 100644
index 39a6cb36ad..0000000000
--- a/autogpt_platform/frontend/src/components/contextual/Chat/components/UserChatBubble/UserChatBubble.tsx
+++ /dev/null
@@ -1,25 +0,0 @@
-import { cn } from "@/lib/utils";
-import { ReactNode } from "react";
-
-export interface UserChatBubbleProps {
- children: ReactNode;
- className?: string;
-}
-
-export function UserChatBubble({ children, className }: UserChatBubbleProps) {
- return (
- <div
- className={cn(
- "group relative min-w-20 overflow-hidden rounded-xl bg-purple-100 px-3 text-left text-[1rem] leading-relaxed transition-all duration-500 ease-in-out",
- className,
- )}
- style={{
- borderBottomRightRadius: 0,
- }}
- >
- <div className="relative z-10 text-slate-900 transition-all duration-500 ease-in-out">
- {children}
- </div>
- </div>
- );
-}
diff --git a/autogpt_platform/frontend/src/components/contextual/Chat/stream-executor.ts b/autogpt_platform/frontend/src/components/contextual/Chat/stream-executor.ts
deleted file mode 100644
index 8f4c8f9fec..0000000000
--- a/autogpt_platform/frontend/src/components/contextual/Chat/stream-executor.ts
+++ /dev/null
@@ -1,255 +0,0 @@
-import { INITIAL_STREAM_ID } from "./chat-constants";
-import type {
- ActiveStream,
- StreamChunk,
- VercelStreamChunk,
-} from "./chat-types";
-import {
- INITIAL_RETRY_DELAY,
- MAX_RETRIES,
- normalizeStreamChunk,
- parseSSELine,
-} from "./stream-utils";
-
-function notifySubscribers(
- stream: ActiveStream,
- chunk: StreamChunk,
- skipStore = false,
-) {
- if (!skipStore) {
- stream.chunks.push(chunk);
- }
- for (const callback of stream.onChunkCallbacks) {
- try {
- callback(chunk);
- } catch (err) {
- console.warn("[StreamExecutor] Subscriber callback error:", err);
- }
- }
-}
-
-interface StreamExecutionOptions {
- stream: ActiveStream;
- mode: "new" | "reconnect";
- message?: string;
- isUserMessage?: boolean;
- context?: { url: string; content: string };
- taskId?: string;
- lastMessageId?: string;
- retryCount?: number;
-}
-
-async function executeStreamInternal(
- options: StreamExecutionOptions,
-): Promise<void> {
- const {
- stream,
- mode,
- message,
- isUserMessage,
- context,
- taskId,
- lastMessageId = INITIAL_STREAM_ID,
- retryCount = 0,
- } = options;
-
- const { sessionId, abortController } = stream;
- const isReconnect = mode === "reconnect";
-
- if (isReconnect) {
- if (!taskId) {
- throw new Error("taskId is required for reconnect mode");
- }
- if (lastMessageId === null || lastMessageId === undefined) {
- throw new Error("lastMessageId is required for reconnect mode");
- }
- } else {
- if (!message) {
- throw new Error("message is required for new stream mode");
- }
- if (isUserMessage === undefined) {
- throw new Error("isUserMessage is required for new stream mode");
- }
- }
-
- try {
- let url: string;
- let fetchOptions: RequestInit;
-
- if (isReconnect) {
- url = `/api/chat/tasks/${taskId}/stream?last_message_id=${encodeURIComponent(lastMessageId)}`;
- fetchOptions = {
- method: "GET",
- headers: {
- Accept: "text/event-stream",
- },
- signal: abortController.signal,
- };
- } else {
- url = `/api/chat/sessions/${sessionId}/stream`;
- fetchOptions = {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- Accept: "text/event-stream",
- },
- body: JSON.stringify({
- message,
- is_user_message: isUserMessage,
- context: context || null,
- }),
- signal: abortController.signal,
- };
- }
-
- const response = await fetch(url, fetchOptions);
-
- if (!response.ok) {
- const errorText = await response.text();
- let errorCode: string | undefined;
- let errorMessage = errorText || `HTTP ${response.status}`;
- try {
- const parsed = JSON.parse(errorText);
- if (parsed.detail) {
- const detail =
- typeof parsed.detail === "string"
- ? parsed.detail
- : parsed.detail.message || JSON.stringify(parsed.detail);
- errorMessage = detail;
- errorCode =
- typeof parsed.detail === "object" ? parsed.detail.code : undefined;
- }
- } catch {}
-
- const isPermanentError =
- isReconnect &&
- (response.status === 404 ||
- response.status === 403 ||
- response.status === 410);
-
- const error = new Error(errorMessage) as Error & {
- status?: number;
- isPermanent?: boolean;
- taskErrorCode?: string;
- };
- error.status = response.status;
- error.isPermanent = isPermanentError;
- error.taskErrorCode = errorCode;
- throw error;
- }
-
- if (!response.body) {
- throw new Error("Response body is null");
- }
-
- const reader = response.body.getReader();
- const decoder = new TextDecoder();
- let buffer = "";
-
- while (true) {
- const { done, value } = await reader.read();
-
- if (done) {
- notifySubscribers(stream, { type: "stream_end" });
- stream.status = "completed";
- return;
- }
-
- buffer += decoder.decode(value, { stream: true });
- const lines = buffer.split("\n");
- buffer = lines.pop() || "";
-
- for (const line of lines) {
- const data = parseSSELine(line);
- if (data !== null) {
- if (data === "[DONE]") {
- notifySubscribers(stream, { type: "stream_end" });
- stream.status = "completed";
- return;
- }
-
- try {
- const rawChunk = JSON.parse(data) as
- | StreamChunk
- | VercelStreamChunk;
- const chunk = normalizeStreamChunk(rawChunk);
- if (!chunk) continue;
-
- notifySubscribers(stream, chunk);
-
- if (chunk.type === "stream_end") {
- stream.status = "completed";
- return;
- }
-
- if (chunk.type === "error") {
- stream.status = "error";
- stream.error = new Error(
- chunk.message || chunk.content || "Stream error",
- );
- return;
- }
- } catch {}
- }
- }
- }
- } catch (err) {
- if (err instanceof Error && err.name === "AbortError") {
- notifySubscribers(stream, { type: "stream_end" });
- stream.status = "completed";
- return;
- }
-
- const isPermanentError =
- err instanceof Error &&
- (err as Error & { isPermanent?: boolean }).isPermanent;
-
- if (!isPermanentError && retryCount < MAX_RETRIES) {
- const retryDelay = INITIAL_RETRY_DELAY * Math.pow(2, retryCount);
- await new Promise((resolve) => setTimeout(resolve, retryDelay));
- return executeStreamInternal({
- ...options,
- retryCount: retryCount + 1,
- });
- }
-
- stream.status = "error";
- stream.error = err instanceof Error ? err : new Error("Stream failed");
- notifySubscribers(stream, {
- type: "error",
- message: stream.error.message,
- });
- }
-}
-
-export async function executeStream(
- stream: ActiveStream,
- message: string,
- isUserMessage: boolean,
- context?: { url: string; content: string },
- retryCount: number = 0,
-): Promise<void> {
- return executeStreamInternal({
- stream,
- mode: "new",
- message,
- isUserMessage,
- context,
- retryCount,
- });
-}
-
-export async function executeTaskReconnect(
- stream: ActiveStream,
- taskId: string,
- lastMessageId: string = INITIAL_STREAM_ID,
- retryCount: number = 0,
-): Promise<void> {
- return executeStreamInternal({
- stream,
- mode: "reconnect",
- taskId,
- lastMessageId,
- retryCount,
- });
-}
diff --git a/autogpt_platform/frontend/src/components/contextual/Chat/stream-utils.ts b/autogpt_platform/frontend/src/components/contextual/Chat/stream-utils.ts
deleted file mode 100644
index 253e47b874..0000000000
--- a/autogpt_platform/frontend/src/components/contextual/Chat/stream-utils.ts
+++ /dev/null
@@ -1,89 +0,0 @@
-import type { ToolArguments, ToolResult } from "@/types/chat";
-import type { StreamChunk, VercelStreamChunk } from "./chat-types";
-
-const LEGACY_STREAM_TYPES = new Set<StreamChunk["type"]>([
- "text_chunk",
- "text_ended",
- "tool_call",
- "tool_call_start",
- "tool_response",
- "login_needed",
- "need_login",
- "credentials_needed",
- "error",
- "usage",
- "stream_end",
-]);
-
-export function isLegacyStreamChunk(
- chunk: StreamChunk | VercelStreamChunk,
-): chunk is StreamChunk {
- return LEGACY_STREAM_TYPES.has(chunk.type as StreamChunk["type"]);
-}
-
-export function normalizeStreamChunk(
- chunk: StreamChunk | VercelStreamChunk,
-): StreamChunk | null {
- if (isLegacyStreamChunk(chunk)) return chunk;
-
- switch (chunk.type) {
- case "text-delta":
- // Vercel AI SDK sends "delta" for text content
- return { type: "text_chunk", content: chunk.delta };
- case "text-end":
- return { type: "text_ended" };
- case "tool-input-available":
- return {
- type: "tool_call_start",
- tool_id: chunk.toolCallId,
- tool_name: chunk.toolName,
- arguments: chunk.input as ToolArguments,
- };
- case "tool-output-available":
- return {
- type: "tool_response",
- tool_id: chunk.toolCallId,
- tool_name: chunk.toolName,
- result: chunk.output as ToolResult,
- success: chunk.success ?? true,
- };
- case "usage":
- return {
- type: "usage",
- promptTokens: chunk.promptTokens,
- completionTokens: chunk.completionTokens,
- totalTokens: chunk.totalTokens,
- };
- case "error":
- return {
- type: "error",
- message: chunk.errorText,
- code: chunk.code,
- details: chunk.details,
- };
- case "finish":
- return { type: "stream_end" };
- case "start":
- // Start event with optional taskId for reconnection
- return chunk.taskId
- ? { type: "stream_start", taskId: chunk.taskId }
- : null;
- case "text-start":
- return null;
- case "tool-input-start":
- return {
- type: "tool_call_start",
- tool_id: chunk.toolCallId,
- tool_name: chunk.toolName,
- arguments: {},
- };
- }
-}
-
-export const MAX_RETRIES = 3;
-export const INITIAL_RETRY_DELAY = 1000;
-
-export function parseSSELine(line: string): string | null {
- if (line.startsWith("data: ")) return line.slice(6);
- return null;
-}
diff --git a/autogpt_platform/frontend/src/components/contextual/Chat/useChat.ts b/autogpt_platform/frontend/src/components/contextual/Chat/useChat.ts
deleted file mode 100644
index 124301abc4..0000000000
--- a/autogpt_platform/frontend/src/components/contextual/Chat/useChat.ts
+++ /dev/null
@@ -1,100 +0,0 @@
-"use client";
-
-import { useSupabase } from "@/lib/supabase/hooks/useSupabase";
-import { useEffect, useRef, useState } from "react";
-import { useChatSession } from "./useChatSession";
-import { useChatStream } from "./useChatStream";
-
-interface UseChatArgs {
- urlSessionId?: string | null;
-}
-
-export function useChat({ urlSessionId }: UseChatArgs = {}) {
- const hasClaimedSessionRef = useRef(false);
- const { user } = useSupabase();
- const { sendMessage: sendStreamMessage } = useChatStream();
- const [showLoader, setShowLoader] = useState(false);
- const {
- session,
- sessionId: sessionIdFromHook,
- messages,
- isLoading,
- isCreating,
- error,
- isSessionNotFound,
- createSession,
- claimSession,
- clearSession: clearSessionBase,
- loadSession,
- startPollingForOperation,
- } = useChatSession({
- urlSessionId,
- autoCreate: false,
- });
-
- useEffect(
- function autoClaimSession() {
- if (
- session &&
- !session.user_id &&
- user &&
- !hasClaimedSessionRef.current &&
- !isLoading &&
- sessionIdFromHook
- ) {
- hasClaimedSessionRef.current = true;
- claimSession(sessionIdFromHook)
- .then(() => {
- sendStreamMessage(
- sessionIdFromHook,
- "User has successfully logged in.",
- () => {},
- false,
- ).catch(() => {});
- })
- .catch(() => {
- hasClaimedSessionRef.current = false;
- });
- }
- },
- [
- session,
- user,
- isLoading,
- sessionIdFromHook,
- claimSession,
- sendStreamMessage,
- ],
- );
-
- useEffect(
- function showLoaderWithDelay() {
- if (isLoading || isCreating) {
- const timer = setTimeout(() => setShowLoader(true), 300);
- return () => clearTimeout(timer);
- }
- setShowLoader(false);
- },
- [isLoading, isCreating],
- );
-
- function clearSession() {
- clearSessionBase();
- hasClaimedSessionRef.current = false;
- }
-
- return {
- session,
- messages,
- isLoading,
- isCreating,
- error,
- isSessionNotFound,
- createSession,
- clearSession,
- loadSession,
- sessionId: sessionIdFromHook,
- showLoader,
- startPollingForOperation,
- };
-}
diff --git a/autogpt_platform/frontend/src/components/contextual/Chat/useChatSession.ts b/autogpt_platform/frontend/src/components/contextual/Chat/useChatSession.ts
deleted file mode 100644
index 936a49936c..0000000000
--- a/autogpt_platform/frontend/src/components/contextual/Chat/useChatSession.ts
+++ /dev/null
@@ -1,385 +0,0 @@
-import {
- getGetV2GetSessionQueryKey,
- getGetV2GetSessionQueryOptions,
- getGetV2ListSessionsQueryKey,
- postV2CreateSession,
- useGetV2GetSession,
- usePatchV2SessionAssignUser,
- usePostV2CreateSession,
-} from "@/app/api/__generated__/endpoints/chat/chat";
-import type { SessionDetailResponse } from "@/app/api/__generated__/models/sessionDetailResponse";
-import { okData } from "@/app/api/helpers";
-import { isValidUUID } from "@/lib/utils";
-import { useQueryClient } from "@tanstack/react-query";
-import { useEffect, useMemo, useRef, useState } from "react";
-import { toast } from "sonner";
-
-interface UseChatSessionArgs {
- urlSessionId?: string | null;
- autoCreate?: boolean;
-}
-
-export function useChatSession({
- urlSessionId,
- autoCreate = false,
-}: UseChatSessionArgs = {}) {
- const queryClient = useQueryClient();
- const [sessionId, setSessionId] = useState<string | null>(null);
- const [error, setError] = useState<Error | null>(null);
- const justCreatedSessionIdRef = useRef<string | null>(null);
-
- useEffect(() => {
- if (urlSessionId) {
- if (!isValidUUID(urlSessionId)) {
- console.error("Invalid session ID format:", urlSessionId);
- toast.error("Invalid session ID", {
- description:
- "The session ID in the URL is not valid. Starting a new session...",
- });
- setSessionId(null);
- return;
- }
- setSessionId(urlSessionId);
- } else if (autoCreate) {
- setSessionId(null);
- } else {
- setSessionId(null);
- }
- }, [urlSessionId, autoCreate]);
-
- const { isPending: isCreating, error: createError } =
- usePostV2CreateSession();
-
- const {
- data: sessionData,
- isLoading: isLoadingSession,
- error: loadError,
- refetch,
- } = useGetV2GetSession(sessionId || "", {
- query: {
- enabled: !!sessionId,
- select: okData,
- staleTime: 0,
- retry: shouldRetrySessionLoad,
- retryDelay: getSessionRetryDelay,
- },
- });
-
- const { mutateAsync: claimSessionMutation } = usePatchV2SessionAssignUser();
-
- const session = useMemo(() => {
- if (sessionData) return sessionData;
-
- if (sessionId && justCreatedSessionIdRef.current === sessionId) {
- return {
- id: sessionId,
- user_id: null,
- messages: [],
- created_at: new Date().toISOString(),
- updated_at: new Date().toISOString(),
- } as SessionDetailResponse;
- }
- return null;
- }, [sessionData, sessionId]);
-
- const messages = session?.messages || [];
- const isLoading = isCreating || isLoadingSession;
-
- useEffect(() => {
- if (createError) {
- setError(
- createError instanceof Error
- ? createError
- : new Error("Failed to create session"),
- );
- } else if (loadError) {
- setError(
- loadError instanceof Error
- ? loadError
- : new Error("Failed to load session"),
- );
- } else {
- setError(null);
- }
- }, [createError, loadError]);
-
- // Track if we should be polling (set by external callers when they receive operation_started via SSE)
- const [forcePolling, setForcePolling] = useState(false);
- // Track if we've seen server acknowledge the pending operation (to avoid clearing forcePolling prematurely)
- const hasSeenServerPendingRef = useRef(false);
-
- // Check if there are any pending operations in the messages
- // Must check all operation types: operation_pending, operation_started, operation_in_progress
- const hasPendingOperationsFromServer = useMemo(() => {
- if (!messages || messages.length === 0) return false;
- const pendingTypes = new Set([
- "operation_pending",
- "operation_in_progress",
- "operation_started",
- ]);
- return messages.some((msg) => {
- if (msg.role !== "tool" || !msg.content) return false;
- try {
- const content =
- typeof msg.content === "string"
- ? JSON.parse(msg.content)
- : msg.content;
- return pendingTypes.has(content?.type);
- } catch {
- return false;
- }
- });
- }, [messages]);
-
- // Track when server has acknowledged the pending operation
- useEffect(() => {
- if (hasPendingOperationsFromServer) {
- hasSeenServerPendingRef.current = true;
- }
- }, [hasPendingOperationsFromServer]);
-
- // Combined: poll if server has pending ops OR if we received operation_started via SSE
- const hasPendingOperations = hasPendingOperationsFromServer || forcePolling;
-
- // Clear forcePolling only after server has acknowledged AND completed the operation
- useEffect(() => {
- if (
- forcePolling &&
- !hasPendingOperationsFromServer &&
- hasSeenServerPendingRef.current
- ) {
- // Server acknowledged the operation and it's now complete
- setForcePolling(false);
- hasSeenServerPendingRef.current = false;
- }
- }, [forcePolling, hasPendingOperationsFromServer]);
-
- // Function to trigger polling (called when operation_started is received via SSE)
- function startPollingForOperation() {
- setForcePolling(true);
- hasSeenServerPendingRef.current = false; // Reset for new operation
- }
-
- // Refresh sessions list when a pending operation completes
- // (hasPendingOperations transitions from true to false)
- const prevHasPendingOperationsRef = useRef(hasPendingOperations);
- useEffect(
- function refreshSessionsListOnOperationComplete() {
- const wasHasPending = prevHasPendingOperationsRef.current;
- prevHasPendingOperationsRef.current = hasPendingOperations;
-
- // Only invalidate when transitioning from pending to not pending
- if (wasHasPending && !hasPendingOperations && sessionId) {
- queryClient.invalidateQueries({
- queryKey: getGetV2ListSessionsQueryKey(),
- });
- }
- },
- [hasPendingOperations, sessionId, queryClient],
- );
-
- // Poll for updates when there are pending operations
- // Backoff: 2s, 4s, 6s, 8s, 10s, ... up to 30s max
- const pollAttemptRef = useRef(0);
- const hasPendingOperationsRef = useRef(hasPendingOperations);
- hasPendingOperationsRef.current = hasPendingOperations;
-
- useEffect(
- function pollForPendingOperations() {
- if (!sessionId || !hasPendingOperations) {
- pollAttemptRef.current = 0;
- return;
- }
-
- let cancelled = false;
- let timeoutId: ReturnType<typeof setTimeout> | null = null;
-
- function schedule() {
- // 2s, 4s, 6s, 8s, 10s, ... 30s (max)
- const delay = Math.min((pollAttemptRef.current + 1) * 2000, 30000);
- timeoutId = setTimeout(async () => {
- if (cancelled) return;
- pollAttemptRef.current += 1;
- try {
- await refetch();
- } catch (err) {
- console.error("[useChatSession] Poll failed:", err);
- } finally {
- if (!cancelled && hasPendingOperationsRef.current) {
- schedule();
- }
- }
- }, delay);
- }
-
- schedule();
-
- return () => {
- cancelled = true;
- if (timeoutId) clearTimeout(timeoutId);
- };
- },
- [sessionId, hasPendingOperations, refetch],
- );
-
- async function createSession() {
- try {
- setError(null);
- const response = await postV2CreateSession({
- body: JSON.stringify({}),
- });
- if (response.status !== 200) {
- throw new Error("Failed to create session");
- }
- const newSessionId = response.data.id;
- setSessionId(newSessionId);
- justCreatedSessionIdRef.current = newSessionId;
- setTimeout(() => {
- if (justCreatedSessionIdRef.current === newSessionId) {
- justCreatedSessionIdRef.current = null;
- }
- }, 10000);
- return newSessionId;
- } catch (err) {
- const error =
- err instanceof Error ? err : new Error("Failed to create session");
- setError(error);
- toast.error("Failed to create chat session", {
- description: error.message,
- });
- throw error;
- }
- }
-
- async function loadSession(id: string) {
- try {
- setError(null);
- // Invalidate the query cache for this session to force a fresh fetch
- await queryClient.invalidateQueries({
- queryKey: getGetV2GetSessionQueryKey(id),
- });
- // Set sessionId after invalidation to ensure the hook refetches
- setSessionId(id);
- // Force fetch with fresh data (bypass cache)
- const queryOptions = getGetV2GetSessionQueryOptions(id, {
- query: {
- staleTime: 0, // Force fresh fetch
- retry: shouldRetrySessionLoad,
- retryDelay: getSessionRetryDelay,
- },
- });
- const result = await queryClient.fetchQuery(queryOptions);
- if (!result || ("status" in result && result.status !== 200)) {
- console.warn("Session not found on server");
- setSessionId(null);
- throw new Error("Session not found");
- }
- } catch (err) {
- const error =
- err instanceof Error ? err : new Error("Failed to load session");
- setError(error);
- throw error;
- }
- }
-
- async function refreshSession() {
- if (!sessionId) return;
- try {
- setError(null);
- await refetch();
- } catch (err) {
- const error =
- err instanceof Error ? err : new Error("Failed to refresh session");
- setError(error);
- throw error;
- }
- }
-
- async function claimSession(id: string) {
- try {
- setError(null);
- await claimSessionMutation({ sessionId: id });
- if (justCreatedSessionIdRef.current === id) {
- justCreatedSessionIdRef.current = null;
- }
- await queryClient.invalidateQueries({
- queryKey: getGetV2GetSessionQueryKey(id),
- });
- await refetch();
- toast.success("Session claimed successfully", {
- description: "Your chat history has been saved to your account",
- });
- } catch (err: unknown) {
- const error =
- err instanceof Error ? err : new Error("Failed to claim session");
- const is404 =
- (typeof err === "object" &&
- err !== null &&
- "status" in err &&
- err.status === 404) ||
- (typeof err === "object" &&
- err !== null &&
- "response" in err &&
- typeof err.response === "object" &&
- err.response !== null &&
- "status" in err.response &&
- err.response.status === 404);
- if (!is404) {
- setError(error);
- toast.error("Failed to claim session", {
- description: error.message || "Unable to claim session",
- });
- }
- throw error;
- }
- }
-
- function clearSession() {
- setSessionId(null);
- setError(null);
- justCreatedSessionIdRef.current = null;
- }
-
- return {
- session,
- sessionId,
- messages,
- isLoading,
- isCreating,
- error,
- isSessionNotFound: isNotFoundError(loadError),
- hasPendingOperations,
- createSession,
- loadSession,
- refreshSession,
- claimSession,
- clearSession,
- startPollingForOperation,
- };
-}
-
-function isNotFoundError(error: unknown): boolean {
- if (!error || typeof error !== "object") return false;
- if ("status" in error && error.status === 404) return true;
- if (
- "response" in error &&
- typeof error.response === "object" &&
- error.response !== null &&
- "status" in error.response &&
- error.response.status === 404
- ) {
- return true;
- }
- return false;
-}
-
-function shouldRetrySessionLoad(failureCount: number, error: unknown): boolean {
- if (!isNotFoundError(error)) return false;
- return failureCount <= 2;
-}
-
-function getSessionRetryDelay(attemptIndex: number): number {
- if (attemptIndex === 0) return 3000;
- if (attemptIndex === 1) return 5000;
- return 0;
-}
diff --git a/autogpt_platform/frontend/src/components/contextual/Chat/useChatStream.ts b/autogpt_platform/frontend/src/components/contextual/Chat/useChatStream.ts
deleted file mode 100644
index 5a9f637457..0000000000
--- a/autogpt_platform/frontend/src/components/contextual/Chat/useChatStream.ts
+++ /dev/null
@@ -1,115 +0,0 @@
-"use client";
-
-import { useEffect, useRef, useState } from "react";
-import { toast } from "sonner";
-import { useChatStore } from "./chat-store";
-import type { StreamChunk } from "./chat-types";
-
-export type { StreamChunk } from "./chat-types";
-
-export function useChatStream() {
- const [isStreaming, setIsStreaming] = useState(false);
- const [error, setError] = useState<Error | null>(null);
- const currentSessionIdRef = useRef<string | null>(null);
- const onChunkCallbackRef = useRef<((chunk: StreamChunk) => void) | null>(
- null,
- );
-
- const stopStream = useChatStore((s) => s.stopStream);
- const unregisterActiveSession = useChatStore(
- (s) => s.unregisterActiveSession,
- );
- const isSessionActive = useChatStore((s) => s.isSessionActive);
- const onStreamComplete = useChatStore((s) => s.onStreamComplete);
- const getCompletedStream = useChatStore((s) => s.getCompletedStream);
- const registerActiveSession = useChatStore((s) => s.registerActiveSession);
- const startStream = useChatStore((s) => s.startStream);
- const getStreamStatus = useChatStore((s) => s.getStreamStatus);
-
- function stopStreaming(sessionId?: string) {
- const targetSession = sessionId || currentSessionIdRef.current;
- if (targetSession) {
- stopStream(targetSession);
- unregisterActiveSession(targetSession);
- }
- setIsStreaming(false);
- }
-
- useEffect(() => {
- return function cleanup() {
- const sessionId = currentSessionIdRef.current;
- if (sessionId && !isSessionActive(sessionId)) {
- stopStream(sessionId);
- }
- currentSessionIdRef.current = null;
- onChunkCallbackRef.current = null;
- };
- }, []);
-
- useEffect(() => {
- const unsubscribe = onStreamComplete(
- function handleStreamComplete(completedSessionId) {
- if (completedSessionId !== currentSessionIdRef.current) return;
-
- setIsStreaming(false);
- const completed = getCompletedStream(completedSessionId);
- if (completed?.error) {
- setError(completed.error);
- }
- unregisterActiveSession(completedSessionId);
- },
- );
-
- return unsubscribe;
- }, []);
-
- async function sendMessage(
- sessionId: string,
- message: string,
- onChunk: (chunk: StreamChunk) => void,
- isUserMessage: boolean = true,
- context?: { url: string; content: string },
- ) {
- const previousSessionId = currentSessionIdRef.current;
- if (previousSessionId && previousSessionId !== sessionId) {
- stopStreaming(previousSessionId);
- }
-
- currentSessionIdRef.current = sessionId;
- onChunkCallbackRef.current = onChunk;
- setIsStreaming(true);
- setError(null);
-
- registerActiveSession(sessionId);
-
- try {
- await startStream(sessionId, message, isUserMessage, context, onChunk);
-
- const status = getStreamStatus(sessionId);
- if (status === "error") {
- const completed = getCompletedStream(sessionId);
- if (completed?.error) {
- setError(completed.error);
- toast.error("Connection Failed", {
- description: "Unable to connect to chat service. Please try again.",
- });
- throw completed.error;
- }
- }
- } catch (err) {
- const streamError =
- err instanceof Error ? err : new Error("Failed to start stream");
- setError(streamError);
- throw streamError;
- } finally {
- setIsStreaming(false);
- }
- }
-
- return {
- isStreaming,
- error,
- sendMessage,
- stopStreaming,
- };
-}
diff --git a/autogpt_platform/frontend/src/components/contextual/Chat/usePageContext.ts b/autogpt_platform/frontend/src/components/contextual/Chat/usePageContext.ts
deleted file mode 100644
index c567422a5c..0000000000
--- a/autogpt_platform/frontend/src/components/contextual/Chat/usePageContext.ts
+++ /dev/null
@@ -1,98 +0,0 @@
-import { useCallback } from "react";
-
-export interface PageContext {
- url: string;
- content: string;
-}
-
-const MAX_CONTENT_CHARS = 10000;
-
-/**
- * Hook to capture the current page context (URL + full page content)
- * Privacy-hardened: removes sensitive inputs and enforces content size limits
- */
-export function usePageContext() {
- const capturePageContext = useCallback((): PageContext => {
- if (typeof window === "undefined" || typeof document === "undefined") {
- return { url: "", content: "" };
- }
-
- const url = window.location.href;
-
- // Clone document to avoid modifying the original
- const clone = document.cloneNode(true) as Document;
-
- // Remove script, style, and noscript elements
- const scripts = clone.querySelectorAll("script, style, noscript");
- scripts.forEach((el) => el.remove());
-
- // Remove sensitive elements and their content
- const sensitiveSelectors = [
- "input",
- "textarea",
- "[contenteditable]",
- 'input[type="password"]',
- 'input[type="email"]',
- 'input[type="tel"]',
- 'input[type="search"]',
- 'input[type="hidden"]',
- "form",
- "[data-sensitive]",
- "[data-sensitive='true']",
- ];
-
- sensitiveSelectors.forEach((selector) => {
- const elements = clone.querySelectorAll(selector);
- elements.forEach((el) => {
- // For form elements, remove the entire element
- if (el.tagName === "FORM") {
- el.remove();
- } else {
- // For inputs and textareas, clear their values but keep the element structure
- if (
- el instanceof HTMLInputElement ||
- el instanceof HTMLTextAreaElement
- ) {
- el.value = "";
- el.textContent = "";
- } else {
- // For other sensitive elements, remove them entirely
- el.remove();
- }
- }
- });
- });
-
- // Strip any remaining input values that might have been missed
- const allInputs = clone.querySelectorAll("input, textarea");
- allInputs.forEach((el) => {
- if (el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement) {
- el.value = "";
- el.textContent = "";
- }
- });
-
- // Get text content from body
- const body = clone.body;
- const content = body?.textContent || body?.innerText || "";
-
- // Clean up whitespace
- let cleanedContent = content
- .replace(/\s+/g, " ")
- .replace(/\n\s*\n/g, "\n")
- .trim();
-
- // Enforce maximum content size
- if (cleanedContent.length > MAX_CONTENT_CHARS) {
- cleanedContent =
- cleanedContent.substring(0, MAX_CONTENT_CHARS) + "... [truncated]";
- }
-
- return {
- url,
- content: cleanedContent,
- };
- }, []);
-
- return { capturePageContext };
-}
diff --git a/autogpt_platform/frontend/src/components/layout/Navbar/Navbar.tsx b/autogpt_platform/frontend/src/components/layout/Navbar/Navbar.tsx
index 9997c4a51c..ce5992b4be 100644
--- a/autogpt_platform/frontend/src/components/layout/Navbar/Navbar.tsx
+++ b/autogpt_platform/frontend/src/components/layout/Navbar/Navbar.tsx
@@ -62,7 +62,7 @@ export function Navbar() {
<PreviewBanner branchName={previewBranchName} />
) : null}
<nav
- className="border-zinc-[#EFEFF0] inline-flex w-full items-center border border-[#EFEFF0] bg-[#F3F4F6]/20 p-3 backdrop-blur-[26px]"
+ className="inline-flex w-full items-center border border-none bg-[#FAFAFA] p-3 backdrop-blur-[26px]"
style={{ height: NAVBAR_HEIGHT_PX }}
>
{/* Left section */}
diff --git a/autogpt_platform/frontend/src/components/renderers/InputRenderer/FormRenderer.tsx b/autogpt_platform/frontend/src/components/renderers/InputRenderer/FormRenderer.tsx
index fc388cc343..c3a20d8cd2 100644
--- a/autogpt_platform/frontend/src/components/renderers/InputRenderer/FormRenderer.tsx
+++ b/autogpt_platform/frontend/src/components/renderers/InputRenderer/FormRenderer.tsx
@@ -30,8 +30,6 @@ export const FormRenderer = ({
return generateUiSchemaForCustomFields(preprocessedSchema, uiSchema);
}, [preprocessedSchema, uiSchema]);
- console.log("preprocessedSchema", preprocessedSchema);
-
return (
<div className={"mb-6 mt-4"} data-tutorial-id="input-handles">
<Form
diff --git a/autogpt_platform/frontend/src/components/renderers/InputRenderer/base/anyof/AnyOfField.tsx b/autogpt_platform/frontend/src/components/renderers/InputRenderer/base/anyof/AnyOfField.tsx
index 6514ce9af0..0340ff03da 100644
--- a/autogpt_platform/frontend/src/components/renderers/InputRenderer/base/anyof/AnyOfField.tsx
+++ b/autogpt_platform/frontend/src/components/renderers/InputRenderer/base/anyof/AnyOfField.tsx
@@ -1,6 +1,6 @@
import { FieldProps, getUiOptions, getWidget } from "@rjsf/utils";
import { AnyOfFieldTitle } from "./components/AnyOfFieldTitle";
-import { isEmpty } from "lodash";
+import isEmpty from "lodash/isEmpty";
import { useAnyOfField } from "./useAnyOfField";
import { cleanUpHandleId, getHandleId, updateUiOption } from "../../helpers";
import { useEdgeStore } from "@/app/(platform)/build/stores/edgeStore";
diff --git a/autogpt_platform/frontend/src/components/ui/button-group.tsx b/autogpt_platform/frontend/src/components/ui/button-group.tsx
new file mode 100644
index 0000000000..6eeace3265
--- /dev/null
+++ b/autogpt_platform/frontend/src/components/ui/button-group.tsx
@@ -0,0 +1,83 @@
+import { Slot } from "@radix-ui/react-slot";
+import { cva, type VariantProps } from "class-variance-authority";
+
+import { cn } from "@/lib/utils";
+import { Separator } from "@/components/ui/separator";
+
+const buttonGroupVariants = cva(
+ "flex w-fit items-stretch has-[>[data-slot=button-group]]:gap-2 [&>*]:focus-visible:relative [&>*]:focus-visible:z-10 has-[select[aria-hidden=true]:last-child]:[&>[data-slot=select-trigger]:last-of-type]:rounded-r-md [&>[data-slot=select-trigger]:not([class*='w-'])]:w-fit [&>input]:flex-1",
+ {
+ variants: {
+ orientation: {
+ horizontal:
+ "[&>*:not(:first-child)]:rounded-l-none [&>*:not(:first-child)]:border-l-0 [&>*:not(:last-child)]:rounded-r-none",
+ vertical:
+ "flex-col [&>*:not(:first-child)]:rounded-t-none [&>*:not(:first-child)]:border-t-0 [&>*:not(:last-child)]:rounded-b-none",
+ },
+ },
+ defaultVariants: {
+ orientation: "horizontal",
+ },
+ },
+);
+
+function ButtonGroup({
+ className,
+ orientation,
+ ...props
+}: React.ComponentProps<"div"> & VariantProps<typeof buttonGroupVariants>) {
+ return (
+ <div
+ role="group"
+ data-slot="button-group"
+ data-orientation={orientation}
+ className={cn(buttonGroupVariants({ orientation }), className)}
+ {...props}
+ />
+ );
+}
+
+function ButtonGroupText({
+ className,
+ asChild = false,
+ ...props
+}: React.ComponentProps<"div"> & {
+ asChild?: boolean;
+}) {
+ const Comp = asChild ? Slot : "div";
+
+ return (
+ <Comp
+ className={cn(
+ "shadow-xs flex items-center gap-2 rounded-md border border-neutral-200 bg-neutral-100 px-4 text-sm font-medium dark:border-neutral-800 dark:bg-neutral-800 [&_svg:not([class*='size-'])]:size-4 [&_svg]:pointer-events-none",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function ButtonGroupSeparator({
+ className,
+ orientation = "vertical",
+ ...props
+}: React.ComponentProps<typeof Separator>) {
+ return (
+ <Separator
+ data-slot="button-group-separator"
+ orientation={orientation}
+ className={cn(
+ "relative !m-0 self-stretch bg-neutral-200 data-[orientation=vertical]:h-auto dark:bg-neutral-800",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+export {
+ ButtonGroup,
+ ButtonGroupSeparator,
+ ButtonGroupText,
+ buttonGroupVariants,
+};
diff --git a/autogpt_platform/frontend/src/components/ui/button.tsx b/autogpt_platform/frontend/src/components/ui/button.tsx
new file mode 100644
index 0000000000..1cd93355cf
--- /dev/null
+++ b/autogpt_platform/frontend/src/components/ui/button.tsx
@@ -0,0 +1,59 @@
+import * as React from "react";
+import { Slot } from "@radix-ui/react-slot";
+import { cva, type VariantProps } from "class-variance-authority";
+
+import { cn } from "@/lib/utils";
+
+const buttonVariants = cva(
+ "inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-neutral-950 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0 dark:focus-visible:ring-neutral-300",
+ {
+ variants: {
+ variant: {
+ default:
+ "bg-neutral-900 text-neutral-50 shadow hover:bg-neutral-900/90 dark:bg-neutral-50 dark:text-neutral-900 dark:hover:bg-neutral-50/90",
+ destructive:
+ "bg-red-500 text-neutral-50 shadow-sm hover:bg-red-500/90 dark:bg-red-900 dark:text-neutral-50 dark:hover:bg-red-900/90",
+ outline:
+ "border border-neutral-200 bg-white shadow-sm hover:bg-neutral-100 hover:text-neutral-900 dark:border-neutral-800 dark:bg-neutral-950 dark:hover:bg-neutral-800 dark:hover:text-neutral-50",
+ secondary:
+ "bg-neutral-100 text-neutral-900 shadow-sm hover:bg-neutral-100/80 dark:bg-neutral-800 dark:text-neutral-50 dark:hover:bg-neutral-800/80",
+ ghost:
+ "hover:bg-neutral-100 hover:text-neutral-900 dark:hover:bg-neutral-800 dark:hover:text-neutral-50",
+ link: "text-neutral-900 underline-offset-4 hover:underline dark:text-neutral-50",
+ },
+ size: {
+ default: "h-9 px-4 py-2",
+ sm: "h-8 rounded-md px-3 text-xs",
+ lg: "h-10 rounded-md px-8",
+ icon: "h-9 w-9",
+ "icon-sm": "h-8 w-8",
+ },
+ },
+ defaultVariants: {
+ variant: "default",
+ size: "default",
+ },
+ },
+);
+
+export interface ButtonProps
+ extends React.ButtonHTMLAttributes<HTMLButtonElement>,
+ VariantProps<typeof buttonVariants> {
+ asChild?: boolean;
+}
+
+const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
+ ({ className, variant, size, asChild = false, ...props }, ref) => {
+ const Comp = asChild ? Slot : "button";
+ return (
+ <Comp
+ className={cn(buttonVariants({ variant, size, className }))}
+ ref={ref}
+ {...props}
+ />
+ );
+ },
+);
+Button.displayName = "Button";
+
+export { Button, buttonVariants };
diff --git a/autogpt_platform/frontend/src/components/ui/input.tsx b/autogpt_platform/frontend/src/components/ui/input.tsx
new file mode 100644
index 0000000000..34b89469ce
--- /dev/null
+++ b/autogpt_platform/frontend/src/components/ui/input.tsx
@@ -0,0 +1,22 @@
+import * as React from "react";
+
+import { cn } from "@/lib/utils";
+
+const Input = React.forwardRef<HTMLInputElement, React.ComponentProps<"input">>(
+ ({ className, type, ...props }, ref) => {
+ return (
+ <input
+ type={type}
+ className={cn(
+ "flex h-9 w-full rounded-md border border-neutral-200 bg-transparent px-3 py-1 text-base shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-neutral-950 placeholder:text-neutral-500 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-neutral-950 disabled:cursor-not-allowed disabled:opacity-50 dark:border-neutral-800 dark:file:text-neutral-50 dark:placeholder:text-neutral-400 dark:focus-visible:ring-neutral-300 md:text-sm",
+ className,
+ )}
+ ref={ref}
+ {...props}
+ />
+ );
+ },
+);
+Input.displayName = "Input";
+
+export { Input };
diff --git a/autogpt_platform/frontend/src/components/ui/separator.tsx b/autogpt_platform/frontend/src/components/ui/separator.tsx
new file mode 100644
index 0000000000..4b261e23c1
--- /dev/null
+++ b/autogpt_platform/frontend/src/components/ui/separator.tsx
@@ -0,0 +1,31 @@
+"use client";
+
+import * as React from "react";
+import * as SeparatorPrimitive from "@radix-ui/react-separator";
+
+import { cn } from "@/lib/utils";
+
+const Separator = React.forwardRef<
+ React.ElementRef<typeof SeparatorPrimitive.Root>,
+ React.ComponentPropsWithoutRef<typeof SeparatorPrimitive.Root>
+>(
+ (
+ { className, orientation = "horizontal", decorative = true, ...props },
+ ref,
+ ) => (
+ <SeparatorPrimitive.Root
+ ref={ref}
+ decorative={decorative}
+ orientation={orientation}
+ className={cn(
+ "shrink-0 bg-neutral-200 dark:bg-neutral-800",
+ orientation === "horizontal" ? "h-[1px] w-full" : "h-full w-[1px]",
+ className,
+ )}
+ {...props}
+ />
+ ),
+);
+Separator.displayName = SeparatorPrimitive.Root.displayName;
+
+export { Separator };
diff --git a/autogpt_platform/frontend/src/components/ui/sheet.tsx b/autogpt_platform/frontend/src/components/ui/sheet.tsx
new file mode 100644
index 0000000000..30ae1d3e44
--- /dev/null
+++ b/autogpt_platform/frontend/src/components/ui/sheet.tsx
@@ -0,0 +1,143 @@
+"use client";
+
+import * as React from "react";
+import * as SheetPrimitive from "@radix-ui/react-dialog";
+import { cva, type VariantProps } from "class-variance-authority";
+import { X } from "lucide-react";
+
+import { cn } from "@/lib/utils";
+
+const Sheet = SheetPrimitive.Root;
+
+const SheetTrigger = SheetPrimitive.Trigger;
+
+const SheetClose = SheetPrimitive.Close;
+
+const SheetPortal = SheetPrimitive.Portal;
+
+const SheetOverlay = React.forwardRef<
+ React.ElementRef<typeof SheetPrimitive.Overlay>,
+ React.ComponentPropsWithoutRef<typeof SheetPrimitive.Overlay>
+>(({ className, ...props }, ref) => (
+ <SheetPrimitive.Overlay
+ className={cn(
+ "fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
+ className,
+ )}
+ {...props}
+ ref={ref}
+ />
+));
+SheetOverlay.displayName = SheetPrimitive.Overlay.displayName;
+
+const sheetVariants = cva(
+ "fixed z-50 gap-4 bg-white p-6 shadow-lg transition ease-in-out data-[state=closed]:duration-300 data-[state=open]:duration-500 data-[state=open]:animate-in data-[state=closed]:animate-out dark:bg-neutral-950",
+ {
+ variants: {
+ side: {
+ top: "inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",
+ bottom:
+ "inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",
+ left: "inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm",
+ right:
+ "inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm",
+ },
+ },
+ defaultVariants: {
+ side: "right",
+ },
+ },
+);
+
+interface SheetContentProps
+ extends React.ComponentPropsWithoutRef<typeof SheetPrimitive.Content>,
+ VariantProps<typeof sheetVariants> {}
+
+const SheetContent = React.forwardRef<
+ React.ElementRef<typeof SheetPrimitive.Content>,
+ SheetContentProps
+>(({ side = "right", className, children, ...props }, ref) => (
+ <SheetPortal>
+ <SheetOverlay />
+ <SheetPrimitive.Content
+ ref={ref}
+ className={cn(sheetVariants({ side }), className)}
+ {...props}
+ >
+ <SheetPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-white transition-opacity data-[state=open]:bg-neutral-100 hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-neutral-950 focus:ring-offset-2 disabled:pointer-events-none dark:ring-offset-neutral-950 dark:data-[state=open]:bg-neutral-800 dark:focus:ring-neutral-300">
+ <X className="h-4 w-4" />
+ <span className="sr-only">Close</span>
+ </SheetPrimitive.Close>
+ {children}
+ </SheetPrimitive.Content>
+ </SheetPortal>
+));
+SheetContent.displayName = SheetPrimitive.Content.displayName;
+
+const SheetHeader = ({
+ className,
+ ...props
+}: React.HTMLAttributes<HTMLDivElement>) => (
+ <div
+ className={cn(
+ "flex flex-col space-y-2 text-center sm:text-left",
+ className,
+ )}
+ {...props}
+ />
+);
+SheetHeader.displayName = "SheetHeader";
+
+const SheetFooter = ({
+ className,
+ ...props
+}: React.HTMLAttributes<HTMLDivElement>) => (
+ <div
+ className={cn(
+ "flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",
+ className,
+ )}
+ {...props}
+ />
+);
+SheetFooter.displayName = "SheetFooter";
+
+const SheetTitle = React.forwardRef<
+ React.ElementRef<typeof SheetPrimitive.Title>,
+ React.ComponentPropsWithoutRef<typeof SheetPrimitive.Title>
+>(({ className, ...props }, ref) => (
+ <SheetPrimitive.Title
+ ref={ref}
+ className={cn(
+ "text-lg font-semibold text-neutral-950 dark:text-neutral-50",
+ className,
+ )}
+ {...props}
+ />
+));
+SheetTitle.displayName = SheetPrimitive.Title.displayName;
+
+const SheetDescription = React.forwardRef<
+ React.ElementRef<typeof SheetPrimitive.Description>,
+ React.ComponentPropsWithoutRef<typeof SheetPrimitive.Description>
+>(({ className, ...props }, ref) => (
+ <SheetPrimitive.Description
+ ref={ref}
+ className={cn("text-sm text-neutral-500 dark:text-neutral-400", className)}
+ {...props}
+ />
+));
+SheetDescription.displayName = SheetPrimitive.Description.displayName;
+
+export {
+ Sheet,
+ SheetPortal,
+ SheetOverlay,
+ SheetTrigger,
+ SheetClose,
+ SheetContent,
+ SheetHeader,
+ SheetFooter,
+ SheetTitle,
+ SheetDescription,
+};
diff --git a/autogpt_platform/frontend/src/components/ui/sidebar.tsx b/autogpt_platform/frontend/src/components/ui/sidebar.tsx
new file mode 100644
index 0000000000..1b6f69e27b
--- /dev/null
+++ b/autogpt_platform/frontend/src/components/ui/sidebar.tsx
@@ -0,0 +1,778 @@
+"use client";
+
+import { Slot } from "@radix-ui/react-slot";
+import { cva, type VariantProps } from "class-variance-authority";
+import * as React from "react";
+
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { Separator } from "@/components/ui/separator";
+import {
+ Sheet,
+ SheetContent,
+ SheetDescription,
+ SheetHeader,
+ SheetTitle,
+} from "@/components/ui/sheet";
+import { Skeleton } from "@/components/ui/skeleton";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
+import { useIsMobile } from "@/hooks/use-mobile";
+import { cn } from "@/lib/utils";
+import { SidebarSimpleIcon } from "@phosphor-icons/react";
+
+const SIDEBAR_COOKIE_NAME = "sidebar_state";
+const SIDEBAR_COOKIE_MAX_AGE = 60 * 60 * 24 * 7;
+const SIDEBAR_WIDTH = "20rem";
+const SIDEBAR_WIDTH_MOBILE = "20rem";
+const SIDEBAR_WIDTH_ICON = "3rem";
+const SIDEBAR_KEYBOARD_SHORTCUT = "b";
+
+type SidebarContextProps = {
+ state: "expanded" | "collapsed";
+ open: boolean;
+ setOpen: (open: boolean) => void;
+ openMobile: boolean;
+ setOpenMobile: (open: boolean) => void;
+ isMobile: boolean;
+ toggleSidebar: () => void;
+};
+
+const SidebarContext = React.createContext<SidebarContextProps | null>(null);
+
+function useSidebar() {
+ const context = React.useContext(SidebarContext);
+ if (!context) {
+ throw new Error("useSidebar must be used within a SidebarProvider.");
+ }
+
+ return context;
+}
+
+const SidebarProvider = React.forwardRef<
+ HTMLDivElement,
+ React.ComponentProps<"div"> & {
+ defaultOpen?: boolean;
+ open?: boolean;
+ onOpenChange?: (open: boolean) => void;
+ }
+>(
+ (
+ {
+ defaultOpen = true,
+ open: openProp,
+ onOpenChange: setOpenProp,
+ className,
+ style,
+ children,
+ ...props
+ },
+ ref,
+ ) => {
+ const isMobile = useIsMobile();
+ const [openMobile, setOpenMobile] = React.useState(false);
+
+ // This is the internal state of the sidebar.
+ // We use openProp and setOpenProp for control from outside the component.
+ const [_open, _setOpen] = React.useState(defaultOpen);
+ const open = openProp ?? _open;
+ const setOpen = React.useCallback(
+ (value: boolean | ((value: boolean) => boolean)) => {
+ const openState = typeof value === "function" ? value(open) : value;
+ if (setOpenProp) {
+ setOpenProp(openState);
+ } else {
+ _setOpen(openState);
+ }
+
+ // This sets the cookie to keep the sidebar state.
+ document.cookie = `${SIDEBAR_COOKIE_NAME}=${openState}; path=/; max-age=${SIDEBAR_COOKIE_MAX_AGE}`;
+ },
+ [setOpenProp, open],
+ );
+
+ // Helper to toggle the sidebar.
+ const toggleSidebar = React.useCallback(() => {
+ return isMobile
+ ? setOpenMobile((open) => !open)
+ : setOpen((open) => !open);
+ }, [isMobile, setOpen, setOpenMobile]);
+
+ // Adds a keyboard shortcut to toggle the sidebar.
+ React.useEffect(() => {
+ const handleKeyDown = (event: KeyboardEvent) => {
+ if (
+ event.key === SIDEBAR_KEYBOARD_SHORTCUT &&
+ (event.metaKey || event.ctrlKey)
+ ) {
+ event.preventDefault();
+ toggleSidebar();
+ }
+ };
+
+ window.addEventListener("keydown", handleKeyDown);
+ return () => window.removeEventListener("keydown", handleKeyDown);
+ }, [toggleSidebar]);
+
+ // We add a state so that we can do data-state="expanded" or "collapsed".
+ // This makes it easier to style the sidebar with Tailwind classes.
+ const state = open ? "expanded" : "collapsed";
+
+ const contextValue = React.useMemo<SidebarContextProps>(
+ () => ({
+ state,
+ open,
+ setOpen,
+ isMobile,
+ openMobile,
+ setOpenMobile,
+ toggleSidebar,
+ }),
+ [
+ state,
+ open,
+ setOpen,
+ isMobile,
+ openMobile,
+ setOpenMobile,
+ toggleSidebar,
+ ],
+ );
+
+ return (
+ <SidebarContext.Provider value={contextValue}>
+ <TooltipProvider delayDuration={0}>
+ <div
+ style={
+ {
+ "--sidebar-width": SIDEBAR_WIDTH,
+ "--sidebar-width-icon": SIDEBAR_WIDTH_ICON,
+ ...style,
+ } as React.CSSProperties
+ }
+ className={cn(
+ "group/sidebar-wrapper flex min-h-svh w-full has-[[data-variant=inset]]:bg-sidebar",
+ className,
+ )}
+ ref={ref}
+ {...props}
+ >
+ {children}
+ </div>
+ </TooltipProvider>
+ </SidebarContext.Provider>
+ );
+ },
+);
+SidebarProvider.displayName = "SidebarProvider";
+
+const Sidebar = React.forwardRef<
+ HTMLDivElement,
+ React.ComponentProps<"div"> & {
+ side?: "left" | "right";
+ variant?: "sidebar" | "floating" | "inset";
+ collapsible?: "offcanvas" | "icon" | "none";
+ }
+>(
+ (
+ {
+ side = "left",
+ variant = "sidebar",
+ collapsible = "offcanvas",
+ className,
+ children,
+ ...props
+ },
+ ref,
+ ) => {
+ const { isMobile, state, openMobile, setOpenMobile } = useSidebar();
+
+ if (collapsible === "none") {
+ return (
+ <div
+ className={cn(
+ "flex h-full w-[--sidebar-width] flex-col bg-sidebar text-sidebar-foreground",
+ className,
+ )}
+ ref={ref}
+ {...props}
+ >
+ {children}
+ </div>
+ );
+ }
+
+ if (isMobile) {
+ return (
+ <Sheet open={openMobile} onOpenChange={setOpenMobile} {...props}>
+ <SheetContent
+ data-sidebar="sidebar"
+ data-mobile="true"
+ className="w-[--sidebar-width] bg-sidebar p-0 text-sidebar-foreground [&>button]:hidden"
+ style={
+ {
+ "--sidebar-width": SIDEBAR_WIDTH_MOBILE,
+ } as React.CSSProperties
+ }
+ side={side}
+ >
+ <SheetHeader className="sr-only">
+ <SheetTitle>Sidebar</SheetTitle>
+ <SheetDescription>Displays the mobile sidebar.</SheetDescription>
+ </SheetHeader>
+ <div className="flex h-full w-full flex-col">{children}</div>
+ </SheetContent>
+ </Sheet>
+ );
+ }
+
+ return (
+ <div
+ ref={ref}
+ className="group peer hidden text-sidebar-foreground md:block"
+ data-state={state}
+ data-collapsible={state === "collapsed" ? collapsible : ""}
+ data-variant={variant}
+ data-side={side}
+ >
+ {/* This is what handles the sidebar gap on desktop */}
+ <div
+ className={cn(
+ "relative w-[--sidebar-width] bg-transparent transition-[width] duration-200 ease-linear",
+ "group-data-[collapsible=offcanvas]:w-0",
+ "group-data-[side=right]:rotate-180",
+ variant === "floating" || variant === "inset"
+ ? "group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)_+_theme(spacing.4))]"
+ : "group-data-[collapsible=icon]:w-[--sidebar-width-icon]",
+ )}
+ />
+ <div
+ className={cn(
+ "fixed inset-y-0 z-10 hidden h-svh w-[--sidebar-width] transition-[left,right,width] duration-200 ease-linear md:flex",
+ side === "left"
+ ? "left-0 group-data-[collapsible=offcanvas]:left-[calc(var(--sidebar-width)*-1)]"
+ : "right-0 group-data-[collapsible=offcanvas]:right-[calc(var(--sidebar-width)*-1)]",
+ // Adjust the padding for floating and inset variants.
+ variant === "floating" || variant === "inset"
+ ? "p-2 group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)_+_theme(spacing.4)_+2px)]"
+ : "group-data-[collapsible=icon]:w-[--sidebar-width-icon] group-data-[side=left]:border-r group-data-[side=right]:border-l",
+ className,
+ )}
+ {...props}
+ >
+ <div
+ data-sidebar="sidebar"
+ className="flex h-full w-full flex-col bg-sidebar group-data-[variant=floating]:rounded-lg group-data-[variant=floating]:border group-data-[variant=floating]:border-sidebar-border group-data-[variant=floating]:shadow"
+ >
+ {children}
+ </div>
+ </div>
+ </div>
+ );
+ },
+);
+Sidebar.displayName = "Sidebar";
+
+const SidebarTrigger = React.forwardRef<
+ React.ElementRef<typeof Button>,
+ React.ComponentProps<typeof Button>
+>(({ onClick }, ref) => {
+ const { toggleSidebar } = useSidebar();
+
+ return (
+ <Button
+ ref={ref}
+ data-sidebar="trigger"
+ variant="ghost"
+ onClick={(event) => {
+ onClick?.(event);
+ toggleSidebar();
+ }}
+ >
+ <SidebarSimpleIcon className="!size-5" />
+ <span className="sr-only">Toggle Sidebar</span>
+ </Button>
+ );
+});
+SidebarTrigger.displayName = "SidebarTrigger";
+
+const SidebarRail = React.forwardRef<
+ HTMLButtonElement,
+ React.ComponentProps<"button">
+>(({ className, ...props }, ref) => {
+ const { toggleSidebar } = useSidebar();
+
+ return (
+ <button
+ ref={ref}
+ data-sidebar="rail"
+ aria-label="Toggle Sidebar"
+ tabIndex={-1}
+ onClick={toggleSidebar}
+ title="Toggle Sidebar"
+ className={cn(
+ "absolute inset-y-0 z-20 hidden w-4 -translate-x-1/2 transition-all ease-linear after:absolute after:inset-y-0 after:left-1/2 after:w-[2px] group-data-[side=left]:-right-4 group-data-[side=right]:left-0 hover:after:bg-sidebar-border sm:flex",
+ "[[data-side=left]_&]:cursor-w-resize [[data-side=right]_&]:cursor-e-resize",
+ "[[data-side=left][data-state=collapsed]_&]:cursor-e-resize [[data-side=right][data-state=collapsed]_&]:cursor-w-resize",
+ "group-data-[collapsible=offcanvas]:translate-x-0 group-data-[collapsible=offcanvas]:after:left-full group-data-[collapsible=offcanvas]:hover:bg-sidebar",
+ "[[data-side=left][data-collapsible=offcanvas]_&]:-right-2",
+ "[[data-side=right][data-collapsible=offcanvas]_&]:-left-2",
+ className,
+ )}
+ {...props}
+ />
+ );
+});
+SidebarRail.displayName = "SidebarRail";
+
+const SidebarInset = React.forwardRef<
+ HTMLDivElement,
+ React.ComponentProps<"main">
+>(({ className, ...props }, ref) => {
+ return (
+ <main
+ ref={ref}
+ className={cn(
+ "relative flex w-full flex-1 flex-col bg-white dark:bg-neutral-950",
+ "md:peer-data-[variant=inset]:m-2 md:peer-data-[state=collapsed]:peer-data-[variant=inset]:ml-2 md:peer-data-[variant=inset]:ml-0 md:peer-data-[variant=inset]:rounded-xl md:peer-data-[variant=inset]:shadow",
+ className,
+ )}
+ {...props}
+ />
+ );
+});
+SidebarInset.displayName = "SidebarInset";
+
+const SidebarInput = React.forwardRef<
+ React.ElementRef<typeof Input>,
+ React.ComponentProps<typeof Input>
+>(({ className, ...props }, ref) => {
+ return (
+ <Input
+ ref={ref}
+ data-sidebar="input"
+ className={cn(
+ "h-8 w-full bg-white shadow-none focus-visible:ring-2 focus-visible:ring-sidebar-ring dark:bg-neutral-950",
+ className,
+ )}
+ {...props}
+ />
+ );
+});
+SidebarInput.displayName = "SidebarInput";
+
+const SidebarHeader = React.forwardRef<
+ HTMLDivElement,
+ React.ComponentProps<"div">
+>(({ className, ...props }, ref) => {
+ return (
+ <div
+ ref={ref}
+ data-sidebar="header"
+ className={cn("flex flex-col gap-2 p-2", className)}
+ {...props}
+ />
+ );
+});
+SidebarHeader.displayName = "SidebarHeader";
+
+const SidebarFooter = React.forwardRef<
+ HTMLDivElement,
+ React.ComponentProps<"div">
+>(({ className, ...props }, ref) => {
+ return (
+ <div
+ ref={ref}
+ data-sidebar="footer"
+ className={cn("flex flex-col gap-2 p-2", className)}
+ {...props}
+ />
+ );
+});
+SidebarFooter.displayName = "SidebarFooter";
+
+const SidebarSeparator = React.forwardRef<
+ React.ElementRef<typeof Separator>,
+ React.ComponentProps<typeof Separator>
+>(({ className, ...props }, ref) => {
+ return (
+ <Separator
+ ref={ref}
+ data-sidebar="separator"
+ className={cn("mx-2 w-auto bg-sidebar-border", className)}
+ {...props}
+ />
+ );
+});
+SidebarSeparator.displayName = "SidebarSeparator";
+
+const SidebarContent = React.forwardRef<
+ HTMLDivElement,
+ React.ComponentProps<"div">
+>(({ className, ...props }, ref) => {
+ return (
+ <div
+ ref={ref}
+ data-sidebar="content"
+ className={cn(
+ "flex min-h-0 flex-1 flex-col gap-2 overflow-auto group-data-[collapsible=icon]:overflow-hidden",
+ className,
+ )}
+ {...props}
+ />
+ );
+});
+SidebarContent.displayName = "SidebarContent";
+
+const SidebarGroup = React.forwardRef<
+ HTMLDivElement,
+ React.ComponentProps<"div">
+>(({ className, ...props }, ref) => {
+ return (
+ <div
+ ref={ref}
+ data-sidebar="group"
+ className={cn("relative flex w-full min-w-0 flex-col p-2", className)}
+ {...props}
+ />
+ );
+});
+SidebarGroup.displayName = "SidebarGroup";
+
+const SidebarGroupLabel = React.forwardRef<
+ HTMLDivElement,
+ React.ComponentProps<"div"> & { asChild?: boolean }
+>(({ className, asChild = false, ...props }, ref) => {
+ const Comp = asChild ? Slot : "div";
+
+ return (
+ <Comp
+ ref={ref}
+ data-sidebar="group-label"
+ className={cn(
+ "flex h-8 shrink-0 items-center rounded-md px-2 text-xs font-medium text-sidebar-foreground/70 outline-none ring-sidebar-ring transition-[margin,opacity] duration-200 ease-linear focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
+ "group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0",
+ className,
+ )}
+ {...props}
+ />
+ );
+});
+SidebarGroupLabel.displayName = "SidebarGroupLabel";
+
+const SidebarGroupAction = React.forwardRef<
+ HTMLButtonElement,
+ React.ComponentProps<"button"> & { asChild?: boolean }
+>(({ className, asChild = false, ...props }, ref) => {
+ const Comp = asChild ? Slot : "button";
+
+ return (
+ <Comp
+ ref={ref}
+ data-sidebar="group-action"
+ className={cn(
+ "absolute right-3 top-3.5 flex aspect-square w-5 items-center justify-center rounded-md p-0 text-sidebar-foreground outline-none ring-sidebar-ring transition-transform hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
+ // Increases the hit area of the button on mobile.
+ "after:absolute after:-inset-2 after:md:hidden",
+ "group-data-[collapsible=icon]:hidden",
+ className,
+ )}
+ {...props}
+ />
+ );
+});
+SidebarGroupAction.displayName = "SidebarGroupAction";
+
+const SidebarGroupContent = React.forwardRef<
+ HTMLDivElement,
+ React.ComponentProps<"div">
+>(({ className, ...props }, ref) => (
+ <div
+ ref={ref}
+ data-sidebar="group-content"
+ className={cn("w-full text-sm", className)}
+ {...props}
+ />
+));
+SidebarGroupContent.displayName = "SidebarGroupContent";
+
+const SidebarMenu = React.forwardRef<
+ HTMLUListElement,
+ React.ComponentProps<"ul">
+>(({ className, ...props }, ref) => (
+ <ul
+ ref={ref}
+ data-sidebar="menu"
+ className={cn("flex w-full min-w-0 flex-col gap-1", className)}
+ {...props}
+ />
+));
+SidebarMenu.displayName = "SidebarMenu";
+
+const SidebarMenuItem = React.forwardRef<
+ HTMLLIElement,
+ React.ComponentProps<"li">
+>(({ className, ...props }, ref) => (
+ <li
+ ref={ref}
+ data-sidebar="menu-item"
+ className={cn("group/menu-item relative", className)}
+ {...props}
+ />
+));
+SidebarMenuItem.displayName = "SidebarMenuItem";
+
+const sidebarMenuButtonVariants = cva(
+ "peer/menu-button flex w-full items-center gap-2 overflow-hidden rounded-md p-2 text-left text-sm outline-none ring-sidebar-ring transition-[width,height,padding] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 group-has-[[data-sidebar=menu-action]]/menu-item:pr-8 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[active=true]:bg-sidebar-accent data-[active=true]:font-medium data-[active=true]:text-sidebar-accent-foreground data-[state=open]:hover:bg-sidebar-accent data-[state=open]:hover:text-sidebar-accent-foreground group-data-[collapsible=icon]:!size-8 group-data-[collapsible=icon]:!p-2 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0",
+ {
+ variants: {
+ variant: {
+ default: "hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",
+ outline:
+ "bg-white shadow-[0_0_0_1px_hsl(var(--sidebar-border))] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground hover:shadow-[0_0_0_1px_hsl(var(--sidebar-accent))] dark:bg-neutral-950",
+ },
+ size: {
+ default: "h-8 text-sm",
+ sm: "h-7 text-xs",
+ lg: "h-12 text-sm group-data-[collapsible=icon]:!p-0",
+ },
+ },
+ defaultVariants: {
+ variant: "default",
+ size: "default",
+ },
+ },
+);
+
+const SidebarMenuButton = React.forwardRef<
+ HTMLButtonElement,
+ React.ComponentProps<"button"> & {
+ asChild?: boolean;
+ isActive?: boolean;
+ tooltip?: string | React.ComponentProps<typeof TooltipContent>;
+ } & VariantProps<typeof sidebarMenuButtonVariants>
+>(
+ (
+ {
+ asChild = false,
+ isActive = false,
+ variant = "default",
+ size = "default",
+ tooltip,
+ className,
+ ...props
+ },
+ ref,
+ ) => {
+ const Comp = asChild ? Slot : "button";
+ const { isMobile, state } = useSidebar();
+
+ const button = (
+ <Comp
+ ref={ref}
+ data-sidebar="menu-button"
+ data-size={size}
+ data-active={isActive}
+ className={cn(sidebarMenuButtonVariants({ variant, size }), className)}
+ {...props}
+ />
+ );
+
+ if (!tooltip) {
+ return button;
+ }
+
+ if (typeof tooltip === "string") {
+ tooltip = {
+ children: tooltip,
+ };
+ }
+
+ return (
+ <Tooltip>
+ <TooltipTrigger asChild>{button}</TooltipTrigger>
+ <TooltipContent
+ side="right"
+ align="center"
+ hidden={state !== "collapsed" || isMobile}
+ {...tooltip}
+ />
+ </Tooltip>
+ );
+ },
+);
+SidebarMenuButton.displayName = "SidebarMenuButton";
+
+const SidebarMenuAction = React.forwardRef<
+ HTMLButtonElement,
+ React.ComponentProps<"button"> & {
+ asChild?: boolean;
+ showOnHover?: boolean;
+ }
+>(({ className, asChild = false, showOnHover = false, ...props }, ref) => {
+ const Comp = asChild ? Slot : "button";
+
+ return (
+ <Comp
+ ref={ref}
+ data-sidebar="menu-action"
+ className={cn(
+ "absolute right-1 top-1.5 flex aspect-square w-5 items-center justify-center rounded-md p-0 text-sidebar-foreground outline-none ring-sidebar-ring transition-transform peer-hover/menu-button:text-sidebar-accent-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
+ // Increases the hit area of the button on mobile.
+ "after:absolute after:-inset-2 after:md:hidden",
+ "peer-data-[size=sm]/menu-button:top-1",
+ "peer-data-[size=default]/menu-button:top-1.5",
+ "peer-data-[size=lg]/menu-button:top-2.5",
+ "group-data-[collapsible=icon]:hidden",
+ showOnHover &&
+ "group-focus-within/menu-item:opacity-100 group-hover/menu-item:opacity-100 data-[state=open]:opacity-100 peer-data-[active=true]/menu-button:text-sidebar-accent-foreground md:opacity-0",
+ className,
+ )}
+ {...props}
+ />
+ );
+});
+SidebarMenuAction.displayName = "SidebarMenuAction";
+
+const SidebarMenuBadge = React.forwardRef<
+ HTMLDivElement,
+ React.ComponentProps<"div">
+>(({ className, ...props }, ref) => (
+ <div
+ ref={ref}
+ data-sidebar="menu-badge"
+ className={cn(
+ "pointer-events-none absolute right-1 flex h-5 min-w-5 select-none items-center justify-center rounded-md px-1 text-xs font-medium tabular-nums text-sidebar-foreground",
+ "peer-hover/menu-button:text-sidebar-accent-foreground peer-data-[active=true]/menu-button:text-sidebar-accent-foreground",
+ "peer-data-[size=sm]/menu-button:top-1",
+ "peer-data-[size=default]/menu-button:top-1.5",
+ "peer-data-[size=lg]/menu-button:top-2.5",
+ "group-data-[collapsible=icon]:hidden",
+ className,
+ )}
+ {...props}
+ />
+));
+SidebarMenuBadge.displayName = "SidebarMenuBadge";
+
+const SidebarMenuSkeleton = React.forwardRef<
+ HTMLDivElement,
+ React.ComponentProps<"div"> & {
+ showIcon?: boolean;
+ }
+>(({ className, showIcon = false, ...props }, ref) => {
+ // Random width between 50 to 90%.
+ const width = React.useMemo(() => {
+ return `${Math.floor(Math.random() * 40) + 50}%`;
+ }, []);
+
+ return (
+ <div
+ ref={ref}
+ data-sidebar="menu-skeleton"
+ className={cn("flex h-8 items-center gap-2 rounded-md px-2", className)}
+ {...props}
+ >
+ {showIcon && (
+ <Skeleton
+ className="size-4 rounded-md"
+ data-sidebar="menu-skeleton-icon"
+ />
+ )}
+ <Skeleton
+ className="h-4 max-w-[--skeleton-width] flex-1"
+ data-sidebar="menu-skeleton-text"
+ style={
+ {
+ "--skeleton-width": width,
+ } as React.CSSProperties
+ }
+ />
+ </div>
+ );
+});
+SidebarMenuSkeleton.displayName = "SidebarMenuSkeleton";
+
+const SidebarMenuSub = React.forwardRef<
+ HTMLUListElement,
+ React.ComponentProps<"ul">
+>(({ className, ...props }, ref) => (
+ <ul
+ ref={ref}
+ data-sidebar="menu-sub"
+ className={cn(
+ "mx-3.5 flex min-w-0 translate-x-px flex-col gap-1 border-l border-sidebar-border px-2.5 py-0.5",
+ "group-data-[collapsible=icon]:hidden",
+ className,
+ )}
+ {...props}
+ />
+));
+SidebarMenuSub.displayName = "SidebarMenuSub";
+
+const SidebarMenuSubItem = React.forwardRef<
+ HTMLLIElement,
+ React.ComponentProps<"li">
+>(({ ...props }, ref) => <li ref={ref} {...props} />);
+SidebarMenuSubItem.displayName = "SidebarMenuSubItem";
+
+const SidebarMenuSubButton = React.forwardRef<
+ HTMLAnchorElement,
+ React.ComponentProps<"a"> & {
+ asChild?: boolean;
+ size?: "sm" | "md";
+ isActive?: boolean;
+ }
+>(({ asChild = false, size = "md", isActive, className, ...props }, ref) => {
+ const Comp = asChild ? Slot : "a";
+
+ return (
+ <Comp
+ ref={ref}
+ data-sidebar="menu-sub-button"
+ data-size={size}
+ data-active={isActive}
+ className={cn(
+ "flex h-7 min-w-0 -translate-x-px items-center gap-2 overflow-hidden rounded-md px-2 text-sidebar-foreground outline-none ring-sidebar-ring aria-disabled:pointer-events-none aria-disabled:opacity-50 hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0 [&>svg]:text-sidebar-accent-foreground",
+ "data-[active=true]:bg-sidebar-accent data-[active=true]:text-sidebar-accent-foreground",
+ size === "sm" && "text-xs",
+ size === "md" && "text-sm",
+ "group-data-[collapsible=icon]:hidden",
+ className,
+ )}
+ {...props}
+ />
+ );
+});
+SidebarMenuSubButton.displayName = "SidebarMenuSubButton";
+
+export {
+ Sidebar,
+ SidebarContent,
+ SidebarFooter,
+ SidebarGroup,
+ SidebarGroupAction,
+ SidebarGroupContent,
+ SidebarGroupLabel,
+ SidebarHeader,
+ SidebarInput,
+ SidebarInset,
+ SidebarMenu,
+ SidebarMenuAction,
+ SidebarMenuBadge,
+ SidebarMenuButton,
+ SidebarMenuItem,
+ SidebarMenuSkeleton,
+ SidebarMenuSub,
+ SidebarMenuSubButton,
+ SidebarMenuSubItem,
+ SidebarProvider,
+ SidebarRail,
+ SidebarSeparator,
+ SidebarTrigger,
+ useSidebar,
+};
diff --git a/autogpt_platform/frontend/src/components/ui/skeleton.tsx b/autogpt_platform/frontend/src/components/ui/skeleton.tsx
new file mode 100644
index 0000000000..f38dd7313a
--- /dev/null
+++ b/autogpt_platform/frontend/src/components/ui/skeleton.tsx
@@ -0,0 +1,18 @@
+import { cn } from "@/lib/utils";
+
+function Skeleton({
+ className,
+ ...props
+}: React.HTMLAttributes<HTMLDivElement>) {
+ return (
+ <div
+ className={cn(
+ "animate-pulse rounded-md bg-neutral-900/10 dark:bg-neutral-50/10",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+export { Skeleton };
diff --git a/autogpt_platform/frontend/src/components/ui/tooltip.tsx b/autogpt_platform/frontend/src/components/ui/tooltip.tsx
new file mode 100644
index 0000000000..93d498e1e4
--- /dev/null
+++ b/autogpt_platform/frontend/src/components/ui/tooltip.tsx
@@ -0,0 +1,32 @@
+"use client";
+
+import * as React from "react";
+import * as TooltipPrimitive from "@radix-ui/react-tooltip";
+
+import { cn } from "@/lib/utils";
+
+const TooltipProvider = TooltipPrimitive.Provider;
+
+const Tooltip = TooltipPrimitive.Root;
+
+const TooltipTrigger = TooltipPrimitive.Trigger;
+
+const TooltipContent = React.forwardRef<
+ React.ElementRef<typeof TooltipPrimitive.Content>,
+ React.ComponentPropsWithoutRef<typeof TooltipPrimitive.Content>
+>(({ className, sideOffset = 4, ...props }, ref) => (
+ <TooltipPrimitive.Portal>
+ <TooltipPrimitive.Content
+ ref={ref}
+ sideOffset={sideOffset}
+ className={cn(
+ "z-50 origin-[--radix-tooltip-content-transform-origin] overflow-hidden rounded-md bg-neutral-900 px-3 py-1.5 text-xs text-neutral-50 animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 dark:bg-neutral-50 dark:text-neutral-900",
+ className,
+ )}
+ {...props}
+ />
+ </TooltipPrimitive.Portal>
+));
+TooltipContent.displayName = TooltipPrimitive.Content.displayName;
+
+export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider };
diff --git a/autogpt_platform/frontend/src/hooks/use-mobile.tsx b/autogpt_platform/frontend/src/hooks/use-mobile.tsx
new file mode 100644
index 0000000000..a93d583938
--- /dev/null
+++ b/autogpt_platform/frontend/src/hooks/use-mobile.tsx
@@ -0,0 +1,21 @@
+import * as React from "react";
+
+const MOBILE_BREAKPOINT = 768;
+
+export function useIsMobile() {
+ const [isMobile, setIsMobile] = React.useState<boolean | undefined>(
+ undefined,
+ );
+
+ React.useEffect(() => {
+ const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`);
+ const onChange = () => {
+ setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
+ };
+ mql.addEventListener("change", onChange);
+ setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
+ return () => mql.removeEventListener("change", onChange);
+ }, []);
+
+ return !!isMobile;
+}
diff --git a/autogpt_platform/frontend/src/lib/utils.ts b/autogpt_platform/frontend/src/lib/utils.ts
index d3abc56b6c..8c300dd6c9 100644
--- a/autogpt_platform/frontend/src/lib/utils.ts
+++ b/autogpt_platform/frontend/src/lib/utils.ts
@@ -1,5 +1,5 @@
import { type ClassValue, clsx } from "clsx";
-import { isEmpty as _isEmpty } from "lodash";
+import _isEmpty from "lodash/isEmpty";
import { twMerge } from "tailwind-merge";
import { NodeDimension } from "@/app/(platform)/build/components/legacy-builder/Flow/Flow";
diff --git a/autogpt_platform/frontend/src/tests/signin.spec.ts b/autogpt_platform/frontend/src/tests/signin.spec.ts
index 8582ce8b3a..8a852531b4 100644
--- a/autogpt_platform/frontend/src/tests/signin.spec.ts
+++ b/autogpt_platform/frontend/src/tests/signin.spec.ts
@@ -172,7 +172,7 @@ test("multi-tab logout with WebSocket cleanup", async ({ context }) => {
await page2.close();
});
-test("logged in user is redirected from /login to /library", async ({
+test("logged in user is redirected from /login to /copilot", async ({
page,
}) => {
const testUser = await getTestUser();
diff --git a/autogpt_platform/frontend/tailwind.config.ts b/autogpt_platform/frontend/tailwind.config.ts
index 1adc53bdc4..85b31c72f8 100644
--- a/autogpt_platform/frontend/tailwind.config.ts
+++ b/autogpt_platform/frontend/tailwind.config.ts
@@ -65,6 +65,16 @@ const config = {
"600": "#282828",
"700": "#272727",
},
+ sidebar: {
+ DEFAULT: "hsl(var(--sidebar-background))",
+ foreground: "hsl(var(--sidebar-foreground))",
+ primary: "hsl(var(--sidebar-primary))",
+ "primary-foreground": "hsl(var(--sidebar-primary-foreground))",
+ accent: "hsl(var(--sidebar-accent))",
+ "accent-foreground": "hsl(var(--sidebar-accent-foreground))",
+ border: "hsl(var(--sidebar-border))",
+ ring: "hsl(var(--sidebar-ring))",
+ },
},
spacing: {
"0": "0rem",