Skip to content

Same agent Smaller bill. The tools and infrastructure to get more work from your AI. Fewer tokens. Less compute. Lower cost.

fix: complete onboarding ClickHouse setup instead of looping on connectors (#1534)

Aman Agarwaldbf3e0ab7a2f
diff --git a/src/Dockerfile b/src/Dockerfile
index dd6ca16d..6f11345f 100644
--- a/src/Dockerfile
+++ b/src/Dockerfile
@@ -79,8 +79,9 @@ RUN echo "Downloading binaries for architecture: ${TARGETARCH}" && \
echo "opampsupervisor binary info:" && file opampsupervisor
-# Final runtime image - Node 20 (OpenPlait adapters declare engines.node >=20)
-FROM node:20-bullseye-slim@sha256:65ef49f7d24aefd012a7fc6f9a2b734bcc19e424976a81f60c86b47266ef5b28
+# Final runtime image - Node 20 on Debian bookworm (bullseye-security
+# package indexes now 404 openssl 1.1.1w updates required by bullseye-slim)
+FROM node:20-bookworm-slim@sha256:2cf067cfed83d5ea958367df9f966191a942351a2df77d6f0193e162b5febfc0
# Accept build arguments to pass version and architecture info
# TARGETARCH is automatically provided by Docker buildx based on --platform
@@ -95,8 +96,7 @@ ENV OPAMP_SUPERVISOR_VERSION=${OPAMP_SUPERVISOR_VERSION}
ENV TARGETARCH=${TARGETARCH}
# Install only the additional runtime dependencies needed.
-# bullseye-security InRelease Valid-Until can expire in CI while the mirror is
-# otherwise healthy; skip the timestamp check so apt-get update still works.
+# Skip Valid-Until so a briefly stale security index cannot fail the image build.
RUN apt-get update -o Acquire::Check-Valid-Until=false && apt-get install -y --no-install-recommends \
bash \
openssl \
diff --git a/src/client/src/__tests__/app/chat-page.test.tsx b/src/client/src/__tests__/app/chat-page.test.tsx
new file mode 100644
index 00000000..c524f8f4
--- /dev/null
+++ b/src/client/src/__tests__/app/chat-page.test.tsx
@@ -0,0 +1,116 @@
+/**
+ * @jest-environment jsdom
+ */
+
+const fetchDatabaseConfigList = jest.fn(
+ async (successCb?: (data: unknown[]) => void) => {
+ successCb?.([]);
+ }
+);
+const fetchProjectList = jest.fn().mockResolvedValue([]);
+const replace = jest.fn();
+
+jest.mock("next/navigation", () => ({
+ useRouter: () => ({ replace, push: jest.fn() }),
+ useSearchParams: () => ({ get: () => null }),
+}));
+
+jest.mock("@/helpers/client/project", () => ({
+ fetchProjectList: (...args: unknown[]) => fetchProjectList(...args),
+}));
+
+jest.mock("@/helpers/client/database-config", () => ({
+ fetchDatabaseConfigList: (...args: any[]) => fetchDatabaseConfigList(...args),
+ projectHasDatabaseConfig: (list: unknown[] | undefined | null) =>
+ Array.isArray(list) && list.length > 0,
+}));
+
+jest.mock("@/store", () => ({
+ useRootStore: jest.fn(),
+}));
+
+jest.mock("@/components/(playground)/chat/chat-layout", () => () => null);
+jest.mock("@/components/(playground)/request/request-context", () => ({
+ RequestProvider: ({ children }: { children: React.ReactNode }) => children,
+}));
+
+import { render } from "@testing-library/react";
+import ChatPage from "@/app/(playground)/chat/page";
+import { useRootStore } from "@/store";
+
+const org = { id: "org-1", name: "My cool org", isCurrent: true };
+const project = {
+ id: "proj-1",
+ organisationId: "org-1",
+ name: "Default Project",
+ isCurrent: true,
+};
+
+function mockStore(
+ overrides: {
+ databaseConfigs?: unknown[] | undefined;
+ organisationList?: unknown[] | undefined;
+ isOrganisationLoading?: boolean;
+ projects?: unknown[] | undefined;
+ currentOrg?: typeof org | undefined;
+ } = {}
+) {
+ const currentOrg = "currentOrg" in overrides ? overrides.currentOrg : org;
+ const projects =
+ "projects" in overrides ? overrides.projects : [project];
+ const state = {
+ organisation: {
+ current: currentOrg,
+ list:
+ "organisationList" in overrides ? overrides.organisationList : [org],
+ isLoading: overrides.isOrganisationLoading ?? false,
+ },
+ project: {
+ list: projects,
+ current: Array.isArray(projects) && projects.length > 0 ? project : undefined,
+ isLoading: false,
+ },
+ databaseConfig: {
+ list: "databaseConfigs" in overrides ? overrides.databaseConfigs : [],
+ isLoading: false,
+ },
+ };
+ (useRootStore as unknown as jest.Mock).mockImplementation((selector) =>
+ selector(state)
+ );
+}
+
+describe("ChatPage database setup gate", () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ fetchDatabaseConfigList.mockImplementation(
+ async (successCb?: (data: unknown[]) => void) => {
+ successCb?.([]);
+ }
+ );
+ global.fetch = jest.fn() as unknown as typeof fetch;
+ });
+
+ it("loads project database configs instead of /api/connectors and stays on chat when none exist", async () => {
+ mockStore({ databaseConfigs: [] });
+ render(<ChatPage />);
+
+ expect(fetchDatabaseConfigList).toHaveBeenCalled();
+ expect(replace).not.toHaveBeenCalled();
+ expect(global.fetch).not.toHaveBeenCalled();
+ });
+
+ it("does not bounce to onboarding while organisation or database configs are still loading", () => {
+ fetchDatabaseConfigList.mockImplementation(async () => undefined);
+ mockStore({
+ databaseConfigs: undefined,
+ organisationList: undefined,
+ isOrganisationLoading: true,
+ currentOrg: undefined,
+ projects: undefined,
+ });
+ render(<ChatPage />);
+
+ expect(replace).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/client/src/__tests__/app/home-page.test.tsx b/src/client/src/__tests__/app/home-page.test.tsx
new file mode 100644
index 00000000..62bbf8b3
--- /dev/null
+++ b/src/client/src/__tests__/app/home-page.test.tsx
@@ -0,0 +1,145 @@
+/**
+ * @jest-environment jsdom
+ */
+
+const fetchDatabaseConfigList = jest.fn(
+ async (successCb?: (data: unknown[]) => void) => {
+ successCb?.([]);
+ }
+);
+const replace = jest.fn();
+const fireRequest = jest.fn().mockResolvedValue({ response: {}, error: undefined });
+
+jest.mock("next/navigation", () => ({
+ useRouter: () => ({ replace, push: jest.fn() }),
+ useSearchParams: () => ({ get: () => null }),
+}));
+
+jest.mock("posthog-js/react", () => ({
+ usePostHog: () => ({ capture: jest.fn() }),
+}));
+
+jest.mock("@/selectors/page", () => ({
+ usePageHeader: () => ({ setHeader: jest.fn() }),
+}));
+
+jest.mock("@/utils/hooks/useFetchWrapper", () => () => ({
+ fireRequest,
+ isLoading: false,
+}));
+
+jest.mock("@/helpers/client/filter", () => ({
+ getFilterParamsForDashboard: () => ({}),
+}));
+
+jest.mock("@/helpers/client/database-config", () => ({
+ fetchDatabaseConfigList: (...args: any[]) => fetchDatabaseConfigList(...args),
+ projectHasDatabaseConfig: (list: unknown[] | undefined | null) =>
+ Array.isArray(list) && list.length > 0,
+}));
+
+jest.mock("@/store", () => ({
+ useRootStore: jest.fn(),
+}));
+
+jest.mock("../../components/(playground)/filter", () => () => null);
+jest.mock("../../app/(playground)/home/board-list", () => () => null);
+jest.mock("../../components/(playground)/manage-dashboard/board-creator", () => ({
+ __esModule: true,
+ default: () => null,
+}));
+
+import { render, waitFor } from "@testing-library/react";
+import HomePage from "@/app/(playground)/home/page";
+import { useRootStore } from "@/store";
+
+const org = { id: "org-1", name: "My cool org", isCurrent: true };
+const project = {
+ id: "proj-1",
+ organisationId: "org-1",
+ name: "Default Project",
+ isCurrent: true,
+};
+
+function mockStore(
+ overrides: {
+ databaseConfigs?: unknown[] | undefined;
+ organisationList?: unknown[] | undefined;
+ isOrganisationLoading?: boolean;
+ projects?: unknown[] | undefined;
+ isProjectLoading?: boolean;
+ currentOrg?: typeof org | undefined;
+ } = {}
+) {
+ const currentOrg = "currentOrg" in overrides ? overrides.currentOrg : org;
+ const projects =
+ "projects" in overrides ? overrides.projects : [project];
+ const state = {
+ organisation: {
+ current: currentOrg,
+ list:
+ "organisationList" in overrides ? overrides.organisationList : [org],
+ isLoading: overrides.isOrganisationLoading ?? false,
+ },
+ project: {
+ list: projects,
+ current: Array.isArray(projects) && projects.length > 0 ? project : undefined,
+ isLoading: overrides.isProjectLoading ?? false,
+ },
+ databaseConfig: {
+ list: "databaseConfigs" in overrides ? overrides.databaseConfigs : [],
+ isLoading: false,
+ },
+ filter: { details: {} },
+ };
+ (useRootStore as unknown as jest.Mock).mockImplementation((selector) =>
+ selector(state)
+ );
+}
+
+describe("HomePage database setup gate", () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ fetchDatabaseConfigList.mockImplementation(
+ async (successCb?: (data: unknown[]) => void) => {
+ successCb?.([]);
+ }
+ );
+ global.fetch = jest.fn() as unknown as typeof fetch;
+ });
+
+ it("loads project database configs instead of /api/connectors and stays on home while setup is empty", async () => {
+ mockStore({ databaseConfigs: [] });
+ render(<HomePage />);
+
+ expect(fetchDatabaseConfigList).toHaveBeenCalled();
+ expect(replace).not.toHaveBeenCalled();
+ expect(global.fetch).not.toHaveBeenCalled();
+ expect(fireRequest).not.toHaveBeenCalled();
+ });
+
+ it("does not bounce to onboarding while organisation or database configs are still loading", () => {
+ fetchDatabaseConfigList.mockImplementation(async () => undefined);
+ mockStore({
+ databaseConfigs: undefined,
+ organisationList: undefined,
+ isOrganisationLoading: true,
+ currentOrg: undefined,
+ projects: undefined,
+ });
+ render(<HomePage />);
+
+ expect(replace).not.toHaveBeenCalled();
+ expect(fireRequest).not.toHaveBeenCalled();
+ });
+
+ it("stays on home once the current project has a database config", async () => {
+ mockStore({ databaseConfigs: [{ id: "db-1" }] });
+ render(<HomePage />);
+
+ await waitFor(() => {
+ expect(fireRequest).toHaveBeenCalled();
+ });
+ expect(replace).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/client/src/__tests__/app/onboarding-page.test.tsx b/src/client/src/__tests__/app/onboarding-page.test.tsx
index e7e5a74a..1be13e9e 100644
--- a/src/client/src/__tests__/app/onboarding-page.test.tsx
+++ b/src/client/src/__tests__/app/onboarding-page.test.tsx
@@ -5,7 +5,11 @@
const fetchOrganisationList = jest.fn().mockResolvedValue(undefined);
const fetchPendingInvitations = jest.fn().mockResolvedValue(undefined);
const fetchProjectList = jest.fn().mockResolvedValue([]);
-const fetchDatabaseConfigList = jest.fn().mockResolvedValue(undefined);
+const fetchDatabaseConfigList = jest.fn(
+ async (successCb?: (data: unknown[]) => void) => {
+ successCb?.([]);
+ }
+);
jest.mock("next-auth/react", () => ({
useSession: () => ({ update: jest.fn() }),
@@ -34,8 +38,10 @@ jest.mock("@/helpers/client/project", () => ({
}));
jest.mock("@/helpers/client/database-config", () => ({
- fetchDatabaseConfigList: (...args: unknown[]) => fetchDatabaseConfigList(...args),
+ fetchDatabaseConfigList: (...args: any[]) => fetchDatabaseConfigList(...args),
deleteDatabaseConfig: jest.fn(),
+ projectHasDatabaseConfig: (list: unknown[] | undefined | null) =>
+ Array.isArray(list) && list.length > 0,
}));
jest.mock("@/store", () => ({
@@ -116,4 +122,16 @@ describe("OnboardingPage database config step", () => {
expect(screen.getByPlaceholderText("127.0.0.1")).toBeInTheDocument();
expect(screen.getByPlaceholderText("8123")).toBeInTheDocument();
});
+
+ it("shows Finish setup once the current project already has a database config", async () => {
+ mockStore({ databaseConfigs: [{ id: "db-1", name: "Primary" }] });
+ render(<OnboardingPage />);
+
+ expect(
+ await screen.findByRole("button", { name: "Finish setup" })
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByRole("button", { name: "Add database config" })
+ ).not.toBeInTheDocument();
+ });
});
diff --git a/src/client/src/__tests__/helpers/client/database-config.test.ts b/src/client/src/__tests__/helpers/client/database-config.test.ts
index 33cf3c64..81fb8355 100644
--- a/src/client/src/__tests__/helpers/client/database-config.test.ts
+++ b/src/client/src/__tests__/helpers/client/database-config.test.ts
@@ -15,6 +15,7 @@ import {
pingActiveDatabaseConfig,
changeActiveDatabaseConfig,
deleteDatabaseConfig,
+ projectHasDatabaseConfig,
} from '@/helpers/client/database-config';
import { useRootStore } from '@/store';
import { getData, deleteData } from '@/utils/api';
@@ -25,13 +26,16 @@ const mockSetIsLoading = jest.fn();
const mockSetList = jest.fn();
const mockSetPing = jest.fn();
-const makeGetState = (list: any[] = []) => ({
+const makeGetState = (list: any[] = [], currentProjectId: string | null = 'proj-1') => ({
databaseConfig: {
setIsLoading: mockSetIsLoading,
setList: mockSetList,
setPing: mockSetPing,
list,
},
+ project: {
+ current: currentProjectId ? { id: currentProjectId } : undefined,
+ },
});
beforeEach(() => {
@@ -53,19 +57,51 @@ describe('fetchDatabaseConfigList', () => {
expect(mockSetList).toHaveBeenCalledWith(data);
});
- it('calls successCb with empty array on error', async () => {
- (asaw as jest.Mock).mockResolvedValue([null, null]);
+ it('treats a fetch error as an empty list and surfaces it', async () => {
+ (asaw as jest.Mock).mockResolvedValue(['Unauthorized']);
const successCb = jest.fn();
await fetchDatabaseConfigList(successCb);
expect(successCb).toHaveBeenCalledWith([]);
+ expect(mockSetList).toHaveBeenCalledWith([]);
+ expect(toast.error).toHaveBeenCalled();
});
- it('coerces non-array payloads to an empty list', async () => {
+ it('does not treat a non-array payload as a successful list', async () => {
(asaw as jest.Mock).mockResolvedValue([null, '<html>login</html>']);
const successCb = jest.fn();
await fetchDatabaseConfigList(successCb);
expect(successCb).toHaveBeenCalledWith([]);
expect(mockSetList).toHaveBeenCalledWith([]);
+ expect(toast.error).toHaveBeenCalled();
+ });
+
+ it('ignores a response after the current project has changed', async () => {
+ let resolveAsaw: (value: unknown) => void = () => {};
+ (asaw as jest.Mock).mockReturnValue(
+ new Promise((resolve) => {
+ resolveAsaw = resolve;
+ })
+ );
+ const successCb = jest.fn();
+
+ const pending = fetchDatabaseConfigList(successCb, { projectId: 'proj-1' });
+ (useRootStore.getState as jest.Mock).mockReturnValue(makeGetState([], 'proj-2'));
+ resolveAsaw([null, [{ id: 'db1' }]]);
+ await pending;
+
+ expect(successCb).not.toHaveBeenCalled();
+ expect(mockSetList).not.toHaveBeenCalled();
+ });
+
+ it('still applies the list when the current project has not been set yet', async () => {
+ (useRootStore.getState as jest.Mock).mockReturnValue(makeGetState([], null));
+ (asaw as jest.Mock).mockResolvedValue([null, [{ id: 'db1' }]]);
+ const successCb = jest.fn();
+
+ await fetchDatabaseConfigList(successCb, { projectId: 'proj-1' });
+
+ expect(successCb).toHaveBeenCalledWith([{ id: 'db1' }]);
+ expect(mockSetList).toHaveBeenCalledWith([{ id: 'db1' }]);
});
});
@@ -217,3 +253,15 @@ describe('deleteDatabaseConfig', () => {
expect(mockSetList).toHaveBeenCalledWith([]);
});
});
+
+describe('projectHasDatabaseConfig', () => {
+ it('is false for missing or empty lists', () => {
+ expect(projectHasDatabaseConfig(undefined)).toBe(false);
+ expect(projectHasDatabaseConfig(null)).toBe(false);
+ expect(projectHasDatabaseConfig([])).toBe(false);
+ });
+
+ it('is true when the project has at least one database config', () => {
+ expect(projectHasDatabaseConfig([{ id: 'db1' }])).toBe(true);
+ });
+});
diff --git a/src/client/src/__tests__/utils/hooks/use-project-database-setup.test.ts b/src/client/src/__tests__/utils/hooks/use-project-database-setup.test.ts
new file mode 100644
index 00000000..307b8b46
--- /dev/null
+++ b/src/client/src/__tests__/utils/hooks/use-project-database-setup.test.ts
@@ -0,0 +1,139 @@
+/**
+ * @jest-environment jsdom
+ */
+
+const fetchDatabaseConfigList = jest.fn().mockResolvedValue(undefined);
+
+jest.mock("@/helpers/client/database-config", () => ({
+ fetchDatabaseConfigList: (...args: any[]) => fetchDatabaseConfigList(...args),
+ projectHasDatabaseConfig: (list: unknown[] | undefined | null) =>
+ Array.isArray(list) && list.length > 0,
+}));
+
+jest.mock("@/store", () => ({
+ useRootStore: jest.fn(),
+}));
+
+import { renderHook } from "@testing-library/react";
+import { useRootStore } from "@/store";
+import {
+ useProjectDatabaseSetup,
+ useWorkspaceSetup,
+} from "@/utils/hooks/use-project-database-setup";
+
+function mockStore(
+ overrides: {
+ currentOrg?: { id: string } | undefined;
+ organisationList?: unknown[] | undefined;
+ isOrganisationLoading?: boolean;
+ currentProject?: { id: string } | undefined;
+ projects?: unknown[] | undefined;
+ isProjectLoading?: boolean;
+ list?: unknown[] | undefined;
+ isLoading?: boolean;
+ } = {}
+) {
+ const state = {
+ organisation: {
+ current:
+ "currentOrg" in overrides ? overrides.currentOrg : { id: "org-1" },
+ list:
+ "organisationList" in overrides
+ ? overrides.organisationList
+ : [{ id: "org-1" }],
+ isLoading: overrides.isOrganisationLoading ?? false,
+ },
+ project: {
+ current:
+ "currentProject" in overrides ? overrides.currentProject : { id: "proj-1" },
+ list:
+ "projects" in overrides
+ ? overrides.projects
+ : [{ id: "proj-1" }],
+ isLoading: overrides.isProjectLoading ?? false,
+ },
+ databaseConfig: {
+ list: overrides.list,
+ isLoading: overrides.isLoading ?? false,
+ },
+ };
+ (useRootStore as unknown as jest.Mock).mockImplementation((selector) =>
+ selector(state)
+ );
+}
+
+describe("useProjectDatabaseSetup", () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ });
+
+ it("fetches database configs for the current project", () => {
+ mockStore({ list: [] });
+ renderHook(() => useProjectDatabaseSetup());
+ expect(fetchDatabaseConfigList).toHaveBeenCalledWith(expect.any(Function), {
+ projectId: "proj-1",
+ });
+ });
+
+ it("does not fetch when there is no current project", () => {
+ mockStore({ currentProject: undefined, list: undefined });
+ renderHook(() => useProjectDatabaseSetup());
+ expect(fetchDatabaseConfigList).not.toHaveBeenCalled();
+ });
+
+ it("treats an empty list as incomplete setup", () => {
+ mockStore({ list: [] });
+ const { result } = renderHook(() => useProjectDatabaseSetup());
+ expect(result.current.hasDbConfig).toBe(false);
+ expect(result.current.isDatabaseSetupLoading).toBe(false);
+ });
+
+ it("treats a populated list as complete setup", () => {
+ mockStore({ list: [{ id: "db-1" }] });
+ const { result } = renderHook(() => useProjectDatabaseSetup());
+ expect(result.current.hasDbConfig).toBe(true);
+ });
+
+ it("keeps setup loading while the project config list is still undefined", () => {
+ mockStore({ list: undefined, isLoading: false });
+ const { result } = renderHook(() => useProjectDatabaseSetup());
+ expect(result.current.isDatabaseSetupLoading).toBe(true);
+ expect(result.current.hasDbConfig).toBe(false);
+ });
+});
+
+describe("useWorkspaceSetup", () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ });
+
+ it("stays loading while organisation list has not hydrated", () => {
+ mockStore({
+ organisationList: undefined,
+ isOrganisationLoading: false,
+ currentOrg: undefined,
+ currentProject: undefined,
+ projects: undefined,
+ list: undefined,
+ });
+ const { result } = renderHook(() => useWorkspaceSetup());
+ expect(result.current.isSetupLoading).toBe(true);
+ });
+
+ it("stays loading while the current organisation's projects are still undefined", () => {
+ mockStore({
+ projects: undefined,
+ list: [{ id: "db-1" }],
+ });
+ const { result } = renderHook(() => useWorkspaceSetup());
+ expect(result.current.isSetupLoading).toBe(true);
+ });
+
+ it("is ready once organisation, project, and database config lists have loaded", () => {
+ mockStore({ list: [{ id: "db-1" }] });
+ const { result } = renderHook(() => useWorkspaceSetup());
+ expect(result.current.isSetupLoading).toBe(false);
+ expect(result.current.hasDbConfig).toBe(true);
+ expect(result.current.hasProject).toBe(true);
+ });
+});
diff --git a/src/client/src/app/(playground)/chat/page.tsx b/src/client/src/app/(playground)/chat/page.tsx
index b35e202c..76314e13 100644
--- a/src/client/src/app/(playground)/chat/page.tsx
+++ b/src/client/src/app/(playground)/chat/page.tsx
@@ -1,56 +1,24 @@
"use client";
-import { useEffect, useState } from "react";
-import { useRouter, useSearchParams } from "next/navigation";
+import { useEffect } from "react";
+import { useSearchParams } from "next/navigation";
import ChatLayout from "@/components/(playground)/chat/chat-layout";
import { RequestProvider } from "@/components/(playground)/request/request-context";
-import { useRootStore } from "@/store";
-import { getCurrentOrganisation } from "@/selectors/organisation";
-import {
- getCurrentProject,
- getProjectIsLoading,
- getProjectList,
-} from "@/selectors/project";
+import { useWorkspaceSetup } from "@/utils/hooks/use-project-database-setup";
import { fetchProjectList } from "@/helpers/client/project";
import Loader from "@/components/common/loader";
export default function ChatPage() {
- const router = useRouter();
const searchParams = useSearchParams();
const conversationId = searchParams.get("id");
const initialPrompt = searchParams.get("prompt");
- const currentOrg = useRootStore(getCurrentOrganisation);
- const projects = useRootStore(getProjectList);
- const currentProject = useRootStore(getCurrentProject);
- const isProjectLoading = useRootStore(getProjectIsLoading);
- const [hasDbConfig, setHasDbConfig] = useState<boolean>();
- const hasProject = Boolean(currentProject?.id && (projects?.length || 0) > 0);
- const isSetupLoading =
- isProjectLoading ||
- hasDbConfig === undefined ||
- projects === undefined;
+ const { currentOrg, isSetupLoading } = useWorkspaceSetup();
useEffect(() => {
if (currentOrg?.id) fetchProjectList(currentOrg.id);
}, [currentOrg?.id]);
- useEffect(() => {
- if (currentProject?.id) {
- setHasDbConfig(undefined);
- fetch("/api/connectors")
- .then((response) => response.ok ? response.json() : { connectors: [] })
- .then((body) => setHasDbConfig((body.connectors || []).some((connector: { type?: string }) => connector.type === "clickhouse")))
- .catch(() => setHasDbConfig(false));
- }
- }, [currentProject?.id]);
-
- useEffect(() => {
- if (!isSetupLoading && (!currentOrg?.id || !hasProject || !hasDbConfig)) {
- router.replace("/onboarding");
- }
- }, [currentOrg?.id, hasDbConfig, hasProject, isSetupLoading, router]);
-
- if (isSetupLoading || !hasProject || !hasDbConfig) {
+ if (isSetupLoading) {
return (
<div className="flex h-full w-full items-center justify-center">
<Loader />
diff --git a/src/client/src/app/(playground)/home/page.tsx b/src/client/src/app/(playground)/home/page.tsx
index 0c346791..5d95e010 100644
--- a/src/client/src/app/(playground)/home/page.tsx
+++ b/src/client/src/app/(playground)/home/page.tsx
@@ -3,18 +3,13 @@
import Filter from "@/components/(playground)/filter";
import { useEffect, useMemo, useState } from "react";
import useFetchWrapper from "@/utils/hooks/useFetchWrapper";
-import { useRouter, useSearchParams } from "next/navigation";
+import { useSearchParams } from "next/navigation";
import Dashboard, {
DashboardConfig,
} from "../../../components/(playground)/manage-dashboard/board-creator";
import { useRootStore } from "@/store";
import { getFilterDetails } from "@/selectors/filter";
-import { getCurrentOrganisation } from "@/selectors/organisation";
-import {
- getCurrentProject,
- getProjectIsLoading,
- getProjectList,
-} from "@/selectors/project";
+import { useWorkspaceSetup } from "@/utils/hooks/use-project-database-setup";
import { getFilterParamsForDashboard } from "@/helpers/client/filter";
import Loader from "@/components/common/loader";
import { usePageHeader } from "@/selectors/page";
@@ -24,13 +19,8 @@ import { toast } from "sonner";
import BoardList from "./board-list";
export default function DashboardPage() {
- const router = useRouter();
const filter = useRootStore(getFilterDetails);
- const currentOrg = useRootStore(getCurrentOrganisation);
- const projects = useRootStore(getProjectList);
- const currentProject = useRootStore(getCurrentProject);
- const isProjectLoading = useRootStore(getProjectIsLoading);
- const [hasDbConfig, setHasDbConfig] = useState<boolean>();
+ const { hasDbConfig, hasProject, isSetupLoading } = useWorkspaceSetup();
const { fireRequest, isLoading } = useFetchWrapper();
const { fireRequest: fireRunQuery } = useFetchWrapper();
const [initialConfig, setInitialConfig] = useState<
@@ -40,27 +30,6 @@ export default function DashboardPage() {
const dashboardId = searchParams.get("dashboardId");
const { setHeader } = usePageHeader();
const posthog = usePostHog();
- const hasProject = Boolean(currentProject?.id && (projects?.length || 0) > 0);
- const isSetupLoading =
- isProjectLoading ||
- hasDbConfig === undefined ||
- projects === undefined;
-
- useEffect(() => {
- if (currentProject?.id) {
- setHasDbConfig(undefined);
- fetch("/api/connectors")
- .then((response) => response.ok ? response.json() : { connectors: [] })
- .then((body) => setHasDbConfig((body.connectors || []).some((connector: { type?: string }) => connector.type === "clickhouse")))
- .catch(() => setHasDbConfig(false));
- }
- }, [currentProject?.id]);
-
- useEffect(() => {
- if (!isSetupLoading && (!currentOrg?.id || !hasProject || !hasDbConfig)) {
- router.replace("/onboarding");
- }
- }, [currentOrg?.id, hasDbConfig, hasProject, isSetupLoading, router]);
useEffect(() => {
if (isSetupLoading || !hasProject || !hasDbConfig) return;
@@ -127,7 +96,7 @@ export default function DashboardPage() {
return data.response;
};
- if (isSetupLoading || !hasProject || !hasDbConfig) {
+ if (isSetupLoading) {
return (
<div className="flex h-full w-full items-center justify-center">
<Loader />
diff --git a/src/client/src/app/(playground)/onboarding/page.tsx b/src/client/src/app/(playground)/onboarding/page.tsx
index 1d56bead..ef5f0d88 100644
--- a/src/client/src/app/(playground)/onboarding/page.tsx
+++ b/src/client/src/app/(playground)/onboarding/page.tsx
@@ -38,10 +38,6 @@ import {
getProjectIsLoading,
getProjectList,
} from "@/selectors/project";
-import {
- getDatabaseConfigList,
- getDatabaseConfigListIsLoading,
-} from "@/selectors/database-config";
import {
acceptInvitation,
declineInvitation,
@@ -49,7 +45,7 @@ import {
fetchPendingInvitations,
} from "@/helpers/client/organisation";
import { fetchProjectList } from "@/helpers/client/project";
-import { fetchDatabaseConfigList } from "@/helpers/client/database-config";
+import { useProjectDatabaseSetup } from "@/utils/hooks/use-project-database-setup";
import { postData } from "@/utils/api";
import asaw from "@/utils/asaw";
import getMessage from "@/constants/messages";
@@ -156,10 +152,9 @@ export default function OnboardingPage() {
const projects = useRootStore(getProjectList);
const currentProject = useRootStore(getCurrentProject);
const isProjectLoading = useRootStore(getProjectIsLoading);
- const databaseConfigs = useRootStore(getDatabaseConfigList);
- const isDatabaseConfigLoading = useRootStore(getDatabaseConfigListIsLoading);
+ const { databaseConfigs, hasDbConfig, isDatabaseConfigLoading } =
+ useProjectDatabaseSetup();
const hasProject = Boolean(currentProject?.id && (projects?.length || 0) > 0);
- const hasDbConfig = Boolean(databaseConfigs?.length);
const isSetupComplete = Boolean(currentOrg?.id && hasProject && hasDbConfig);
const isInitialising =
!currentOrg?.id &&
@@ -185,12 +180,6 @@ export default function OnboardingPage() {
}
}, [currentOrg?.id]);
- useEffect(() => {
- if (currentProject?.id) {
- fetchDatabaseConfigList(() => {});
- }
- }, [currentProject?.id]);
-
const handleCreateProject = async () => {
if (!currentOrg?.id || !projectName.trim()) return;
setIsCreatingProject(true);
@@ -445,7 +434,7 @@ export default function OnboardingPage() {
>
{isSetupComplete ? (
<Button size="sm" className="h-9" onClick={() => currentOrg?.id && setCurrentOrgAndComplete(currentOrg.id)} disabled={isCompleting}>
- {isCompleting ? messages.LOADING : "Finish setup"}
+ {isCompleting ? messages.LOADING : messages.HOME_SETUP_FINISH}
</Button>
) : null}
</TimelineStep>
diff --git a/src/client/src/constants/messages/en.ts b/src/client/src/constants/messages/en.ts
index 45ab3718..bd9ee566 100644
--- a/src/client/src/constants/messages/en.ts
+++ b/src/client/src/constants/messages/en.ts
@@ -1304,6 +1304,7 @@ export const MANAGE_DB_CONFIG = "Manage DB Config";
export const MODIFYING_DB_CONFIG = "Modifying database config...";
export const DB_CONFIG_UPDATED = "Database config updated";
export const DB_CONFIG_UPDATE_FAILED = "Database config update failed";
+export const DB_CONFIG_LIST_FAILED = "Failed to load database configs";
export const DB_CONFIG_SET_ACTIVE = (name: string) =>
`Database config: ${name} is being set active`;
export const DB_CONFIG_FIELD_CONFIG_NAME = "Config Name";
@@ -1480,6 +1481,7 @@ export const HOME_SETUP_DB_CONFIG_DESCRIPTION =
export const HOME_SETUP_READY_STEP = "Devtool unlocked";
export const HOME_SETUP_READY_DESCRIPTION =
"Your AI devtool is ready. Explore traces, prompts, evals, and the rest of the workspace.";
+export const HOME_SETUP_FINISH = "Finish setup";
export const SLUG = "Slug";
export const USER_ALREADY_INVITED = "User has already been invited to this organisation";
export const INVITATION_NOT_FOR_YOU = "This invitation is not for you";
diff --git a/src/client/src/helpers/client/database-config.ts b/src/client/src/helpers/client/database-config.ts
index 0bc90be5..31117d17 100644
--- a/src/client/src/helpers/client/database-config.ts
+++ b/src/client/src/helpers/client/database-config.ts
@@ -1,23 +1,43 @@
import { DatabaseConfigWithActive } from "@/constants/dbConfig";
+import getMessage from "@/constants/messages";
import { useRootStore } from "@/store";
import { deleteData, getData } from "@/utils/api";
import asaw from "@/utils/asaw";
import { toast } from "sonner";
+export const projectHasDatabaseConfig = (
+ list: unknown[] | undefined | null
+): boolean => Array.isArray(list) && list.length > 0;
+
export const fetchDatabaseConfigList = async (
- successCb: (data: any[]) => void
+ successCb: (data: any[]) => void,
+ options: { projectId?: string } = {}
) => {
+ const requestedProjectId = options.projectId;
useRootStore.getState().databaseConfig.setIsLoading(true);
- const [, data] = await asaw(
+ const [err, data] = await asaw(
getData({
method: "GET",
url: "/api/db-config",
})
);
- const list = Array.isArray(data) ? data : [];
- successCb(list);
- useRootStore.getState().databaseConfig.setList(list);
+ const currentProjectId = useRootStore.getState().project?.current?.id;
+ if (requestedProjectId && currentProjectId && currentProjectId !== requestedProjectId) {
+ return;
+ }
+
+ if (err || !Array.isArray(data)) {
+ toast.error(err || getMessage().DB_CONFIG_LIST_FAILED, {
+ id: "db-config-list",
+ });
+ successCb([]);
+ useRootStore.getState().databaseConfig.setList([]);
+ return;
+ }
+
+ successCb(data);
+ useRootStore.getState().databaseConfig.setList(data);
};
export const pingActiveDatabaseConfig = async () => {
diff --git a/src/client/src/utils/hooks/use-project-database-setup.ts b/src/client/src/utils/hooks/use-project-database-setup.ts
new file mode 100644
index 00000000..5d0a0f5d
--- /dev/null
+++ b/src/client/src/utils/hooks/use-project-database-setup.ts
@@ -0,0 +1,69 @@
+"use client";
+
+import { useEffect } from "react";
+import {
+ fetchDatabaseConfigList,
+ projectHasDatabaseConfig,
+} from "@/helpers/client/database-config";
+import {
+ getDatabaseConfigList,
+ getDatabaseConfigListIsLoading,
+} from "@/selectors/database-config";
+import {
+ getCurrentOrganisation,
+ getOrganisationIsLoading,
+ getOrganisationList,
+} from "@/selectors/organisation";
+import {
+ getCurrentProject,
+ getProjectIsLoading,
+ getProjectList,
+} from "@/selectors/project";
+import { useRootStore } from "@/store";
+
+export function useProjectDatabaseSetup() {
+ const currentProject = useRootStore(getCurrentProject);
+ const databaseConfigs = useRootStore(getDatabaseConfigList);
+ const isDatabaseConfigLoading = useRootStore(getDatabaseConfigListIsLoading);
+
+ useEffect(() => {
+ if (!currentProject?.id) {
+ return;
+ }
+
+ void fetchDatabaseConfigList(() => {}, { projectId: currentProject.id });
+ }, [currentProject?.id]);
+
+ return {
+ databaseConfigs,
+ hasDbConfig: projectHasDatabaseConfig(databaseConfigs),
+ isDatabaseConfigLoading,
+ isDatabaseSetupLoading:
+ isDatabaseConfigLoading ||
+ (Boolean(currentProject?.id) && databaseConfigs === undefined),
+ };
+}
+
+export function useWorkspaceSetup() {
+ const currentOrg = useRootStore(getCurrentOrganisation);
+ const organisationList = useRootStore(getOrganisationList);
+ const isOrganisationLoading = useRootStore(getOrganisationIsLoading);
+ const projects = useRootStore(getProjectList);
+ const currentProject = useRootStore(getCurrentProject);
+ const isProjectLoading = useRootStore(getProjectIsLoading);
+ const { hasDbConfig, isDatabaseSetupLoading } = useProjectDatabaseSetup();
+ const hasProject = Boolean(currentProject?.id && (projects?.length || 0) > 0);
+ const isSetupLoading =
+ isOrganisationLoading ||
+ organisationList === undefined ||
+ isProjectLoading ||
+ (Boolean(currentOrg?.id) && projects === undefined) ||
+ isDatabaseSetupLoading;
+
+ return {
+ currentOrg,
+ hasDbConfig,
+ hasProject,
+ isSetupLoading,
+ };
+}