The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
feat: add git settings modal to data studio (#67178)
Edward Pagetff4f2bf95667
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/app/pages/DataStudioLayout/DataStudioLayout.setup.spec.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/app/pages/DataStudioLayout/DataStudioLayout.setup.spec.tsxnew file mode 100644index 00000000000..bcfb651c51f--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/app/pages/DataStudioLayout/DataStudioLayout.setup.spec.tsx@@ -0,0 +1,184 @@+import fetchMock from "fetch-mock";++import {+ setupPropertiesEndpoints,+ setupRemoteSyncEndpoints,+ setupSettingsEndpoints,+ setupUserKeyValueEndpoints,+} from "__support__/server-mocks";+import { mockSettings } from "__support__/settings";+import { renderWithProviders } from "__support__/ui";+import { initializePlugin as initializeDependenciesPlugin } from "metabase-enterprise/dependencies";+import { initializePlugin as initializeFeatureLevelPermissionsPlugin } from "metabase-enterprise/feature_level_permissions";+import { initializePlugin as initializeRemoteSyncPlugin } from "metabase-enterprise/remote_sync";+import { initializePlugin as initializeTransformsPlugin } from "metabase-enterprise/transforms";+import type { RemoteSyncEntity } from "metabase-types/api";+import {+ createMockCollection,+ createMockSettings,+ createMockTokenFeatures,+ createMockUser,+} from "metabase-types/api/mocks";+import { createMockRemoteSyncEntity } from "metabase-types/api/mocks/remote-sync";+import { createMockState } from "metabase-types/store/mocks";++import { DataStudioLayout } from "./DataStudioLayout";++interface SetupEndpointsOpts {+ isNavbarOpened?: boolean;+ remoteSyncEnabled?: boolean;+ remoteSyncBranch?: string | null;+ remoteSyncType?: "read-only" | "read-write";+ hasDirtyChanges?: boolean;+}++const setupEndpoints = ({+ isNavbarOpened = true,+ remoteSyncEnabled = false,+ remoteSyncBranch = null,+ remoteSyncType = "read-write",+ hasDirtyChanges = false,+}: SetupEndpointsOpts = {}) => {+ // Mock session properties for settings (used by useAdminSetting and useSetting)+ setupPropertiesEndpoints(+ createMockSettings({+ "remote-sync-enabled": remoteSyncEnabled,+ "remote-sync-branch": remoteSyncBranch,+ "remote-sync-type": remoteSyncType,+ }),+ );++ // Mock settings details endpoint+ setupSettingsEndpoints([]);++ // Mock collection tree endpoint (used by useHasLibraryDirtyChanges)+ fetchMock.get("path:/api/collection/tree", () => {+ if (hasDirtyChanges) {+ return [+ createMockCollection({+ id: 1,+ name: "Library",+ type: "library",+ }),+ ];+ }+ return [];+ });++ const dirty: RemoteSyncEntity[] = hasDirtyChanges+ ? [createMockRemoteSyncEntity({ id: 1, model: "card", collection_id: 1 })]+ : [];+ const branches = remoteSyncBranch ? [remoteSyncBranch] : [];+ setupRemoteSyncEndpoints({ dirty, branches });++ setupUserKeyValueEndpoints({+ namespace: "data_studio",+ key: "isNavbarOpened",+ value: isNavbarOpened,+ });++ // Mock user key value PUT endpoint+ fetchMock.put(+ "express:/api/user-key-value/namespace/data_studio/key/isNavbarOpened",+ { status: 200 },+ );+};++const createStoreState = ({+ isAdmin = true,+ remoteSyncEnabled = false,+ remoteSyncBranch = null as string | null,+ remoteSyncType = "read-write" as "read-only" | "read-write",+ canAccessDataModel = true,+}: {+ isAdmin?: boolean;+ remoteSyncEnabled?: boolean;+ remoteSyncBranch?: string | null;+ remoteSyncType?: "read-only" | "read-write";+ canAccessDataModel?: boolean;+} = {}) => {+ return createMockState({+ currentUser: createMockUser({+ is_superuser: isAdmin,+ permissions: {+ can_access_data_model: canAccessDataModel,+ can_access_db_details: false,+ },+ }),+ settings: mockSettings({+ "remote-sync-enabled": remoteSyncEnabled,+ "remote-sync-branch": remoteSyncBranch,+ "remote-sync-type": remoteSyncType,+ "token-features": createMockTokenFeatures({+ remote_sync: true,+ advanced_permissions: true,+ }),+ }),+ });+};++interface SetupOpts {+ isGitSyncVisible?: boolean;+ isGitSettingsVisible?: boolean;+ isAdmin?: boolean;+ hasDirtyChanges?: boolean;+ isNavbarOpened?: boolean;+}++export const setup = ({+ isGitSyncVisible = false,+ isGitSettingsVisible = false,+ isAdmin = true,+ hasDirtyChanges = false,+ isNavbarOpened = true,+}: SetupOpts = {}) => {+ // Derive API state from the visibility flags+ // useGitSyncVisible returns isVisible when: isAdmin && remoteSyncEnabled && currentBranch && syncType === "read-write"+ // useGitSettingsVisible returns true when: isAdmin && !remoteSyncEnabled+ let remoteSyncEnabled: boolean;+ let remoteSyncBranch: string | null;+ const remoteSyncType = "read-write" as const;++ if (isGitSyncVisible) {+ // Git sync visible requires: enabled + branch + admin + read-write+ remoteSyncEnabled = true;+ remoteSyncBranch = "main";+ } else if (isGitSettingsVisible) {+ // Git settings visible requires: admin + NOT enabled+ remoteSyncEnabled = false;+ remoteSyncBranch = null;+ } else {+ // Neither visible - could be enabled with no branch, or not admin+ remoteSyncEnabled = true;+ remoteSyncBranch = null;+ }++ setupEndpoints({+ isNavbarOpened,+ remoteSyncEnabled,+ remoteSyncBranch,+ remoteSyncType,+ hasDirtyChanges,+ });++ renderWithProviders(+ <DataStudioLayout>+ <div data-testid="content">{"Content"}</div>+ </DataStudioLayout>,+ {+ storeInitialState: createStoreState({+ isAdmin,+ remoteSyncEnabled,+ remoteSyncBranch,+ remoteSyncType,+ canAccessDataModel: isAdmin,+ }),+ withRouter: false,+ },+ );++ initializeRemoteSyncPlugin();+ initializeFeatureLevelPermissionsPlugin();+ initializeTransformsPlugin();+ initializeDependenciesPlugin();+};diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/app/pages/DataStudioLayout/DataStudioLayout.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/app/pages/DataStudioLayout/DataStudioLayout.tsxindex d2e285716fb..2c9fcb21ed9 100644--- a/enterprise/frontend/src/metabase-enterprise/data-studio/app/pages/DataStudioLayout/DataStudioLayout.tsx+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/app/pages/DataStudioLayout/DataStudioLayout.tsx@@ -1,5 +1,5 @@import cx from "classnames";-import type { ReactNode } from "react";+import { type ReactNode, useState } from "react";import { t } from "ttag";import DataStudioLogo from "assets/img/data-studio-logo.svg";@@ -76,6 +76,7 @@ function DataStudioNav({ isNavbarOpened, onNavbarToggle }: DataStudioNavProps) {PLUGIN_TRANSFORMS.canAccessTransforms,);const hasDirtyChanges = PLUGIN_REMOTE_SYNC.useHasLibraryDirtyChanges();+ const [isGitSettingsOpen, setIsGitSettingsOpen] = useState(false);const currentTab = getCurrentTab(pathname);@@ -146,6 +147,10 @@ function DataStudioNav({ isNavbarOpened, onNavbarToggle }: DataStudioNavProps) {)}</Stack><Stack gap="0.75rem">+ <PLUGIN_REMOTE_SYNC.GitSyncSetupMenuItem+ isNavbarOpened={isNavbarOpened}+ onClick={() => setIsGitSettingsOpen(true)}+ />{canAccessTransforms && (<DataStudioTablabel={t`Jobs`}@@ -171,6 +176,10 @@ function DataStudioNav({ isNavbarOpened, onNavbarToggle }: DataStudioNavProps) {showLabel={isNavbarOpened}/></Stack>+ <PLUGIN_REMOTE_SYNC.GitSettingsModal+ isOpen={isGitSettingsOpen}+ onClose={() => setIsGitSettingsOpen(false)}+ /></Stack>);}diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/app/pages/DataStudioLayout/DataStudioLayout.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/app/pages/DataStudioLayout/DataStudioLayout.unit.spec.tsxnew file mode 100644index 00000000000..d49fa8490d4--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/app/pages/DataStudioLayout/DataStudioLayout.unit.spec.tsx@@ -0,0 +1,139 @@+import userEvent from "@testing-library/user-event";+import fetchMock from "fetch-mock";++import { screen, waitFor } from "__support__/ui";++import { setup } from "./DataStudioLayout.setup.spec";++describe("DataStudioLayout", () => {+ beforeEach(() => {+ fetchMock.removeRoutes();+ fetchMock.clearHistory();+ jest.clearAllMocks();+ });++ afterEach(() => {+ jest.restoreAllMocks();+ });++ describe("Set up git sync button", () => {+ it("should show Set up git sync button when git settings is visible", async () => {+ setup({ isGitSettingsVisible: true });++ await waitFor(() => {+ expect(screen.getByTestId("data-studio-nav")).toBeInTheDocument();+ });++ expect(screen.getByLabelText("Set up git sync")).toBeInTheDocument();+ });++ it("should hide Set up git sync button when git settings is not visible", async () => {+ setup({ isGitSettingsVisible: false });++ await waitFor(() => {+ expect(screen.getByTestId("data-studio-nav")).toBeInTheDocument();+ });++ expect(+ screen.queryByLabelText("Set up git sync"),+ ).not.toBeInTheDocument();+ });++ it("should open modal when Set up git sync button is clicked", async () => {+ setup({ isGitSettingsVisible: true });++ await waitFor(() => {+ expect(screen.getByTestId("data-studio-nav")).toBeInTheDocument();+ });++ const gitSettingsButton = screen.getByLabelText("Set up git sync");+ await userEvent.click(gitSettingsButton);++ await waitFor(() => {+ expect(+ screen.getByText("Set up remote sync for your Library"),+ ).toBeInTheDocument();+ });+ });++ it("should close modal when onClose is called", async () => {+ setup({ isGitSettingsVisible: true });++ await waitFor(() => {+ expect(screen.getByTestId("data-studio-nav")).toBeInTheDocument();+ });++ // Open the modal+ const gitSettingsButton = screen.getByLabelText("Set up git sync");+ await userEvent.click(gitSettingsButton);++ await waitFor(() => {+ expect(+ screen.getByText("Set up remote sync for your Library"),+ ).toBeInTheDocument();+ });++ // Close the modal by pressing escape+ await userEvent.keyboard("{Escape}");++ await waitFor(() => {+ expect(+ screen.queryByText("Set up remote sync for your Library"),+ ).not.toBeInTheDocument();+ });+ });++ it("should show Set up git sync text when sidebar is expanded", async () => {+ setup({ isGitSettingsVisible: true, isNavbarOpened: true });++ await waitFor(() => {+ expect(screen.getByTestId("data-studio-nav")).toBeInTheDocument();+ });++ expect(screen.getByText("Set up git sync")).toBeInTheDocument();+ });+ });++ describe("sidebar rendering", () => {+ it("should render the sidebar with navigation tabs", async () => {+ setup({ isGitSyncVisible: true });++ await waitFor(() => {+ expect(screen.getByTestId("data-studio-nav")).toBeInTheDocument();+ });++ expect(screen.getByText("Library")).toBeInTheDocument();+ expect(screen.getByText("Exit")).toBeInTheDocument();+ });++ it("should render GitSyncAppBarControls when sidebar is expanded", async () => {+ setup({ isGitSyncVisible: true, isNavbarOpened: true });++ await waitFor(() => {+ expect(screen.getByTestId("data-studio-nav")).toBeInTheDocument();+ });++ expect(screen.getByTestId("git-sync-controls")).toBeInTheDocument();+ });++ it("should not render GitSyncAppBarControls when sidebar is collapsed", async () => {+ setup({ isGitSyncVisible: true, isNavbarOpened: false });++ await waitFor(() => {+ expect(screen.getByTestId("data-studio-nav")).toBeInTheDocument();+ });++ expect(screen.queryByTestId("git-sync-controls")).not.toBeInTheDocument();+ });++ it("should render content area", async () => {+ setup({ isGitSyncVisible: false });++ await waitFor(() => {+ expect(screen.getByTestId("data-studio-nav")).toBeInTheDocument();+ });++ expect(screen.getByTestId("content")).toBeInTheDocument();+ });+ });+});diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/analytics.ts b/enterprise/frontend/src/metabase-enterprise/remote_sync/analytics.tsindex 1e3d84229ce..0d9be6f4fb2 100644--- a/enterprise/frontend/src/metabase-enterprise/remote_sync/analytics.ts+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/analytics.ts@@ -50,10 +50,14 @@ export const trackPushChanges = ({});};-export const trackRemoteSyncSettingsChanged = () => {+export const trackRemoteSyncSettingsChanged = ({+ triggeredFrom,+}: {+ triggeredFrom: "admin-settings" | "data-studio";+}) => {trackSimpleEvent({event: "remote_sync_settings_changed",- triggered_from: "admin-settings",+ triggered_from: triggeredFrom,});};diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/GitSettingsModal/GitSettingsModal.tsx b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/GitSettingsModal/GitSettingsModal.tsxnew file mode 100644index 00000000000..d3f5f4cb64e--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/GitSettingsModal/GitSettingsModal.tsx@@ -0,0 +1,39 @@+import { t } from "ttag";++import { Modal, Text } from "metabase/ui";++import { RemoteSyncSettingsForm } from "../RemoteSyncAdminSettings";++export interface GitSettingsModalProps {+ isOpen: boolean;+ onClose: () => void;+}++export const GitSettingsModal = ({+ isOpen,+ onClose,+}: GitSettingsModalProps) => {+ return (+ <Modal+ opened={isOpen}+ onClose={onClose}+ withCloseButton={false}+ title={+ <Text fw={700} size="1.5rem">+ {t`Set up remote sync for your Library`}+ </Text>+ }+ size="xl"+ padding="xl"+ >+ <Text c="text-medium" size="md" fw={400} lh="1.25rem" mb="lg">+ {t`Keep your Library and transforms safely backed up in Git.`}+ </Text>+ <RemoteSyncSettingsForm+ onCancel={onClose}+ onSaveSuccess={onClose}+ variant="settings-modal"+ />+ </Modal>+ );+};diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/GitSettingsModal/GitSettingsModal.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/GitSettingsModal/GitSettingsModal.unit.spec.tsxnew file mode 100644index 00000000000..b35752451d9--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/GitSettingsModal/GitSettingsModal.unit.spec.tsx@@ -0,0 +1,78 @@+import userEvent from "@testing-library/user-event";+import fetchMock from "fetch-mock";++import {+ setupPropertiesEndpoints,+ setupRootCollectionItemsEndpoint,+ setupSettingsEndpoints,+} from "__support__/server-mocks";+import { renderWithProviders, screen, waitFor } from "__support__/ui";+import { createMockSettings } from "metabase-types/api/mocks";++import { GitSettingsModal } from "./GitSettingsModal";++interface SetupOpts {+ isOpen?: boolean;+}++const setup = ({ isOpen = true }: SetupOpts = {}) => {+ const onClose = jest.fn();+ setupPropertiesEndpoints(createMockSettings());+ setupSettingsEndpoints([]);+ fetchMock.get("express:/api/ee/library", { data: null });+ fetchMock.get("path:/api/ee/remote-sync/dirty", { dirty: [] });+ fetchMock.put("path:/api/ee/remote-sync/settings", { success: true });+ setupRootCollectionItemsEndpoint({ rootCollectionItems: [] });++ renderWithProviders(<GitSettingsModal isOpen={isOpen} onClose={onClose} />);++ return { onClose };+};++describe("GitSettingsModal", () => {+ beforeEach(() => {+ fetchMock.removeRoutes();+ fetchMock.clearHistory();+ });++ describe("modal rendering", () => {+ it("should render modal when isOpen is true", async () => {+ setup({ isOpen: true });++ await waitFor(() => {+ expect(screen.getByRole("dialog")).toBeInTheDocument();+ });+ // Modal title displays "Set up remote sync for your Library"+ expect(+ screen.getByText("Set up remote sync for your Library"),+ ).toBeInTheDocument();+ // Modal subtitle displays+ expect(+ screen.getByText(+ "Keep your Library and transforms safely backed up in Git.",+ ),+ ).toBeInTheDocument();+ });++ it("should not render modal when isOpen is false", () => {+ setup({ isOpen: false });++ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();+ });+ });++ it("should call onClose when cancel button is clicked", async () => {+ const { onClose } = setup({ isOpen: true });++ expect(+ screen.getByText("Set up remote sync for your Library"),+ ).toBeInTheDocument();++ expect(onClose).not.toHaveBeenCalled();++ const cancelButton = screen.getByRole("button", { name: "Cancel" });+ await userEvent.click(cancelButton);++ expect(onClose).toHaveBeenCalled();+ });+});diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/GitSettingsModal/index.ts b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/GitSettingsModal/index.tsnew file mode 100644index 00000000000..64116489e33--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/GitSettingsModal/index.ts@@ -0,0 +1,2 @@+export { GitSettingsModal } from "./GitSettingsModal";+export type { GitSettingsModalProps } from "./GitSettingsModal";diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/GitSyncSetupMenuItem/GitSyncSetupMenuItem.module.css b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/GitSyncSetupMenuItem/GitSyncSetupMenuItem.module.cssnew file mode 100644index 00000000000..4f9bfabad14--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/GitSyncSetupMenuItem/GitSyncSetupMenuItem.module.css@@ -0,0 +1,21 @@+.icon {+ color: var(--mb-color-text-secondary);+}++.tab {+ display: flex;+ align-items: center;+ gap: 0.5rem;+ position: relative;+ color: var(--mb-color-text-primary);++ &:hover,+ &.selected {+ background-color: var(--mb-color-brand-light);+ color: var(--mb-color-brand);++ .icon {+ color: inherit;+ }+ }+}diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/GitSyncSetupMenuItem/GitSyncSetupMenuItem.tsx b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/GitSyncSetupMenuItem/GitSyncSetupMenuItem.tsxnew file mode 100644index 00000000000..69fcce347e8--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/GitSyncSetupMenuItem/GitSyncSetupMenuItem.tsx@@ -0,0 +1,43 @@+import { t } from "ttag";++import { useSetting } from "metabase/common/hooks";+import { useSelector } from "metabase/lib/redux";+import type { GitSyncSetupMenuItemProps } from "metabase/plugins/types";+import { getUserIsAdmin } from "metabase/selectors/user";+import { FixedSizeIcon, Text, Tooltip, UnstyledButton } from "metabase/ui";++import S from "./GitSyncSetupMenuItem.module.css";++const TOOLTIP_OPEN_DELAY = 1000;++export const GitSyncSetupMenuItem = (props: GitSyncSetupMenuItemProps) => {+ const { isNavbarOpened, onClick } = props;+ const isAdmin = useSelector(getUserIsAdmin);+ const isRemoteSyncEnabled = useSetting("remote-sync-enabled");+ // Only show the "Set up Git Sync" menu item when user is admin and remote sync is not yet enabled+ const isVisible = isAdmin && !isRemoteSyncEnabled;++ if (isVisible) {+ return (+ <Tooltip+ label={t`Set up git sync`}+ position="right"+ openDelay={TOOLTIP_OPEN_DELAY}+ disabled={isNavbarOpened}+ >+ <UnstyledButton+ aria-label={t`Set up git sync`}+ bdrs="md"+ className={S.tab}+ onClick={onClick}+ p="0.5rem"+ >+ <FixedSizeIcon name="gear" className={S.icon} />+ {isNavbarOpened && <Text lh="sm">{t`Set up git sync`}</Text>}+ </UnstyledButton>+ </Tooltip>+ );+ }++ return null;+};diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/GitSyncSetupMenuItem/index.ts b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/GitSyncSetupMenuItem/index.tsnew file mode 100644index 00000000000..f3a3b1d3372--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/GitSyncSetupMenuItem/index.ts@@ -0,0 +1 @@+export { GitSyncSetupMenuItem } from "./GitSyncSetupMenuItem";diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/PullChangesButton.tsx b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/PullChangesButton.tsxindex d533973bbb6..dccc79ee2e3 100644--- a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/PullChangesButton.tsx+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/PullChangesButton.tsx@@ -48,7 +48,7 @@ export const PullChangesButton = (props: PullChangesButtonProps) => {onClick={handlePullChanges}variant="outline">- {t`Pull changes`}+ {t`Pull changes now`}</Button></Tooltip>);diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/RemoteSyncAdminSettings.tsx b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/RemoteSyncAdminSettings.tsxindex 27cf6a606c6..5089982a433 100644--- a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/RemoteSyncAdminSettings.tsx+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/RemoteSyncAdminSettings.tsx@@ -1,440 +1,16 @@-import { useCallback, useMemo, useRef } from "react";-import { jt, t } from "ttag";+import { t } from "ttag";-import {- SettingsPageWrapper,- SettingsSection,-} from "metabase/admin/components/SettingsSection";-import {- useGetAdminSettingsDetailsQuery,- useGetSettingsQuery,- useListCollectionItemsQuery,-} from "metabase/api";-import ExternalLink from "metabase/common/components/ExternalLink";-import { useDocsUrl, useSetting, useToast } from "metabase/common/hooks";-import { useConfirmation } from "metabase/common/hooks/use-confirmation";-import {- Form,- FormErrorMessage,- FormProvider,- FormRadioGroup,- FormSubmitButton,- FormSwitch,- FormTextInput,-} from "metabase/forms";-import { useSelector } from "metabase/lib/redux";-import { getApplicationName } from "metabase/selectors/whitelabel";-import {- Box,- Button,- Flex,- Icon,- Radio,- Stack,- Text,- Tooltip,-} from "metabase/ui";-import { useGetLibraryCollectionQuery } from "metabase-enterprise/api";-import {- useGetRemoteSyncChangesQuery,- useUpdateRemoteSyncSettingsMutation,-} from "metabase-enterprise/api/remote-sync";-import type {- RemoteSyncConfigurationSettings,- SettingDefinition,-} from "metabase-types/api";+import { SettingsPageWrapper } from "metabase/admin/components/SettingsSection";-import {- trackBranchSwitched,- trackRemoteSyncDeactivated,- trackRemoteSyncSettingsChanged,-} from "../../analytics";-import {- AUTO_IMPORT_KEY,- BRANCH_KEY,- COLLECTIONS_KEY,- REMOTE_SYNC_KEY,- REMOTE_SYNC_SCHEMA,- TOKEN_KEY,- TYPE_KEY,- URL_KEY,-} from "../../constants";-import { SharedTenantCollectionsList } from "../SharedTenantCollectionsList";-import { TopLevelCollectionsList } from "../TopLevelCollectionsList";--import { PullChangesButton } from "./PullChangesButton";+import { RemoteSyncSettingsForm } from "./RemoteSyncSettingsForm";export const RemoteSyncAdminSettings = () => {- const { data: settingValues } = useGetSettingsQuery();- const { data: settingDetails } = useGetAdminSettingsDetailsQuery();- const [updateRemoteSyncSettings] = useUpdateRemoteSyncSettingsMutation();- const { data: dirtyData } = useGetRemoteSyncChangesQuery(undefined, {- refetchOnFocus: true,- refetchOnMountOrArgChange: true,- });- const pendingConfirmationSettingsRef =- useRef<RemoteSyncConfigurationSettings | null>(null);-- const isRemoteSyncEnabled = useSetting(REMOTE_SYNC_KEY);- const useTenants = useSetting("use-tenants");- const applicationName = useSelector(getApplicationName);-- // Fetch top-level collections to build initial sync state- const { data: topLevelCollectionsData } = useListCollectionItemsQuery(- { id: "root", models: ["collection"] },- { skip: !isRemoteSyncEnabled },- );-- // Fetch library collection to build initial sync state- const { data: libraryCollectionData } = useGetLibraryCollectionQuery(- undefined,- { skip: !isRemoteSyncEnabled },- );- // Library collection endpoint returns { data: null } when not found- const libraryCollection =- libraryCollectionData && "name" in libraryCollectionData- ? libraryCollectionData- : undefined;-- // Fetch tenant collections to build initial sync state- const { data: tenantCollectionsData } = useListCollectionItemsQuery(- {- id: "root",- namespace: "shared-tenant-collection",- },- { skip: !isRemoteSyncEnabled || !useTenants },- );-- const {- show: showChangeBranchConfirmation,- modalContent: changeBranchConfirmationModal,- } = useConfirmation();- const [sendToast] = useToast();-- const {- show: showDisableConfirmation,- modalContent: disableConfirmationModal,- } = useConfirmation();-- const handleSubmit = useCallback(- async (values: RemoteSyncConfigurationSettings) => {- const didBranchChange =- values[BRANCH_KEY] !== settingValues?.[BRANCH_KEY];-- // Don't send collections when in read-only mode- const settingsToSave =- values[TYPE_KEY] === "read-only"- ? (Object.fromEntries(- Object.entries(values).filter(([key]) => key !== COLLECTIONS_KEY),- ) as RemoteSyncConfigurationSettings)- : values;-- const saveSettings = async (- settings: RemoteSyncConfigurationSettings,- ) => {- try {- await updateRemoteSyncSettings(settings).unwrap();-- trackRemoteSyncSettingsChanged();-- if (- didBranchChange &&- settingValues?.[BRANCH_KEY] &&- values[BRANCH_KEY]- ) {- trackBranchSwitched({- triggeredFrom: "admin-settings",- });- }-- sendToast({ message: t`Settings saved successfully`, icon: "check" });- } catch (error) {- sendToast({- message: t`Settings could not be saved`,- icon: "warning",- });- throw error;- }- };-- if (didBranchChange) {- pendingConfirmationSettingsRef.current = settingsToSave;- showChangeBranchConfirmation({- title: t`Switch branches?`,- message: t`The synced collection will update to match the new branch. Questions that exist in the current branch but not the new one will be removed from any dashboards or content that reference them permanently, even if you switch back.`,- confirmButtonText: t`Continue`,- confirmButtonProps: {- variant: "filled",- color: "danger",- },- onConfirm: async () => {- if (pendingConfirmationSettingsRef.current) {- await saveSettings(pendingConfirmationSettingsRef.current);- pendingConfirmationSettingsRef.current = null;- }- },- onCancel: () => {- pendingConfirmationSettingsRef.current = null;- },- });- return;- }- await saveSettings(settingsToSave);- },- [- settingValues,- updateRemoteSyncSettings,- sendToast,- showChangeBranchConfirmation,- ],- );-- const handleDisable = useCallback(async () => {- showDisableConfirmation({- title: t`Disable Remote Sync?`,- message: t`This will clear all remote sync settings. Any changes made to the Library collection after disabling can be overwritten if you enable sync again.`,- confirmButtonText: t`Disable`,- confirmButtonProps: {- variant: "filled",- color: "danger",- },- onConfirm: async () => {- try {- await updateRemoteSyncSettings({ [URL_KEY]: "" }).unwrap();- trackRemoteSyncDeactivated();- sendToast({ message: t`Remote Sync disabled`, icon: "check" });- } catch (error) {- console.error(error);- sendToast({- message: t`Failed to disable Remote Sync`,- icon: "warning",- });- }- },- });- }, [updateRemoteSyncSettings, sendToast, showDisableConfirmation]);-- const initialValues = useMemo(() => {- const values = REMOTE_SYNC_SCHEMA.cast(settingValues, {- stripUnknown: true,- });- const tokenValue =- settingDetails?.[TOKEN_KEY]?.value ?? settingValues?.[TOKEN_KEY];-- // Build initial collection sync map from server data- const collectionSyncMap: Record<number, boolean> = {};-- // Add library collection- if (libraryCollection) {- collectionSyncMap[libraryCollection.id] =- libraryCollection.is_remote_synced ?? false;- }-- // Add top-level collections (excluding personal)- topLevelCollectionsData?.data- ?.filter((c) => !c.personal_owner_id)- .forEach((collection) => {- collectionSyncMap[collection.id] = collection.is_remote_synced ?? false;- });-- // Add tenant collections- tenantCollectionsData?.data?.forEach((collection) => {- collectionSyncMap[collection.id] = collection.is_remote_synced ?? false;- });-- return {- ...values,- [TOKEN_KEY]: tokenValue,- [COLLECTIONS_KEY]: collectionSyncMap,- };- }, [- settingValues,- settingDetails,- libraryCollection,- topLevelCollectionsData,- tenantCollectionsData,- ]);-- // eslint-disable-next-line no-unconditional-metabase-links-render -- This links only shows for admins.- const { url: docsUrl } = useDocsUrl(- "installation-and-operation/remote-sync",- {- anchor: "remote-sync",- },- );-- const hasUnsyncedChanges = !!dirtyData?.dirty?.length;-return (<SettingsPageWrappertitle={t`Remote Sync`}description={t`Keep your dashboards, questions, and collections safely backed up in Git.`}>- <FormProvider- initialValues={initialValues as RemoteSyncConfigurationSettings}- enableReinitialize- validationSchema={REMOTE_SYNC_SCHEMA}- validationContext={settingValues}- onSubmit={handleSubmit}- >- {({ dirty, values }) => (- <Form disabled={!dirty}>- <Stack gap="xl" maw="52rem">- {!isRemoteSyncEnabled && (- <Text c="text-medium" size="sm">- {jt`Need help setting this up? Check out our ${(- <ExternalLink key="link" href={docsUrl}>- {t`setup guide`}- </ExternalLink>- )}.`}- </Text>- )}-- {/* Section 1: Git Settings */}- <SettingsSection title={t`Git Settings`}>- <FormTextInput- name={URL_KEY}- label={t`Repository URL`}- placeholder="https://github.com/yourcompany/metabase-library.git"- {...getEnvSettingProps(settingDetails?.[URL_KEY])}- />- <FormTextInput- name={TOKEN_KEY}- label={t`Access Token`}- description={t`Personal access token with write permissions`}- type="password"- {...getEnvSettingProps(settingDetails?.[TOKEN_KEY])}- />- </SettingsSection>-- {/* Section 2: Sync Mode for this Instance */}- <SettingsSection title={t`Sync Mode for this Instance`}>- <FormRadioGroup name={TYPE_KEY}>- <Stack mt="sm">- <Tooltip- disabled={!hasUnsyncedChanges}- label={t`You can't switch to Read-only as you have unpublished changes.`}- position="bottom-start"- >- <Box>- <Radio- description={t`Usually you should use this for your production ${applicationName} instance. All synced collections are read-only, and will automatically sync with the specified branch (we'd recommend syncing with main).`}- disabled={hasUnsyncedChanges}- label={t`Read-only`}- value="read-only"- />- </Box>- </Tooltip>- <Radio- value="read-write"- label={t`Read-write`}- description={t`This mode is generally for development or local instances of ${applicationName}. Changes you make to content in synced collections can be pushed and pulled from any git branch.`}- />- </Stack>- </FormRadioGroup>- </SettingsSection>-- {/* Section 3: Branch to sync with (Read-only only) */}- {values?.[TYPE_KEY] === "read-only" && (- <SettingsSection title={t`Branch to sync with`}>- <Flex align="center" gap="md">- <Box style={{ flex: 1 }}>- <FormTextInput- name={BRANCH_KEY}- placeholder="main"- label={`Sync branch`}- {...getEnvSettingProps(settingDetails?.[BRANCH_KEY])}- />- </Box>- <FormSwitch- size="sm"- name={AUTO_IMPORT_KEY}- label={t`Auto-sync with git`}- />- </Flex>- {isRemoteSyncEnabled && (- <Box>- <PullChangesButton- branch={values?.[BRANCH_KEY] || "main"}- dirty={dirty}- forcePull- />- </Box>- )}- </SettingsSection>- )}-- {/* Section 4: Collections to sync */}- {isRemoteSyncEnabled && (- <SettingsSection- title={t`Collections to sync`}- description={t`Choose which collections to sync with git.`}- >- <Stack gap="lg">- <TopLevelCollectionsList />- {useTenants && (- <>- <Text- fw={700}- size="md"- lh="16px"- >{t`Shared collections`}</Text>- <SharedTenantCollectionsList />- </>- )}- </Stack>- </SettingsSection>- )}-- {/* Footer Actions - Outside Sections */}- <Flex justify="space-between" align="center">- <Box>- {isRemoteSyncEnabled && (- <Button- c="error"- variant="subtle"- size="md"- w="12rem"- leftSection={<Icon name="close" />}- onClick={handleDisable}- >- {t`Disable remote sync`}- </Button>- )}- </Box>- <Flex align="center" gap="md">- <FormErrorMessage />- <FormSubmitButton- data-testid="remote-sync-submit-button"- size="md"- w="12rem"- label={- isRemoteSyncEnabled- ? t`Save changes`- : t`Set up Remote Sync`- }- variant="filled"- disabled={isRemoteSyncEnabled ? !dirty : !values?.[URL_KEY]}- />- </Flex>- </Flex>- </Stack>- </Form>- )}- </FormProvider>-- {changeBranchConfirmationModal}- {disableConfirmationModal}+ <RemoteSyncSettingsForm /></SettingsPageWrapper>);};--const getEnvSettingProps = (setting?: SettingDefinition) => {- if (setting?.is_env_setting) {- return {- description: t`Using ${setting.env_name}`,- readOnly: true,- };- }- return {};-};diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/RemoteSyncSettingsForm.setup.spec.tsx b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/RemoteSyncSettingsForm.setup.spec.tsxnew file mode 100644index 00000000000..4bfe932aa7b--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/RemoteSyncSettingsForm.setup.spec.tsx@@ -0,0 +1,131 @@+import fetchMock from "fetch-mock";++import {+ setupPropertiesEndpoints,+ setupRemoteSyncEndpoints,+ setupRootCollectionItemsEndpoint,+ setupSettingsEndpoints,+} from "__support__/server-mocks";+import { mockSettings } from "__support__/settings";+import { renderWithProviders } from "__support__/ui";+import type { Collection } from "metabase-types/api";+import {+ createMockCollection,+ createMockSettings,+ createMockUser,+} from "metabase-types/api/mocks";+import { createMockState } from "metabase-types/store/mocks";++import {+ RemoteSyncSettingsForm,+ type RemoteSyncSettingsFormProps,+} from "./RemoteSyncSettingsForm";++export const createMockLibraryCollection = (+ overrides?: Partial<Collection>,+): Collection =>+ createMockCollection({+ id: 999,+ name: "Library",+ type: "library",+ ...overrides,+ });++const setupEndpoints = ({+ remoteSyncEnabled = false,+ remoteSyncUrl = "",+ remoteSyncToken = "",+ remoteSyncType = "read-only" as const,+ remoteSyncBranch = "main",+ remoteSyncAutoImport = false,+ libraryCollection = null as Collection | null,+ dirty = [] as any[],+}: {+ remoteSyncEnabled?: boolean;+ remoteSyncUrl?: string;+ remoteSyncToken?: string;+ remoteSyncType?: "read-only" | "read-write";+ remoteSyncBranch?: string;+ remoteSyncAutoImport?: boolean;+ libraryCollection?: Collection | null;+ dirty?: any[];+} = {}) => {+ const settings = createMockSettings({+ "remote-sync-enabled": remoteSyncEnabled,+ "remote-sync-url": remoteSyncUrl,+ "remote-sync-token": remoteSyncToken,+ "remote-sync-type": remoteSyncType,+ "remote-sync-branch": remoteSyncBranch,+ "remote-sync-auto-import": remoteSyncAutoImport,+ });++ setupPropertiesEndpoints(settings);+ setupSettingsEndpoints([]);+ setupRemoteSyncEndpoints({ dirty, branches: [remoteSyncBranch] });++ fetchMock.get("express:/api/ee/library", libraryCollection ?? { data: null });++ setupRootCollectionItemsEndpoint({ rootCollectionItems: [] });+};++const createStoreState = ({+ isAdmin = true,+ remoteSyncEnabled = false,+ remoteSyncType = "read-only" as const,+}: {+ isAdmin?: boolean;+ remoteSyncEnabled?: boolean;+ remoteSyncType?: "read-only" | "read-write";+} = {}) => {+ return createMockState({+ currentUser: createMockUser({ is_superuser: isAdmin }),+ settings: mockSettings({+ "remote-sync-enabled": remoteSyncEnabled,+ "remote-sync-type": remoteSyncType,+ }),+ });+};++interface SetupOpts {+ onCancel?: () => void;+ remoteSyncEnabled?: boolean;+ remoteSyncUrl?: string;+ remoteSyncToken?: string;+ remoteSyncType?: "read-only" | "read-write";+ remoteSyncBranch?: string;+ libraryCollection?: Collection | null;+ dirty?: any[];+ variant?: RemoteSyncSettingsFormProps["variant"];+}++export const setup = ({+ onCancel,+ remoteSyncEnabled = false,+ remoteSyncUrl = "",+ remoteSyncToken = "",+ remoteSyncType = "read-only",+ remoteSyncBranch = "main",+ libraryCollection = null,+ dirty = [],+ variant,+}: SetupOpts = {}) => {+ setupEndpoints({+ remoteSyncEnabled,+ remoteSyncUrl,+ remoteSyncToken,+ remoteSyncType,+ remoteSyncBranch,+ libraryCollection,+ dirty,+ });++ renderWithProviders(+ <RemoteSyncSettingsForm onCancel={onCancel} variant={variant} />,+ {+ storeInitialState: createStoreState({+ remoteSyncEnabled,+ remoteSyncType,+ }),+ },+ );+};diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/RemoteSyncSettingsForm.tsx b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/RemoteSyncSettingsForm.tsxnew file mode 100644index 00000000000..9a8719ec49b--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/RemoteSyncSettingsForm.tsx@@ -0,0 +1,520 @@+import { type ComponentProps, useCallback, useMemo, useRef } from "react";+import { jt, t } from "ttag";++import { SettingsSection } from "metabase/admin/components/SettingsSection";+import {+ useGetAdminSettingsDetailsQuery,+ useGetSettingsQuery,+ useListCollectionItemsQuery,+} from "metabase/api";+import ExternalLink from "metabase/common/components/ExternalLink";+import { useDocsUrl, useSetting, useToast } from "metabase/common/hooks";+import { useConfirmation } from "metabase/common/hooks/use-confirmation";+import {+ Form,+ FormErrorMessage,+ FormProvider,+ FormRadioGroup,+ FormSubmitButton,+ FormSwitch,+ FormTextInput,+} from "metabase/forms";+import { useSelector } from "metabase/lib/redux";+import { getApplicationName } from "metabase/selectors/whitelabel";+import {+ Box,+ Button,+ Flex,+ Icon,+ Radio,+ Stack,+ Text,+ Tooltip,+} from "metabase/ui";+import { useGetLibraryCollectionQuery } from "metabase-enterprise/api";+import {+ useGetRemoteSyncChangesQuery,+ useUpdateRemoteSyncSettingsMutation,+} from "metabase-enterprise/api/remote-sync";+import type {+ RemoteSyncConfigurationSettings,+ SettingDefinition,+} from "metabase-types/api";++import {+ trackBranchSwitched,+ trackRemoteSyncDeactivated,+ trackRemoteSyncSettingsChanged,+} from "../../analytics";+import {+ AUTO_IMPORT_KEY,+ BRANCH_KEY,+ COLLECTIONS_KEY,+ REMOTE_SYNC_KEY,+ REMOTE_SYNC_SCHEMA,+ TOKEN_KEY,+ TYPE_KEY,+ URL_KEY,+} from "../../constants";+import { SharedTenantCollectionsList } from "../SharedTenantCollectionsList";+import { TopLevelCollectionsList } from "../TopLevelCollectionsList";++import { PullChangesButton } from "./PullChangesButton";++export type RemoteSyncSettingsFormProps = {+ onCancel?: VoidFunction;+ onSaveSuccess?: VoidFunction;+ variant?: "admin" | "settings-modal";+};++export const RemoteSyncSettingsForm = (props: RemoteSyncSettingsFormProps) => {+ const { onCancel, onSaveSuccess, variant = "admin" } = props;+ const { data: settingValues } = useGetSettingsQuery();+ const { data: settingDetails } = useGetAdminSettingsDetailsQuery();+ const [+ updateRemoteSyncSettings,+ { isLoading: isUpdatingRemoteSyncSettings },+ ] = useUpdateRemoteSyncSettingsMutation();+ const { data: dirtyData } = useGetRemoteSyncChangesQuery(undefined, {+ refetchOnFocus: true,+ refetchOnMountOrArgChange: true,+ });+ const pendingConfirmationSettingsRef =+ useRef<RemoteSyncConfigurationSettings | null>(null);++ const isRemoteSyncEnabled = useSetting(REMOTE_SYNC_KEY);+ const useTenants = useSetting("use-tenants");+ const applicationName = useSelector(getApplicationName);++ // Fetch top-level collections to build initial sync state+ const { data: topLevelCollectionsData } = useListCollectionItemsQuery(+ { id: "root", models: ["collection"] },+ { skip: !isRemoteSyncEnabled },+ );++ // Fetch library collection to build initial sync state+ const { data: libraryCollectionData } = useGetLibraryCollectionQuery(+ undefined,+ { skip: !isRemoteSyncEnabled },+ );+ // Library collection endpoint returns { data: null } when not found+ const libraryCollection =+ libraryCollectionData && "name" in libraryCollectionData+ ? libraryCollectionData+ : undefined;++ // Fetch tenant collections to build initial sync state+ const { data: tenantCollectionsData } = useListCollectionItemsQuery(+ {+ id: "root",+ namespace: "shared-tenant-collection",+ },+ { skip: !isRemoteSyncEnabled || !useTenants },+ );++ const {+ show: showChangeBranchConfirmation,+ modalContent: changeBranchConfirmationModal,+ } = useConfirmation();+ const [sendToast] = useToast();++ const {+ show: showDisableConfirmation,+ modalContent: disableConfirmationModal,+ } = useConfirmation();+ const isModalVariant = variant === "settings-modal";++ const handleSubmit = useCallback(+ async (values: RemoteSyncConfigurationSettings) => {+ const didBranchChange =+ values[BRANCH_KEY] !== settingValues?.[BRANCH_KEY];++ // Don't send collections when in read-only mode+ const settingsToSave =+ values[TYPE_KEY] === "read-only"+ ? (Object.fromEntries(+ Object.entries(values).filter(([key]) => key !== COLLECTIONS_KEY),+ ) as RemoteSyncConfigurationSettings)+ : values;++ const saveSettings = async (+ settings: RemoteSyncConfigurationSettings,+ ) => {+ try {+ await updateRemoteSyncSettings(settings).unwrap();++ trackRemoteSyncSettingsChanged({+ triggeredFrom: isModalVariant ? "data-studio" : "admin-settings",+ });++ if (+ didBranchChange &&+ settingValues?.[BRANCH_KEY] &&+ values[BRANCH_KEY]+ ) {+ trackBranchSwitched({+ triggeredFrom: "admin-settings",+ });+ }++ sendToast({ message: t`Settings saved successfully`, icon: "check" });+ onSaveSuccess?.();+ } catch (error) {+ sendToast({+ message: t`Settings could not be saved`,+ icon: "warning",+ });+ throw error;+ }+ };++ if (didBranchChange) {+ pendingConfirmationSettingsRef.current = settingsToSave;+ showChangeBranchConfirmation({+ title: t`Switch branches?`,+ message: t`The synced collection will update to match the new branch. Questions that exist in the current branch but not the new one will be removed from any dashboards or content that reference them permanently, even if you switch back.`,+ confirmButtonText: t`Continue`,+ confirmButtonProps: {+ variant: "filled",+ color: "danger",+ },+ onConfirm: async () => {+ if (pendingConfirmationSettingsRef.current) {+ await saveSettings(pendingConfirmationSettingsRef.current);+ pendingConfirmationSettingsRef.current = null;+ }+ },+ onCancel: () => {+ pendingConfirmationSettingsRef.current = null;+ },+ });+ return;+ }+ await saveSettings(settingsToSave);+ },+ [+ settingValues,+ updateRemoteSyncSettings,+ isModalVariant,+ sendToast,+ onSaveSuccess,+ showChangeBranchConfirmation,+ ],+ );++ const handleDisable = useCallback(async () => {+ showDisableConfirmation({+ title: t`Disable Remote Sync?`,+ message: t`This will clear all remote sync settings. Any changes made to the Library collection after disabling can be overwritten if you enable sync again.`,+ confirmButtonText: t`Disable`,+ confirmButtonProps: {+ variant: "filled",+ color: "danger",+ },+ onConfirm: async () => {+ try {+ await updateRemoteSyncSettings({ [URL_KEY]: "" }).unwrap();+ trackRemoteSyncDeactivated();+ sendToast({ message: t`Remote Sync disabled`, icon: "check" });+ } catch (error) {+ console.error(error);+ sendToast({+ message: t`Failed to disable Remote Sync`,+ icon: "warning",+ });+ }+ },+ });+ }, [updateRemoteSyncSettings, sendToast, showDisableConfirmation]);++ const initialValues = useMemo(() => {+ const values = REMOTE_SYNC_SCHEMA.cast(settingValues, {+ stripUnknown: true,+ });+ const tokenValue =+ settingDetails?.[TOKEN_KEY]?.value ?? settingValues?.[TOKEN_KEY];++ // Build initial collection sync map from server data+ const collectionSyncMap: Record<number, boolean> = {};++ // Add library collection+ if (libraryCollection) {+ collectionSyncMap[libraryCollection.id] =+ libraryCollection.is_remote_synced ?? false;+ }++ // Add top-level collections (excluding personal)+ topLevelCollectionsData?.data+ ?.filter((c) => !c.personal_owner_id)+ .forEach((collection) => {+ collectionSyncMap[collection.id] = collection.is_remote_synced ?? false;+ });++ // Add tenant collections+ tenantCollectionsData?.data?.forEach((collection) => {+ collectionSyncMap[collection.id] = collection.is_remote_synced ?? false;+ });++ return {+ ...values,+ [TOKEN_KEY]: tokenValue,+ [COLLECTIONS_KEY]: collectionSyncMap,+ };+ }, [+ settingValues,+ settingDetails,+ libraryCollection,+ topLevelCollectionsData,+ tenantCollectionsData,+ ]);++ // eslint-disable-next-line no-unconditional-metabase-links-render -- This links only shows for admins.+ const { url: docsUrl } = useDocsUrl(+ "installation-and-operation/remote-sync",+ {+ anchor: "remote-sync",+ },+ );++ const hasUnsyncedChanges = !!dirtyData?.dirty?.length;++ return (+ <>+ <FormProvider+ initialValues={initialValues as RemoteSyncConfigurationSettings}+ enableReinitialize+ validationSchema={REMOTE_SYNC_SCHEMA}+ validationContext={settingValues}+ onSubmit={handleSubmit}+ >+ {({ dirty, values }) => (+ <Form disabled={!dirty}>+ <Stack gap="xl" maw="52rem">+ {!isModalVariant && !isRemoteSyncEnabled && (+ <Text c="text-medium" size="sm">+ {jt`Need help setting this up? Check out our ${(+ <ExternalLink key="link" href={docsUrl}>+ {t`setup guide`}+ </ExternalLink>+ )}.`}+ </Text>+ )}++ {/* Section 1: Git settings */}+ <RemoteSyncSettingsSection+ title={t`Git settings`}+ variant={variant}+ >+ <FormTextInput+ name={URL_KEY}+ label={t`Repository URL`}+ placeholder="https://github.com/yourcompany/metabase-library.git"+ labelProps={{ mb: "0.75rem" }}+ {...getEnvSettingProps(settingDetails?.[URL_KEY])}+ />+ <FormTextInput+ name={TOKEN_KEY}+ label={t`Access Token`}+ description={+ <Text c="text-light" size="sm" lh="md" component="span">+ {t`Personal access token with write permissions`}+ </Text>+ }+ type="password"+ {...getEnvSettingProps(settingDetails?.[TOKEN_KEY])}+ />+ </RemoteSyncSettingsSection>++ {/* Section 2: Sync mode for this instance */}+ <RemoteSyncSettingsSection+ title={t`Sync mode for this instance`}+ variant={variant}+ >+ <FormRadioGroup name={TYPE_KEY}>+ <Stack>+ <Tooltip+ disabled={!hasUnsyncedChanges}+ label={t`You can't switch to Read-only as you have unpublished changes.`}+ position="bottom-start"+ >+ <Box>+ <Radio+ description={+ <Text c="text-medium" lh="1.25rem" component="span">+ {t`Usually you should use this for your production ${applicationName} instance. All synced collections are read-only, and will automatically sync with the specified branch (we'd recommend syncing with main).`}+ </Text>+ }+ disabled={hasUnsyncedChanges}+ label={+ <Text fw={700} lh="1.25rem" mb="xs">+ {t`Read-only`}+ </Text>+ }+ value="read-only"+ />+ </Box>+ </Tooltip>+ <Radio+ value="read-write"+ label={+ <Text fw={700} lh="1.25rem" mb="xs">+ {t`Read-write`}+ </Text>+ }+ description={+ <Text c="text-medium" lh="1.25rem" component="span">+ {t`This mode is generally for development or local instances of ${applicationName}. Changes you make to content in synced collections can be pushed and pulled from any git branch.`}+ </Text>+ }+ />+ </Stack>+ </FormRadioGroup>+ </RemoteSyncSettingsSection>++ {/* Section 3: Branch to sync with (read-only only) */}+ {values?.[TYPE_KEY] === "read-only" && (+ <RemoteSyncSettingsSection+ title={t`Branch to sync with`}+ variant={variant}+ >+ <Flex align="flex-end" gap="md">+ <Box style={{ flex: 1 }}>+ <FormTextInput+ name={BRANCH_KEY}+ placeholder="main"+ label={t`Sync branch`}+ labelProps={{ mb: "0.75rem" }}+ {...getEnvSettingProps(settingDetails?.[BRANCH_KEY])}+ />+ </Box>+ <FormSwitch+ label={t`Auto-sync with git`}+ mb="0.6125rem"+ name={AUTO_IMPORT_KEY}+ size="sm"+ />+ </Flex>+ {isRemoteSyncEnabled && (+ <Box>+ <PullChangesButton+ branch={values?.[BRANCH_KEY] || "main"}+ dirty={dirty}+ forcePull+ />+ </Box>+ )}+ </RemoteSyncSettingsSection>+ )}++ {/* Section 4: Collections to sync */}+ {isRemoteSyncEnabled && (+ <RemoteSyncSettingsSection+ description={t`Choose which collections to sync with git.`}+ title={t`Collections to sync`}+ variant={variant}+ >+ <Stack gap="lg">+ <TopLevelCollectionsList />+ {useTenants && (+ <>+ <Text fw={700} size="md" lh="1rem">+ {t`Shared collections`}+ </Text>+ <SharedTenantCollectionsList />+ </>+ )}+ </Stack>+ </RemoteSyncSettingsSection>+ )}++ {/* Read-write mode info */}+ {isModalVariant && values?.[TYPE_KEY] === "read-write" && (+ <Text c="text-medium" size="sm">+ {t`In read-write mode, the Library collection will be enabled for syncing.`}+ </Text>+ )}++ {/* Footer Actions - Outside Sections */}+ <Flex justify="space-between" align="center">+ <Box>+ {isRemoteSyncEnabled && (+ <Button+ c="error"+ variant="subtle"+ size="md"+ w="12rem"+ leftSection={<Icon name="close" />}+ onClick={handleDisable}+ >+ {t`Disable remote sync`}+ </Button>+ )}+ </Box>++ <Flex align="center" gap="md">+ <FormErrorMessage />+ {onCancel && (+ <Button+ variant="default"+ onClick={onCancel}+ disabled={isUpdatingRemoteSyncSettings}+ >+ {t`Cancel`}+ </Button>+ )}+ <FormSubmitButton+ data-testid="remote-sync-submit-button"+ size="md"+ label={+ isRemoteSyncEnabled+ ? t`Save changes`+ : t`Set up Remote Sync`+ }+ variant="filled"+ disabled={isRemoteSyncEnabled ? !dirty : !values?.[URL_KEY]}+ loading={isUpdatingRemoteSyncSettings}+ />+ </Flex>+ </Flex>+ </Stack>+ </Form>+ )}+ </FormProvider>++ {changeBranchConfirmationModal}+ {disableConfirmationModal}+ </>+ );+};++const RemoteSyncSettingsSection = ({+ children,+ title,+ variant,+ ...props+}: ComponentProps<typeof SettingsSection> & {+ title: string;+ variant: RemoteSyncSettingsFormProps["variant"];+}) => {+ return (+ <SettingsSection+ {...props}+ title={title}+ titleProps={{+ order: variant === "settings-modal" ? 3 : 2,+ }}+ >+ {children}+ </SettingsSection>+ );+};++const getEnvSettingProps = (setting?: SettingDefinition) => {+ if (setting?.is_env_setting) {+ return {+ description: t`Using ${setting.env_name}`,+ readOnly: true,+ };+ }+ return {};+};diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/RemoteSyncSettingsForm.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/RemoteSyncSettingsForm.unit.spec.tsxnew file mode 100644index 00000000000..2df3b6b51a9--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/RemoteSyncSettingsForm.unit.spec.tsx@@ -0,0 +1,162 @@+import userEvent from "@testing-library/user-event";++import { screen, waitFor } from "__support__/ui";++import {+ createMockLibraryCollection,+ setup,+} from "./RemoteSyncSettingsForm.setup.spec";++describe("RemoteSyncSettingsForm", () => {+ it("should display Git settings section with URL and Token fields", async () => {+ setup();++ expect(screen.getByText("Git settings")).toBeInTheDocument();+ expect(screen.getByLabelText(/Repository URL/i)).toBeInTheDocument();+ expect(screen.getByLabelText(/Access token/i)).toBeInTheDocument();+ });++ it("should display Sync Mode section with radio options", async () => {+ setup();++ expect(screen.getByText("Sync mode for this instance")).toBeInTheDocument();+ expect(screen.getByLabelText("Read-only")).toBeInTheDocument();+ expect(screen.getByLabelText("Read-write")).toBeInTheDocument();+ });++ it("should show set up help link", async () => {+ setup();+ expect(+ screen.getByRole("link", { name: "setup guide" }),+ ).toBeInTheDocument();+ });++ describe("conditional branch section", () => {+ it("should show branch settings when read-only mode is selected", async () => {+ setup({ remoteSyncType: "read-only" });++ expect(screen.getByText("Branch to sync with")).toBeInTheDocument();+ expect(screen.getByLabelText(/Sync branch/i)).toBeInTheDocument();+ expect(screen.getByLabelText(/Auto-sync with git/i)).toBeInTheDocument();+ });++ it("should hide branch settings when read-write mode is selected", async () => {+ setup({ remoteSyncType: "read-write" });++ // Wait for the form to be fully rendered+ await waitFor(() => {+ expect(screen.getByLabelText("Read-write")).toBeChecked();+ });++ expect(screen.queryByText("Branch to sync with")).not.toBeInTheDocument();+ });+ });++ describe("submit behavior - read-write mode", () => {+ it("should show the 'Save changes' button", async () => {+ const libraryCollection = createMockLibraryCollection({ id: 999 });++ setup({+ remoteSyncType: "read-write",+ remoteSyncUrl: "https://github.com/test/repo.git",+ remoteSyncEnabled: true,+ libraryCollection,+ });++ // Verify the submit button shows correct text for existing setup+ expect(+ screen.getByRole("button", { name: /Save changes/i }),+ ).toBeInTheDocument();+ });+ });++ describe("submit behavior - read-only mode", () => {+ beforeEach(() => {+ setup({+ remoteSyncType: "read-only",+ remoteSyncUrl: "",+ remoteSyncEnabled: false,+ });+ });++ it("should show the 'Set up Remote Sync' button", async () => {+ // Verify the submit button shows correct text for new setup+ expect(+ screen.getByRole("button", { name: /Set up Remote Sync/i }),+ ).toBeInTheDocument();+ });++ it("should show the 'Branch to sync with' section", async () => {+ expect(+ screen.getByRole("heading", { name: "Branch to sync with" }),+ ).toBeInTheDocument();+ expect(+ screen.getByRole("switch", { name: "Auto-sync with git" }),+ ).toBeInTheDocument();+ });+ });++ describe("cancel behavior", () => {+ it("does not show the cancel button if onCancel is not set", () => {+ setup({+ onCancel: undefined,+ remoteSyncUrl: "https://github.com/test/repo.git",+ });+ expect(+ screen.queryByRole("button", { name: "Cancel" }),+ ).not.toBeInTheDocument();+ });++ it("should close modal when Cancel is clicked", async () => {+ const onCancel = jest.fn();++ setup({+ onCancel,+ remoteSyncUrl: "https://github.com/test/repo.git",+ });++ const cancelButton = screen.getByRole("button", { name: "Cancel" });+ await userEvent.click(cancelButton);++ expect(onCancel).toHaveBeenCalled();+ });+ });++ describe("read-only mode restriction", () => {+ it("should disable read-only option when there are unsynced changes", async () => {+ const dirty = [+ { id: 1, name: "Test Card", model: "card", sync_status: "update" },+ ];++ setup({+ remoteSyncType: "read-write",+ remoteSyncEnabled: true,+ dirty,+ });++ await waitFor(() => {+ const readOnlyRadio = screen.getByLabelText("Read-only");+ expect(readOnlyRadio).toBeDisabled();+ });+ });+ });++ describe("settings-modal variant", () => {+ it("should show info text when read-write mode is selected", async () => {+ setup({ remoteSyncType: "read-write", variant: "settings-modal" });++ await waitFor(() => {+ expect(+ screen.getByText(/Library collection will be enabled for syncing/i),+ ).toBeInTheDocument();+ });+ });++ it("should now show set up help link", async () => {+ setup({ variant: "settings-modal" });+ expect(+ screen.queryByRole("link", { name: "setup guide" }),+ ).not.toBeInTheDocument();+ });+ });+});diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/index.ts b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/index.tsindex 7ace6424e2c..fc4836c6525 100644--- a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/index.ts+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/index.ts@@ -1 +1,2 @@export { RemoteSyncAdminSettings } from "./RemoteSyncAdminSettings";+export { RemoteSyncSettingsForm } from "./RemoteSyncSettingsForm";diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/index.ts b/enterprise/frontend/src/metabase-enterprise/remote_sync/index.tsindex 7a2ca16fbbd..69fec97e47a 100644--- a/enterprise/frontend/src/metabase-enterprise/remote_sync/index.ts+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/index.ts@@ -7,8 +7,10 @@ import { hasPremiumFeature } from "metabase-enterprise/settings";import { LibraryNav } from "./LibraryNav";import { CollectionsNavTree } from "./components/CollectionsNavTree";+import { GitSettingsModal } from "./components/GitSettingsModal";import { GitSyncControls } from "./components/GitSyncControls";-import { RemoteSyncAdminSettings } from "./components/RemoteSyncAdminSettings/RemoteSyncAdminSettings";+import { GitSyncSetupMenuItem } from "./components/GitSyncSetupMenuItem";+import { RemoteSyncAdminSettings } from "./components/RemoteSyncAdminSettings";import {CollectionSyncStatusBadge,SyncedCollectionsSidebarSection,@@ -30,12 +32,14 @@ export function initializePlugin() {PLUGIN_REMOTE_SYNC.SyncedCollectionsSidebarSection =SyncedCollectionsSidebarSection;PLUGIN_REMOTE_SYNC.GitSyncAppBarControls = GitSyncControls;+ PLUGIN_REMOTE_SYNC.GitSettingsModal = GitSettingsModal;PLUGIN_REMOTE_SYNC.CollectionsNavTree = CollectionsNavTree;PLUGIN_REMOTE_SYNC.CollectionSyncStatusBadge = CollectionSyncStatusBadge;PLUGIN_REMOTE_SYNC.REMOTE_SYNC_INVALIDATION_TAGS =REMOTE_SYNC_INVALIDATION_TAGS;PLUGIN_REMOTE_SYNC.useSyncStatus = useSyncStatus;PLUGIN_REMOTE_SYNC.useGitSyncVisible = useGitSyncVisible;+ PLUGIN_REMOTE_SYNC.GitSyncSetupMenuItem = GitSyncSetupMenuItem;PLUGIN_REMOTE_SYNC.useHasLibraryDirtyChanges = useHasLibraryDirtyChanges;PLUGIN_REDUX_MIDDLEWARES.push(remoteSyncListenerMiddleware.middleware);diff --git a/frontend/src/metabase-types/analytics/event.ts b/frontend/src/metabase-types/analytics/event.tsindex 3289ade8df2..003fff81a47 100644--- a/frontend/src/metabase-types/analytics/event.ts+++ b/frontend/src/metabase-types/analytics/event.ts@@ -495,7 +495,7 @@ export type RemoteSyncPushChangesEvent = ValidateEvent<{export type RemoteSyncSettingsChangedEvent = ValidateEvent<{event: "remote_sync_settings_changed";- triggered_from: "admin-settings";+ triggered_from: "admin-settings" | "data-studio";}>;export type RemoteSyncDeactivatedEvent = ValidateEvent<{diff --git a/frontend/src/metabase/admin/components/SettingsSection/SettingsSection.tsx b/frontend/src/metabase/admin/components/SettingsSection/SettingsSection.tsxindex 1330b2450dd..17df689e181 100644--- a/frontend/src/metabase/admin/components/SettingsSection/SettingsSection.tsx+++ b/frontend/src/metabase/admin/components/SettingsSection/SettingsSection.tsx@@ -7,18 +7,21 @@ import {type StackProps,Text,Title,+ type TitleProps,} from "metabase/ui";import S from "./SettingsSection.module.css";export function SettingsSection({title,+ titleProps,description,children,stackProps,...boxProps}: {title?: React.ReactNode;+ titleProps?: TitleProps;description?: React.ReactNode;children?: React.ReactNode;stackProps?: StackProps;@@ -29,7 +32,11 @@ export function SettingsSection({<Stack gap="lg" className={S.SettingsSection} {...stackProps}>{(title || description) && (<Box mb="sm">- {title && <Title order={2}>{title}</Title>}+ {title && (+ <Title order={2} {...titleProps}>+ {title}+ </Title>+ )}{description && <Text c="text-medium">{description}</Text>}</Box>)}diff --git a/frontend/src/metabase/plugins/index.ts b/frontend/src/metabase/plugins/index.tsindex 9cb71c15997..cdb3f5a3b26 100644--- a/frontend/src/metabase/plugins/index.ts+++ b/frontend/src/metabase/plugins/index.ts@@ -144,6 +144,7 @@ export { PLUGIN_TENANTS } from "./oss/tenants";// Re-export types that are used by other filesexport type {GetAuthProviders,+ GitSyncSetupMenuItemProps,PluginGroupManagersType,SyncedCollectionsSidebarSectionProps,} from "./types";diff --git a/frontend/src/metabase/plugins/oss/remote-sync.ts b/frontend/src/metabase/plugins/oss/remote-sync.tsindex ea818c9b3a6..368b41bb963 100644--- a/frontend/src/metabase/plugins/oss/remote-sync.ts+++ b/frontend/src/metabase/plugins/oss/remote-sync.ts@@ -3,13 +3,15 @@ import type { ComponentType, ReactNode } from "react";import type { ITreeNodeItem } from "metabase/common/components/tree/types";import type { CollectionTreeItem } from "metabase/entities/collections";+import type {+ GitSyncSetupMenuItemProps,+ SyncedCollectionsSidebarSectionProps,+} from "metabase/plugins";import {NotFoundPlaceholder,PluginPlaceholder,} from "metabase/plugins/components/PluginPlaceholder";-import type { SyncedCollectionsSidebarSectionProps } from "../types";-export type CollectionsNavTreeProps = {collections: CollectionTreeItem[];selectedId?: number | string;@@ -20,12 +22,19 @@ export interface GitSyncAppBarControlsProps {fullWidth?: boolean;}+export interface GitSettingsModalProps {+ isOpen: boolean;+ onClose: () => void;+}+const getDefaultPluginRemoteSync = () => ({LibraryNav: PluginPlaceholder,RemoteSyncSettings: NotFoundPlaceholder,SyncedCollectionsSidebarSection: PluginPlaceholder,GitSyncAppBarControls:PluginPlaceholder as ComponentType<GitSyncAppBarControlsProps>,+ GitSettingsModal: PluginPlaceholder as ComponentType<GitSettingsModalProps>,+ GitSyncSetupMenuItem: PluginPlaceholder,CollectionsNavTree: null as ComponentType<CollectionsNavTreeProps> | null,CollectionSyncStatusBadge: null as ComponentType | null,REMOTE_SYNC_INVALIDATION_TAGS: null,@@ -45,6 +54,8 @@ export const PLUGIN_REMOTE_SYNC: {RemoteSyncSettings: ComponentType;SyncedCollectionsSidebarSection: ComponentType<SyncedCollectionsSidebarSectionProps>;GitSyncAppBarControls: ComponentType<GitSyncAppBarControlsProps>;+ GitSettingsModal: ComponentType<GitSettingsModalProps>;+ GitSyncSetupMenuItem: ComponentType<GitSyncSetupMenuItemProps>;CollectionsNavTree: ComponentType<CollectionsNavTreeProps> | null;CollectionSyncStatusBadge: ComponentType | null;REMOTE_SYNC_INVALIDATION_TAGS: TagDescription<any>[] | null;diff --git a/frontend/src/metabase/plugins/types.ts b/frontend/src/metabase/plugins/types.tsindex 5903b8b969a..3cbcd620a49 100644--- a/frontend/src/metabase/plugins/types.ts+++ b/frontend/src/metabase/plugins/types.ts@@ -54,3 +54,8 @@ export type SyncedCollectionsSidebarSectionProps = {selectedId?: number | string;syncedCollections: CollectionTreeItem[];};++export type GitSyncSetupMenuItemProps = {+ isNavbarOpened: boolean;+ onClick: VoidFunction;+};diff --git a/frontend/test/__support__/server-mocks/remote-sync.ts b/frontend/test/__support__/server-mocks/remote-sync.tsindex f5292de3014..75fa8b354ca 100644--- a/frontend/test/__support__/server-mocks/remote-sync.ts+++ b/frontend/test/__support__/server-mocks/remote-sync.ts@@ -19,4 +19,6 @@ export const setupRemoteSyncEndpoints = ({fetchMock.post("path:/api/ee/remote-sync/import", {});fetchMock.post("path:/api/ee/remote-sync/create-branch", {});fetchMock.get("path:/api/ee/remote-sync/current-task", { status: "idle" });++ fetchMock.put("path:/api/ee/remote-sync/settings", { success: true });};