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
Move remote-sync branch switching into Settings with destructive-action guard rails (GHY-4019) (#77286)
Eric Normand0a3932e9cf1c
diff --git a/e2e/support/helpers/e2e-remote-sync-helpers.ts b/e2e/support/helpers/e2e-remote-sync-helpers.tsindex 161d509e465..2bc4d443353 100644--- a/e2e/support/helpers/e2e-remote-sync-helpers.ts+++ b/e2e/support/helpers/e2e-remote-sync-helpers.ts@@ -236,22 +236,16 @@ export const getPushOption = () => {return popover().findByRole("option", { name: /Push changes/ });};-export const getSwitchBranchOption = () => {- ensureGitSyncMenuOpen();- return popover().findByRole("option", { name: /Switch branch/ });-};-// Mantine combobox options can drop a synthetic `.click()` if the dropdown's// state machine isn't fully wired yet (e.g. right after the menu opens — the// dropdown is visible but the option's handler isn't attached). `realClick`// dispatches native mouse events that Mantine processes reliably, and we then// verify the menu closed; if not, re-click once with a synthetic click.//-// We detect "menu still open" by looking for the main-menu options-// (Pull/Push/Switch branch) — neither "any popover visible" nor the controls'-// `data-expanded` attribute distinguishes the main menu from follow-up popovers-// like the branch picker that opens after clicking "Switch branch".-const MAIN_MENU_OPTION_RE = /Pull changes|Push changes|Switch branch/;+// We detect "menu still open" by looking for the main-menu options (Pull/Push) —+// neither "any popover visible" nor the controls' `data-expanded` attribute+// distinguishes the main menu from follow-up popovers.+const MAIN_MENU_OPTION_RE = /Pull changes|Push changes/;const clickGitSyncOption = (getOption: () => Cypress.Chainable<JQuery<HTMLElement>>,) => {@@ -271,8 +265,40 @@ const clickGitSyncOption = (export const clickPullOption = () => clickGitSyncOption(getPullOption);export const clickPushOption = () => clickGitSyncOption(getPushOption);-export const clickSwitchBranchOption = () =>- clickGitSyncOption(getSwitchBranchOption);++// --- Branch switching (moved from the app bar to the instance Settings panel) ---++export const visitRemoteSyncSettings = () =>+ cy.visit("/admin/settings/remote-sync");++// The read-write branch switcher lives in the "Sync branch" section of the Settings page.+export const getSettingsBranchSwitcher = () =>+ cy.findByTestId("settings-branch-switcher");++// Open the branch picker on the Settings page (navigates there first).+const openSettingsBranchPicker = () => {+ visitRemoteSyncSettings();+ // The Sync branch section sits below the fold at the default viewport, and Cypress treats an element+ // clipped by a scrollable ancestor as hidden, so scroll to it before asserting visibility.+ getSettingsBranchSwitcher().scrollIntoView().should("be.visible").click();+};++// Create a new branch (forks the current branch and switches to it) via the Settings branch switcher.+export const createBranchViaSettings = (name: string) => {+ openSettingsBranchPicker();+ popover().findByPlaceholderText("Find or create a branch...").type(name);+ popover()+ .findByRole("option", { name: /Create branch/ })+ .click();+};++// Select an existing branch via the Settings branch switcher. With unsaved changes this opens the+// choose-what-to-do modal instead of switching immediately.+export const switchBranchViaSettings = (branch: string) => {+ openSettingsBranchPicker();+ popover().findByPlaceholderText("Find or create a branch...").type(branch);+ popover().findByRole("option", { name: branch }).click();+};// Enable tenants feature for testingexport const enableTenants = () => {diff --git a/e2e/test/scenarios/admin/remote-sync.cy.spec.ts b/e2e/test/scenarios/admin/remote-sync.cy.spec.tsindex b000e22670e..f0355725f82 100644--- a/e2e/test/scenarios/admin/remote-sync.cy.spec.ts+++ b/e2e/test/scenarios/admin/remote-sync.cy.spec.ts@@ -190,12 +190,13 @@ describe("Remote Sync", () => {cy.findByText("Remote Sync Test Question");});- H.clickSwitchBranchOption();- H.popover().findByRole("option", { name: "main" }).click();-+ // Switch back to main from Settings (local is synced after stashing, so it switches directly)+ H.switchBranchViaSettings("main");H.waitForTask({ taskName: "import" });// Upstream change will get pulled when switching branches+ cy.visit("/collection/root");+ H.goToSyncedCollection();H.collectionTable().findByText("Sloan for Frontend Emperor").should("exist");@@ -208,15 +209,10 @@ describe("Remote Sync", () => {branchCount = 0;});+ // Branch switching moved to the instance Settings panel; these helpers drive it there.const createNewBranch = (newBranchName: string) => {branchCount++;- H.clickSwitchBranchOption();- H.popover()- .findByPlaceholderText("Find or create a branch...")- .type(newBranchName);- H.popover()- .findByRole("option", { name: /Create branch/ })- .click();+ H.createBranchViaSettings(newBranchName);H.expectUnstructuredSnowplowEvent({@@ -226,15 +222,12 @@ describe("Remote Sync", () => {branchCount,);- H.getGitSyncControls().should("contain.text", newBranchName);+ H.getSettingsBranchSwitcher().should("contain.text", newBranchName);};+ // Only for a clean instance — with unsaved changes the switcher opens the choice modal instead.const switchToExistingBranch = (branch: string) => {- H.clickSwitchBranchOption();- H.popover()- .findByPlaceholderText("Find or create a branch...")- .type(branch);- cy.findByRole("option", { name: branch }).click();+ H.switchBranchViaSettings(branch);};const pushUpdates = () => {@@ -270,6 +263,7 @@ describe("Remote Sync", () => {createNewBranch(NEW_BRANCH_1);// Move something into synced collection for the new branch+ cy.visit("/collection/root");H.moveCollectionItemToSyncedCollection("Orders, Count","Test Synced Collection",@@ -277,9 +271,10 @@ describe("Remote Sync", () => {pushUpdates();- // Go back to the main branch+ // Create a second branch (off the first) and add different contentcreateNewBranch(NEW_BRANCH_2);+ cy.visit("/collection/root");H.moveCollectionItemToSyncedCollection("Orders Model","Test Synced Collection",@@ -289,14 +284,17 @@ describe("Remote Sync", () => {H.collectionTable().findByText("Orders Model").should("exist");pushUpdates();- // Go back to the first branch+ // Go back to the first branch (clean, so it switches directly)switchToExistingBranch(NEW_BRANCH_1);+ H.waitForTask({ taskName: "import" });H.expectUnstructuredSnowplowEvent({event: "remote_sync_branch_switched",- triggered_from: "app-bar",+ triggered_from: "admin-settings",});+ cy.visit("/collection/root");+ H.goToSyncedCollection("Test Synced Collection");H.collectionTable().findByText("Orders, Count").should("exist");// The second item should not exist in the first branchH.collectionTable().findByText("Orders Model").should("not.exist");@@ -322,16 +320,26 @@ describe("Remote Sync", () => {createNewBranch(NEW_BRANCH);// Move something into synced collection for the new branch+ cy.visit("/collection/root");H.moveCollectionItemToSyncedCollection("Orders, Count","Test Synced Collection",);- // Attempt to go back to main- switchToExistingBranch("main");+ // Attempt to go back to main from Settings. Wait for the unsaved-changes indicator so the switch+ // opens the choose-what-to-do modal rather than switching directly.+ H.visitRemoteSyncSettings();+ cy.findByTestId("branch-switcher-dirty-warning")+ .scrollIntoView()+ .should("be.visible");+ H.getSettingsBranchSwitcher().click();+ H.popover()+ .findByPlaceholderText("Find or create a branch...")+ .type("main");+ H.popover().findByRole("option", { name: "main" }).click();- // Check that we haven't switched to main- H.getGitSyncControls().should("not.contain.text", "main");+ // Check that we haven't switched to main yet+ H.getSettingsBranchSwitcher().should("not.contain.text", "main");H.modal().should("exist");H.modal().within(() => {@@ -350,8 +358,10 @@ describe("Remote Sync", () => {cy.button(/Delete unsynced changes/).click();});+ H.waitForTask({ taskName: "import" });+// Now we switched to main- H.getGitSyncControls().should("contain.text", "main");+ H.getSettingsBranchSwitcher().should("contain.text", "main");});});@@ -410,10 +420,12 @@ describe("Remote Sync", () => {// waitForTask above already closed the sync confirmation modal.H.modal().should("not.exist");- H.clickSwitchBranchOption();- H.popover().findByRole("option", { name: "main" }).click();+ // Switch back to main from Settings (clean after stashing, so it switches directly)+ H.switchBranchViaSettings("main");H.waitForTask({ taskName: "import" }).then(() => {+ cy.visit("/collection/root");+ H.goToSyncedCollection();H.collectionTable().within(() => {cy.findByText("Orders").should("not.exist");cy.findByText(REMOTE_QUESTION_NAME).should("exist");diff --git a/enterprise/backend/src/metabase_enterprise/remote_sync/api.clj b/enterprise/backend/src/metabase_enterprise/remote_sync/api.cljindex ba296878344..4cf9bebcbeb 100644--- a/enterprise/backend/src/metabase_enterprise/remote_sync/api.clj+++ b/enterprise/backend/src/metabase_enterprise/remote_sync/api.clj@@ -248,6 +248,21 @@[:remote-sync-transforms {:optional true} [:maybe :boolean]][:collections {:optional true} [:maybe [:map-of pos-int? :boolean]]]]](api/check-superuser)+ ;; In read-write mode, changing the branch here would flip the setting without reconciling synced+ ;; collections (the setting would silently disagree with local content), so a switch must go through the+ ;; guarded import (POST /import), which blocks on unsaved changes and surfaces deletion conflicts. In+ ;; read-only mode the branch is a declarative setting whose change triggers a reconciling import, so it is+ ;; still allowed here. Setting the branch during first-time configuration (no current branch) is allowed.+ ;; Blanking the branch is also blocked in read-write — otherwise it would reset the guard and let a+ ;; follow-up call switch freely.+ (let [current-branch (settings/remote-sync-branch)+ new-branch (:remote-sync-branch settings)+ effective-type (or remote-sync-type (settings/remote-sync-type))]+ (api/check-400 (not (and (= :read-write effective-type)+ (not (str/blank? current-branch))+ (some? new-branch)+ (not= new-branch current-branch)))+ "Switching the remote-sync branch is not allowed here. Use the branch switch action, which reconciles synced collections and guards against data loss."))(api/check-400 (not (and (remote-sync.object/dirty?) (= :read-only remote-sync-type)))"There are unsaved changes in the Remote Sync collection which will be overwritten switching to read-only mode.");; Filter out no-op collection changes before checking read-only mode or running bulk-setdiff --git a/enterprise/backend/src/metabase_enterprise/remote_sync/impl.clj b/enterprise/backend/src/metabase_enterprise/remote_sync/impl.cljindex df246daa051..eda5cd37bcf 100644--- a/enterprise/backend/src/metabase_enterprise/remote_sync/impl.clj+++ b/enterprise/backend/src/metabase_enterprise/remote_sync/impl.clj@@ -55,19 +55,6 @@(spec/transforms-namespace-collection? entity))))serdes-paths))))-(defn- build-entity-id-where-clause- "Builds a HoneySQL WHERE clause for entity_id filtering.- Combines the imported entity-ids exclusion with any spec-level entity_id condition."- [entity-ids spec-entity-id-condition]- (let [imported-condition (when (seq entity-ids)- [:not-in :entity_id entity-ids])- spec-condition (when spec-entity-id-condition- (let [[op value] spec-entity-id-condition]- [op :entity_id value]))- conditions (filterv some? [imported-condition spec-condition])]- (when (pos? (count conditions))- (into [:and] conditions))))-(defn- remove-unsynced!"Deletes any remote sync content that was NOT part of the import.@@ -83,33 +70,17 @@Collection are deleted before Collection itself)."[synced-collection-ids {:keys [by-entity-id]}](doseq [[model-key model-spec] (spec/specs-for-deletion)- :let [serdes-model (:model-type model-spec)- entity-ids (get by-entity-id serdes-model [])- removal-conds (spec/removal-conditions model-spec)- spec-entity-id-condition (get removal-conds :entity_id)- entity-id-where (build-entity-id-where-clause entity-ids spec-entity-id-condition)- scope-key (get-in model-spec [:removal :scope-key])- ;; Get non-entity_id conditions from spec- other-conditions (into [] cat (dissoc removal-conds :entity_id))]]- (let [conditions (cond-> []- (and scope-key (seq synced-collection-ids))- (conj [:in scope-key synced-collection-ids])-- entity-id-where- (conj entity-id-where)-- (and (not scope-key) (seq other-conditions))- (into (for [[k v] (partition 2 other-conditions)]- [:= k v])))- where-clause (when (seq conditions)- (if (= 1 (count conditions))- (first conditions)- (into [:and] conditions)))]- (cond- ;; Scoped models with no collections to scope to — nothing to delete- (and scope-key (empty? synced-collection-ids)) nil- where-clause (t2/delete! model-key {:where where-clause})- :else (t2/delete! model-key)))))+ :let [entity-ids (get by-entity-id (:model-type model-spec) [])+ clauses (spec/removal-where-clauses model-spec synced-collection-ids entity-ids)]]+ (cond+ ;; Scoped model with no collections to scope to — nothing to delete+ (nil? clauses) nil+ ;; A predicate — delete matching rows+ (seq clauses) (t2/delete! model-key {:where (if (= 1 (count clauses))+ (first clauses)+ (into [:and] clauses))})+ ;; No predicate (global model, no imported ids or conditions) — delete all+ :else (t2/delete! model-key))))(defn source-error-message"Constructs user-friendly error messages from remote sync source exceptions.@@ -204,7 +175,8 @@ns-coll-conflicts(when library-conflict [library-conflict]))]{:first-import-conflicts (vec first-import-conflicts)- :deletion-conflicts (spec/check-deletion-conflicts imported-data)}))+ :deletion-conflicts (into (spec/check-deletion-conflicts imported-data)+ (spec/check-content-deletion-conflicts imported-data))}))(def app-db-batch-size"Max rows per select/update batch, to keep IN-lists and CASE expressions bounded."@@ -1386,7 +1358,10 @@(when (and has-dirty? (not force?) (not merge?))(throw (ex-info "There are unsaved changes in the Remote Sync collection which will be overwritten by the import. Force the import to discard these changes."{:status-code 400- :conflicts true})))+ :conflicts true+ ;; The un-pushed local changes a switch would discard, so the client can name exactly+ ;; what would be lost without a second round-trip to /dirty.+ :dirty_objects (remote-sync.object/dirty-objects)})))(run-async! "import" branch(fn [task-id](when (branch-changed-since-scheduling? pre-task-branch)diff --git a/enterprise/backend/src/metabase_enterprise/remote_sync/spec.clj b/enterprise/backend/src/metabase_enterprise/remote_sync/spec.cljindex 9f196d55965..6f04c7eb82f 100644--- a/enterprise/backend/src/metabase_enterprise/remote_sync/spec.clj+++ b/enterprise/backend/src/metabase_enterprise/remote_sync/spec.clj@@ -595,15 +595,46 @@category category)}))))(defn- removal-condition-clauses- "Converts a spec's removal-conditions map into HoneySQL where-fragments, matching the semantics- [[metabase-enterprise.remote-sync.impl/build-entity-id-where-clause]] uses: an :entity_id entry- whose value is an [op value] pair becomes [op :entity_id value]; any other entry becomes [:= key value]."+ "Converts a spec's removal-conditions map into HoneySQL where-fragments: an :entity_id entry whose value is+ an [op value] pair becomes [op :entity_id value]; any other entry becomes [:= key value]."[removal-conds](for [[k v] removal-conds](if (and (= k :entity_id) (vector? v))(let [[op value] v] [op :entity_id value])[:= k v])))+(defn removal-where-clauses+ "The AND-clauses selecting the rows an import reconcile removes for one entity-id `spec`: rows scoped to+ `synced-collection-ids` (when the spec has a `:scope-key`), minus the imported `entity-ids`, honoring the+ spec's removal conditions.++ Returns nil for a scoped model with no synced collections (removes nothing); an empty vector means no+ predicate (a global, unconditioned delete)."+ [spec synced-collection-ids entity-ids]+ (let [scope-key (get-in spec [:removal :scope-key])]+ (when-not (and scope-key (empty? synced-collection-ids))+ (cond-> []+ scope-key (conj [:in scope-key synced-collection-ids])+ (seq entity-ids) (conj [:not-in :entity_id entity-ids])+ :always (into (removal-condition-clauses (removal-conditions spec)))))))++(defn- model-id-column+ "The qualified id column of a model's own table (e.g. :report_card.id), for correlating a subquery."+ [model-key]+ (keyword (str (name (t2/table-name model-key)) ".id")))++(defn- unsynced-anti-join+ "A [:not [:exists ...]] HoneySQL fragment keeping only rows with no RemoteSyncObject in 'synced' status —+ i.e. unsynced local work (an already-synced entity's removal is a normal reconcile, not data loss).+ `id-col` is the qualified id column of the model's own table (see [[model-id-column]])."+ [model-type id-col]+ [:not [:exists {:select [1]+ :from [:remote_sync_object]+ :where [:and+ [:= :remote_sync_object.model_type model-type]+ [:= :remote_sync_object.model_id id-col]+ [:= :remote_sync_object.status "synced"]]}]])+(defn check-deletion-conflicts"Detects local entities of all-or-nothing models (specs with :all-on-setting-disable) that an importwould wholesale-delete because they are absent from it, but which hold unsaved local work — i.e. they@@ -620,18 +651,12 @@:when setting-kw:let [model-type (:model-type spec)imported-ids (get by-entity-id model-type #{})- conds (cond-> []- (seq imported-ids) (conj [:not-in :entity_id imported-ids])- :always (into (removal-condition-clauses (removal-conditions spec))))- candidates (if (seq conds)- (t2/select [model-key :id] {:where (into [:and] conds)})- (t2/select [model-key :id]))- n-unsynced (count (remove (fn [{:keys [id]}]- (t2/exists? :model/RemoteSyncObject- :model_type model-type- :model_id id- :status "synced"))- candidates))]+ ;; These models are unscoped (no :scope-key), so removal-where-clauses just yields the+ ;; not-in-import + removal-condition clauses; the anti-join keeps the unsynced ones.+ where (-> [:and]+ (into (removal-where-clauses spec nil imported-ids))+ (conj (unsynced-anti-join model-type (model-id-column model-key))))+ n-unsynced (t2/count model-key {:where where})]:when (pos? n-unsynced):let [category (setting->category setting-kw)]]{:type (keyword (str (u/lower-case-en category) "-conflict"))@@ -683,6 +708,49 @@(when (rs-settings/library-is-remote-synced?)(t2/select-pks-vec :model/Collection :namespace "snippets"))]))+(def ^:private max-conflict-names+ "Cap on how many entity names a collection deletion conflict carries, so the payload stays bounded when+ a whole collection's worth of content would be swept. The :count field always holds the true total."+ 100)++(defn check-content-deletion-conflicts+ "Detects unsynced local content an import would delete because it is absent from the import, but which+ holds unsaved local work — it has no RemoteSyncObject in 'synced' status, so its removal is data loss+ (unlike an already-synced entity's, which is a normal reconcile against the remote source of truth).++ Covers the entity-id content models [[check-deletion-conflicts]] does not (that one handles only the+ all-or-nothing, setting-gated transform family): Cards/metrics, Dashboards, Documents, Timelines, and+ NativeQuerySnippets. Collection is excluded — it is structural, its deletion cascades, and its contents+ are already covered here. The count matches what an import would actually delete.++ Takes imported-data from [[extract-imported-entities]]. Returns a vector of conflict maps+ ({:type :category :model :count :names :message}), one per affected model type."+ [{:keys [by-entity-id]}]+ (let [synced-collection-ids (all-syncable-collection-ids)]+ (cond-> []+ (seq synced-collection-ids)+ (into (for [[model-key spec] (specs-for-deletion)+ :when (and (not (get-in spec [:removal :all-on-setting-disable]))+ (not= :model/Collection model-key))+ :let [model-type (:model-type spec)+ imported-ids (get by-entity-id model-type #{})+ ;; Same base predicate remove-unsynced! deletes by, plus an anti-join keeping only the+ ;; unsynced rows the import would delete. Done in SQL so we never materialize a whole+ ;; collection's worth of rows just to count/sample them.+ where (-> [:and]+ (into (removal-where-clauses spec synced-collection-ids imported-ids))+ (conj (unsynced-anti-join model-type (model-id-column model-key))))+ n (t2/count model-key {:where where})]+ :when (pos? n)]+ {:type (keyword (str (u/lower-case-en model-type) "-deletion-conflict"))+ :category model-type+ :model model-type+ :count n+ ;; A bounded sample of names for the UI; :count above is the true total.+ :names (t2/select-fn-vec :name model-key {:where where :limit max-conflict-names})+ :message (format "Import would delete %d unsynced local %s %s"+ n model-type (if (= 1 n) "entity" "entities"))})))))+(defmulti check-eligibility"Determines if a model instance should be tracked for remote sync.Dispatches on the eligibility type defined in the spec."diff --git a/enterprise/backend/test/metabase_enterprise/remote_sync/api_test.clj b/enterprise/backend/test/metabase_enterprise/remote_sync/api_test.cljindex 0ebb0a8e83f..27952cf7210 100644--- a/enterprise/backend/test/metabase_enterprise/remote_sync/api_test.clj+++ b/enterprise/backend/test/metabase_enterprise/remote_sync/api_test.clj@@ -218,6 +218,27 @@(is (= "success" (:status response)))(is (remote-sync.task/successful? completed-task))))))))+(deftest import-dirty-guard-includes-dirty-objects-test+ (testing "GHY-4019: a blocked (dirty, non-forced) import names the un-pushed changes it would discard"+ (mt/with-temp [:model/Collection coll {:name "Synced" :is_remote_synced true :location "/"}+ :model/Card card {:name "Local Metric" :type :metric :collection_id (:id coll)}+ :model/RemoteSyncObject _ {:model_type "Card"+ :model_id (:id card)+ :status "create"+ :status_changed_at (t/instant)+ :model_name "Local Metric"+ :model_collection_id (:id coll)}]+ (let [mock-main (test-helpers/create-mock-source)]+ (mt/with-temporary-setting-values [remote-sync-url "https://github.com/test/repo.git"+ remote-sync-token "test-token"+ remote-sync-branch "main"]+ (mt/with-dynamic-fn-redefs [source/source-from-settings (constantly mock-main)]+ (let [resp (mt/user-http-request :crowberto :post 400 "ee/remote-sync/import"+ {:branch "develop" :expected_branch "main"})]+ (is (true? (:conflicts resp)))+ (is (some (comp #{"Local Metric"} :name) (:dirty_objects resp))+ "the response lists the un-pushed local metric"))))))))+(deftest import-rejects-expected-branch-mismatch-test(testing "POST /api/ee/remote-sync/import rejects when expected_branch disagrees with the configured setting"(let [mock-main (test-helpers/create-mock-source)]@@ -270,9 +291,14 @@(deftest import-requires-superuser-test(testing "POST /api/ee/remote-sync/import requires superuser permissions"- (mt/with-temporary-setting-values [remote-sync-enabled true]- (is (= "You don't have permissions to do that."- (mt/user-http-request :rasta :post 403 "ee/remote-sync/import" {:expected_branch "main"}))))))+ (mt/with-temporary-setting-values [remote-sync-enabled true remote-sync-branch "main"]+ (testing "a non-admin cannot pull"+ (is (= "You don't have permissions to do that."+ (mt/user-http-request :rasta :post 403 "ee/remote-sync/import" {:expected_branch "main"}))))+ (testing "a non-admin cannot switch branches (branch != expected_branch)"+ (is (= "You don't have permissions to do that."+ (mt/user-http-request :rasta :post 403 "ee/remote-sync/import"+ {:branch "develop" :expected_branch "main"})))))))(deftest import-errors-when-remote-sync-disabled-test(testing "POST /api/ee/remote-sync/import errors when remote sync is disabled"@@ -943,6 +969,62 @@(is (=? {:success true} response))(is (remote-sync.task/successful? task))))))))+(deftest settings-rejects-read-write-branch-switch-test+ (testing "GHY-4019: PUT /api/ee/remote-sync/settings guards branch changes"+ (let [mock-main (test-helpers/create-mock-source)+ reject-message (str "Switching the remote-sync branch is not allowed here. "+ "Use the branch switch action, which reconciles synced "+ "collections and guards against data loss.")]+ (mt/with-dynamic-fn-redefs [settings/check-git-settings! (constantly nil)+ source/source-from-settings (constantly mock-main)]+ (testing "rejects a branch switch in read-write mode (must use the guarded import)"+ (mt/with-temporary-setting-values [remote-sync-url "https://github.com/test/repo.git"+ remote-sync-token "test-token"+ remote-sync-branch "main"+ remote-sync-type :read-write]+ (is (= reject-message+ (mt/user-http-request :crowberto :put 400 "ee/remote-sync/settings"+ {:remote-sync-branch "develop"})))+ (is (= "main" (settings/remote-sync-branch))+ "the branch setting is left unchanged")))+ (testing "rejects blanking the branch in read-write mode (would otherwise reset the guard)"+ (mt/with-temporary-setting-values [remote-sync-url "https://github.com/test/repo.git"+ remote-sync-token "test-token"+ remote-sync-branch "main"+ remote-sync-type :read-write]+ (is (= reject-message+ (mt/user-http-request :crowberto :put 400 "ee/remote-sync/settings"+ {:remote-sync-branch ""})))+ (is (= "main" (settings/remote-sync-branch))+ "the branch cannot be blanked to bypass the guard, then switched freely")))+ (testing "allows an unchanged branch in read-write mode"+ (mt/with-temporary-setting-values [remote-sync-url "https://github.com/test/repo.git"+ remote-sync-token "test-token"+ remote-sync-branch "main"+ remote-sync-type :read-write]+ (is (=? {:success true}+ (mt/user-http-request :crowberto :put 200 "ee/remote-sync/settings"+ {:remote-sync-branch "main"})))))+ (testing "allows setting the branch during first-time configuration (no current branch)"+ (mt/with-temporary-setting-values [remote-sync-url "https://github.com/test/repo.git"+ remote-sync-token "test-token"+ remote-sync-branch ""+ remote-sync-type :read-write]+ (is (=? {:success true}+ (mt/user-http-request :crowberto :put 200 "ee/remote-sync/settings"+ {:remote-sync-branch "develop"})))+ (is (= "develop" (settings/remote-sync-branch)))))+ (testing "allows a branch change in read-only mode (the change triggers a reconciling import)"+ (mt/with-dynamic-fn-redefs [impl/finish-remote-config! (constantly nil)]+ (mt/with-temporary-setting-values [remote-sync-url "https://github.com/test/repo.git"+ remote-sync-token "test-token"+ remote-sync-branch "main"+ remote-sync-type :read-only]+ (is (=? {:success true}+ (mt/user-http-request :crowberto :put 200 "ee/remote-sync/settings"+ {:remote-sync-branch "develop" :remote-sync-type :read-only})))+ (is (= "develop" (settings/remote-sync-branch))))))))))+(deftest settings-requires-superuser-test(testing "PUT /api/ee/remote-sync/settings requires superuser permissions"(is (= "You don't have permissions to do that."@@ -1506,6 +1588,8 @@"Token should be preserved when not included in request")))))))(deftest settings-preserves-token-when-changing-branch-test+ ;; Read-only mode: a branch change here is a declarative setting whose change triggers a reconciling import+ ;; (in read-write, a branch switch must go through the guarded POST /import instead — GHY-4019).(testing "PUT /api/ee/remote-sync/settings preserves token when changing branch"(let [mock-source (test-helpers/create-mock-source)](mt/with-dynamic-fn-redefs [settings/check-git-settings! (constantly nil)@@ -1513,7 +1597,7 @@(mt/with-temporary-setting-values [remote-sync-url "https://github.com/test/repo.git"remote-sync-token "secret-token-value"remote-sync-branch "main"- remote-sync-type :read-write]+ remote-sync-type :read-only](let [{:as resp :keys [task_id]} (mt/user-http-request :crowberto :put 200 "ee/remote-sync/settings"{:remote-sync-branch "develop"})](wait-for-task-completion task_id)@@ -1578,9 +1662,10 @@remote-sync-branch "main"remote-sync-type :read-writeremote-sync-transforms true]- (let [{:as resp :keys [task_id]} (mt/user-http-request :crowberto :put 200 "ee/remote-sync/settings"- {:remote-sync-branch "develop"})]- (wait-for-task-completion task_id)+ ;; Toggle an unrelated setting (auto-import) so no branch switch is attempted and no import runs+ ;; that could itself re-toggle remote-sync-transforms; the point is transforms is left untouched.+ (let [resp (mt/user-http-request :crowberto :put 200 "ee/remote-sync/settings"+ {:remote-sync-auto-import true})](is (=? {:success true} resp))(is (true? (settings/remote-sync-transforms))"Transforms setting should be preserved when not included in request")))))))diff --git a/enterprise/backend/test/metabase_enterprise/remote_sync/impl_test.clj b/enterprise/backend/test/metabase_enterprise/remote_sync/impl_test.cljindex 26366fee8d9..fc15d5a598a 100644--- a/enterprise/backend/test/metabase_enterprise/remote_sync/impl_test.clj+++ b/enterprise/backend/test/metabase_enterprise/remote_sync/impl_test.clj@@ -291,22 +291,31 @@(is (= coll-id (:collection_id card))))))))))(deftest collection-cleanup-during-import-test- (testing "collection cleanup during import (tests clean-synced! private function)"- (let [import-task (t2/insert-returning-instance! :model/RemoteSyncTask {:sync_task_type "import" :initiated_by (mt/user->id :rasta)})]- (mt/with-temp [:model/Collection {coll1-id :id} {:name "Collection 1" :is_remote_synced true :entity_id "test-collection-1xxxx" :location "/"}- :model/Collection {coll2-id :id} {:name "Collection 2" :is_remote_synced true :entity_id "test-collection-2xxxx" :location "/"}- :model/Card {card1-id :id} {:name "Card 1" :collection_id coll1-id :entity_id "test-card-1xxxxxxxxxx"}- :model/Card {card2-id :id} {:name "Card 2" :collection_id coll2-id :entity_id "test-card-2xxxxxxxxxx"}]- (let [test-files {"test-branch" {"collections/main/test_collection_1/test_collection_1.yaml"- (test-helpers/generate-collection-yaml "test-collection-1xxxx" "Test Collection 1")- "collections/main/test_collection_1/test_card_1.yaml"- (test-helpers/generate-card-yaml "test-card-1xxxxxxxxxx" "Test Card 1" "test-collection-1xxxx")}}- mock-main (test-helpers/create-mock-source :initial-files test-files :branch "test-branch")- result (impl/import! (source.p/snapshot mock-main) (:id import-task))]- (is (= :success (:status result)))- (is (t2/exists? :model/Card :id card1-id))- (is (not (t2/exists? :model/Collection :id coll2-id)))- (is (not (t2/exists? :model/Card :id card2-id))))))))+ (testing "collection cleanup during import (remove-unsynced!)"+ (mt/with-temp [:model/Collection {coll1-id :id} {:name "Collection 1" :is_remote_synced true :entity_id "test-collection-1xxxx" :location "/"}+ :model/Collection {coll2-id :id} {:name "Collection 2" :is_remote_synced true :entity_id "test-collection-2xxxx" :location "/"}+ :model/Card {card1-id :id} {:name "Card 1" :collection_id coll1-id :entity_id "test-card-1xxxxxxxxxx"}+ :model/Card {card2-id :id} {:name "Card 2" :collection_id coll2-id :entity_id "test-card-2xxxxxxxxxx"}]+ (let [test-files {"test-branch" {"collections/main/test_collection_1/test_collection_1.yaml"+ (test-helpers/generate-collection-yaml "test-collection-1xxxx" "Test Collection 1")+ "collections/main/test_collection_1/test_card_1.yaml"+ (test-helpers/generate-card-yaml "test-card-1xxxxxxxxxx" "Test Card 1" "test-collection-1xxxx")}}+ mock-main (test-helpers/create-mock-source :initial-files test-files :branch "test-branch")+ new-task! #(t2/insert-returning-instance! :model/RemoteSyncTask {:sync_task_type "import" :initiated_by (mt/user->id :rasta)})]+ (testing "GHY-4019: by default the import blocks with a conflict rather than deleting unsynced local content (Card 2)"+ (let [task (new-task!)+ result (impl/import! (source.p/snapshot mock-main) (:id task))]+ (is (= :conflict (:status result)))+ (is (t2/exists? :model/Card :id card2-id) "the unsynced local card is preserved")+ (is (t2/exists? :model/Collection :id coll2-id))+ ;; free the running-task guard so the next import can start+ (remote-sync.task/complete-sync-task! (:id task))))+ (testing "with force-deletion? the cleanup proceeds and removes content not present in the import"+ (let [result (impl/import! (source.p/snapshot mock-main) (:id (new-task!)) :force-deletion? true)]+ (is (= :success (:status result)))+ (is (t2/exists? :model/Card :id card1-id))+ (is (not (t2/exists? :model/Collection :id coll2-id)))+ (is (not (t2/exists? :model/Card :id card2-id)))))))))(deftest import!-records-file-path-test(testing "import! records each entity's actual repo file_path on its RemoteSyncObject row, so laterdiff --git a/enterprise/backend/test/metabase_enterprise/remote_sync/spec_test.clj b/enterprise/backend/test/metabase_enterprise/remote_sync/spec_test.cljindex ea4b58fdf5b..5eed35c1fb8 100644--- a/enterprise/backend/test/metabase_enterprise/remote_sync/spec_test.clj+++ b/enterprise/backend/test/metabase_enterprise/remote_sync/spec_test.clj@@ -2,9 +2,11 @@(:require[clojure.set :as set][clojure.test :refer :all]+ [java-time.api :as t][metabase-enterprise.remote-sync.spec :as spec][metabase-enterprise.transforms-python.core :as transforms-python]- [metabase.test :as mt]))+ [metabase.test :as mt]+ [toucan2.core :as t2]))(set! *warn-on-reflection* true)@@ -481,3 +483,93 @@"export-conditions falls back to :conditions for TransformTag")(is (= {:built_in_type nil} (spec/removal-conditions spec))"removal-conditions falls back to :conditions for TransformTag"))))++(deftest check-deletion-conflicts-test+ (testing "unsynced transform-family content absent from an import is flagged; synced content is excluded"+ (mt/with-temporary-setting-values [remote-sync-transforms true]+ (mt/with-temp [:model/TransformTag unsynced {:name "Unsynced Tag"}+ :model/TransformTag synced {:name "Synced Tag"}+ :model/RemoteSyncObject _ {:model_type "TransformTag" :model_id (:id synced)+ :status "synced" :status_changed_at (t/instant)+ :model_name "Synced Tag"}]+ (testing "the unsynced tag is flagged; the already-synced one is not counted as data loss"+ (let [tconf (first (filter #(= "Transforms" (:category %))+ (spec/check-deletion-conflicts {:by-entity-id {}})))]+ (is (= "Import would delete 1 unsynced local Transforms entity" (:message tconf)))))+ (testing "tags present in the import are not flagged"+ (is (empty? (filter #(= "Transforms" (:category %))+ (spec/check-deletion-conflicts+ {:by-entity-id {"TransformTag" #{(:entity_id unsynced) (:entity_id synced)}}})))))))))++(deftest check-content-deletion-conflicts-test+ (testing "GHY-4019: unsynced local collection content absent from an import is flagged as a deletion conflict"+ (mt/with-temp [:model/Collection coll {:name "Synced" :is_remote_synced true :location "/"}+ :model/Card metric {:name "Local Metric" :type :metric :collection_id (:id coll)}+ :model/Card question {:name "Local Q" :collection_id (:id coll)}]+ (testing "cards absent from the import are reported (metrics are Cards)"+ (let [conflicts (spec/check-content-deletion-conflicts {:by-entity-id {}})+ card-conflict (first (filter #(= "Card" (:model %)) conflicts))]+ (is (= 2 (:count card-conflict)))+ (is (= #{"Local Metric" "Local Q"} (set (:names card-conflict))))+ (is (= "Card" (:category card-conflict)))))+ (testing "cards present in the import are not reported"+ (is (empty? (spec/check-content-deletion-conflicts+ {:by-entity-id {"Card" #{(:entity_id metric) (:entity_id question)}}}))))))+ (testing "content already synced (present in RemoteSyncObject as 'synced') is not data loss and is excluded"+ (mt/with-temp [:model/Collection coll {:name "Synced" :is_remote_synced true :location "/"}+ :model/Card synced-card {:name "Pushed" :collection_id (:id coll)}+ :model/Card _local {:name "Never pushed" :type :metric :collection_id (:id coll)}+ :model/RemoteSyncObject _ {:model_type "Card" :model_id (:id synced-card)+ :status "synced" :status_changed_at (t/instant)+ :model_name "Pushed"}]+ (let [conflicts (spec/check-content-deletion-conflicts {:by-entity-id {}})+ card-conflict (first (filter #(= "Card" (:model %)) conflicts))]+ (is (= 1 (:count card-conflict)))+ (is (= ["Never pushed"] (:names card-conflict))))))+ (testing "content in a non-synced collection is not scoped in, so nothing is flagged"+ (mt/with-temp [:model/Collection coll {:name "Not synced" :is_remote_synced false :location "/"}+ :model/Card _card {:name "Local Q" :collection_id (:id coll)}]+ (is (empty? (spec/check-content-deletion-conflicts {:by-entity-id {}})))))+ (testing "GHY-4019: unsynced NativeQuerySnippets are flagged too (not just collection content)"+ ;; Snippets sync when the Library collection is remote-synced; they are entity-id content with no+ ;; collection scope, so they'd previously fall through both deletion-conflict checks.+ (mt/with-temp [:model/Collection _lib {:name "Library" :type "library" :is_remote_synced true :location "/"}+ :model/NativeQuerySnippet _unsynced {:name "Local Snippet"}+ :model/NativeQuerySnippet synced {:name "Synced Snippet"}+ :model/RemoteSyncObject _ {:model_type "NativeQuerySnippet" :model_id (:id synced)+ :status "synced" :status_changed_at (t/instant)+ :model_name "Synced Snippet"}]+ (let [conflict (first (filter #(= "NativeQuerySnippet" (:model %))+ (spec/check-content-deletion-conflicts {:by-entity-id {}})))]+ (is (= 1 (:count conflict)) "the unsynced snippet is flagged; the synced one is excluded")+ (is (= ["Local Snippet"] (:names conflict)))))))++(deftest removal-where-clauses-parity-test+ (testing "GHY-4019: the deletion-conflict warning is exactly the unsynced subset of what an import removes"+ ;; Both the delete path (remove-unsynced!) and the warning build their WHERE from+ ;; spec/removal-where-clauses, so they can't diverge. This locks in that relationship: the rows the+ ;; predicate removes (absent from the import, in a synced collection) minus the already-synced ones are+ ;; exactly the rows the warning flags.+ (mt/with-temp [:model/Collection coll {:name "Synced" :is_remote_synced true :location "/"}+ :model/Card _unsynced {:name "Unsynced" :collection_id (:id coll)}+ :model/Card synced {:name "Synced pushed" :collection_id (:id coll)}+ :model/Card imported {:name "In import" :collection_id (:id coll)}+ :model/RemoteSyncObject _ {:model_type "Card" :model_id (:id synced) :status "synced"+ :status_changed_at (t/instant) :model_name "Synced pushed"}]+ (let [imported-eids #{(:entity_id imported)}+ imported-data {:by-entity-id {"Card" imported-eids}}+ synced-ids (spec/all-syncable-collection-ids)+ card-spec (spec/spec-for-model-key :model/Card)+ ;; what remove-unsynced! would delete for Card (its predicate, run as a SELECT rather than a delete)+ would-delete (t2/select-fn-set :name :model/Card+ {:where (into [:and] (spec/removal-where-clauses+ card-spec synced-ids imported-eids))})+ flagged (into #{}+ (comp (filter #(= "Card" (:model %))) (mapcat :names))+ (spec/check-content-deletion-conflicts imported-data))]+ (is (= #{"Unsynced" "Synced pushed"} would-delete)+ "the import removes everything in the synced collection that is absent from it")+ (is (= #{"Unsynced"} flagged)+ "the warning covers only the unsynced subset (the potential data loss)")+ (is (set/subset? flagged would-delete)+ "everything the warning flags would indeed be removed")))))diff --git a/enterprise/frontend/src/metabase-enterprise/api/remote-sync.ts b/enterprise/frontend/src/metabase-enterprise/api/remote-sync.tsindex b0c38e04afb..05191f31399 100644--- a/enterprise/frontend/src/metabase-enterprise/api/remote-sync.ts+++ b/enterprise/frontend/src/metabase-enterprise/api/remote-sync.ts@@ -172,6 +172,7 @@ export const remoteSyncApi = EnterpriseApi.injectEndpoints({export const {useGetRemoteSyncChangesQuery,+ useLazyGetRemoteSyncChangesQuery,useGetRemoteSyncHasChangesQuery,useGetHasRemoteChangesQuery,useUpdateRemoteSyncSettingsMutation,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 5e11cc9e7b3..ce2d57a1415 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@@ -30,7 +30,7 @@ import {} from "metabase-enterprise/remote_sync/sync-task-slice";import type { ExportPreflightResponse } from "metabase-types/api";-import { trackBranchSwitched, trackPullChanges } from "../../analytics";+import { trackPullChanges } from "../../analytics";import { useGitSyncVisible } from "../../hooks/use-git-sync-visible";import { useRemoteSyncDirtyState } from "../../hooks/use-remote-sync-dirty-state";import { useSyncStatus } from "../../hooks/use-sync-status";@@ -38,23 +38,21 @@ import { type SyncError, parseSyncError } from "../../utils";import { PushChangesModal } from "../PushChangesModal";import { SyncConflictModal } from "../SyncConflictModal";-import { BranchDropdown } from "./BranchDropdown";import S from "./GitSyncControls.module.css";import { GitSyncOptionsDropdown } from "./GitSyncOptionsDropdown";-type DropdownView = "options" | "branch";-export const GitSyncControls = () => {const dispatch = useDispatch();const conflictVariant = useSelector(getSyncConflictVariant);- const { isVisible, currentBranch, isBranchSetByEnv } = useGitSyncVisible();+ // Branch switching now lives in the instance Settings panel (behind destructive-action guard rails),+ // so these controls show the current branch read-only and expose only Push/Pull.+ const { isVisible, currentBranch } = useGitSyncVisible();const [importChanges, { isLoading: isImporting }] =useImportChangesMutation();const [runExportPreflight] = useLazyGetExportPreflightQuery();const { isRunning: isSyncTaskRunning } = useSyncStatus();- const [nextBranch, setNextBranch] = useState<string | null>(null);// Set when a push or pull needs the conflict modal; carries whether a clean merge is available.const [conflictPreflight, setConflictPreflight] =useState<ExportPreflightResponse | null>(null);@@ -68,10 +66,9 @@ export const GitSyncControls = () => {const [isCheckingPreflight, setIsCheckingPreflight] = useState(false);const [showPushModal, { toggle: togglePushModal }] = useDisclosure(false);const [sendToast] = useToast();- const [dropdownView, setDropdownView] = useState<DropdownView>("options");const combobox = useCombobox();- const { isDirty, refetch: refetchDirty } = useRemoteSyncDirtyState();+ const { isDirty } = useRemoteSyncDirtyState();// An export task that ends in conflict (the push lost the preflight->execute race, or fell through a// preflight error) is otherwise silent: the middleware can't toast (no hook), so surface it here, then@@ -100,12 +97,7 @@ export const GitSyncControls = () => {});const { has_changes: hasRemoteChanges } = hasRemoteChangesData || {};- const isSwitchingBranch = !!nextBranch;- const isLoading =- isSyncTaskRunning ||- isSwitchingBranch ||- isImporting ||- isCheckingPreflight;+ const isLoading = isSyncTaskRunning || isImporting || isCheckingPreflight;// If `error` is a branch-mismatch rejection (another session switched branches), open the// out-of-date modal prompting a refresh and return true so the caller can stop. Returns false for@@ -126,75 +118,6 @@ export const GitSyncControls = () => {return false;}, []);- const changeBranch = useCallback(- async (branch: string | null, isNewBranch?: boolean) => {- if (branch == null) {- console.warn("Trying to switch to null branch");- return;- }-- if (!isNewBranch) {- if (currentBranch == null) {- return;- }- // expected_branch is the branch we're switching away from: reject if another session already- // moved off it, so we don't switch from a stale base. unwrap() so a rejection (e.g. the CAS 409)- // throws and reaches handleBranchSelect's catch instead of resolving silently.- await importChanges({- branch,- expected_branch: currentBranch,- }).unwrap();-- trackBranchSwitched({- triggeredFrom: "app-bar",- });- }-- setNextBranch(null);- },- [importChanges, currentBranch],- );-- const handleBranchSelect = useCallback(- async (branch: string, isNewBranch?: boolean) => {- try {- if (branch === currentBranch) {- return;- }-- setNextBranch(branch);-- const freshDirtyData = await refetchDirty().unwrap();- const hasDirtyChanges = freshDirtyData.dirty.length > 0;-- if (hasDirtyChanges && !isNewBranch) {- dispatch(syncConflictVariantUpdated("switch-branch"));- } else {- await changeBranch(branch, isNewBranch);- setNextBranch(null);- }- } catch (error) {- setNextBranch(null);- if (showBranchMismatchIfPresent(error)) {- return;- }- sendToast({- icon: "warning",- toastColor: "feedback-negative",- message: t`Sorry, we were unable to switch branches.`,- });- }- },- [- currentBranch,- refetchDirty,- dispatch,- changeBranch,- sendToast,- showBranchMismatchIfPresent,- ],- );-const handlePushClick = useCallback(async () => {if (!currentBranch) {return;@@ -308,14 +231,9 @@ export const GitSyncControls = () => {const handleCloseSyncConflictModal = useCallback(() => {dispatch(syncConflictVariantUpdated(null));- setNextBranch(null);setConflictPreflight(null);}, [dispatch]);- const handleSwitchBranchClick = useCallback(() => {- setDropdownView("branch");- }, []);-if (!isVisible || !currentBranch) {return null;}@@ -336,10 +254,7 @@ export const GitSyncControls = () => {bd="none"mr="lg"disabled={isLoading}- onClick={() => {- setDropdownView("options");- combobox.toggleDropdown();- }}+ onClick={() => combobox.toggleDropdown()}leftSection={<Icon name="git_branch" c="text-secondary" size={14} />}@@ -365,25 +280,14 @@ export const GitSyncControls = () => {</Button></Combobox.Target>- {dropdownView === "options" ? (- <GitSyncOptionsDropdown- isPullDisabled={!hasRemoteChanges}- isPullError={hasRemoteChangesError}- isLoadingPull={isFetchingRemoteChanges}- isPushDisabled={!isDirty || isLoading}- isSwitchBranchDisabled={isBranchSetByEnv}- onPullClick={handlePullClick}- onPushClick={handlePushClick}- onSwitchBranchClick={handleSwitchBranchClick}- />- ) : (- <BranchDropdown- baseBranch={currentBranch}- combobox={combobox}- onChange={handleBranchSelect}- value={currentBranch}- />- )}+ <GitSyncOptionsDropdown+ isPullDisabled={!hasRemoteChanges}+ isPullError={hasRemoteChangesError}+ isLoadingPull={isFetchingRemoteChanges}+ isPushDisabled={!isDirty || isLoading}+ onPullClick={handlePullClick}+ onPushClick={handlePushClick}+ /></Combobox>{showPushModal && (@@ -396,7 +300,6 @@ export const GitSyncControls = () => {{conflictVariant && (<SyncConflictModalcurrentBranch={currentBranch}- nextBranch={nextBranch}onClose={handleCloseSyncConflictModal}variant={conflictVariant}canMerge={conflictPreflight?.clean}diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/GitSyncControls/GitSyncControls.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/GitSyncControls/GitSyncControls.unit.spec.tsxindex e032702a34c..86878d73098 100644--- a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/GitSyncControls/GitSyncControls.unit.spec.tsx+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/GitSyncControls/GitSyncControls.unit.spec.tsx@@ -143,7 +143,8 @@ describe("GitSyncControls", () => {expect(await findOption(/Push changes/)).toBeInTheDocument();expect(await findOption(/Pull changes/)).toBeInTheDocument();- expect(await findOption(/Switch branch/)).toBeInTheDocument();+ // Branch switching moved to the Settings panel (GHY-4019); it is no longer offered here.+ expect(screen.queryByText(/Switch branch/)).not.toBeInTheDocument();});});@@ -385,58 +386,6 @@ describe("GitSyncControls", () => {});});- describe("switch branch option", () => {- it("should show branch dropdown when switch branch is clicked", async () => {- setup({ branches: ["main", "develop", "feature-1"] });-- await waitFor(() => {- expect(getBranchButton(/main/)).toBeInTheDocument();- });- await userEvent.click(getBranchButton(/main/));- await userEvent.click(await findOption(/Switch branch/));-- await waitFor(() => {- expect(- screen.getByPlaceholderText("Find or create a branch..."),- ).toBeInTheDocument();- });- });-- it("shows a refresh modal when a clean branch switch is rejected for a stale branch", async () => {- setup({ branches: ["main", "develop"] });-- // Another session already switched the branch; the import CAS guard rejects the switch.- fetchMock.removeRoute("remote-sync-import");- fetchMock.post(- "path:/api/ee/remote-sync/import",- {- status: 409,- body: {- message:- "The sync branch changed to 'develop' in another session. Refresh and try again.",- branch_mismatch: true,- current_branch: "develop",- },- },- { name: "remote-sync-import" },- );-- await waitFor(() => {- expect(getBranchButton(/main/)).toBeInTheDocument();- });- await userEvent.click(getBranchButton(/main/));- await userEvent.click(await findOption(/Switch branch/));- await userEvent.click(await findOption(/develop/));-- expect(- await screen.findByText(/changed .* in another session/i),- ).toBeInTheDocument();- expect(- screen.getByRole("button", { name: /Refresh/ }),- ).toBeInTheDocument();- });- });-// Kept last: setupEnterprisePlugins() registers the remote-sync redux reducer globally, which the other// tests in this file deliberately don't need (they use local state). Doing it here keeps that contained.describe("export conflict toast", () => {diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/GitSyncControls/GitSyncOptionsDropdown.tsx b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/GitSyncControls/GitSyncOptionsDropdown.tsxindex a3ca492353d..f1e8e3caa56 100644--- a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/GitSyncControls/GitSyncOptionsDropdown.tsx+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/GitSyncControls/GitSyncOptionsDropdown.tsx@@ -1,25 +1,14 @@import { t } from "ttag";-import {- Badge,- Box,- Combobox,- Group,- Icon,- Loader,- Text,- Tooltip,-} from "metabase/ui";+import { Box, Combobox, Group, Icon, Loader, Text, Tooltip } from "metabase/ui";export interface GitSyncOptionsDropdownProps {isPullDisabled: boolean;isPullError: boolean;isLoadingPull: boolean;isPushDisabled: boolean;- isSwitchBranchDisabled?: boolean;onPullClick: VoidFunction;onPushClick: VoidFunction;- onSwitchBranchClick: VoidFunction;}export const GitSyncOptionsDropdown = ({@@ -27,10 +16,8 @@ export const GitSyncOptionsDropdown = ({isPullError,isLoadingPull,isPushDisabled,- isSwitchBranchDisabled,onPullClick,onPushClick,- onSwitchBranchClick,}: GitSyncOptionsDropdownProps) => {if (isPullError) {return (@@ -82,25 +69,6 @@ export const GitSyncOptionsDropdown = ({</Group></Combobox.Option></Tooltip>-- {isSwitchBranchDisabled ? (- <Badge- my="xs"- size="sm"- variant="light"- >{t`Branch set by an environment variable`}</Badge>- ) : (- <Combobox.Option- onClick={onSwitchBranchClick}- py="sm"- value="switch-branch"- >- <Group gap="md" wrap="nowrap">- <Icon name="git_branch" size={12} />- <Text>{t`Switch branch`}</Text>- </Group>- </Combobox.Option>- )}</Combobox.Options></Combobox.Dropdown>);diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/BranchSwitcher.tsx b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/BranchSwitcher.tsxnew file mode 100644index 00000000000..bf51a4c3e6a--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/BranchSwitcher.tsx@@ -0,0 +1,219 @@+import { useState } from "react";+import { msgid, ngettext, t } from "ttag";++import { useToast } from "metabase/common/hooks";+import { useSelector } from "metabase/redux";+import { getUserIsAdmin } from "metabase/selectors/user";+import {+ Button,+ Combobox,+ Group,+ Icon,+ Modal,+ Text,+ useCombobox,+} from "metabase/ui";+import {+ useImportChangesMutation,+ useLazyGetRemoteSyncChangesQuery,+} from "metabase-enterprise/api/remote-sync";+import type { RemoteSyncEntity } from "metabase-types/api";++import { trackBranchSwitched } from "../../analytics";+import { type SyncError, parseSyncError } from "../../utils";+import { BranchDropdown } from "../GitSyncControls/BranchDropdown";+import { SyncConflictModal } from "../SyncConflictModal";++interface BranchSwitcherProps {+ /** May be undefined for non-admins, who can't read the admin-visibility branch setting. */+ currentBranch?: string | null;+ /** Un-pushed local changes; when present, switching prompts the admin to choose what to do with them. */+ dirty: RemoteSyncEntity[];+ disabled?: boolean;+ /** Name of the env var pinning the branch (e.g. "MB_REMOTE_SYNC_BRANCH"), when set; shows a "Using …" note. */+ envVarName?: string | null;+}++/**+ * Read-write branch switching, surfaced only in the instance Settings panel. When the instance is clean+ * the switch runs directly — everything is already pushed, so it is reversible. When there are+ * unsaved changes, the admin is offered a choice (push them, stash to a new branch, or discard and switch)+ * rather than a silent overwrite. Creating a new branch forks the current one (no reconcile), so it is+ * allowed even with unsaved changes — it is the safe way to keep local work.+ */+export const BranchSwitcher = ({+ currentBranch,+ dirty,+ disabled,+ envVarName,+}: BranchSwitcherProps) => {+ const combobox = useCombobox();+ const [sendToast] = useToast();+ const [importChanges, { isLoading }] = useImportChangesMutation();+ const [fetchDirty] = useLazyGetRemoteSyncChangesQuery();+ // Switching goes through superuser-only endpoints, so only admins get the control.+ const isAdmin = useSelector(getUserIsAdmin);+ // Set to the target branch when there are unsaved changes, opening the choose-what-to-do modal.+ const [pendingBranch, setPendingBranch] = useState<string | null>(null);+ const [branchMismatch, setBranchMismatch] = useState<string | null>(null);++ // Switching is admin-only; show the section with a message rather than a control they can't use.+ if (!isAdmin) {+ return (+ <Text c="text-secondary" size="sm">+ {t`You need to be an admin to switch the sync branch.`}+ </Text>+ );+ }+ // Admins can read the branch setting; guard anyway so the rest can treat it as a definite string.+ if (!currentBranch) {+ return null;+ }++ const performSwitch = async (branch: string) => {+ try {+ // force is left false so the backend surfaces deletion conflicts rather than silently discarding+ // local-only content.+ await importChanges({+ branch,+ expected_branch: currentBranch,+ }).unwrap();+ trackBranchSwitched({ triggeredFrom: "admin-settings" });+ } catch (error) {+ const { hasBranchMismatch, errorMessage } = parseSyncError(+ error as SyncError,+ );+ if (hasBranchMismatch) {+ setBranchMismatch(+ errorMessage ?? t`The sync branch changed in another session.`,+ );+ return;+ }+ sendToast({+ icon: "warning",+ toastColor: "feedback-negative",+ message: errorMessage ?? t`Sorry, we were unable to switch branches.`,+ });+ }+ };++ const handleSelect = async (branch: string, isNewBranch?: boolean) => {+ if (branch === currentBranch) {+ return;+ }+ // Creating a branch forks the current one server-side (identical content, already switched to), so no+ // reconcile runs and unsaved changes are preserved on the new branch. The branch picker already+ // reports the creation, so don't also report a switch.+ if (isNewBranch) {+ return;+ }+ // Refetch the dirty state at switch time so a stale snapshot (e.g. content edited since the settings+ // page loaded) doesn't send us down the wrong path. Fall back to the last-known state on error.+ let hasUnsavedChanges = dirty.length > 0;+ try {+ const fresh = await fetchDirty().unwrap();+ hasUnsavedChanges = fresh.dirty.length > 0;+ } catch {+ // keep hasUnsavedChanges as the last-known value+ }+ // With unsaved changes, let the admin choose what to do with them (push / stash / discard) instead of+ // silently discarding.+ if (hasUnsavedChanges) {+ setPendingBranch(branch);+ return;+ }+ // Clean instance: everything is already pushed, so the switch is reversible (content missing from the+ // target still lives on the remote and returns when you switch back). No confirmation needed.+ performSwitch(branch);+ };++ const dirtyCount = dirty.length;++ return (+ <>+ <Group gap="md" align="center">+ <Combobox+ store={combobox}+ position="bottom-start"+ width={320}+ withinPortal+ >+ <Combobox.Target>+ <Button+ variant="default"+ disabled={disabled || isLoading}+ loading={isLoading}+ onClick={() => combobox.toggleDropdown()}+ leftSection={<Icon name="git_branch" size={14} />}+ rightSection={<Icon name="chevrondown" size={10} />}+ data-testid="settings-branch-switcher"+ w="20rem"+ // Pack contents to the start (branch name next to the icon, like a standard select)+ // and let the label's auto end-margin push the chevron to the right edge.+ styles={{+ inner: { justifyContent: "flex-start" },+ label: { marginInlineEnd: "auto" },+ }}+ >+ {currentBranch}+ </Button>+ </Combobox.Target>+ <BranchDropdown+ baseBranch={currentBranch}+ combobox={combobox}+ onChange={handleSelect}+ value={currentBranch}+ />+ </Combobox>+ {dirtyCount > 0 && (+ <Text+ c="feedback-negative"+ size="sm"+ data-testid="branch-switcher-dirty-warning"+ >+ {ngettext(+ msgid`${dirtyCount} unsaved change`,+ `${dirtyCount} unsaved changes`,+ dirtyCount,+ )}+ </Text>+ )}+ </Group>++ {envVarName && (+ <Text c="text-secondary" size="sm" mt="sm">+ {t`Using ${envVarName}`}+ </Text>+ )}++ {pendingBranch && (+ <SyncConflictModal+ variant="switch-branch"+ currentBranch={currentBranch}+ nextBranch={pendingBranch}+ onClose={() => setPendingBranch(null)}+ />+ )}++ {branchMismatch && (+ <Modal+ opened+ padding="xl"+ title={t`This view is out of date`}+ withCloseButton={false}+ onClose={() => setBranchMismatch(null)}+ >+ <Text mt="md">{branchMismatch}</Text>+ <Group gap="sm" justify="end" mt="xl">+ <Button variant="subtle" onClick={() => setBranchMismatch(null)}>+ {t`Cancel`}+ </Button>+ <Button variant="filled" onClick={() => window.location.reload()}>+ {t`Refresh`}+ </Button>+ </Group>+ </Modal>+ )}+ </>+ );+};diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/BranchSwitcher.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/BranchSwitcher.unit.spec.tsxnew file mode 100644index 00000000000..59e2bedf091--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/BranchSwitcher.unit.spec.tsx@@ -0,0 +1,120 @@+import userEvent from "@testing-library/user-event";+import fetchMock from "fetch-mock";++import { setupEnterprisePlugins } from "__support__/enterprise";+import { setupRemoteSyncEndpoints } from "__support__/server-mocks";+import { renderWithProviders, screen, waitFor } from "__support__/ui";+import type { RemoteSyncEntity } from "metabase-types/api";++import {+ createMockDirtyEntity,+ createRemoteSyncStoreState,+ setupCollectionEndpoints,+ setupSessionEndpoints,+} from "../GitSyncControls/test-utils";++import { BranchSwitcher } from "./BranchSwitcher";++const setup = ({+ isAdmin = true,+ currentBranch = "main",+ dirty = [],+ branches = ["main", "develop"],+ envVarName,+}: {+ isAdmin?: boolean;+ currentBranch?: string;+ dirty?: RemoteSyncEntity[];+ branches?: string[];+ envVarName?: string;+} = {}) => {+ setupEnterprisePlugins();+ setupRemoteSyncEndpoints({ branches, dirty });+ setupSessionEndpoints({ currentBranch, syncType: "read-write" });+ setupCollectionEndpoints();+ // SyncConflictModal (shown on the dirty path) fetches the library collection.+ fetchMock.get("path:/api/ee/library", { data: null });++ return renderWithProviders(+ <BranchSwitcher+ currentBranch={currentBranch}+ dirty={dirty}+ disabled={Boolean(envVarName)}+ envVarName={envVarName}+ />,+ {+ storeInitialState: createRemoteSyncStoreState({+ isAdmin,+ currentBranch,+ syncType: "read-write",+ }),+ },+ );+};++const openBranchPickerAndSelect = async (branch: string) => {+ await userEvent.click(screen.getByTestId("settings-branch-switcher"));+ await userEvent.type(+ await screen.findByPlaceholderText("Find or create a branch..."),+ branch,+ );+ await userEvent.click(await screen.findByRole("option", { name: branch }));+};++describe("BranchSwitcher", () => {+ it("tells non-admins they need to be an admin instead of showing the control", () => {+ setup({ isAdmin: false });++ expect(+ screen.getByText("You need to be an admin to switch the sync branch."),+ ).toBeInTheDocument();+ expect(+ screen.queryByTestId("settings-branch-switcher"),+ ).not.toBeInTheDocument();+ });++ it("shows the current branch and an unsaved-changes count when dirty", () => {+ setup({ dirty: [createMockDirtyEntity()] });++ expect(screen.getByTestId("settings-branch-switcher")).toHaveTextContent(+ "main",+ );+ expect(+ screen.getByTestId("branch-switcher-dirty-warning"),+ ).toHaveTextContent("1 unsaved change");+ });++ it("explains that the branch is pinned by an env var and disables the control", () => {+ setup({ envVarName: "MB_REMOTE_SYNC_BRANCH" });++ expect(screen.getByText("Using MB_REMOTE_SYNC_BRANCH")).toBeInTheDocument();+ expect(screen.getByTestId("settings-branch-switcher")).toBeDisabled();+ });++ it("switches directly when the instance is clean", async () => {+ setup({ dirty: [] });++ await openBranchPickerAndSelect("develop");++ await waitFor(() => {+ expect(fetchMock.callHistory.called("remote-sync-import")).toBe(true);+ });+ // no choose-what-to-do modal on a clean switch+ expect(+ screen.queryByText(/You have unsynced changes/),+ ).not.toBeInTheDocument();+ });++ it("opens the choose-what-to-do modal when there are unsaved changes", async () => {+ setup({ dirty: [createMockDirtyEntity()] });++ await openBranchPickerAndSelect("develop");++ // the modal (rather than a direct switch) means the unsaved-changes path was taken+ expect(+ await screen.findByText(+ "You have unsynced changes. What do you want to do?",+ ),+ ).toBeInTheDocument();+ });+});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.tsxindex 7e895d8df10..0aa7bc72061 100644--- a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/RemoteSyncSettingsForm.tsx+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/RemoteSyncSettingsForm.tsx@@ -70,6 +70,7 @@ import { SharedTenantCollectionsList } from "../SharedTenantCollectionsList";import { SyncConflictModal } from "../SyncConflictModal";import { TopLevelCollectionsList } from "../TopLevelCollectionsList";+import { BranchSwitcher } from "./BranchSwitcher";import { DevInstanceUpsell } from "./DevInstanceUpsell";import { PullChangesButton } from "./PullChangesButton";import { TestConnectionButton } from "./TestConnectionButton";@@ -477,6 +478,30 @@ export const RemoteSyncSettingsForm = (props: RemoteSyncSettingsFormProps) => {)}</RemoteSyncSettingsSection>+ {/* Branch switching (read-write): a rare, destructive operation kept out of the everyday sync+ controls and behind guard rails. Read-only mode changes the branch via the Sync branch+ field below, which triggers a reconciling import. */}+ {isRemoteSyncEnabled &&+ values?.[TYPE_KEY] === "read-write" &&+ !isModalVariant && (+ <RemoteSyncSettingsSection+ title={t`Sync branch`}+ description={t`Choose which branch to sync with git.`}+ variant={variant}+ >+ <BranchSwitcher+ currentBranch={currentBranch}+ dirty={dirtyData?.dirty ?? []}+ disabled={settingDetails?.[BRANCH_KEY]?.is_env_setting}+ envVarName={+ settingDetails?.[BRANCH_KEY]?.is_env_setting+ ? settingDetails?.[BRANCH_KEY]?.env_name+ : undefined+ }+ />+ </RemoteSyncSettingsSection>+ )}+{/* Section 3: Branch to sync with (read-only only) */}{values?.[TYPE_KEY] === "read-only" && (<RemoteSyncSettingsSectiondiff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/SyncConflictModal/OutOfSyncOptions.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/SyncConflictModal/OutOfSyncOptions.unit.spec.tsxindex fbd3b713d84..6f9edb5155f 100644--- a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/SyncConflictModal/OutOfSyncOptions.unit.spec.tsx+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/SyncConflictModal/OutOfSyncOptions.unit.spec.tsx@@ -50,7 +50,7 @@ describe("OutOfSyncOptions", () => {});describe("switch-branch variant", () => {- it("shows correct options", () => {+ it("offers push, new-branch, and discard", () => {setup({ variant: "switch-branch" });expect(screen.getAllByRole("radio")).toHaveLength(3);expect(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 65db041db22..c9465bdd5d7 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@@ -46,6 +46,7 @@ import {interface UnsyncedWarningModalProps {currentBranch: string;+ /** switch-branch variant only: the branch to switch to once the chosen action resolves local changes. */nextBranch?: string | null;onClose: VoidFunction;variant: RemoteSyncConflictVariant;@@ -158,8 +159,9 @@ export const SyncConflictModal = (props: UnsyncedWarningModalProps) => {}if (optionValue === "discard") {- // nextBranch is set on a switch-branch discard; currentBranch is the branch we're on now and is- // asserted against the setting to catch a stale tab.+ // nextBranch is set on a switch-branch discard (the branch we're switching to); otherwise we discard+ // and reload the current branch. currentBranch is the expected-branch assertion (caught if a stale tab+ // switched under us).await discardChangesAndImport(nextBranch || currentBranch,currentBranch,diff --git a/frontend/src/metabase-types/api/remote-sync.ts b/frontend/src/metabase-types/api/remote-sync.tsindex 20ce041785b..26f2122804b 100644--- a/frontend/src/metabase-types/api/remote-sync.ts+++ b/frontend/src/metabase-types/api/remote-sync.ts@@ -173,7 +173,7 @@ export type RemoteSyncTask = {export type RemoteSyncConflictVariant =| "push" // Conflict when pushing (need to pull from remote first)| "pull" // Conflict when pulling (need to sync local changes)- | "switch-branch" // Conflict when switching branches+ | "switch-branch" // Local changes present when switching branches (Settings panel)| "setup"; // Conflict when setting up or pulling for the first timeexport type GetBranchesResponse = {