🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
refactor(monitors): remove unnecessary use of useEffect (#14998)
Mark Salpeter02a1c9ccb483
diff --git a/web/src/features/monitors/components/MonitorAutomationsPanel.clienttest.ts b/web/src/features/monitors/components/MonitorAutomationsPanel.clienttest.tsdeleted file mode 100644index a0e48db639..0000000000--- a/web/src/features/monitors/components/MonitorAutomationsPanel.clienttest.ts+++ /dev/null@@ -1,52 +0,0 @@-import { describe, expect, it } from "vitest";--import { __test } from "./MonitorAutomationsPanel";--const { computeSelectedSet, toggle } = __test;--describe("computeSelectedSet", () => {- it("pre-checks rows whose trigger.id is in triggerIds", () => {- const liveIds = ["t1", "t2", "t3"];- const selected = computeSelectedSet(["t1", "t3"], liveIds);- expect(selected.has("t1")).toBe(true);- expect(selected.has("t2")).toBe(false);- expect(selected.has("t3")).toBe(true);- });-- it("drops stale IDs that are no longer in liveTriggerIds", () => {- const liveIds = ["t1", "t2"];- const selected = computeSelectedSet(["t1", "t99-stale"], liveIds);- expect(selected.has("t1")).toBe(true);- expect(selected.has("t99-stale")).toBe(false);- expect(selected.size).toBe(1);- });-});--describe("toggle", () => {- it("toggle-on appends the id to the selected set and returns the new array", () => {- const liveIds = ["t1", "t2", "t3"];- const current = ["t1"];- const next = toggle("t2", current, liveIds);- expect(next).toContain("t1");- expect(next).toContain("t2");- expect(next).not.toContain("t3");- });-- it("toggle-off removes the id from the selected set and returns the new array", () => {- const liveIds = ["t1", "t2", "t3"];- const current = ["t1", "t2"];- const next = toggle("t2", current, liveIds);- expect(next).toContain("t1");- expect(next).not.toContain("t2");- });-- it("stale IDs are dropped during a toggle-on (lazy cleanup)", () => {- const liveIds = ["t1", "t2"];- // t99 is stale — not in liveIds; t2 is being toggled on- const current = ["t1", "t99-stale"];- const next = toggle("t2", current, liveIds);- expect(next).toContain("t1");- expect(next).toContain("t2");- expect(next).not.toContain("t99-stale");- });-});diff --git a/web/src/features/monitors/components/MonitorAutomationsPanel.prune.clienttest.tsx b/web/src/features/monitors/components/MonitorAutomationsPanel.prune.clienttest.tsxindex 985c36cff8..74a88a3dc4 100644--- a/web/src/features/monitors/components/MonitorAutomationsPanel.prune.clienttest.tsx+++ b/web/src/features/monitors/components/MonitorAutomationsPanel.prune.clienttest.tsx@@ -1,4 +1,4 @@-import { render } from "@testing-library/react";+import { fireEvent, render, screen } from "@testing-library/react";const automationRow = {id: "auto-1",@@ -25,9 +25,9 @@ vi.mock("next/router", () => ({import { MonitorAutomationsPanel } from "./MonitorAutomationsPanel";-describe("MonitorAutomationsPanel auto-prune", () => {- it("does not prune while the query is loading", () => {- useQueryMock.mockReturnValue({ data: undefined, isSuccess: false });+describe("MonitorAutomationsPanel stale-id pruning", () => {+ it("does not write back while the query is loading", () => {+ useQueryMock.mockReturnValue({ data: undefined, isPending: true });const onTriggerIdsChange = vi.fn();render(<MonitorAutomationsPanel@@ -39,8 +39,8 @@ describe("MonitorAutomationsPanel auto-prune", () => {expect(onTriggerIdsChange).not.toHaveBeenCalled();});- it("prunes a stale ID once loaded, calling onChange once with the pruned array", () => {- useQueryMock.mockReturnValue({ data: [automationRow], isSuccess: true });+ it("hides a stale ID on load without writing back", () => {+ useQueryMock.mockReturnValue({ data: [automationRow], isPending: false });const onTriggerIdsChange = vi.fn();render(<MonitorAutomationsPanel@@ -49,20 +49,21 @@ describe("MonitorAutomationsPanel auto-prune", () => {onTriggerIdsChange={onTriggerIdsChange}/>,);- expect(onTriggerIdsChange).toHaveBeenCalledTimes(1);- expect(onTriggerIdsChange).toHaveBeenCalledWith(["trig-1"]);+ expect(onTriggerIdsChange).not.toHaveBeenCalled();});- it("does not write back when the selection already matches the live set", () => {- useQueryMock.mockReturnValue({ data: [automationRow], isSuccess: true });+ it("drops the stale ID when the user toggles a row", () => {+ useQueryMock.mockReturnValue({ data: [automationRow], isPending: false });const onTriggerIdsChange = vi.fn();render(<MonitorAutomationsPanelprojectId="p1"- triggerIds={["trig-1"]}+ triggerIds={["trig-1", "trig-stale"]}onTriggerIdsChange={onTriggerIdsChange}/>,);- expect(onTriggerIdsChange).not.toHaveBeenCalled();+ fireEvent.click(screen.getByRole("button", { name: /ping webhook/i }));+ expect(onTriggerIdsChange).toHaveBeenCalledTimes(1);+ expect(onTriggerIdsChange).toHaveBeenCalledWith([]);});});diff --git a/web/src/features/monitors/components/MonitorAutomationsPanel.toggle.clienttest.tsx b/web/src/features/monitors/components/MonitorAutomationsPanel.toggle.clienttest.tsxnew file mode 100644index 0000000000..b3f1c63545--- /dev/null+++ b/web/src/features/monitors/components/MonitorAutomationsPanel.toggle.clienttest.tsx@@ -0,0 +1,45 @@+import { fireEvent, render, screen } from "@testing-library/react";++const automationRow = {+ id: "auto-1",+ name: "Ping webhook",+ trigger: { id: "trig-1" },+ action: { type: "WEBHOOK" },+};++const useQueryMock = vi.fn();++vi.mock("@/src/utils/api", () => ({+ api: {+ automations: {+ getAutomations: {+ useQuery: () => useQueryMock(),+ },+ },+ },+}));++vi.mock("next/router", () => ({+ useRouter: () => ({ asPath: "/", push: vi.fn() }),+}));++import { MonitorAutomationsPanel } from "./MonitorAutomationsPanel";++describe("MonitorAutomationsPanel toggle immutability", () => {+ it("does not mutate the memoized set: toggling the same unselected row twice reports it selected both times", () => {+ useQueryMock.mockReturnValue({ data: [automationRow], isPending: false });+ const onTriggerIdsChange = vi.fn();+ render(+ <MonitorAutomationsPanel+ projectId="p1"+ triggerIds={[]}+ onTriggerIdsChange={onTriggerIdsChange}+ />,+ );+ const row = screen.getByRole("button", { name: /ping webhook/i });+ fireEvent.click(row);+ fireEvent.click(row);+ expect(onTriggerIdsChange).toHaveBeenNthCalledWith(1, ["trig-1"]);+ expect(onTriggerIdsChange).toHaveBeenNthCalledWith(2, ["trig-1"]);+ });+});diff --git a/web/src/features/monitors/components/MonitorAutomationsPanel.tsx b/web/src/features/monitors/components/MonitorAutomationsPanel.tsxindex 1f46332e56..1784596c7c 100644--- a/web/src/features/monitors/components/MonitorAutomationsPanel.tsx+++ b/web/src/features/monitors/components/MonitorAutomationsPanel.tsx@@ -1,12 +1,12 @@-import { useEffect, useMemo } from "react";+import { type ReactNode, useMemo, useCallback } from "react";import Link from "next/link";import { useRouter } from "next/router";import {Check,- Webhook as WebhookIcon,Github,Plus,Slack,+ Webhook as WebhookIcon,} from "lucide-react";import { api } from "@/src/utils/api";@@ -18,13 +18,14 @@ import {DropdownMenuItem,DropdownMenuTrigger,} from "@/src/components/ui/dropdown-menu";+import { automationCreateHref } from "@/src/features/automations/components/automationForm";+import { cn } from "@/src/utils/tailwind";import {ActionTypeSchema,type ActionTypes,+ type AutomationDomain,TriggerEventSource,} from "@langfuse/shared";-import { automationCreateHref } from "@/src/features/automations/components/automationForm";-import { cn } from "@/src/utils/tailwind";/** actionLabel maps each automation action type to its display name. */const actionLabel: Record<ActionTypes, string> = {@@ -45,7 +46,7 @@ export const MonitorAutomationsPanel = ({onTriggerIdsChange: (next: string[]) => void;hasAccess?: boolean;}) => {- const automations = api.automations.getAutomations.useQuery(+ const { data, isPending } = api.automations.getAutomations.useQuery({projectId,eventSource: TriggerEventSource.Monitor,@@ -56,104 +57,174 @@ export const MonitorAutomationsPanel = ({},);- /** liveTriggerIds is the set of trigger IDs that exist in the current project. */- const liveTriggerIds = useMemo(- () => (automations.data ?? []).map((a) => a.trigger.id),- [automations.data],- );+ if (isPending || !data || data?.length == 0)+ return (+ <SetupMonitorAutomationsCard+ projectId={projectId}+ isDisabled={!hasAccess}+ />+ );- /** selectedSet is the intersection of triggerIds with liveTriggerIds — stale IDs fall out automatically. */- const selectedSet = useMemo(- () => computeSelectedSet(triggerIds, liveTriggerIds),- [triggerIds, liveTriggerIds],+ return (+ <MonitorAutomationsListCard+ projectId={projectId}+ isDisabled={!hasAccess}+ automations={data}+ selectedTriggerIds={triggerIds}+ onSelectedTriggerIdsChange={onTriggerIdsChange}+ />);+};- // Write the pruned selection back once the live set is known; gating on- // isSuccess avoids wiping a real selection while liveIds is still [].- useEffect(() => {- if (!automations.isSuccess) return;- const pruned = Array.from(selectedSet);- if (pruned.length !== triggerIds.length) onTriggerIdsChange(pruned);- }, [automations.isSuccess, selectedSet, triggerIds, onTriggerIdsChange]);+/** SetupMonitorAutomationsCard is the empty state prompting creation of the first automation. */+const SetupMonitorAutomationsCard = ({+ isDisabled,+ projectId,+}: {+ isDisabled: boolean;+ projectId: string;+}) => (+ <MonitorAutomationsCard>+ <p className="text-muted-foreground px-4 py-6 text-center text-base">+ Set up Slack, Webhook, and Github Action Automations to Receive Alerts+ </p>+ <AddAutomationDropdown+ projectId={projectId}+ fullWidth+ isDisabled={isDisabled}+ />+ </MonitorAutomationsCard>+);++/** MonitorAutomationsListCard renders the selectable automations and reports the selected trigger IDs. */+const MonitorAutomationsListCard = ({+ projectId,+ isDisabled,+ automations,+ selectedTriggerIds,+ onSelectedTriggerIdsChange,+}: {+ projectId: string;+ isDisabled: boolean;+ automations: AutomationDomain[];+ selectedTriggerIds: string[];+ onSelectedTriggerIdsChange: (selectedTriggerIds: string[]) => void;+}) => {+ const activeTriggerIds = useMemo(+ () => new Set(automations.map((a) => a.trigger.id)),+ [automations],+ );- /** handleToggle flips membership for a trigger ID and calls onTriggerIdsChange with the new array. */- const handleToggle = (triggerId: string) => {- if (!hasAccess) return;- onTriggerIdsChange(toggle(triggerId, triggerIds, liveTriggerIds));- };+ // drop selected ids whose automation no longer exists on the server+ const activeSelectedTriggerIds = useMemo(+ () => new Set(selectedTriggerIds.filter((id) => activeTriggerIds.has(id))),+ [selectedTriggerIds, activeTriggerIds],+ );- // Only show the empty splash after the query has actually resolved with no- // rows; otherwise loading or errored requests would flash the splash and- // make linked automations look like they have vanished.- const showEmptyState = automations.isSuccess && automations.data.length === 0;+ const toggleSelectedTriggerId = useCallback(+ (triggerId: string) => {+ const next = new Set(activeSelectedTriggerIds);+ if (next.has(triggerId)) {+ next.delete(triggerId);+ } else {+ next.add(triggerId);+ }+ onSelectedTriggerIdsChange(Array.from(next));+ },+ [onSelectedTriggerIdsChange, activeSelectedTriggerIds],+ );return (- <div className="space-y-3">- <Card>- <CardContent className="space-y-3 pt-4">- {showEmptyState ? (- <>- <p className="text-muted-foreground px-4 py-6 text-center text-base">- Set up Slack, Webhook, and Github Action Automations to Receive- Alerts- </p>- <AddAutomationDropdown- projectId={projectId}- fullWidth- hasAccess={hasAccess}- />- </>- ) : (- <>- <ul className="space-y-1">- {(automations.data ?? []).map((automation) => {- const checked = selectedSet.has(automation.trigger.id);- const handleClick = () => handleToggle(automation.trigger.id);- return (- <li key={automation.id}>- <div- role="button"- tabIndex={hasAccess ? 0 : -1}- aria-pressed={checked}- aria-disabled={!hasAccess}- onClick={handleClick}- onKeyDown={(e) => {- if (e.key === "Enter" || e.key === " ") {- e.preventDefault();- handleClick();- }- }}- className={cn(- "hover:bg-muted/60 focus-visible:ring-ring flex cursor-pointer items-center gap-2 rounded-md border p-2 text-xs outline-hidden transition-colors focus-visible:ring-2",- !hasAccess && "pointer-events-none opacity-50",- )}- >- <RowCheckbox checked={checked} />- <ActionIcon- type={automation.action.type as ActionTypes}- className="h-3.5 w-3.5 shrink-0"- />- <span className="truncate" title={automation.name}>- {automation.name}- </span>- </div>- </li>- );- })}- </ul>- <AddAutomationDropdown- projectId={projectId}- fullWidth- hasAccess={hasAccess}- />- </>- )}- </CardContent>- </Card>- </div>+ <MonitorAutomationsCard>+ <MonitorAutomationsList+ automations={automations}+ isDisabled={isDisabled}+ selectedTriggerIds={activeSelectedTriggerIds}+ onClick={toggleSelectedTriggerId}+ />+ <AddAutomationDropdown+ projectId={projectId}+ fullWidth+ isDisabled={isDisabled}+ />+ </MonitorAutomationsCard>);};+/** MonitorAutomationsCard is the shared card shell for the panel's contents. */+const MonitorAutomationsCard = ({ children }: { children: ReactNode }) => (+ <div className="space-y-3">+ <Card>+ <CardContent className="space-y-3 pt-4">{children}</CardContent>+ </Card>+ </div>+);++/** MonitorAutomationsList renders one selectable row per automation. */+const MonitorAutomationsList = ({+ automations,+ isDisabled,+ selectedTriggerIds,+ onClick,+}: {+ automations: AutomationDomain[];+ isDisabled: boolean;+ selectedTriggerIds: Set<string>;+ onClick: (triggerId: string) => void;+}) => (+ <ul className="space-y-1">+ {automations.map((automation) => (+ <MonitorAutomationsListRow+ key={automation.id}+ automation={automation}+ isSelected={selectedTriggerIds.has(automation.trigger.id)}+ isDisabled={isDisabled}+ onClick={() => onClick(automation.trigger.id)}+ />+ ))}+ </ul>+);++/** MonitorAutomationsListRow is a selectable row toggling one automation's trigger. */+const MonitorAutomationsListRow = ({+ automation,+ isSelected,+ isDisabled,+ onClick,+}: {+ automation: AutomationDomain;+ isSelected: boolean;+ isDisabled: boolean;+ onClick: () => void;+}) => (+ <li+ role="button"+ tabIndex={isDisabled ? -1 : 0}+ aria-pressed={isSelected}+ aria-disabled={isDisabled}+ onClick={isDisabled ? undefined : onClick}+ onKeyDown={(e) => {+ if (e.key === "Enter" || e.key === " ") {+ e.preventDefault();+ if (!isDisabled) onClick();+ }+ }}+ className={cn(+ "hover:bg-muted/60 focus-visible:ring-ring flex cursor-pointer items-center gap-2 rounded-md border p-2 text-xs outline-hidden transition-colors focus-visible:ring-2",+ isDisabled && "pointer-events-none opacity-50",+ )}+ >+ <RowCheckbox checked={isSelected} />+ <ActionIcon+ type={automation.action.type as ActionTypes}+ className="h-3.5 w-3.5 shrink-0"+ />+ <span className="truncate" title={automation.name}>+ {automation.name}+ </span>+ </li>+);+/** RowCheckbox is a non-interactive visual stand-in for a checkbox. */const RowCheckbox = ({ checked }: { checked: boolean }) => (<span@@ -167,35 +238,15 @@ const RowCheckbox = ({ checked }: { checked: boolean }) => (</span>);-/** ActionIcon renders the lucide icon for a given automation action type. */-const ActionIcon = ({- type,- className,-}: {- type: ActionTypes;- className?: string;-}) => {- switch (type) {- case "WEBHOOK":- return <WebhookIcon className={className} />;- case "SLACK":- // eslint-disable-next-line @typescript-eslint/no-deprecated -- see import note.- return <Slack className={className} />;- case "GITHUB_DISPATCH":- // eslint-disable-next-line @typescript-eslint/no-deprecated -- see import note.- return <Github className={className} />;- }-};--/** AddAutomationDropdown renders the "+ Automation" CTA used in both the empty state and the populated-list footer. Threads the current route through `redirectUrl` so the create-automation flow returns the user here on save. */+/** AddAutomationDropdown renders the "+ Automation" CTA for the empty state and the list footer. */const AddAutomationDropdown = ({projectId,fullWidth,- hasAccess = true,+ isDisabled,}: {projectId: string;fullWidth?: boolean;- hasAccess?: boolean;+ isDisabled?: boolean;}) => {const router = useRouter();return (@@ -204,7 +255,7 @@ const AddAutomationDropdown = ({<Buttonvariant="outline"size="lg"- disabled={!hasAccess}+ disabled={isDisabled}className={fullWidth ? "w-full" : undefined}><Plus className="mr-2 h-4 w-4" />@@ -233,32 +284,22 @@ const AddAutomationDropdown = ({);};-/** computeSelectedSet returns the intersection of triggerIds with liveTriggerIds, dropping stale IDs. */-const computeSelectedSet = (- triggerIds: string[],- liveTriggerIds: string[],-): Set<string> => {- const liveSet = new Set(liveTriggerIds);- return new Set(triggerIds.filter((id) => liveSet.has(id)));-};--/** toggle flips membership of triggerId in the current selection (after dropping stale IDs) and returns the new array. */-const toggle = (- triggerId: string,- currentTriggerIds: string[],- liveTriggerIds: string[],-): string[] => {- const next = computeSelectedSet(currentTriggerIds, liveTriggerIds);- if (next.has(triggerId)) {- next.delete(triggerId);- } else {- next.add(triggerId);+/** ActionIcon renders the lucide icon for a given automation action type. */+const ActionIcon = ({+ type,+ className,+}: {+ type: ActionTypes;+ className?: string;+}) => {+ switch (type) {+ case "WEBHOOK":+ return <WebhookIcon className={className} />;+ case "SLACK":+ // eslint-disable-next-line @typescript-eslint/no-deprecated -- see import note.+ return <Slack className={className} />;+ case "GITHUB_DISPATCH":+ // eslint-disable-next-line @typescript-eslint/no-deprecated -- see import note.+ return <Github className={className} />;}- return Array.from(next);-};--/** __test exposes private helpers to co-located tests without widening the module API. */-export const __test = {- computeSelectedSet,- toggle,};diff --git a/web/src/features/monitors/components/MonitorForm.tsx b/web/src/features/monitors/components/MonitorForm.tsxindex 41d9227db9..fc9ac48593 100644--- a/web/src/features/monitors/components/MonitorForm.tsx+++ b/web/src/features/monitors/components/MonitorForm.tsx@@ -1,4 +1,4 @@-import React, { useEffect, useMemo, useRef } from "react";+import React, { useMemo, useRef } from "react";import { useRouter } from "next/router";import { type LucideIcon, Plus } from "lucide-react";import { useForm, useWatch } from "react-hook-form";@@ -328,12 +328,6 @@ export const MonitorForm = ({[monitorWindow],);- // Push the live name up to the host (e.g. the edit page header) so the page- // title can mirror it as the user types instead of waiting for save.- useEffect(() => {- onNameChange?.(watched.name ?? "");- }, [watched.name, onNameChange]);-/** eventsFilterOptions loads the events v2 filter dictionary (environments, tags, models, …) for the picked view. */const eventsFilterOptions = api.events.filterOptions.useQuery({@@ -849,6 +843,10 @@ export const MonitorForm = ({disabled={!hasAccess}{...field}value={field.value ?? ""}+ onChange={(e) => {+ field.onChange(e);+ onNameChange?.(e.target.value ?? "");+ }}/></FormControl><FormMessage />diff --git a/web/src/features/monitors/components/MonitorsTable.tsx b/web/src/features/monitors/components/MonitorsTable.tsxindex b241d4b063..f0034f5de4 100644--- a/web/src/features/monitors/components/MonitorsTable.tsx+++ b/web/src/features/monitors/components/MonitorsTable.tsx@@ -1,7 +1,7 @@import { MoreVertical, PauseCircle, PlayCircle, SquarePen } from "lucide-react";import Link from "next/link";import { useRouter } from "next/router";-import { useEffect, useMemo } from "react";+import { useMemo } from "react";import { useMediaQuery } from "react-responsive";import { DeleteMonitorButton } from "@/src/components/deleteButton";@@ -19,7 +19,6 @@ import {} from "@/src/components/ui/dropdown-menu";import { monitorFilterConfig } from "@/src/features/filters/config/monitors-config";import { useSidebarFilterState } from "@/src/features/filters/hooks/useSidebarFilterState";-import { useDetailPageLists } from "@/src/features/navigate-detail-pages/context";import { showErrorToast } from "@/src/features/notifications/showErrorToast";import { showSuccessToast } from "@/src/features/notifications/showSuccessToast";import { useOrderByState } from "@/src/features/orderBy/hooks/useOrderByState";@@ -57,7 +56,6 @@ type MonitorsOrderBy = RouterInputs["monitors"]["all"]["orderBy"];export function MonitorsTable() {const router = useRouter();const projectId = useProjectIdFromURL() ?? "";- const { setDetailPageList } = useDetailPageLists();const utils = api.useUtils();/** hasCUDAccess gates the edit, pause/resume, and delete row actions behind the monitors:CUD RBAC scope. */const hasCUDAccess = useHasProjectAccess({@@ -158,16 +156,6 @@ export function MonitorsTable() {},);- useEffect(() => {- if (monitors.isSuccess) {- setDetailPageList(- "monitors",- monitors.data.monitors.map((m) => ({ id: m.id })),- );- }- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [monitors.isSuccess, monitors.data]);-/** columns is the DataTable column schema, conditionally including Tags on viewports wider than a phone. */const columns: LangfuseColumnDef<MonitorRow>[] = [{diff --git a/web/src/features/monitors/pages/EditMonitorPage.tsx b/web/src/features/monitors/pages/EditMonitorPage.tsxindex 2f18bde894..7cdab2a1e2 100644--- a/web/src/features/monitors/pages/EditMonitorPage.tsx+++ b/web/src/features/monitors/pages/EditMonitorPage.tsx@@ -1,23 +1,24 @@import { useRouter } from "next/router";-import { useEffect, useState } from "react";+import { useState } from "react";import { ErrorPage } from "@/src/components/error-page";import Page from "@/src/components/layouts/page";import { MonitorForm } from "@/src/features/monitors/components/MonitorForm";import { MonitorPagePermissions } from "@/src/features/monitors/components/MonitorPagePermissions";-import { api } from "@/src/utils/api";+import { api, type APIError } from "@/src/utils/api";+import { type Monitor } from "@langfuse/shared/monitors";/** EditMonitorPage gates the edit-monitor route and defers all data fetching to EditMonitorPageContent so blocked users never trigger the monitor query. */export default function EditMonitorPage() {return (<MonitorPagePermissions scope="monitors:read">- <EditMonitorPageContent />+ <EditMonitorPageRouter /></MonitorPagePermissions>);}-/** EditMonitorPageContent renders the edit form for a single monitor; runs only when the route gate has admitted the user. */-function EditMonitorPageContent() {+/** EditMonitorPageRouter fetches data and renders loading, error and editor pages based on the state of the query */+function EditMonitorPageRouter() {const router = useRouter();const projectId = router.query.projectId as string;const monitorId = router.query.monitorId as string;@@ -27,13 +28,35 @@ function EditMonitorPageContent() {{ enabled: Boolean(monitorId) },);- /** liveName mirrors the form's name so the page title updates as the user edits, without waiting for a save round-trip. */- const [liveName, setLiveName] = useState("");- useEffect(() => {- setLiveName(data?.name ?? "");- }, [data?.name]);+ if (isPending) {+ return <EditMonitorLoadingPage projectId={projectId} />;+ }++ if (error) {+ return <GetMonitorErrorPage error={error} />;+ }++ return <EditMonitorFormPage monitor={data} />;+}++/** EditMonitorFormPage renders the edit monitors form */+const EditMonitorFormPage = ({ monitor }: { monitor: Monitor }) => {+ const [liveName, setLiveName] = useState(monitor.name);- if (error?.data?.code === "NOT_FOUND") {+ return (+ <Page withPadding headerProps={getHeaderProps(monitor.projectId, liveName)}>+ <MonitorForm+ projectId={monitor.projectId}+ monitor={monitor}+ onNameChange={setLiveName}+ />+ </Page>+ );+};++/** GetMonitorErrorPage renders the error message returned by the api.monitors.get method */+const GetMonitorErrorPage = ({ error }: { error: APIError }) => {+ if (error?.data?.code == "NOT_FOUND") {return (<ErrorPagetitle="Monitor not found"@@ -43,22 +66,19 @@ function EditMonitorPageContent() {}return (- <Page- withPadding- headerProps={{- title: liveName ? `Edit Monitor - ${liveName}` : "Edit Monitor",- breadcrumb: [- { name: "Monitors", href: `/project/${projectId}/monitors` },- ],- }}- >- {isPending ? null : data ? (- <MonitorForm- projectId={projectId}- monitor={data}- onNameChange={setLiveName}- />- ) : null}- </Page>+ <ErrorPage title="Monitor could not be edited" message={error.message} />);-}+};++/** EditMonitorLoadingPage renders a loading page while the monitor is loading */+const EditMonitorLoadingPage = ({ projectId }: { projectId: string }) => (+ <Page withPadding headerProps={getHeaderProps(projectId)}>+ <></>+ </Page>+);++/** getHeaderProps returns the page header properties for the EditMonitors page */+const getHeaderProps = (projectId: string, monitorName?: string) => ({+ title: `Edit Monitor${monitorName ? " - " + monitorName : ""}`,+ breadcrumb: [{ name: "Monitors", href: `/project/${projectId}/monitors` }],+});diff --git a/web/src/utils/api.ts b/web/src/utils/api.tsindex ead64f16af..62f7201148 100644--- a/web/src/utils/api.ts+++ b/web/src/utils/api.ts@@ -13,6 +13,7 @@ import {loggerLink,splitLink,TRPCClientError,+ type TRPCClientErrorLike,type Operation,type TRPCLink,} from "@trpc/client";@@ -289,6 +290,9 @@ const shouldSilenceError = (return false;};+/** APIError is returned by api.*.*.useQuery */+export type APIError = TRPCClientErrorLike<AppRouter>;+/** A set of type-safe react-query hooks for your tRPC API. */export const api = createTRPCNext<AppRouter>({config() {