Skip to content

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

feat(frontend): read-only Builder for non-owned graphs (#13238)

Krzysztof Czerwinskifc7239f155d0
diff --git a/autogpt_platform/frontend/src/app/(platform)/build/__tests__/useCopyPaste.test.ts b/autogpt_platform/frontend/src/app/(platform)/build/__tests__/useCopyPaste.test.ts
index d1e5883844..6d835d07c6 100644
--- a/autogpt_platform/frontend/src/app/(platform)/build/__tests__/useCopyPaste.test.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/build/__tests__/useCopyPaste.test.ts
@@ -516,6 +516,40 @@ describe("useCopyPaste", () => {
});
});
+ describe("read-only graph", () => {
+ it("ignores Ctrl+C when the graph is read-only", async () => {
+ const node = createTestNode("1", { selected: true });
+ useNodeStore.setState({ nodes: [node] });
+
+ const { result } = renderHook(() => useCopyPaste(true));
+
+ act(() => {
+ result.current(makeCopyEvent());
+ });
+
+ expect(mockWriteText).not.toHaveBeenCalled();
+ });
+
+ it("ignores Ctrl+V when the graph is read-only", async () => {
+ mockReadText.mockResolvedValue(
+ clipboardPayload(
+ [createTestNode("a", { position: { x: 0, y: 0 } })],
+ [],
+ ),
+ );
+ useNodeStore.setState({ nodes: [], nodeCounter: 0 });
+
+ const { result } = renderHook(() => useCopyPaste(true));
+
+ act(() => {
+ result.current(makePasteEvent());
+ });
+
+ expect(mockReadText).not.toHaveBeenCalled();
+ expect(useNodeStore.getState().nodes).toHaveLength(0);
+ });
+ });
+
describe("meta key support (macOS)", () => {
it("handles Cmd+C (metaKey) the same as Ctrl+C", async () => {
const node = createTestNode("1", { selected: true });
diff --git a/autogpt_platform/frontend/src/app/(platform)/build/__tests__/useDuplicateGraph.test.tsx b/autogpt_platform/frontend/src/app/(platform)/build/__tests__/useDuplicateGraph.test.tsx
new file mode 100644
index 0000000000..49ec879221
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/build/__tests__/useDuplicateGraph.test.tsx
@@ -0,0 +1,148 @@
+import { act, renderHook, waitFor } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const mockPush = vi.fn();
+vi.mock("next/navigation", () => ({
+ useRouter: () => ({ push: mockPush }),
+}));
+
+const mockToast = vi.fn();
+vi.mock("@/components/molecules/Toast/use-toast", () => ({
+ useToast: () => ({ toast: mockToast }),
+}));
+
+vi.mock("nuqs", () => ({
+ parseAsString: {},
+ useQueryStates: vi.fn(() => [{ flowID: "graph-1" }, vi.fn()]),
+}));
+
+let mockLibraryAgent: { id: string; graph_id: string } | undefined;
+let mockIsLoading = false;
+const mockForkAgent = vi.fn();
+vi.mock("@/app/api/__generated__/endpoints/library/library", () => ({
+ useGetV2GetLibraryAgentByGraphId: vi.fn(() => ({
+ data: mockLibraryAgent,
+ isLoading: mockIsLoading,
+ })),
+ usePostV2ForkLibraryAgent: vi.fn(() => ({
+ mutateAsync: mockForkAgent,
+ isPending: false,
+ })),
+}));
+
+import { useDuplicateGraph } from "../hooks/useDuplicateGraph";
+
+describe("useDuplicateGraph", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockLibraryAgent = undefined;
+ mockIsLoading = false;
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it("cannot duplicate when there is no library agent for the graph", () => {
+ mockLibraryAgent = undefined;
+
+ const { result } = renderHook(() => useDuplicateGraph());
+
+ expect(result.current.canDuplicate).toBe(false);
+ });
+
+ it("reports the library lookup as in flight while loading", () => {
+ mockLibraryAgent = undefined;
+ mockIsLoading = true;
+
+ const { result } = renderHook(() => useDuplicateGraph());
+
+ expect(result.current.isCheckingLibrary).toBe(true);
+ expect(result.current.canDuplicate).toBe(false);
+ });
+
+ it("duplicates via fork and navigates to the new graph", async () => {
+ mockLibraryAgent = { id: "lib-1", graph_id: "graph-1" };
+ mockForkAgent.mockResolvedValue({
+ status: 200,
+ data: { id: "lib-2", graph_id: "graph-2" },
+ });
+
+ const { result } = renderHook(() => useDuplicateGraph());
+
+ expect(result.current.canDuplicate).toBe(true);
+
+ await act(async () => {
+ await result.current.duplicate();
+ });
+
+ expect(mockForkAgent).toHaveBeenCalledWith({ libraryAgentId: "lib-1" });
+ await waitFor(() => {
+ expect(mockPush).toHaveBeenCalledWith("/build?flowID=graph-2");
+ });
+ });
+
+ it("does nothing when there is no library agent to fork", async () => {
+ mockLibraryAgent = undefined;
+
+ const { result } = renderHook(() => useDuplicateGraph());
+
+ await act(async () => {
+ await result.current.duplicate();
+ });
+
+ expect(mockForkAgent).not.toHaveBeenCalled();
+ expect(mockPush).not.toHaveBeenCalled();
+ });
+
+ it("shows a toast and does not navigate when the fork returns no graph", async () => {
+ mockLibraryAgent = { id: "lib-1", graph_id: "graph-1" };
+ mockForkAgent.mockResolvedValue({ status: 200, data: { id: "lib-2" } });
+
+ const { result } = renderHook(() => useDuplicateGraph());
+
+ await act(async () => {
+ await result.current.duplicate();
+ });
+
+ expect(mockPush).not.toHaveBeenCalled();
+ expect(mockToast).toHaveBeenCalledWith(
+ expect.objectContaining({ variant: "destructive" }),
+ );
+ });
+
+ it("shows a toast and does not navigate when duplicate fails", async () => {
+ mockLibraryAgent = { id: "lib-1", graph_id: "graph-1" };
+ mockForkAgent.mockRejectedValue(new Error("boom"));
+
+ const { result } = renderHook(() => useDuplicateGraph());
+
+ await act(async () => {
+ await result.current.duplicate();
+ });
+
+ expect(mockPush).not.toHaveBeenCalled();
+ expect(mockToast).toHaveBeenCalledWith(
+ expect.objectContaining({ variant: "destructive" }),
+ );
+ });
+
+ it("falls back to a generic message for non-Error exceptions", async () => {
+ mockLibraryAgent = { id: "lib-1", graph_id: "graph-1" };
+ mockForkAgent.mockRejectedValue("string error");
+
+ const { result } = renderHook(() => useDuplicateGraph());
+
+ await act(async () => {
+ await result.current.duplicate();
+ });
+
+ expect(mockPush).not.toHaveBeenCalled();
+ expect(mockToast).toHaveBeenCalledWith(
+ expect.objectContaining({
+ variant: "destructive",
+ description: "An unexpected error occurred.",
+ }),
+ );
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/build/__tests__/useFlow.test.ts b/autogpt_platform/frontend/src/app/(platform)/build/__tests__/useFlow.test.ts
index 4b02bef42c..194b090572 100644
--- a/autogpt_platform/frontend/src/app/(platform)/build/__tests__/useFlow.test.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/build/__tests__/useFlow.test.ts
@@ -63,12 +63,24 @@ vi.mock("../components/helper", () => ({
convertNodesPlusBlockInfoIntoCustomNodes: vi.fn(),
}));
+let mockIsReadOnly = false;
+
+vi.mock("../hooks/useIsReadOnlyGraph", () => ({
+ useIsReadOnlyGraph: vi.fn(() => ({
+ isReadOnly: mockIsReadOnly,
+ duplicate: vi.fn(),
+ isDuplicating: false,
+ canDuplicate: false,
+ })),
+}));
+
describe("useFlow", () => {
beforeEach(() => {
vi.clearAllMocks();
vi.useFakeTimers({ shouldAdvanceTime: true });
mockGraphLoading = false;
mockBlocksLoading = false;
+ mockIsReadOnly = false;
mockQueryStateValues = {
flowID: null,
flowVersion: null,
@@ -131,4 +143,36 @@ describe("useFlow", () => {
expect(result.current.isInitialLoadComplete).toBe(true);
});
});
+
+ describe("read-only lock", () => {
+ it("defaults to unlocked and allows toggling for owned graphs", async () => {
+ const { useFlow } = await import("../components/FlowEditor/Flow/useFlow");
+ const { result } = renderHook(() => useFlow());
+
+ expect(result.current.isReadOnly).toBe(false);
+ expect(result.current.isLocked).toBe(false);
+
+ act(() => {
+ result.current.setIsLocked(true);
+ });
+
+ expect(result.current.isLocked).toBe(true);
+ });
+
+ it("forces the canvas locked and ignores unlock attempts when read-only", async () => {
+ mockIsReadOnly = true;
+
+ const { useFlow } = await import("../components/FlowEditor/Flow/useFlow");
+ const { result } = renderHook(() => useFlow());
+
+ expect(result.current.isReadOnly).toBe(true);
+ expect(result.current.isLocked).toBe(true);
+
+ act(() => {
+ result.current.setIsLocked(false);
+ });
+
+ expect(result.current.isLocked).toBe(true);
+ });
+ });
});
diff --git a/autogpt_platform/frontend/src/app/(platform)/build/__tests__/useIsReadOnlyGraph.test.tsx b/autogpt_platform/frontend/src/app/(platform)/build/__tests__/useIsReadOnlyGraph.test.tsx
new file mode 100644
index 0000000000..be4c902e86
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/build/__tests__/useIsReadOnlyGraph.test.tsx
@@ -0,0 +1,81 @@
+import { renderHook } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+let mockUser: { id: string } | null = null;
+let mockIsUserLoading = false;
+vi.mock("@/lib/supabase/hooks/useSupabase", () => ({
+ useSupabase: () => ({ user: mockUser, isUserLoading: mockIsUserLoading }),
+}));
+
+vi.mock("nuqs", () => ({
+ parseAsString: {},
+ parseAsInteger: {},
+ useQueryStates: vi.fn(() => [
+ { flowID: "graph-1", flowVersion: null },
+ vi.fn(),
+ ]),
+}));
+
+let mockGraph: { id: string; user_id: string } | undefined;
+vi.mock("@/app/api/__generated__/endpoints/graphs/graphs", () => ({
+ useGetV1GetSpecificGraph: vi.fn(() => ({ data: mockGraph })),
+}));
+
+import { useIsReadOnlyGraph } from "../hooks/useIsReadOnlyGraph";
+
+describe("useIsReadOnlyGraph", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockUser = { id: "user-1" };
+ mockIsUserLoading = false;
+ mockGraph = { id: "graph-1", user_id: "user-1" };
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it("is not read-only when the current user owns the graph", () => {
+ mockGraph = { id: "graph-1", user_id: "user-1" };
+
+ const { result } = renderHook(() => useIsReadOnlyGraph());
+
+ expect(result.current.isReadOnly).toBe(false);
+ });
+
+ it("is read-only when the graph is owned by a different user", () => {
+ mockGraph = { id: "graph-1", user_id: "other-user" };
+
+ const { result } = renderHook(() => useIsReadOnlyGraph());
+
+ expect(result.current.isReadOnly).toBe(true);
+ });
+
+ it("is not read-only while the graph is still loading", () => {
+ mockGraph = undefined;
+
+ const { result } = renderHook(() => useIsReadOnlyGraph());
+
+ expect(result.current.isReadOnly).toBe(false);
+ });
+
+ it("is not read-only while auth is still resolving", () => {
+ mockUser = null;
+ mockIsUserLoading = true;
+ mockGraph = { id: "graph-1", user_id: "other-user" };
+
+ const { result } = renderHook(() => useIsReadOnlyGraph());
+
+ expect(result.current.isReadOnly).toBe(false);
+ });
+
+ it("is read-only for a logged-out viewer once auth resolves", () => {
+ mockUser = null;
+ mockIsUserLoading = false;
+ mockGraph = { id: "graph-1", user_id: "other-user" };
+
+ const { result } = renderHook(() => useIsReadOnlyGraph());
+
+ expect(result.current.isReadOnly).toBe(true);
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/build/components/FlowEditor/Flow/Flow.tsx b/autogpt_platform/frontend/src/app/(platform)/build/components/FlowEditor/Flow/Flow.tsx
index 84ae0c297a..2ea7f58cb1 100644
--- a/autogpt_platform/frontend/src/app/(platform)/build/components/FlowEditor/Flow/Flow.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/build/components/FlowEditor/Flow/Flow.tsx
@@ -14,6 +14,7 @@ import { BuilderActions } from "../../BuilderActions/BuilderActions";
import { DraftRecoveryPopup } from "../../DraftRecoveryDialog/DraftRecoveryPopup";
import { FloatingSafeModeToggle } from "../../FloatingSafeModeToogle";
import NewControlPanel from "../../NewControlPanel/NewControlPanel";
+import { ReadOnlyBanner } from "../../ReadOnlyBanner/ReadOnlyBanner";
import CustomEdge from "../edges/CustomEdge";
import { useCustomEdge } from "../edges/useCustomEdge";
import { CustomNode } from "../nodes/CustomNode/CustomNode";
@@ -81,13 +82,14 @@ export const Flow = () => {
isInitialLoadComplete,
isLocked,
setIsLocked,
+ isReadOnly,
} = useFlow();
// This hook is used for websocket realtime updates.
useFlowRealtime();
// Copy/paste functionality
- useCopyPaste();
+ useCopyPaste(isReadOnly);
const isGraphRunning = useGraphStore(
useShallow((state) => state.isGraphRunning),
@@ -120,12 +122,18 @@ export const Flow = () => {
deleteKeyCode={["Backspace", "Delete"]}
>
<Background />
- <CustomControls setIsLocked={setIsLocked} isLocked={isLocked} />
- <NewControlPanel />
- {hasWebhookNodes ? <TriggerAgentBanner /> : <BuilderActions />}
+ <CustomControls
+ setIsLocked={setIsLocked}
+ isLocked={isLocked}
+ isReadOnly={isReadOnly}
+ />
+ <NewControlPanel isReadOnly={isReadOnly} />
+ {isReadOnly && <ReadOnlyBanner />}
+ {!isReadOnly &&
+ (hasWebhookNodes ? <TriggerAgentBanner /> : <BuilderActions />)}
{<GraphLoadingBox flowContentLoading={isFlowContentLoading} />}
{isGraphRunning && <RunningBackground />}
- {graph && (
+ {graph && !isReadOnly && (
<FloatingSafeModeToggle
graph={graph}
className="right-2 top-32 p-2"
diff --git a/autogpt_platform/frontend/src/app/(platform)/build/components/FlowEditor/Flow/__tests__/CustomControl.test.tsx b/autogpt_platform/frontend/src/app/(platform)/build/components/FlowEditor/Flow/__tests__/CustomControl.test.tsx
new file mode 100644
index 0000000000..e8ecd18bac
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/build/components/FlowEditor/Flow/__tests__/CustomControl.test.tsx
@@ -0,0 +1,72 @@
+import { TooltipProvider } from "@/components/atoms/Tooltip/BaseTooltip";
+import { fireEvent, render } from "@testing-library/react";
+import { ReactElement } from "react";
+import { describe, expect, test, vi } from "vitest";
+
+vi.mock("@xyflow/react", () => ({
+ useReactFlow: () => ({
+ zoomIn: vi.fn(),
+ zoomOut: vi.fn(),
+ fitView: vi.fn(),
+ }),
+}));
+
+vi.mock("@/app/(platform)/build/stores/tutorialStore", () => ({
+ useTutorialStore: () => ({
+ isTutorialRunning: false,
+ setIsTutorialRunning: vi.fn(),
+ }),
+}));
+
+vi.mock("../../tutorial", () => ({
+ startTutorial: vi.fn(),
+ setTutorialLoadingCallback: vi.fn(),
+}));
+
+vi.mock("next/navigation", () => ({
+ useSearchParams: () => new URLSearchParams(),
+ useRouter: () => ({ push: vi.fn() }),
+}));
+
+import { CustomControls } from "../components/CustomControl";
+
+function renderControls(ui: ReactElement) {
+ return render(<TooltipProvider>{ui}</TooltipProvider>);
+}
+
+describe("CustomControls", () => {
+ test("lock toggle is enabled and works when not read-only", () => {
+ const setIsLocked = vi.fn();
+ const { container } = renderControls(
+ <CustomControls isLocked={false} setIsLocked={setIsLocked} />,
+ );
+
+ const lockButton = container.querySelector<HTMLButtonElement>(
+ '[data-id="lock-button"]',
+ );
+ expect(lockButton).not.toBeNull();
+ expect(lockButton!.disabled).toBe(false);
+
+ fireEvent.click(lockButton!);
+ expect(setIsLocked).toHaveBeenCalledWith(true);
+ });
+
+ test("lock toggle is disabled when read-only", () => {
+ const setIsLocked = vi.fn();
+ const { container } = renderControls(
+ <CustomControls isLocked={true} setIsLocked={setIsLocked} isReadOnly />,
+ );
+
+ const lockButton = container.querySelector<HTMLButtonElement>(
+ '[data-id="lock-button"]',
+ );
+ expect(lockButton).not.toBeNull();
+ expect(lockButton!.disabled).toBe(true);
+ expect(lockButton!.textContent).toContain(
+ "Canvas is locked because this is a read-only graph",
+ );
+
+ fireEvent.click(lockButton!);
+ expect(setIsLocked).not.toHaveBeenCalled();
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/build/components/FlowEditor/Flow/__tests__/Flow.test.tsx b/autogpt_platform/frontend/src/app/(platform)/build/components/FlowEditor/Flow/__tests__/Flow.test.tsx
new file mode 100644
index 0000000000..3dc19d1df5
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/build/components/FlowEditor/Flow/__tests__/Flow.test.tsx
@@ -0,0 +1,177 @@
+import { render, screen } from "@testing-library/react";
+import { ReactNode } from "react";
+import { beforeEach, describe, expect, test, vi } from "vitest";
+
+let mockIsReadOnly = false;
+let mockHasWebhookNodes = false;
+
+const mockUseFlow = vi.fn(() => ({
+ onDragOver: vi.fn(),
+ onDrop: vi.fn(),
+ isFlowContentLoading: false,
+ isInitialLoadComplete: true,
+ isLocked: mockIsReadOnly,
+ setIsLocked: vi.fn(),
+ isReadOnly: mockIsReadOnly,
+}));
+
+vi.mock("../useFlow", () => ({ useFlow: () => mockUseFlow() }));
+vi.mock("../useFlowRealtime", () => ({ useFlowRealtime: vi.fn() }));
+vi.mock("../useCopyPaste", () => ({ useCopyPaste: vi.fn() }));
+vi.mock("../../edges/useCustomEdge", () => ({
+ useCustomEdge: () => ({
+ edges: [],
+ onConnect: vi.fn(),
+ onEdgesChange: vi.fn(),
+ }),
+}));
+vi.mock("../../nodes/CustomNode/CustomNode", () => ({
+ CustomNode: () => null,
+}));
+vi.mock("../../edges/CustomEdge", () => ({ default: () => null }));
+vi.mock("../helpers/resolve-collision", () => ({
+ resolveCollisions: (nodes: unknown) => nodes,
+}));
+
+vi.mock("@xyflow/react", () => ({
+ ReactFlow: ({ children }: { children: ReactNode }) => (
+ <div data-testid="react-flow">{children}</div>
+ ),
+ Background: () => <div data-testid="background" />,
+ useReactFlow: () => ({ zoomIn: vi.fn(), zoomOut: vi.fn(), fitView: vi.fn() }),
+}));
+
+vi.mock("zustand/react/shallow", () => ({
+ useShallow: (fn: unknown) => fn,
+}));
+
+const nodeState = {
+ nodes: [],
+ setNodes: vi.fn(),
+ onNodesChange: vi.fn(),
+ hasWebhookNodes: () => mockHasWebhookNodes,
+};
+const useNodeStoreMock = (selector: (state: typeof nodeState) => unknown) =>
+ selector(nodeState);
+useNodeStoreMock.getState = () => nodeState;
+vi.mock("../../../../stores/nodeStore", () => ({
+ useNodeStore: (selector: (state: typeof nodeState) => unknown) =>
+ useNodeStoreMock(selector),
+}));
+
+const graphState = { isGraphRunning: false };
+vi.mock("../../../../stores/graphStore", () => ({
+ useGraphStore: (selector: (state: typeof graphState) => unknown) =>
+ selector(graphState),
+}));
+
+vi.mock("@/services/feature-flags/use-get-flag", () => ({
+ Flag: { BUILDER_CHAT_PANEL: "builder-chat-panel" },
+ useGetFlag: () => false,
+}));
+
+vi.mock("@/app/api/__generated__/endpoints/graphs/graphs", () => ({
+ useGetV1GetSpecificGraph: () => ({ data: { id: "graph-1" } }),
+}));
+
+vi.mock("@/app/api/helpers", () => ({
+ okData: (res: { data: unknown }) => res?.data,
+}));
+
+vi.mock("nuqs", () => ({
+ parseAsString: {},
+ parseAsInteger: {},
+ useQueryStates: () => [{ flowID: "graph-1", flowExecutionID: null }, vi.fn()],
+}));
+
+vi.mock("../../../NewControlPanel/NewControlPanel", () => ({
+ default: ({ isReadOnly }: { isReadOnly?: boolean }) => (
+ <div data-testid="control-panel" data-readonly={String(!!isReadOnly)} />
+ ),
+}));
+vi.mock("../../../ReadOnlyBanner/ReadOnlyBanner", () => ({
+ ReadOnlyBanner: () => <div data-testid="read-only-banner" />,
+}));
+vi.mock("../../../BuilderActions/BuilderActions", () => ({
+ BuilderActions: () => <div data-testid="builder-actions" />,
+}));
+vi.mock("../components/CustomControl", () => ({
+ CustomControls: ({ isReadOnly }: { isReadOnly?: boolean }) => (
+ <div data-testid="custom-controls" data-readonly={String(!!isReadOnly)} />
+ ),
+}));
+vi.mock("../components/GraphLoadingBox", () => ({
+ GraphLoadingBox: () => <div data-testid="graph-loading-box" />,
+}));
+vi.mock("../components/RunningBackground", () => ({
+ RunningBackground: () => <div data-testid="running-background" />,
+}));
+vi.mock("../components/TriggerAgentBanner", () => ({
+ TriggerAgentBanner: () => <div data-testid="trigger-agent-banner" />,
+}));
+vi.mock("../../../FloatingSafeModeToogle", () => ({
+ FloatingSafeModeToggle: () => <div data-testid="safe-mode-toggle" />,
+}));
+vi.mock("../../../DraftRecoveryDialog/DraftRecoveryPopup", () => ({
+ DraftRecoveryPopup: () => <div data-testid="draft-recovery" />,
+}));
+vi.mock("../../../BuilderChatPanel/BuilderChatPanel", () => ({
+ BuilderChatPanel: () => <div data-testid="builder-chat" />,
+}));
+vi.mock("@/components/molecules/ErrorBoundary/ErrorBoundary", () => ({
+ ErrorBoundary: ({ children }: { children: ReactNode }) => <>{children}</>,
+}));
+vi.mock(
+ "@/components/organisms/FloatingReviewsPanel/FloatingReviewsPanel",
+ () => ({
+ FloatingReviewsPanel: () => <div data-testid="reviews-panel" />,
+ }),
+);
+
+import { Flow } from "../Flow";
+
+describe("Flow read-only gating", () => {
+ beforeEach(() => {
+ mockIsReadOnly = false;
+ mockHasWebhookNodes = false;
+ });
+
+ test("owned graph: shows builder actions, hides read-only banner, controls editable", () => {
+ render(<Flow />);
+
+ expect(screen.queryByTestId("builder-actions")).not.toBeNull();
+ expect(screen.queryByTestId("read-only-banner")).toBeNull();
+ expect(screen.queryByTestId("safe-mode-toggle")).not.toBeNull();
+ expect(
+ screen.getByTestId("control-panel").getAttribute("data-readonly"),
+ ).toBe("false");
+ expect(
+ screen.getByTestId("custom-controls").getAttribute("data-readonly"),
+ ).toBe("false");
+ });
+
+ test("non-owned graph: shows read-only banner, hides action bar, gates controls", () => {
+ mockIsReadOnly = true;
+ render(<Flow />);
+
+ expect(screen.queryByTestId("read-only-banner")).not.toBeNull();
+ expect(screen.queryByTestId("builder-actions")).toBeNull();
+ expect(screen.queryByTestId("trigger-agent-banner")).toBeNull();
+ expect(screen.queryByTestId("safe-mode-toggle")).toBeNull();
+ expect(
+ screen.getByTestId("control-panel").getAttribute("data-readonly"),
+ ).toBe("true");
+ expect(
+ screen.getByTestId("custom-controls").getAttribute("data-readonly"),
+ ).toBe("true");
+ });
+
+ test("non-owned trigger graph still hides the trigger banner", () => {
+ mockIsReadOnly = true;
+ mockHasWebhookNodes = true;
+ render(<Flow />);
+
+ expect(screen.queryByTestId("read-only-banner")).not.toBeNull();
+ expect(screen.queryByTestId("trigger-agent-banner")).toBeNull();
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/build/components/FlowEditor/Flow/components/CustomControl.tsx b/autogpt_platform/frontend/src/app/(platform)/build/components/FlowEditor/Flow/components/CustomControl.tsx
index 7b723d73b3..a3a4e7b9ac 100644
--- a/autogpt_platform/frontend/src/app/(platform)/build/components/FlowEditor/Flow/components/CustomControl.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/build/components/FlowEditor/Flow/components/CustomControl.tsx
@@ -22,9 +22,11 @@ export const CustomControls = memo(
({
setIsLocked,
isLocked,
+ isReadOnly = false,
}: {
isLocked: boolean;
setIsLocked: (isLocked: boolean) => void;
+ isReadOnly?: boolean;
}) => {
const { zoomIn, zoomOut, fitView } = useReactFlow();
const { isTutorialRunning, setIsTutorialRunning } = useTutorialStore();
@@ -91,9 +93,12 @@ export const CustomControls = memo(
) : (
<LockIcon className="size-3.5 text-zinc-600" />
),
- label: "Toggle Lock",
+ label: isReadOnly
+ ? "Canvas is locked because this is a read-only graph"
+ : "Toggle Lock",
onClick: () => setIsLocked(!isLocked),
className: `h-10 w-10 border-none ${isLocked ? "bg-zinc-100" : "bg-white"}`,
+ disabled: isReadOnly,
},
];
diff --git a/autogpt_platform/frontend/src/app/(platform)/build/components/FlowEditor/Flow/useCopyPaste.ts b/autogpt_platform/frontend/src/app/(platform)/build/components/FlowEditor/Flow/useCopyPaste.ts
index c6c54006d4..addad7b9fc 100644
--- a/autogpt_platform/frontend/src/app/(platform)/build/components/FlowEditor/Flow/useCopyPaste.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/build/components/FlowEditor/Flow/useCopyPaste.ts
@@ -14,12 +14,16 @@ interface CopyableData {
const CLIPBOARD_PREFIX = "autogpt-flow-data:";
-export function useCopyPaste() {
+export function useCopyPaste(isReadOnly = false) {
const { getViewport } = useReactFlow();
const { toast } = useToast();
const handleCopyPaste = useCallback(
(event: KeyboardEvent) => {
+ // Read-only graphs cannot be edited, so paste (which would add nodes) is a
+ // no-op. The visual edit controls are hidden in this mode too.
+ if (isReadOnly) return;
+
const activeElement = document.activeElement;
const isInputField =
activeElement?.tagName === "INPUT" ||
@@ -148,7 +152,7 @@ export function useCopyPaste() {
}
}
},
- [getViewport, toast],
+ [getViewport, toast, isReadOnly],
);
useEffect(() => {
diff --git a/autogpt_platform/frontend/src/app/(platform)/build/components/FlowEditor/Flow/useFlow.ts b/autogpt_platform/frontend/src/app/(platform)/build/components/FlowEditor/Flow/useFlow.ts
index 11a354abff..04a0135af1 100644
--- a/autogpt_platform/frontend/src/app/(platform)/build/components/FlowEditor/Flow/useFlow.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/build/components/FlowEditor/Flow/useFlow.ts
@@ -19,9 +19,11 @@ import { useControlPanelStore } from "../../../stores/controlPanelStore";
import { useHistoryStore } from "../../../stores/historyStore";
import { AgentExecutionStatus } from "@/app/api/__generated__/models/agentExecutionStatus";
import { okData } from "@/app/api/helpers";
+import { useIsReadOnlyGraph } from "../../../hooks/useIsReadOnlyGraph";
export const useFlow = () => {
- const [isLocked, setIsLocked] = useState(false);
+ const { isReadOnly } = useIsReadOnlyGraph();
+ const [isLockedState, setIsLockedState] = useState(false);
const [hasAutoFramed, setHasAutoFramed] = useState(false);
const [isInitialLoadComplete, setIsInitialLoadComplete] = useState(false);
const addNodes = useNodeStore(useShallow((state) => state.addNodes));
@@ -301,6 +303,17 @@ export const useFlow = () => {
[screenToFlowPosition, addBlock, setBlockMenuOpen],
);
+ // When the graph is read-only, force the canvas locked and ignore unlock
+ // attempts so non-owners cannot edit nodes.
+ const isLocked = isReadOnly || isLockedState;
+ const setIsLocked = useCallback(
+ (locked: boolean) => {
+ if (isReadOnly) return;
+ setIsLockedState(locked);
+ },
+ [isReadOnly],
+ );
+
return {
isFlowContentLoading: isGraphLoading || isBlocksLoading,
isInitialLoadComplete,
@@ -308,5 +321,6 @@ export const useFlow = () => {
onDrop,
isLocked,
setIsLocked,
+ isReadOnly,
};
};
diff --git a/autogpt_platform/frontend/src/app/(platform)/build/components/NewControlPanel/NewControlPanel.tsx b/autogpt_platform/frontend/src/app/(platform)/build/components/NewControlPanel/NewControlPanel.tsx
index 1f9c529aa8..1a0f7e0bb2 100644
--- a/autogpt_platform/frontend/src/app/(platform)/build/components/NewControlPanel/NewControlPanel.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/build/components/NewControlPanel/NewControlPanel.tsx
@@ -7,7 +7,13 @@ import { GraphSearchMenu } from "./NewSearchGraph/GraphMenu/GraphMenu";
import { UndoRedoButtons } from "./UndoRedoButtons";
import { useGraphSearchShortcut } from "./useGraphSearchShortcut";
-export const NewControlPanel = memo(function NewControlPanel() {
+interface Props {
+ isReadOnly?: boolean;
+}
+
+export const NewControlPanel = memo(function NewControlPanel({
+ isReadOnly = false,
+}: Props) {
useGraphSearchShortcut();
return (
@@ -17,13 +23,19 @@ export const NewControlPanel = memo(function NewControlPanel() {
)}
>
<div className="flex flex-col items-center justify-center rounded-[1rem] p-0">
- <BlockMenu />
- <Separator className="text-[#E1E1E1]" />
- <GraphSearchMenu />
- <Separator className="text-[#E1E1E1]" />
- <NewSaveControl />
- <Separator className="text-[#E1E1E1]" />
- <UndoRedoButtons />
+ {isReadOnly ? (
+ <GraphSearchMenu />
+ ) : (
+ <>
+ <BlockMenu />
+ <Separator className="text-[#E1E1E1]" />
+ <GraphSearchMenu />
+ <Separator className="text-[#E1E1E1]" />
+ <NewSaveControl />
+ <Separator className="text-[#E1E1E1]" />
+ <UndoRedoButtons />
+ </>
+ )}
</div>
</section>
);
diff --git a/autogpt_platform/frontend/src/app/(platform)/build/components/NewControlPanel/__tests__/NewControlPanel.test.tsx b/autogpt_platform/frontend/src/app/(platform)/build/components/NewControlPanel/__tests__/NewControlPanel.test.tsx
new file mode 100644
index 0000000000..a4ec6c6568
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/build/components/NewControlPanel/__tests__/NewControlPanel.test.tsx
@@ -0,0 +1,44 @@
+import { render, screen } from "@testing-library/react";
+import { describe, expect, test, vi } from "vitest";
+
+vi.mock("../NewBlockMenu/BlockMenu/BlockMenu", () => ({
+ BlockMenu: () => <div data-testid="block-menu" />,
+}));
+
+vi.mock("../NewSaveControl/NewSaveControl", () => ({
+ NewSaveControl: () => <div data-testid="save-control" />,
+}));
+
+vi.mock("../NewSearchGraph/GraphMenu/GraphMenu", () => ({
+ GraphSearchMenu: () => <div data-testid="graph-search" />,
+}));
+
+vi.mock("../UndoRedoButtons", () => ({
+ UndoRedoButtons: () => <div data-testid="undo-redo" />,
+}));
+
+vi.mock("../useGraphSearchShortcut", () => ({
+ useGraphSearchShortcut: vi.fn(),
+}));
+
+import { NewControlPanel } from "../NewControlPanel";
+
+describe("NewControlPanel", () => {
+ test("renders all controls when the graph is editable", () => {
+ render(<NewControlPanel />);
+
+ expect(screen.queryByTestId("block-menu")).not.toBeNull();
+ expect(screen.queryByTestId("save-control")).not.toBeNull();
+ expect(screen.queryByTestId("undo-redo")).not.toBeNull();
+ expect(screen.queryByTestId("graph-search")).not.toBeNull();
+ });
+
+ test("renders only the graph search when read-only", () => {
+ render(<NewControlPanel isReadOnly />);
+
+ expect(screen.queryByTestId("graph-search")).not.toBeNull();
+ expect(screen.queryByTestId("block-menu")).toBeNull();
+ expect(screen.queryByTestId("save-control")).toBeNull();
+ expect(screen.queryByTestId("undo-redo")).toBeNull();
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/build/components/ReadOnlyBanner/ReadOnlyBanner.tsx b/autogpt_platform/frontend/src/app/(platform)/build/components/ReadOnlyBanner/ReadOnlyBanner.tsx
new file mode 100644
index 0000000000..f6ada4952c
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/build/components/ReadOnlyBanner/ReadOnlyBanner.tsx
@@ -0,0 +1,55 @@
+import { Button } from "@/components/atoms/Button/Button";
+import { Text } from "@/components/atoms/Text/Text";
+import { CopyIcon, XIcon } from "@phosphor-icons/react";
+import { useState } from "react";
+import { useDuplicateGraph } from "../../hooks/useDuplicateGraph";
+
+export function ReadOnlyBanner() {
+ const { duplicate, isDuplicating, canDuplicate, isCheckingLibrary } =
+ useDuplicateGraph();
+ const [isDismissed, setIsDismissed] = useState(false);
+
+ if (isDismissed) return null;
+
+ // Show the Duplicate CTA immediately while we look up the library agent, only
+ // falling back to the "add to library" hint once we know it can't be forked.
+ const showDuplicate = canDuplicate || isCheckingLibrary;
+
+ return (
+ <div
+ data-id="read-only-banner"
+ role="status"
+ aria-live="polite"
+ className="absolute left-1/2 top-4 z-20 flex -translate-x-1/2 select-none items-center gap-3 rounded-full bg-white px-4 py-2 shadow-lg"
+ >
+ <Text variant="body" className="px-2 text-zinc-700">
+ You&apos;re viewing a read-only copy of this agent.
+ <br />
+ {showDuplicate
+ ? "Duplicate it to make changes."
+ : "Add it to your library to enable duplication."}
+ </Text>
+ {showDuplicate && (
+ <Button
+ variant="primary"
+ size="small"
+ onClick={duplicate}
+ loading={isDuplicating}
+ disabled={!canDuplicate}
+ leftIcon={<CopyIcon className="size-4" />}
+ >
+ Duplicate
+ </Button>
+ )}
+ <Button
+ variant="ghost"
+ size="icon"
+ onClick={() => setIsDismissed(true)}
+ aria-label="Dismiss"
+ title="Dismiss"
+ >
+ <XIcon className="h-4 w-4" />
+ </Button>
+ </div>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/build/components/ReadOnlyBanner/__tests__/ReadOnlyBanner.test.tsx b/autogpt_platform/frontend/src/app/(platform)/build/components/ReadOnlyBanner/__tests__/ReadOnlyBanner.test.tsx
new file mode 100644
index 0000000000..42e19f2f49
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/build/components/ReadOnlyBanner/__tests__/ReadOnlyBanner.test.tsx
@@ -0,0 +1,83 @@
+import { fireEvent, render, screen } from "@testing-library/react";
+import { beforeEach, describe, expect, test, vi } from "vitest";
+
+const mockDuplicate = vi.fn();
+let mockCanDuplicate = true;
+let mockIsDuplicating = false;
+let mockIsCheckingLibrary = false;
+
+vi.mock("../../../hooks/useDuplicateGraph", () => ({
+ useDuplicateGraph: () => ({
+ duplicate: mockDuplicate,
+ isDuplicating: mockIsDuplicating,
+ canDuplicate: mockCanDuplicate,
+ isCheckingLibrary: mockIsCheckingLibrary,
+ }),
+}));
+
+import { ReadOnlyBanner } from "../ReadOnlyBanner";
+
+describe("ReadOnlyBanner", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockCanDuplicate = true;
+ mockIsDuplicating = false;
+ mockIsCheckingLibrary = false;
+ });
+
+ test("shows the Duplicate CTA when the agent can be duplicated", () => {
+ render(<ReadOnlyBanner />);
+
+ const button = screen.getByRole("button", { name: /duplicate/i });
+ expect(button).not.toBeNull();
+ expect(screen.getByText(/Duplicate it to make changes/i)).not.toBeNull();
+
+ fireEvent.click(button);
+ expect(mockDuplicate).toHaveBeenCalledTimes(1);
+ });
+
+ test("explains how to enable duplication and hides the CTA when it cannot duplicate", () => {
+ mockCanDuplicate = false;
+ render(<ReadOnlyBanner />);
+
+ expect(screen.queryByRole("button", { name: /duplicate/i })).toBeNull();
+ expect(
+ screen.getByText(/Add it to your library to enable duplication/i),
+ ).not.toBeNull();
+ });
+
+ test("shows the Duplicate CTA disabled while the library lookup is in flight", () => {
+ mockCanDuplicate = false;
+ mockIsCheckingLibrary = true;
+ render(<ReadOnlyBanner />);
+
+ const button = screen.getByRole("button", {
+ name: /duplicate/i,
+ }) as HTMLButtonElement;
+ expect(button.disabled).toBe(true);
+ expect(screen.getByText(/Duplicate it to make changes/i)).not.toBeNull();
+ expect(
+ screen.queryByText(/Add it to your library to enable duplication/i),
+ ).toBeNull();
+ });
+
+ test("announces the read-only state to assistive technology", () => {
+ const { container } = render(<ReadOnlyBanner />);
+
+ const banner = container.querySelector('[data-id="read-only-banner"]');
+ expect(banner?.getAttribute("role")).toBe("status");
+ expect(banner?.getAttribute("aria-live")).toBe("polite");
+ });
+
+ test("can be dismissed", () => {
+ const { container } = render(<ReadOnlyBanner />);
+
+ expect(
+ container.querySelector('[data-id="read-only-banner"]'),
+ ).not.toBeNull();
+
+ fireEvent.click(screen.getByRole("button", { name: /dismiss/i }));
+
+ expect(container.querySelector('[data-id="read-only-banner"]')).toBeNull();
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/build/hooks/useDuplicateGraph.ts b/autogpt_platform/frontend/src/app/(platform)/build/hooks/useDuplicateGraph.ts
new file mode 100644
index 0000000000..4dfbef812f
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/build/hooks/useDuplicateGraph.ts
@@ -0,0 +1,61 @@
+import {
+ useGetV2GetLibraryAgentByGraphId,
+ usePostV2ForkLibraryAgent,
+} from "@/app/api/__generated__/endpoints/library/library";
+import { LibraryAgent } from "@/app/api/__generated__/models/libraryAgent";
+import { useToast } from "@/components/molecules/Toast/use-toast";
+import { useRouter } from "next/navigation";
+import { parseAsString, useQueryStates } from "nuqs";
+
+export function useDuplicateGraph() {
+ const router = useRouter();
+ const { toast } = useToast();
+
+ const [{ flowID }] = useQueryStates({
+ flowID: parseAsString,
+ });
+
+ const { data: libraryAgent, isLoading: isCheckingLibrary } =
+ useGetV2GetLibraryAgentByGraphId(
+ flowID ?? "",
+ {},
+ {
+ query: {
+ select: (res) => res.data as LibraryAgent,
+ enabled: !!flowID,
+ },
+ },
+ );
+
+ const { mutateAsync: forkAgent, isPending: isDuplicating } =
+ usePostV2ForkLibraryAgent();
+
+ async function duplicate() {
+ if (!libraryAgent) return;
+
+ try {
+ const result = await forkAgent({ libraryAgentId: libraryAgent.id });
+ const forked = result.data as LibraryAgent;
+ if (!forked?.graph_id) {
+ throw new Error("Fork did not return a graph to open.");
+ }
+ router.push(`/build?flowID=${forked.graph_id}`);
+ } catch (error) {
+ toast({
+ title: "Failed to duplicate agent",
+ description:
+ error instanceof Error
+ ? error.message
+ : "An unexpected error occurred.",
+ variant: "destructive",
+ });
+ }
+ }
+
+ return {
+ duplicate,
+ isDuplicating,
+ canDuplicate: !!libraryAgent,
+ isCheckingLibrary,
+ };
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/build/hooks/useIsReadOnlyGraph.ts b/autogpt_platform/frontend/src/app/(platform)/build/hooks/useIsReadOnlyGraph.ts
new file mode 100644
index 0000000000..7aa2d21d88
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/build/hooks/useIsReadOnlyGraph.ts
@@ -0,0 +1,39 @@
+import { useGetV1GetSpecificGraph } from "@/app/api/__generated__/endpoints/graphs/graphs";
+import { GraphModel } from "@/app/api/__generated__/models/graphModel";
+import { useSupabase } from "@/lib/supabase/hooks/useSupabase";
+import { parseAsInteger, parseAsString, useQueryStates } from "nuqs";
+
+// Read-only detection is a UX affordance only — the backend is the security
+// boundary and already rejects mutations (save, etc.) from non-owners. This
+// hook just hides controls that would otherwise fail silently.
+export function useIsReadOnlyGraph() {
+ const { user, isUserLoading } = useSupabase();
+
+ const [{ flowID, flowVersion }] = useQueryStates({
+ flowID: parseAsString,
+ flowVersion: parseAsInteger,
+ });
+
+ // Mirror useFlow's query (same key incl. version) so React Query serves both
+ // from one cache entry and ownership reflects the version actually being
+ // viewed, not just the latest.
+ const { data: graph } = useGetV1GetSpecificGraph(
+ flowID ?? "",
+ flowVersion !== null ? { version: flowVersion } : {},
+ {
+ query: {
+ select: (res) => res.data as GraphModel,
+ enabled: !!flowID,
+ },
+ },
+ );
+
+ // Wait for both the graph and the auth state to resolve before deciding, so
+ // the banner doesn't flicker for owners during initial mount. Once resolved,
+ // anyone who isn't the confirmed owner (including a logged-out viewer) is
+ // read-only — failing safe toward read-only rather than toward editable.
+ const isReadOnly =
+ !!graph && !isUserLoading && (!user || graph.user_id !== user.id);
+
+ return { isReadOnly };
+}