Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

fix(dashboards): show agent-created widgets immediately (#15871)

Lysander Kiesel62a9f59bcbc3
diff --git a/web/src/features/dashboard/hooks/useDashboardDefinitionDraft.clienttest.ts b/web/src/features/dashboard/hooks/useDashboardDefinitionDraft.clienttest.ts
new file mode 100644
index 0000000000..39274488cd
--- /dev/null
+++ b/web/src/features/dashboard/hooks/useDashboardDefinitionDraft.clienttest.ts
@@ -0,0 +1,90 @@
+import { act, renderHook } from "@testing-library/react";
+
+import { useDashboardDefinitionDraft } from "@/src/features/dashboard/hooks/useDashboardDefinitionDraft";
+
+const definition = (placementId: string) => ({
+ widgets: [
+ {
+ id: placementId,
+ type: "widget" as const,
+ widgetId: `widget-${placementId}`,
+ x: 0,
+ y: 0,
+ x_size: 6,
+ y_size: 6,
+ },
+ ],
+});
+
+describe("useDashboardDefinitionDraft", () => {
+ it("adopts refreshed dashboard definitions while no local edit is pending", () => {
+ const initialDefinition = definition("initial");
+ const refreshedDefinition = definition("agent-created");
+ const { result, rerender } = renderHook(
+ ({ serverDefinition }) => useDashboardDefinitionDraft(serverDefinition),
+ { initialProps: { serverDefinition: initialDefinition } },
+ );
+
+ expect(result.current.definition).toBe(initialDefinition);
+
+ rerender({ serverDefinition: refreshedDefinition });
+
+ expect(result.current.definition).toBe(refreshedDefinition);
+ });
+
+ it("preserves newer local edits until their exact save completes", () => {
+ const initialDefinition = definition("initial");
+ const firstDraft = definition("first-local-edit");
+ const newerDraft = definition("newer-local-edit");
+ const refreshedDefinition = definition("agent-created");
+ const savedDefinition = definition("saved-newer-edit");
+ const { result, rerender } = renderHook(
+ ({ serverDefinition }) => useDashboardDefinitionDraft(serverDefinition),
+ { initialProps: { serverDefinition: initialDefinition } },
+ );
+
+ act(() => result.current.applyDraft(firstDraft));
+ rerender({ serverDefinition: refreshedDefinition });
+
+ expect(result.current.definition).toBe(firstDraft);
+
+ act(() => result.current.applyDraft(newerDraft));
+ act(() => result.current.clearDraftIfSaved(firstDraft));
+
+ expect(result.current.definition).toBe(newerDraft);
+
+ rerender({ serverDefinition: savedDefinition });
+ act(() => result.current.clearDraftIfSaved(newerDraft));
+
+ expect(result.current.definition).toBe(savedDefinition);
+ });
+
+ it("rejects an older save after a newer draft has completed", () => {
+ const initialDefinition = definition("initial");
+ const olderDraft = definition("older-local-edit");
+ const newerDraft = definition("newer-local-edit");
+ const savedDefinition = definition("saved-newer-edit");
+ const { result, rerender } = renderHook(
+ ({ serverDefinition }) => useDashboardDefinitionDraft(serverDefinition),
+ { initialProps: { serverDefinition: initialDefinition } },
+ );
+
+ act(() => result.current.applyDraft(olderDraft));
+ act(() => result.current.applyDraft(newerDraft));
+
+ let acceptedNewerSave: boolean | undefined;
+ act(() => {
+ acceptedNewerSave = result.current.clearDraftIfSaved(newerDraft);
+ });
+ rerender({ serverDefinition: savedDefinition });
+
+ let acceptedOlderSave: boolean | undefined;
+ act(() => {
+ acceptedOlderSave = result.current.clearDraftIfSaved(olderDraft);
+ });
+
+ expect(acceptedNewerSave).toBe(true);
+ expect(acceptedOlderSave).toBe(false);
+ expect(result.current.definition).toBe(savedDefinition);
+ });
+});
diff --git a/web/src/features/dashboard/hooks/useDashboardDefinitionDraft.ts b/web/src/features/dashboard/hooks/useDashboardDefinitionDraft.ts
new file mode 100644
index 0000000000..c235adbd5e
--- /dev/null
+++ b/web/src/features/dashboard/hooks/useDashboardDefinitionDraft.ts
@@ -0,0 +1,38 @@
+import { useCallback, useRef, useState } from "react";
+
+import type { DashboardPlacement } from "@/src/features/widgets/components/DashboardGrid";
+
+export type DashboardDefinition = {
+ widgets: DashboardPlacement[];
+};
+
+export function useDashboardDefinitionDraft(
+ serverDefinition: DashboardDefinition | null | undefined,
+) {
+ const [draft, setDraft] = useState<DashboardDefinition | null>(null);
+ const draftRef = useRef(draft);
+ const definition = draft ?? serverDefinition ?? null;
+ const definitionRef = useRef(definition);
+ definitionRef.current = definition;
+
+ const applyDraft = useCallback((updated: DashboardDefinition) => {
+ draftRef.current = updated;
+ definitionRef.current = updated;
+ setDraft(updated);
+ }, []);
+
+ const clearDraftIfSaved = useCallback((saved: DashboardDefinition) => {
+ if (draftRef.current !== saved) return false;
+
+ draftRef.current = null;
+ setDraft(null);
+ return true;
+ }, []);
+
+ return {
+ definition,
+ definitionRef,
+ applyDraft,
+ clearDraftIfSaved,
+ };
+}
diff --git a/web/src/features/in-app-agent/components/InAppAgentExecution.clienttest.tsx b/web/src/features/in-app-agent/components/InAppAgentExecution.clienttest.tsx
index 7e4c7dd0c8..c4544e8754 100644
--- a/web/src/features/in-app-agent/components/InAppAgentExecution.clienttest.tsx
+++ b/web/src/features/in-app-agent/components/InAppAgentExecution.clienttest.tsx
@@ -333,7 +333,7 @@ describe("in-app agent execution", () => {
).toBeInTheDocument();
});
- it("replays prompt invalidations after a detached run completes", async () => {
+ it("replays prompt and dashboard invalidations after a detached run completes", async () => {
providerMocks.backgroundExecutionEnabled = true;
const completedSnapshot = {
conversation: {
@@ -383,6 +383,27 @@ describe("in-app agent execution", () => {
toolCallId: "prompt-tool-call-2",
content: '{"id":"prompt-2"}',
},
+ {
+ id: "placement-call",
+ role: "assistant",
+ content: "",
+ toolCalls: [
+ {
+ id: "placement-tool-call",
+ type: "function",
+ function: {
+ name: "langfuse_addDashboardPlacement",
+ arguments: "{}",
+ },
+ },
+ ],
+ },
+ {
+ id: "placement-result",
+ role: "tool",
+ toolCallId: "placement-tool-call",
+ content: '{"id":"placement-1"}',
+ },
],
eventCursor: 14,
latestRun: {
@@ -409,11 +430,11 @@ describe("in-app agent execution", () => {
fireEvent.click(screen.getByRole("button", { name: "Reopen assistant" }));
- // Two completed prompt tool calls must union into a single invalidation.
+ // Repeated calls union into one invalidation per affected route.
await waitFor(() => {
expect(providerMocks.utils.prompts.invalidate).toHaveBeenCalledOnce();
+ expect(providerMocks.utils.dashboard.invalidate).toHaveBeenCalledOnce();
});
- expect(providerMocks.utils.dashboard.invalidate).not.toHaveBeenCalled();
expect(
providerMocks.utils.dashboardWidgets.invalidate,
).not.toHaveBeenCalled();
diff --git a/web/src/features/mcp/features/dashboardWidgets/tools/dashboardCrud.ts b/web/src/features/mcp/features/dashboardWidgets/tools/dashboardCrud.ts
index 0caf1f64b1..5acdde42d0 100644
--- a/web/src/features/mcp/features/dashboardWidgets/tools/dashboardCrud.ts
+++ b/web/src/features/mcp/features/dashboardWidgets/tools/dashboardCrud.ts
@@ -371,9 +371,7 @@ export const [addDashboardPlacementTool, handleAddDashboardPlacement] =
"appends the tile below existing ones at the default 6x6 size. Explicit " +
"positions are not checked for overlap. After adding, call getDashboard " +
"to verify the full grid arrangement; use updateDashboardPlacement to " +
- "move or resize the new tile when needed. Returns the created placement. " +
- "If the user has the dashboard open, remind them to refresh the page to " +
- "see the new widget.",
+ "move or resize the new tile when needed. Returns the created placement.",
baseSchema: DashboardIdQuery.extend(placementCreateBaseSchema.shape),
inputSchema: DashboardIdQuery.extend(
placementCreateBaseSchema.shape,
diff --git a/web/src/pages/project/[projectId]/dashboards/[dashboardId]/index.tsx b/web/src/pages/project/[projectId]/dashboards/[dashboardId]/index.tsx
index 91bf0b94bf..431032fd5e 100644
--- a/web/src/pages/project/[projectId]/dashboards/[dashboardId]/index.tsx
+++ b/web/src/pages/project/[projectId]/dashboards/[dashboardId]/index.tsx
@@ -81,6 +81,7 @@ import { useClipboardWidgetProbe } from "@/src/features/widgets/hooks/useClipboa
import { extractTransferFiles } from "@/src/components/editor/fileDropPaste";
import { Layer } from "@/src/components/ui/layer";
import { showSuccessToast } from "@/src/features/notifications/showSuccessToast";
+import { useDashboardDefinitionDraft } from "@/src/features/dashboard/hooks/useDashboardDefinitionDraft";
// Position for a tile inserted "next to" an anchor tile: same size,
// immediately to the right when that fits the 12-column grid, otherwise
@@ -176,17 +177,17 @@ export default function DashboardDetail() {
return JSON.stringify(currentFilters) !== JSON.stringify(savedFilters);
}, [currentFilters, savedFilters]);
- // State for handling widget deletion and addition
- const [localDashboardDefinition, setLocalDashboardDefinition] = useState<{
- widgets: DashboardPlacement[];
- } | null>(null);
+ const {
+ definition: dashboardDefinition,
+ definitionRef: dashboardDefinitionRef,
+ applyDraft,
+ clearDraftIfSaved,
+ } = useDashboardDefinitionDraft(dashboard.data?.definition);
// The async flows below (paste/duplicate/import) commit a definition change
// only after a network round-trip. They must compute it from this ref — the
// definition as of NOW — not from the state captured when the handler
// started, or a drag/delete/paste that landed during the await gets
// silently discarded.
- const localDashboardDefinitionRef = useRef(localDashboardDefinition);
- localDashboardDefinitionRef.current = localDashboardDefinition;
// State for the widget selection dialog
const [isWidgetDialogOpen, setIsWidgetDialogOpen] = useState(false);
@@ -195,9 +196,16 @@ export default function DashboardDetail() {
const updateDashboardDefinition =
api.dashboard.updateDashboardDefinition.useMutation({
// Saves are silent; the header shows a spinner while in flight.
- onSuccess: () => {
- // Invalidate the dashboard query to refetch the data
- dashboard.refetch();
+ onSuccess: (updatedDashboard, variables) => {
+ if (!clearDraftIfSaved(variables.definition)) return;
+
+ utils.dashboard.getDashboard.setData(
+ {
+ projectId: variables.projectId,
+ dashboardId: variables.dashboardId,
+ },
+ updatedDashboard,
+ );
},
onError: (error) => {
showErrorToast("Error updating dashboard", error.message);
@@ -266,11 +274,10 @@ export default function DashboardDetail() {
// the debounced save.
const applyDashboardDefinition = useCallback(
(updated: { widgets: DashboardPlacement[] }) => {
- localDashboardDefinitionRef.current = updated;
- setLocalDashboardDefinition(updated);
+ applyDraft(updated);
saveDashboardChanges(updated);
},
- [saveDashboardChanges],
+ [applyDraft, saveDashboardChanges],
);
// Function to save current filters
@@ -294,7 +301,7 @@ export default function DashboardDetail() {
) => {
// Read through the ref: async callers (paste/duplicate) reach here
// after a network round-trip.
- const currentDefinition = localDashboardDefinitionRef.current;
+ const currentDefinition = dashboardDefinitionRef.current;
if (!currentDefinition) return;
// Find the maximum y position to place the new widget at the bottom
@@ -332,7 +339,7 @@ export default function DashboardDetail() {
?.scrollIntoView({ behavior: "smooth", block: "center" });
}, 150);
},
- [applyDashboardDefinition],
+ [applyDashboardDefinition, dashboardDefinitionRef],
);
const addWidgetToDashboard = useCallback(
@@ -348,7 +355,7 @@ export default function DashboardDetail() {
presetId: HomeDashboardPresetId,
position?: { x: number; y: number; x_size: number; y_size: number },
) => {
- const currentDefinition = localDashboardDefinitionRef.current;
+ const currentDefinition = dashboardDefinitionRef.current;
if (!currentDefinition) return;
const maxY =
@@ -381,7 +388,7 @@ export default function DashboardDetail() {
?.scrollIntoView({ behavior: "smooth", block: "center" });
}, 150);
},
- [applyDashboardDefinition],
+ [applyDashboardDefinition, dashboardDefinitionRef],
);
const addPresetToDashboard = useCallback(
@@ -482,7 +489,7 @@ export default function DashboardDetail() {
// Don't create a widget row the placement step couldn't attach — a
// paste firing before the dashboard definition has loaded would
// otherwise leave an orphan widget in the library.
- if (!localDashboardDefinitionRef.current) return;
+ if (!dashboardDefinitionRef.current) return;
try {
const result = await createWidgetAsync({
projectId,
@@ -513,7 +520,14 @@ export default function DashboardDetail() {
);
}
},
- [capture, createWidgetAsync, dashboardId, insertWidgetPlacement, projectId],
+ [
+ capture,
+ createWidgetAsync,
+ dashboardDefinitionRef,
+ dashboardId,
+ insertWidgetPlacement,
+ projectId,
+ ],
);
// Menu-driven paste ("Paste widget" / "Paste to the right"): read the
@@ -639,7 +653,7 @@ export default function DashboardDetail() {
// file's relative layout.
const handleDashboardImport = useCallback(
async (imported: ParsedDashboardImport) => {
- if (!localDashboardDefinitionRef.current) return;
+ if (!dashboardDefinitionRef.current) return;
try {
const widgetPlacements = imported.placements.flatMap((p) =>
p.type === "widget" ? [p] : [],
@@ -677,7 +691,7 @@ export default function DashboardDetail() {
// Re-read the definition after the awaits: a drag/delete/paste may
// have landed while the widgets were being created.
- const currentDefinition = localDashboardDefinitionRef.current;
+ const currentDefinition = dashboardDefinitionRef.current;
if (!currentDefinition) return;
const maxY =
currentDefinition.widgets.length > 0
@@ -752,6 +766,7 @@ export default function DashboardDetail() {
},
[
createWidgetAsync,
+ dashboardDefinitionRef,
deleteWidgetAsync,
projectId,
applyDashboardDefinition,
@@ -979,12 +994,6 @@ export default function DashboardDetail() {
},
);
- useEffect(() => {
- if (dashboard.data && !localDashboardDefinition) {
- setLocalDashboardDefinition(dashboard.data.definition);
- }
- }, [dashboard.data, localDashboardDefinition]);
-
// Initialize filters from dashboard data
useEffect(() => {
if (dashboard.data?.filters) {
@@ -994,9 +1003,9 @@ export default function DashboardDetail() {
}, [dashboard.data?.filters]);
useEffect(() => {
- if (localDashboardDefinition && widgetToAdd.data && addWidgetId) {
+ if (dashboardDefinition && widgetToAdd.data && addWidgetId) {
if (
- !localDashboardDefinition.widgets.some(
+ !dashboardDefinition.widgets.some(
(w) => w.type === "widget" && w.widgetId === addWidgetId,
)
) {
@@ -1012,7 +1021,7 @@ export default function DashboardDetail() {
widgetToAdd.data,
addWidgetId,
addWidgetToDashboard,
- localDashboardDefinition,
+ dashboardDefinition,
projectId,
dashboardId,
router,
@@ -1020,13 +1029,13 @@ export default function DashboardDetail() {
// Handle deleting a widget
const handleDeleteWidget = (tileId: string) => {
- if (localDashboardDefinition) {
- const updatedWidgets = localDashboardDefinition.widgets.filter(
+ if (dashboardDefinition) {
+ const updatedWidgets = dashboardDefinition.widgets.filter(
(widget) => widget.id !== tileId,
);
const updatedDefinition = {
- ...localDashboardDefinition,
+ ...dashboardDefinition,
widgets: updatedWidgets,
};
@@ -1342,7 +1351,7 @@ export default function DashboardDetail() {
setGridResetKey((key) => key + 1);
}}
/>
- {dashboard.isPending || !localDashboardDefinition ? (
+ {dashboard.isPending || !dashboardDefinition ? (
<NoDataOrLoading isLoading={true} />
) : dashboard.isError ? (
<div className="flex h-64 items-center justify-center">
@@ -1354,18 +1363,18 @@ export default function DashboardDetail() {
<div>
<DashboardGrid
key={gridResetKey}
- widgets={localDashboardDefinition.widgets}
+ widgets={dashboardDefinition.widgets}
onChange={(updatedWidgets) => {
if (isLockedEditable) {
// Carry the attempted layout change into the clone.
openCloneFirst("layout_change", {
- ...localDashboardDefinition,
+ ...dashboardDefinition,
widgets: updatedWidgets,
});
return;
}
applyDashboardDefinition({
- ...localDashboardDefinition,
+ ...dashboardDefinition,
widgets: updatedWidgets,
});
}}