diff --git a/acceptance/cmd/aitools/auto-install/enable-disable/output.txt b/acceptance/cmd/aitools/auto-install/enable-disable/output.txt index d651e45cd40..a93c9e1d184 100644 --- a/acceptance/cmd/aitools/auto-install/enable-disable/output.txt +++ b/acceptance/cmd/aitools/auto-install/enable-disable/output.txt @@ -14,13 +14,15 @@ Automatic installation of Databricks AI tools is disabled. "opted_out": true } -=== enable clears it +=== enable stores the consent in its place >>> [CLI] aitools auto-install enable Automatic installation of Databricks AI tools is enabled. >>> auto_install_state -{} +{ + "consented": true +} === enable says when the environment still turns it off @@ -46,7 +48,9 @@ Error: no skills or plugins installed Exit code: 1 >>> auto_install_state -{} +{ + "consented": true +} === a global uninstall of a mistyped skill leaves it on @@ -56,7 +60,9 @@ Error: skill "databricks-tset" is not installed Exit code: 1 >>> auto_install_state -{} +{ + "consented": true +} === a global uninstall turns it off @@ -74,4 +80,25 @@ Uninstalled 1 skill. Uninstalled 1 skill. >>> auto_install_state -{} +{ + "consented": true +} + +=== a project install stores no consent + +>>> auto_install_state +(no auto-install state) + +=== a global install stores the consent + +>>> auto_install_state +{ + "consented": true +} + +=== a global install keeps an opt-out + +>>> auto_install_state +{ + "opted_out": true +} diff --git a/acceptance/cmd/aitools/auto-install/enable-disable/script b/acceptance/cmd/aitools/auto-install/enable-disable/script index 6bf99ed965d..e33d80ae40c 100644 --- a/acceptance/cmd/aitools/auto-install/enable-disable/script +++ b/acceptance/cmd/aitools/auto-install/enable-disable/script @@ -8,7 +8,7 @@ title "disable stores the opt-out" trace $CLI aitools auto-install disable trace auto_install_state -title "enable clears it" +title "enable stores the consent in its place" trace $CLI aitools auto-install enable trace auto_install_state @@ -41,3 +41,17 @@ cd "${USERPROFILE:-$HOME}/project" $CLI aitools install --skills-only --scope=project --agents=claude-code &> LOG.install-project trace $CLI aitools uninstall --scope=project trace auto_install_state + +title "a project install stores no consent" +rm "${USERPROFILE:-$HOME}/.databricks/aitools/auto-install.json" +$CLI aitools install --skills-only --scope=project --agents=claude-code &> LOG.install-project-2 +trace auto_install_state + +title "a global install stores the consent" +$CLI aitools install --skills-only --scope=global --agents=cursor &> LOG.install-global-2 +trace auto_install_state + +title "a global install keeps an opt-out" +$CLI aitools auto-install disable &> LOG.disable +$CLI aitools install --skills-only --scope=global --agents=cursor &> LOG.install-global-3 +trace auto_install_state diff --git a/acceptance/cmd/aitools/auto-install/first-run/output.txt b/acceptance/cmd/aitools/auto-install/first-run/output.txt index b67062b878c..e1ad16612b3 100644 --- a/acceptance/cmd/aitools/auto-install/first-run/output.txt +++ b/acceptance/cmd/aitools/auto-install/first-run/output.txt @@ -14,6 +14,7 @@ databricks-test >>> auto_install_state { "last_version": "1.30.0", + "installed_without_consent": true, "id": "treatment-machine" } @@ -56,7 +57,7 @@ SKILL.md my own skill >>> settled_version -{"last_version":"1.30.0"} +{"last_version":"1.30.0","installed_without_consent":true} === first run with the user's own skill under another name in an agent's skills directory: installs diff --git a/acceptance/cmd/aitools/auto-install/no-terminal/output.txt b/acceptance/cmd/aitools/auto-install/no-terminal/output.txt index 095daafc365..943fbd74005 100644 --- a/acceptance/cmd/aitools/auto-install/no-terminal/output.txt +++ b/acceptance/cmd/aitools/auto-install/no-terminal/output.txt @@ -26,5 +26,6 @@ databricks-test >>> auto_install_state { "last_version": "1.30.0", + "installed_without_consent": true, "id": "treatment-machine" } diff --git a/acceptance/cmd/aitools/auto-install/retries/output.txt b/acceptance/cmd/aitools/auto-install/retries/output.txt index b5aeb021d0b..17072cd7d67 100644 --- a/acceptance/cmd/aitools/auto-install/retries/output.txt +++ b/acceptance/cmd/aitools/auto-install/retries/output.txt @@ -15,6 +15,7 @@ "attempts": 1, "last_attempt": "[LAST_ATTEMPT]", "installing": true, + "installed_without_consent": true, "id": "treatment-machine" } @@ -51,5 +52,6 @@ Installed Databricks AI tools for Cursor. Disable: databricks aitools auto-insta >>> auto_install_state { "last_version": "1.31.0", + "installed_without_consent": true, "id": "treatment-machine" } diff --git a/acceptance/cmd/aitools/auto-install/skipped/output.txt b/acceptance/cmd/aitools/auto-install/skipped/output.txt index 75c41d79442..1fa240f0124 100644 --- a/acceptance/cmd/aitools/auto-install/skipped/output.txt +++ b/acceptance/cmd/aitools/auto-install/skipped/output.txt @@ -53,6 +53,7 @@ Automatic installation of Databricks AI tools is enabled. >>> auto_install_state { "last_version": "1.32.0", + "consented": true, "id": "treatment-machine" } @@ -68,6 +69,7 @@ Automatic installation of Databricks AI tools is enabled. >>> auto_install_state { "last_version": "1.33.0", + "consented": true, "id": "treatment-machine" } diff --git a/acceptance/cmd/aitools/auto-install/upgrade/output.txt b/acceptance/cmd/aitools/auto-install/upgrade/output.txt index e7e2668e911..82dcc6685ac 100644 --- a/acceptance/cmd/aitools/auto-install/upgrade/output.txt +++ b/acceptance/cmd/aitools/auto-install/upgrade/output.txt @@ -13,6 +13,13 @@ databricks-dropped databricks-edited databricks-kept +>>> auto_install_state +{ + "last_version": "1.30.0", + "installed_without_consent": true, + "id": "treatment-machine" +} + === upgrade to 1.31.0 with release 0.4.0: updates like aitools update, keeping the edited skills >>> DATABRICKS_AITOOLS_AUTO_INSTALL_CLI_VERSION=1.31.0 DATABRICKS_CLI_GITHUB_API_URL=[DATABRICKS_URL]/newer [CLI] jobs list @@ -37,6 +44,13 @@ my notes edited 1.0.0 my notes +>>> auto_install_state +{ + "last_version": "1.31.0", + "installed_without_consent": true, + "id": "treatment-machine" +} + === upgrade to 1.32.0 while the latest release is 0.2.0: no downgrade, nothing printed, not retried >>> DATABRICKS_AITOOLS_AUTO_INSTALL_CLI_VERSION=1.32.0 DATABRICKS_CLI_GITHUB_API_URL=[DATABRICKS_URL]/older [CLI] jobs list @@ -50,6 +64,7 @@ kept 2.0.0 >>> auto_install_state { "last_version": "1.32.0", + "installed_without_consent": true, "id": "treatment-machine" } @@ -62,6 +77,7 @@ kept 2.0.0 >>> auto_install_state { "last_version": "1.32.0", + "installed_without_consent": true, "id": "treatment-machine" } @@ -88,5 +104,6 @@ kept 2.0.0 >>> auto_install_state { "last_version": "1.33.0", + "consented": true, "id": "treatment-machine" } diff --git a/acceptance/cmd/aitools/auto-install/upgrade/script b/acceptance/cmd/aitools/auto-install/upgrade/script index 0cd0338817d..10ed0719170 100644 --- a/acceptance/cmd/aitools/auto-install/upgrade/script +++ b/acceptance/cmd/aitools/auto-install/upgrade/script @@ -11,6 +11,7 @@ title "first run of 1.30.0 installs skills release 0.3.0" trace $CLI jobs list trace print_telemetry trace cursor_skills +trace auto_install_state # The user edits a skill that the next release drops, and one that it updates. echo "my notes" >> "$skills_dir/databricks-dropped/SKILL.md" @@ -25,6 +26,9 @@ trace cursor_skills trace skill_file databricks-kept trace skill_file databricks-dropped trace skill_file databricks-edited +# Auto-install made the installation without asking, so it is not the user's +# consent. +trace auto_install_state title "upgrade to 1.32.0 while the latest release is 0.2.0: no downgrade, nothing printed, not retried" trace DATABRICKS_AITOOLS_AUTO_INSTALL_CLI_VERSION=1.32.0 DATABRICKS_CLI_GITHUB_API_URL=$DATABRICKS_HOST/older $CLI jobs list diff --git a/cmd/aitools/autoinstall.go b/cmd/aitools/autoinstall.go index ccd5aa70577..e9b2067ff77 100644 --- a/cmd/aitools/autoinstall.go +++ b/cmd/aitools/autoinstall.go @@ -47,7 +47,11 @@ func newAutoInstallToggleCmd(enable bool) *cobra.Command { Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, args []string) error { ctx := cmd.Context() - if err := autoinstall.SetOptedOut(ctx, !enable); err != nil { + consent := autoinstall.ConsentOptedOut + if enable { + consent = autoinstall.ConsentGiven + } + if _, err := autoinstall.SetConsent(ctx, consent); err != nil { return fmt.Errorf("failed to save the auto-install setting: %w", err) } printAutoInstallSetting(ctx, enable) diff --git a/cmd/aitools/autoinstall_run.go b/cmd/aitools/autoinstall_run.go index 55976446f7c..4f3d2919731 100644 --- a/cmd/aitools/autoinstall_run.go +++ b/cmd/aitools/autoinstall_run.go @@ -180,6 +180,7 @@ func autoInstall(ctx context.Context, skippedCommand bool) os.Signal { log.Debugf(ctx, "auto-install: skipped: %v", err) return nil } + consentExistingInstall(ctx, &in) reason := autoinstall.Decide(in) if !reason.Due() { log.Debugf(ctx, "auto-install: skipped: %s", reason) @@ -402,6 +403,47 @@ func installStateSaved(globalDir string) bool { return err != nil || existing != nil } +// consentExistingInstall stores the consent of a machine whose user never +// answered but has a global installation that the CLI made (one with install +// state): the user installed the tools, so auto-install keeps them up to date. +// Skills without install state may be the user's own copies, and a project +// installation belongs to the project, so neither counts. Nor does install +// state that auto-install wrote itself without consent (a coding agent's run, +// or a first install that did not finish). in is a run past stateFreeSkips; +// one in CI or with auto-install turned off in the environment stores nothing. +// in.State gets the stored consent. +func consentExistingInstall(ctx context.Context, in *autoinstall.Inputs) { + if in.CI || in.EnvOptOut || in.State.Consent() != autoinstall.ConsentUnknown { + return + } + if in.State.Installing || in.State.InstalledWithoutConsent { + return + } + globalDir, err := installer.GlobalSkillsDir(ctx) + if err != nil { + log.Debugf(ctx, "auto-install: could not look for an installation: %v", err) + return + } + existing, err := installer.LoadState(globalDir) + if err != nil { + log.Debugf(ctx, "auto-install: could not look for an installation: %v", err) + return + } + if existing == nil { + return + } + previous, err := autoinstall.GiveConsentIfUnknown(ctx) + if err != nil { + log.Debugf(ctx, "auto-install: could not save the state: %v", err) + return + } + // An opt-out stored since the state was read stays, and the run finds it + // when it reads the state again under the run lock. + if previous != autoinstall.ConsentOptedOut { + in.State.Consented = true + } +} + // saveInstallStateDigest records the digest of the install state that a first // install that did not finish saved, so that a later run can tell it from // install state that anything else wrote. Without the digest, a later run @@ -468,8 +510,8 @@ const skippedNotice = "Skipped. To install Databricks AI tools later, run: datab // version even when it is never answered: the process is killed, stdin is // closed, Ctrl+C is pressed, nobody answers within promptTimeout (an // unrecognized agent in a pseudo-terminal), or the answer is neither yes nor -// no. "Yes" is recorded so that the version's retries do not ask again; only -// "no" stores the opt-out. +// no. "Yes" is recorded so that the version's retries do not ask again, and +// stores the consent; "no" stores the opt-out. func (r autoInstallRun) ask(ctx context.Context, names []string) (bool, os.Signal) { if err := cmdio.DiscardInput(ctx); err != nil { log.Debugf(ctx, "auto-install: could not discard the pending input: %v", err) @@ -504,6 +546,10 @@ func (r autoInstallRun) ask(ctx context.Context, names []string) (bool, os.Signa // The install goes ahead; a retry of it asks again. log.Debugf(ctx, "auto-install: could not save the answer: %v", err) } + // The consent stays even if the install then fails or is refused. + if _, err := autoinstall.GiveConsentIfUnknown(ctx); err != nil { + log.Debugf(ctx, "auto-install: could not save the consent: %v", err) + } return true, nil case "n", "no": r.decline(ctx) @@ -519,7 +565,7 @@ func (r autoInstallRun) ask(ctx context.Context, names []string) (bool, os.Signa // asks again. func (r autoInstallRun) decline(ctx context.Context) { r.settle(ctx, protos.AitoolsAutoInstallOutcomeDeclined) - if err := autoinstall.Decline(ctx); err != nil { + if _, err := autoinstall.Decline(ctx); err != nil { log.Warnf(ctx, "Could not save the answer, so a later CLI version asks again: %v", err) cmdio.LogString(ctx, skippedNotice) return diff --git a/cmd/aitools/autoinstall_run_test.go b/cmd/aitools/autoinstall_run_test.go index 076090d57ea..812eed3fddf 100644 --- a/cmd/aitools/autoinstall_run_test.go +++ b/cmd/aitools/autoinstall_run_test.go @@ -3,6 +3,7 @@ package aitools import ( "bytes" "context" + "encoding/json" "errors" "io" "os" @@ -83,7 +84,7 @@ func TestAutoInstallPrompt(t *testing.T) { input: "\n", wantStderr: []string{"Installed Databricks AI tools for Cursor. Disable: databricks aitools auto-install disable"}, wantSkills: true, - wantState: autoinstall.State{LastVersion: "1.30.0", AcceptedVersion: "1.30.0", ID: "treatment-machine"}, + wantState: autoinstall.State{LastVersion: "1.30.0", Consented: true, AcceptedVersion: "1.30.0", ID: "treatment-machine"}, wantOutcome: protos.AitoolsAutoInstallOutcomeInstalled, }, { @@ -92,7 +93,7 @@ func TestAutoInstallPrompt(t *testing.T) { input: "Y\n", wantStderr: []string{"Installed Databricks AI tools for Cursor."}, wantSkills: true, - wantState: autoinstall.State{LastVersion: "1.30.0", AcceptedVersion: "1.30.0", ID: "treatment-machine"}, + wantState: autoinstall.State{LastVersion: "1.30.0", Consented: true, AcceptedVersion: "1.30.0", ID: "treatment-machine"}, wantOutcome: protos.AitoolsAutoInstallOutcomeInstalled, }, { @@ -130,7 +131,7 @@ func TestAutoInstallPrompt(t *testing.T) { wantPrompt: true, input: "\n", wantStderr: []string{"Could not install Databricks AI tools. To install them, run: databricks aitools install"}, - wantState: autoinstall.State{LastVersion: "1.30.0", Attempts: 1, LastAttempt: autoInstallTestNow, AcceptedVersion: "1.30.0", Installing: true, ID: "treatment-machine"}, + wantState: autoinstall.State{LastVersion: "1.30.0", Attempts: 1, LastAttempt: autoInstallTestNow, Consented: true, AcceptedVersion: "1.30.0", Installing: true, ID: "treatment-machine"}, wantOutcome: protos.AitoolsAutoInstallOutcomeFailed, }, { @@ -140,7 +141,7 @@ func TestAutoInstallPrompt(t *testing.T) { stdinPiped: true, stdoutRedirected: true, stderrRedirected: true, - wantState: autoinstall.State{LastVersion: "1.30.0", Attempts: 1, LastAttempt: autoInstallTestNow, Installing: true, ID: "treatment-machine"}, + wantState: autoinstall.State{LastVersion: "1.30.0", Attempts: 1, LastAttempt: autoInstallTestNow, Installing: true, InstalledWithoutConsent: true, ID: "treatment-machine"}, wantOutcome: protos.AitoolsAutoInstallOutcomeFailed, }, { @@ -149,7 +150,7 @@ func TestAutoInstallPrompt(t *testing.T) { wantPrompt: true, input: "\n", wantStderr: []string{"Did not install the Databricks AI tools skills: kept the databricks-test skill in the skills directory of Cursor, which an install would move aside; run 'databricks aitools install' to replace it"}, - wantState: autoinstall.State{LastVersion: "1.30.0", AcceptedVersion: "1.30.0", ID: "treatment-machine"}, + wantState: autoinstall.State{LastVersion: "1.30.0", Consented: true, AcceptedVersion: "1.30.0", ID: "treatment-machine"}, wantOutcome: protos.AitoolsAutoInstallOutcomeKept, }, { @@ -159,7 +160,7 @@ func TestAutoInstallPrompt(t *testing.T) { input: "\n", wantStderr: []string{"Installed Databricks AI tools for Cursor."}, wantSkills: true, - wantState: autoinstall.State{LastVersion: "1.30.0", AcceptedVersion: "1.30.0", ID: "treatment-machine"}, + wantState: autoinstall.State{LastVersion: "1.30.0", Consented: true, AcceptedVersion: "1.30.0", ID: "treatment-machine"}, wantOutcome: protos.AitoolsAutoInstallOutcomeInstalled, }, { @@ -204,7 +205,7 @@ func TestAutoInstallPrompt(t *testing.T) { stderrRedirected: true, wantStderr: []string{"Installed Databricks AI tools for Cursor."}, wantSkills: true, - wantState: autoinstall.State{LastVersion: "1.30.0", ID: "treatment-machine"}, + wantState: autoinstall.State{LastVersion: "1.30.0", InstalledWithoutConsent: true, ID: "treatment-machine"}, wantOutcome: protos.AitoolsAutoInstallOutcomeInstalled, }, { @@ -213,7 +214,7 @@ func TestAutoInstallPrompt(t *testing.T) { input: "n\n", wantStderr: []string{"Installed Databricks AI tools for Cursor."}, wantSkills: true, - wantState: autoinstall.State{LastVersion: "1.30.0", ID: "treatment-machine"}, + wantState: autoinstall.State{LastVersion: "1.30.0", InstalledWithoutConsent: true, ID: "treatment-machine"}, wantOutcome: protos.AitoolsAutoInstallOutcomeInstalled, }, { @@ -222,7 +223,7 @@ func TestAutoInstallPrompt(t *testing.T) { input: "", wantStderr: []string{"Installed Databricks AI tools for Cursor."}, wantSkills: true, - wantState: autoinstall.State{LastVersion: "1.30.0", AcceptedVersion: "1.30.0", ID: "treatment-machine"}, + wantState: autoinstall.State{LastVersion: "1.30.0", AcceptedVersion: "1.30.0", InstalledWithoutConsent: true, ID: "treatment-machine"}, wantOutcome: protos.AitoolsAutoInstallOutcomeInstalled, }, { @@ -234,7 +235,7 @@ func TestAutoInstallPrompt(t *testing.T) { stderrRedirected: true, wantStderr: []string{"Installed Databricks AI tools for Cursor."}, wantSkills: true, - wantState: autoinstall.State{LastVersion: "1.30.0", AcceptedVersion: "1.30.0", ID: "treatment-machine"}, + wantState: autoinstall.State{LastVersion: "1.30.0", AcceptedVersion: "1.30.0", InstalledWithoutConsent: true, ID: "treatment-machine"}, wantOutcome: protos.AitoolsAutoInstallOutcomeInstalled, }, { @@ -244,7 +245,7 @@ func TestAutoInstallPrompt(t *testing.T) { wantPrompt: true, input: "\n", wantSkills: true, - wantState: autoinstall.State{LastVersion: "1.30.0", AcceptedVersion: "1.30.0", ID: "treatment-machine"}, + wantState: autoinstall.State{LastVersion: "1.30.0", Consented: true, AcceptedVersion: "1.30.0", ID: "treatment-machine"}, wantOutcome: protos.AitoolsAutoInstallOutcomeInstalled, }, { @@ -274,7 +275,7 @@ func TestAutoInstallPrompt(t *testing.T) { inContainer: true, wantStderr: []string{"Installed Databricks AI tools for Cursor."}, wantSkills: true, - wantState: autoinstall.State{LastVersion: "1.30.0", ID: "treatment-machine"}, + wantState: autoinstall.State{LastVersion: "1.30.0", InstalledWithoutConsent: true, ID: "treatment-machine"}, wantOutcome: protos.AitoolsAutoInstallOutcomeInstalled, }, { @@ -541,7 +542,7 @@ func TestAutoInstallWaitsBeforeARetry(t *testing.T) { t.Setenv("DATABRICKS_AITOOLS_AUTO_INSTALL_CLI_VERSION", "1.31.0") outcomes, state = runAutoInstallAt(t, -time.Hour) assert.Equal(t, []protos.AitoolsAutoInstallOutcome{protos.AitoolsAutoInstallOutcomeInstalled}, outcomes) - assert.Equal(t, autoinstall.State{LastVersion: "1.31.0", ID: "treatment-machine"}, state) + assert.Equal(t, autoinstall.State{LastVersion: "1.31.0", InstalledWithoutConsent: true, ID: "treatment-machine"}, state) } // A first install that saved install state but did not give Cursor the skills @@ -565,7 +566,8 @@ func TestAutoInstallRetriesAnAgentThatGotNoSkills(t *testing.T) { require.NoError(t, os.Remove(skillsDir)) outcomes, state = runAutoInstallAt(t, 5*time.Minute) assert.Equal(t, []protos.AitoolsAutoInstallOutcome{protos.AitoolsAutoInstallOutcomeInstalled}, outcomes) - assert.Equal(t, autoinstall.State{LastVersion: "1.30.0", ID: "treatment-machine"}, state) + // The install state of the first attempt is not the user's consent. + assert.Equal(t, autoinstall.State{LastVersion: "1.30.0", InstalledWithoutConsent: true, ID: "treatment-machine"}, state) assert.FileExists(t, filepath.Join(skillsDir, "databricks-test", "SKILL.md")) } @@ -602,7 +604,7 @@ func TestAutoInstallFinishesAMixedInstallRefusedTheSkills(t *testing.T) { assert.Empty(t, installState.Skills) digest, err := installStateDigest(installState) require.NoError(t, err) - assert.Equal(t, autoinstall.State{LastVersion: "1.30.0", Installing: true, InstallStateDigest: digest, ID: "treatment-machine"}, state) + assert.Equal(t, autoinstall.State{LastVersion: "1.30.0", Installing: true, InstallStateDigest: digest, InstalledWithoutConsent: true, ID: "treatment-machine"}, state) assert.NoFileExists(t, filepath.Join(handPlaced, "SKILL.md")) assert.Equal(t, 1, pluginInstalls) @@ -610,14 +612,14 @@ func TestAutoInstallFinishesAMixedInstallRefusedTheSkills(t *testing.T) { t.Setenv("DATABRICKS_AITOOLS_AUTO_INSTALL_CLI_VERSION", "1.31.0") outcomes, state = runAutoInstallAt(t, 0) assert.Equal(t, []protos.AitoolsAutoInstallOutcome{protos.AitoolsAutoInstallOutcomeKept}, outcomes) - assert.Equal(t, autoinstall.State{LastVersion: "1.31.0", Installing: true, InstallStateDigest: digest, ID: "treatment-machine"}, state) + assert.Equal(t, autoinstall.State{LastVersion: "1.31.0", Installing: true, InstallStateDigest: digest, InstalledWithoutConsent: true, ID: "treatment-machine"}, state) assert.Equal(t, 1, pluginInstalls) require.NoError(t, os.RemoveAll(handPlaced)) t.Setenv("DATABRICKS_AITOOLS_AUTO_INSTALL_CLI_VERSION", "1.32.0") outcomes, state = runAutoInstallAt(t, 0) assert.Equal(t, installed, outcomes) - assert.Equal(t, autoinstall.State{LastVersion: "1.32.0", ID: "treatment-machine"}, state) + assert.Equal(t, autoinstall.State{LastVersion: "1.32.0", InstalledWithoutConsent: true, ID: "treatment-machine"}, state) assert.FileExists(t, filepath.Join(handPlaced, "SKILL.md")) assert.Equal(t, 1, pluginInstalls) installState, err = installer.LoadState(filepath.Join(home, ".databricks", "aitools", "skills")) @@ -638,7 +640,7 @@ func TestAutoInstallSettlesARefusalThatWroteNothing(t *testing.T) { outcomes, state := runAutoInstallAt(t, 0) assert.Equal(t, kept, outcomes) - assert.Equal(t, autoinstall.State{LastVersion: "1.30.0", ID: "treatment-machine"}, state) + assert.Equal(t, autoinstall.State{LastVersion: "1.30.0", InstalledWithoutConsent: true, ID: "treatment-machine"}, state) moved := filepath.Join(home, ".databricks", "aitools", "skills", "databricks-test") require.NoError(t, os.MkdirAll(filepath.Dir(moved), 0o755)) @@ -646,7 +648,7 @@ func TestAutoInstallSettlesARefusalThatWroteNothing(t *testing.T) { t.Setenv("DATABRICKS_AITOOLS_AUTO_INSTALL_CLI_VERSION", "1.31.0") outcomes, state = runAutoInstallAt(t, 0) assert.Equal(t, kept, outcomes) - assert.Equal(t, autoinstall.State{LastVersion: "1.31.0", ID: "treatment-machine"}, state) + assert.Equal(t, autoinstall.State{LastVersion: "1.31.0", InstalledWithoutConsent: true, ID: "treatment-machine"}, state) data, err := os.ReadFile(filepath.Join(moved, "SKILL.md")) require.NoError(t, err) assert.Equal(t, "my own skill", string(data)) @@ -668,14 +670,14 @@ func TestAutoInstallKeepsAnUnfinishedInstallRefusedTheSkills(t *testing.T) { outcomes, state := runAutoInstallAt(t, 0) assert.Equal(t, []protos.AitoolsAutoInstallOutcome{protos.AitoolsAutoInstallOutcomeKept}, outcomes) - assert.Equal(t, autoinstall.State{LastVersion: "1.30.0", Installing: true, ID: "treatment-machine"}, state) + assert.Equal(t, autoinstall.State{LastVersion: "1.30.0", Installing: true, InstalledWithoutConsent: true, ID: "treatment-machine"}, state) assert.NoFileExists(t, filepath.Join(handPlaced, "SKILL.md")) require.NoError(t, os.RemoveAll(handPlaced)) t.Setenv("DATABRICKS_AITOOLS_AUTO_INSTALL_CLI_VERSION", "1.31.0") outcomes, state = runAutoInstallAt(t, 0) assert.Equal(t, []protos.AitoolsAutoInstallOutcome{protos.AitoolsAutoInstallOutcomeInstalled}, outcomes) - assert.Equal(t, autoinstall.State{LastVersion: "1.31.0", ID: "treatment-machine"}, state) + assert.Equal(t, autoinstall.State{LastVersion: "1.31.0", InstalledWithoutConsent: true, ID: "treatment-machine"}, state) assert.FileExists(t, filepath.Join(handPlaced, "SKILL.md")) } @@ -700,7 +702,7 @@ func runAutoInstallAt(t *testing.T, elapsed time.Duration) ([]protos.AitoolsAuto // failedAttempts is the state after attempts failed first installs of 1.30.0, // the last at autoInstallTestNow plus elapsed. func failedAttempts(attempts int, elapsed time.Duration) autoinstall.State { - return autoinstall.State{LastVersion: "1.30.0", Attempts: attempts, LastAttempt: autoInstallTestNow.Add(elapsed), Installing: true, ID: "treatment-machine"} + return autoinstall.State{LastVersion: "1.30.0", Attempts: attempts, LastAttempt: autoInstallTestNow.Add(elapsed), Installing: true, InstalledWithoutConsent: true, ID: "treatment-machine"} } // A run that has nothing to install or cannot ask skips before the gate @@ -768,7 +770,7 @@ func TestAutoInstallSkipsRootInAUserHome(t *testing.T) { assert.Equal(t, 1, *lookups) state, err := autoinstall.Load(ctx) require.NoError(t, err) - assert.Equal(t, autoinstall.State{LastVersion: "1.30.0", ID: "treatment-machine"}, state) + assert.Equal(t, autoinstall.State{LastVersion: "1.30.0", InstalledWithoutConsent: true, ID: "treatment-machine"}, state) }) } @@ -803,7 +805,8 @@ func TestAutoInstallStopsAtAnOptOutStoredWhileItDecides(t *testing.T) { home := setupAutoInstallHome(t, "", "CLAUDECODE", "1") t.Cleanup(func() { gateOn = autoinstall.GateOn }) gateOn = func(ctx context.Context, _ string) (bool, error) { - require.NoError(t, autoinstall.SetOptedOut(ctx, true)) + _, err := autoinstall.SetConsent(ctx, autoinstall.ConsentOptedOut) + require.NoError(t, err) return true, nil } ctx := cmdio.MockDiscard(t.Context()) @@ -870,6 +873,84 @@ func TestUninstallFailsWhileAnAutoInstallRuns(t *testing.T) { assert.Equal(t, autoinstall.State{LastVersion: "1.30.0", OptedOut: true, ID: "treatment-machine"}, state) } +// A global installation the CLI made counts as the user's consent on a run +// that could auto-install. The machine settled the version already, so the +// runs install nothing and only the consent changes. +func TestAutoInstallStoresTheConsentOfAnExistingInstall(t *testing.T) { + const settled = `{"id": "treatment-machine", "last_version": "1.30.0"}` + tests := []struct { + name string + state string + // global and project write install state in that scope. + global bool + project bool + // mcpOnly writes global install state that records only MCP servers. + mcpOnly bool + // untracked puts skills in the global directory without install state. + untracked bool + env []string + want autoinstall.Consent + }{ + {name: "global install state", global: true, want: autoinstall.ConsentGiven}, + {name: "no installation", want: autoinstall.ConsentUnknown}, + {name: "skills without install state", untracked: true, want: autoinstall.ConsentUnknown}, + {name: "a project installation", project: true, want: autoinstall.ConsentUnknown}, + {name: "global install state of MCP servers only", mcpOnly: true, want: autoinstall.ConsentUnknown}, + // Install state that auto-install wrote itself is not the user's + // consent: a coding agent's install, or a first install that did not + // finish. + {name: "install state auto-install wrote without consent", state: `{"id": "treatment-machine", "last_version": "1.30.0", "installed_without_consent": true}`, global: true, want: autoinstall.ConsentUnknown}, + {name: "install state of an unfinished first install", state: `{"id": "treatment-machine", "last_version": "1.30.0", "installing": true}`, global: true, want: autoinstall.ConsentUnknown}, + {name: "an opt-out stays", state: `{"id": "treatment-machine", "last_version": "1.30.0", "opted_out": true}`, global: true, want: autoinstall.ConsentOptedOut}, + {name: "not in CI", global: true, env: []string{"CI", "true"}, want: autoinstall.ConsentUnknown}, + {name: "not with the environment opt-out", global: true, env: []string{autoinstall.EnvVar, "false"}, want: autoinstall.ConsentUnknown}, + {name: "not on a development build", global: true, env: []string{"DATABRICKS_AITOOLS_AUTO_INSTALL_CLI_VERSION", "1.30.0-dev+abcdef123456"}, want: autoinstall.ConsentUnknown}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + state := tc.state + if state == "" { + state = settled + } + home := setupAutoInstallHome(t, state, tc.env...) + globalDir := filepath.Join(home, ".databricks", "aitools", "skills") + project := t.TempDir() + t.Chdir(project) + recorded := &installer.InstallState{SchemaVersion: installer.CurrentSchemaVersion, Skills: map[string]string{"databricks-test": "1.0.0"}} + if tc.global { + require.NoError(t, installer.SaveState(globalDir, recorded)) + } + if tc.project { + require.NoError(t, installer.SaveState(filepath.Join(project, ".databricks", "aitools", "skills"), recorded)) + } + if tc.mcpOnly { + require.NoError(t, os.MkdirAll(globalDir, 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(globalDir, ".state.json"), []byte(`{"mcp": {"servers": {}}}`), 0o600)) + } + if tc.untracked { + require.NoError(t, os.MkdirAll(filepath.Join(globalDir, "databricks-test"), 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(globalDir, "databricks-test", "SKILL.md"), []byte("mine"), 0o644)) + } + t.Cleanup(func() { gateOn = autoinstall.GateOn }) + gateOn = func(context.Context, string) (bool, error) { + t.Error("the gate was looked up") + return true, nil + } + ctx := telemetry.WithNewLogger(cmdio.MockDiscard(t.Context())) + runAutoInstallHook(ctx) + + got, err := autoinstall.Load(ctx) + require.NoError(t, err) + assert.Equal(t, tc.want, got.Consent()) + var seeded autoinstall.State + require.NoError(t, json.Unmarshal([]byte(state), &seeded)) + got.OptedOut, got.Consented = seeded.OptedOut, seeded.Consented + assert.Equal(t, seeded, got, "nothing else changes") + assert.Empty(t, telemetry.BufferedEvents(ctx)) + }) + } +} + func TestToolsPlanNewAgents(t *testing.T) { claude := &agents.Agent{DisplayName: "Claude Code"} cursor := &agents.Agent{DisplayName: "Cursor"} diff --git a/cmd/aitools/install.go b/cmd/aitools/install.go index 7ab0cb6056e..ea43c89606e 100644 --- a/cmd/aitools/install.go +++ b/cmd/aitools/install.go @@ -12,6 +12,7 @@ import ( "github.com/charmbracelet/huh" "github.com/databricks/cli/cmd/root" "github.com/databricks/cli/libs/aitools/agents" + "github.com/databricks/cli/libs/aitools/autoinstall" "github.com/databricks/cli/libs/aitools/installer" "github.com/databricks/cli/libs/cmdio" "github.com/databricks/cli/libs/flags" @@ -390,6 +391,10 @@ Supported agents: ` + strings.Join(agents.SupportedNames(), ", "), }() outcomes, runErr = executePlan(ctx, src, plan, opts, rerun, jsonMode) + // Auto-install keeps only the global scope up to date. + if scope == installer.ScopeGlobal && anyInstalled(outcomes) { + storeInstallConsent(ctx) + } for _, s := range deliverySteps(outcomes) { funnel.step(ctx, s) } @@ -1352,3 +1357,12 @@ func printNoAgentsMessage(ctx context.Context, rerun installInvocation) { named, _ := commandText(runtime.GOOS, rerun, nil, "--agents=") cmdio.LogString(ctx, "Install one, then re-run "+rerunPhrase(runtime.GOOS, rerun)+". To set up an agent that was not detected, name it: "+named) } + +// storeInstallConsent records a global install as the user's consent to +// installing the tools and keeping them up to date, unless the user answered +// before: an earlier opt-out stays. +func storeInstallConsent(ctx context.Context) { + if _, err := autoinstall.GiveConsentIfUnknown(ctx); err != nil { + log.Debugf(ctx, "Could not save the consent to install Databricks AI tools automatically: %v", err) + } +} diff --git a/cmd/aitools/install_test.go b/cmd/aitools/install_test.go index e852aa62b52..f4c7eff22c5 100644 --- a/cmd/aitools/install_test.go +++ b/cmd/aitools/install_test.go @@ -22,6 +22,7 @@ import ( "github.com/charmbracelet/huh" "github.com/databricks/cli/cmd/root" "github.com/databricks/cli/libs/aitools/agents" + "github.com/databricks/cli/libs/aitools/autoinstall" "github.com/databricks/cli/libs/aitools/installer" "github.com/databricks/cli/libs/cmdio" "github.com/databricks/cli/libs/flags" @@ -2505,3 +2506,45 @@ func TestTopLevelFailureKeepsErrorsOutsideAgents(t *testing.T) { require.ErrorIs(t, top, signInErr) assert.Equal(t, signInErr.Error(), top.Error()) } + +// A global install that set an agent up is the user's consent to keeping the +// tools up to date, unless the user answered before. +func TestInstallStoresTheConsent(t *testing.T) { + tests := []struct { + name string + consent autoinstall.Consent + args []string + // failSkills makes the skills install fail, so no agent is set up. + failSkills bool + want autoinstall.Consent + }{ + {name: "global install", args: []string{"--scope=global"}, want: autoinstall.ConsentGiven}, + {name: "an opt-out stays", consent: autoinstall.ConsentOptedOut, args: []string{"--scope=global"}, want: autoinstall.ConsentOptedOut}, + {name: "project install", args: []string{"--scope=project"}, want: autoinstall.ConsentUnknown}, + {name: "a global install that set no agent up", args: []string{"--scope=global"}, failSkills: true, want: autoinstall.ConsentUnknown}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + isolateAgents(t, "CURSOR_AGENT", "1") + setupTestAgents(t) + t.Chdir(t.TempDir()) + setupInstallMock(t) + if tc.failSkills { + installSkillsForAgentsFn = func(context.Context, installer.ManifestSource, []*agents.Agent, installer.InstallOptions) error { + return errors.New("download failed") + } + } + ctx := cmdio.MockDiscard(t.Context()) + if tc.consent != autoinstall.ConsentUnknown { + _, err := autoinstall.SetConsent(ctx, tc.consent) + require.NoError(t, err) + } + + ctx, err := runInstall(t, ctx, append(tc.args, "--skills-only")...) + assert.Equal(t, tc.failSkills, err != nil, "install fails: %v", err) + state, err := autoinstall.Load(ctx) + require.NoError(t, err) + assert.Equal(t, tc.want, state.Consent()) + }) + } +} diff --git a/cmd/aitools/uninstall.go b/cmd/aitools/uninstall.go index 1a90556b862..e38598e70ba 100644 --- a/cmd/aitools/uninstall.go +++ b/cmd/aitools/uninstall.go @@ -142,7 +142,7 @@ The command exits with code 1 when every removal it attempts fails.`, // one counts too: the update it runs re-adds removed skills. A run // that removed nothing (a mistyped skill, nothing installed) does not. if scope == installer.ScopeGlobal && (result.PluginsRemoved > 0 || result.SkillsChanged > 0) { - if err := autoinstall.SetOptedOut(ctx, true); err != nil { + if _, err := autoinstall.SetConsent(ctx, autoinstall.ConsentOptedOut); err != nil { log.Warnf(ctx, "Could not turn off the automatic installation of Databricks AI tools: %v", err) } } diff --git a/cmd/apps/init_test.go b/cmd/apps/init_test.go index 3551102727a..b8262632fab 100644 --- a/cmd/apps/init_test.go +++ b/cmd/apps/init_test.go @@ -1820,7 +1820,8 @@ func TestSelfExecEnvCarriesBothMarkers(t *testing.T) { assert.Equal(t, []string{"HOME=/home/user", "DATABRICKS_CLI_SELF_EXEC=1"}, selfExecEnv([]string{"HOME=/home/user"})) // After a "no", the child also does not auto-install. - require.NoError(t, autoinstall.Decline(ctx)) + _, err := autoinstall.Decline(ctx) + require.NoError(t, err) environ := selfExecEnv([]string{"HOME=/home/user"}) assert.Contains(t, environ, "DATABRICKS_CLI_SELF_EXEC=1") assert.Contains(t, environ, autoinstall.EnvVar+"=false") diff --git a/libs/aitools/agents/recommend.go b/libs/aitools/agents/recommend.go index 963c382f990..2509ae95d43 100644 --- a/libs/aitools/agents/recommend.go +++ b/libs/aitools/agents/recommend.go @@ -61,7 +61,8 @@ func noInstalledPlugins(context.Context) []string { return nil } // or the databricks plugin) installed. Callers pass installer.InstalledPluginAgents as // installedPlugins (see HasDatabricksToolingInstalled). // In interactive mode, prompts the user to install now using installFn; a "no" also turns -// auto-install off. In non-interactive mode, prints a hint. +// auto-install off, and a "yes" stores the consent to keep the tools up to date unless the +// user answered before. In non-interactive mode, prints a hint. func RecommendSkillsInstall(ctx context.Context, installedPlugins func(context.Context) []string, installFn func(context.Context) error) error { if HasDatabricksToolingInstalled(ctx, installedPlugins) { return nil @@ -80,7 +81,7 @@ func RecommendSkillsInstall(ctx context.Context, installedPlugins func(context.C if !yes { // The automatic install after this command (and after later upgrades) // must not install what the user just turned down. - if err := autoinstall.Decline(ctx); err != nil { + if _, err := autoinstall.Decline(ctx); err != nil { log.Warnf(ctx, "Could not turn off the automatic installation of Databricks AI tools: %v", err) return nil } @@ -89,6 +90,12 @@ func RecommendSkillsInstall(ctx context.Context, installedPlugins func(context.C return nil } + // The user asked for the tools, so the automatic install may keep them up to + // date, also when this install fails. An earlier opt-out stays. + if _, err := autoinstall.GiveConsentIfUnknown(ctx); err != nil { + log.Debugf(ctx, "Could not save the consent to install Databricks AI tools automatically: %v", err) + } + if err := installFn(ctx); err != nil { log.Warnf(ctx, "Skills installation failed: %v", err) } diff --git a/libs/aitools/agents/recommend_test.go b/libs/aitools/agents/recommend_test.go index 241878b52f3..cdf1525016a 100644 --- a/libs/aitools/agents/recommend_test.go +++ b/libs/aitools/agents/recommend_test.go @@ -165,6 +165,65 @@ func TestRecommendSkillsInstallInteractiveDecline(t *testing.T) { assert.Contains(t, <-stderr, "databricks aitools auto-install enable") } +// A "yes" is the consent to keep the tools up to date, unless the user +// answered before. +func TestRecommendSkillsInstallInteractiveYesStoresTheConsent(t *testing.T) { + for _, tc := range []struct { + name string + prior autoinstall.Consent + want autoinstall.Consent + }{ + {name: "unknown", prior: autoinstall.ConsentUnknown, want: autoinstall.ConsentGiven}, + {name: "an opt-out stays", prior: autoinstall.ConsentOptedOut, want: autoinstall.ConsentOptedOut}, + } { + t.Run(tc.name, func(t *testing.T) { + tmpDir := t.TempDir() + t.Setenv("HOME", tmpDir) + t.Setenv("USERPROFILE", tmpDir) + + origRegistry := Registry + Registry = []*Agent{ + { + Name: "test-agent", + DisplayName: "Test Agent", + ConfigDir: func(_ context.Context) (string, error) { return tmpDir, nil }, + }, + } + defer func() { Registry = origRegistry }() + + ctx, testIO := cmdio.SetupTest(t.Context(), cmdio.TestOptions{PromptSupported: true}) + defer testIO.Done() + ctx = telemetry.WithNewLogger(ctx) + if tc.prior != autoinstall.ConsentUnknown { + _, err := autoinstall.SetConsent(ctx, tc.prior) + require.NoError(t, err) + } + + // Drain stderr so the prompt write doesn't block. + go func() { _, _ = io.Copy(io.Discard, testIO.Stderr) }() + + installed := false + errc := make(chan error, 1) + go func() { + errc <- RecommendSkillsInstall(ctx, noInstalledPlugins, func(context.Context) error { + installed = true + return nil + }) + }() + + _, err := testIO.Stdin.WriteString("y\n") + require.NoError(t, err) + require.NoError(t, testIO.Stdin.Flush()) + + require.NoError(t, <-errc) + assert.True(t, installed) + state, err := autoinstall.Load(ctx) + require.NoError(t, err) + assert.Equal(t, tc.want, state.Consent()) + }) + } +} + func TestMaybeVersionCheckTip(t *testing.T) { noPlugins := func(context.Context) []string { return nil } recordedCodexPlugin := func(context.Context) []string { return []string{NameCodex} } diff --git a/libs/aitools/autoinstall/decide_test.go b/libs/aitools/autoinstall/decide_test.go index 6aee094c50a..15e991c290e 100644 --- a/libs/aitools/autoinstall/decide_test.go +++ b/libs/aitools/autoinstall/decide_test.go @@ -71,6 +71,7 @@ func TestDecide(t *testing.T) { {name: "CI before the opt-out", modify: func(in *Inputs) { in.CI = true; in.EnvOptOut = true }, want: ReasonSkippedCI}, {name: "env opt-out", modify: func(in *Inputs) { in.EnvOptOut = true }, want: ReasonSkippedOptOut}, {name: "persisted opt-out", modify: func(in *Inputs) { in.State.OptedOut = true }, want: ReasonSkippedOptOut}, + {name: "env opt-out over a stored consent", modify: func(in *Inputs) { in.EnvOptOut = true; in.State.Consented = true }, want: ReasonSkippedOptOut}, {name: "opt-out before the gate", modify: func(in *Inputs) { in.State.OptedOut = true; in.GateOn = false }, want: ReasonSkippedOptOut}, {name: "gate off", modify: func(in *Inputs) { in.GateOn = false }, want: ReasonGateOff}, {name: "gate off hides the holdout", modify: func(in *Inputs) { in.GateOn = false; in.Bucket = 0 }, want: ReasonGateOff}, diff --git a/libs/aitools/autoinstall/run.go b/libs/aitools/autoinstall/run.go index 5e0f9a7f958..ab9ec43240a 100644 --- a/libs/aitools/autoinstall/run.go +++ b/libs/aitools/autoinstall/run.go @@ -135,9 +135,15 @@ func RecordUnfinished(ctx context.Context, version, id string) error { }) } -// MarkInstalling sets State.Installing before a first install starts. +// MarkInstalling sets State.Installing before a first install starts, and +// State.InstalledWithoutConsent when the user has not answered. func MarkInstalling(ctx context.Context) error { - return updateState(ctx, func(s *State) { s.Installing = true }) + return updateState(ctx, func(s *State) { + s.Installing = true + if s.Consent() == ConsentUnknown { + s.InstalledWithoutConsent = true + } + }) } // SaveInstallStateDigest sets State.InstallStateDigest after a first install diff --git a/libs/aitools/autoinstall/run_test.go b/libs/aitools/autoinstall/run_test.go index 3c43583cc13..59841b6056c 100644 --- a/libs/aitools/autoinstall/run_test.go +++ b/libs/aitools/autoinstall/run_test.go @@ -42,7 +42,10 @@ func TestRecordKeepsConcurrentOptOut(t *testing.T) { for range 20 { wg.Go(func() { assert.NoError(t, Record(ctx, "1.30.0", 1, "machine", time.Now())) }) } - wg.Go(func() { assert.NoError(t, SetOptedOut(ctx, true)) }) + wg.Go(func() { + _, err := SetConsent(ctx, ConsentOptedOut) + assert.NoError(t, err) + }) wg.Wait() s, err := Load(ctx) @@ -118,14 +121,15 @@ func TestLockReturnsOtherErrorsAtOnce(t *testing.T) { assert.Equal(t, 1, tries) } -func TestSetOptedOutWithoutLocks(t *testing.T) { +func TestSetConsentWithoutLocks(t *testing.T) { ctx := env.WithUserHomeDir(t.Context(), t.TempDir()) // An explicit opt-out must work where the filesystem has no locks. orig := tryLock t.Cleanup(func() { tryLock = orig }) tryLock = func(*os.File) error { return errors.New("no locks here") } - require.NoError(t, SetOptedOut(ctx, true)) + _, err := SetConsent(ctx, ConsentOptedOut) + require.NoError(t, err) s, err := load(ctx) require.NoError(t, err) @@ -133,7 +137,8 @@ func TestSetOptedOutWithoutLocks(t *testing.T) { // A lock another process holds is waited for, not skipped. tryLock = func(*os.File) error { return errLockHeld } - assert.ErrorIs(t, SetOptedOut(ctx, false), errLockHeld) + _, err = SetConsent(ctx, ConsentGiven) + assert.ErrorIs(t, err, errLockHeld) } func TestRecordClearsInstallingWhenSettled(t *testing.T) { @@ -164,7 +169,38 @@ func TestRecordUnfinishedSettlesAndKeepsInstalling(t *testing.T) { require.NoError(t, RecordUnfinished(ctx, "1.30.0", "machine")) s, err := Load(ctx) require.NoError(t, err) - assert.Equal(t, State{LastVersion: "1.30.0", Installing: true, InstallStateDigest: "digest", ID: "machine"}, s) + assert.Equal(t, State{LastVersion: "1.30.0", Installing: true, InstallStateDigest: "digest", InstalledWithoutConsent: true, ID: "machine"}, s) +} + +// A first install that starts before the user answered is marked as made +// without consent, until the user answers. +func TestMarkInstallingRecordsAnInstallWithoutConsent(t *testing.T) { + for _, tc := range []struct { + name string + state State + want State + }{ + {"unknown", State{}, State{Installing: true, InstalledWithoutConsent: true}}, + {"given", State{Consented: true}, State{Consented: true, Installing: true}}, + } { + t.Run(tc.name, func(t *testing.T) { + ctx := env.WithUserHomeDir(t.Context(), t.TempDir()) + require.NoError(t, save(ctx, tc.state)) + + require.NoError(t, MarkInstalling(ctx)) + s, err := Load(ctx) + require.NoError(t, err) + assert.Equal(t, tc.want, s) + }) + } + + ctx := env.WithUserHomeDir(t.Context(), t.TempDir()) + require.NoError(t, MarkInstalling(ctx)) + _, err := SetConsent(ctx, ConsentOptedOut) + require.NoError(t, err) + s, err := Load(ctx) + require.NoError(t, err) + assert.Equal(t, State{OptedOut: true, Installing: true}, s, "an answer clears the mark") } func TestRecordStoresTheLastFailedAttempt(t *testing.T) { @@ -240,7 +276,8 @@ func TestStartAttemptStopsAtAnOptOut(t *testing.T) { require.NoError(t, err) assert.Equal(t, State{LastVersion: "1.30.0", Attempts: 1, LastAttempt: at, ID: "machine"}, s) - require.NoError(t, SetOptedOut(ctx, true)) + _, err = SetConsent(ctx, ConsentOptedOut) + require.NoError(t, err) started, err = StartAttempt(ctx, "1.30.0", 2, "machine", at) require.NoError(t, err) assert.False(t, started) diff --git a/libs/aitools/autoinstall/state.go b/libs/aitools/autoinstall/state.go index e401c928b73..92a456f1943 100644 --- a/libs/aitools/autoinstall/state.go +++ b/libs/aitools/autoinstall/state.go @@ -48,6 +48,17 @@ type State struct { // "no" to the skills prompt of `databricks apps init`. OptedOut bool `json:"opted_out,omitempty"` + // Consented records that the user agreed to installing the tools and + // keeping them up to date. It is set by `databricks aitools auto-install + // enable`, by a global-scope `databricks aitools install` that set an agent + // up, by a "yes" to the install prompt, by a "yes" to the skills prompt of + // `databricks apps init`, and by a run that finds a global installation + // made by the CLI other than one auto-install made without consent (see + // InstalledWithoutConsent and Installing). It is never set + // together with OptedOut (see Consent), so a CLI that knows only OptedOut + // still reads an opt-out as one. + Consented bool `json:"consented,omitempty"` + // AcceptedVersion is the CLI version whose install prompt the user // answered "yes". Retries of that version install without asking again; // any other version asks. @@ -69,6 +80,12 @@ type State struct { // Installing. InstallStateDigest string `json:"install_state_digest,omitempty"` + // InstalledWithoutConsent records that auto-install started a first + // install while the user had not answered (a coding agent's run, which + // does not ask). The install state it leaves is not the user's consent, so + // a run does not read it as one. It is cleared once the user answers. + InstalledWithoutConsent bool `json:"installed_without_consent,omitempty"` + // ID is a random per-machine identifier, created on the first run that // decides anything. Only its Bucket is used, and it never leaves the // machine. The CLI has no other stable machine identifier. @@ -133,16 +150,49 @@ func save(ctx context.Context, s State) error { return atomicfile.Write(path, append(data, '\n'), 0o600, atomicfile.MkDir(0o755)) } -// SetOptedOut turns auto-install off (true) or back on (false), keeping the -// rest of the state. A state file that cannot be read is replaced: the user's -// explicit choice matters more than a broken record. Where the state lock -// cannot be taken at all (a filesystem without locks), it writes without it: -// auto-install cannot run there, so nothing else writes the state. -func SetOptedOut(ctx context.Context, optedOut bool) error { +// Consent is the user's answer to installing Databricks AI tools and keeping +// them up to date. It is one answer per machine, for every CLI version. +type Consent int + +const ( + // ConsentUnknown is a machine whose user never answered. + ConsentUnknown Consent = iota + // ConsentGiven is a machine whose user agreed. + ConsentGiven + // ConsentOptedOut is a machine whose user refused. + ConsentOptedOut +) + +// Consent returns the stored answer. A state with both OptedOut and Consented +// set, which only a hand edit makes, is opted out. +func (s State) Consent() Consent { + switch { + case s.OptedOut: + return ConsentOptedOut + case s.Consented: + return ConsentGiven + } + return ConsentUnknown +} + +// setConsent stores c in s, clearing the other answer. +func setConsent(s *State, c Consent) { + s.OptedOut = c == ConsentOptedOut + s.Consented = c == ConsentGiven + s.InstalledWithoutConsent = false +} + +// SetConsent stores the user's answer c, keeping the rest of the state, and +// returns the answer stored before. A state file that cannot be read is +// replaced: the user's explicit choice matters more than a broken record. +// Where the state lock cannot be taken at all (a filesystem without locks), +// it writes without it: auto-install cannot run there, so nothing else writes +// the state. +func SetConsent(ctx context.Context, c Consent) (previous Consent, err error) { unlock, err := lock(ctx, stateLockFileName, stateLockWait) switch { case errors.Is(err, errLockHeld): - return err + return ConsentUnknown, err case err != nil: log.Debugf(ctx, "Saving the auto-install state without its lock: %v", err) default: @@ -153,20 +203,36 @@ func SetOptedOut(ctx context.Context, optedOut bool) error { log.Debugf(ctx, "Replacing unreadable auto-install state: %v", err) s = State{} } - s.OptedOut = optedOut - return save(ctx, s) + previous = s.Consent() + setConsent(&s, c) + return previous, save(ctx, s) +} + +// GiveConsentIfUnknown stores ConsentGiven unless the user answered already, +// and returns the answer stored before. It is for actions that count as +// consent without asking for it, such as an install, so an earlier opt-out +// stays. For the same reason it fails on a state file it cannot read, rather +// than replacing it: the file may hold an opt-out. +func GiveConsentIfUnknown(ctx context.Context) (previous Consent, err error) { + err = updateState(ctx, func(s *State) { + previous = s.Consent() + if previous == ConsentUnknown { + setConsent(s, ConsentGiven) + } + }) + return previous, err } // declined is set once the user turned the tools down in this process. var declined atomic.Bool // Decline turns auto-install off after the user turned the tools down: for -// this process at once, and for later ones through the stored opt-out. The -// error is that of storing the opt-out; this process honors the answer either -// way. -func Decline(ctx context.Context) error { +// this process at once, and for later ones through the stored opt-out. It +// returns the answer stored before. The error is that of storing the opt-out; +// this process honors the answer either way. +func Decline(ctx context.Context) (previous Consent, err error) { declined.Store(true) - return SetOptedOut(ctx, true) + return SetConsent(ctx, ConsentOptedOut) } // Declined reports whether Decline ran in this process. diff --git a/libs/aitools/autoinstall/state_test.go b/libs/aitools/autoinstall/state_test.go index f331b3634f1..ecbf1ccbcf0 100644 --- a/libs/aitools/autoinstall/state_test.go +++ b/libs/aitools/autoinstall/state_test.go @@ -1,9 +1,11 @@ package autoinstall import ( + "encoding/json" "os" "path/filepath" "testing" + "time" "github.com/databricks/cli/libs/env" "github.com/stretchr/testify/assert" @@ -53,34 +55,170 @@ func TestLoadNegativeAttemptsFails(t *testing.T) { assert.ErrorContains(t, err, "negative attempts -1") } -func TestSetOptedOutKeepsOtherFields(t *testing.T) { - ctx := env.WithUserHomeDir(t.Context(), t.TempDir()) - require.NoError(t, save(ctx, State{LastVersion: "1.2.3", Attempts: 2})) +// writeStateFile writes data as the state file of home. +func writeStateFile(t *testing.T, home, data string) { + t.Helper() + path := filepath.Join(home, ".databricks", "aitools", stateFileName) + require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o755)) + require.NoError(t, os.WriteFile(path, []byte(data), 0o600)) +} - require.NoError(t, SetOptedOut(ctx, true)) - s, err := Load(ctx) +// State files as CLI 1.27 and 1.28 write them, which know only opted_out. +func TestLoadStateOfEarlierVersions(t *testing.T) { + at := time.Date(2026, 11, 20, 10, 0, 0, 0, time.UTC) + for _, tc := range []struct { + name string + data string + want State + }{ + { + name: "1.27 opted out", + data: `{"last_version": "1.27.0", "opted_out": true, "id": "machine"}`, + want: State{LastVersion: "1.27.0", OptedOut: true, ID: "machine"}, + }, + { + name: "1.27 after a yes at the install prompt", + data: `{"last_version": "1.27.0", "accepted_version": "1.27.0", "installing": true, "id": "machine"}`, + want: State{LastVersion: "1.27.0", AcceptedVersion: "1.27.0", Installing: true, ID: "machine"}, + }, + { + name: "1.28 opted out during retries", + data: `{"last_version": "1.28.0", "attempts": 2, "last_attempt": "2026-11-20T10:00:00Z", "opted_out": true, "id": "machine"}`, + want: State{LastVersion: "1.28.0", Attempts: 2, LastAttempt: at, OptedOut: true, ID: "machine"}, + }, + } { + t.Run(tc.name, func(t *testing.T) { + home := t.TempDir() + ctx := env.WithUserHomeDir(t.Context(), home) + writeStateFile(t, home, tc.data) + + s, err := Load(ctx) + require.NoError(t, err) + assert.Equal(t, tc.want, s) + want := ConsentUnknown + if tc.want.OptedOut { + want = ConsentOptedOut + } + assert.Equal(t, want, s.Consent()) + }) + } +} + +// olderState is the state as CLI 1.28 reads it. +type olderState struct { + LastVersion string `json:"last_version,omitempty"` + Attempts int `json:"attempts,omitempty"` + LastAttempt time.Time `json:"last_attempt,omitzero"` + OptedOut bool `json:"opted_out,omitempty"` + AcceptedVersion string `json:"accepted_version,omitempty"` + Installing bool `json:"installing,omitempty"` + ID string `json:"id,omitempty"` +} + +// A CLI from before the consent was stored reads the file that this one +// writes: an opt-out is one for it too, and a consent is not. +func TestOlderCLIReadsTheConsent(t *testing.T) { + home := t.TempDir() + ctx := env.WithUserHomeDir(t.Context(), home) + path := filepath.Join(home, ".databricks", "aitools", stateFileName) + readOlder := func() olderState { + data, err := os.ReadFile(path) + require.NoError(t, err) + var s olderState + require.NoError(t, json.Unmarshal(data, &s)) + return s + } + + _, err := SetConsent(ctx, ConsentGiven) require.NoError(t, err) - assert.Equal(t, State{LastVersion: "1.2.3", Attempts: 2, OptedOut: true}, s) + assert.False(t, readOlder().OptedOut) - require.NoError(t, SetOptedOut(ctx, false)) - s, err = Load(ctx) + _, err = SetConsent(ctx, ConsentOptedOut) require.NoError(t, err) - assert.Equal(t, State{LastVersion: "1.2.3", Attempts: 2}, s) + assert.True(t, readOlder().OptedOut) +} + +func TestConsent(t *testing.T) { + assert.Equal(t, ConsentUnknown, State{}.Consent()) + assert.Equal(t, ConsentGiven, State{Consented: true}.Consent()) + assert.Equal(t, ConsentOptedOut, State{OptedOut: true}.Consent()) + assert.Equal(t, ConsentOptedOut, State{OptedOut: true, Consented: true}.Consent(), "a hand-edited file with both is opted out") } -func TestSetOptedOutReplacesCorruptFile(t *testing.T) { +func TestSetConsentKeepsOtherFields(t *testing.T) { + ctx := env.WithUserHomeDir(t.Context(), t.TempDir()) + require.NoError(t, save(ctx, State{LastVersion: "1.2.3", Attempts: 2})) + + for _, step := range []struct { + consent Consent + wantPrevious Consent + want State + }{ + {ConsentOptedOut, ConsentUnknown, State{LastVersion: "1.2.3", Attempts: 2, OptedOut: true}}, + {ConsentGiven, ConsentOptedOut, State{LastVersion: "1.2.3", Attempts: 2, Consented: true}}, + {ConsentOptedOut, ConsentGiven, State{LastVersion: "1.2.3", Attempts: 2, OptedOut: true}}, + } { + previous, err := SetConsent(ctx, step.consent) + require.NoError(t, err) + assert.Equal(t, step.wantPrevious, previous) + s, err := Load(ctx) + require.NoError(t, err) + assert.Equal(t, step.want, s) + } +} + +func TestSetConsentReplacesCorruptFile(t *testing.T) { home := t.TempDir() ctx := env.WithUserHomeDir(t.Context(), home) - path := filepath.Join(home, ".databricks", "aitools", stateFileName) - require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o755)) - require.NoError(t, os.WriteFile(path, []byte("not json"), 0o600)) + writeStateFile(t, home, "not json") - require.NoError(t, SetOptedOut(ctx, true)) + previous, err := SetConsent(ctx, ConsentOptedOut) + require.NoError(t, err) + assert.Equal(t, ConsentUnknown, previous) s, err := Load(ctx) require.NoError(t, err) assert.Equal(t, State{OptedOut: true}, s) } +func TestGiveConsentIfUnknown(t *testing.T) { + for _, tc := range []struct { + name string + state State + want State + }{ + {"unknown", State{LastVersion: "1.2.3"}, State{LastVersion: "1.2.3", Consented: true}}, + {"unknown after an install without consent", State{InstalledWithoutConsent: true}, State{Consented: true}}, + {"given", State{Consented: true}, State{Consented: true}}, + {"an opt-out stays", State{OptedOut: true}, State{OptedOut: true}}, + } { + t.Run(tc.name, func(t *testing.T) { + ctx := env.WithUserHomeDir(t.Context(), t.TempDir()) + require.NoError(t, save(ctx, tc.state)) + + previous, err := GiveConsentIfUnknown(ctx) + require.NoError(t, err) + assert.Equal(t, tc.state.Consent(), previous) + s, err := Load(ctx) + require.NoError(t, err) + assert.Equal(t, tc.want, s) + }) + } +} + +// The unreadable file may hold an opt-out, which an implied consent must not +// replace. +func TestGiveConsentIfUnknownKeepsACorruptFile(t *testing.T) { + home := t.TempDir() + ctx := env.WithUserHomeDir(t.Context(), home) + writeStateFile(t, home, "not json") + + _, err := GiveConsentIfUnknown(ctx) + assert.ErrorContains(t, err, "parse ") + data, err := os.ReadFile(filepath.Join(home, ".databricks", "aitools", stateFileName)) + require.NoError(t, err) + assert.Equal(t, "not json", string(data)) +} + func TestEnvOptedOut(t *testing.T) { ctx := t.Context() assert.False(t, EnvOptedOut(ctx), "unset")