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: collection selector for remote-sync (#66977)
Edward Paget43217e93502b
diff --git a/e2e/test/scenarios/admin/remote-sync.cy.spec.ts b/e2e/test/scenarios/admin/remote-sync.cy.spec.tsindex 9bb94890b6e..7a5fe8e3e50 100644--- a/e2e/test/scenarios/admin/remote-sync.cy.spec.ts+++ b/e2e/test/scenarios/admin/remote-sync.cy.spec.ts@@ -659,8 +659,11 @@ describe("Remote Sync", () => {cy.visit("/admin/settings/remote-sync");cy.findByTestId("admin-layout-content").within(() => {- // Section should be visible- cy.findByText("Shared tenant collections to sync").should("exist");+ // Main section should be visible+ cy.findByText("Collections to sync").should("exist");++ // Shared collections sub-section should be visible+ cy.findByText("Shared collections").should("exist");// Should show the tenant collectionscy.findByText("Tenant A Shared").should("exist");@@ -678,18 +681,18 @@ describe("Remote Sync", () => {H.configureGit("read-write");cy.visit("/admin/settings/remote-sync");- // Section should NOT be visible+ // Shared collections sub-section should NOT be visiblecy.findByTestId("admin-layout-content")- .findByText("Shared tenant collections to sync")+ .findByText("Shared collections").should("not.exist");});it("should not show shared tenant collections section when remote sync is not enabled", () => {cy.visit("/admin/settings/remote-sync");- // Section should NOT be visible (remote sync not yet configured)+ // Collections to sync section should NOT be visible (remote sync not yet configured)cy.findByTestId("admin-layout-content")- .findByText("Shared tenant collections to sync")+ .findByText("Collections to sync").should("not.exist");});@@ -698,7 +701,7 @@ describe("Remote Sync", () => {cy.visit("/admin/settings/remote-sync");cy.findByTestId("admin-layout-content").within(() => {- cy.findByText("Shared tenant collections to sync").should("exist");+ cy.findByText("Shared collections").should("exist");cy.findByText("No shared tenant collections found").should("exist");});});diff --git a/enterprise/frontend/src/metabase-enterprise/api/remote-sync.ts b/enterprise/frontend/src/metabase-enterprise/api/remote-sync.tsindex f9fe580eb80..2cb38dd3f81 100644--- a/enterprise/frontend/src/metabase-enterprise/api/remote-sync.ts+++ b/enterprise/frontend/src/metabase-enterprise/api/remote-sync.ts@@ -91,6 +91,11 @@ export const remoteSyncApi = EnterpriseApi.injectEndpoints({tag("session-properties"),// Invalidate collection list to refresh is_remote_synced valueslistTag("collection"),+ // Invalidate library collection to refresh is_remote_synced value+ tag("library-collection"),+ // Invalidate dirty state to refetch after settings change+ tag("collection-dirty-entities"),+ tag("collection-is-dirty"),],}),getBranches: builder.query<GetBranchesResponse, void>({diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/ChangesLists/AllChangesView.tsx b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/ChangesLists/AllChangesView.tsxindex 2249d80eaab..392ee379df9 100644--- a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/ChangesLists/AllChangesView.tsx+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/ChangesLists/AllChangesView.tsx@@ -3,6 +3,7 @@ import { t } from "ttag";import _ from "underscore";import { useListCollectionsTreeQuery } from "metabase/api";+import { useSetting } from "metabase/common/hooks";import {Box,Divider,@@ -19,7 +20,7 @@ import {getSyncStatusColor,getSyncStatusIcon,} from "metabase-enterprise/remote_sync/utils";-import type { Collection, RemoteSyncEntity } from "metabase-types/api";+import type { RemoteSyncEntity } from "metabase-types/api";import { CollectionPath } from "./CollectionPath";import { EntityLink } from "./EntityLink";@@ -33,40 +34,23 @@ const SYNC_STATUS_ORDER: RemoteSyncEntity["sync_status"][] = [interface AllChangesViewProps {entities: RemoteSyncEntity[];- collections: Collection[];title?: string;}-export const AllChangesView = ({- entities,- collections,- title,-}: AllChangesViewProps) => {- const { data: collectionTree = [] } = useListCollectionsTreeQuery();-- // Fetch collection tree for shared-tenant-collections namespace- // This is needed to show changes in tenant collections that have is_remote_synced=true- const { data: tenantCollectionTree = [] } = useListCollectionsTreeQuery({- namespace: "shared-tenant-collection",+export const AllChangesView = ({ entities, title }: AllChangesViewProps) => {+ const isUsingTenants = useSetting("use-tenants");+ const { data: collectionTree = [] } = useListCollectionsTreeQuery({+ namespaces: [+ "",+ "analytics",+ ...(isUsingTenants ? ["shared-tenant-collection"] : []),+ ],+ "include-library": true,});const collectionMap = useMemo(() => {- const map = new Map([- ...buildCollectionMap(collectionTree),- ...buildCollectionMap(tenantCollectionTree),- ]);-- // Add all synced collections to the map, including those from namespaces.- // This ensures that collections from namespaces like "shared-tenant-collection"- // are available when building collection path segments.- collections.forEach((c) => {- if (typeof c.id === "number") {- map.set(c.id, c);- }- });-- return map;- }, [collectionTree, tenantCollectionTree, collections]);+ return buildCollectionMap(collectionTree);+ }, [collectionTree]);const hasRemovals = useMemo(() => {return (diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/ChangesLists/AllChangesView.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/ChangesLists/AllChangesView.unit.spec.tsxindex cdddd95596f..8283af8bb12 100644--- a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/ChangesLists/AllChangesView.unit.spec.tsx+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/ChangesLists/AllChangesView.unit.spec.tsx@@ -1,12 +1,17 @@import fetchMock from "fetch-mock";import { renderWithProviders, screen } from "__support__/ui";-import type { RemoteSyncEntity } from "metabase-types/api";+import type { Collection, RemoteSyncEntity } from "metabase-types/api";import { createMockCollection } from "metabase-types/api/mocks";import { createMockRemoteSyncEntity } from "metabase-types/api/mocks/remote-sync";import { AllChangesView } from "./AllChangesView";+const defaultCollection = createMockCollection({+ id: 1,+ name: "Entity Collection",+});+const updatedEntity = createMockRemoteSyncEntity({collection_id: 1,});@@ -25,18 +30,16 @@ const deletedEntity = createMockRemoteSyncEntity({const setup = ({entities = [updatedEntity],+ collections = [defaultCollection],}: {entities: RemoteSyncEntity[];+ collections?: Collection[];}) => {- const collections = [createMockCollection({ name: "Entity Collection" })];-- fetchMock.get("/api/collection/tree", collections);- fetchMock.get("/api/collection/tree?namespace=shared-tenant-collection", []);- fetchMock.get("path:/api/session/properties", {});+ // Mock the new useListCollectionsTreeQuery endpoint format+ fetchMock.get("path:/api/collection/tree", collections);+ fetchMock.get("path:/api/session/properties", { "use-tenants": false });- renderWithProviders(- <AllChangesView entities={entities} collections={collections} />,- );+ renderWithProviders(<AllChangesView entities={entities} />);};describe("AllChangesView", () => {@@ -63,7 +66,7 @@ describe("AllChangesView", () => {});describe("namespaced collections", () => {- it("should display collections from namespaces like shared-tenant-collection", () => {+ it("should display collections from namespaces like shared-tenant-collection", async () => {const namespacedCollection = createMockCollection({id: 10,name: "Tenant Collection",@@ -78,38 +81,29 @@ describe("AllChangesView", () => {sync_status: "update",});- fetchMock.get("/api/collection/tree", []);- fetchMock.get("/api/collection/tree?namespace=shared-tenant-collection", [- namespacedCollection,- ]);- fetchMock.get("path:/api/session/properties", {});-- renderWithProviders(- <AllChangesView- entities={[entityInNamespacedCollection]}- collections={[namespacedCollection]}- />,- );+ setup({+ entities: [entityInNamespacedCollection],+ collections: [namespacedCollection],+ });- expect(screen.getByText("Tenant Collection")).toBeInTheDocument();+ expect(await screen.findByText("Tenant Collection")).toBeInTheDocument();expect(screen.getByText("Dashboard in Tenant Collection"),).toBeInTheDocument();});- it("should display collection hierarchy for namespaced collections with ancestors", () => {- const parentCollection = createMockCollection({- id: 5,- name: "Parent Tenant Collection",- namespace: "shared-tenant-collection",- });+ it("should display collection hierarchy for namespaced collections with ancestors", async () => {const childCollection = createMockCollection({id: 10,name: "Child Tenant Collection",namespace: "shared-tenant-collection",- effective_ancestors: [- { id: 5, name: "Parent Tenant Collection" } as any,- ],+ });+ // Use nested tree structure - parent contains child+ const parentCollection = createMockCollection({+ id: 5,+ name: "Parent Tenant Collection",+ namespace: "shared-tenant-collection",+ children: [childCollection],});const entityInChildCollection = createMockRemoteSyncEntity({id: 20,@@ -119,26 +113,19 @@ describe("AllChangesView", () => {sync_status: "create",});- fetchMock.get("/api/collection/tree", []);- fetchMock.get("/api/collection/tree?namespace=shared-tenant-collection", [- parentCollection,- childCollection,- ]);- fetchMock.get("path:/api/session/properties", {});-- renderWithProviders(- <AllChangesView- entities={[entityInChildCollection]}- collections={[parentCollection, childCollection]}- />,- );-- expect(screen.getByText("Parent Tenant Collection")).toBeInTheDocument();+ setup({+ entities: [entityInChildCollection],+ collections: [parentCollection],+ });++ expect(+ await screen.findByText("Parent Tenant Collection"),+ ).toBeInTheDocument();expect(screen.getByText("Child Tenant Collection")).toBeInTheDocument();expect(screen.getByText("Item in Child Collection")).toBeInTheDocument();});- it("should display regular items in collections", () => {+ it("should display regular items in collections", async () => {const entityInCollection = createMockRemoteSyncEntity({id: 20,name: "Regular Item",@@ -151,7 +138,7 @@ describe("AllChangesView", () => {entities: [entityInCollection],});- expect(screen.getByText("Entity Collection")).toBeInTheDocument();+ expect(await screen.findByText("Entity Collection")).toBeInTheDocument();expect(screen.getByText("Regular Item")).toBeInTheDocument();});});diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/ChangesLists/ChangesLists.tsx b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/ChangesLists/ChangesLists.tsxindex 689d4387297..9e0e02dee29 100644--- a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/ChangesLists/ChangesLists.tsx+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/ChangesLists/ChangesLists.tsx@@ -2,16 +2,14 @@ import { t } from "ttag";import { Box, Loader, Text } from "metabase/ui";import { useGetRemoteSyncChangesQuery } from "metabase-enterprise/api";-import type { Collection } from "metabase-types/api";import { AllChangesView } from "./AllChangesView";interface ChangesListsProps {- collections: Collection[];title?: string;}-export const ChangesLists = ({ collections, title }: ChangesListsProps) => {+export const ChangesLists = ({ title }: ChangesListsProps) => {const { data: dirtyData, isLoading: isLoadingChanges } =useGetRemoteSyncChangesQuery(undefined, {refetchOnMountOrArgChange: true,@@ -38,11 +36,5 @@ export const ChangesLists = ({ collections, title }: ChangesListsProps) => {);}- return (- <AllChangesView- entities={allEntities}- collections={collections}- title={title}- />- );+ return <AllChangesView entities={allEntities} title={title} />;};diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/CollectionSyncList/CollectionSyncList.tsx b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/CollectionSyncList/CollectionSyncList.tsxnew file mode 100644index 00000000000..aea771f847e--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/CollectionSyncList/CollectionSyncList.tsx@@ -0,0 +1,88 @@+import { useFormikContext } from "formik";+import { useCallback, useEffect } from "react";+import { usePrevious } from "react-use";++import { Box, Flex, Loader, Text } from "metabase/ui";+import type {+ CollectionItem,+ CollectionSyncPreferences,+ RemoteSyncConfigurationSettings,+} from "metabase-types/api";++import { COLLECTIONS_KEY, TYPE_KEY } from "../../constants";+import { CollectionSyncRow } from "../CollectionSyncRow";++interface CollectionSyncListProps {+ collections: CollectionItem[];+ isLoading: boolean;+ error: string | null;+ emptyMessage: string;+}++export const CollectionSyncList = ({+ collections,+ isLoading,+ error,+ emptyMessage,+}: CollectionSyncListProps) => {+ const { values, setFieldValue, initialValues } =+ useFormikContext<RemoteSyncConfigurationSettings>();++ const syncMap: CollectionSyncPreferences = values[COLLECTIONS_KEY] ?? {};+ const currentType = values[TYPE_KEY];+ const isReadOnly = currentType === "read-only";+ const previousType = usePrevious(currentType);++ // Reset collections to initial values when switching from read-write to read-only+ useEffect(() => {+ if (previousType === "read-write" && currentType === "read-only") {+ setFieldValue(COLLECTIONS_KEY, initialValues[COLLECTIONS_KEY] ?? {});+ }+ }, [currentType, initialValues, setFieldValue, previousType]);++ const handleToggle = useCallback(+ (collection: CollectionItem, checked: boolean) => {+ // Use nested path to avoid stale closure issues with syncMap after form reinitialization+ setFieldValue(`${COLLECTIONS_KEY}.${collection.id}`, checked);+ },+ [setFieldValue],+ );++ if (isLoading) {+ return (+ <Flex justify="center" py="lg">+ <Loader data-testid="loading-indicator" />+ </Flex>+ );+ }++ if (error) {+ return <Text c="error">{error}</Text>;+ }++ if (collections.length === 0) {+ return <Text c="text-medium">{emptyMessage}</Text>;+ }++ return (+ <Box+ style={{+ borderRadius: "var(--mantine-radius-md)",+ border: "1px solid var(--mb-color-border)",+ backgroundColor: "var(--mb-color-bg-white)",+ overflow: "hidden",+ }}+ >+ {collections.map((collection, index) => (+ <CollectionSyncRow+ key={collection.id}+ collection={collection}+ isChecked={syncMap[collection.id] ?? false}+ onToggle={handleToggle}+ isLast={index === collections.length - 1}+ isReadOnly={isReadOnly}+ />+ ))}+ </Box>+ );+};diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/CollectionSyncList/CollectionSyncList.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/CollectionSyncList/CollectionSyncList.unit.spec.tsxnew file mode 100644index 00000000000..98d5d17ae8a--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/CollectionSyncList/CollectionSyncList.unit.spec.tsx@@ -0,0 +1,505 @@+import userEvent from "@testing-library/user-event";+import React from "react";++import { renderWithProviders, screen, waitFor } from "__support__/ui";+import {+ Form,+ FormProvider,+ FormRadioGroup,+ FormSubmitButton,+} from "metabase/forms";+import { Radio, Stack } from "metabase/ui";+import type {+ CollectionItem,+ CollectionSyncPreferences,+} from "metabase-types/api";+import { createMockCollectionItem } from "metabase-types/api/mocks";++import { COLLECTIONS_KEY, TYPE_KEY } from "../../constants";++import { CollectionSyncList } from "./CollectionSyncList";++const createMockCollection = (+ overrides?: Partial<ReturnType<typeof createMockCollectionItem>>,+): CollectionItem =>+ createMockCollectionItem({+ model: "collection",+ name: "Test Collection",+ can_write: true,+ is_remote_synced: false,+ ...overrides,+ });++interface SetupOpts {+ collections?: CollectionItem[];+ isLoading?: boolean;+ error?: string | null;+ emptyMessage?: string;+ initialSyncMap?: CollectionSyncPreferences;+ syncType?: "read-only" | "read-write";+}++const setup = ({+ collections = [createMockCollection()],+ isLoading = false,+ error = null,+ emptyMessage = "No collections found",+ initialSyncMap = {},+ syncType = "read-write",+}: SetupOpts = {}) => {+ const onSubmit = jest.fn();++ renderWithProviders(+ <FormProvider+ initialValues={{+ [COLLECTIONS_KEY]: initialSyncMap,+ [TYPE_KEY]: syncType,+ }}+ onSubmit={onSubmit}+ >+ <Form>+ <CollectionSyncList+ collections={collections}+ isLoading={isLoading}+ error={error}+ emptyMessage={emptyMessage}+ />+ <FormSubmitButton label="Save" />+ </Form>+ </FormProvider>,+ );++ return { onSubmit };+};++const setupWithSyncTypeToggle = ({+ collections = [createMockCollection()],+ isLoading = false,+ error = null,+ emptyMessage = "No collections found",+ initialSyncMap = {},+ syncType = "read-write",+}: SetupOpts = {}) => {+ const onSubmit = jest.fn();++ renderWithProviders(+ <FormProvider+ initialValues={{+ [COLLECTIONS_KEY]: initialSyncMap,+ [TYPE_KEY]: syncType,+ }}+ onSubmit={onSubmit}+ >+ <Form>+ <FormRadioGroup name={TYPE_KEY}>+ <Stack>+ <Radio label="Read-only" value="read-only" />+ <Radio label="Read-write" value="read-write" />+ </Stack>+ </FormRadioGroup>+ <CollectionSyncList+ collections={collections}+ isLoading={isLoading}+ error={error}+ emptyMessage={emptyMessage}+ />+ <FormSubmitButton label="Save" />+ </Form>+ </FormProvider>,+ );++ return { onSubmit };+};++describe("CollectionSyncList", () => {+ describe("rendering states", () => {+ it("should show loading state when isLoading is true", () => {+ setup({ isLoading: true });++ expect(screen.getByTestId("loading-indicator")).toBeInTheDocument();+ });++ it("should show empty message when collections array is empty", () => {+ setup({ collections: [], emptyMessage: "Custom empty message" });++ expect(screen.getByText("Custom empty message")).toBeInTheDocument();+ });++ it("should show error message when error is provided", () => {+ setup({ error: "Custom error" });++ expect(screen.getByText("Custom error")).toBeInTheDocument();+ });++ it("should render collections when provided", () => {+ setup({+ collections: [+ createMockCollection({ id: 1, name: "Collection A" }),+ createMockCollection({ id: 2, name: "Collection B" }),+ ],+ });++ expect(screen.getByText("Collection A")).toBeInTheDocument();+ expect(screen.getByText("Collection B")).toBeInTheDocument();+ });+ });++ describe("toggle state from form values", () => {+ it("should show unchecked when syncMap has false value", () => {+ setup({+ collections: [createMockCollection({ id: 1 })],+ initialSyncMap: { 1: false },+ });++ expect(screen.getByRole("switch")).not.toBeChecked();+ });++ it("should show checked when syncMap has true value", () => {+ setup({+ collections: [createMockCollection({ id: 1 })],+ initialSyncMap: { 1: true },+ });++ expect(screen.getByRole("switch")).toBeChecked();+ });++ it("should show unchecked when collection not in syncMap", () => {+ setup({+ collections: [createMockCollection({ id: 1 })],+ initialSyncMap: {},+ });++ expect(screen.getByRole("switch")).not.toBeChecked();+ });+ });++ describe("toggle behavior", () => {+ it("should update form state when toggling on", async () => {+ const { onSubmit } = setup({+ collections: [createMockCollection({ id: 42 })],+ initialSyncMap: { 42: false },+ });++ await userEvent.click(screen.getByRole("switch"));+ await userEvent.click(screen.getByText("Save"));++ await waitFor(() => {+ expect(onSubmit).toHaveBeenCalledWith(+ expect.objectContaining({+ [COLLECTIONS_KEY]: { 42: true },+ }),+ expect.anything(),+ );+ });+ });++ it("should update form state when toggling off", async () => {+ const { onSubmit } = setup({+ collections: [createMockCollection({ id: 42 })],+ initialSyncMap: { 42: true },+ });++ await userEvent.click(screen.getByRole("switch"));+ await userEvent.click(screen.getByText("Save"));++ await waitFor(() => {+ expect(onSubmit).toHaveBeenCalledWith(+ expect.objectContaining({+ [COLLECTIONS_KEY]: { 42: false },+ }),+ expect.anything(),+ );+ });+ });++ it("should handle multiple collections independently", async () => {+ const { onSubmit } = setup({+ collections: [+ createMockCollection({ id: 1, name: "Collection A" }),+ createMockCollection({ id: 2, name: "Collection B" }),+ ],+ initialSyncMap: { 1: false, 2: false },+ });++ const switches = screen.getAllByRole("switch");+ expect(switches).toHaveLength(2);++ // Toggle only the first collection+ await userEvent.click(switches[0]);+ await userEvent.click(screen.getByText("Save"));++ await waitFor(() => {+ expect(onSubmit).toHaveBeenCalledWith(+ expect.objectContaining({+ [COLLECTIONS_KEY]: { 1: true, 2: false },+ }),+ expect.anything(),+ );+ });+ });++ it("should preserve other collections when toggling one", async () => {+ const { onSubmit } = setup({+ collections: [+ createMockCollection({ id: 1, name: "Collection A" }),+ createMockCollection({ id: 2, name: "Collection B" }),+ createMockCollection({ id: 3, name: "Collection C" }),+ ],+ initialSyncMap: { 1: true, 2: false, 3: true },+ });++ const switches = screen.getAllByRole("switch");++ // Toggle the second collection (index 1)+ await userEvent.click(switches[1]);+ await userEvent.click(screen.getByText("Save"));++ await waitFor(() => {+ expect(onSubmit).toHaveBeenCalledWith(+ expect.objectContaining({+ [COLLECTIONS_KEY]: { 1: true, 2: true, 3: true },+ }),+ expect.anything(),+ );+ });+ });+ });++ describe("permissions", () => {+ it("should disable toggle when can_write is false", () => {+ setup({+ collections: [createMockCollection({ can_write: false })],+ });++ expect(screen.getByRole("switch")).toBeDisabled();+ });++ it("should enable toggle when can_write is true", () => {+ setup({+ collections: [createMockCollection({ can_write: true })],+ });++ expect(screen.getByRole("switch")).toBeEnabled();+ });++ it("should disable toggle when sync type is read-only", () => {+ setup({+ collections: [createMockCollection({ can_write: true })],+ syncType: "read-only",+ });++ expect(screen.getByRole("switch")).toBeDisabled();+ });++ it("should enable toggle when sync type is read-write and can_write is true", () => {+ setup({+ collections: [createMockCollection({ can_write: true })],+ syncType: "read-write",+ });++ expect(screen.getByRole("switch")).toBeEnabled();+ });+ });++ describe("mode switching", () => {+ it("should reset collection sync state to initial values when switching from read-write to read-only", async () => {+ const { onSubmit } = setupWithSyncTypeToggle({+ collections: [createMockCollection({ id: 1 })],+ initialSyncMap: { 1: false },+ syncType: "read-write",+ });++ // Toggle the collection sync on+ await userEvent.click(screen.getByRole("switch"));+ expect(screen.getByRole("switch")).toBeChecked();++ // Switch to read-only mode+ await userEvent.click(screen.getByLabelText("Read-only"));++ // The collection sync should be reset to initial value (false)+ await waitFor(() => {+ expect(screen.getByRole("switch")).not.toBeChecked();+ });++ // Submit and verify the collections were reset+ await userEvent.click(screen.getByText("Save"));++ await waitFor(() => {+ expect(onSubmit).toHaveBeenCalledWith(+ expect.objectContaining({+ [COLLECTIONS_KEY]: { 1: false },+ [TYPE_KEY]: "read-only",+ }),+ expect.anything(),+ );+ });+ });++ it("should not reset collection sync state when switching from read-only to read-write", async () => {+ const { onSubmit } = setupWithSyncTypeToggle({+ collections: [createMockCollection({ id: 1 })],+ initialSyncMap: { 1: true },+ syncType: "read-only",+ });++ // Verify initial state is checked+ expect(screen.getByRole("switch")).toBeChecked();++ // Switch to read-write mode+ await userEvent.click(screen.getByLabelText("Read-write"));++ // The collection sync should remain as is+ expect(screen.getByRole("switch")).toBeChecked();++ // Submit and verify the collections were not reset+ await userEvent.click(screen.getByText("Save"));++ await waitFor(() => {+ expect(onSubmit).toHaveBeenCalledWith(+ expect.objectContaining({+ [COLLECTIONS_KEY]: { 1: true },+ [TYPE_KEY]: "read-write",+ }),+ expect.anything(),+ );+ });+ });+ });++ describe("dirty state tracking after reinitialization", () => {+ const SetupWithReinitialize = ({+ collections,+ initialSyncMap,+ syncType = "read-write",+ }: {+ collections: CollectionItem[];+ initialSyncMap: CollectionSyncPreferences;+ syncType?: "read-only" | "read-write";+ }) => {+ const [currentInitialValues, setCurrentInitialValues] = React.useState({+ [COLLECTIONS_KEY]: initialSyncMap,+ [TYPE_KEY]: syncType,+ });+ const [lastSubmittedValues, setLastSubmittedValues] =+ React.useState<Record<string, unknown> | null>(null);++ const handleSubmit = (values: Record<string, unknown>) => {+ setLastSubmittedValues(values);+ // Simulate server update by changing initial values to match submitted values+ setCurrentInitialValues({+ ...currentInitialValues,+ [COLLECTIONS_KEY]: values[+ COLLECTIONS_KEY+ ] as CollectionSyncPreferences,+ });+ };++ return (+ <FormProvider+ initialValues={currentInitialValues}+ onSubmit={handleSubmit}+ enableReinitialize+ >+ {({ dirty }) => (+ <Form>+ <CollectionSyncList+ collections={collections}+ isLoading={false}+ error={null}+ emptyMessage="No collections found"+ />+ <FormSubmitButton+ label="Save"+ disabled={!dirty}+ data-testid="save-button"+ />+ <div data-testid="dirty-status">{dirty ? "dirty" : "clean"}</div>+ <div data-testid="last-submitted">+ {lastSubmittedValues+ ? JSON.stringify(lastSubmittedValues)+ : "none"}+ </div>+ </Form>+ )}+ </FormProvider>+ );+ };++ it("should track dirty state correctly after save and toggle back", async () => {+ const collections = [createMockCollection({ id: 42 })];++ renderWithProviders(+ <SetupWithReinitialize+ collections={collections}+ initialSyncMap={{ 42: true }}+ />,+ );++ // Initial state: collection is synced (ON), form is clean+ expect(screen.getByRole("switch")).toBeChecked();+ expect(screen.getByTestId("dirty-status")).toHaveTextContent("clean");+ expect(screen.getByTestId("save-button")).toBeDisabled();++ // Toggle collection OFF+ await userEvent.click(screen.getByRole("switch"));+ expect(screen.getByRole("switch")).not.toBeChecked();+ expect(screen.getByTestId("dirty-status")).toHaveTextContent("dirty");+ expect(screen.getByTestId("save-button")).toBeEnabled();++ // Save - this triggers reinitialization with new values+ await userEvent.click(screen.getByTestId("save-button"));++ // After save, form should be clean with new initial values+ await waitFor(() => {+ expect(screen.getByTestId("dirty-status")).toHaveTextContent("clean");+ });+ expect(screen.getByRole("switch")).not.toBeChecked();+ expect(screen.getByTestId("save-button")).toBeDisabled();++ // Toggle back to ON (original value)+ await userEvent.click(screen.getByRole("switch"));++ // Form should now be dirty because current value (ON) differs from saved value (OFF)+ expect(screen.getByRole("switch")).toBeChecked();+ expect(screen.getByTestId("dirty-status")).toHaveTextContent("dirty");+ expect(screen.getByTestId("save-button")).toBeEnabled();+ });++ it("should track dirty state correctly with multiple toggles after reinitialization", async () => {+ const collections = [+ createMockCollection({ id: 1, name: "Collection A" }),+ createMockCollection({ id: 2, name: "Collection B" }),+ ];++ renderWithProviders(+ <SetupWithReinitialize+ collections={collections}+ initialSyncMap={{ 1: true, 2: false }}+ />,+ );++ const switches = screen.getAllByRole("switch");++ // Initial state+ expect(switches[0]).toBeChecked(); // Collection 1 is ON+ expect(switches[1]).not.toBeChecked(); // Collection 2 is OFF+ expect(screen.getByTestId("dirty-status")).toHaveTextContent("clean");++ // Toggle collection 1 OFF+ await userEvent.click(switches[0]);+ expect(screen.getByTestId("dirty-status")).toHaveTextContent("dirty");++ // Save+ await userEvent.click(screen.getByTestId("save-button"));++ await waitFor(() => {+ expect(screen.getByTestId("dirty-status")).toHaveTextContent("clean");+ });++ // Now toggle collection 2 ON+ await userEvent.click(switches[1]);+ expect(screen.getByTestId("dirty-status")).toHaveTextContent("dirty");+ expect(screen.getByTestId("save-button")).toBeEnabled();+ });+ });+});diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/CollectionSyncList/index.ts b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/CollectionSyncList/index.tsnew file mode 100644index 00000000000..93b9e27f5ca--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/CollectionSyncList/index.ts@@ -0,0 +1 @@+export { CollectionSyncList } from "./CollectionSyncList";diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/CollectionSyncRow/CollectionSyncRow.tsx b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/CollectionSyncRow/CollectionSyncRow.tsxnew file mode 100644index 00000000000..db41668504c--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/CollectionSyncRow/CollectionSyncRow.tsx@@ -0,0 +1,54 @@+import { c, t } from "ttag";++import { PLUGIN_COLLECTIONS } from "metabase/plugins";+import { Box, Flex, Icon, Switch, Text } from "metabase/ui";+import type { CollectionItem } from "metabase-types/api";++interface CollectionSyncRowProps {+ collection: CollectionItem;+ isChecked: boolean;+ onToggle: (collection: CollectionItem, checked: boolean) => void;+ isLast: boolean;+ isReadOnly: boolean;+}++export const CollectionSyncRow = ({+ collection,+ isChecked,+ onToggle,+ isLast,+ isReadOnly,+}: CollectionSyncRowProps) => {+ const canWrite = collection.can_write ?? false;+ const icon = PLUGIN_COLLECTIONS.getIcon({+ model: "collection",+ is_remote_synced: isChecked,+ });++ return (+ <Box+ p="md"+ style={{+ borderBottom: isLast ? undefined : "1px solid var(--mb-color-border)",+ }}+ >+ <Flex justify="space-between" align="center">+ <Flex align="center" gap="sm">+ <Icon name={icon.name} c={icon.color ?? "text-medium"} />+ <Text fw="medium">{collection.name}</Text>+ </Flex>+ <Flex align="center" gap="sm">+ <Switch+ size="sm"+ checked={isChecked}+ onChange={(e) => onToggle(collection, e.currentTarget.checked)}+ disabled={!canWrite || isReadOnly}+ aria-label={c("{0} is the name of a metabase collection")+ .t`Sync ${collection.name}`}+ />+ <Text>{t`Sync`}</Text>+ </Flex>+ </Flex>+ </Box>+ );+};diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/CollectionSyncRow/CollectionSyncRow.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/CollectionSyncRow/CollectionSyncRow.unit.spec.tsxnew file mode 100644index 00000000000..17eced59532--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/CollectionSyncRow/CollectionSyncRow.unit.spec.tsx@@ -0,0 +1,152 @@+import userEvent from "@testing-library/user-event";++import { renderWithProviders, screen } from "__support__/ui";+import type { CollectionItem } from "metabase-types/api";+import { createMockCollectionItem } from "metabase-types/api/mocks";++import { CollectionSyncRow } from "./CollectionSyncRow";++const createMockCollection = (+ overrides?: Partial<ReturnType<typeof createMockCollectionItem>>,+): CollectionItem =>+ createMockCollectionItem({+ model: "collection",+ name: "Test Collection",+ can_write: true,+ is_remote_synced: false,+ ...overrides,+ });++interface SetupOpts {+ collection?: CollectionItem;+ isChecked?: boolean;+ isLast?: boolean;+ isReadOnly?: boolean;+}++const setup = ({+ collection = createMockCollection(),+ isChecked = false,+ isLast = true,+ isReadOnly = false,+}: SetupOpts = {}) => {+ const onToggle = jest.fn();++ renderWithProviders(+ <CollectionSyncRow+ collection={collection}+ isChecked={isChecked}+ onToggle={onToggle}+ isLast={isLast}+ isReadOnly={isReadOnly}+ />,+ );++ return { onToggle };+};++describe("CollectionSyncRow", () => {+ describe("rendering", () => {+ it("should render collection name", () => {+ setup({ collection: createMockCollection({ name: "My Collection" }) });++ expect(screen.getByText("My Collection")).toBeInTheDocument();+ });++ it("should render sync label", () => {+ setup();++ expect(screen.getByText("Sync")).toBeInTheDocument();+ });++ it("should render a switch toggle", () => {+ setup();++ expect(screen.getByRole("switch")).toBeInTheDocument();+ });++ it("should have aria-label for accessibility", () => {+ setup({ collection: createMockCollection({ name: "Analytics" }) });++ expect(+ screen.getByRole("switch", { name: /sync analytics/i }),+ ).toBeInTheDocument();+ });+ });++ describe("toggle state", () => {+ it("should show unchecked when isChecked is false", () => {+ setup({ isChecked: false });++ expect(screen.getByRole("switch")).not.toBeChecked();+ });++ it("should show checked when isChecked is true", () => {+ setup({ isChecked: true });++ expect(screen.getByRole("switch")).toBeChecked();+ });+ });++ describe("toggle interaction", () => {+ it("should call onToggle with collection and true when toggling on", async () => {+ const collection = createMockCollection({ id: 42 });+ const { onToggle } = setup({ collection, isChecked: false });++ await userEvent.click(screen.getByRole("switch"));++ expect(onToggle).toHaveBeenCalledWith(collection, true);+ });++ it("should call onToggle with collection and false when toggling off", async () => {+ const collection = createMockCollection({ id: 42 });+ const { onToggle } = setup({ collection, isChecked: true });++ await userEvent.click(screen.getByRole("switch"));++ expect(onToggle).toHaveBeenCalledWith(collection, false);+ });+ });++ describe("disabled state", () => {+ it("should disable toggle when can_write is false", () => {+ setup({ collection: createMockCollection({ can_write: false }) });++ expect(screen.getByRole("switch")).toBeDisabled();+ });++ it("should enable toggle when can_write is true", () => {+ setup({ collection: createMockCollection({ can_write: true }) });++ expect(screen.getByRole("switch")).toBeEnabled();+ });++ it("should disable toggle when isReadOnly is true", () => {+ setup({+ collection: createMockCollection({ can_write: true }),+ isReadOnly: true,+ });++ expect(screen.getByRole("switch")).toBeDisabled();+ });++ it("should disable toggle when can_write is false and isReadOnly is true", () => {+ setup({+ collection: createMockCollection({ can_write: false }),+ isReadOnly: true,+ });++ expect(screen.getByRole("switch")).toBeDisabled();+ });++ it("should not call onToggle when disabled and clicked", async () => {+ const { onToggle } = setup({+ collection: createMockCollection({ can_write: false }),+ });++ await userEvent.click(screen.getByRole("switch"));++ expect(onToggle).not.toHaveBeenCalled();+ });+ });+});diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/CollectionSyncRow/index.ts b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/CollectionSyncRow/index.tsnew file mode 100644index 00000000000..9c7ac0ca622--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/CollectionSyncRow/index.ts@@ -0,0 +1 @@+export { CollectionSyncRow } from "./CollectionSyncRow";diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/GitSyncControls/GitSyncControls.tsx b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/GitSyncControls/GitSyncControls.tsxindex 214431aaaf3..967cb2fbcc0 100644--- a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/GitSyncControls/GitSyncControls.tsx+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/GitSyncControls/GitSyncControls.tsx@@ -1,11 +1,8 @@-import { useCallback, useMemo, useState } from "react";+import { useCallback, useState } from "react";import { t } from "ttag";-import { useListCollectionsTreeQuery } from "metabase/api";import { useAdminSetting } from "metabase/api/utils";-import { isSyncedCollection } from "metabase/collections/utils";import { useToast } from "metabase/common/hooks";-import { buildCollectionTree } from "metabase/entities/collections";import { useSelector } from "metabase/lib/redux";import { getUserIsAdmin } from "metabase/selectors/user";import { Button, Icon, Loader, Tooltip } from "metabase/ui";@@ -48,20 +45,6 @@ export const GitSyncControls = () => {refetchOnFocus: true,});- // Fetch collections to filter synced ones for the push modal- const { data: collections = [] } = useListCollectionsTreeQuery(- {- "exclude-other-user-collections": true,- "exclude-archived": true,- },- { skip: !isRemoteSyncEnabled },- );-- const syncedCollections = useMemo(() => {- const synced = collections.filter(isSyncedCollection);- return buildCollectionTree(synced);- }, [collections]);-const isSwitchingBranch = !!nextBranch;const isDirty = !!(dirtyData?.dirty && dirtyData.dirty.length > 0);const isLoading = isSyncTaskRunning || isSwitchingBranch || isImporting;@@ -219,14 +202,12 @@ export const GitSyncControls = () => {{showPushModal && (<PushChangesModalonClose={handleClosePushModal}- collections={syncedCollections}currentBranch={currentBranch}/>)}{syncConflictVariant && (<SyncConflictModal- collections={syncedCollections}currentBranch={currentBranch}nextBranch={nextBranch}onClose={handleCloseSyncConflictModal}diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/PushChangesModal/PushChangesModal.tsx b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/PushChangesModal/PushChangesModal.tsxindex 0c2156b5a16..1e6b6d44e90 100644--- a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/PushChangesModal/PushChangesModal.tsx+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/PushChangesModal/PushChangesModal.tsx@@ -12,7 +12,6 @@ import {Stack,} from "metabase/ui";import { useExportChangesMutation } from "metabase-enterprise/api";-import type { Collection } from "metabase-types/api";import { trackPushChanges } from "../../analytics";import { type SyncError, parseSyncError } from "../../utils";@@ -22,7 +21,6 @@ import { SyncConflictModal } from "../SyncConflictModal";import { CommitMessageSection } from "./CommitMessageSection";interface PushChangesModalProps {- collections: Collection[];currentBranch: string;onClose: () => void;}@@ -30,7 +28,6 @@ interface PushChangesModalProps {export const PushChangesModal = ({onClose,currentBranch,- collections,}: PushChangesModalProps) => {const [commitMessage, setCommitMessage] = useState("");@@ -69,7 +66,6 @@ export const PushChangesModal = ({if (hasConflict) {return (<SyncConflictModal- collections={collections}currentBranch={currentBranch}onClose={onClose}variant="push"@@ -93,7 +89,7 @@ export const PushChangesModal = ({)}<Stack gap="lg">- <ChangesLists collections={collections} title={t`Changes to push`} />+ <ChangesLists title={t`Changes to push`} /><CommitMessageSectionvalue={commitMessage}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 131dd0cc2b5..27cf6a606c6 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@@ -34,6 +34,7 @@ import {Text,Tooltip,} from "metabase/ui";+import { useGetLibraryCollectionQuery } from "metabase-enterprise/api";import {useGetRemoteSyncChangesQuery,useUpdateRemoteSyncSettingsMutation,@@ -59,6 +60,7 @@ import {URL_KEY,} from "../../constants";import { SharedTenantCollectionsList } from "../SharedTenantCollectionsList";+import { TopLevelCollectionsList } from "../TopLevelCollectionsList";import { PullChangesButton } from "./PullChangesButton";@@ -77,6 +79,23 @@ export const RemoteSyncAdminSettings = () => {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 stateconst { data: tenantCollectionsData } = useListCollectionItemsQuery({@@ -101,9 +120,20 @@ export const RemoteSyncAdminSettings = () => {async (values: RemoteSyncConfigurationSettings) => {const didBranchChange =values[BRANCH_KEY] !== settingValues?.[BRANCH_KEY];- const saveSettings = async (values: RemoteSyncConfigurationSettings) => {++ // 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(values).unwrap();+ await updateRemoteSyncSettings(settings).unwrap();trackRemoteSyncSettingsChanged();@@ -128,7 +158,7 @@ export const RemoteSyncAdminSettings = () => {};if (didBranchChange) {- pendingConfirmationSettingsRef.current = values;+ 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.`,@@ -149,7 +179,7 @@ export const RemoteSyncAdminSettings = () => {});return;}- await saveSettings(values);+ await saveSettings(settingsToSave);},[settingValues,@@ -193,6 +223,21 @@ export const RemoteSyncAdminSettings = () => {// Build initial collection sync map from server dataconst 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 collectionstenantCollectionsData?.data?.forEach((collection) => {collectionSyncMap[collection.id] = collection.is_remote_synced ?? false;});@@ -202,7 +247,13 @@ export const RemoteSyncAdminSettings = () => {[TOKEN_KEY]: tokenValue,[COLLECTIONS_KEY]: collectionSyncMap,};- }, [settingValues, settingDetails, tenantCollectionsData]);+ }, [+ settingValues,+ settingDetails,+ libraryCollection,+ topLevelCollectionsData,+ tenantCollectionsData,+ ]);// eslint-disable-next-line no-unconditional-metabase-links-render -- This links only shows for admins.const { url: docsUrl } = useDocsUrl(@@ -313,13 +364,25 @@ export const RemoteSyncAdminSettings = () => {</SettingsSection>)}- {/* Section 4: Shared tenant collections to sync */}- {isRemoteSyncEnabled && useTenants && (+ {/* Section 4: Collections to sync */}+ {isRemoteSyncEnabled && (<SettingsSection- title={t`Shared tenant collections to sync`}- description={t`Choose which shared tenant collections to sync with git.`}+ title={t`Collections to sync`}+ description={t`Choose which collections to sync with git.`}>- <SharedTenantCollectionsList />+ <Stack gap="lg">+ <TopLevelCollectionsList />+ {useTenants && (+ <>+ <Text+ fw={700}+ size="md"+ lh="16px"+ >{t`Shared collections`}</Text>+ <SharedTenantCollectionsList />+ </>+ )}+ </Stack></SettingsSection>)}diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/SharedTenantCollectionsList/SharedTenantCollectionsList.tsx b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/SharedTenantCollectionsList/SharedTenantCollectionsList.tsxindex 192a54e33c6..4e7226aa11f 100644--- a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/SharedTenantCollectionsList/SharedTenantCollectionsList.tsx+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/SharedTenantCollectionsList/SharedTenantCollectionsList.tsx@@ -1,138 +1,21 @@-import { useFormikContext } from "formik";-import { useCallback, useEffect, useMemo } from "react";-import { usePrevious } from "react-use";-import { c, t } from "ttag";+import { t } from "ttag";import { useListCollectionItemsQuery } from "metabase/api";-import { PLUGIN_COLLECTIONS } from "metabase/plugins";-import { Box, Flex, Icon, Loader, Switch, Text } from "metabase/ui";-import type {- CollectionItem,- CollectionSyncPreferences,- RemoteSyncConfigurationSettings,-} from "metabase-types/api";-import { COLLECTIONS_KEY, TYPE_KEY } from "../../constants";+import { CollectionSyncList } from "../CollectionSyncList";export const SharedTenantCollectionsList = () => {const { data, isLoading, error } = useListCollectionItemsQuery({id: "root",namespace: "shared-tenant-collection",});- const { values, setFieldValue, initialValues } =- useFormikContext<RemoteSyncConfigurationSettings>();-- const collections = data?.data ?? [];- const syncMap: CollectionSyncPreferences = useMemo(- () => values[COLLECTIONS_KEY] ?? {},- [values],- );- const currentType = values[TYPE_KEY];- const isReadOnly = currentType === "read-only";- const previousType = usePrevious(currentType);-- // Reset collections to initial values when switching from read-write to read-only- useEffect(() => {- if (previousType === "read-write" && currentType === "read-only") {- setFieldValue(COLLECTIONS_KEY, initialValues[COLLECTIONS_KEY] ?? {});- }- }, [currentType, initialValues, setFieldValue, previousType]);-- const handleToggle = useCallback(- (collection: CollectionItem, checked: boolean) => {- // Update form state directly via Formik context- setFieldValue(COLLECTIONS_KEY, {- ...syncMap,- [collection.id]: checked,- });- },- [syncMap, setFieldValue],- );-- if (isLoading) {- return (- <Flex justify="center" py="lg">- <Loader data-testid="loading-indicator" />- </Flex>- );- }-- if (error) {- return <Text c="error">{t`Failed to load shared tenant collections`}</Text>;- }-- if (collections.length === 0) {- return <Text c="text-medium">{t`No shared tenant collections found`}</Text>;- }-- return (- <Box- style={{- borderRadius: "var(--mantine-radius-md)",- border: "1px solid var(--mb-color-border)",- backgroundColor: "var(--mb-color-bg-white)",- overflow: "hidden",- }}- >- {collections.map((collection, index) => (- <CollectionSyncRow- key={collection.id}- collection={collection}- isChecked={syncMap[collection.id] ?? false}- onToggle={handleToggle}- isLast={index === collections.length - 1}- isReadOnly={isReadOnly}- />- ))}- </Box>- );-};--interface CollectionSyncRowProps {- collection: CollectionItem;- isChecked: boolean;- onToggle: (collection: CollectionItem, checked: boolean) => void;- isLast: boolean;- isReadOnly: boolean;-}--const CollectionSyncRow = ({- collection,- isChecked,- onToggle,- isLast,- isReadOnly,-}: CollectionSyncRowProps) => {- const canWrite = collection.can_write ?? false;- const icon = PLUGIN_COLLECTIONS.getIcon({- model: "collection",- is_remote_synced: isChecked,- });return (- <Box- p="md"- style={{- borderBottom: isLast ? undefined : "1px solid var(--mb-color-border)",- }}- >- <Flex justify="space-between" align="center">- <Flex align="center" gap="sm">- <Icon name={icon.name} c={icon.color ?? "text-medium"} />- <Text fw="medium">{collection.name}</Text>- </Flex>- <Flex align="center" gap="sm">- <Switch- size="sm"- checked={isChecked}- onChange={(e) => onToggle(collection, e.currentTarget.checked)}- disabled={!canWrite || isReadOnly}- aria-label={c("{0} is the name of a metabase collection")- .t`Sync ${collection.name}`}- />- <Text>{t`Sync`}</Text>- </Flex>- </Flex>- </Box>+ <CollectionSyncList+ collections={data?.data ?? []}+ isLoading={isLoading}+ error={error ? t`Failed to load shared tenant collections` : null}+ emptyMessage={t`No shared tenant collections found`}+ />);};diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/SyncConflictModal/SyncConflictModal.tsx b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/SyncConflictModal/SyncConflictModal.tsxindex 183d0fe9472..81b634412c3 100644--- a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/SyncConflictModal/SyncConflictModal.tsx+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/SyncConflictModal/SyncConflictModal.tsx@@ -3,7 +3,6 @@ import { t } from "ttag";import { Box, Button, Group, Icon, Modal } from "metabase/ui";import { useGetBranchesQuery } from "metabase-enterprise/api";-import type { Collection } from "metabase-types/api";import { ChangesLists } from "../ChangesLists";@@ -21,7 +20,6 @@ import {} from "./utils";interface UnsyncedWarningModalProps {- collections: Collection[];currentBranch: string;nextBranch?: string | null;onClose: VoidFunction;@@ -29,7 +27,7 @@ interface UnsyncedWarningModalProps {}export const SyncConflictModal = (props: UnsyncedWarningModalProps) => {- const { collections, onClose, currentBranch, nextBranch, variant } = props;+ const { onClose, currentBranch, nextBranch, variant } = props;const [optionValue, setOptionValue] = useState<OptionValue>();const [newBranchName, setNewBranchName] = useState<string>("");const { data: branchesData } = useGetBranchesQuery();@@ -92,7 +90,7 @@ export const SyncConflictModal = (props: UnsyncedWarningModalProps) => {withCloseButton={false}><Box pt="md">- <ChangesLists collections={collections} />+ <ChangesLists /><OutOfSyncOptionscurrentBranch={currentBranch}diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/TopLevelCollectionsList/TopLevelCollectionsList.tsx b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/TopLevelCollectionsList/TopLevelCollectionsList.tsxnew file mode 100644index 00000000000..ca7281b8d31--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/TopLevelCollectionsList/TopLevelCollectionsList.tsx@@ -0,0 +1,47 @@+import { useMemo } from "react";+import { t } from "ttag";++import { useListCollectionItemsQuery } from "metabase/api";+import { useGetLibraryCollectionQuery } from "metabase-enterprise/api";+import type { CollectionItem } from "metabase-types/api";++import { CollectionSyncList } from "../CollectionSyncList";++export const TopLevelCollectionsList = () => {+ const { data, isLoading, error } = useListCollectionItemsQuery({+ id: "root",+ models: ["collection"],+ });++ const { data: libraryCollectionData, isLoading: isLoadingLibrary } =+ useGetLibraryCollectionQuery();++ // Library collection endpoint returns { data: null } when not found+ const libraryCollection: CollectionItem | undefined =+ libraryCollectionData && "name" in libraryCollectionData+ ? libraryCollectionData+ : undefined;++ // Filter out personal collections and analytics collections, combine with library collection+ const collections = useMemo(() => {+ const topLevelCollections = (data?.data ?? []).filter(+ (c) => !c.personal_owner_id && c.type !== "instance-analytics",+ );++ // Add library collection at the beginning if it exists+ if (libraryCollection) {+ return [libraryCollection, ...topLevelCollections];+ }++ return topLevelCollections;+ }, [data, libraryCollection]);++ return (+ <CollectionSyncList+ collections={collections}+ isLoading={isLoading || isLoadingLibrary}+ error={error ? t`Failed to load collections` : null}+ emptyMessage={t`No collections found`}+ />+ );+};diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/TopLevelCollectionsList/TopLevelCollectionsList.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/TopLevelCollectionsList/TopLevelCollectionsList.unit.spec.tsxnew file mode 100644index 00000000000..a961133cb3e--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/TopLevelCollectionsList/TopLevelCollectionsList.unit.spec.tsx@@ -0,0 +1,432 @@+import userEvent from "@testing-library/user-event";+import fetchMock from "fetch-mock";++import { renderWithProviders, screen, waitFor } from "__support__/ui";+import { Form, FormProvider, FormSubmitButton } from "metabase/forms";+import type { CollectionSyncPreferences } from "metabase-types/api";+import { createMockCollectionItem } from "metabase-types/api/mocks";++import { COLLECTIONS_KEY, TYPE_KEY } from "../../constants";++import { TopLevelCollectionsList } from "./TopLevelCollectionsList";++const createMockTopLevelCollectionItem = (+ overrides?: Partial<ReturnType<typeof createMockCollectionItem>>,+) =>+ createMockCollectionItem({+ model: "collection",+ name: "Top Level Collection",+ can_write: true,+ is_remote_synced: false,+ ...overrides,+ });++const createMockLibraryCollection = (+ overrides?: Partial<ReturnType<typeof createMockCollectionItem>>,+) =>+ createMockCollectionItem({+ id: 999,+ model: "collection",+ name: "Library",+ can_write: true,+ is_remote_synced: false,+ type: "library",+ ...overrides,+ });++const setupEndpoints = ({+ collections = [createMockTopLevelCollectionItem()],+ libraryCollection = null as ReturnType<+ typeof createMockCollectionItem+ > | null,+}: {+ collections?: ReturnType<typeof createMockCollectionItem>[];+ libraryCollection?: ReturnType<typeof createMockCollectionItem> | null;+} = {}) => {+ fetchMock.get(+ "express:/api/collection/root/items",+ { data: collections },+ { name: "root-items" },+ );++ fetchMock.get(+ "express:/api/ee/library",+ libraryCollection ?? { data: null },+ { name: "library" },+ );+};++interface SetupOpts {+ collections?: ReturnType<typeof createMockCollectionItem>[];+ libraryCollection?: ReturnType<typeof createMockCollectionItem> | null;+ initialSyncMap?: CollectionSyncPreferences;+ syncType?: "read-only" | "read-write";+}++const setup = ({+ collections = [createMockTopLevelCollectionItem()],+ libraryCollection = null,+ initialSyncMap = {},+ syncType = "read-write",+}: SetupOpts = {}) => {+ setupEndpoints({ collections, libraryCollection });++ const onSubmit = jest.fn();++ renderWithProviders(+ <FormProvider+ initialValues={{+ [COLLECTIONS_KEY]: initialSyncMap,+ [TYPE_KEY]: syncType,+ }}+ onSubmit={onSubmit}+ >+ <Form>+ <TopLevelCollectionsList />+ <FormSubmitButton label="Save" />+ </Form>+ </FormProvider>,+ );++ return { onSubmit };+};++describe("TopLevelCollectionsList", () => {+ beforeEach(() => {+ fetchMock.removeRoutes();+ fetchMock.clearHistory();+ });++ describe("rendering", () => {+ it("should show loading state while fetching", async () => {+ fetchMock.get(+ "express:/api/collection/root/items",+ { data: [] },+ { name: "root-items", delay: 100 },+ );+ fetchMock.get(+ "express:/api/ee/library",+ { data: null },+ { name: "library", delay: 100 },+ );++ renderWithProviders(+ <FormProvider+ initialValues={{+ [COLLECTIONS_KEY]: {},+ [TYPE_KEY]: "read-write",+ }}+ onSubmit={jest.fn()}+ >+ <Form>+ <TopLevelCollectionsList />+ </Form>+ </FormProvider>,+ );++ expect(screen.getByTestId("loading-indicator")).toBeInTheDocument();+ });++ it("should show empty state when no collections exist", async () => {+ setup({ collections: [], libraryCollection: null });++ await waitFor(() => {+ expect(screen.getByText("No collections found")).toBeInTheDocument();+ });+ });++ it("should show error state when API fails", async () => {+ fetchMock.get(+ "express:/api/collection/root/items",+ { status: 500 },+ { name: "root-items" },+ );+ fetchMock.get(+ "express:/api/ee/library",+ { data: null },+ { name: "library" },+ );++ renderWithProviders(+ <FormProvider+ initialValues={{+ [COLLECTIONS_KEY]: {},+ [TYPE_KEY]: "read-write",+ }}+ onSubmit={jest.fn()}+ >+ <Form>+ <TopLevelCollectionsList />+ </Form>+ </FormProvider>,+ );++ await waitFor(() => {+ expect(+ screen.getByText("Failed to load collections"),+ ).toBeInTheDocument();+ });+ });++ it("should render list of collections", async () => {+ const collections = [+ createMockTopLevelCollectionItem({ id: 1, name: "Collection A" }),+ createMockTopLevelCollectionItem({ id: 2, name: "Collection B" }),+ ];++ setup({ collections });++ await waitFor(() => {+ expect(screen.getByText("Collection A")).toBeInTheDocument();+ });+ expect(screen.getByText("Collection B")).toBeInTheDocument();+ });+ });++ describe("filtering", () => {+ it("should filter out personal collections", async () => {+ const collections = [+ createMockTopLevelCollectionItem({ id: 1, name: "Team Collection" }),+ createMockTopLevelCollectionItem({+ id: 2,+ name: "Personal Collection",+ personal_owner_id: 123,+ }),+ ];++ setup({ collections });++ await waitFor(() => {+ expect(screen.getByText("Team Collection")).toBeInTheDocument();+ });++ expect(screen.queryByText("Personal Collection")).not.toBeInTheDocument();+ });++ it("should filter out instance-analytics collections", async () => {+ const collections = [+ createMockTopLevelCollectionItem({ id: 1, name: "Team Collection" }),+ createMockTopLevelCollectionItem({+ id: 2,+ name: "Usage Analytics",+ type: "instance-analytics",+ }),+ ];++ setup({ collections });++ await waitFor(() => {+ expect(screen.getByText("Team Collection")).toBeInTheDocument();+ });++ expect(screen.queryByText("Usage Analytics")).not.toBeInTheDocument();+ });++ it("should filter out both personal and analytics collections", async () => {+ const collections = [+ createMockTopLevelCollectionItem({ id: 1, name: "Team Collection" }),+ createMockTopLevelCollectionItem({+ id: 2,+ name: "Personal Collection",+ personal_owner_id: 123,+ }),+ createMockTopLevelCollectionItem({+ id: 3,+ name: "Usage Analytics",+ type: "instance-analytics",+ }),+ ];++ setup({ collections });++ await waitFor(() => {+ expect(screen.getByText("Team Collection")).toBeInTheDocument();+ });++ expect(screen.queryByText("Personal Collection")).not.toBeInTheDocument();+ expect(screen.queryByText("Usage Analytics")).not.toBeInTheDocument();+ });+ });++ describe("library collection", () => {+ it("should include library collection when it exists", async () => {+ const collections = [+ createMockTopLevelCollectionItem({ id: 1, name: "Regular Collection" }),+ ];+ const libraryCollection = createMockLibraryCollection();++ setup({ collections, libraryCollection });++ await waitFor(() => {+ expect(screen.getByText("Library")).toBeInTheDocument();+ });+ expect(screen.getByText("Regular Collection")).toBeInTheDocument();+ });++ it("should show library collection first in the list", async () => {+ const collections = [+ createMockTopLevelCollectionItem({ id: 1, name: "A Collection" }),+ ];+ const libraryCollection = createMockLibraryCollection();++ setup({ collections, libraryCollection });++ await waitFor(() => {+ expect(screen.getByText("Library")).toBeInTheDocument();+ });++ const switches = screen.getAllByRole("switch");+ expect(switches).toHaveLength(2);++ // Library should be first (based on the order in the DOM)+ const collectionNames = screen+ .getAllByText(/Library|A Collection/)+ .map((el) => el.textContent);+ expect(collectionNames[0]).toBe("Library");+ });++ it("should work without library collection", async () => {+ const collections = [+ createMockTopLevelCollectionItem({ id: 1, name: "Collection A" }),+ ];++ setup({ collections, libraryCollection: null });++ await waitFor(() => {+ expect(screen.getByText("Collection A")).toBeInTheDocument();+ });++ expect(screen.queryByText("Library")).not.toBeInTheDocument();+ });+ });++ describe("toggle state from form values", () => {+ it("should show unchecked when syncMap has false value", async () => {+ setup({+ collections: [createMockTopLevelCollectionItem({ id: 1 })],+ initialSyncMap: { 1: false },+ });++ await waitFor(() => {+ expect(screen.getByRole("switch")).not.toBeChecked();+ });+ });++ it("should show checked when syncMap has true value", async () => {+ setup({+ collections: [createMockTopLevelCollectionItem({ id: 1 })],+ initialSyncMap: { 1: true },+ });++ await waitFor(() => {+ expect(screen.getByRole("switch")).toBeChecked();+ });+ });+ });++ describe("deferred save behavior", () => {+ it("should update form state when toggling on", async () => {+ const { onSubmit } = setup({+ collections: [createMockTopLevelCollectionItem({ id: 42 })],+ initialSyncMap: { 42: false },+ });++ await waitFor(() => {+ expect(screen.getByRole("switch")).toBeInTheDocument();+ });++ await userEvent.click(screen.getByRole("switch"));+ await userEvent.click(screen.getByText("Save"));++ await waitFor(() => {+ expect(onSubmit).toHaveBeenCalledWith(+ expect.objectContaining({+ [COLLECTIONS_KEY]: { 42: true },+ }),+ expect.anything(),+ );+ });+ });++ it("should update form state when toggling off", async () => {+ const { onSubmit } = setup({+ collections: [createMockTopLevelCollectionItem({ id: 42 })],+ initialSyncMap: { 42: true },+ });++ await waitFor(() => {+ expect(screen.getByRole("switch")).toBeInTheDocument();+ });++ await userEvent.click(screen.getByRole("switch"));+ await userEvent.click(screen.getByText("Save"));++ await waitFor(() => {+ expect(onSubmit).toHaveBeenCalledWith(+ expect.objectContaining({+ [COLLECTIONS_KEY]: { 42: false },+ }),+ expect.anything(),+ );+ });+ });++ it("should handle toggling library collection", async () => {+ const libraryCollection = createMockLibraryCollection({ id: 999 });+ const { onSubmit } = setup({+ collections: [],+ libraryCollection,+ initialSyncMap: { 999: false },+ });++ await waitFor(() => {+ expect(screen.getByRole("switch")).toBeInTheDocument();+ });++ await userEvent.click(screen.getByRole("switch"));+ await userEvent.click(screen.getByText("Save"));++ await waitFor(() => {+ expect(onSubmit).toHaveBeenCalledWith(+ expect.objectContaining({+ [COLLECTIONS_KEY]: { 999: true },+ }),+ expect.anything(),+ );+ });+ });+ });++ describe("permissions", () => {+ it("should disable toggle when can_write is false", async () => {+ setup({+ collections: [createMockTopLevelCollectionItem({ can_write: false })],+ });++ await waitFor(() => {+ expect(screen.getByRole("switch")).toBeDisabled();+ });+ });++ it("should enable toggle when can_write is true", async () => {+ setup({+ collections: [createMockTopLevelCollectionItem({ can_write: true })],+ });++ await waitFor(() => {+ expect(screen.getByRole("switch")).toBeEnabled();+ });+ });++ it("should disable toggle when sync type is read-only", async () => {+ setup({+ collections: [createMockTopLevelCollectionItem({ can_write: true })],+ syncType: "read-only",+ });++ await waitFor(() => {+ expect(screen.getByRole("switch")).toBeDisabled();+ });+ });+ });+});diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/TopLevelCollectionsList/index.ts b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/TopLevelCollectionsList/index.tsnew file mode 100644index 00000000000..0f8b132122f--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/TopLevelCollectionsList/index.ts@@ -0,0 +1 @@+export { TopLevelCollectionsList } from "./TopLevelCollectionsList";