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.
fix(frontend/library): Fix crash on Trigger Agent selection in Triggers tab (#13594)
Reinier van der Leera59b87968e11
diff --git a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/__tests__/helpers.test.ts b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/__tests__/helpers.test.tsnew file mode 100644index 0000000000..f61b12950e--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/__tests__/helpers.test.ts@@ -0,0 +1,109 @@+import type { LibraryAgentPreset } from "@/app/api/__generated__/models/libraryAgentPreset";+import { describe, expect, test } from "vitest";+import {+ activeItemParamFor,+ deriveSelectedTriggerKind,+ parseActiveItemParam,+ retryUnlessClientError,+} from "../components/NewAgentLibraryView/helpers";++describe("activeItem param prefix contract", () => {+ test("round-trips both kinds and passes through bare IDs and null", () => {+ for (const kind of ["trigger-agent", "webhook-trigger"] as const) {+ expect(parseActiveItemParam(activeItemParamFor(kind, "some-id"))).toEqual(+ { activeItemId: "some-id", triggerKindHint: kind },+ );+ }+ expect(parseActiveItemParam("bare-id")).toEqual({+ activeItemId: "bare-id",+ triggerKindHint: null,+ });+ expect(parseActiveItemParam(null)).toEqual({+ activeItemId: null,+ triggerKindHint: null,+ });+ });+});++describe("retryUnlessClientError", () => {+ test("fails fast on 4xx, retries server/unknown errors up to 3 times", () => {+ const notFound = Object.assign(new Error("Preset #x not found"), {+ status: 404,+ });+ expect(retryUnlessClientError(0, notFound)).toBe(false);++ const serverError = Object.assign(new Error("boom"), { status: 500 });+ expect(retryUnlessClientError(0, serverError)).toBe(true);+ expect(retryUnlessClientError(3, serverError)).toBe(false);+ expect(retryUnlessClientError(0, new Error("network down"))).toBe(true);+ });+});++describe("deriveSelectedTriggerKind", () => {+ const webhookPreset = {+ id: "preset-1",+ webhook_id: "webhook-1",+ } as LibraryAgentPreset;+ const template = { id: "template-1", webhook_id: null } as LibraryAgentPreset;+ const settled = {+ triggerAgents: [{ id: "agent-1" }],+ presets: [webhookPreset, template],+ presetsComplete: true,+ listsResolved: true,+ anyListFailed: false,+ triggerKindHint: null,+ };++ test("resolves membership, ignoring a contradicting hint", () => {+ expect(+ deriveSelectedTriggerKind({+ ...settled,+ activeItemId: "agent-1",+ triggerKindHint: "webhook-trigger",+ }),+ ).toBe("trigger-agent");+ expect(+ deriveSelectedTriggerKind({+ ...settled,+ activeItemId: "preset-1",+ triggerKindHint: "trigger-agent",+ }),+ ).toBe("webhook-trigger");+ expect(+ deriveSelectedTriggerKind({ ...settled, activeItemId: "template-1" }),+ ).toBe("not-found");+ });++ test("uses the hint while lists are unresolved, else loading/error", () => {+ const unresolved = {+ ...settled,+ activeItemId: "unknown-id",+ triggerAgents: undefined,+ presets: undefined,+ listsResolved: false,+ };+ expect(+ deriveSelectedTriggerKind({+ ...unresolved,+ triggerKindHint: "trigger-agent",+ }),+ ).toBe("trigger-agent");+ expect(deriveSelectedTriggerKind(unresolved)).toBe("loading");+ expect(+ deriveSelectedTriggerKind({ ...unresolved, anyListFailed: true }),+ ).toBe("error");+ });++ test("only concludes not-found when the presets page is complete", () => {+ expect(+ deriveSelectedTriggerKind({ ...settled, activeItemId: "unknown-id" }),+ ).toBe("not-found");+ expect(+ deriveSelectedTriggerKind({+ ...settled,+ activeItemId: "unknown-id",+ presetsComplete: false,+ }),+ ).toBe("webhook-trigger");+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/__tests__/trigger-agents.test.tsx b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/__tests__/trigger-agents.test.tsxindex aa54a506fd..eb9331cf86 100644--- a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/__tests__/trigger-agents.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/__tests__/trigger-agents.test.tsx@@ -7,7 +7,13 @@ import {} from "@/app/api/__generated__/endpoints/library/library.msw";import { getGetV1ListGraphExecutionsMockHandler } from "@/app/api/__generated__/endpoints/graphs/graphs.msw";import { getGetV1ListExecutionSchedulesForAGraphMockHandler } from "@/app/api/__generated__/endpoints/schedules/schedules.msw";-import { getGetV2ListPresetsMockHandler } from "@/app/api/__generated__/endpoints/presets/presets.msw";+import {+ getGetV2GetASpecificPresetMockHandler,+ getGetV2GetASpecificPresetResponseMock,+ getGetV2ListPresetsMockHandler,+ getGetV2ListPresetsMockHandler422,+} from "@/app/api/__generated__/endpoints/presets/presets.msw";+import type { LibraryAgentPreset } from "@/app/api/__generated__/models/libraryAgentPreset";import { TooltipProvider } from "@/components/atoms/Tooltip/BaseTooltip";import { BackendAPIProvider } from "@/lib/autogpt-server-api/context";import OnboardingProvider from "@/providers/onboarding/onboarding-provider";@@ -15,10 +21,12 @@ import { server } from "@/mocks/mock-server";import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import { fireEvent, render, screen, waitFor } from "@testing-library/react";import userEvent from "@testing-library/user-event";+import { http, HttpResponse } from "msw";import { NuqsTestingAdapter } from "nuqs/adapters/testing";import { ReactNode } from "react";import { beforeEach, describe, expect, test, vi } from "vitest";import { NewAgentLibraryView } from "../components/NewAgentLibraryView/NewAgentLibraryView";+import { PRESETS_PAGE_SIZE } from "../components/NewAgentLibraryView/hooks/useAgentPresetsQuery";const PARENT_ID = "parent-agent-id";const PARENT_GRAPH_ID = "parent-graph-id";@@ -65,6 +73,7 @@ vi.mock("@/services/feature-flags/use-get-flag", () => ({GENERIC_TRIGGER_AGENTS: "generic-trigger-agents",},useGetFlag: mockUseGetFlag,+ useFlagStatus: () => ({ enabled: mockUseGetFlag(), ready: true }),}));// Per-test render wrapper so we can set the nuqs initial URL state@@ -124,6 +133,40 @@ const emptyPresetsHandler = getGetV2ListPresetsMockHandler({const emptySchedulesHandler =getGetV1ListExecutionSchedulesForAGraphMockHandler([]);+function makeWebhookPreset(overrides: Partial<LibraryAgentPreset> = {}) {+ return {+ id: "preset-1",+ user_id: "user-1",+ graph_id: PARENT_GRAPH_ID,+ graph_version: 1,+ name: "Webhook Trigger",+ description: "",+ inputs: {},+ credentials: {},+ is_active: true,+ webhook_id: "webhook-1",+ webhook: null,+ created_at: new Date("2026-01-01T00:00:00.000Z"),+ updated_at: new Date("2026-01-01T00:00:00.000Z"),+ ...overrides,+ };+}++function singlePresetListHandler(+ preset: ReturnType<typeof makeWebhookPreset>,+ totalItems = 1,+) {+ return getGetV2ListPresetsMockHandler({+ presets: [preset],+ pagination: {+ total_items: totalItems,+ total_pages: Math.ceil(totalItems / PRESETS_PAGE_SIZE),+ current_page: 1,+ page_size: PRESETS_PAGE_SIZE,+ },+ });+}+describe("Library agent view — trigger agents", () => {beforeEach(() => {server.resetHandlers();@@ -182,31 +225,7 @@ describe("Library agent view — trigger agents", () => {...baseHandlers(),emptySchedulesHandler,getGetV2ListTriggerAgentsMockHandler([triggerAgent]),- getGetV2ListPresetsMockHandler({- presets: [- {- id: "preset-1",- user_id: "user-1",- graph_id: PARENT_GRAPH_ID,- graph_version: 1,- name: "Webhook Trigger",- description: "",- inputs: {},- credentials: {},- is_active: true,- webhook_id: "webhook-1",- webhook: null,- created_at: new Date("2026-01-01T00:00:00.000Z"),- updated_at: new Date("2026-01-01T00:00:00.000Z"),- },- ],- pagination: {- total_items: 1,- total_pages: 1,- current_page: 1,- page_size: 100,- },- }),+ singlePresetListHandler(makeWebhookPreset()),);renderWithInitialParams(<NewAgentLibraryView />, "activeTab=triggers");@@ -453,6 +472,255 @@ describe("Library agent view — trigger agents", () => {});});+ test("selecting a webhook trigger renders its preset detail view", async () => {+ const webhookPreset = makeWebhookPreset({+ description: "Fires on webhook",+ });++ server.use(+ ...baseHandlers(),+ emptySchedulesHandler,+ getGetV2ListTriggerAgentsMockHandler([]),+ singlePresetListHandler(webhookPreset),+ getGetV2GetASpecificPresetMockHandler(webhookPreset),+ );++ renderWithInitialParams(+ <NewAgentLibraryView />,+ "activeTab=triggers&activeItem=preset-1",+ );++ await screen.findByText("Trigger Details");+ screen.getByDisplayValue("Webhook Trigger");+ });++ test("agent:-prefixed activeItem renders the trigger agent detail view", async () => {+ const triggerAgent = getGetV2GetLibraryAgentResponseMock({+ id: TRIGGER_ID,+ graph_id: TRIGGER_GRAPH_ID,+ name: "Hinted Watcher",+ description: "Selected via type-hinted URL",+ is_hidden: true,+ });++ server.use(+ ...baseHandlers(),+ emptyPresetsHandler,+ emptySchedulesHandler,+ getGetV2ListTriggerAgentsMockHandler([triggerAgent]),+ );++ renderWithInitialParams(+ <NewAgentLibraryView />,+ `activeTab=triggers&activeItem=agent:${TRIGGER_ID}`,+ );++ await screen.findByText("Selected via type-hinted URL");+ });++ test("stale trigger id shows a graceful not-found state without fetching a preset", async () => {+ const triggerAgent = getGetV2GetLibraryAgentResponseMock({+ id: TRIGGER_ID,+ graph_id: TRIGGER_GRAPH_ID,+ name: "Still Alive",+ is_hidden: true,+ });++ let presetGetCalls = 0;+ server.use(+ ...baseHandlers(),+ emptyPresetsHandler,+ emptySchedulesHandler,+ getGetV2ListTriggerAgentsMockHandler([triggerAgent]),+ // If the view wrongly assumes the unknown id is a preset, this+ // handler fires — the old behavior that produced a 404 error page.+ getGetV2GetASpecificPresetMockHandler(() => {+ presetGetCalls += 1;+ return getGetV2GetASpecificPresetResponseMock();+ }),+ );++ renderWithInitialParams(+ <NewAgentLibraryView />,+ "activeTab=triggers&activeItem=deleted-preset-id",+ );++ await screen.findByText("Trigger not found");+ await screen.findByText(/doesn't exist or is no longer available/i);+ expect(presetGetCalls).toBe(0);+ });++ test("a preset: hint mounts the detail view while the lists are still loading", async () => {+ const webhookPreset = makeWebhookPreset({ name: "Hint Routed Early" });+ let releaseLists!: () => void;+ const listGate = new Promise<void>((resolve) => {+ releaseLists = resolve;+ });++ server.use(+ ...baseHandlers(),+ emptySchedulesHandler,+ getGetV2ListTriggerAgentsMockHandler(async () => {+ await listGate;+ return [];+ }),+ getGetV2ListPresetsMockHandler(async () => {+ await listGate;+ return {+ presets: [webhookPreset],+ pagination: {+ total_items: 1,+ total_pages: 1,+ current_page: 1,+ page_size: PRESETS_PAGE_SIZE,+ },+ };+ }),+ getGetV2GetASpecificPresetMockHandler(webhookPreset),+ );++ renderWithInitialParams(+ <NewAgentLibraryView />,+ `activeTab=triggers&activeItem=preset:${webhookPreset.id}`,+ );++ // The detail view renders from the hint alone — both list queries are+ // still gated at this point.+ await screen.findByText("Trigger Details");+ screen.getByDisplayValue("Hint Routed Early");++ releaseLists();+ });++ test("stale selection of the sole trigger keeps its not-found state with a recovery action", async () => {+ server.use(+ ...baseHandlers(),+ emptyPresetsHandler,+ emptySchedulesHandler,+ getGetV2ListTriggerAgentsMockHandler([]),+ );++ renderWithInitialParams(+ <NewAgentLibraryView />,+ "activeTab=triggers&activeItem=agent:deleted-trigger-id",+ );++ // Without the activeItem guards, the zero-trigger redirect + zero-item+ // layout replace this with the empty-tasks screen.+ await screen.findByText("Trigger not found");+ const clearButton = await screen.findByRole("button", {+ name: /clear selection/i,+ });++ fireEvent.click(clearButton);+ await waitFor(() => {+ expect(screen.queryByText("Trigger not found")).toBeNull();+ });+ });++ test("unknown ID with an incomplete presets page falls back to the preset detail view", async () => {+ const beyondPagePreset = makeWebhookPreset({+ id: "beyond-page-1",+ name: "Beyond Page Trigger",+ });++ server.use(+ ...baseHandlers(),+ emptySchedulesHandler,+ getGetV2ListTriggerAgentsMockHandler([]),+ // The first page doesn't contain the selected ID, but total_items says+ // the page is incomplete — membership must NOT conclude "not-found".+ singlePresetListHandler(makeWebhookPreset(), 150),+ getGetV2GetASpecificPresetMockHandler(beyondPagePreset),+ );++ renderWithInitialParams(+ <NewAgentLibraryView />,+ "activeTab=triggers&activeItem=beyond-page-1",+ );++ await screen.findByText("Trigger Details");+ screen.getByDisplayValue("Beyond Page Trigger");+ expect(screen.queryByText("Trigger not found")).toBeNull();+ });++ test("webhook trigger deleted between list and detail fetch renders the not-found card", async () => {+ const webhookPreset = makeWebhookPreset({ name: "Just Deleted" });++ server.use(+ ...baseHandlers(),+ emptySchedulesHandler,+ getGetV2ListTriggerAgentsMockHandler([]),+ singlePresetListHandler(webhookPreset),+ // The preset is in the list, but its by-ID detail fetch 404s — the+ // race where it's deleted between the list load and selection.+ http.get(+ "http://localhost:3000/api/proxy/api/library/presets/:presetId",+ () =>+ new HttpResponse(+ JSON.stringify({ detail: "Preset #preset-1 not found" }),+ {+ status: 404,+ headers: { "Content-Type": "application/json" },+ },+ ),+ ),+ );++ renderWithInitialParams(+ <NewAgentLibraryView />,+ `activeTab=triggers&activeItem=preset:${webhookPreset.id}`,+ );++ await screen.findByText("Trigger not found");+ expect(screen.queryByText(/when retrieving/i)).toBeNull();+ });++ test("failed presets fetch shows an error card instead of an endless skeleton", async () => {+ server.use(+ ...baseHandlers(),+ emptySchedulesHandler,+ getGetV2ListTriggerAgentsMockHandler([]),+ getGetV2ListPresetsMockHandler422(),+ );++ renderWithInitialParams(+ <NewAgentLibraryView />,+ "activeTab=triggers&activeItem=some-bare-id",+ );++ await screen.findByText(/when retrieving triggers/i);+ });++ test("templates-tab preset failure still surfaces the page-level error", async () => {+ server.use(+ ...baseHandlers(),+ emptyPresetsHandler,+ emptySchedulesHandler,+ getGetV2ListTriggerAgentsMockHandler([]),+ http.get(+ "http://localhost:3000/api/proxy/api/library/presets/:presetId",+ () =>+ new HttpResponse(+ JSON.stringify({ detail: "Preset #gone-template not found" }),+ {+ status: 404,+ headers: { "Content-Type": "application/json" },+ },+ ),+ ),+ );++ renderWithInitialParams(+ <NewAgentLibraryView />,+ "activeTab=templates&activeItem=gone-template",+ );++ // On the Templates tab the shared preset query's error must still+ // surface — the tab guard only suppresses it elsewhere.+ await screen.findByText(/when retrieving agent/i);+ });+test("when generic-trigger-agents flag is off, hides 'Trigger Agents' subsection and skips the trigger-agents fetch", async () => {mockUseGetFlag.mockReturnValue(false);@@ -474,31 +742,7 @@ describe("Library agent view — trigger agents", () => {return [triggerAgent];}),// Webhook trigger so the Triggers tab still has reason to exist.- getGetV2ListPresetsMockHandler({- presets: [- {- id: "preset-1",- user_id: "user-1",- graph_id: PARENT_GRAPH_ID,- graph_version: 1,- name: "Webhook Trigger",- description: "",- inputs: {},- credentials: {},- is_active: true,- webhook_id: "webhook-1",- webhook: null,- created_at: new Date("2026-01-01T00:00:00.000Z"),- updated_at: new Date("2026-01-01T00:00:00.000Z"),- },- ],- pagination: {- total_items: 1,- total_pages: 1,- current_page: 1,- page_size: 100,- },- }),+ singlePresetListHandler(makeWebhookPreset()),);renderWithInitialParams(<NewAgentLibraryView />, "activeTab=triggers");diff --git a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/NewAgentLibraryView.tsx b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/NewAgentLibraryView.tsxindex 38d7f5d3f6..85587bccdc 100644--- a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/NewAgentLibraryView.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/NewAgentLibraryView.tsx@@ -17,6 +17,7 @@ import { EmptyTemplates } from "./components/other/EmptyTemplates";import { EmptyTriggers } from "./components/other/EmptyTriggers";import { MarketplaceBanners } from "./components/other/MarketplaceBanners";import { SectionWrap } from "./components/other/SectionWrap";+import { TriggerNotFound } from "./components/other/TriggerNotFound";import { LoadingSelectedContent } from "./components/selected-views/LoadingSelectedContent";import { SelectedRunView } from "./components/selected-views/SelectedRunView/SelectedRunView";import { SelectedScheduleView } from "./components/selected-views/SelectedScheduleView/SelectedScheduleView";@@ -38,8 +39,9 @@ export function NewAgentLibraryView() {isTemplateLoading,error,hasAnyItems,- activeItem,- isActiveItemTriggerAgent,+ activeItemId,+ selectedTriggerKind,+ retryTriggerLists,sidebarLoading,activeTab,setActiveTab,@@ -119,6 +121,60 @@ export function NewAgentLibraryView() {);}+ function renderSelectedTrigger(selectedItemId: string) {+ if (!agent) return null;++ switch (selectedTriggerKind) {+ case "trigger-agent":+ return (+ <SelectedTriggerAgentView+ agent={agent}+ triggerAgentId={selectedItemId}+ onClearSelectedRun={handleClearSelectedRun}+ banner={renderMarketplaceUpdateBanner()}+ />+ );+ case "webhook-trigger":+ return (+ <SelectedTriggerView+ agent={agent}+ triggerId={selectedItemId}+ onClearSelectedRun={handleClearSelectedRun}+ onSwitchToRunsTab={() => setActiveTab("runs")}+ banner={renderMarketplaceUpdateBanner()}+ />+ );+ case "loading":+ return <LoadingSelectedContent agent={agent} />;+ case "error":+ return (+ <SelectedViewLayout+ agent={agent}+ banner={renderMarketplaceUpdateBanner()}+ >+ <ErrorCard+ responseError={{+ message:+ "Could not load this agent's triggers. Check your connection and try again.",+ }}+ context="triggers"+ onRetry={retryTriggerLists}+ />+ </SelectedViewLayout>+ );+ case "not-found":+ return (+ <TriggerNotFound+ agent={agent}+ banner={renderMarketplaceUpdateBanner()}+ onClearSelection={handleClearSelectedRun}+ />+ );+ default:+ return null;+ }+ }+if (error) {return (<ErrorCard@@ -134,7 +190,9 @@ export function NewAgentLibraryView() {return <AgentRunsLoading />;}- if (!sidebarLoading && !hasAnyItems) {+ // Keep the selected-content layout while an item is selected — even with+ // zero listable items — so a stale selection can show its not-found state.+ if (!sidebarLoading && !hasAnyItems && !activeItemId) {return (<><div className="flex h-full flex-col">@@ -196,7 +254,7 @@ export function NewAgentLibraryView() {<SidebarRunsListagent={agent}- selectedRunId={activeItem ?? undefined}+ selectedRunId={activeItemId ?? undefined}onSelectRun={handleSelectRun}onClearSelectedRun={handleClearSelectedRun}onScheduleDeleted={handleScheduleDeleted}@@ -205,11 +263,11 @@ export function NewAgentLibraryView() {/></SectionWrap>- {activeItem ? (+ {activeItemId ? (activeTab === "scheduled" ? (<SelectedScheduleViewagent={agent}- scheduleId={activeItem}+ scheduleId={activeItemId}onScheduleDeleted={handleScheduleDeleted}onSelectRun={(id) => handleSelectRun(id, "runs")}banner={renderMarketplaceUpdateBanner()}@@ -217,7 +275,7 @@ export function NewAgentLibraryView() {) : activeTab === "templates" ? (<SelectedTemplateViewagent={agent}- templateId={activeItem}+ templateId={activeItemId}onClearSelectedRun={handleClearSelectedRun}onRunCreated={(execution) =>handleSelectRun(execution.id, "runs")@@ -226,26 +284,11 @@ export function NewAgentLibraryView() {banner={renderMarketplaceUpdateBanner()}/>) : activeTab === "triggers" ? (- isActiveItemTriggerAgent ? (- <SelectedTriggerAgentView- agent={agent}- triggerAgentId={activeItem}- onClearSelectedRun={handleClearSelectedRun}- banner={renderMarketplaceUpdateBanner()}- />- ) : (- <SelectedTriggerView- agent={agent}- triggerId={activeItem}- onClearSelectedRun={handleClearSelectedRun}- onSwitchToRunsTab={() => setActiveTab("runs")}- banner={renderMarketplaceUpdateBanner()}- />- )+ renderSelectedTrigger(activeItemId)) : (<SelectedRunViewagent={agent}- runId={activeItem}+ runId={activeItemId}onSelectRun={handleSelectRun}onClearSelectedRun={handleClearSelectedRun}banner={renderMarketplaceUpdateBanner()}diff --git a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/other/TriggerNotFound.tsx b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/other/TriggerNotFound.tsxnew file mode 100644index 0000000000..1a2390eb47--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/other/TriggerNotFound.tsx@@ -0,0 +1,32 @@+"use client";++import type { LibraryAgent } from "@/app/api/__generated__/models/libraryAgent";+import { Button } from "@/components/atoms/Button/Button";+import { Text } from "@/components/atoms/Text/Text";+import { RunDetailCard } from "../selected-views/RunDetailCard/RunDetailCard";+import { SelectedViewLayout } from "../selected-views/SelectedViewLayout";++interface Props {+ agent: LibraryAgent;+ banner?: React.ReactNode;+ onClearSelection?: () => void;+}++export function TriggerNotFound({ agent, banner, onClearSelection }: Props) {+ return (+ <SelectedViewLayout agent={agent} banner={banner}>+ <RunDetailCard title="Trigger not found">+ <div className="flex flex-col items-start gap-4">+ <Text variant="body" className="!text-zinc-500">+ This trigger doesn't exist or is no longer available.+ </Text>+ {onClearSelection && (+ <Button variant="secondary" size="small" onClick={onClearSelection}>+ Clear selection+ </Button>+ )}+ </div>+ </RunDetailCard>+ </SelectedViewLayout>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/selected-views/LoadingSelectedContent.tsx b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/selected-views/LoadingSelectedContent.tsxindex bc5548afd0..9a68c4edfe 100644--- a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/selected-views/LoadingSelectedContent.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/selected-views/LoadingSelectedContent.tsx@@ -13,6 +13,10 @@ export function LoadingSelectedContent(props: Props) {<SelectedViewLayout agent={props.agent}><divclassName={cn("flex flex-col gap-4", AGENT_LIBRARY_SECTION_PADDING_X)}+ data-testid="loading-selected-content"+ role="status"+ aria-busy="true"+ aria-label="Loading content"><Skeleton className="h-8 w-full" /><Skeleton className="h-12 w-full" />diff --git a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/selected-views/SelectedTriggerView/SelectedTriggerView.tsx b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/selected-views/SelectedTriggerView/SelectedTriggerView.tsxindex 74dfbd12c2..c1cf00e8e0 100644--- a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/selected-views/SelectedTriggerView/SelectedTriggerView.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/selected-views/SelectedTriggerView/SelectedTriggerView.tsx@@ -4,6 +4,8 @@ import type { LibraryAgent } from "@/app/api/__generated__/models/libraryAgent";import { Input } from "@/components/atoms/Input/Input";import { CredentialsInput } from "@/components/contextual/CredentialsInput/CredentialsInput";import { ErrorCard } from "@/components/molecules/ErrorCard/ErrorCard";+import { getErrorStatus } from "../../../helpers";+import { TriggerNotFound } from "../../other/TriggerNotFound";import {getAgentCredentialsFields,getAgentInputFields,@@ -56,6 +58,16 @@ export function SelectedTriggerView({const inputFields = Object.entries(agentInputFields);const credentialFields = Object.entries(agentCredentialsFields);+ if (getErrorStatus(error) === 404) {+ return (+ <TriggerNotFound+ agent={agent}+ banner={banner}+ onClearSelection={onClearSelectedRun}+ />+ );+ }+if (error) {return (<ErrorCarddiff --git a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/selected-views/SelectedTriggerView/useSelectedTriggerView.ts b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/selected-views/SelectedTriggerView/useSelectedTriggerView.tsindex 235c653134..ed3ceb7205 100644--- a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/selected-views/SelectedTriggerView/useSelectedTriggerView.ts+++ b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/selected-views/SelectedTriggerView/useSelectedTriggerView.ts@@ -10,6 +10,7 @@ import type { LibraryAgentPresetUpdatable } from "@/app/api/__generated__/modelsimport { okData } from "@/app/api/helpers";import { useToast } from "@/components/molecules/Toast/use-toast";import type { CredentialsMetaInput } from "@/lib/autogpt-server-api/types";+import { retryUnlessClientError } from "../../../helpers";import { useQueryClient } from "@tanstack/react-query";import { useEffect, useState } from "react";@@ -26,6 +27,7 @@ export function useSelectedTriggerView({ triggerId, graphId }: Args) {query: {enabled: !!triggerId,select: okData,+ retry: retryUnlessClientError,},});diff --git a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/sidebar/SidebarRunsList/SidebarRunsList.tsx b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/sidebar/SidebarRunsList/SidebarRunsList.tsxindex f5c55e7897..f505dea5e0 100644--- a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/sidebar/SidebarRunsList/SidebarRunsList.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/sidebar/SidebarRunsList/SidebarRunsList.tsx@@ -13,7 +13,10 @@ import {TabsLineTrigger,} from "@/components/molecules/TabsLine/TabsLine";import { cn } from "@/lib/utils";-import { AGENT_LIBRARY_SECTION_PADDING_X } from "../../../helpers";+import {+ activeItemParamFor,+ AGENT_LIBRARY_SECTION_PADDING_X,+} from "../../../helpers";import { ScheduleListItem } from "./components/ScheduleListItem";import { TaskListItem } from "./components/TaskListItem";import { TemplateListItem } from "./components/TemplateListItem";@@ -66,8 +69,7 @@ export function SidebarRunsList({isFetchingMoreRuns,tabValue,} = useSidebarRunsList({- graphId: agent.graph_id,- libraryAgentID: agent.id,+ agent,onSelectRun,onCountsChange,});@@ -223,7 +225,12 @@ export function SidebarRunsList({trigger={trigger}agent={agent}selected={selectedRunId === trigger.id}- onClick={() => onSelectRun(trigger.id, "triggers")}+ onClick={() =>+ onSelectRun(+ activeItemParamFor("webhook-trigger", trigger.id),+ "triggers",+ )+ }/></div>))}@@ -246,7 +253,13 @@ export function SidebarRunsList({parentAgent={agent}selected={selectedRunId === triggerAgent.id}onClick={() =>- onSelectRun(triggerAgent.id, "triggers")+ onSelectRun(+ activeItemParamFor(+ "trigger-agent",+ triggerAgent.id,+ ),+ "triggers",+ )}/></div>diff --git a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/sidebar/SidebarRunsList/useSidebarRunsList.ts b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/sidebar/SidebarRunsList/useSidebarRunsList.tsindex 3b74e9ff6a..0385a0272a 100644--- a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/sidebar/SidebarRunsList/useSidebarRunsList.ts+++ b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/sidebar/SidebarRunsList/useSidebarRunsList.ts@@ -10,8 +10,14 @@ import {} from "@/app/api/helpers";import { useGetV1ListGraphExecutionsInfinite } from "@/app/api/__generated__/endpoints/graphs/graphs";import { useGetV2ListTriggerAgents } from "@/app/api/__generated__/endpoints/library/library";-import { useGetV2ListPresets } from "@/app/api/__generated__/endpoints/presets/presets";+import type { LibraryAgent } from "@/app/api/__generated__/models/libraryAgent";import { useGetV1ListExecutionSchedulesForAGraph } from "@/app/api/__generated__/endpoints/schedules/schedules";+import {+ activeItemParamFor,+ isWebhookPreset,+ retryUnlessClientError,+} from "../../../helpers";+import { useAgentPresetsQuery } from "../../../hooks/useAgentPresetsQuery";import { useExecutionEvents } from "@/hooks/useExecutionEvents";import { Flag, useGetFlag } from "@/services/feature-flags/use-get-flag";import { useQueryClient } from "@tanstack/react-query";@@ -32,8 +38,7 @@ function parseTab(}type Args = {- graphId: string;- libraryAgentID: string;+ agent: LibraryAgent;onSelectRun: (runId: string,tab?: "runs" | "scheduled" | "templates" | "triggers",@@ -48,11 +53,12 @@ type Args = {};export function useSidebarRunsList({- graphId,- libraryAgentID,+ agent,onSelectRun,onCountsChange,}: Args) {+ const graphId = agent.graph_id;+ const libraryAgentID = agent.id;const [{ activeItem, activeTab: activeTabRaw }] = useQueryStates({activeItem: parseAsString,activeTab: parseAsString,@@ -80,21 +86,14 @@ export function useSidebarRunsList({},});- const presetsQuery = useGetV2ListPresets(- { graph_id: graphId, page: 1, page_size: 100 },- {- query: {- enabled: !!graphId,- select: (r) => okData(r)?.presets,- },- },- );+ const presetsQuery = useAgentPresetsQuery(graphId || undefined);const triggerAgentsEnabled = useGetFlag(Flag.GENERIC_TRIGGER_AGENTS);const triggerAgentsQuery = useGetV2ListTriggerAgents(libraryAgentID, {query: {enabled: triggerAgentsEnabled && !!libraryAgentID,select: okData,+ retry: retryUnlessClientError,},});@@ -104,13 +103,16 @@ export function useSidebarRunsList({);const schedules = schedulesQuery.data || [];- const allPresets = presetsQuery.data || [];+ const allPresets = useMemo(+ () => presetsQuery.data?.presets ?? [],+ [presetsQuery.data],+ );const triggers = useMemo(- () => allPresets.filter((preset) => preset.webhook_id),+ () => allPresets.filter(isWebhookPreset),[allPresets],);const templates = useMemo(- () => allPresets.filter((preset) => !preset.webhook_id),+ () => allPresets.filter((preset) => !isWebhookPreset(preset)),[allPresets],);const triggerAgents = triggerAgentsEnabled@@ -190,9 +192,15 @@ export function useSidebarRunsList({useEffect(() => {if (tabValue !== "triggers" || activeItem) return;if (triggers.length > 0) {- onSelectRun(triggers[0].id, "triggers");+ onSelectRun(+ activeItemParamFor("webhook-trigger", triggers[0].id),+ "triggers",+ );} else if (triggerAgents.length > 0) {- onSelectRun(triggerAgents[0].id, "triggers");+ onSelectRun(+ activeItemParamFor("trigger-agent", triggerAgents[0].id),+ "triggers",+ );}}, [triggers, triggerAgents, activeItem, tabValue, onSelectRun]);diff --git a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/helpers.tsindex 302468d5e8..0861314a35 100644--- a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/helpers.ts+++ b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/helpers.ts@@ -1 +1,105 @@+import type { LibraryAgent } from "@/app/api/__generated__/models/libraryAgent";+import type { LibraryAgentPreset } from "@/app/api/__generated__/models/libraryAgentPreset";+export const AGENT_LIBRARY_SECTION_PADDING_X = "px-4";++export type TriggerKind = "trigger-agent" | "webhook-trigger";++export type SelectedTriggerKind =+ | TriggerKind+ | "loading"+ | "error"+ | "not-found";++// Optional type-hint prefixes for `activeItem` values on the Triggers tab,+// so the right detail view can render without waiting for the item lists.+// Bare IDs (old links, other tabs) parse with a null hint and are resolved+// by list membership instead. IDs are UUIDs, so the prefixes can't collide.+const TRIGGER_KIND_PREFIX: Record<TriggerKind, string> = {+ "trigger-agent": "agent:",+ "webhook-trigger": "preset:",+};++export function parseActiveItemParam(activeItem: string | null): {+ activeItemId: string | null;+ triggerKindHint: TriggerKind | null;+} {+ const entries = Object.entries(TRIGGER_KIND_PREFIX) as [+ TriggerKind,+ string,+ ][];+ for (const [kind, prefix] of entries) {+ if (activeItem?.startsWith(prefix)) {+ return {+ activeItemId: activeItem.slice(prefix.length),+ triggerKindHint: kind,+ };+ }+ }+ return { activeItemId: activeItem, triggerKindHint: null };+}++export function activeItemParamFor(kind: TriggerKind, id: string): string {+ return `${TRIGGER_KIND_PREFIX[kind]}${id}`;+}++/** Presets with a webhook show under "Triggers"; the rest are templates. */+export function isWebhookPreset(preset: LibraryAgentPreset): boolean {+ return !!preset.webhook_id;+}++/**+ * Resolve what a selected Triggers-tab item actually is. An unknown ID must+ * never be assumed to be a preset: fetching a preset by a trigger-agent ID+ * (or a stale link) guarantees a 404 error screen. List membership is the+ * source of truth; the URL hint only short-circuits the loading state, so a+ * wrong or stale hint self-corrects once the lists load.+ */+export function deriveSelectedTriggerKind(args: {+ activeItemId: string | null;+ triggerKindHint: TriggerKind | null;+ triggerAgents: Pick<LibraryAgent, "id">[] | undefined;+ presets: LibraryAgentPreset[] | undefined;+ presetsComplete: boolean;+ listsResolved: boolean;+ anyListFailed: boolean;+}): SelectedTriggerKind | null {+ if (!args.activeItemId) return null;+ if (args.triggerAgents?.some((t) => t.id === args.activeItemId)) {+ return "trigger-agent";+ }+ if (+ args.presets?.some((p) => isWebhookPreset(p) && p.id === args.activeItemId)+ ) {+ return "webhook-trigger";+ }+ // Membership is only conclusive once both lists resolved successfully.+ if (!args.listsResolved) {+ if (args.triggerKindHint) return args.triggerKindHint;+ return args.anyListFailed ? "error" : "loading";+ }+ // If the fetched presets page is capped/incomplete, the ID could be a+ // preset beyond it — let the by-ID detail view resolve it (fails fast+ // into the not-found card if truly gone).+ if (!args.presetsComplete) return "webhook-trigger";+ return "not-found";+}++export function getErrorStatus(error: unknown): number | null {+ if (typeof error !== "object" || error === null || !("status" in error)) {+ return null;+ }+ const status = (error as { status?: unknown }).status;+ return typeof status === "number" ? status : null;+}++/** A 4xx won't heal on retry — fail fast instead of stalling ~7s in backoff. */+export function retryUnlessClientError(+ failureCount: number,+ error: unknown,+): boolean {+ const status = getErrorStatus(error);+ return (+ failureCount < 3 && !(status !== null && status >= 400 && status < 500)+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/hooks/useAgentPresetsQuery.ts b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/hooks/useAgentPresetsQuery.tsnew file mode 100644index 0000000000..75cf332464--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/hooks/useAgentPresetsQuery.ts@@ -0,0 +1,25 @@+import { useGetV2ListPresets } from "@/app/api/__generated__/endpoints/presets/presets";+import { okData } from "@/app/api/helpers";+import { retryUnlessClientError } from "../helpers";++// Single-page cap; beyond it unknown IDs fall back to a by-ID preset fetch+// (see deriveSelectedTriggerKind). Unpaginating the endpoint would remove+// this — tracked in #13633.+export const PRESETS_PAGE_SIZE = 100;++/**+ * The agent's presets (webhook triggers + templates). Shared by the sidebar+ * and the detail-pane router so both read one React Query cache entry.+ */+export function useAgentPresetsQuery(graphId: string | undefined) {+ return useGetV2ListPresets(+ { graph_id: graphId ?? "", page: 1, page_size: PRESETS_PAGE_SIZE },+ {+ query: {+ enabled: !!graphId,+ select: okData,+ retry: retryUnlessClientError,+ },+ },+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/useNewAgentLibraryView.ts b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/useNewAgentLibraryView.tsindex fd4995df68..c7046e578e 100644--- a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/useNewAgentLibraryView.ts+++ b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/useNewAgentLibraryView.ts@@ -8,10 +8,17 @@ import { GraphExecutionJobInfo } from "@/app/api/__generated__/models/graphExecuimport { GraphExecutionMeta } from "@/app/api/__generated__/models/graphExecutionMeta";import { LibraryAgentPreset } from "@/app/api/__generated__/models/libraryAgentPreset";import { okData } from "@/app/api/helpers";-import { Flag, useGetFlag } from "@/services/feature-flags/use-get-flag";+import { Flag, useFlagStatus } from "@/services/feature-flags/use-get-flag";import { useParams } from "next/navigation";import { parseAsString, useQueryStates } from "nuqs";import { useCallback, useEffect, useMemo, useState } from "react";+import {+ deriveSelectedTriggerKind,+ parseActiveItemParam,+ retryUnlessClientError,+ SelectedTriggerKind,+} from "./helpers";+import { useAgentPresetsQuery } from "./hooks/useAgentPresetsQuery";function parseTab(value: string | null,@@ -42,10 +49,24 @@ export function useNewAgentLibraryView() {error,} = useGetV2GetLibraryAgent(agentId, { query: { select: okData } });- const triggerAgentsEnabled = useGetFlag(Flag.GENERIC_TRIGGER_AGENTS);- const { data: triggerAgents } = useGetV2ListTriggerAgents(agentId, {- query: { enabled: triggerAgentsEnabled && !!agentId, select: okData },+ const { enabled: triggerAgentsEnabled, ready: triggerAgentsFlagReady } =+ useFlagStatus(Flag.GENERIC_TRIGGER_AGENTS);+ // This list is unpaginated on the backend, so membership is authoritative.+ const triggerAgentsQuery = useGetV2ListTriggerAgents(agentId, {+ query: {+ enabled: triggerAgentsEnabled && !!agentId,+ select: okData,+ retry: retryUnlessClientError,+ },});+ const triggerAgents = triggerAgentsQuery.data;++ const presetsQuery = useAgentPresetsQuery(agent?.graph_id);+ const presets = presetsQuery.data?.presets;+ const presetsComplete =+ !!presetsQuery.data &&+ presetsQuery.data.pagination.total_items <=+ presetsQuery.data.presets.length;const [{ activeItem, activeTab: activeTabRaw }, setQueryStates] =useQueryStates({@@ -54,24 +75,25 @@ export function useNewAgentLibraryView() {});const activeTab = useMemo(() => parseTab(activeTabRaw), [activeTabRaw]);+ const { activeItemId, triggerKindHint } = parseActiveItemParam(activeItem);- const {- data: _template,- isSuccess: isTemplateLoaded,- isLoading: isTemplateLoading,- error: templateError,- } = useGetV2GetASpecificPreset(activeItem ?? "", {+ const onTemplatesTab = Boolean(activeTab === "templates" && activeItemId);+ const templateQuery = useGetV2GetASpecificPreset(activeItemId ?? "", {query: {- enabled: Boolean(activeTab === "templates" && activeItem),+ enabled: onTemplatesTab,select: okData,+ retry: retryUnlessClientError,},});+ // This query shares its cache key with SelectedTriggerView's preset detail+ // fetch, so its state must stay scoped to the Templates tab — a preset 404+ // on the Triggers tab is handled inline there, not as a page-level error.const activeTemplate =- isTemplateLoaded &&- activeTab === "templates" &&- _template?.id === activeItem- ? _template+ onTemplatesTab && templateQuery.data?.id === activeItemId+ ? templateQuery.data: null;+ const isTemplateLoading = templateQuery.isLoading;+ const templateError = onTemplatesTab ? templateQuery.error : null;useEffect(() => {if (!activeTabRaw && !activeItem) {@@ -109,9 +131,13 @@ export function useNewAgentLibraryView() {}}, [agent]);+ // Leave the Triggers tab when it becomes empty — but never while an item+ // is still selected: a stale selection must keep its detail pane (showing+ // the not-found state) instead of being re-routed to Runs as a bogus run ID.useEffect(() => {if (activeTab === "triggers" &&+ !activeItemId &&sidebarCounts.triggersCount === 0 &&!sidebarLoading) {@@ -119,7 +145,13 @@ export function useNewAgentLibraryView() {activeTab: "runs",});}- }, [activeTab, sidebarCounts.triggersCount, sidebarLoading, setQueryStates]);+ }, [+ activeTab,+ activeItemId,+ sidebarCounts.triggersCount,+ sidebarLoading,+ setQueryStates,+ ]);function handleSelectRun(id: string,@@ -237,11 +269,25 @@ export function useNewAgentLibraryView() {onItemCreated({ item: newSchedule, type: "scheduled" });}- const isActiveItemTriggerAgent =- triggerAgentsEnabled &&- activeTab === "triggers" &&- !!activeItem &&- !!triggerAgents?.some((t) => t.id === activeItem);+ const triggerAgentsUnresolved =+ !triggerAgentsFlagReady ||+ (triggerAgentsEnabled && !triggerAgentsQuery.isSuccess);+ const selectedTriggerKind: SelectedTriggerKind | null =+ activeTab === "triggers"+ ? deriveSelectedTriggerKind({+ activeItemId,+ triggerKindHint,+ triggerAgents,+ presets,+ presetsComplete,+ listsResolved: presetsQuery.isSuccess && !triggerAgentsUnresolved,+ anyListFailed: presetsQuery.isError || triggerAgentsQuery.isError,+ })+ : null;+ function retryTriggerLists() {+ if (presetsQuery.isError) presetsQuery.refetch();+ if (triggerAgentsQuery.isError) triggerAgentsQuery.refetch();+ }return {agentId: id,@@ -252,8 +298,9 @@ export function useNewAgentLibraryView() {error: error || templateError,hasAnyItems,showSidebarLayout,- activeItem,- isActiveItemTriggerAgent,+ activeItemId,+ selectedTriggerKind,+ retryTriggerLists,sidebarLoading,activeTab,setActiveTab: handleSetActiveTab,