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(frontend): add Agent Briefing Panel (#12764)
Ubbe31b88a6e5622
diff --git a/autogpt_platform/backend/backend/api/features/library/db.py b/autogpt_platform/backend/backend/api/features/library/db.pyindex fcfc896ea2..0e7357bad3 100644--- a/autogpt_platform/backend/backend/api/features/library/db.py+++ b/autogpt_platform/backend/backend/api/features/library/db.py@@ -43,6 +43,25 @@ config = Config()integration_creds_manager = IntegrationCredentialsManager()+async def _fetch_execution_counts(user_id: str, graph_ids: list[str]) -> dict[str, int]:+ """Fetch execution counts per graph in a single batched query."""+ if not graph_ids:+ return {}+ rows = await prisma.models.AgentGraphExecution.prisma().group_by(+ by=["agentGraphId"],+ where={+ "userId": user_id,+ "agentGraphId": {"in": graph_ids},+ "isDeleted": False,+ },+ count=True,+ )+ return {+ row["agentGraphId"]: int((row.get("_count") or {}).get("_all") or 0)+ for row in rows+ }++async def list_library_agents(user_id: str,search_term: Optional[str] = None,@@ -137,12 +156,18 @@ async def list_library_agents(logger.debug(f"Retrieved {len(library_agents)} library agents for user #{user_id}")+ graph_ids = [a.agentGraphId for a in library_agents if a.agentGraphId]+ execution_counts = await _fetch_execution_counts(user_id, graph_ids)+# Only pass valid agents to the responsevalid_library_agents: list[library_model.LibraryAgent] = []for agent in library_agents:try:- library_agent = library_model.LibraryAgent.from_db(agent)+ library_agent = library_model.LibraryAgent.from_db(+ agent,+ execution_count_override=execution_counts.get(agent.agentGraphId),+ )valid_library_agents.append(library_agent)except Exception as e:# Skip this agent if there was an error@@ -214,12 +239,18 @@ async def list_favorite_library_agents(f"Retrieved {len(library_agents)} favorite library agents for user #{user_id}")+ graph_ids = [a.agentGraphId for a in library_agents if a.agentGraphId]+ execution_counts = await _fetch_execution_counts(user_id, graph_ids)+# Only pass valid agents to the responsevalid_library_agents: list[library_model.LibraryAgent] = []for agent in library_agents:try:- library_agent = library_model.LibraryAgent.from_db(agent)+ library_agent = library_model.LibraryAgent.from_db(+ agent,+ execution_count_override=execution_counts.get(agent.agentGraphId),+ )valid_library_agents.append(library_agent)except Exception as e:# Skip this agent if there was an errordiff --git a/autogpt_platform/backend/backend/api/features/library/db_test.py b/autogpt_platform/backend/backend/api/features/library/db_test.pyindex 5e3e36ac63..562a0bfdfd 100644--- a/autogpt_platform/backend/backend/api/features/library/db_test.py+++ b/autogpt_platform/backend/backend/api/features/library/db_test.py@@ -65,6 +65,11 @@ async def test_get_library_agents(mocker):)mock_library_agent.return_value.count = mocker.AsyncMock(return_value=1)+ mocker.patch(+ "backend.api.features.library.db._fetch_execution_counts",+ new=mocker.AsyncMock(return_value={}),+ )+# Call functionresult = await db.list_library_agents("test-user")@@ -353,3 +358,136 @@ async def test_create_library_agent_uses_upsert():# Verify update branch restores soft-deleted/archived agentsassert data["update"]["isDeleted"] is Falseassert data["update"]["isArchived"] is False+++async def test_list_favorite_library_agents(mocker):+ mock_library_agents = [+ prisma.models.LibraryAgent(+ id="fav1",+ userId="test-user",+ agentGraphId="agent-fav",+ settings="{}", # type: ignore+ agentGraphVersion=1,+ isCreatedByUser=False,+ isDeleted=False,+ isArchived=False,+ createdAt=datetime.now(),+ updatedAt=datetime.now(),+ isFavorite=True,+ useGraphIsActiveVersion=True,+ AgentGraph=prisma.models.AgentGraph(+ id="agent-fav",+ version=1,+ name="Favorite Agent",+ description="My Favorite",+ userId="other-user",+ isActive=True,+ createdAt=datetime.now(),+ ),+ )+ ]++ mock_library_agent = mocker.patch("prisma.models.LibraryAgent.prisma")+ mock_library_agent.return_value.find_many = mocker.AsyncMock(+ return_value=mock_library_agents+ )+ mock_library_agent.return_value.count = mocker.AsyncMock(return_value=1)++ mocker.patch(+ "backend.api.features.library.db._fetch_execution_counts",+ new=mocker.AsyncMock(return_value={"agent-fav": 7}),+ )++ result = await db.list_favorite_library_agents("test-user")++ assert len(result.agents) == 1+ assert result.agents[0].id == "fav1"+ assert result.agents[0].name == "Favorite Agent"+ assert result.agents[0].graph_id == "agent-fav"+ assert result.pagination.total_items == 1+ assert result.pagination.total_pages == 1+ assert result.pagination.current_page == 1+ assert result.pagination.page_size == 50+++async def test_list_library_agents_skips_failed_agent(mocker):+ """Agents that fail parsing should be skipped — covers the except branch."""+ mock_library_agents = [+ prisma.models.LibraryAgent(+ id="ua-bad",+ userId="test-user",+ agentGraphId="agent-bad",+ settings="{}", # type: ignore+ agentGraphVersion=1,+ isCreatedByUser=False,+ isDeleted=False,+ isArchived=False,+ createdAt=datetime.now(),+ updatedAt=datetime.now(),+ isFavorite=False,+ useGraphIsActiveVersion=True,+ AgentGraph=prisma.models.AgentGraph(+ id="agent-bad",+ version=1,+ name="Bad Agent",+ description="",+ userId="other-user",+ isActive=True,+ createdAt=datetime.now(),+ ),+ )+ ]++ mock_library_agent = mocker.patch("prisma.models.LibraryAgent.prisma")+ mock_library_agent.return_value.find_many = mocker.AsyncMock(+ return_value=mock_library_agents+ )+ mock_library_agent.return_value.count = mocker.AsyncMock(return_value=1)++ mocker.patch(+ "backend.api.features.library.db._fetch_execution_counts",+ new=mocker.AsyncMock(return_value={}),+ )+ mocker.patch(+ "backend.api.features.library.model.LibraryAgent.from_db",+ side_effect=Exception("parse error"),+ )++ result = await db.list_library_agents("test-user")++ assert len(result.agents) == 0+ assert result.pagination.total_items == 1+++async def test_fetch_execution_counts_empty_graph_ids():+ result = await db._fetch_execution_counts("user-1", [])+ assert result == {}+++async def test_fetch_execution_counts_uses_group_by(mocker):+ mock_prisma = mocker.patch("prisma.models.AgentGraphExecution.prisma")+ mock_prisma.return_value.group_by = mocker.AsyncMock(+ return_value=[+ {"agentGraphId": "graph-1", "_count": {"_all": 5}},+ {"agentGraphId": "graph-2", "_count": {"_all": 2}},+ ]+ )++ result = await db._fetch_execution_counts(+ "user-1", ["graph-1", "graph-2", "graph-3"]+ )++ assert result == {"graph-1": 5, "graph-2": 2}+ mock_prisma.return_value.group_by.assert_called_once_with(+ by=["agentGraphId"],+ where={+ "userId": "user-1",+ "agentGraphId": {"in": ["graph-1", "graph-2", "graph-3"]},+ "isDeleted": False,+ },+ count=True,+ )diff --git a/autogpt_platform/backend/backend/api/features/library/model.py b/autogpt_platform/backend/backend/api/features/library/model.pyindex 7211a7ebfe..26251a2cd1 100644--- a/autogpt_platform/backend/backend/api/features/library/model.py+++ b/autogpt_platform/backend/backend/api/features/library/model.py@@ -223,6 +223,7 @@ class LibraryAgent(pydantic.BaseModel):sub_graphs: Optional[list[prisma.models.AgentGraph]] = None,store_listing: Optional[prisma.models.StoreListing] = None,profile: Optional[prisma.models.Profile] = None,+ execution_count_override: Optional[int] = None,) -> "LibraryAgent":"""Factory method that constructs a LibraryAgent from a Prisma LibraryAgent@@ -258,10 +259,14 @@ class LibraryAgent(pydantic.BaseModel):status = status_result.statusnew_output = status_result.new_output- execution_count = len(executions)+ execution_count = (+ execution_count_override+ if execution_count_override is not None+ else len(executions)+ )success_rate: float | None = Noneavg_correctness_score: float | None = None- if execution_count > 0:+ if executions and execution_count > 0:success_count = sum(1for e in executionsdiff --git a/autogpt_platform/backend/backend/api/features/library/model_test.py b/autogpt_platform/backend/backend/api/features/library/model_test.pyindex a32b19322d..31924a1793 100644--- a/autogpt_platform/backend/backend/api/features/library/model_test.py+++ b/autogpt_platform/backend/backend/api/features/library/model_test.py@@ -1,11 +1,66 @@import datetime+import prisma.enumsimport prisma.modelsimport pytestfrom . import model as library_model+def _make_library_agent(+ *,+ graph_id: str = "g1",+ executions: list | None = None,+) -> prisma.models.LibraryAgent:+ return prisma.models.LibraryAgent(+ id="la1",+ userId="u1",+ agentGraphId=graph_id,+ settings="{}", # type: ignore+ agentGraphVersion=1,+ isCreatedByUser=True,+ isDeleted=False,+ isArchived=False,+ createdAt=datetime.datetime.now(),+ updatedAt=datetime.datetime.now(),+ isFavorite=False,+ useGraphIsActiveVersion=True,+ AgentGraph=prisma.models.AgentGraph(+ id=graph_id,+ version=1,+ name="Agent",+ description="Desc",+ userId="u1",+ isActive=True,+ createdAt=datetime.datetime.now(),+ Executions=executions,+ ),+ )+++def test_from_db_execution_count_override_covers_success_rate():+ """Covers execution_count_override is not None branch and executions/count > 0 block."""+ now = datetime.datetime.now(datetime.timezone.utc)+ exec1 = prisma.models.AgentGraphExecution(+ id="exec-1",+ agentGraphId="g1",+ agentGraphVersion=1,+ userId="u1",+ executionStatus=prisma.enums.AgentExecutionStatus.COMPLETED,+ createdAt=now,+ updatedAt=now,+ isDeleted=False,+ isShared=False,+ )+ agent = _make_library_agent(executions=[exec1])++ result = library_model.LibraryAgent.from_db(agent, execution_count_override=1)++ assert result.execution_count == 1+ assert result.success_rate is not None+ assert result.success_rate == 100.0++@pytest.mark.asyncioasync def test_agent_preset_from_db(test_user_id: str):# Create mock DB agentdiff --git a/autogpt_platform/frontend/package.json b/autogpt_platform/frontend/package.jsonindex 4661ab2050..292e64e8dd 100644--- a/autogpt_platform/frontend/package.json+++ b/autogpt_platform/frontend/package.json@@ -155,6 +155,7 @@"@types/twemoji": "13.1.2","@vitejs/plugin-react": "5.1.2","@vitest/coverage-v8": "4.0.17",+ "agentation": "3.0.2","axe-playwright": "2.2.2","chromatic": "13.3.3","concurrently": "9.2.1",diff --git a/autogpt_platform/frontend/pnpm-lock.yaml b/autogpt_platform/frontend/pnpm-lock.yamlindex 057719def1..ad6429ac52 100644--- a/autogpt_platform/frontend/pnpm-lock.yaml+++ b/autogpt_platform/frontend/pnpm-lock.yaml@@ -376,6 +376,9 @@ importers:'@vitest/coverage-v8':specifier: 4.0.17version: 4.0.17([email protected](@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected]))([email protected])([email protected]))+ agentation:+ specifier: 3.0.2axe-playwright:specifier: 2.2.2version: 2.2.2([email protected])@@ -4119,6 +4122,17 @@ packages:resolution: {integrity: sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==}engines: {node: '>= 14'}+ resolution: {integrity: sha512-iGzBxFVTuZEIKzLY6AExSLAQH6i6SwxV4pAu7v7m3X6bInZ7qlZXAwrEqyc4+EfP4gM7z2RXBF6SF4DeH0f2lA==}+ peerDependencies:+ react: '>=18.0.0'+ react-dom: '>=18.0.0'+ peerDependenciesMeta:+ react:+ optional: true+ react-dom:+ optional: true+resolution: {integrity: sha512-YalNEaavld/kE444gOcsMKXdVVRGEe0SK77fAFcWYcqLg+a7xKnEet8bdfrEAJTfnMjj01rhgrIL10903w1a5Q==}engines: {node: '>=18'}@@ -13119,6 +13133,11 @@ snapshots:optional: true+ optionalDependencies:+ react: 18.3.1+ react-dom: 18.3.1([email protected])+dependencies:'@ai-sdk/gateway': 3.0.77([email protected])diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/ChatInput.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/ChatInput.tsxindex 44f59fcc39..ae24800142 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/ChatInput.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/ChatInput.tsx@@ -86,11 +86,11 @@ export function ChatInput({title:next === "advanced"? "Switched to Advanced model"- : "Switched to Standard model",+ : "Switched to Balanced model",description:next === "advanced"? "Using the highest-capability model."- : "Using the balanced standard model.",+ : "Using the balanced default model.",});}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/__tests__/ChatInput.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/__tests__/ChatInput.test.tsxindex b5a94a3bea..5bac773deb 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/__tests__/ChatInput.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/__tests__/ChatInput.test.tsx@@ -162,10 +162,15 @@ describe("ChatInput mode toggle", () => {expect(mockSetCopilotChatMode).toHaveBeenCalledWith("extended_thinking");});- it("hides toggle button when streaming", () => {+ it("hides toggle buttons when streaming", () => {mockFlagValue = true;render(<ChatInput onSend={mockOnSend} isStreaming />);- expect(screen.queryByLabelText(/switch to/i)).toBeNull();+ expect(+ screen.queryByLabelText(/switch to (fast|extended thinking) mode/i),+ ).toBeNull();+ expect(+ screen.queryByLabelText(/switch to (advanced|balanced|standard) model/i),+ ).toBeNull();});it("shows mode toggle when hasSession is true and not streaming", () => {@@ -234,7 +239,7 @@ describe("ChatInput model toggle", () => {mockFlagValue = true;mockCopilotLlmModel = "advanced";render(<ChatInput onSend={mockOnSend} />);- fireEvent.click(screen.getByLabelText(/switch to standard model/i));+ fireEvent.click(screen.getByLabelText(/switch to balanced model/i));expect(mockSetCopilotLlmModel).toHaveBeenCalledWith("standard");});@@ -288,10 +293,10 @@ describe("ChatInput model toggle", () => {mockFlagValue = true;mockCopilotLlmModel = "advanced";render(<ChatInput onSend={mockOnSend} />);- fireEvent.click(screen.getByLabelText(/switch to standard model/i));+ fireEvent.click(screen.getByLabelText(/switch to balanced model/i));expect(toast).toHaveBeenCalledWith(expect.objectContaining({- title: expect.stringMatching(/switched to standard model/i),+ title: expect.stringMatching(/switched to balanced model/i),}),);});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/DryRunToggleButton.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/DryRunToggleButton.tsxindex 36c84d6826..a0b6b5b8f1 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/DryRunToggleButton.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/DryRunToggleButton.tsx@@ -2,6 +2,11 @@import { cn } from "@/lib/utils";import { Flask } from "@phosphor-icons/react";+import {+ Tooltip,+ TooltipContent,+ TooltipTrigger,+} from "@/components/ui/tooltip";// This button is only rendered on NEW chats (no active session).// Once a session exists, it is hidden — the session's dry_run flag is@@ -14,27 +19,31 @@ interface Props {export function DryRunToggleButton({ isDryRun, onToggle }: Props) {return (- <button- type="button"- aria-pressed={isDryRun}- onClick={onToggle}- className={cn(- "inline-flex min-h-11 min-w-11 items-center justify-center gap-1 rounded-md px-2 py-1 text-xs font-medium transition-colors",- isDryRun- ? "bg-amber-100 text-amber-900 hover:bg-amber-200"- : "text-neutral-500 hover:bg-neutral-100 hover:text-neutral-700",- )}- aria-label={- isDryRun ? "Test mode active — click to disable" : "Enable Test mode"- }- title={- isDryRun- ? "Test mode ON — new chats run agents as simulation (click to disable)"- : "Enable Test mode — new chats will run agents as simulation"- }- >- <Flask size={14} />- {isDryRun && "Test"}- </button>+ <Tooltip>+ <TooltipTrigger asChild>+ <button+ type="button"+ aria-pressed={isDryRun}+ onClick={onToggle}+ className={cn(+ "inline-flex h-9 items-center justify-center gap-1 rounded-full border border-neutral-200 bg-white px-2.5 text-xs font-medium shadow-sm transition-colors hover:bg-neutral-50",+ isDryRun+ ? "text-amber-900"+ : "text-neutral-500 hover:text-neutral-700",+ )}+ aria-label={isDryRun ? "Test mode active" : "Enable Test mode"}+ >+ <Flask size={14} />+ <span className="hidden sm:inline">+ {isDryRun ? "Test mode enabled" : "Enable test mode"}+ </span>+ </button>+ </TooltipTrigger>+ <TooltipContent>+ {isDryRun+ ? "Test mode on — new sessions run without performing real actions (click to turn off)."+ : "Turn on test mode to try prompts without performing real actions."}+ </TooltipContent>+ </Tooltip>);}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/ModeToggleButton.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/ModeToggleButton.tsxindex 6a3ab0d34d..5636123324 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/ModeToggleButton.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/ModeToggleButton.tsx@@ -2,6 +2,11 @@import { cn } from "@/lib/utils";import { Brain, Lightning } from "@phosphor-icons/react";+import {+ Tooltip,+ TooltipContent,+ TooltipTrigger,+} from "@/components/ui/tooltip";import type { CopilotMode } from "../../../store";interface Props {@@ -11,37 +16,42 @@ interface Props {export function ModeToggleButton({ mode, onToggle }: Props) {const isExtended = mode === "extended_thinking";++ const tooltipText = isExtended+ ? "Extended Thinking — deeper reasoning (click to switch to Fast)"+ : "Fast mode — quicker responses (click to switch to Thinking)";+return (- <button- type="button"- aria-pressed={isExtended}- onClick={onToggle}- className={cn(- "inline-flex min-h-11 min-w-11 items-center justify-center gap-1 rounded-md px-2 py-1 text-xs font-medium transition-colors",- isExtended- ? "bg-purple-100 text-purple-900 hover:bg-purple-200"- : "bg-amber-100 text-amber-900 hover:bg-amber-200",- )}- aria-label={- isExtended ? "Switch to Fast mode" : "Switch to Extended Thinking mode"- }- title={- isExtended- ? "Extended Thinking mode — deeper reasoning (click to switch to Fast mode)"- : "Fast mode — quicker responses (click to switch to Extended Thinking)"- }- >- {isExtended ? (- <>- <Brain size={14} />- Thinking- </>- ) : (- <>- <Lightning size={14} />- Fast- </>- )}- </button>+ <Tooltip>+ <TooltipTrigger asChild>+ <button+ type="button"+ aria-pressed={isExtended}+ onClick={onToggle}+ className={cn(+ "ml-2 inline-flex h-9 items-center justify-center gap-1 rounded-full border border-neutral-200 bg-white px-2.5 text-xs font-medium shadow-sm transition-colors hover:bg-neutral-50",+ isExtended ? "text-purple-900" : "text-amber-900",+ )}+ aria-label={+ isExtended+ ? "Switch to Fast mode"+ : "Switch to Extended Thinking mode"+ }+ >+ {isExtended ? (+ <>+ <Brain size={14} />+ Thinking+ </>+ ) : (+ <>+ <Lightning size={14} />+ Fast+ </>+ )}+ </button>+ </TooltipTrigger>+ <TooltipContent>{tooltipText}</TooltipContent>+ </Tooltip>);}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/ModelToggleButton.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/ModelToggleButton.tsxindex cb3bc25f4f..68ec4d5fac 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/ModelToggleButton.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/ModelToggleButton.tsx@@ -2,6 +2,11 @@import { cn } from "@/lib/utils";import { Cpu } from "@phosphor-icons/react";+import {+ Tooltip,+ TooltipContent,+ TooltipTrigger,+} from "@/components/ui/tooltip";import type { CopilotLlmModel } from "../../../store";interface Props {@@ -12,27 +17,33 @@ interface Props {export function ModelToggleButton({ model, onToggle }: Props) {const isAdvanced = model === "advanced";return (- <button- type="button"- aria-pressed={isAdvanced}- onClick={onToggle}- className={cn(- "inline-flex min-h-11 min-w-11 items-center justify-center gap-1 rounded-md px-2 py-1 text-xs font-medium transition-colors",- isAdvanced- ? "bg-sky-100 text-sky-900 hover:bg-sky-200"- : "text-neutral-500 hover:bg-neutral-100 hover:text-neutral-700",- )}- aria-label={- isAdvanced ? "Switch to Standard model" : "Switch to Advanced model"- }- title={- isAdvanced- ? "Advanced model — highest capability (click to switch to Standard)"- : "Standard model — click to switch to Advanced"- }- >- <Cpu size={14} />- {isAdvanced && "Advanced"}- </button>+ <Tooltip>+ <TooltipTrigger asChild>+ <button+ type="button"+ aria-pressed={isAdvanced}+ onClick={onToggle}+ className={cn(+ "inline-flex h-9 items-center justify-center gap-1 rounded-full border border-neutral-200 bg-white px-2.5 text-xs font-medium shadow-sm transition-colors hover:bg-neutral-50",+ isAdvanced+ ? "text-sky-900"+ : "text-neutral-500 hover:text-neutral-700",+ )}+ aria-label={+ isAdvanced ? "Switch to Balanced model" : "Switch to Advanced model"+ }+ >+ <Cpu size={14} />+ <span className="hidden sm:inline">+ {isAdvanced ? "Advanced" : "Balanced"}+ </span>+ </button>+ </TooltipTrigger>+ <TooltipContent>+ {isAdvanced+ ? "Using the highest-capability model (click to switch to Balanced)."+ : "Using the balanced default model (click to switch to Advanced)."}+ </TooltipContent>+ </Tooltip>);}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/__tests__/DryRunToggleButton.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/__tests__/DryRunToggleButton.test.tsxindex d8920c8749..f48f8a40c8 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/__tests__/DryRunToggleButton.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/__tests__/DryRunToggleButton.test.tsx@@ -1,21 +1,32 @@-import { render, screen, fireEvent, cleanup } from "@testing-library/react";+import {+ render as rtlRender,+ screen,+ fireEvent,+ cleanup,+} from "@testing-library/react";import { afterEach, describe, expect, it, vi } from "vitest";+import type { ReactElement } from "react";+import { TooltipProvider } from "@/components/ui/tooltip";import { DryRunToggleButton } from "../DryRunToggleButton";afterEach(cleanup);+function render(ui: ReactElement) {+ return rtlRender(<TooltipProvider>{ui}</TooltipProvider>);+}+// DryRunToggleButton only appears on new chats (no active session).// It has no readOnly/isStreaming props — those scenarios are handled by hiding// the button entirely at the ChatInput level when hasSession is true.describe("DryRunToggleButton", () => {- it("shows Test label when isDryRun is true", () => {+ it("shows enabled label when isDryRun is true", () => {render(<DryRunToggleButton isDryRun={true} onToggle={vi.fn()} />);- expect(screen.getByText("Test")).toBeTruthy();+ expect(screen.getByText("Test mode enabled")).toBeTruthy();});- it("shows no text label when isDryRun is false", () => {+ it("shows enable label when isDryRun is false", () => {render(<DryRunToggleButton isDryRun={false} onToggle={vi.fn()} />);- expect(screen.queryByText("Test")).toBeNull();+ expect(screen.getByText("Enable test mode")).toBeTruthy();});it("calls onToggle when clicked", () => {diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/__tests__/ModelToggleButton.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/__tests__/ModelToggleButton.test.tsxindex a17e702f1a..6193eb8694 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/__tests__/ModelToggleButton.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/__tests__/ModelToggleButton.test.tsx@@ -1,9 +1,20 @@-import { render, screen, fireEvent, cleanup } from "@testing-library/react";+import {+ render as rtlRender,+ screen,+ fireEvent,+ cleanup,+} from "@testing-library/react";import { afterEach, describe, expect, it, vi } from "vitest";+import type { ReactElement } from "react";+import { TooltipProvider } from "@/components/ui/tooltip";import { ModelToggleButton } from "../ModelToggleButton";afterEach(cleanup);+function render(ui: ReactElement) {+ return rtlRender(<TooltipProvider>{ui}</TooltipProvider>);+}+describe("ModelToggleButton", () => {it("shows no text label when model is standard", () => {render(<ModelToggleButton model="standard" onToggle={vi.fn()} />);@@ -31,7 +42,7 @@ describe("ModelToggleButton", () => {it("sets aria-pressed=true for advanced", () => {render(<ModelToggleButton model="advanced" onToggle={vi.fn()} />);- const btn = screen.getByLabelText("Switch to Standard model");+ const btn = screen.getByLabelText("Switch to Balanced model");expect(btn.getAttribute("aria-pressed")).toBe("true");});});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.tsxindex 0bd0cb8a5b..933172b880 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/EmptySession/EmptySession.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/EmptySession/EmptySession.tsx@@ -13,6 +13,10 @@ import {getSuggestionThemes,} from "./helpers";import { SuggestionThemes } from "./components/SuggestionThemes/SuggestionThemes";+import { PulseChips } from "../PulseChips/PulseChips";+import { usePulseChips } from "../PulseChips/usePulseChips";+import { Flag, useGetFlag } from "@/services/feature-flags/use-get-flag";+import { EditNameDialog } from "./components/EditNameDialog/EditNameDialog";interface Props {inputLayoutId: string;@@ -34,6 +38,8 @@ export function EmptySession({}: Props) {const { user } = useSupabase();const greetingName = getGreetingName(user);+ const isAgentBriefingEnabled = useGetFlag(Flag.AGENT_BRIEFING);+ const pulseChips = usePulseChips();const { data: suggestedPromptsResponse, isLoading: isLoadingPrompts } =useGetV2GetSuggestedPrompts({@@ -75,11 +81,16 @@ export function EmptySession({<div className="mx-auto max-w-[52rem]"><Text variant="h3" className="mb-1 !text-[1.375rem] text-zinc-700">Hey, <span className="text-violet-600">{greetingName}</span>+ <EditNameDialog currentName={greetingName} /></Text><Text variant="h3" className="mb-8 !font-normal">Tell me about your work — I'll find what to automate.</Text>+ {isAgentBriefingEnabled && (+ <PulseChips chips={pulseChips} onChipClick={onSend} />+ )}+<div className="mb-6"><motion.divlayoutId={inputLayoutId}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/EmptySession/components/EditNameDialog/EditNameDialog.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/EmptySession/components/EditNameDialog/EditNameDialog.tsxnew file mode 100644index 0000000000..ba47bb9223--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/EmptySession/components/EditNameDialog/EditNameDialog.tsx@@ -0,0 +1,105 @@+"use client";++import { Button } from "@/components/atoms/Button/Button";+import { Input } from "@/components/atoms/Input/Input";+import { Dialog } from "@/components/molecules/Dialog/Dialog";+import { useToast } from "@/components/molecules/Toast/use-toast";+import { useSupabase } from "@/lib/supabase/hooks/useSupabase";+import { PencilSimpleIcon } from "@phosphor-icons/react";+import { useState } from "react";++interface Props {+ currentName: string;+}++export function EditNameDialog({ currentName }: Props) {+ const [isOpen, setIsOpen] = useState(false);+ const [name, setName] = useState(currentName);+ const [isSaving, setIsSaving] = useState(false);+ const { supabase, refreshSession } = useSupabase();+ const { toast } = useToast();++ function handleOpenChange(open: boolean) {+ if (open) setName(currentName);+ setIsOpen(open);+ }++ async function handleSave() {+ const trimmed = name.trim();+ if (!trimmed || !supabase) return;++ setIsSaving(true);+ try {+ const { error } = await supabase.auth.updateUser({+ data: { full_name: trimmed },+ });++ if (error) {+ toast({+ title: "Failed to update name",+ description: error.message,+ variant: "destructive",+ });+ return;+ }++ try {+ await refreshSession();+ } catch (e) {+ toast({+ title: "Name saved, but session refresh failed",+ description: e instanceof Error ? e.message : "Please reload.",+ variant: "destructive",+ });+ setIsOpen(false);+ return;+ }+ setIsOpen(false);+ toast({ title: "Name updated" });+ } finally {+ setIsSaving(false);+ }+ }++ return (+ <Dialog+ title="Edit display name"+ styling={{ maxWidth: "24rem" }}+ controlled={{ isOpen, set: handleOpenChange }}+ >+ <Dialog.Trigger>+ <button+ type="button"+ className="ml-1 inline-flex items-center text-violet-500 transition-colors hover:text-violet-700"+ >+ <PencilSimpleIcon size={16} />+ </button>+ </Dialog.Trigger>+ <Dialog.Content>+ <div className="flex flex-col gap-4 px-1">+ <Input+ id="display-name"+ label="Display name"+ placeholder="Your name"+ value={name}+ onChange={(e) => setName(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === "Enter") {+ e.preventDefault();+ handleSave();+ }+ }}+ />+ <Button+ variant="primary"+ onClick={handleSave}+ disabled={!name.trim() || isSaving}+ loading={isSaving}+ >+ Save+ </Button>+ </div>+ </Dialog.Content>+ </Dialog>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/EmptySession/components/EditNameDialog/__tests__/EditNameDialog.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/EmptySession/components/EditNameDialog/__tests__/EditNameDialog.test.tsxnew file mode 100644index 0000000000..873a08f4c8--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/EmptySession/components/EditNameDialog/__tests__/EditNameDialog.test.tsx@@ -0,0 +1,138 @@+import { beforeEach, describe, expect, test, vi } from "vitest";+import {+ fireEvent,+ render,+ screen,+ waitFor,+} from "@/tests/integrations/test-utils";+import { EditNameDialog } from "../EditNameDialog";++const mockToast = vi.hoisted(() => vi.fn());+const mockUseSupabase = vi.hoisted(() => vi.fn());++vi.mock("@/components/molecules/Toast/use-toast", () => ({+ useToast: () => ({ toast: mockToast }),+}));++vi.mock("@/lib/supabase/hooks/useSupabase", () => ({+ useSupabase: mockUseSupabase,+}));++function setup({+ updateUser = vi.fn().mockResolvedValue({ error: null }),+ refreshSession = vi.fn().mockResolvedValue(undefined),+}: {+ updateUser?: ReturnType<typeof vi.fn>;+ refreshSession?: ReturnType<typeof vi.fn>;+} = {}) {+ mockUseSupabase.mockReturnValue({+ supabase: { auth: { updateUser } },+ refreshSession,+ });+ return { updateUser, refreshSession };+}++async function openDialogAndGetInput() {+ const trigger = screen.getByRole("button");+ fireEvent.click(trigger);+ await screen.findAllByLabelText(/display name/i);+ const inputs =+ document.querySelectorAll<HTMLInputElement>("input#display-name");+ return inputs[0];+}++function getSaveButton() {+ const saves = screen.getAllByRole("button", { name: /save/i });+ return saves[0] as HTMLButtonElement;+}++describe("EditNameDialog", () => {+ beforeEach(() => {+ mockToast.mockReset();+ mockUseSupabase.mockReset();+ });++ test("opens dialog with current name prefilled", async () => {+ setup();+ render(<EditNameDialog currentName="Alice" />);++ const input = await openDialogAndGetInput();+ expect(input.value).toBe("Alice");+ });++ test("saves name successfully and closes dialog", async () => {+ const { updateUser, refreshSession } = setup();+ render(<EditNameDialog currentName="Alice" />);++ const input = await openDialogAndGetInput();+ fireEvent.change(input, { target: { value: "Bob" } });+ fireEvent.click(getSaveButton());++ await waitFor(() => {+ expect(updateUser).toHaveBeenCalledWith({ data: { full_name: "Bob" } });+ });+ expect(refreshSession).toHaveBeenCalled();+ await waitFor(() => {+ expect(mockToast).toHaveBeenCalledWith({ title: "Name updated" });+ });+ });++ test("shows error toast when updateUser fails and keeps dialog open", async () => {+ const updateUser = vi+ .fn()+ .mockResolvedValue({ error: { message: "Network error" } });+ const refreshSession = vi.fn();+ setup({ updateUser, refreshSession });++ render(<EditNameDialog currentName="Alice" />);++ const input = await openDialogAndGetInput();+ fireEvent.change(input, { target: { value: "Bob" } });+ fireEvent.click(getSaveButton());++ await waitFor(() => {+ expect(mockToast).toHaveBeenCalledWith(+ expect.objectContaining({+ title: "Failed to update name",+ description: "Network error",+ variant: "destructive",+ }),+ );+ });+ expect(refreshSession).not.toHaveBeenCalled();+ });++ test("closes dialog and toasts failure when refreshSession throws", async () => {+ const updateUser = vi.fn().mockResolvedValue({ error: null });+ const refreshSession = vi+ .fn()+ .mockRejectedValue(new Error("refresh failed"));+ setup({ updateUser, refreshSession });++ render(<EditNameDialog currentName="Alice" />);++ const input = await openDialogAndGetInput();+ fireEvent.change(input, { target: { value: "Bob" } });+ fireEvent.click(getSaveButton());++ await waitFor(() => {+ expect(mockToast).toHaveBeenCalledWith(+ expect.objectContaining({+ title: "Name saved, but session refresh failed",+ variant: "destructive",+ }),+ );+ });+ expect(mockToast).not.toHaveBeenCalledWith({ title: "Name updated" });+ });++ test("disables Save button while empty input", async () => {+ setup();+ render(<EditNameDialog currentName="Alice" />);++ const input = await openDialogAndGetInput();+ fireEvent.change(input, { target: { value: " " } });++ expect(getSaveButton().disabled).toBe(true);+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/PulseChips/PulseChips.module.css b/autogpt_platform/frontend/src/app/(platform)/copilot/components/PulseChips/PulseChips.module.cssnew file mode 100644index 0000000000..da221fb7d8--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/PulseChips/PulseChips.module.css@@ -0,0 +1,93 @@+.glassPanel {+ position: relative;+ isolation: isolate;+}++.glassPanel::before {+ content: "";+ position: absolute;+ inset: 0;+ border-radius: inherit;+ padding: 1px;+ background: conic-gradient(+ from var(--border-angle, 0deg),+ rgba(129, 120, 228, 0.08),+ rgba(129, 120, 228, 0.28),+ rgba(168, 130, 255, 0.18),+ rgba(129, 120, 228, 0.08),+ rgba(99, 102, 241, 0.24),+ rgba(129, 120, 228, 0.08)+ );+ -webkit-mask:+ linear-gradient(#000 0 0) content-box,+ linear-gradient(#000 0 0);+ mask:+ linear-gradient(#000 0 0) content-box,+ linear-gradient(#000 0 0);+ -webkit-mask-composite: xor;+ mask-composite: exclude;+ animation: rotate-border 6s linear infinite;+ pointer-events: none;+ z-index: -1;+}++@property --border-angle {+ syntax: "<angle>";+ initial-value: 0deg;+ inherits: false;+}++@keyframes rotate-border {+ to {+ --border-angle: 360deg;+ }+}++.chip {+ overflow: hidden;+}++@media (hover: hover) {+ .chip {+ padding-bottom: 0.9rem;+ }+}++@media (hover: none) {+ .chip {+ padding-bottom: 2.25rem;+ }+}++.chipActions {+ position: absolute;+ inset-inline: 0;+ bottom: 0;+ background: rgba(255, 255, 255, 0.95);+ backdrop-filter: blur(4px);+ -webkit-backdrop-filter: blur(4px);+}++@media (hover: hover) {+ .chipActions {+ opacity: 0;+ transform: translateY(100%);+ transition:+ opacity 0.2s ease-out,+ transform 0.2s ease-out;+ }++ .chip:hover .chipActions {+ opacity: 1;+ transform: translateY(0);+ }++ .chipContent {+ transition: filter 0.2s ease-out;+ }++ .chip:hover .chipContent {+ filter: blur(2px);+ opacity: 0.5;+ }+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/PulseChips/PulseChips.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/PulseChips/PulseChips.tsxnew file mode 100644index 0000000000..f1fb984dfb--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/PulseChips/PulseChips.tsx@@ -0,0 +1,116 @@+"use client";++import { Text } from "@/components/atoms/Text/Text";+import {+ ArrowRightIcon,+ EyeIcon,+ ChatCircleDotsIcon,+} from "@phosphor-icons/react";+import NextLink from "next/link";+import { StatusBadge } from "@/app/(platform)/library/components/StatusBadge/StatusBadge";+import styles from "./PulseChips.module.css";+import type { PulseChipData } from "./types";++interface Props {+ chips: PulseChipData[];+ onChipClick?: (prompt: string) => void;+}++export function PulseChips({ chips, onChipClick }: Props) {+ if (chips.length === 0) return null;++ return (+ <div+ className={`${styles.glassPanel} mx-[0.6875rem] mb-5 rounded-large p-5`}+ >+ <div className="mb-3 flex items-center gap-3">+ <Text variant="body-medium" className="text-zinc-600">+ What's happening with your agents+ </Text>+ <NextLink+ href="/library"+ className="flex items-center gap-1 text-xs text-zinc-500 hover:text-zinc-700"+ >+ View all <ArrowRightIcon size={12} />+ </NextLink>+ </div>+ <div className="flex gap-2 overflow-x-auto">+ {chips.map((chip) => (+ <PulseChip key={chip.id} chip={chip} onAsk={onChipClick} />+ ))}+ </div>+ </div>+ );+}++interface ChipProps {+ chip: PulseChipData;+ onAsk?: (prompt: string) => void;+}++function PulseChip({ chip, onAsk }: ChipProps) {+ function handleAsk() {+ const prompt = buildChipPrompt(chip);+ onAsk?.(prompt);+ }++ return (+ <div+ className={`${styles.chip} relative flex shrink-0 flex-col items-start gap-2 rounded-medium border border-zinc-100 bg-white px-3 py-2`}+ >+ <div className={`${styles.chipContent} w-full text-left`}>+ {chip.priority === "success" ? (+ <span className="inline-flex items-center gap-1.5 rounded-full px-2 py-0.5 text-xs font-medium text-emerald-600">+ <span className="h-1.5 w-1.5 rounded-full bg-emerald-500" />+ Completed+ </span>+ ) : (+ <StatusBadge status={chip.status} />+ )}+ <div className="mt-2 min-w-0">+ <Text variant="small-medium" className="truncate text-zinc-900">+ {chip.name}+ </Text>+ <Text variant="small" className="truncate text-zinc-500">+ {chip.shortMessage}+ </Text>+ </div>+ </div>+ <div+ className={`${styles.chipActions} flex items-center justify-center gap-1.5 rounded-b-medium px-3 py-1.5`}+ >+ <NextLink+ href={`/library/agents/${chip.agentID}`}+ className="flex items-center gap-1 rounded-md px-2 py-1 text-xs text-zinc-500 transition-colors hover:bg-zinc-100 hover:text-zinc-700"+ >+ <EyeIcon size={14} />+ See+ </NextLink>+ <button+ type="button"+ onClick={handleAsk}+ className="flex items-center gap-1 rounded-md px-2 py-1 text-xs text-zinc-500 transition-colors hover:bg-zinc-100 hover:text-zinc-700"+ >+ <ChatCircleDotsIcon size={14} />+ Ask+ </button>+ </div>+ </div>+ );+}++function buildChipPrompt(chip: PulseChipData): string {+ if (chip.priority === "success") {+ return `${chip.name} just finished a run — can you summarize what it did?`;+ }+ switch (chip.status) {+ case "error":+ return `What happened with ${chip.name}? It has an error — can you check?`;+ case "running":+ return `Give me a status update on ${chip.name} — what has it done so far?`;+ case "idle":+ return `${chip.name} hasn't run recently. Should I keep it or update and re-run it?`;+ default:+ return `Tell me about ${chip.name} — what's its current status?`;+ }+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/PulseChips/types.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/PulseChips/types.tsnew file mode 100644index 0000000000..7650afe5ee--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/PulseChips/types.ts@@ -0,0 +1,13 @@+import type {+ AgentStatus,+ SitrepPriority,+} from "@/app/(platform)/library/types";++export interface PulseChipData {+ id: string;+ agentID: string;+ name: string;+ status: AgentStatus;+ priority: SitrepPriority;+ shortMessage: string;+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/PulseChips/usePulseChips.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/PulseChips/usePulseChips.tsnew file mode 100644index 0000000000..f1d56232fe--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/PulseChips/usePulseChips.ts@@ -0,0 +1,23 @@+"use client";++import { useLibraryAgents } from "@/hooks/useLibraryAgents/useLibraryAgents";+import { useSitrepItems } from "@/app/(platform)/library/components/SitrepItem/useSitrepItems";+import type { PulseChipData } from "./types";+import { useMemo } from "react";++export function usePulseChips(): PulseChipData[] {+ const { agents } = useLibraryAgents();++ const sitrepItems = useSitrepItems(agents, 5);++ return useMemo(() => {+ return sitrepItems.map((item) => ({+ id: item.id,+ agentID: item.agentID,+ name: item.agentName,+ status: item.status,+ priority: item.priority,+ shortMessage: item.message,+ }));+ }, [sitrepItems]);+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/RateLimitResetDialog/RateLimitResetDialog.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/RateLimitResetDialog/RateLimitResetDialog.tsxindex c704a5505d..22e892655a 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/RateLimitResetDialog/RateLimitResetDialog.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/RateLimitResetDialog/RateLimitResetDialog.tsx@@ -6,6 +6,9 @@ import { Dialog } from "@/components/molecules/Dialog/Dialog";import { useRouter } from "next/navigation";import { useEffect, useRef } from "react";import { useResetRateLimit } from "../../hooks/useResetRateLimit";+import { formatCents } from "../usageHelpers";++export { formatCents };interface Props {isOpen: boolean;@@ -18,10 +21,6 @@ interface Props {onCreditChange?: () => void;}-export function formatCents(cents: number): string {- return `$${(cents / 100).toFixed(2)}`;-}-export function RateLimitResetDialog({isOpen,onClose,diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/UsageLimits/UsagePanelContent.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/UsageLimits/UsagePanelContent.tsxindex fe420d145d..91187816da 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/UsageLimits/UsagePanelContent.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/UsageLimits/UsagePanelContent.tsx@@ -1,35 +1,10 @@import type { CoPilotUsageStatus } from "@/app/api/__generated__/models/coPilotUsageStatus";import { Button } from "@/components/atoms/Button/Button";import Link from "next/link";-import { formatCents } from "../RateLimitResetDialog/RateLimitResetDialog";+import { formatCents, formatResetTime } from "../usageHelpers";import { useResetRateLimit } from "../../hooks/useResetRateLimit";-export function formatResetTime(- resetsAt: Date | string,- now: Date = new Date(),-): string {- const resetDate =- typeof resetsAt === "string" ? new Date(resetsAt) : resetsAt;- const diffMs = resetDate.getTime() - now.getTime();- if (diffMs <= 0) return "now";-- const hours = Math.floor(diffMs / (1000 * 60 * 60));-- // Under 24h: show relative time ("in 4h 23m")- if (hours < 24) {- const minutes = Math.floor((diffMs % (1000 * 60 * 60)) / (1000 * 60));- if (hours > 0) return `in ${hours}h ${minutes}m`;- return `in ${minutes}m`;- }-- // Over 24h: show day and time in local timezone ("Mon 12:00 AM PST")- return resetDate.toLocaleString(undefined, {- weekday: "short",- hour: "numeric",- minute: "2-digit",- timeZoneName: "short",- });-}+export { formatResetTime };function UsageBar({label,diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/usageHelpers.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/usageHelpers.tsnew file mode 100644index 0000000000..599442075f--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/usageHelpers.ts@@ -0,0 +1,28 @@+export function formatCents(cents: number): string {+ return `$${(cents / 100).toFixed(2)}`;+}++export function formatResetTime(+ resetsAt: Date | string,+ now: Date = new Date(),+): string {+ const resetDate =+ typeof resetsAt === "string" ? new Date(resetsAt) : resetsAt;+ const diffMs = resetDate.getTime() - now.getTime();+ if (diffMs <= 0) return "now";++ const hours = Math.floor(diffMs / (1000 * 60 * 60));++ if (hours < 24) {+ const minutes = Math.floor((diffMs % (1000 * 60 * 60)) / (1000 * 60));+ if (hours > 0) return `in ${hours}h ${minutes}m`;+ return `in ${minutes}m`;+ }++ return resetDate.toLocaleString(undefined, {+ weekday: "short",+ hour: "numeric",+ minute: "2-digit",+ timeZoneName: "short",+ });+}diff --git a/autogpt_platform/frontend/src/app/(platform)/layout.tsx b/autogpt_platform/frontend/src/app/(platform)/layout.tsxindex 048110f8b2..0d72326e17 100644--- a/autogpt_platform/frontend/src/app/(platform)/layout.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/layout.tsx@@ -2,14 +2,17 @@ import { Navbar } from "@/components/layout/Navbar/Navbar";import { NetworkStatusMonitor } from "@/services/network-status/NetworkStatusMonitor";import { ReactNode } from "react";import { AdminImpersonationBanner } from "./admin/components/AdminImpersonationBanner";+import { AutoPilotBridgeProvider } from "@/contexts/AutoPilotBridgeContext";export default function PlatformLayout({ children }: { children: ReactNode }) {return (- <main className="flex h-screen w-full flex-col">- <NetworkStatusMonitor />- <Navbar />- <AdminImpersonationBanner />- <section className="flex-1">{children}</section>- </main>+ <AutoPilotBridgeProvider>+ <main className="flex h-screen w-full flex-col">+ <NetworkStatusMonitor />+ <Navbar />+ <AdminImpersonationBanner />+ <section className="flex-1">{children}</section>+ </main>+ </AutoPilotBridgeProvider>);}diff --git a/autogpt_platform/frontend/src/app/(platform)/library/__tests__/main.test.tsx b/autogpt_platform/frontend/src/app/(platform)/library/__tests__/main.test.tsxindex 8d7960dc9b..6f6d7f3794 100644--- a/autogpt_platform/frontend/src/app/(platform)/library/__tests__/main.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/library/__tests__/main.test.tsx@@ -137,8 +137,10 @@ describe("LibraryPage", () => {user_id: "test-user",name: "Work Agents",agent_count: 3,+ subfolder_count: 0,color: null,icon: null,+ parent_id: null,created_at: new Date(),updated_at: new Date(),},@@ -147,8 +149,10 @@ describe("LibraryPage", () => {user_id: "test-user",name: "Personal",agent_count: 1,+ subfolder_count: 0,color: null,icon: null,+ parent_id: null,created_at: new Date(),updated_at: new Date(),},@@ -158,12 +162,14 @@ describe("LibraryPage", () => {render(<LibraryPage />);+ await waitForAgentsToLoad();+expect(await screen.findByText("Work Agents")).toBeDefined();expect(screen.getByText("Personal")).toBeDefined();expect(screen.getAllByTestId("library-folder")).toHaveLength(2);});- test("shows See runs link on agent card", async () => {+ test("shows See tasks link on agent card", async () => {setupHandlers({agents: [makeAgent({ name: "Linked Agent", can_access_graph: true })],});@@ -172,7 +178,7 @@ describe("LibraryPage", () => {await screen.findByText("Linked Agent");- const runLinks = screen.getAllByText("See runs");+ const runLinks = screen.getAllByText("See tasks");expect(runLinks.length).toBeGreaterThan(0);});@@ -190,7 +196,7 @@ describe("LibraryPage", () => {expect(importButtons.length).toBeGreaterThan(0);});- test("renders Jump Back In when there is an active execution", async () => {+ test("renders running agent card when execution is active", async () => {const agent = makeAgent({id: "lib-1",graph_id: "g-1",@@ -218,6 +224,6 @@ describe("LibraryPage", () => {render(<LibraryPage />);- expect(await screen.findByText("Jump Back In")).toBeDefined();+ expect(await screen.findByText("Running Agent")).toBeDefined();});});diff --git a/autogpt_platform/frontend/src/app/(platform)/library/components/AgentBriefingPanel/AgentBriefingPanel.module.css b/autogpt_platform/frontend/src/app/(platform)/library/components/AgentBriefingPanel/AgentBriefingPanel.module.cssnew file mode 100644index 0000000000..8c2bd69313--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/library/components/AgentBriefingPanel/AgentBriefingPanel.module.css@@ -0,0 +1,44 @@+.glassPanel {+ position: relative;+ isolation: isolate;+}++.glassPanel::before {+ content: "";+ position: absolute;+ inset: 0;+ border-radius: inherit;+ padding: 1px;+ background: conic-gradient(+ from var(--border-angle, 0deg),+ rgba(129, 120, 228, 0.04),+ rgba(129, 120, 228, 0.14),+ rgba(168, 130, 255, 0.09),+ rgba(129, 120, 228, 0.04),+ rgba(99, 102, 241, 0.12),+ rgba(129, 120, 228, 0.04)+ );+ -webkit-mask:+ linear-gradient(#000 0 0) content-box,+ linear-gradient(#000 0 0);+ mask:+ linear-gradient(#000 0 0) content-box,+ linear-gradient(#000 0 0);+ -webkit-mask-composite: xor;+ mask-composite: exclude;+ animation: rotate-border 6s linear infinite;+ pointer-events: none;+ z-index: -1;+}++@property --border-angle {+ syntax: "<angle>";+ initial-value: 0deg;+ inherits: false;+}++@keyframes rotate-border {+ to {+ --border-angle: 360deg;+ }+}diff --git a/autogpt_platform/frontend/src/app/(platform)/library/components/AgentBriefingPanel/AgentBriefingPanel.tsx b/autogpt_platform/frontend/src/app/(platform)/library/components/AgentBriefingPanel/AgentBriefingPanel.tsxnew file mode 100644index 0000000000..82bf930b7b--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/library/components/AgentBriefingPanel/AgentBriefingPanel.tsx@@ -0,0 +1,36 @@+"use client";++import { Text } from "@/components/atoms/Text/Text";+import type { LibraryAgent } from "@/app/api/__generated__/models/libraryAgent";+import { useState } from "react";+import type { FleetSummary, AgentStatusFilter } from "../../types";+import { BriefingTabContent } from "./BriefingTabContent";+import { StatsGrid } from "./StatsGrid";+import styles from "./AgentBriefingPanel.module.css";++interface Props {+ summary: FleetSummary;+ agents: LibraryAgent[];+}++export function AgentBriefingPanel({ summary, agents }: Props) {+ const [userTab, setUserTab] = useState<AgentStatusFilter | null>(null);+ const activeTab: AgentStatusFilter =+ userTab ?? (summary.running > 0 ? "running" : "all");++ return (+ <div+ className={`${styles.glassPanel} min-h-[14.75rem] rounded-large bg-gradient-to-br from-indigo-50/30 via-white/90 to-purple-50/25 px-5 pb-5 pt-[1.125rem] shadow-sm backdrop-blur-md`}+ >+ <Text variant="h5">Agent Briefing</Text>+ <div className="mt-4 space-y-5">+ <StatsGrid+ summary={summary}+ activeTab={activeTab}+ onTabChange={setUserTab}+ />+ <BriefingTabContent activeTab={activeTab} agents={agents} />+ </div>+ </div>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/library/components/AgentBriefingPanel/BriefingTabContent.tsx b/autogpt_platform/frontend/src/app/(platform)/library/components/AgentBriefingPanel/BriefingTabContent.tsxnew file mode 100644index 0000000000..5d4df627d9--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/library/components/AgentBriefingPanel/BriefingTabContent.tsx@@ -0,0 +1,347 @@+"use client";++import type { CoPilotUsageStatus } from "@/app/api/__generated__/models/coPilotUsageStatus";+import type { LibraryAgent } from "@/app/api/__generated__/models/libraryAgent";+import { useGetV2GetCopilotUsage } from "@/app/api/__generated__/endpoints/chat/chat";+import {+ formatResetTime,+ formatCents,+} from "@/app/(platform)/copilot/components/usageHelpers";+import { useResetRateLimit } from "@/app/(platform)/copilot/hooks/useResetRateLimit";+import { Button } from "@/components/atoms/Button/Button";+import { Badge } from "@/components/atoms/Badge/Badge";+import useCredits from "@/hooks/useCredits";+import { Flag, useGetFlag } from "@/services/feature-flags/use-get-flag";+import { useSitrepItems } from "../SitrepItem/useSitrepItems";+import { SitrepItem } from "../SitrepItem/SitrepItem";+import { useAgentStatusMap } from "../../hooks/useAgentStatus";+import type { AgentStatusFilter } from "../../types";+import { Text } from "@/components/atoms/Text/Text";+import Link from "next/link";+import { useState } from "react";++interface Props {+ activeTab: AgentStatusFilter;+ agents: LibraryAgent[];+}++export function BriefingTabContent({ activeTab, agents }: Props) {+ if (activeTab === "all") {+ return <UsageSection />;+ }++ if (+ activeTab === "running" ||+ activeTab === "attention" ||+ activeTab === "completed"+ ) {+ return <ExecutionListSection activeTab={activeTab} agents={agents} />;+ }++ return <AgentListSection activeTab={activeTab} agents={agents} />;+}++function UsageSection() {+ const { data: usage } = useGetV2GetCopilotUsage({+ query: {+ select: (res) => res.data as CoPilotUsageStatus,+ refetchInterval: 30000,+ staleTime: 10000,+ },+ });++ const isBillingEnabled = useGetFlag(Flag.ENABLE_PLATFORM_PAYMENT);+ const { credits, fetchCredits } = useCredits({ fetchInitialCredits: true });+ const resetCost = usage?.reset_cost;+ const hasInsufficientCredits =+ credits !== null && resetCost != null && credits < resetCost;++ if (!usage?.daily || !usage?.weekly) return null;++ return (+ <div className="py-2">+ <div className="flex items-center gap-2">+ <Text variant="h5" className="text-neutral-800">+ Usage limits+ </Text>+ {usage.tier && (+ <Badge variant="info" size="small" className="bg-[rgb(224,237,255)]">+ {usage.tier.charAt(0) + usage.tier.slice(1).toLowerCase()} plan+ </Badge>+ )}+ <div className="flex-1" />+ {isBillingEnabled && (+ <Link+ href="/profile/credits"+ className="text-sm text-blue-600 hover:underline"+ >+ Manage billing+ </Link>+ )}+ </div>+ <div className="mt-4 grid grid-cols-1 gap-6 sm:grid-cols-2">+ {usage.daily.limit > 0 && (+ <UsageMeter+ label="Today"+ used={usage.daily.used}+ limit={usage.daily.limit}+ resetsAt={usage.daily.resets_at}+ />+ )}+ {usage.weekly.limit > 0 && (+ <UsageMeter+ label="This week"+ used={usage.weekly.used}+ limit={usage.weekly.limit}+ resetsAt={usage.weekly.resets_at}+ />+ )}+ </div>+ <UsageFooter+ usage={usage}+ hasInsufficientCredits={hasInsufficientCredits}+ onCreditChange={fetchCredits}+ />+ </div>+ );+}++const MAX_VISIBLE = 6;++function ExecutionListSection({+ activeTab,+ agents,+}: {+ activeTab: AgentStatusFilter;+ agents: LibraryAgent[];+}) {+ const allItems = useSitrepItems(agents, 50);+ const [showAll, setShowAll] = useState(false);++ const filtered = allItems.filter((item) => {+ if (activeTab === "running") return item.priority === "running";+ if (activeTab === "attention") return item.priority === "error";+ if (activeTab === "completed") return item.priority === "success";+ return false;+ });++ if (filtered.length === 0) {+ return <EmptyMessage tab={activeTab} />;+ }++ const visible = showAll ? filtered : filtered.slice(0, MAX_VISIBLE);+ const hasMore = filtered.length > MAX_VISIBLE;++ return (+ <div>+ <div className="grid grid-cols-1 gap-3 lg:grid-cols-2">+ {visible.map((item) => (+ <SitrepItem key={item.id} item={item} />+ ))}+ </div>+ {hasMore && (+ <div className="mt-3 flex justify-center">+ <Button+ variant="secondary"+ size="small"+ onClick={() => setShowAll(!showAll)}+ >+ {showAll ? "Collapse" : `Show all (${filtered.length})`}+ </Button>+ </div>+ )}+ </div>+ );+}++const TAB_STATUS_LABEL: Record<string, string> = {+ listening: "Waiting for trigger event",+ scheduled: "Has a scheduled run",+ idle: "No recent activity",+};++function AgentListSection({+ activeTab,+ agents,+}: {+ activeTab: AgentStatusFilter;+ agents: LibraryAgent[];+}) {+ const [showAll, setShowAll] = useState(false);+ const statusMap = useAgentStatusMap(agents);++ const filtered = agents.filter((agent) => {+ const status = statusMap.get(agent.graph_id)?.status;+ if (activeTab === "listening") return status === "listening";+ if (activeTab === "scheduled") return status === "scheduled";+ if (activeTab === "idle") return status === "idle";+ return false;+ });++ if (filtered.length === 0) {+ return <EmptyMessage tab={activeTab} />;+ }++ const status =+ activeTab === "listening"+ ? ("listening" as const)+ : activeTab === "scheduled"+ ? ("scheduled" as const)+ : ("idle" as const);++ const visible = showAll ? filtered : filtered.slice(0, MAX_VISIBLE);+ const hasMore = filtered.length > MAX_VISIBLE;++ return (+ <div>+ <div className="grid grid-cols-1 gap-3 lg:grid-cols-2">+ {visible.map((agent) => (+ <SitrepItem+ key={agent.id}+ item={{+ id: agent.id,+ agentID: agent.id,+ agentName: agent.name,+ agentImageUrl: agent.image_url,+ priority: status,+ message: TAB_STATUS_LABEL[activeTab] ?? "",+ status,+ }}+ />+ ))}+ </div>+ {hasMore && (+ <div className="mt-3 flex justify-center">+ <Button+ variant="secondary"+ size="small"+ onClick={() => setShowAll(!showAll)}+ >+ {showAll ? "Collapse" : `Show all (${filtered.length})`}+ </Button>+ </div>+ )}+ </div>+ );+}++function UsageFooter({+ usage,+ hasInsufficientCredits,+ onCreditChange,+}: {+ usage: CoPilotUsageStatus;+ hasInsufficientCredits: boolean;+ onCreditChange?: () => void;+}) {+ const isDailyExhausted =+ usage.daily.limit > 0 && usage.daily.used >= usage.daily.limit;+ const isWeeklyExhausted =+ usage.weekly.limit > 0 && usage.weekly.used >= usage.weekly.limit;+ const resetCost = usage.reset_cost ?? 0;+ const { resetUsage, isPending } = useResetRateLimit({ onCreditChange });++ const showReset =+ isDailyExhausted &&+ !isWeeklyExhausted &&+ resetCost > 0 &&+ !hasInsufficientCredits;++ const showAddCredits =+ isDailyExhausted && !isWeeklyExhausted && hasInsufficientCredits;++ if (!showReset && !showAddCredits) return null;++ return (+ <div className="mt-4 flex items-center gap-3">+ {showReset && (+ <Button+ variant="primary"+ size="small"+ onClick={() => resetUsage()}+ loading={isPending}+ >+ {isPending+ ? "Resetting..."+ : `Reset daily limit for ${formatCents(resetCost)}`}+ </Button>+ )}+ {showAddCredits && (+ <Link+ href="/profile/credits"+ className="inline-flex items-center justify-center rounded-md bg-primary px-3 py-1.5 text-sm font-medium text-primary-foreground hover:bg-primary/90"+ >+ Add credits to reset+ </Link>+ )}+ </div>+ );+}++function UsageMeter({+ label,+ used,+ limit,+ resetsAt,+}: {+ label: string;+ used: number;+ limit: number;+ resetsAt: Date | string;+}) {+ if (limit <= 0) return null;++ const rawPercent = (used / limit) * 100;+ const percent = Math.min(100, Math.round(rawPercent));+ const isHigh = percent >= 80;+ const percentLabel =+ used > 0 && percent === 0 ? "<1% used" : `${percent}% used`;++ return (+ <div className="flex flex-col gap-2">+ <div className="flex items-baseline justify-between">+ <Text variant="body-medium" className="text-neutral-700">+ {label}+ </Text>+ <Text variant="body" className="tabular-nums text-neutral-500">+ {percentLabel}+ </Text>+ </div>+ <div className="h-2 w-full overflow-hidden rounded-full bg-neutral-200">+ <div+ className={`h-full rounded-full transition-[width] duration-300 ease-out ${+ isHigh ? "bg-orange-500" : "bg-blue-500"+ }`}+ style={{ width: `${Math.max(used > 0 ? 1 : 0, percent)}%` }}+ />+ </div>+ <div className="flex items-baseline justify-between">+ <Text variant="small" className="tabular-nums text-neutral-500">+ {used.toLocaleString()} / {limit.toLocaleString()}+ </Text>+ <Text variant="small" className="text-neutral-400">+ Resets {formatResetTime(resetsAt)}+ </Text>+ </div>+ </div>+ );+}++const EMPTY_MESSAGES: Record<string, string> = {+ running: "No agents running right now",+ attention: "No agents that need attention",+ completed: "No recently completed runs",+ listening: "No agents listening for events",+ scheduled: "No agents with scheduled runs",+ idle: "No idle agents",+};++function EmptyMessage({ tab }: { tab: AgentStatusFilter }) {+ return (+ <div className="flex items-center justify-center pt-4">+ <Text variant="body-medium" className="text-zinc-600">+ {EMPTY_MESSAGES[tab] ?? "No agents in this category"}+ </Text>+ </div>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/library/components/AgentBriefingPanel/StatsGrid.tsx b/autogpt_platform/frontend/src/app/(platform)/library/components/AgentBriefingPanel/StatsGrid.tsxnew file mode 100644index 0000000000..74f81fae9c--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/library/components/AgentBriefingPanel/StatsGrid.tsx@@ -0,0 +1,99 @@+"use client";++import { Text } from "@/components/atoms/Text/Text";+import { Emoji } from "@/components/atoms/Emoji/Emoji";+import { cn } from "@/lib/utils";+import type { FleetSummary, AgentStatusFilter } from "../../types";++interface Props {+ summary: FleetSummary;+ activeTab: AgentStatusFilter;+ onTabChange: (tab: AgentStatusFilter) => void;+}++const TILES: {+ label: string;+ key: keyof FleetSummary;+ format?: (v: number) => string;+ filter: AgentStatusFilter;+ emoji: string;+ color: string;+}[] = [+ {+ label: "Spent this month",+ key: "monthlySpend",+ format: (v) => `$${v.toLocaleString()}`,+ filter: "all",+ emoji: "💵",+ color: "text-zinc-700",+ },+ {+ label: "Running now",+ key: "running",+ filter: "running",+ emoji: "🚩",+ color: "text-blue-600",+ },+ {+ label: "Recently completed",+ key: "completed",+ filter: "completed",+ emoji: "🗃️",+ color: "text-green-600",+ },+ {+ label: "Needs attention",+ key: "error",+ filter: "attention",+ emoji: "⚠️",+ color: "text-red-500",+ },+ {+ label: "Scheduled",+ key: "scheduled",+ filter: "scheduled",+ emoji: "📅",+ color: "text-yellow-600",+ },+ {+ label: "Idle",+ key: "idle",+ filter: "idle",+ emoji: "💤",+ color: "text-zinc-400",+ },+];++export function StatsGrid({ summary, activeTab, onTabChange }: Props) {+ return (+ <div className="grid grid-cols-1 gap-3 min-[450px]:grid-cols-2 sm:grid-cols-3 lg:grid-cols-6">+ {TILES.map((tile) => {+ const rawValue = summary[tile.key];+ const value = tile.format ? tile.format(rawValue) : rawValue;+ const isActive = activeTab === tile.filter;++ return (+ <button+ key={tile.label}+ type="button"+ onClick={() => onTabChange(tile.filter)}+ className={cn(+ "flex flex-col gap-1 rounded-medium border p-3 text-left shadow-md transition-all hover:shadow-lg",+ isActive+ ? "border-zinc-900 bg-zinc-50"+ : "border-zinc-100 bg-white",+ )}+ >+ <div className="flex items-center gap-1.5">+ <Emoji text={tile.emoji} size={18} />+ <Text variant="body" className="text-zinc-800">+ {tile.label}+ </Text>+ </div>+ <Text variant="h4">{value}</Text>+ </button>+ );+ })}+ </div>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/library/components/AgentFilterMenu/AgentFilterMenu.tsx b/autogpt_platform/frontend/src/app/(platform)/library/components/AgentFilterMenu/AgentFilterMenu.tsxnew file mode 100644index 0000000000..9d92e2f35c--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/library/components/AgentFilterMenu/AgentFilterMenu.tsx@@ -0,0 +1,50 @@+"use client";++import { Select } from "@/components/atoms/Select/Select";+import type { SelectOption } from "@/components/atoms/Select/Select";+import { FunnelIcon } from "@phosphor-icons/react";+import type { AgentStatusFilter, FleetSummary } from "../../types";++interface Props {+ value: AgentStatusFilter;+ onChange: (value: AgentStatusFilter) => void;+ summary: FleetSummary;+}++function buildOptions(summary: FleetSummary): SelectOption[] {+ return [+ { value: "all", label: "All Agents" },+ { value: "running", label: `Running (${summary.running})` },+ { value: "attention", label: `Needs Attention (${summary.error})` },+ { value: "listening", label: `Listening (${summary.listening})` },+ { value: "scheduled", label: `Scheduled (${summary.scheduled})` },+ { value: "idle", label: `Idle / Stale (${summary.idle})` },+ { value: "healthy", label: "Healthy" },+ ];+}++export function AgentFilterMenu({ value, onChange, summary }: Props) {+ function handleChange(val: string) {+ onChange(val as AgentStatusFilter);+ }++ const options = buildOptions(summary);++ return (+ <div className="flex items-center" data-testid="agent-filter-dropdown">+ <span className="hidden whitespace-nowrap text-sm sm:inline">filter</span>+ <FunnelIcon className="ml-1 h-4 w-4 sm:hidden" />+ <Select+ id="agent-status-filter"+ label="Filter agents"+ hideLabel+ value={value}+ onValueChange={handleChange}+ options={options}+ size="small"+ className="ml-1 w-fit border-none px-0 text-sm underline underline-offset-4 shadow-none"+ wrapperClassName="mb-0"+ />+ </div>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/library/components/ContextualActionButton/ContextualActionButton.tsx b/autogpt_platform/frontend/src/app/(platform)/library/components/ContextualActionButton/ContextualActionButton.tsxnew file mode 100644index 0000000000..5788db815a--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/library/components/ContextualActionButton/ContextualActionButton.tsx@@ -0,0 +1,68 @@+"use client";++import {+ EyeIcon,+ ArrowsClockwiseIcon,+ MonitorPlayIcon,+ PlayIcon,+ ArrowCounterClockwiseIcon,+} from "@phosphor-icons/react";+import { cn } from "@/lib/utils";+import { useRouter } from "next/navigation";+import type { AgentStatus } from "../../types";++interface Props {+ status: AgentStatus;+ agentID: string;+ executionID?: string;+ className?: string;+}++export function ContextualActionButton({+ status,+ agentID,+ executionID,+ className,+}: Props) {+ const router = useRouter();++ const config = ACTION_CONFIG[status];+ if (!config) return null;++ const Icon = config.icon;++ function handleClick(e: React.MouseEvent) {+ e.preventDefault();+ e.stopPropagation();++ const params = new URLSearchParams();+ if (executionID) params.set("activeItem", executionID);+ const query = params.toString();+ router.push(`/library/agents/${agentID}${query ? `?${query}` : ""}`);+ }++ return (+ <button+ type="button"+ onClick={handleClick}+ className={cn(+ "inline-flex items-center gap-1 rounded-md px-2 py-1.5 text-[13px] font-medium text-zinc-600 transition-colors hover:bg-zinc-50 hover:text-zinc-800",+ className,+ )}+ >+ <Icon size={12} className="shrink-0" />+ {config.label}+ </button>+ );+}++const ACTION_CONFIG: Record<+ AgentStatus,+ { label: string; icon: typeof EyeIcon }+> = {+ error: { label: "View error", icon: EyeIcon },+ listening: { label: "Reconnect", icon: ArrowsClockwiseIcon },+ running: { label: "Watch live", icon: MonitorPlayIcon },+ idle: { label: "Start", icon: PlayIcon },+ scheduled: { label: "Start", icon: ArrowCounterClockwiseIcon },+};diff --git a/autogpt_platform/frontend/src/app/(platform)/library/components/JumpBackIn/JumpBackIn.tsx b/autogpt_platform/frontend/src/app/(platform)/library/components/JumpBackIn/JumpBackIn.tsxdeleted file mode 100644index d8a108b88b..0000000000--- a/autogpt_platform/frontend/src/app/(platform)/library/components/JumpBackIn/JumpBackIn.tsx+++ /dev/null@@ -1,46 +0,0 @@-"use client";--import { ArrowRight, Lightning } from "@phosphor-icons/react";-import NextLink from "next/link";--import { Button } from "@/components/atoms/Button/Button";-import { Text } from "@/components/atoms/Text/Text";-import { useJumpBackIn } from "./useJumpBackIn";--export function JumpBackIn() {- const { execution, isLoading } = useJumpBackIn();-- if (isLoading || !execution) {- return null;- }-- const href = execution.libraryAgentId- ? `/library/agents/${execution.libraryAgentId}?activeTab=runs&activeItem=${execution.id}`- : "#";-- return (- <div className="rounded-large bg-gradient-to-r from-zinc-200 via-zinc-200/60 to-indigo-200/50 p-[1px]">- <div className="flex items-center justify-between rounded-large bg-[#F6F7F8] px-5 py-4">- <div className="flex items-center gap-3">- <div className="flex h-9 w-9 items-center justify-center rounded-full bg-zinc-900">- <Lightning size={18} weight="fill" className="text-white" />- </div>- <div className="flex flex-col">- <Text variant="small" className="text-zinc-500">- {execution.statusLabel} · {execution.duration}- </Text>- <Text variant="body-medium" className="text-zinc-900">- {execution.agentName}- </Text>- </div>- </div>- <NextLink href={href}>- <Button variant="secondary" size="small" className="gap-1.5">- Jump Back In- <ArrowRight size={16} />- </Button>- </NextLink>- </div>- </div>- );-}diff --git a/autogpt_platform/frontend/src/app/(platform)/library/components/JumpBackIn/useJumpBackIn.ts b/autogpt_platform/frontend/src/app/(platform)/library/components/JumpBackIn/useJumpBackIn.tsdeleted file mode 100644index 295a656caf..0000000000--- a/autogpt_platform/frontend/src/app/(platform)/library/components/JumpBackIn/useJumpBackIn.ts+++ /dev/null@@ -1,82 +0,0 @@-"use client";--import { useGetV1ListAllExecutions } from "@/app/api/__generated__/endpoints/graphs/graphs";-import { AgentExecutionStatus } from "@/app/api/__generated__/models/agentExecutionStatus";-import { okData } from "@/app/api/helpers";-import { useLibraryAgents } from "@/hooks/useLibraryAgents/useLibraryAgents";-import { useMemo } from "react";--function isActive(status: AgentExecutionStatus) {- return (- status === AgentExecutionStatus.RUNNING ||- status === AgentExecutionStatus.QUEUED ||- status === AgentExecutionStatus.REVIEW- );-}--function formatDuration(startedAt: Date | string | null | undefined): string {- if (!startedAt) return "";-- const start = new Date(startedAt);- if (isNaN(start.getTime())) return "";-- const ms = Date.now() - start.getTime();- if (ms < 0) return "";-- const sec = Math.floor(ms / 1000);- if (sec < 5) return "a few seconds";- if (sec < 60) return `${sec}s`;- const min = Math.floor(sec / 60);- if (min < 60) return `${min}m ${sec % 60}s`;- const hr = Math.floor(min / 60);- return `${hr}h ${min % 60}m`;-}--function getStatusLabel(status: AgentExecutionStatus) {- if (status === AgentExecutionStatus.RUNNING) return "Running";- if (status === AgentExecutionStatus.QUEUED) return "Queued";- if (status === AgentExecutionStatus.REVIEW) return "Awaiting approval";- return "";-}--export function useJumpBackIn() {- const { data: executions, isLoading: executionsLoading } =- useGetV1ListAllExecutions({- query: { select: okData },- });-- const { agentInfoMap, isRefreshing: agentsLoading } = useLibraryAgents();-- const activeExecution = useMemo(() => {- if (!executions) return null;-- const active = executions- .filter((e) => isActive(e.status))- .sort((a, b) => {- const aTime = a.started_at ? new Date(a.started_at).getTime() : 0;- const bTime = b.started_at ? new Date(b.started_at).getTime() : 0;- return bTime - aTime;- });-- return active[0] ?? null;- }, [executions]);-- const enriched = useMemo(() => {- if (!activeExecution) return null;-- const info = agentInfoMap.get(activeExecution.graph_id);- return {- id: activeExecution.id,- agentName: info?.name ?? "Unknown Agent",- libraryAgentId: info?.library_agent_id,- status: activeExecution.status,- statusLabel: getStatusLabel(activeExecution.status),- duration: formatDuration(activeExecution.started_at),- };- }, [activeExecution, agentInfoMap]);-- return {- execution: enriched,- isLoading: executionsLoading || agentsLoading,- };-}diff --git a/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryActionHeader/LibraryActionHeader.tsx b/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryActionHeader/LibraryActionHeader.tsxindex 54b5f4bf9c..c41b67cb36 100644--- a/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryActionHeader/LibraryActionHeader.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryActionHeader/LibraryActionHeader.tsx@@ -8,7 +8,7 @@ interface Props {export function LibraryActionHeader({ setSearchTerm }: Props) {return (<>- <div className="mb-[32px] hidden items-center justify-center gap-4 md:flex">+ <div className="mb-7 hidden items-center justify-center gap-4 md:flex"><LibrarySearchBar setSearchTerm={setSearchTerm} /><LibraryImportDialog /></div>diff --git a/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryAgentCard/LibraryAgentCard.tsx b/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryAgentCard/LibraryAgentCard.tsxindex 2209e82503..f8abebc3ed 100644--- a/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryAgentCard/LibraryAgentCard.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryAgentCard/LibraryAgentCard.tsx@@ -1,29 +1,40 @@"use client";import { Text } from "@/components/atoms/Text/Text";-import { CaretCircleRightIcon } from "@phosphor-icons/react";+import { EyeIcon, ChatCircleDotsIcon } from "@phosphor-icons/react";import Image from "next/image";import NextLink from "next/link";+import { useRouter } from "next/navigation";import { motion } from "framer-motion";import { LibraryAgent } from "@/app/api/__generated__/models/libraryAgent";-import Avatar, {- AvatarFallback,- AvatarImage,-} from "@/components/atoms/Avatar/Avatar";-import { Link } from "@/components/atoms/Link/Link";+import { cn } from "@/lib/utils";import { AgentCardMenu } from "./components/AgentCardMenu";import { FavoriteButton } from "./components/FavoriteButton";import { useLibraryAgentCard } from "./useLibraryAgentCard";import { useFavoriteAnimation } from "../../context/FavoriteAnimationContext";+import { StatusBadge } from "../StatusBadge/StatusBadge";+import { ContextualActionButton } from "../ContextualActionButton/ContextualActionButton";+import type { AgentStatusInfo } from "../../types";+import {+ Tooltip,+ TooltipContent,+ TooltipTrigger,+} from "@/components/ui/tooltip";interface Props {agent: LibraryAgent;+ statusInfo: AgentStatusInfo;draggable?: boolean;}-export function LibraryAgentCard({ agent, draggable = true }: Props) {- const { id, name, graph_id, can_access_graph, image_url } = agent;+export function LibraryAgentCard({+ agent,+ statusInfo,+ draggable = true,+}: Props) {+ const { id, name, image_url } = agent;+ const router = useRouter();const { triggerFavoriteAnimation } = useFavoriteAnimation();function handleDragStart(e: React.DragEvent<HTMLDivElement>) {@@ -31,18 +42,14 @@ export function LibraryAgentCard({ agent, draggable = true }: Props) {e.dataTransfer.effectAllowed = "move";}- const {- isFromMarketplace,- isFavorite,- profile,- creator_image_url,- handleToggleFavorite,- } = useLibraryAgentCard({+ const { isFavorite, handleToggleFavorite } = useLibraryAgentCard({agent,onFavoriteAdd: triggerFavoriteAnimation,});- return (+ const hasError = statusInfo.status === "error";++ const card = (<divdraggable={draggable}onDragStart={handleDragStart}@@ -52,7 +59,10 @@ export function LibraryAgentCard({ agent, draggable = true }: Props) {layoutId={`agent-card-${id}`}data-testid="library-agent-card"data-agent-id={id}- className="group relative inline-flex h-[10.625rem] w-full max-w-[25rem] flex-col items-start justify-start gap-2.5 rounded-medium border border-zinc-100 bg-white hover:shadow-md"+ className={cn(+ "group relative inline-flex h-auto min-h-[10.625rem] w-full max-w-[25rem] flex-col items-start justify-start gap-2.5 rounded-medium border bg-white hover:shadow-md",+ hasError ? "border-red-400" : "border-zinc-100",+ )}transition={{type: "spring",damping: 25,@@ -61,23 +71,10 @@ export function LibraryAgentCard({ agent, draggable = true }: Props) {style={{ willChange: "transform" }}><NextLink href={`/library/agents/${id}`} className="flex-shrink-0">- <div className="relative flex items-center gap-2 px-4 pt-3">- <Avatar className="h-4 w-4 rounded-full">- <AvatarImage- src={- isFromMarketplace- ? creator_image_url || "/avatar-placeholder.png"- : profile?.avatar_url || "/avatar-placeholder.png"- }- alt={`${name} creator avatar`}- />- <AvatarFallback size={48}>{name.charAt(0)}</AvatarFallback>- </Avatar>- <Text- variant="small-medium"- className="uppercase tracking-wide text-zinc-400"- >- {isFromMarketplace ? "FROM MARKETPLACE" : "Built by you"}+ <div className="relative flex items-center gap-3 pl-2 pr-4 pt-3">+ <StatusBadge status={statusInfo.status} />+ <Text variant="small" className="text-zinc-400">+ {statusInfo.totalRuns} tasks</Text></div></NextLink>@@ -89,7 +86,7 @@ export function LibraryAgentCard({ agent, draggable = true }: Props) {<AgentCardMenu agent={agent} /><div className="flex w-full flex-1 flex-col px-4 pb-2">- <Link+ <NextLinkhref={`/library/agents/${id}`}className="flex w-full items-start justify-between gap-2 no-underline hover:no-underline focus:ring-0">@@ -126,30 +123,52 @@ export function LibraryAgentCard({ agent, draggable = true }: Props) {className="flex-shrink-0 rounded-small object-cover"/>)}- </Link>+ </NextLink>- <div className="mt-auto flex w-full justify-start gap-6 border-t border-zinc-100 pb-1 pt-3">- <Link- href={`/library/agents/${id}`}+ <div className="mt-4 flex w-full items-center justify-end gap-1 border-t border-zinc-100 pb-0 pt-2">+ <button+ type="button"+ onClick={() => router.push(`/library/agents/${id}`)}data-testid="library-agent-card-see-runs-link"- className="flex items-center gap-1 text-[13px]"+ className="inline-flex items-center gap-1 rounded-md px-2 py-1.5 text-[13px] font-medium text-zinc-600 transition-colors hover:bg-zinc-50 hover:text-zinc-800">- See runs <CaretCircleRightIcon size={20} />- </Link>-- {can_access_graph && (- <Link- href={`/build?flowID=${graph_id}`}- data-testid="library-agent-card-open-in-builder-link"- className="flex items-center gap-1 text-[13px]"- isExternal- >- Open in builder <CaretCircleRightIcon size={20} />- </Link>- )}+ <EyeIcon size={14} className="shrink-0" />+ See tasks+ </button>+ <ContextualActionButton+ status={statusInfo.status}+ agentID={id}+ executionID={statusInfo.activeExecutionID ?? undefined}+ />+ <button+ type="button"+ onClick={() => {+ const prompt = encodeURIComponent(+ `Tell me about ${name}, its current status, recent runs and how can I get the most out of it`,+ );+ router.push(`/copilot?autosubmit=true#prompt=${prompt}`);+ }}+ className="inline-flex items-center gap-1 rounded-md px-2 py-1.5 text-[13px] font-medium text-zinc-600 transition-colors hover:bg-zinc-50 hover:text-zinc-800"+ >+ <ChatCircleDotsIcon size={14} className="shrink-0" />+ Chat+ </button></div></div></motion.div></div>);++ if (hasError && statusInfo.lastError) {+ return (+ <Tooltip>+ <TooltipTrigger asChild>{card}</TooltipTrigger>+ <TooltipContent className="max-w-xs text-red-600">+ {statusInfo.lastError}+ </TooltipContent>+ </Tooltip>+ );+ }++ return card;}diff --git a/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryAgentCard/components/AgentCardMenu.tsx b/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryAgentCard/components/AgentCardMenu.tsxindex afea4e9fe7..a473234b9a 100644--- a/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryAgentCard/components/AgentCardMenu.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryAgentCard/components/AgentCardMenu.tsx@@ -169,6 +169,7 @@ export function AgentCardMenu({ agent }: AgentCardMenuProps) {href={`/build?flowID=${agent.graph_id}&flowVersion=${agent.graph_version}`}target="_blank"className="flex items-center gap-2"+ data-testid="library-agent-card-open-in-builder-link"onClick={(e) => e.stopPropagation()}>Edit agentdiff --git a/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryAgentList/LibraryAgentList.tsx b/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryAgentList/LibraryAgentList.tsxindex d71c5805b1..a654b71547 100644--- a/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryAgentList/LibraryAgentList.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryAgentList/LibraryAgentList.tsx@@ -1,6 +1,7 @@"use client";import { LibraryAgentSort } from "@/app/api/__generated__/models/libraryAgentSort";+import type { LibraryAgent } from "@/app/api/__generated__/models/libraryAgent";import { LoadingSpinner } from "@/components/atoms/LoadingSpinner/LoadingSpinner";import { InfiniteScroll } from "@/components/contextual/InfiniteScroll/InfiniteScroll";import { LibraryAgentCard } from "../LibraryAgentCard/LibraryAgentCard";@@ -16,8 +17,11 @@ import {} from "framer-motion";import { LibraryFolderEditDialog } from "../LibraryFolderEditDialog/LibraryFolderEditDialog";import { LibraryFolderDeleteDialog } from "../LibraryFolderDeleteDialog/LibraryFolderDeleteDialog";-import { LibraryTab } from "../../types";+import type { LibraryTab, AgentStatusFilter, FleetSummary } from "../../types";import { useLibraryAgentList } from "./useLibraryAgentList";+import { AgentBriefingPanel } from "../AgentBriefingPanel/AgentBriefingPanel";+import { Flag, useGetFlag } from "@/services/feature-flags/use-get-flag";+import { useAgentStatusMap, getAgentStatus } from "../../hooks/useAgentStatus";// cancels the current spring and starts a new one from current state.const containerVariants = {@@ -70,6 +74,10 @@ interface Props {tabs: LibraryTab[];activeTab: string;onTabChange: (tabId: string) => void;+ statusFilter?: AgentStatusFilter;+ onStatusFilterChange?: (filter: AgentStatusFilter) => void;+ fleetSummary?: FleetSummary;+ briefingAgents?: LibraryAgent[];}export function LibraryAgentList({@@ -81,7 +89,12 @@ export function LibraryAgentList({tabs,activeTab,onTabChange,+ statusFilter = "all",+ onStatusFilterChange,+ fleetSummary,+ briefingAgents,}: Props) {+ const isAgentBriefingEnabled = useGetFlag(Flag.AGENT_BRIEFING);const shouldReduceMotion = useReducedMotion();const activeContainerVariants = shouldReduceMotion? reducedContainerVariants@@ -95,7 +108,7 @@ export function LibraryAgentList({const {isFavoritesTab,agentLoading,- allAgentsCount,+ displayedCount,favoritesCount,agents,hasNextPage,@@ -116,18 +129,37 @@ export function LibraryAgentList({selectedFolderId,onFolderSelect,activeTab,+ statusFilter,});+ const agentStatusMap = useAgentStatusMap(agents);+return (<>+ {isAgentBriefingEnabled &&+ !selectedFolderId &&+ fleetSummary &&+ briefingAgents &&+ briefingAgents.length > 0 && (+ <div className="mb-4">+ <AgentBriefingPanel+ summary={fleetSummary}+ agents={briefingAgents}+ />+ </div>+ )}+{!selectedFolderId && (<LibrarySubSectiontabs={tabs}activeTab={activeTab}onTabChange={onTabChange}- allCount={allAgentsCount}+ allCount={displayedCount}favoritesCount={favoritesCount}setLibrarySort={setLibrarySort}+ statusFilter={statusFilter}+ onStatusFilterChange={onStatusFilterChange}+ fleetSummary={fleetSummary}/>)}@@ -219,7 +251,13 @@ export function LibraryAgentList({0.04,}}>- <LibraryAgentCard agent={agent} />+ <LibraryAgentCard+ agent={agent}+ statusInfo={getAgentStatus(+ agentStatusMap,+ agent.graph_id,+ )}+ /></motion.div>))}</motion.div>diff --git a/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryAgentList/useLibraryAgentList.ts b/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryAgentList/useLibraryAgentList.tsindex 86c749b39b..d4c79158a7 100644--- a/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryAgentList/useLibraryAgentList.ts+++ b/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryAgentList/useLibraryAgentList.ts@@ -21,7 +21,12 @@ import { useToast } from "@/components/molecules/Toast/use-toast";import { useFavoriteAgents } from "../../hooks/useFavoriteAgents";import { getQueryClient } from "@/lib/react-query/queryClient";import { useQueryClient } from "@tanstack/react-query";-import { useEffect, useRef, useState } from "react";+import { useEffect, useMemo, useRef, useState } from "react";+import type { AgentStatusFilter } from "../../types";+import { useGetV1ListAllExecutions } from "@/app/api/__generated__/endpoints/graphs/graphs";+import { AgentExecutionStatus } from "@/app/api/__generated__/models/agentExecutionStatus";++const FILTER_EXHAUST_THRESHOLD = 3;interface Props {searchTerm: string;@@ -29,6 +34,7 @@ interface Props {selectedFolderId: string | null;onFolderSelect: (folderId: string | null) => void;activeTab: string;+ statusFilter?: AgentStatusFilter;}export function useLibraryAgentList({@@ -37,12 +43,16 @@ export function useLibraryAgentList({selectedFolderId,onFolderSelect,activeTab,+ statusFilter = "all",}: Props) {const isFavoritesTab = activeTab === "favorites";const { toast } = useToast();const stableQueryClient = getQueryClient();const queryClient = useQueryClient();const prevSortRef = useRef<LibraryAgentSort | null>(null);+ const [consecutiveEmptyPages, setConsecutiveEmptyPages] = useState(0);+ const prevFilteredLengthRef = useRef(0);+ const prevAgentsLengthRef = useRef(0);const [editingFolder, setEditingFolder] = useState<LibraryFolder | null>(null,@@ -199,6 +209,90 @@ export function useLibraryAgentList({const showFolders = !isFavoritesTab;+ const { data: executions } = useGetV1ListAllExecutions({+ query: { select: okData },+ });++ const { activeGraphIds, errorGraphIds, completedGraphIds } = useMemo(() => {+ const active = new Set<string>();+ const errors = new Set<string>();+ const completed = new Set<string>();+ const cutoff = Date.now() - 72 * 60 * 60 * 1000;+ for (const exec of executions ?? []) {+ if (+ exec.status === AgentExecutionStatus.RUNNING ||+ exec.status === AgentExecutionStatus.QUEUED ||+ exec.status === AgentExecutionStatus.REVIEW+ ) {+ active.add(exec.graph_id);+ }+ const endedTs = exec.ended_at+ ? exec.ended_at instanceof Date+ ? exec.ended_at.getTime()+ : new Date(String(exec.ended_at)).getTime()+ : 0;+ if (+ (exec.status === AgentExecutionStatus.FAILED ||+ exec.status === AgentExecutionStatus.TERMINATED) &&+ endedTs > cutoff+ ) {+ errors.add(exec.graph_id);+ }+ if (exec.status === AgentExecutionStatus.COMPLETED && endedTs > cutoff) {+ completed.add(exec.graph_id);+ }+ }+ return {+ activeGraphIds: active,+ errorGraphIds: errors,+ completedGraphIds: completed,+ };+ }, [executions]);++ const filteredAgents = filterAgentsByStatus(+ agents,+ statusFilter,+ activeGraphIds,+ errorGraphIds,+ completedGraphIds,+ );++ useEffect(() => {+ if (statusFilter === "all") {+ setConsecutiveEmptyPages(0);+ prevFilteredLengthRef.current = filteredAgents.length;+ prevAgentsLengthRef.current = agents.length;+ return;+ }++ if (agents.length > prevAgentsLengthRef.current) {+ const newFilteredCount = filteredAgents.length;+ const previousCount = prevFilteredLengthRef.current;++ if (newFilteredCount > previousCount) {+ setConsecutiveEmptyPages(0);+ } else {+ setConsecutiveEmptyPages((prev) => prev + 1);+ }+ }++ prevAgentsLengthRef.current = agents.length;+ prevFilteredLengthRef.current = filteredAgents.length;+ }, [agents.length, filteredAgents.length, statusFilter]);++ useEffect(() => {+ setConsecutiveEmptyPages(0);+ prevFilteredLengthRef.current = 0;+ prevAgentsLengthRef.current = 0;+ }, [statusFilter]);++ const filteredExhausted =+ statusFilter !== "all" && consecutiveEmptyPages >= FILTER_EXHAUST_THRESHOLD;++ // When a filter is active, show the filtered count instead of the API total.+ const displayedCount =+ statusFilter === "all" ? allAgentsCount : filteredAgents.length;+function handleFolderDeleted() {if (selectedFolderId === deletingFolder?.id) {onFolderSelect(null);@@ -210,9 +304,10 @@ export function useLibraryAgentList({agentLoading,agentCount,allAgentsCount,+ displayedCount,favoritesCount: favoriteAgentsData.agentCount,- agents,- hasNextPage: agentsHasNextPage,+ agents: filteredAgents,+ hasNextPage: agentsHasNextPage && !filteredExhausted,isFetchingNextPage: agentsIsFetchingNextPage,fetchNextPage: agentsFetchNextPage,foldersData,@@ -226,3 +321,46 @@ export function useLibraryAgentList({handleFolderDeleted,};}++function filterAgentsByStatus<+ T extends {+ graph_id: string;+ has_external_trigger: boolean;+ recommended_schedule_cron?: string | null;+ },+>(+ agents: T[],+ statusFilter: AgentStatusFilter,+ activeGraphIds: Set<string>,+ errorGraphIds: Set<string>,+ completedGraphIds: Set<string>,+): T[] {+ if (statusFilter === "all") return agents;+ return agents.filter((agent) => {+ const isRunning = activeGraphIds.has(agent.graph_id);+ const hasError = errorGraphIds.has(agent.graph_id);++ if (statusFilter === "running") return isRunning;+ if (statusFilter === "attention") return hasError && !isRunning;+ if (statusFilter === "completed")+ return completedGraphIds.has(agent.graph_id);+ if (statusFilter === "listening")+ return !isRunning && !hasError && agent.has_external_trigger;+ if (statusFilter === "scheduled")+ return (+ !isRunning &&+ !hasError &&+ !agent.has_external_trigger &&+ !!agent.recommended_schedule_cron+ );+ if (statusFilter === "idle")+ return (+ !isRunning &&+ !hasError &&+ !agent.has_external_trigger &&+ !agent.recommended_schedule_cron+ );+ if (statusFilter === "healthy") return !hasError;+ return true;+ });+}diff --git a/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryFolder/LibraryFolder.tsx b/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryFolder/LibraryFolder.tsxindex 58e2392adb..5c93ebc878 100644--- a/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryFolder/LibraryFolder.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryFolder/LibraryFolder.tsx@@ -2,14 +2,11 @@import { Text } from "@/components/atoms/Text/Text";import { Button } from "@/components/atoms/Button/Button";-import {- FolderIcon,- FolderColor,- folderCardStyles,- resolveColor,-} from "./FolderIcon";+import { FolderIcon, FolderColor } from "./FolderIcon";import { useState } from "react";import { PencilSimpleIcon, TrashIcon } from "@phosphor-icons/react";+import type { AgentStatus } from "../../types";+import { StatusBadge } from "../StatusBadge/StatusBadge";interface Props {id: string;@@ -21,6 +18,8 @@ interface Props {onDelete?: () => void;onAgentDrop?: (agentId: string, folderId: string) => void;onClick?: () => void;+ /** Worst status among child agents (optional, for status aggregation). */+ worstStatus?: AgentStatus;}export function LibraryFolder({@@ -33,11 +32,10 @@ export function LibraryFolder({onDelete,onAgentDrop,onClick,+ worstStatus,}: Props) {const [isHovered, setIsHovered] = useState(false);const [isDragOver, setIsDragOver] = useState(false);- const resolvedColor = resolveColor(color);- const cardStyle = folderCardStyles[resolvedColor];function handleDragOver(e: React.DragEvent<HTMLDivElement>) {if (e.dataTransfer.types.includes("application/agent-id")) {@@ -64,10 +62,10 @@ export function LibraryFolder({<divdata-testid="library-folder"data-folder-id={id}- className={`group relative inline-flex h-[10.625rem] w-full max-w-[25rem] cursor-pointer flex-col items-start justify-between gap-2.5 rounded-medium border p-4 transition-all duration-200 hover:shadow-md ${+ className={`group relative inline-flex h-[10.625rem] w-full max-w-[25rem] cursor-pointer flex-col items-start justify-between gap-2.5 rounded-medium border p-4 shadow-sm backdrop-blur-md transition-all duration-200 hover:shadow-md ${isDragOver? "border-blue-400 bg-blue-50 ring-2 ring-blue-200"- : `${cardStyle.border} ${cardStyle.bg}`+ : "border-indigo-200/40 bg-gradient-to-br from-indigo-50/40 via-white/70 to-purple-50/30"}`}onMouseEnter={() => setIsHovered(true)}onMouseLeave={() => setIsHovered(false)}@@ -76,7 +74,7 @@ export function LibraryFolder({onDrop={handleDrop}onClick={onClick}>- <div className="flex w-full items-start justify-between gap-4">+ <div className="flex w-full items-center justify-between gap-4">{/* Left side - Folder name and agent count */}<div className="flex flex-1 flex-col gap-2"><Text@@ -86,17 +84,22 @@ export function LibraryFolder({>{name}</Text>- <Text- variant="small"- className="text-zinc-500"- data-testid="library-folder-agent-count"- >- {agentCount} {agentCount === 1 ? "agent" : "agents"}- </Text>+ <div className="flex items-center gap-2">+ <Text+ variant="small"+ className="text-zinc-500"+ data-testid="library-folder-agent-count"+ >+ {agentCount} {agentCount === 1 ? "agent" : "agents"}+ </Text>+ {worstStatus && worstStatus !== "idle" && (+ <StatusBadge status={worstStatus} />+ )}+ </div></div>{/* Right side - Custom folder icon */}- <div className="flex-shrink-0">+ <div className="relative top-5 flex flex-shrink-0 items-center"><FolderIcon isOpen={isHovered} color={color} icon={icon} /></div></div>@@ -114,7 +117,7 @@ export function LibraryFolder({e.stopPropagation();onEdit?.();}}- className={`h-8 w-8 border p-2 ${cardStyle.buttonBase} ${cardStyle.buttonHover}`}+ className="h-8 w-8 border border-neutral-200 bg-white/80 p-2 text-neutral-500 hover:bg-white hover:text-neutral-700"><PencilSimpleIcon className="h-4 w-4" /></Button>@@ -126,7 +129,7 @@ export function LibraryFolder({e.stopPropagation();onDelete?.();}}- className={`h-8 w-8 border p-2 ${cardStyle.buttonBase} ${cardStyle.buttonHover}`}+ className="h-8 w-8 border border-neutral-200 bg-white/80 p-2 text-neutral-500 hover:bg-white hover:text-neutral-700"><TrashIcon className="h-4 w-4" /></Button>diff --git a/autogpt_platform/frontend/src/app/(platform)/library/components/LibrarySubSection/LibrarySubSection.tsx b/autogpt_platform/frontend/src/app/(platform)/library/components/LibrarySubSection/LibrarySubSection.tsxindex 32169cf441..3a4475d55d 100644--- a/autogpt_platform/frontend/src/app/(platform)/library/components/LibrarySubSection/LibrarySubSection.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/library/components/LibrarySubSection/LibrarySubSection.tsx@@ -6,9 +6,10 @@ import {} from "@/components/molecules/TabsLine/TabsLine";import { LibraryAgentSort } from "@/app/api/__generated__/models/libraryAgentSort";import { useFavoriteAnimation } from "../../context/FavoriteAnimationContext";-import { LibraryTab } from "../../types";+import type { LibraryTab, AgentStatusFilter, FleetSummary } from "../../types";import LibraryFolderCreationDialog from "../LibraryFolderCreationDialog/LibraryFolderCreationDialog";import { LibrarySortMenu } from "../LibrarySortMenu/LibrarySortMenu";+import { AgentFilterMenu } from "../AgentFilterMenu/AgentFilterMenu";interface Props {tabs: LibraryTab[];@@ -17,6 +18,9 @@ interface Props {allCount: number;favoritesCount: number;setLibrarySort: (value: LibraryAgentSort) => void;+ statusFilter?: AgentStatusFilter;+ onStatusFilterChange?: (filter: AgentStatusFilter) => void;+ fleetSummary?: FleetSummary;}export function LibrarySubSection({@@ -26,6 +30,9 @@ export function LibrarySubSection({allCount,favoritesCount,setLibrarySort,+ statusFilter = "all",+ onStatusFilterChange,+ fleetSummary,}: Props) {const { registerFavoritesTabRef } = useFavoriteAnimation();const favoritesRef = useRef<HTMLButtonElement>(null);@@ -68,8 +75,15 @@ export function LibrarySubSection({))}</TabsLineList></TabsLine>- <div className="hidden items-center gap-6 md:flex">+ <div className="relative top-1.5 hidden items-center gap-6 md:flex"><LibraryFolderCreationDialog />+ {fleetSummary && onStatusFilterChange && (+ <AgentFilterMenu+ value={statusFilter}+ onChange={onStatusFilterChange}+ summary={fleetSummary}+ />+ )}<LibrarySortMenu setLibrarySort={setLibrarySort} /></div></div>diff --git a/autogpt_platform/frontend/src/app/(platform)/library/components/SitrepItem/SitrepItem.module.css b/autogpt_platform/frontend/src/app/(platform)/library/components/SitrepItem/SitrepItem.module.cssnew file mode 100644index 0000000000..56d9944327--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/library/components/SitrepItem/SitrepItem.module.css@@ -0,0 +1,17 @@+.spinner {+ aspect-ratio: 1;+ border-radius: 50%;+ background:+ radial-gradient(farthest-side, currentColor 94%, #0000) top/3px 3px+ no-repeat,+ conic-gradient(#0000 30%, currentColor);+ -webkit-mask: radial-gradient(farthest-side, #0000 calc(100% - 3px), #000 0);+ mask: radial-gradient(farthest-side, #0000 calc(100% - 3px), #000 0);+ animation: spin 1s infinite linear;+}++@keyframes spin {+ 100% {+ transform: rotate(1turn);+ }+}diff --git a/autogpt_platform/frontend/src/app/(platform)/library/components/SitrepItem/SitrepItem.tsx b/autogpt_platform/frontend/src/app/(platform)/library/components/SitrepItem/SitrepItem.tsxnew file mode 100644index 0000000000..3277b06716--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/library/components/SitrepItem/SitrepItem.tsx@@ -0,0 +1,172 @@+"use client";++import { Text } from "@/components/atoms/Text/Text";+import {+ WarningCircleIcon,+ ClockCountdownIcon,+ CheckCircleIcon,+ ChatCircleDotsIcon,+ EarIcon,+ CalendarDotsIcon,+ MoonIcon,+ EyeIcon,+} from "@phosphor-icons/react";+import NextLink from "next/link";+import { cn } from "@/lib/utils";+import { useRouter } from "next/navigation";+import type { SitrepItemData, SitrepPriority } from "../../types";+import { ContextualActionButton } from "../ContextualActionButton/ContextualActionButton";+import styles from "./SitrepItem.module.css";++interface Props {+ item: SitrepItemData;+}++const PRIORITY_CONFIG: Record<+ SitrepPriority,+ {+ icon?: typeof WarningCircleIcon;+ color: string;+ bg: string;+ cssSpinner?: boolean;+ }+> = {+ error: {+ icon: WarningCircleIcon,+ color: "text-red-500",+ bg: "bg-red-50",+ },+ running: {+ color: "text-zinc-800",+ bg: "",+ cssSpinner: true,+ },+ stale: {+ icon: ClockCountdownIcon,+ color: "text-yellow-600",+ bg: "bg-yellow-50",+ },+ success: {+ icon: CheckCircleIcon,+ color: "text-green-600",+ bg: "bg-green-50",+ },+ listening: {+ icon: EarIcon,+ color: "text-purple-500",+ bg: "bg-purple-50",+ },+ scheduled: {+ icon: CalendarDotsIcon,+ color: "text-yellow-600",+ bg: "bg-yellow-50",+ },+ idle: {+ icon: MoonIcon,+ color: "text-zinc-400",+ bg: "bg-zinc-100",+ },+};++export function SitrepItem({ item }: Props) {+ const config = PRIORITY_CONFIG[item.priority];+ const router = useRouter();++ function handleAskAutoPilot() {+ const prompt = buildAutoPilotPrompt(item);+ const encoded = encodeURIComponent(prompt);+ router.push(`/copilot?autosubmit=true#prompt=${encoded}`);+ }++ return (+ <div+ className={cn(+ "flex flex-col gap-2 rounded-medium border border-zinc-200/50 bg-transparent p-2 sm:flex-row sm:items-center sm:gap-3",+ )}+ >+ <div className="flex min-w-0 flex-1 items-center gap-3">+ {item.agentImageUrl ? (+ <img+ src={item.agentImageUrl}+ alt={item.agentName}+ className="h-6 w-6 flex-shrink-0 rounded-full object-cover"+ />+ ) : (+ <div+ className={cn(+ "flex h-6 w-6 flex-shrink-0 items-center justify-center rounded-full",+ config.bg,+ )}+ >+ {config.cssSpinner ? (+ <div+ className={cn(+ styles.spinner,+ "h-[21px] w-[21px] text-zinc-800",+ )}+ />+ ) : (+ config.icon && (+ <config.icon size={14} className={config.color} weight="fill" />+ )+ )}+ </div>+ )}++ <div className="min-w-0 flex-1">+ <Text variant="body-medium" className="leading-tight text-zinc-900">+ {item.agentName}+ </Text>+ <Text variant="small" className="leading-tight text-zinc-500">+ {item.message}+ </Text>+ </div>+ </div>++ <div className="flex flex-shrink-0 flex-wrap items-center justify-center gap-1.5 sm:flex-nowrap sm:justify-end">+ {item.priority === "success" ? (+ <NextLink+ href={`/library/agents/${item.agentID}${item.executionID ? `?activeItem=${item.executionID}` : ""}`}+ className="inline-flex items-center gap-1 rounded-md px-2 py-1.5 text-[13px] font-medium text-zinc-600 transition-colors hover:bg-zinc-50 hover:text-zinc-800"+ >+ <EyeIcon size={14} className="shrink-0" />+ See task+ </NextLink>+ ) : (+ <ContextualActionButton+ status={item.status}+ agentID={item.agentID}+ executionID={item.executionID}+ />+ )}+ <button+ type="button"+ onClick={handleAskAutoPilot}+ className="inline-flex items-center gap-1 rounded-md px-2 py-1.5 text-[13px] font-medium text-zinc-600 transition-colors hover:bg-zinc-50 hover:text-zinc-800"+ >+ <ChatCircleDotsIcon size={14} className="shrink-0" />+ Ask AutoPilot+ </button>+ </div>+ </div>+ );+}++function buildAutoPilotPrompt(item: SitrepItemData): string {+ switch (item.priority) {+ case "error":+ return `What happened with ${item.agentName}? It says "${item.message}" — can you check the logs and tell me what to fix?`;+ case "running":+ return `Give me a status update on the ${item.agentName} run — what has it found so far?`;+ case "stale":+ return `${item.agentName} hasn't run recently. Should I keep it or update and re-run it?`;+ case "success":+ return `Show me what ${item.agentName} found in its last run — summarize the results and any key takeaways.`;+ case "listening":+ return `What is ${item.agentName} listening for? Give me a summary of its trigger configuration.`;+ case "scheduled":+ return `When is ${item.agentName} scheduled to run next?`;+ case "idle":+ return `${item.agentName} has been idle. Should I keep it or update and re-run it?`;+ }+}diff --git a/autogpt_platform/frontend/src/app/(platform)/library/components/SitrepItem/SitrepList.tsx b/autogpt_platform/frontend/src/app/(platform)/library/components/SitrepItem/SitrepList.tsxnew file mode 100644index 0000000000..5ebf5bfd94--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/library/components/SitrepItem/SitrepList.tsx@@ -0,0 +1,34 @@+"use client";++import { Text } from "@/components/atoms/Text/Text";+import { ClockCounterClockwise } from "@phosphor-icons/react";+import type { LibraryAgent } from "@/app/api/__generated__/models/libraryAgent";+import { useSitrepItems } from "./useSitrepItems";+import { SitrepItem } from "./SitrepItem";++interface Props {+ agents: LibraryAgent[];+ maxItems?: number;+}++export function SitrepList({ agents, maxItems = 10 }: Props) {+ const items = useSitrepItems(agents, maxItems);++ if (items.length === 0) return null;++ return (+ <div>+ <div className="mb-2 flex items-center gap-1.5">+ <ClockCounterClockwise size={16} className="text-zinc-700" />+ <Text variant="body-medium" className="text-zinc-700">+ Recent tasks+ </Text>+ </div>+ <div className="grid grid-cols-1 gap-1 lg:grid-cols-2">+ {items.map((item) => (+ <SitrepItem key={item.id} item={item} />+ ))}+ </div>+ </div>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/library/components/SitrepItem/useSitrepItems.ts b/autogpt_platform/frontend/src/app/(platform)/library/components/SitrepItem/useSitrepItems.tsnew file mode 100644index 0000000000..2b4a1deb8b--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/library/components/SitrepItem/useSitrepItems.ts@@ -0,0 +1,133 @@+"use client";++import { useGetV1ListAllExecutions } from "@/app/api/__generated__/endpoints/graphs/graphs";+import { AgentExecutionStatus } from "@/app/api/__generated__/models/agentExecutionStatus";+import type { GraphExecutionMeta } from "@/app/api/__generated__/models/graphExecutionMeta";+import type { LibraryAgent } from "@/app/api/__generated__/models/libraryAgent";+import { okData } from "@/app/api/helpers";+import { useMemo } from "react";+import type { SitrepItemData, SitrepPriority } from "../../types";+import {+ isActive,+ isFailed,+ toEndTime,+ endedAfter,+ runningMessage,+ SEVENTY_TWO_HOURS_MS,+} from "../../hooks/executionHelpers";++export function useSitrepItems(+ agents: LibraryAgent[],+ maxItems: number,+): SitrepItemData[] {+ const { data: executions } = useGetV1ListAllExecutions({+ query: { select: okData },+ });++ return useMemo(() => {+ if (!executions || agents.length === 0) return [];++ const graphIdToAgent = new Map(agents.map((a) => [a.graph_id, a]));+ const agentExecutions = groupByAgent(executions, graphIdToAgent);+ const items: SitrepItemData[] = [];++ for (const [agent, execs] of agentExecutions) {+ const item = buildSitrepFromExecutions(agent, execs);+ if (item) items.push(item);+ }++ const order: Record<SitrepPriority, number> = {+ error: 0,+ running: 1,+ stale: 2,+ success: 3,+ listening: 4,+ scheduled: 5,+ idle: 6,+ };+ items.sort((a, b) => order[a.priority] - order[b.priority]);++ return items.slice(0, maxItems);+ }, [agents, executions, maxItems]);+}++function groupByAgent(+ executions: GraphExecutionMeta[],+ graphIdToAgent: Map<string, LibraryAgent>,+): Map<LibraryAgent, GraphExecutionMeta[]> {+ const map = new Map<LibraryAgent, GraphExecutionMeta[]>();++ for (const exec of executions) {+ const agent = graphIdToAgent.get(exec.graph_id);+ if (!agent) continue;+ const list = map.get(agent);+ if (list) {+ list.push(exec);+ } else {+ map.set(agent, [exec]);+ }+ }++ return map;+}++function buildSitrepFromExecutions(+ agent: LibraryAgent,+ executions: GraphExecutionMeta[],+): SitrepItemData | null {+ const active = executions.find((e) => isActive(e.status));+ if (active) {+ return {+ id: `${agent.id}-${active.id}`,+ agentID: agent.id,+ agentName: agent.name,+ executionID: active.id,+ priority: "running",+ message:+ active.stats?.activity_status ??+ runningMessage(active.status, active.started_at),+ status: "running",+ };+ }++ const cutoff = Date.now() - SEVENTY_TWO_HOURS_MS;+ const recent = executions+ .filter((e) => endedAfter(e, cutoff))+ .sort((a, b) => toEndTime(b) - toEndTime(a));++ const lastFailed = recent.find((e) => isFailed(e.status));+ if (lastFailed) {+ const errorMsg =+ lastFailed.stats?.error ??+ lastFailed.stats?.activity_status ??+ "Execution failed";+ return {+ id: `${agent.id}-${lastFailed.id}`,+ agentID: agent.id,+ agentName: agent.name,+ executionID: lastFailed.id,+ priority: "error",+ message: typeof errorMsg === "string" ? errorMsg : "Execution failed",+ status: "error",+ };+ }++ const lastCompleted = recent.find(+ (e) => e.status === AgentExecutionStatus.COMPLETED,+ );+ if (lastCompleted) {+ const summary =+ lastCompleted.stats?.activity_status ?? "Completed successfully";+ return {+ id: `${agent.id}-${lastCompleted.id}`,+ agentID: agent.id,+ agentName: agent.name,+ executionID: lastCompleted.id,+ priority: "success",+ message: typeof summary === "string" ? summary : "Completed successfully",+ status: "idle",+ };+ }++ return null;+}diff --git a/autogpt_platform/frontend/src/app/(platform)/library/components/StatusBadge/StatusBadge.tsx b/autogpt_platform/frontend/src/app/(platform)/library/components/StatusBadge/StatusBadge.tsxnew file mode 100644index 0000000000..afcee51380--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/library/components/StatusBadge/StatusBadge.tsx@@ -0,0 +1,84 @@+"use client";++import { cn } from "@/lib/utils";+import type { AgentStatus } from "../../types";++const STATUS_CONFIG: Record<+ AgentStatus,+ { label: string; bg: string; text: string; pulse: boolean }+> = {+ running: {+ label: "Running",+ bg: "",+ text: "text-blue-600",+ pulse: true,+ },+ error: {+ label: "Error",+ bg: "",+ text: "text-red-500",+ pulse: false,+ },+ listening: {+ label: "Listening",+ bg: "",+ text: "text-purple-500",+ pulse: true,+ },+ scheduled: {+ label: "Scheduled",+ bg: "",+ text: "text-yellow-600",+ pulse: false,+ },+ idle: {+ label: "Idle",+ bg: "",+ text: "text-zinc-500",+ pulse: false,+ },+};++interface Props {+ status: AgentStatus;+ className?: string;+}++export function StatusBadge({ status, className }: Props) {+ const config = STATUS_CONFIG[status];++ return (+ <span+ className={cn(+ "inline-flex items-center gap-1.5 rounded-full px-2 py-0.5 text-xs font-medium",+ config.bg,+ config.text,+ className,+ )}+ >+ <span+ className={cn(+ "inline-block h-1.5 w-1.5 rounded-full",+ config.pulse && "animate-pulse",+ statusDotColor(status),+ )}+ />+ {config.label}+ </span>+ );+}++function statusDotColor(status: AgentStatus): string {+ switch (status) {+ case "running":+ return "bg-blue-500";+ case "error":+ return "bg-red-500";+ case "listening":+ return "bg-purple-500";+ case "scheduled":+ return "bg-yellow-500";+ case "idle":+ return "bg-zinc-400";+ }+}diff --git a/autogpt_platform/frontend/src/app/(platform)/library/hooks/executionHelpers.ts b/autogpt_platform/frontend/src/app/(platform)/library/hooks/executionHelpers.tsnew file mode 100644index 0000000000..cd2505c7ce--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/library/hooks/executionHelpers.ts@@ -0,0 +1,59 @@+import { AgentExecutionStatus } from "@/app/api/__generated__/models/agentExecutionStatus";+import type { GraphExecutionMeta } from "@/app/api/__generated__/models/graphExecutionMeta";++export const SEVENTY_TWO_HOURS_MS = 72 * 60 * 60 * 1000;++export function isActive(status: string): boolean {+ return (+ status === AgentExecutionStatus.RUNNING ||+ status === AgentExecutionStatus.QUEUED ||+ status === AgentExecutionStatus.REVIEW+ );+}++export function isFailed(status: string): boolean {+ return (+ status === AgentExecutionStatus.FAILED ||+ status === AgentExecutionStatus.TERMINATED+ );+}++export function toEndTime(exec: GraphExecutionMeta): number {+ if (!exec.ended_at) return 0;+ return exec.ended_at instanceof Date+ ? exec.ended_at.getTime()+ : new Date(exec.ended_at).getTime();+}++export function endedAfter(exec: GraphExecutionMeta, cutoff: number): boolean {+ if (!exec.ended_at) return false;+ return toEndTime(exec) > cutoff;+}++export function runningMessage(+ status: string,+ startedAt?: string | Date | null,+): string {+ if (status === AgentExecutionStatus.QUEUED) return "Queued for execution";+ if (status === AgentExecutionStatus.REVIEW) return "Awaiting review";+ if (!startedAt) return "Currently executing";+ const ms =+ Date.now() -+ (startedAt instanceof Date+ ? startedAt.getTime()+ : new Date(startedAt).getTime());+ return `Running for ${formatRelativeDuration(ms)}`;+}++export function formatRelativeDuration(ms: number): string {+ const seconds = Math.floor(ms / 1000);+ if (seconds < 60) return "a few seconds";+ const minutes = Math.floor(seconds / 60);+ if (minutes < 60) return `${minutes}m`;+ const hours = Math.floor(minutes / 60);+ const remainingMin = minutes % 60;+ if (hours < 24)+ return remainingMin > 0 ? `${hours}h ${remainingMin}m` : `${hours}h`;+ const days = Math.floor(hours / 24);+ return `${days}d ${hours % 24}h`;+}diff --git a/autogpt_platform/frontend/src/app/(platform)/library/hooks/useAgentStatus.ts b/autogpt_platform/frontend/src/app/(platform)/library/hooks/useAgentStatus.tsnew file mode 100644index 0000000000..ada5560040--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/library/hooks/useAgentStatus.ts@@ -0,0 +1,213 @@+"use client";++import { useMemo } from "react";+import { useGetV1ListAllExecutions } from "@/app/api/__generated__/endpoints/graphs/graphs";+import { AgentExecutionStatus } from "@/app/api/__generated__/models/agentExecutionStatus";+import type { GraphExecutionMeta } from "@/app/api/__generated__/models/graphExecutionMeta";+import type { LibraryAgent } from "@/app/api/__generated__/models/libraryAgent";+import { okData } from "@/app/api/helpers";+import type {+ AgentStatus,+ AgentHealth,+ AgentStatusInfo,+ FleetSummary,+} from "../types";+import {+ isActive,+ isFailed,+ toEndTime,+ SEVENTY_TWO_HOURS_MS,+} from "./executionHelpers";++function deriveHealth(+ status: AgentStatus,+ lastRunAt: string | null,+): AgentHealth {+ if (status === "error") return "attention";+ if (status === "idle" && lastRunAt) {+ const daysSince =+ (Date.now() - new Date(lastRunAt).getTime()) / (1000 * 60 * 60 * 24);+ if (daysSince > 14) return "stale";+ }+ return "good";+}++function computeAgentStatus(+ agent: LibraryAgent,+ agentExecutions: GraphExecutionMeta[],+): AgentStatusInfo {+ const activeExec = agentExecutions.find((e) => isActive(e.status));++ let status: AgentStatus;+ let lastError: string | null = null;+ let lastRunAt: string | null = null;+ const activeExecutionID = activeExec?.id ?? null;++ if (activeExec) {+ status = "running";+ } else {+ const cutoff = Date.now() - SEVENTY_TWO_HOURS_MS;+ const recentFailed = agentExecutions.find(+ (e) =>+ isFailed(e.status) &&+ e.ended_at &&+ new Date(+ e.ended_at instanceof Date ? e.ended_at.getTime() : e.ended_at,+ ).getTime() > cutoff,+ );++ if (recentFailed) {+ status = "error";+ lastError =+ (recentFailed.stats?.error as string) ??+ (recentFailed.stats?.activity_status as string) ??+ "Execution failed";+ } else if (agent.has_external_trigger) {+ status = "listening";+ } else if (agent.recommended_schedule_cron) {+ status = "scheduled";+ } else {+ status = "idle";+ }+ }++ const completedExecs = agentExecutions.filter((e) => e.ended_at);+ if (completedExecs.length > 0) {+ const sorted = completedExecs.sort((a, b) => toEndTime(b) - toEndTime(a));+ const endedAt = sorted[0].ended_at;+ lastRunAt =+ endedAt instanceof Date ? endedAt.toISOString() : String(endedAt);+ }++ const totalRuns = agent.execution_count ?? agentExecutions.length;++ return {+ status,+ health: deriveHealth(status, lastRunAt),+ progress: null,+ totalRuns,+ lastRunAt,+ lastError,+ activeExecutionID,+ monthlySpend: 0,+ nextScheduledRun: null,+ triggerType: agent.has_external_trigger ? "webhook" : null,+ };+}++export function useAgentStatusMap(+ agents: LibraryAgent[],+): Map<string, AgentStatusInfo> {+ const { data: executions } = useGetV1ListAllExecutions({+ query: { select: okData },+ });++ return useMemo(() => {+ const map = new Map<string, AgentStatusInfo>();+ const execsByGraph = new Map<string, GraphExecutionMeta[]>();++ for (const exec of executions ?? []) {+ const list = execsByGraph.get(exec.graph_id);+ if (list) {+ list.push(exec);+ } else {+ execsByGraph.set(exec.graph_id, [exec]);+ }+ }++ for (const agent of agents) {+ const agentExecs = execsByGraph.get(agent.graph_id) ?? [];+ map.set(agent.graph_id, computeAgentStatus(agent, agentExecs));+ }++ return map;+ }, [agents, executions]);+}++const DEFAULT_STATUS: AgentStatusInfo = {+ status: "idle",+ health: "good",+ progress: null,+ totalRuns: 0,+ lastRunAt: null,+ lastError: null,+ activeExecutionID: null,+ monthlySpend: 0,+ nextScheduledRun: null,+ triggerType: null,+};++export function getAgentStatus(+ statusMap: Map<string, AgentStatusInfo>,+ graphID: string,+): AgentStatusInfo {+ return statusMap.get(graphID) ?? DEFAULT_STATUS;+}++export function useFleetSummary(agents: LibraryAgent[]): FleetSummary {+ const { data: executions } = useGetV1ListAllExecutions({+ query: { select: okData },+ });++ return useMemo(() => {+ const counts: FleetSummary = {+ running: 0,+ error: 0,+ completed: 0,+ listening: 0,+ scheduled: 0,+ idle: 0,+ monthlySpend: 0,+ };++ const activeGraphIds = new Set<string>();+ const errorGraphIds = new Set<string>();+ const completedGraphIds = new Set<string>();++ if (executions) {+ const cutoff = Date.now() - SEVENTY_TWO_HOURS_MS;+ for (const exec of executions) {+ if (isActive(exec.status)) {+ activeGraphIds.add(exec.graph_id);+ }+ const endedTs = exec.ended_at+ ? new Date(+ exec.ended_at instanceof Date+ ? exec.ended_at.getTime()+ : exec.ended_at,+ ).getTime()+ : 0;+ if (isFailed(exec.status) && endedTs > cutoff) {+ errorGraphIds.add(exec.graph_id);+ }+ if (+ exec.status === AgentExecutionStatus.COMPLETED &&+ endedTs > cutoff+ ) {+ completedGraphIds.add(exec.graph_id);+ }+ }+ }++ for (const agent of agents) {+ if (activeGraphIds.has(agent.graph_id)) {+ counts.running += 1;+ } else if (errorGraphIds.has(agent.graph_id)) {+ counts.error += 1;+ } else if (agent.has_external_trigger) {+ counts.listening += 1;+ } else if (agent.recommended_schedule_cron) {+ counts.scheduled += 1;+ } else {+ counts.idle += 1;+ }+ if (completedGraphIds.has(agent.graph_id)) {+ counts.completed += 1;+ }+ }++ return counts;+ }, [agents, executions]);+}++export { deriveHealth };diff --git a/autogpt_platform/frontend/src/app/(platform)/library/hooks/useLibraryFleetSummary.ts b/autogpt_platform/frontend/src/app/(platform)/library/hooks/useLibraryFleetSummary.tsnew file mode 100644index 0000000000..8aa7a92812--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/library/hooks/useLibraryFleetSummary.ts@@ -0,0 +1,116 @@+"use client";++import {+ getGetV1ListAllExecutionsQueryKey,+ useGetV1ListAllExecutions,+} from "@/app/api/__generated__/endpoints/graphs/graphs";+import { AgentExecutionStatus } from "@/app/api/__generated__/models/agentExecutionStatus";+import type { LibraryAgent } from "@/app/api/__generated__/models/libraryAgent";+import { okData } from "@/app/api/helpers";+import { useExecutionEvents } from "@/hooks/useExecutionEvents";+import { useQueryClient } from "@tanstack/react-query";+import { useCallback, useMemo } from "react";+import type { FleetSummary } from "../types";+import { isActive, isFailed, SEVENTY_TWO_HOURS_MS } from "./executionHelpers";++function isRecentFailure(+ status: string,+ endedAt?: string | Date | null,+): boolean {+ if (!isFailed(status)) return false;+ if (!endedAt) return false;+ const ts =+ endedAt instanceof Date ? endedAt.getTime() : new Date(endedAt).getTime();+ return Date.now() - ts < SEVENTY_TWO_HOURS_MS;+}++function isRecentCompletion(+ status: string,+ endedAt?: string | Date | null,+): boolean {+ if (status !== AgentExecutionStatus.COMPLETED) return false;+ if (!endedAt) return false;+ const ts =+ endedAt instanceof Date ? endedAt.getTime() : new Date(endedAt).getTime();+ return Date.now() - ts < SEVENTY_TWO_HOURS_MS;+}++export function useLibraryFleetSummary(+ agents: LibraryAgent[],+): FleetSummary | undefined {+ const queryClient = useQueryClient();++ const { data: executions, isSuccess } = useGetV1ListAllExecutions({+ query: { select: okData },+ });++ const graphIDs = useMemo(() => agents.map((a) => a.graph_id), [agents]);++ const handleExecutionUpdate = useCallback(() => {+ queryClient.invalidateQueries({+ queryKey: getGetV1ListAllExecutionsQueryKey(),+ });+ }, [queryClient]);++ useExecutionEvents({+ graphIds: graphIDs.length > 0 ? graphIDs : undefined,+ enabled: graphIDs.length > 0,+ onExecutionUpdate: handleExecutionUpdate,+ });++ return useMemo(() => {+ if (!isSuccess || !executions) return undefined;++ const agentsWithActiveExecution = new Set<string>();+ const agentsWithRecentFailure = new Set<string>();+ const agentsWithRecentCompletion = new Set<string>();++ for (const exec of executions) {+ if (isActive(exec.status)) {+ agentsWithActiveExecution.add(exec.graph_id);+ }+ if (isRecentFailure(exec.status, exec.ended_at)) {+ agentsWithRecentFailure.add(exec.graph_id);+ }+ if (isRecentCompletion(exec.status, exec.ended_at)) {+ agentsWithRecentCompletion.add(exec.graph_id);+ }+ }++ const summary: FleetSummary = {+ running: 0,+ error: 0,+ completed: 0,+ listening: 0,+ scheduled: 0,+ idle: 0,+ monthlySpend: 0,+ };++ for (const agent of agents) {+ if (agentsWithActiveExecution.has(agent.graph_id)) {+ summary.running += 1;+ } else if (agentsWithRecentFailure.has(agent.graph_id)) {+ summary.error += 1;+ } else if (agent.has_external_trigger) {+ summary.listening += 1;+ } else if (agent.recommended_schedule_cron) {+ summary.scheduled += 1;+ } else {+ summary.idle += 1;+ }+ // Parallel counter: mutually exclusive with running/error (which match+ // the sitrep priority order used by the "Recently completed" tab list)+ // but orthogonal to listening/scheduled/idle.+ if (+ !agentsWithActiveExecution.has(agent.graph_id) &&+ !agentsWithRecentFailure.has(agent.graph_id) &&+ agentsWithRecentCompletion.has(agent.graph_id)+ ) {+ summary.completed += 1;+ }+ }++ return summary;+ }, [agents, executions, isSuccess]);+}diff --git a/autogpt_platform/frontend/src/app/(platform)/library/page.tsx b/autogpt_platform/frontend/src/app/(platform)/library/page.tsxindex f88c4a64dd..b660999520 100644--- a/autogpt_platform/frontend/src/app/(platform)/library/page.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/library/page.tsx@@ -2,12 +2,14 @@import { useEffect, useState, useCallback } from "react";import { HeartIcon, ListIcon } from "@phosphor-icons/react";-import { JumpBackIn } from "./components/JumpBackIn/JumpBackIn";import { LibraryActionHeader } from "./components/LibraryActionHeader/LibraryActionHeader";import { LibraryAgentList } from "./components/LibraryAgentList/LibraryAgentList";import { useLibraryListPage } from "./components/useLibraryListPage";import { FavoriteAnimationProvider } from "./context/FavoriteAnimationContext";-import { LibraryTab } from "./types";+import type { LibraryTab, AgentStatusFilter } from "./types";+import { useLibraryFleetSummary } from "./hooks/useLibraryFleetSummary";+import { Flag, useGetFlag } from "@/services/feature-flags/use-get-flag";+import { useLibraryAgents } from "@/hooks/useLibraryAgents/useLibraryAgents";const LIBRARY_TABS: LibraryTab[] = [{ id: "all", title: "All", icon: ListIcon },@@ -19,6 +21,10 @@ export default function LibraryPage() {useLibraryListPage();const [selectedFolderId, setSelectedFolderId] = useState<string | null>(null);const [activeTab, setActiveTab] = useState(LIBRARY_TABS[0].id);+ const [statusFilter, setStatusFilter] = useState<AgentStatusFilter>("all");+ const isAgentBriefingEnabled = useGetFlag(Flag.AGENT_BRIEFING);+ const { agents } = useLibraryAgents();+ const fleetSummary = useLibraryFleetSummary(agents);useEffect(() => {document.title = "Library – AutoGPT Platform";@@ -40,7 +46,6 @@ export default function LibraryPage() {><main className="pt-160 container min-h-screen space-y-4 pb-20 pt-16 sm:px-8 md:px-12"><LibraryActionHeader setSearchTerm={setSearchTerm} />- <JumpBackIn /><LibraryAgentListsearchTerm={searchTerm}librarySort={librarySort}@@ -50,6 +55,10 @@ export default function LibraryPage() {tabs={LIBRARY_TABS}activeTab={activeTab}onTabChange={handleTabChange}+ statusFilter={statusFilter}+ onStatusFilterChange={setStatusFilter}+ fleetSummary={isAgentBriefingEnabled ? fleetSummary : undefined}+ briefingAgents={isAgentBriefingEnabled ? agents : undefined}/></main></FavoriteAnimationProvider>diff --git a/autogpt_platform/frontend/src/app/(platform)/library/types.ts b/autogpt_platform/frontend/src/app/(platform)/library/types.tsindex dad4096fc4..b5253b41bc 100644--- a/autogpt_platform/frontend/src/app/(platform)/library/types.ts+++ b/autogpt_platform/frontend/src/app/(platform)/library/types.ts@@ -1,7 +1,76 @@-import { Icon } from "@phosphor-icons/react";+import type { Icon } from "@phosphor-icons/react";export interface LibraryTab {id: string;title: string;icon: Icon;}++/** Agent execution status — drives StatusBadge visuals & filtering. */+export type AgentStatus =+ | "running"+ | "error"+ | "listening"+ | "scheduled"+ | "idle";++/** Derived health bucket for quick triage. */+export type AgentHealth = "good" | "attention" | "stale";++/** Real-time metadata that powers the Intelligence Layer features. */+export interface AgentStatusInfo {+ status: AgentStatus;+ health: AgentHealth;+ /** 0-100 progress for currently running agents. */+ progress: number | null;+ totalRuns: number;+ lastRunAt: string | null;+ lastError: string | null;+ /** ID of the currently active execution (when status is "running"). */+ activeExecutionID: string | null;+ monthlySpend: number;+ nextScheduledRun: string | null;+ triggerType: string | null;+}++/** Fleet-wide aggregate counts used by the Briefing Panel stats grid. */+export interface FleetSummary {+ running: number;+ error: number;+ completed: number;+ listening: number;+ scheduled: number;+ idle: number;+ monthlySpend: number;+}++export type SitrepPriority =+ | "error"+ | "running"+ | "stale"+ | "success"+ | "listening"+ | "scheduled"+ | "idle";++export interface SitrepItemData {+ id: string;+ agentID: string;+ agentName: string;+ agentImageUrl?: string | null;+ executionID?: string;+ priority: SitrepPriority;+ message: string;+ status: AgentStatus;+}++/** Filter options for the agent filter dropdown. */+export type AgentStatusFilter =+ | "all"+ | "running"+ | "attention"+ | "completed"+ | "listening"+ | "scheduled"+ | "idle"+ | "healthy";diff --git a/autogpt_platform/frontend/src/app/layout.tsx b/autogpt_platform/frontend/src/app/layout.tsxindex f793d7dc2b..df67b9d0c2 100644--- a/autogpt_platform/frontend/src/app/layout.tsx+++ b/autogpt_platform/frontend/src/app/layout.tsx@@ -12,6 +12,7 @@ import { Toaster } from "@/components/molecules/Toast/toaster";import { SetupAnalytics } from "@/services/analytics";import { VercelAnalyticsWrapper } from "@/services/analytics/VercelAnalyticsWrapper";import { environment } from "@/services/environment";+import AgentationDevtool from "@/components/AgentationDevtool";import { ReactQueryDevtools } from "@tanstack/react-query-devtools";import { headers } from "next/headers";@@ -77,6 +78,7 @@ export default async function RootLayout({</div><Toaster /><CookieConsentBanner />+ {(isLocal || isDev) && <AgentationDevtool />}</Providers></ErrorBoundary></body>diff --git a/autogpt_platform/frontend/src/components/AgentationDevtool.tsx b/autogpt_platform/frontend/src/components/AgentationDevtool.tsxnew file mode 100644index 0000000000..82b59c78e8--- /dev/null+++ b/autogpt_platform/frontend/src/components/AgentationDevtool.tsx@@ -0,0 +1,12 @@+"use client";++import dynamic from "next/dynamic";++const Agentation = dynamic(+ () => import("agentation").then((mod) => mod.Agentation),+ { ssr: false },+);++export default function AgentationDevtool() {+ return <Agentation />;+}diff --git a/autogpt_platform/frontend/src/contexts/AutoPilotBridgeContext.tsx b/autogpt_platform/frontend/src/contexts/AutoPilotBridgeContext.tsxnew file mode 100644index 0000000000..6fee4c1a1a--- /dev/null+++ b/autogpt_platform/frontend/src/contexts/AutoPilotBridgeContext.tsx@@ -0,0 +1,64 @@+"use client";++import { createContext, useContext, useState } from "react";+import { useRouter } from "next/navigation";++const STORAGE_KEY = "autopilot_pending_prompt";++interface AutoPilotBridgeState {+ pendingPrompt: string | null;+ sendPrompt: (prompt: string) => void;+ consumePrompt: () => string | null;+}++const AutoPilotBridgeContext = createContext<AutoPilotBridgeState | null>(null);++interface Props {+ children: React.ReactNode;+}++export function AutoPilotBridgeProvider({ children }: Props) {+ const router = useRouter();++ const [pendingPrompt, setPendingPrompt] = useState<string | null>(() => {+ if (typeof window === "undefined") return null;+ return sessionStorage.getItem(STORAGE_KEY);+ });++ function sendPrompt(prompt: string) {+ sessionStorage.setItem(STORAGE_KEY, prompt);+ setPendingPrompt(prompt);+ router.push("/");+ }++ function consumePrompt(): string | null {+ const prompt = pendingPrompt ?? sessionStorage.getItem(STORAGE_KEY);+ if (prompt !== null) {+ sessionStorage.removeItem(STORAGE_KEY);+ setPendingPrompt(null);+ }+ return prompt;+ }++ return (+ <AutoPilotBridgeContext.Provider+ value={{ pendingPrompt, sendPrompt, consumePrompt }}+ >+ {children}+ </AutoPilotBridgeContext.Provider>+ );+}++export function useAutoPilotBridge(): AutoPilotBridgeState {+ const context = useContext(AutoPilotBridgeContext);+ if (!context) {+ // Return a no-op implementation when used outside the provider+ // (e.g. in tests or isolated component renders).+ return {+ pendingPrompt: null,+ sendPrompt: () => {},+ consumePrompt: () => null,+ };+ }+ return context;+}diff --git a/autogpt_platform/frontend/src/playwright/library-happy-path.spec.ts b/autogpt_platform/frontend/src/playwright/library-happy-path.spec.tsindex f7ed0e796c..17c02397a6 100644--- a/autogpt_platform/frontend/src/playwright/library-happy-path.spec.ts+++ b/autogpt_platform/frontend/src/playwright/library-happy-path.spec.ts@@ -385,7 +385,9 @@ test("library happy path: user can edit a saved agent from Library and keep chan.context().waitForEvent("page", { timeout: 10000 }).catch(() => null);- await agentCard+ // "Edit agent" link is inside the three-dot dropdown menu+ await agentCard.getByRole("button", { name: "More actions" }).first().click();+ await page.getByTestId("library-agent-card-open-in-builder-link").first().click();diff --git a/autogpt_platform/frontend/src/playwright/pages/library.page.ts b/autogpt_platform/frontend/src/playwright/pages/library.page.tsindex 85c3f3978a..f2e648b341 100644--- a/autogpt_platform/frontend/src/playwright/pages/library.page.ts+++ b/autogpt_platform/frontend/src/playwright/pages/library.page.ts@@ -262,13 +262,19 @@ export class LibraryPage extends BasePage {async clickOpenInBuilder(agent: Agent): Promise<void> {console.log(`clicking open in builder for agent: ${agent.name}`);- const { getId } = getSelectors(this.page);- const agentCard = getId("library-agent-card").filter({- hasText: agent.name,+ const agentCard = this.page+ .getByTestId("library-agent-card")+ .filter({ hasText: agent.name });++ // The "Edit agent" link is inside the three-dot dropdown menu.+ // Open the menu first, then click the builder link.+ const menuTrigger = agentCard.getByRole("button", {+ name: "More actions",});- const builderLink = getId(+ await menuTrigger.first().click();++ const builderLink = this.page.getByTestId("library-agent-card-open-in-builder-link",- agentCard,);await builderLink.first().click();}diff --git a/autogpt_platform/frontend/src/services/feature-flags/use-get-flag.ts b/autogpt_platform/frontend/src/services/feature-flags/use-get-flag.tsindex e16f5b765a..78c82acc5c 100644--- a/autogpt_platform/frontend/src/services/feature-flags/use-get-flag.ts+++ b/autogpt_platform/frontend/src/services/feature-flags/use-get-flag.ts@@ -11,6 +11,7 @@ export enum Flag {ARTIFACTS = "artifacts",CHAT_MODE_OPTION = "chat-mode-option",BUILDER_CHAT_PANEL = "builder-chat-panel",+ AGENT_BRIEFING = "agent-briefing",}const isPwMockEnabled = process.env.NEXT_PUBLIC_PW_TEST === "true";@@ -22,6 +23,7 @@ const defaultFlags = {[Flag.ARTIFACTS]: false,[Flag.CHAT_MODE_OPTION]: false,[Flag.BUILDER_CHAT_PANEL]: false,+ [Flag.AGENT_BRIEFING]: false,};type FlagValues = typeof defaultFlags;