diff --git a/.nextchanges/cli/aitools-auto-install-consent.md b/.nextchanges/cli/aitools-auto-install-consent.md new file mode 100644 index 00000000000..b8e5576b261 --- /dev/null +++ b/.nextchanges/cli/aitools-auto-install-consent.md @@ -0,0 +1 @@ +* The automatic installation of Databricks AI tools now runs only after explicit consent or when an existing CLI-managed global installation is found. Explicit consent is `databricks aitools auto-install enable`, a global `databricks aitools install`, or a "yes" to the skills prompt of `databricks apps init`. If you ran `databricks aitools auto-install enable` with an earlier CLI version and have no global installation that the CLI made, run it again: before, it only undid `disable` and did not record an agreement. With such an installation, the CLI infers the consent automatically. It no longer asks anything after a command, and its notice now also names `databricks aitools uninstall`. ([#8135](https://github.com/databricks/cli/pull/8135)) diff --git a/acceptance/cmd/aitools/auto-install/agent-hint/output.txt b/acceptance/cmd/aitools/auto-install/agent-hint/output.txt index 62ec35240df..8d172071688 100644 --- a/acceptance/cmd/aitools/auto-install/agent-hint/output.txt +++ b/acceptance/cmd/aitools/auto-install/agent-hint/output.txt @@ -1,4 +1,7 @@ +>>> [CLI] aitools auto-install enable +Automatic installation of Databricks AI tools is enabled. + === a failing command: no install, the hint once the command ends >>> CLAUDECODE=1 [CLI] jobs get abc @@ -13,7 +16,7 @@ Exit code: 1 === first run of a new version: the install notice, no install hint >>> CLAUDECODE=1 [CLI] jobs list -Installed Databricks AI tools for Claude Code, Cursor. Disable: databricks aitools auto-install disable +Installed Databricks AI tools for Claude Code, Cursor. Turn off: databricks aitools auto-install disable. Remove: databricks aitools uninstall >>> print_telemetry {"command":"jobs_list","exit_code":0,"aitools_install_event":{"agents":["CLAUDE_CODE","CURSOR"],"scope":"GLOBAL","error_category":"TYPE_UNSPECIFIED","agent_results":[{"agent":"CLAUDE_CODE","error_category":"CLI_NOT_ON_PATH"}],"trigger":"AUTO_FIRST_RUN"}} @@ -27,6 +30,9 @@ Installed Databricks AI tools for Claude Code, Cursor. Disable: databricks aitoo === gate off: no install, the hint once the command ends, and on the next +>>> [CLI] aitools auto-install enable +Automatic installation of Databricks AI tools is enabled. + >>> CLAUDECODE=1 [CLI] jobs list Databricks skills are not installed. To work with Databricks reliably, first run: databricks aitools install @@ -41,9 +47,12 @@ Databricks skills are not installed. To work with Databricks reliably, first run === an agent the install skips is still hinted: Claude Code has no config dir +>>> [CLI] aitools auto-install enable +Automatic installation of Databricks AI tools is enabled. + >>> CLAUDECODE=1 [CLI] jobs list Databricks skills are not installed. To work with Databricks reliably, first run: databricks aitools install -Installed Databricks AI tools for Cursor. Disable: databricks aitools auto-install disable +Installed Databricks AI tools for Cursor. Turn off: databricks aitools auto-install disable. Remove: databricks aitools uninstall >>> print_telemetry {"command":"jobs_list","exit_code":0,"aitools_hint_event":{"hint_kind":"INSTALL_TEXT"}} diff --git a/acceptance/cmd/aitools/auto-install/agent-hint/script b/acceptance/cmd/aitools/auto-install/agent-hint/script index 080d464f2aa..e1d3dc009bc 100644 --- a/acceptance/cmd/aitools/auto-install/agent-hint/script +++ b/acceptance/cmd/aitools/auto-install/agent-hint/script @@ -1,10 +1,12 @@ -# Claude Code calls the CLI: its config dir exists and its CLI is not on PATH, -# so auto-install gives it skill files. The install hint must not tell it to -# install what the same run installs. -unset AGENT CLAUDE_CODE_SESSION_ID CLAUDE_CODE_CHILD_SESSION +# Claude Code calls the CLI on a machine whose user agreed to auto-install: +# its config dir exists and its CLI is not on PATH, so auto-install gives it +# skill files. The install hint must not tell it to install what the same run +# installs. Without the consent, see no-consent. +unset CLAUDE_CODE_SESSION_ID CLAUDE_CODE_CHILD_SESSION use_home home "$mkdir_bin" -p "${USERPROFILE:-$HOME}/.claude" gate true +trace $CLI aitools auto-install enable title "a failing command: no install, the hint once the command ends" errcode trace CLAUDECODE=1 $CLI jobs get abc @@ -22,6 +24,7 @@ title "gate off: no install, the hint once the command ends, and on the next" use_home no-agents-home "$mkdir_bin" -p "${USERPROFILE:-$HOME}/.claude" gate false +trace $CLI aitools auto-install enable trace CLAUDECODE=1 $CLI jobs list trace print_telemetry trace CLAUDECODE=1 $CLI jobs list @@ -30,5 +33,6 @@ trace print_telemetry title "an agent the install skips is still hinted: Claude Code has no config dir" use_home holdout-home gate true +trace $CLI aitools auto-install enable trace CLAUDECODE=1 $CLI jobs list trace print_telemetry diff --git a/acceptance/cmd/aitools/auto-install/first-run/output.txt b/acceptance/cmd/aitools/auto-install/first-run/output.txt index e1ad16612b3..edd6d1b00c9 100644 --- a/acceptance/cmd/aitools/auto-install/first-run/output.txt +++ b/acceptance/cmd/aitools/auto-install/first-run/output.txt @@ -1,8 +1,11 @@ +>>> [CLI] aitools auto-install enable +Automatic installation of Databricks AI tools is enabled. + === first run of a new version: installs for the detected agents, one stderr line >>> [CLI] jobs list -Installed Databricks AI tools for Claude Code, Cursor. Disable: databricks aitools auto-install disable +Installed Databricks AI tools for Claude Code, Cursor. Turn off: databricks aitools auto-install disable. Remove: databricks aitools uninstall >>> print_telemetry {"command":"jobs_list","exit_code":0,"aitools_install_event":{"agents":["CLAUDE_CODE","CURSOR"],"scope":"GLOBAL","error_category":"TYPE_UNSPECIFIED","agent_results":[{"agent":"CLAUDE_CODE","error_category":"CLI_NOT_ON_PATH"}],"trigger":"AUTO_FIRST_RUN"}} @@ -14,7 +17,7 @@ databricks-test >>> auto_install_state { "last_version": "1.30.0", - "installed_without_consent": true, + "consented": true, "id": "treatment-machine" } @@ -44,7 +47,6 @@ Uninstalled 1 skill. >>> [CLI] jobs list >>> auto_install_outcome -KEPT >>> cursor_skills databricks-test @@ -57,19 +59,16 @@ SKILL.md my own skill >>> settled_version -{"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 >>> [CLI] jobs list -Installed Databricks AI tools for Cursor. Disable: databricks aitools auto-install disable >>> auto_install_outcome -INSTALLED >>> cursor_skills databricks-team-conventions -databricks-test >>> cat [TEST_TMP_DIR]/own-skill-home/.cursor/skills/databricks-team-conventions/SKILL.md my own skill diff --git a/acceptance/cmd/aitools/auto-install/first-run/script b/acceptance/cmd/aitools/auto-install/first-run/script index 6b20cad2807..4f4489b894a 100644 --- a/acceptance/cmd/aitools/auto-install/first-run/script +++ b/acceptance/cmd/aitools/auto-install/first-run/script @@ -3,6 +3,7 @@ use_home home # install), so it gets skill files, as `aitools install` gives it. "$mkdir_bin" -p "${USERPROFILE:-$HOME}/.claude" gate true +trace $CLI aitools auto-install enable title "first run of a new version: installs for the detected agents, one stderr line" trace $CLI jobs list diff --git a/acceptance/cmd/aitools/auto-install/no-consent/out.test.toml b/acceptance/cmd/aitools/auto-install/no-consent/out.test.toml new file mode 100644 index 00000000000..18b1a88417e --- /dev/null +++ b/acceptance/cmd/aitools/auto-install/no-consent/out.test.toml @@ -0,0 +1 @@ +Cloud = false diff --git a/acceptance/cmd/aitools/auto-install/no-consent/output.txt b/acceptance/cmd/aitools/auto-install/no-consent/output.txt new file mode 100644 index 00000000000..8a3b21b20c7 --- /dev/null +++ b/acceptance/cmd/aitools/auto-install/no-consent/output.txt @@ -0,0 +1,36 @@ + +=== the user never answered: nothing installed, written or reported, the gate is not looked up, and the agent gets the install hint + +>>> CLAUDECODE=1 [CLI] jobs list --log-file LOG.no-consent --log-level debug +Databricks skills are not installed. To work with Databricks reliably, first run: databricks aitools install + +>>> print_telemetry +{"command":"jobs_list","exit_code":0,"aitools_hint_event":{"hint_kind":"INSTALL_TEXT"}} + +>>> cursor_skills +(no skills) + +>>> auto_install_state +{"id": "treatment-machine"} + +=== the user agrees: the next command of the same version installs + +>>> [CLI] aitools auto-install enable +Automatic installation of Databricks AI tools is enabled. + +>>> CLAUDECODE=1 [CLI] jobs list --log-file LOG.consent --log-level debug +Installed Databricks AI tools for Claude Code, Cursor. Turn off: databricks aitools auto-install disable. Remove: databricks aitools uninstall + +>>> print_telemetry +{"command":"jobs_list","exit_code":0,"aitools_install_event":{"agents":["CLAUDE_CODE","CURSOR"],"scope":"GLOBAL","error_category":"TYPE_UNSPECIFIED","agent_results":[{"agent":"CLAUDE_CODE","error_category":"CLI_NOT_ON_PATH"}],"trigger":"AUTO_FIRST_RUN"}} +{"command":"jobs_list","exit_code":0,"aitools_auto_install_event":{"outcome":"INSTALLED","holdout_arm":"TREATMENT","interactive":false}} + +>>> cursor_skills +databricks-test + +>>> auto_install_state +{ + "last_version": "1.30.0", + "consented": true, + "id": "treatment-machine" +} diff --git a/acceptance/cmd/aitools/auto-install/no-consent/script b/acceptance/cmd/aitools/auto-install/no-consent/script new file mode 100644 index 00000000000..cefbca7e413 --- /dev/null +++ b/acceptance/cmd/aitools/auto-install/no-consent/script @@ -0,0 +1,24 @@ +# Claude Code calls the CLI on a machine whose user never agreed to +# auto-install. Its config dir exists and its CLI is not on PATH, so an install +# would give it skill files. +unset CLAUDE_CODE_SESSION_ID CLAUDE_CODE_CHILD_SESSION +use_home home +"$mkdir_bin" -p "${USERPROFILE:-$HOME}/.claude" +# use_home wrote the state file by hand: a write by the CLI would indent it. +gate true + +title "the user never answered: nothing installed, written or reported, the gate is not looked up, and the agent gets the install hint" +trace CLAUDECODE=1 $CLI jobs list --log-file LOG.no-consent --log-level debug +# The gate lookup would read the compatibility manifest from the cache. +contains.py "auto-install: skipped: no_consent" "!Using cached manifest" < LOG.no-consent > LOG.no-consent-checked +trace print_telemetry +trace cursor_skills +trace auto_install_state + +title "the user agrees: the next command of the same version installs" +trace $CLI aitools auto-install enable +trace CLAUDECODE=1 $CLI jobs list --log-file LOG.consent --log-level debug +contains.py "Using cached manifest" < LOG.consent > LOG.consent-checked +trace print_telemetry +trace cursor_skills +trace auto_install_state diff --git a/acceptance/cmd/aitools/auto-install/no-terminal/output.txt b/acceptance/cmd/aitools/auto-install/no-terminal/output.txt index 943fbd74005..bc309105479 100644 --- a/acceptance/cmd/aitools/auto-install/no-terminal/output.txt +++ b/acceptance/cmd/aitools/auto-install/no-terminal/output.txt @@ -1,31 +1,36 @@ -=== no terminal and no coding agent: cannot ask, so nothing is installed or reported, and the version is not settled +>>> [CLI] aitools auto-install enable +Automatic installation of Databricks AI tools is enabled. + +=== no terminal and no coding agent: installs without asking >>> [CLI] jobs list +Installed Databricks AI tools for Cursor. Turn off: databricks aitools auto-install disable. Remove: databricks aitools uninstall >>> print_telemetry +{"command":"jobs_list","exit_code":0,"aitools_install_event":{"agents":["CURSOR"],"scope":"GLOBAL","error_category":"TYPE_UNSPECIFIED","trigger":"AUTO_FIRST_RUN"}} +{"command":"jobs_list","exit_code":0,"aitools_auto_install_event":{"outcome":"INSTALLED","holdout_arm":"TREATMENT","interactive":false}} >>> cursor_skills -(no skills) +databricks-test >>> auto_install_state -{"id": "treatment-machine"} +{ + "last_version": "1.30.0", + "consented": true, + "id": "treatment-machine" +} -=== the version is still due: a coding agent's call installs without asking +=== a coding agent's call on the next version: the update runs without asking ->>> AGENT=test-agent [CLI] jobs list -Installed Databricks AI tools for Cursor. Disable: databricks aitools auto-install disable +>>> AGENT=test-agent DATABRICKS_AITOOLS_AUTO_INSTALL_CLI_VERSION=1.31.0 [CLI] jobs list >>> print_telemetry -{"command":"jobs_list","exit_code":0,"aitools_install_event":{"agents":["CURSOR"],"scope":"GLOBAL","error_category":"TYPE_UNSPECIFIED","trigger":"AUTO_FIRST_RUN"}} -{"command":"jobs_list","exit_code":0,"aitools_auto_install_event":{"outcome":"INSTALLED","holdout_arm":"TREATMENT","interactive":false}} - ->>> cursor_skills -databricks-test +{"command":"jobs_list","exit_code":0,"aitools_auto_install_event":{"outcome":"UP_TO_DATE","holdout_arm":"TREATMENT","interactive":false}} >>> auto_install_state { - "last_version": "1.30.0", - "installed_without_consent": true, + "last_version": "1.31.0", + "consented": true, "id": "treatment-machine" } diff --git a/acceptance/cmd/aitools/auto-install/no-terminal/script b/acceptance/cmd/aitools/auto-install/no-terminal/script index ad88eec46e6..4454e095b04 100644 --- a/acceptance/cmd/aitools/auto-install/no-terminal/script +++ b/acceptance/cmd/aitools/auto-install/no-terminal/script @@ -1,15 +1,14 @@ use_home home gate true -unset AGENT +trace $CLI aitools auto-install enable -title "no terminal and no coding agent: cannot ask, so nothing is installed or reported, and the version is not settled" +title "no terminal and no coding agent: installs without asking" trace $CLI jobs list trace print_telemetry trace cursor_skills trace auto_install_state -title "the version is still due: a coding agent's call installs without asking" -trace AGENT=test-agent $CLI jobs list +title "a coding agent's call on the next version: the update runs without asking" +trace AGENT=test-agent DATABRICKS_AITOOLS_AUTO_INSTALL_CLI_VERSION=1.31.0 $CLI jobs list trace print_telemetry -trace cursor_skills trace auto_install_state diff --git a/acceptance/cmd/aitools/auto-install/retries/output.txt b/acceptance/cmd/aitools/auto-install/retries/output.txt index 17072cd7d67..9b8c411a39e 100644 --- a/acceptance/cmd/aitools/auto-install/retries/output.txt +++ b/acceptance/cmd/aitools/auto-install/retries/output.txt @@ -1,4 +1,7 @@ +>>> [CLI] aitools auto-install enable +Automatic installation of Databricks AI tools is enabled. + === a failed attempt is silent, and the commands right after it do not retry >>> print_telemetry @@ -14,8 +17,8 @@ "last_version": "1.30.0", "attempts": 1, "last_attempt": "[LAST_ATTEMPT]", + "consented": true, "installing": true, - "installed_without_consent": true, "id": "treatment-machine" } @@ -43,7 +46,7 @@ === a new version starts over >>> DATABRICKS_AITOOLS_AUTO_INSTALL_CLI_VERSION=1.31.0 [CLI] jobs list -Installed Databricks AI tools for Cursor. Disable: databricks aitools auto-install disable +Installed Databricks AI tools for Cursor. Turn off: databricks aitools auto-install disable. Remove: databricks aitools uninstall >>> print_telemetry {"command":"jobs_list","exit_code":0,"aitools_install_event":{"agents":["CURSOR"],"scope":"GLOBAL","error_category":"TYPE_UNSPECIFIED","trigger":"AUTO_FIRST_RUN"}} @@ -52,6 +55,6 @@ Installed Databricks AI tools for Cursor. Disable: databricks aitools auto-insta >>> auto_install_state { "last_version": "1.31.0", - "installed_without_consent": true, + "consented": true, "id": "treatment-machine" } diff --git a/acceptance/cmd/aitools/auto-install/retries/script b/acceptance/cmd/aitools/auto-install/retries/script index 7bb120dccfd..2be5466bf1d 100644 --- a/acceptance/cmd/aitools/auto-install/retries/script +++ b/acceptance/cmd/aitools/auto-install/retries/script @@ -1,5 +1,6 @@ use_home home gate true +trace $CLI aitools auto-install enable # end_retry_wait moves the last failed attempt back in time, as if the wait # before the next attempt were over. diff --git a/acceptance/cmd/aitools/auto-install/script.prepare b/acceptance/cmd/aitools/auto-install/script.prepare index ebc99b77818..82351999e10 100644 --- a/acceptance/cmd/aitools/auto-install/script.prepare +++ b/acceptance/cmd/aitools/auto-install/script.prepare @@ -10,12 +10,6 @@ unset CI DATABRICKS_AITOOLS_AUTO_INSTALL GITHUB_ACTIONS GITLAB_CI JENKINS_URL TF # Telemetry is printed by print_telemetry. unset DATABRICKS_CLI_DISABLE_TELEMETRY DATABRICKS_CLI_TELEMETRY_TIMEOUT -# Without a terminal, only a coding agent's call installs: any other run cannot -# ask first, so it skips (see no-terminal). The cases have no terminal, so they -# run as a coding agent's call. AGENT is the generic marker; this name gets no -# agent hint. -export AGENT=test-agent - # Test binaries are development builds, which never auto-install. Each case # names the released version it simulates. export DATABRICKS_AITOOLS_AUTO_INSTALL_CLI_VERSION=1.30.0 @@ -28,7 +22,7 @@ ls_bin=$(command -v ls) # use_home HOME [ID] isolates HOME with Cursor's config dir present, and stores # the machine id ID (default: treatment-machine, whose holdout bucket is in the # treatment arm; holdout-machine is in the holdout), so the arm does not -# depend on a random id. +# depend on a random id. The user has not agreed to auto-install yet. # # Auto-install acts only on agents whose config directory exists, and installs # plugins through agent CLIs found on PATH. Keep both inside the test: point diff --git a/acceptance/cmd/aitools/auto-install/skipped/output.txt b/acceptance/cmd/aitools/auto-install/skipped/output.txt index 1fa240f0124..a137b27cb64 100644 --- a/acceptance/cmd/aitools/auto-install/skipped/output.txt +++ b/acceptance/cmd/aitools/auto-install/skipped/output.txt @@ -36,6 +36,20 @@ Automatic installation of Databricks AI tools is disabled. >>> [CLI] aitools auto-install enable Automatic installation of Databricks AI tools is enabled. +=== DATABRICKS_AITOOLS_AUTO_INSTALL=false wins over the consent + +>>> DATABRICKS_AITOOLS_AUTO_INSTALL=false [CLI] jobs list + +>>> print_telemetry +{"command":"jobs_list","exit_code":0,"aitools_auto_install_event":{"outcome":"SKIPPED_OPTOUT","holdout_arm":"TREATMENT","interactive":false}} + +>>> auto_install_state +{ + "last_version": "1.32.1", + "consented": true, + "id": "treatment-machine" +} + === commands that never trigger it >>> [CLI] version @@ -52,7 +66,7 @@ Automatic installation of Databricks AI tools is enabled. >>> auto_install_state { - "last_version": "1.32.0", + "last_version": "1.32.1", "consented": true, "id": "treatment-machine" } @@ -82,6 +96,9 @@ Automatic installation of Databricks AI tools is enabled. === a machine in the holdout: not installed +>>> [CLI] aitools auto-install enable +Automatic installation of Databricks AI tools is enabled. + >>> [CLI] jobs list >>> print_telemetry @@ -92,6 +109,9 @@ Automatic installation of Databricks AI tools is enabled. === no agent config directory: nothing to install +>>> [CLI] aitools auto-install enable +Automatic installation of Databricks AI tools is enabled. + >>> [CLI] jobs list >>> print_telemetry diff --git a/acceptance/cmd/aitools/auto-install/skipped/script b/acceptance/cmd/aitools/auto-install/skipped/script index e4b76797c0c..bcf1d64dc2a 100644 --- a/acceptance/cmd/aitools/auto-install/skipped/script +++ b/acceptance/cmd/aitools/auto-install/skipped/script @@ -1,6 +1,8 @@ use_home home gate true +# CI and the opt-outs settle the version and are reported whether or not the +# user agreed: these first cases run before the user answered. title "CI: not installed, reported once for the version" trace CI=true $CLI jobs list trace print_telemetry @@ -21,6 +23,12 @@ trace print_telemetry trace cursor_skills trace $CLI aitools auto-install enable +export DATABRICKS_AITOOLS_AUTO_INSTALL_CLI_VERSION=1.32.1 +title "DATABRICKS_AITOOLS_AUTO_INSTALL=false wins over the consent" +trace DATABRICKS_AITOOLS_AUTO_INSTALL=false $CLI jobs list +trace print_telemetry +trace auto_install_state + export DATABRICKS_AITOOLS_AUTO_INSTALL_CLI_VERSION=1.33.0 title "commands that never trigger it" trace $CLI version @@ -47,6 +55,7 @@ trace cursor_skills title "a machine in the holdout: not installed" use_home holdout-home holdout-machine +trace $CLI aitools auto-install enable trace $CLI jobs list trace print_telemetry trace cursor_skills @@ -54,5 +63,6 @@ trace cursor_skills title "no agent config directory: nothing to install" use_home no-agents-home "$rm_bin" -r "${USERPROFILE:-$HOME}/.cursor" +trace $CLI aitools auto-install enable trace $CLI jobs list trace print_telemetry diff --git a/acceptance/cmd/aitools/auto-install/upgrade/output.txt b/acceptance/cmd/aitools/auto-install/upgrade/output.txt index 82dcc6685ac..97512d43cf7 100644 --- a/acceptance/cmd/aitools/auto-install/upgrade/output.txt +++ b/acceptance/cmd/aitools/auto-install/upgrade/output.txt @@ -1,8 +1,11 @@ +>>> [CLI] aitools auto-install enable +Automatic installation of Databricks AI tools is enabled. + === first run of 1.30.0 installs skills release 0.3.0 >>> [CLI] jobs list -Installed Databricks AI tools for Cursor. Disable: databricks aitools auto-install disable +Installed Databricks AI tools for Cursor. Turn off: databricks aitools auto-install disable. Remove: databricks aitools uninstall >>> print_telemetry {"command":"jobs_list","exit_code":0,"aitools_install_event":{"agents":["CURSOR"],"scope":"GLOBAL","error_category":"TYPE_UNSPECIFIED","trigger":"AUTO_FIRST_RUN"}} @@ -16,14 +19,14 @@ databricks-kept >>> auto_install_state { "last_version": "1.30.0", - "installed_without_consent": true, + "consented": 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 -Updated Databricks AI tools for Cursor. Disable: databricks aitools auto-install disable +Updated Databricks AI tools for Cursor. Turn off: databricks aitools auto-install disable. Remove: databricks aitools uninstall >>> print_telemetry {"command":"jobs_list","exit_code":0,"aitools_auto_install_event":{"outcome":"INSTALLED","holdout_arm":"TREATMENT","interactive":false}} @@ -47,7 +50,7 @@ my notes >>> auto_install_state { "last_version": "1.31.0", - "installed_without_consent": true, + "consented": true, "id": "treatment-machine" } @@ -64,7 +67,7 @@ kept 2.0.0 >>> auto_install_state { "last_version": "1.32.0", - "installed_without_consent": true, + "consented": true, "id": "treatment-machine" } @@ -77,7 +80,7 @@ kept 2.0.0 >>> auto_install_state { "last_version": "1.32.0", - "installed_without_consent": true, + "consented": true, "id": "treatment-machine" } @@ -107,3 +110,28 @@ kept 2.0.0 "consented": true, "id": "treatment-machine" } + +>>> [CLI] aitools install --skills-only --scope=global --agents=cursor +Installing Databricks skills for Cursor... +Using skills version 0.3.0 +Fetching skills manifest... +Installed 3 skills in [TEST_TMP_DIR]/existing-home/.databricks/aitools/skills. + +=== upgrade to 1.31.0 over an installation of a machine whose user never answered: updated, and the installation counts as the consent + +>>> DATABRICKS_AITOOLS_AUTO_INSTALL_CLI_VERSION=1.31.0 DATABRICKS_CLI_GITHUB_API_URL=[DATABRICKS_URL]/newer [CLI] jobs list +Updated Databricks AI tools for Cursor. Turn off: databricks aitools auto-install disable. Remove: databricks aitools uninstall + +>>> print_telemetry +{"command":"jobs_list","exit_code":0,"aitools_auto_install_event":{"outcome":"INSTALLED","holdout_arm":"TREATMENT","interactive":false}} + +>>> cursor_skills +databricks-edited +databricks-kept + +>>> auto_install_state +{ + "last_version": "1.31.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 10ed0719170..2f4a7bf00be 100644 --- a/acceptance/cmd/aitools/auto-install/upgrade/script +++ b/acceptance/cmd/aitools/auto-install/upgrade/script @@ -2,6 +2,7 @@ use_home home # Track the latest skills release, as the compatibility manifest does. unset DATABRICKS_SKILLS_REF gate true +trace $CLI aitools auto-install enable skills_dir="${USERPROFILE:-$HOME}/.databricks/aitools/skills" skill_file() { cat "$skills_dir/$1/SKILL.md" @@ -17,8 +18,6 @@ trace auto_install_state echo "my notes" >> "$skills_dir/databricks-dropped/SKILL.md" echo "my notes" >> "$skills_dir/databricks-edited/SKILL.md" -# An update does not ask, so it runs with no terminal and no coding agent too. -unset AGENT title "upgrade to 1.31.0 with release 0.4.0: updates like aitools update, keeping the edited skills" trace DATABRICKS_AITOOLS_AUTO_INSTALL_CLI_VERSION=1.31.0 DATABRICKS_CLI_GITHUB_API_URL=$DATABRICKS_HOST/newer $CLI jobs list trace print_telemetry @@ -26,8 +25,6 @@ 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" @@ -55,3 +52,17 @@ trace print_telemetry trace cursor_skills trace skill_file databricks-kept trace auto_install_state + +# A global installation that the CLI made before it stored the consent: the +# state of such a CLI has none. +use_home existing-home +trace $CLI aitools install --skills-only --scope=global --agents=cursor +print_telemetry > LOG.telemetry-existing-home +echo '{"id": "treatment-machine", "last_version": "1.30.0"}' > "${USERPROFILE:-$HOME}/.databricks/aitools/auto-install.json" +gate true + +title "upgrade to 1.31.0 over an installation of a machine whose user never answered: updated, and the installation counts as the consent" +trace DATABRICKS_AITOOLS_AUTO_INSTALL_CLI_VERSION=1.31.0 DATABRICKS_CLI_GITHUB_API_URL=$DATABRICKS_HOST/newer $CLI jobs list +trace print_telemetry +trace cursor_skills +trace auto_install_state diff --git a/acceptance/cmd/aitools/auto-install/upgrade/test.toml b/acceptance/cmd/aitools/auto-install/upgrade/test.toml index cd0ef11212d..b266d3f1f19 100644 --- a/acceptance/cmd/aitools/auto-install/upgrade/test.toml +++ b/acceptance/cmd/aitools/auto-install/upgrade/test.toml @@ -1,4 +1,4 @@ -Ignore = ["pinned-home"] +Ignore = ["pinned-home", "existing-home"] # Skills releases: the latest release is v0.3.0, under /newer it is v0.4.0 and # under /older it is v0.2.0 (DATABRICKS_CLI_GITHUB_API_URL picks one). diff --git a/cmd/aitools/autoinstall.go b/cmd/aitools/autoinstall.go index e9b2067ff77..647496ca7e5 100644 --- a/cmd/aitools/autoinstall.go +++ b/cmd/aitools/autoinstall.go @@ -20,14 +20,17 @@ On the first run of a new CLI version, the CLI can install the Databricks AI tools (skills and plugins) for the coding agents already on this machine, as 'databricks aitools install --scope=global' does, or update an existing installation, as 'databricks aitools update' does. It never runs in CI or on -Databricks Runtime, and only touches the global scope. In a terminal it asks -before the first install. +Databricks Runtime, only touches the global scope, and asks nothing. +It runs only once the user agreed to it with 'databricks aitools auto-install +enable', a global-scope 'databricks aitools install' or a "yes" to the skills +prompt of 'databricks apps init', or when it finds a global installation that +the CLI made. It stays off after 'databricks aitools auto-install disable', a global-scope -'databricks aitools uninstall', a "no" at that prompt, or a "no" to the skills -prompt of 'databricks apps init', until 'databricks aitools auto-install enable'. -Setting ` + autoinstall.EnvVar + ` to anything but a true value (true, 1, yes, -on) turns it off in that environment.`, +'databricks aitools uninstall', or a "no" to the skills prompt of 'databricks +apps init', until 'databricks aitools auto-install enable'. Setting +` + autoinstall.EnvVar + ` to anything but a true value (true, 1, yes, on) turns +it off in that environment.`, RunE: root.ReportUnknownSubcommand, } cmd.AddCommand(newAutoInstallToggleCmd(true)) @@ -39,7 +42,7 @@ on) turns it off in that environment.`, func newAutoInstallToggleCmd(enable bool) *cobra.Command { use, short := "disable", "Turn off the automatic installation of Databricks AI tools" if enable { - use, short = "enable", "Turn the automatic installation of Databricks AI tools back on" + use, short = "enable", "Turn on the automatic installation of Databricks AI tools" } return &cobra.Command{ Use: use, diff --git a/cmd/aitools/autoinstall_hint.go b/cmd/aitools/autoinstall_hint.go index 8c67da9ebc2..32c6a7709e0 100644 --- a/cmd/aitools/autoinstall_hint.go +++ b/cmd/aitools/autoinstall_hint.go @@ -12,11 +12,14 @@ import ( // agent agentName tools (see autoinstall.InstallsFor). It decides as // autoInstall does up to the gate lookup, which it skips: a run that would // look the gate up counts as installing, so on a version whose gate is off the -// install hint moves to the end of the command. A machine whose stored ID puts -// it in the holdout never installs. A first install gives tools to the agents -// its plan names; an update gives skills to every agent with a config -// directory when a skill changed, which is only known after the manifest is -// fetched, so it counts as installing for each of them. +// install hint moves to the end of the command. A machine whose user never +// agreed installs nothing, unless the run counts its global installation as +// the consent; that run stores the consent, and this check only reads. A +// machine whose stored ID puts it in the holdout never installs. A first +// install gives tools to the agents its plan names; an update gives skills to +// every agent with a config directory when a skill changed, which is only +// known after the manifest is fetched, so it counts as installing for each of +// them. func AutoInstallsFor(cmd *cobra.Command, agentName string) bool { ctx := cmd.Context() in := autoInstallInputs(ctx, skipsAutoInstall(cmd)) @@ -25,7 +28,13 @@ func AutoInstallsFor(cmd *cobra.Command, agentName string) bool { } var err error in.State, err = autoinstall.Load(ctx) - if err != nil || autoinstall.Decide(in) != autoinstall.ReasonGateOff { + if err != nil { + return false + } + if existingInstallConsents(ctx, in) { + in.State.Consented = true + } + if autoinstall.Decide(in) != autoinstall.ReasonGateOff { return false } if in.State.ID != "" && autoinstall.InHoldout(autoinstall.Bucket(in.State.ID)) { diff --git a/cmd/aitools/autoinstall_hint_test.go b/cmd/aitools/autoinstall_hint_test.go index 369d633415a..898dee9a1cb 100644 --- a/cmd/aitools/autoinstall_hint_test.go +++ b/cmd/aitools/autoinstall_hint_test.go @@ -32,8 +32,11 @@ func TestAutoInstallsFor(t *testing.T) { want bool }{ {name: "first run of a version installs for a detected agent", want: true}, - {name: "a retry installs too", state: `{"id": "treatment-machine", "last_version": "1.30.0", "attempts": 2}`, want: true}, - {name: "a fresh machine with no state installs", state: "{}", want: true}, + {name: "a retry installs too", state: `{"id": "treatment-machine", "consented": true, "last_version": "1.30.0", "attempts": 2}`, want: true}, + {name: "a machine that agreed with no ID yet installs", state: `{"consented": true}`, want: true}, + {name: "a machine whose user never answered installs nothing", state: `{"id": "treatment-machine"}`}, + {name: "a fresh machine with no state installs nothing", state: "{}"}, + {name: "a retry of a machine whose user never answered installs nothing", state: `{"id": "treatment-machine", "last_version": "1.30.0", "attempts": 2}`}, {name: "an agent without a config dir is not installed for", agent: agents.NameClaudeCode}, {name: "a settled version installs nothing", state: `{"id": "treatment-machine", "last_version": "1.30.0"}`}, {name: "a version whose retries ran out installs nothing", state: `{"id": "treatment-machine", "last_version": "1.30.0", "attempts": 10}`}, @@ -43,9 +46,13 @@ func TestAutoInstallsFor(t *testing.T) { {name: "a development build installs nothing", env: map[string]string{"DATABRICKS_AITOOLS_AUTO_INSTALL_CLI_VERSION": ""}}, {name: "a command that skips auto-install installs nothing", command: "aitools list"}, {name: "a failed plan installs nothing", installState: "not json"}, - {name: "a holdout machine installs nothing", state: `{"id": "holdout-machine"}`}, + {name: "a holdout machine installs nothing", state: `{"id": "holdout-machine", "consented": true}`}, {name: "an update may install for an agent with a config dir", installState: globalInstallState, want: true}, {name: "an update installs nothing for an agent without a config dir", installState: globalInstallState, agent: agents.NameClaudeCode}, + // The run counts the installation as the consent and stores it. + {name: "an update of a machine whose user never answered may install", state: `{"id": "treatment-machine"}`, installState: globalInstallState, want: true}, + {name: "an installation is no consent in CI", state: `{"id": "treatment-machine"}`, installState: globalInstallState, env: map[string]string{"CI": "true"}}, + {name: "an installation does not replace an opt-out", state: `{"id": "treatment-machine", "opted_out": true}`, installState: globalInstallState}, } for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { diff --git a/cmd/aitools/autoinstall_run.go b/cmd/aitools/autoinstall_run.go index 4f3d2919731..a71a0c7a1d5 100644 --- a/cmd/aitools/autoinstall_run.go +++ b/cmd/aitools/autoinstall_run.go @@ -33,15 +33,10 @@ import ( "github.com/spf13/cobra" ) -const ( - // installTimeout bounds the install or update (its downloads and the - // agent CLIs it runs). One that runs out of time counts as a failed - // attempt and is retried on a later run. - installTimeout = 10 * time.Second - - // promptTimeout bounds the wait for an answer at the install prompt. - promptTimeout = time.Minute -) +// installTimeout bounds the install or update (its downloads and the agent +// CLIs it runs). One that runs out of time counts as a failed attempt and is +// retried on a later run. +const installTimeout = 10 * time.Second // gateTimeout bounds the gate lookup, one compatibility manifest fetch. Every // machine pays it once per version while the gate is off, and a machine that @@ -59,9 +54,6 @@ var now = time.Now // rootInUserHome is autoinstall.RootInUserHome; tests replace it. var rootInUserHome = autoinstall.RootInUserHome -// inContainer is autoinstall.InContainer; tests replace it. -var inContainer = autoinstall.InContainer - // notifyInterrupt catches sigs: it returns a context that is canceled when // the CLI receives one of them, and a function that stops catching them and // returns the signal received, or nil. Tests replace it. @@ -99,21 +91,22 @@ var notifyInterrupt = func(ctx context.Context, sigs ...os.Signal) (context.Cont // errInterrupted is why a run stopped when it caught a signal. var errInterrupted = errors.New("interrupted") -// autoInstallDisable is the opt-out command named in the notice. -const autoInstallDisable = "databricks aitools auto-install disable" +// autoInstallNoticeCommands is the end of the notice: how to turn auto-install +// off and how to remove what it installed. +const autoInstallNoticeCommands = "Turn off: databricks aitools auto-install disable. Remove: databricks aitools uninstall" // AutoInstall installs Databricks AI tools for the coding agents on this // machine, or updates an existing installation, on the first run of a new CLI -// version. The root command runs it after a command succeeded. It never fails -// the command and never writes to stdout. On stderr it prints the install -// prompt (in a terminal) and one line on what it did; why it skipped or failed -// goes only to the debug log. +// version, once the user agreed to it (see autoinstall.Consent). It asks +// nothing. The root command runs it after a command succeeded. It never fails +// the command and never writes to stdout. On stderr it prints one line on what +// it did; why it skipped or failed goes only to the debug log. // -// It returns the signal that stopped it, if one did: Ctrl+C at the question, -// or Ctrl+C, a request to terminate or the terminal closing during the gate -// lookup. It records what it must first. The root command then ends the CLI -// by the signal, so that the shell stops the script, loop or command list -// that ran the command, as it would have without auto-install. +// It returns the signal that stopped it, if one did: Ctrl+C, a request to +// terminate or the terminal closing during the gate lookup. It records what it +// must first. The root command then ends the CLI by the signal, so that the +// shell stops the script, loop or command list that ran the command, as it +// would have without auto-install. func AutoInstall(cmd *cobra.Command) os.Signal { ctx := cmd.Context() defer func() { @@ -186,27 +179,17 @@ func autoInstall(ctx context.Context, skippedCommand bool) os.Signal { log.Debugf(ctx, "auto-install: skipped: %s", reason) return nil } - // A run that would ask before installing but cannot skips before the lock - // and the gate lookup, since it repeats on every such run until a run that - // can ask. A holdout machine or a gate-off version would otherwise settle - // after the lookup; they wait for that run too, so holdout and treatment - // machines are counted alike. - // - // A machine with no coding agent skips there as well: the gate changes - // nothing for it, and such machines (containers, job pods) often have no - // route to the manifest and a home directory that keeps no state, so they - // would wait for the lookup on every run. The version is not settled, so - // an agent set up later is still found. + // A machine with no coding agent skips before the lock and the gate + // lookup: the gate changes nothing for it, and such machines (containers, + // job pods) often have no route to the manifest and a home directory that + // keeps no state, so they would wait for the lookup on every run. The + // version is not settled, so an agent set up later is still found. if reason == autoinstall.ReasonGateOff { tools, err := planTools(quietContext(ctx), in.State) if err == nil && tools.skip == protos.AitoolsAutoInstallOutcomeSkippedNoAgents { log.Debugf(ctx, "auto-install: skipped: %s", tools.skipWhy) return nil } - if err == nil && autoInstallAsks() && in.State.AcceptedVersion != version && !canAsk(ctx) && len(tools.newAgents()) > 0 { - skipUnaskable(ctx, in.State.ID) - return nil - } } unlock, ok := autoinstall.TryLock(ctx) @@ -225,8 +208,8 @@ func autoInstall(ctx context.Context, skippedCommand bool) os.Signal { in.Now = now() id := in.State.ID if id == "" { - // Saved before it decides anything, so this run and one that cannot - // ask (skipUnaskable, which does not hold this lock) use the same ID. + // Saved before it decides anything, so the bucket the run decides + // with is the stored one. id, err = autoinstall.SaveID(ctx, autoinstall.NewID()) if err != nil { log.Debugf(ctx, "auto-install: skipped: could not save the state: %v", err) @@ -272,7 +255,7 @@ func autoInstall(ctx context.Context, skippedCommand bool) os.Signal { version: version, id: id, arm: holdoutArm(in.Bucket), - interactive: cmdio.HasTerminal(ctx) && autoInstallAsks(), + interactive: cmdio.HasTerminal(ctx) && useragent.AgentProvider() == "", now: in.Now, } if !reason.Due() { @@ -293,43 +276,28 @@ func autoInstall(ctx context.Context, skippedCommand bool) os.Signal { run.settle(ctx, outcome) return nil } - return run.attempt(ctx, in.State) + run.attempt(ctx, in.State) + return nil } // attempt installs or updates the tools and reports the outcome. prior is the // state the run was decided on. -func (r autoInstallRun) attempt(ctx context.Context, prior autoinstall.State) os.Signal { +func (r autoInstallRun) attempt(ctx context.Context, prior autoinstall.State) { attempt := autoinstall.NextAttempt(prior, r.version) qctx := quietContext(ctx) tools, err := planTools(qctx, prior) - // A caller that is not a coding agent is asked before a first install, - // once per version: a "yes" covers that version's retries. A planning - // failure is a failed attempt, and its retry asks. - asked := false - if err == nil && autoInstallAsks() && prior.AcceptedVersion != r.version && len(tools.newAgents()) > 0 { - // autoInstall skips this case before the lock; the state it decided - // on may have changed since. - if !canAsk(ctx) { - skipUnaskable(ctx, r.id) - return nil - } - if ok, sig := r.ask(ctx, tools.newAgents()); !ok { - return sig - } - asked = true - } // Count the attempt before making it: an attempt that never finishes (the // process is killed) still counts, and a state that cannot be saved stops // auto-install instead of retrying it on every run. started, recErr := autoinstall.StartAttempt(ctx, r.version, attempt, r.id, r.now) if recErr != nil { log.Debugf(ctx, "auto-install: skipped: could not save the state: %v", recErr) - return nil + return } if !started { // The user opted out after this run read the state. r.settle(ctx, protos.AitoolsAutoInstallOutcomeSkippedOptOut) - return nil + return } if err == nil && tools.fresh() { // Skills an unfinished install leaves have no install state; the @@ -360,7 +328,7 @@ func (r autoInstallRun) attempt(ctx context.Context, prior autoinstall.State) os // directory for its own. log.Debugf(ctx, "auto-install: kept the installed tools: %v", err) unfinished := tools.fresh() && (prior.Installing || installStateSaved(tools.globalDir)) - result, err = installResult{outcome: protos.AitoolsAutoInstallOutcomeKept, unfinished: unfinished, refusal: err}, nil + result, err = installResult{outcome: protos.AitoolsAutoInstallOutcomeKept, unfinished: unfinished}, nil } switch { case err != nil: @@ -370,10 +338,6 @@ func (r autoInstallRun) attempt(ctx context.Context, prior autoinstall.State) os } log.Debugf(ctx, "auto-install: attempt %d of %d failed: %v", attempt, autoinstall.MaxAttempts, err) r.report(ctx, outcome, classifyInstallError(err)) - if asked { - // The user is waiting for the answer to take effect. - cmdio.LogString(ctx, "Could not install Databricks AI tools. To install them, run: databricks aitools install") - } default: if result.unfinished { r.settleUnfinished(ctx, result.outcome) @@ -385,15 +349,9 @@ func (r autoInstallRun) attempt(ctx context.Context, prior autoinstall.State) os if result.updated { verb = "Updated" } - cmdio.LogString(ctx, fmt.Sprintf("%s Databricks AI tools for %s. Disable: %s", verb, strings.Join(result.agents, ", "), autoInstallDisable)) - } - if asked && result.refusal != nil { - // The user said yes and waits for the skills; the refusal names - // what was kept and the command that replaces it. - cmdio.LogString(ctx, "Did not install the Databricks AI tools skills: "+result.refusal.Error()) + cmdio.LogString(ctx, fmt.Sprintf("%s Databricks AI tools for %s. %s", verb, strings.Join(result.agents, ", "), autoInstallNoticeCommands)) } } - return nil } // installStateSaved reports whether the global directory has install state. @@ -404,44 +362,49 @@ func installStateSaved(globalDir string) bool { } // 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. +// answered but has a global installation that the CLI made (see +// existingInstallConsents). in is a run past stateFreeSkips. in.State gets the +// stored consent. func consentExistingInstall(ctx context.Context, in *autoinstall.Inputs) { - if in.CI || in.EnvOptOut || in.State.Consent() != autoinstall.ConsentUnknown { + if !existingInstallConsents(ctx, *in) { return } - if in.State.Installing || in.State.InstalledWithoutConsent { + 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 settles + // the version for it. + if previous == autoinstall.ConsentOptedOut { + in.State.OptedOut = true + } else { + in.State.Consented = true + } +} + +// existingInstallConsents reports whether the run in counts a global +// installation that the CLI made (one with install state) as the consent of a +// user who never answered: 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. A run +// in CI or with auto-install turned off in the environment does not count it. +// It only reads. +func existingInstallConsents(ctx context.Context, in autoinstall.Inputs) bool { + if in.CI || in.EnvOptOut || in.State.Consent() != autoinstall.ConsentUnknown { + return false + } globalDir, err := installer.GlobalSkillsDir(ctx) if err != nil { log.Debugf(ctx, "auto-install: could not look for an installation: %v", err) - return + return false } 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 + return false } + return existing != nil } // saveInstallStateDigest records the digest of the install state that a first @@ -465,114 +428,6 @@ func saveInstallStateDigest(ctx context.Context, globalDir string) { } } -// autoInstallAsks reports whether auto-install asks before a first install: -// no coding agent is detected. A run that cannot ask (see canAsk) skips; -// coding agents install without a question. -func autoInstallAsks() bool { - return useragent.AgentProvider() == "" -} - -// canAsk reports whether the question can be seen and answered: see -// cmdio.IsLinePromptSupported. A CLI process that the CLI started itself does -// not ask either; the parent asks after its own command. Nor does a run in a -// container: `docker run -t` without `-i` gives it a terminal that never -// delivers an answer, and a container's home often keeps no state, so the -// unanswered question would wait promptTimeout on every run. -func canAsk(ctx context.Context) bool { - return cmdio.IsLinePromptSupported(ctx) && !agents.IsSelfExec(ctx) && !inContainer() -} - -// skipUnaskable skips a run that would ask before installing but cannot: the -// question could not be seen or answered safely, and installing without it -// would skip the consent. The version is not settled, so a later run that can -// ask does. A machine with no stored ID gets one, so that such runs do not -// draw a new holdout bucket each time. -func skipUnaskable(ctx context.Context, storedID string) { - log.Debugf(ctx, "auto-install: skipped: cannot ask (a stream is not a terminal, the CLI runs in the background, in a container or for another CLI process, or stdin is in use)") - if storedID != "" { - return - } - if _, err := autoinstall.SaveID(ctx, autoinstall.NewID()); err != nil { - log.Debugf(ctx, "auto-install: could not save the state: %v", err) - } -} - -// skippedNotice is printed when the question was answered with neither yes nor -// no, or the "no" could not be saved. -const skippedNotice = "Skipped. To install Databricks AI tools later, run: databricks aitools install" - -// ask asks whether to install for the agents names and reports whether to go -// ahead, and the signal that ended the question, if one did (see -// AutoInstall). What was typed before the question, such as the next command -// typed while this one ran, is discarded unread; where it cannot be (a pipe -// that Git Bash's mintty counts as a terminal), the question is not asked. -// The version is settled before asking, so the question is asked once per -// 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, 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) - skipUnaskable(ctx, r.id) - return false, nil - } - if err := autoinstall.Record(ctx, r.version, 0, r.id, r.now); err != nil { - log.Debugf(ctx, "auto-install: skipped: could not save the state: %v", err) - return false, nil - } - actx, cancel := context.WithTimeout(ctx, promptTimeout) - defer cancel() - // Ctrl+C ends the question. The version is settled as unanswered, and - // the signal is returned for the CLI to end by. - actx, stop := notifyInterrupt(actx, os.Interrupt) - ans, err := cmdio.AskCancellable(actx, "Install Databricks AI tools for "+strings.Join(names, ", ")+"? [Y/n]", "") - sig := stop() - if err == nil && sig != nil { - // Ctrl+C right after an answer: the user asked the CLI to stop. - err = errInterrupted - } - if err != nil { - log.Debugf(ctx, "auto-install: skipped: the prompt was not answered: %v", err) - // End the question's line. - cmdio.LogString(ctx, "") - r.settle(ctx, protos.AitoolsAutoInstallOutcomeUnanswered) - return false, sig - } - switch strings.ToLower(strings.TrimSpace(ans)) { - case "", "y", "yes": - if err := autoinstall.Accept(ctx, r.version); err != nil { - // 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) - return false, nil - } - log.Debugf(ctx, "auto-install: skipped: the answer was neither yes nor no") - r.settle(ctx, protos.AitoolsAutoInstallOutcomeUnanswered) - cmdio.LogString(ctx, skippedNotice) - return false, nil -} - -// decline stores a "no" at the prompt as the opt-out, so no later version -// asks again. -func (r autoInstallRun) decline(ctx context.Context) { - r.settle(ctx, protos.AitoolsAutoInstallOutcomeDeclined) - 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 - } - cmdio.LogString(ctx, "Skipped. You won't be asked again; to install Databricks AI tools later, run: databricks aitools install") -} - // stateFreeSkips are the reasons Decide finds without the state. var stateFreeSkips = []autoinstall.Reason{ autoinstall.ReasonSkippedCommand, @@ -591,9 +446,11 @@ var skipOutcomes = map[autoinstall.Reason]protos.AitoolsAutoInstallOutcome{ // autoInstallRun is what the outcome of one auto-install run is reported with. type autoInstallRun struct { - version string - id string - arm protos.AitoolsHoldoutArm + version string + id string + arm protos.AitoolsHoldoutArm + // interactive is set when a person may be at the terminal: there is one, + // and no coding agent is detected. interactive bool // now is the time the run was decided at. now time.Time @@ -653,8 +510,6 @@ type installResult struct { // unfinished is set when a first install was refused the skills after // it left something behind: an agent did not get its tools. unfinished bool - // refusal is why the skills were refused, if they were. - refusal error } // toolsPlan is what an auto-install attempt does: update the existing global @@ -814,7 +669,7 @@ func (t toolsPlan) install(ctx context.Context) (installResult, error) { // caller reports it as kept. if _, refused := errors.AsType[*installer.RefusedError](err); refused && len(names) > 0 { log.Debugf(ctx, "auto-install: kept the skills: %v", err) - return installResult{outcome: protos.AitoolsAutoInstallOutcomeInstalled, agents: names, unfinished: true, refusal: err}, nil + return installResult{outcome: protos.AitoolsAutoInstallOutcomeInstalled, agents: names, unfinished: true}, nil } return installResult{outcome: protos.AitoolsAutoInstallOutcomeInstalled, agents: names}, err } diff --git a/cmd/aitools/autoinstall_run_test.go b/cmd/aitools/autoinstall_run_test.go index 812eed3fddf..2a18286b39f 100644 --- a/cmd/aitools/autoinstall_run_test.go +++ b/cmd/aitools/autoinstall_run_test.go @@ -8,7 +8,6 @@ import ( "io" "os" "path/filepath" - "slices" "strings" "syscall" "testing" @@ -39,28 +38,23 @@ const autoInstallTestManifest = `{ // autoInstallTestNow is the time of the runs setupAutoInstallHome prepares. var autoInstallTestNow = time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC) -// The interactive prompt needs a terminal, which acceptance tests do not -// have, so these cases drive the hook the root command runs with stdin as a -// test terminal; the rest of the terminal is detected as in a real run. Like -// the acceptance tests in acceptance/cmd/aitools/auto-install, they check -// only what the user and the backend see: the prompt and notice on stderr, -// the skills in Cursor's directory, the stored state and the telemetry -// event. -func TestAutoInstallPrompt(t *testing.T) { +// The hook asks nothing: on a machine whose user agreed, it installs whoever +// runs the CLI, also with no terminal and for a coding agent. These cases +// drive the hook the root command runs with each stream a test terminal or +// not; the rest of the terminal is detected as in a real run. Like the +// acceptance tests in acceptance/cmd/aitools/auto-install, they check only +// what the user and the backend see: the notice on stderr, the skills in +// Cursor's directory, the stored state and the telemetry event. +func TestAutoInstallWithConsent(t *testing.T) { tests := []struct { name string state string - input string // installState replaces the global install state file. installState string // unwritableSkillsDir puts a file where Cursor's skills directory // belongs, so Cursor cannot get the skills. unwritableSkillsDir bool - // handPlacedSkill puts the user's own databricks-test skill into - // Cursor's skills directory, so the install is refused the skills. - handPlacedSkill bool - // env is set on top of a terminal with color. - env map[string]string + env map[string]string // agent is a coding agent's env var, set to 1: the run is that // agent's call. agent string @@ -69,222 +63,87 @@ func TestAutoInstallPrompt(t *testing.T) { stdinPiped bool stdoutRedirected bool stderrRedirected bool - // inContainer makes the run one in a container. - inContainer bool - wantPrompt bool - wantStderr []string wantSkills bool wantState autoinstall.State wantOutcome protos.AitoolsAutoInstallOutcome }{ { - name: "enter accepts", - wantPrompt: true, - input: "\n", - wantStderr: []string{"Installed Databricks AI tools for Cursor. Disable: databricks aitools auto-install disable"}, + name: "a terminal", wantSkills: true, - wantState: autoinstall.State{LastVersion: "1.30.0", Consented: true, AcceptedVersion: "1.30.0", ID: "treatment-machine"}, + wantState: autoinstall.State{LastVersion: "1.30.0", Consented: true, ID: "treatment-machine"}, wantOutcome: protos.AitoolsAutoInstallOutcomeInstalled, }, { - name: "yes accepts", - wantPrompt: true, - input: "Y\n", - wantStderr: []string{"Installed Databricks AI tools for Cursor."}, - wantSkills: true, - wantState: autoinstall.State{LastVersion: "1.30.0", Consented: true, AcceptedVersion: "1.30.0", ID: "treatment-machine"}, - wantOutcome: protos.AitoolsAutoInstallOutcomeInstalled, - }, - { - name: "no declines and opts out", - wantPrompt: true, - input: "n\n", - wantStderr: []string{"Skipped. You won't be asked again; to install Databricks AI tools later, run: databricks aitools install"}, - wantState: autoinstall.State{LastVersion: "1.30.0", OptedOut: true, ID: "treatment-machine"}, - wantOutcome: protos.AitoolsAutoInstallOutcomeDeclined, - }, - { - name: "no answer settles the version without opting out", - input: "", - wantPrompt: true, - wantState: autoinstall.State{LastVersion: "1.30.0", ID: "treatment-machine"}, - wantOutcome: protos.AitoolsAutoInstallOutcomeUnanswered, - }, - { - name: "another answer settles the version without opting out", - input: "git status\n", - wantPrompt: true, - wantStderr: []string{"Skipped. To install Databricks AI tools later, run: databricks aitools install"}, - wantState: autoinstall.State{LastVersion: "1.30.0", ID: "treatment-machine"}, - wantOutcome: protos.AitoolsAutoInstallOutcomeUnanswered, - }, - { - name: "a planning failure is a failed attempt, retried later", - installState: "not json", - wantState: autoinstall.State{LastVersion: "1.30.0", Attempts: 1, LastAttempt: autoInstallTestNow, ID: "treatment-machine"}, - wantOutcome: protos.AitoolsAutoInstallOutcomeFailed, - }, - { - name: "a failed install after yes says so", - env: map[string]string{"DATABRICKS_SKILLS_BASE_URL": "http://127.0.0.1:1"}, - 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, Consented: true, AcceptedVersion: "1.30.0", Installing: true, ID: "treatment-machine"}, - wantOutcome: protos.AitoolsAutoInstallOutcomeFailed, - }, - { - name: "an agent that got no skills is a failed attempt, retried later", - unwritableSkillsDir: true, - agent: "CLAUDECODE", - stdinPiped: true, - stdoutRedirected: true, - stderrRedirected: true, - wantState: autoinstall.State{LastVersion: "1.30.0", Attempts: 1, LastAttempt: autoInstallTestNow, Installing: true, InstalledWithoutConsent: true, ID: "treatment-machine"}, - wantOutcome: protos.AitoolsAutoInstallOutcomeFailed, - }, - { - name: "a yes refused the skills says what was kept", - handPlacedSkill: true, - 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", Consented: true, AcceptedVersion: "1.30.0", ID: "treatment-machine"}, - wantOutcome: protos.AitoolsAutoInstallOutcomeKept, - }, - { - name: "NO_COLOR still asks", - env: map[string]string{"NO_COLOR": "1"}, - wantPrompt: true, - input: "\n", - wantStderr: []string{"Installed Databricks AI tools for Cursor."}, - wantSkills: true, - wantState: autoinstall.State{LastVersion: "1.30.0", Consented: true, AcceptedVersion: "1.30.0", ID: "treatment-machine"}, - wantOutcome: protos.AitoolsAutoInstallOutcomeInstalled, - }, - { - name: "TERM=dumb still asks", - env: map[string]string{"TERM": "dumb"}, - wantPrompt: true, - input: "n\n", - wantState: autoinstall.State{LastVersion: "1.30.0", OptedOut: true, ID: "treatment-machine"}, - wantOutcome: protos.AitoolsAutoInstallOutcomeDeclined, - }, - { - name: "redirected stderr skips without installing", - stderrRedirected: true, - input: "\n", - wantState: autoinstall.State{ID: "treatment-machine"}, - }, - { - name: "piped stdin skips without installing", - stdinPiped: true, - input: "\n", - wantState: autoinstall.State{ID: "treatment-machine"}, - }, - { - name: "stdout to a pager skips without installing", + name: "stdout to a pager", stdoutRedirected: true, - input: "\n", - wantState: autoinstall.State{ID: "treatment-machine"}, + wantSkills: true, + wantState: autoinstall.State{LastVersion: "1.30.0", Consented: true, ID: "treatment-machine"}, + wantOutcome: protos.AitoolsAutoInstallOutcomeInstalled, }, { - // ssh, nohup, cron or an IDE extension: nobody sees the question. - name: "no terminal at all skips without installing", + // ssh, nohup, cron or an IDE extension. + name: "no terminal at all", stdinPiped: true, stdoutRedirected: true, stderrRedirected: true, - wantState: autoinstall.State{ID: "treatment-machine"}, + wantSkills: true, + wantState: autoinstall.State{LastVersion: "1.30.0", Consented: true, ID: "treatment-machine"}, + wantOutcome: protos.AitoolsAutoInstallOutcomeInstalled, }, { - name: "a coding agent with no terminal installs without asking", + name: "a coding agent with no terminal", agent: "CLAUDECODE", stdinPiped: true, stdoutRedirected: true, stderrRedirected: true, - wantStderr: []string{"Installed Databricks AI tools for Cursor."}, wantSkills: true, - wantState: autoinstall.State{LastVersion: "1.30.0", InstalledWithoutConsent: true, ID: "treatment-machine"}, + wantState: autoinstall.State{LastVersion: "1.30.0", Consented: true, ID: "treatment-machine"}, wantOutcome: protos.AitoolsAutoInstallOutcomeInstalled, }, { - name: "a coding agent in a terminal installs without asking", + name: "a coding agent in a terminal", agent: "CURSOR_AGENT", - input: "n\n", - wantStderr: []string{"Installed Databricks AI tools for Cursor."}, wantSkills: true, - wantState: autoinstall.State{LastVersion: "1.30.0", InstalledWithoutConsent: true, ID: "treatment-machine"}, + wantState: autoinstall.State{LastVersion: "1.30.0", Consented: true, ID: "treatment-machine"}, wantOutcome: protos.AitoolsAutoInstallOutcomeInstalled, }, { - name: "a retry after yes is not asked again", - state: `{"id": "treatment-machine", "last_version": "1.30.0", "attempts": 1, "accepted_version": "1.30.0"}`, - input: "", - wantStderr: []string{"Installed Databricks AI tools for Cursor."}, + name: "a CLI process started by the CLI", + env: map[string]string{"DATABRICKS_CLI_SELF_EXEC": "1"}, wantSkills: true, - wantState: autoinstall.State{LastVersion: "1.30.0", AcceptedVersion: "1.30.0", InstalledWithoutConsent: true, ID: "treatment-machine"}, + wantState: autoinstall.State{LastVersion: "1.30.0", Consented: true, ID: "treatment-machine"}, wantOutcome: protos.AitoolsAutoInstallOutcomeInstalled, }, { - // The question was answered on an earlier run of this version. - name: "a retry after yes with no terminal installs", - state: `{"id": "treatment-machine", "last_version": "1.30.0", "attempts": 1, "accepted_version": "1.30.0"}`, - stdinPiped: true, - stdoutRedirected: true, - stderrRedirected: true, - wantStderr: []string{"Installed Databricks AI tools for Cursor."}, - wantSkills: true, - wantState: autoinstall.State{LastVersion: "1.30.0", AcceptedVersion: "1.30.0", InstalledWithoutConsent: true, ID: "treatment-machine"}, - wantOutcome: protos.AitoolsAutoInstallOutcomeInstalled, - }, - { - // A failed plan uses up an attempt without asking. - name: "a retry that was never asked asks", - state: `{"id": "treatment-machine", "last_version": "1.30.0", "attempts": 1}`, - wantPrompt: true, - input: "\n", + name: "a retry", + state: `{"id": "treatment-machine", "consented": true, "last_version": "1.30.0", "attempts": 1}`, wantSkills: true, - wantState: autoinstall.State{LastVersion: "1.30.0", Consented: true, AcceptedVersion: "1.30.0", ID: "treatment-machine"}, + wantState: autoinstall.State{LastVersion: "1.30.0", Consented: true, ID: "treatment-machine"}, wantOutcome: protos.AitoolsAutoInstallOutcomeInstalled, }, { - name: "a retry that was never asked skips when it cannot ask", - state: `{"id": "treatment-machine", "last_version": "1.30.0", "attempts": 1}`, - stdoutRedirected: true, - input: "\n", - wantState: autoinstall.State{LastVersion: "1.30.0", Attempts: 1, ID: "treatment-machine"}, - }, - { - name: "a CLI process started by the CLI does not ask", - env: map[string]string{"DATABRICKS_CLI_SELF_EXEC": "1"}, - input: "\n", - wantState: autoinstall.State{ID: "treatment-machine"}, - }, - { - // `docker run -t` without `-i`: a terminal that never delivers - // the answer, in a home that may not outlive the container. - name: "a terminal in a container skips without asking", - inContainer: true, - input: "\n", - wantState: autoinstall.State{ID: "treatment-machine"}, + name: "a planning failure is a failed attempt, retried later", + installState: "not json", + wantState: autoinstall.State{LastVersion: "1.30.0", Attempts: 1, LastAttempt: autoInstallTestNow, Consented: true, ID: "treatment-machine"}, + wantOutcome: protos.AitoolsAutoInstallOutcomeFailed, }, { - name: "a coding agent in a container installs without asking", - agent: "CLAUDECODE", - inContainer: true, - wantStderr: []string{"Installed Databricks AI tools for Cursor."}, - wantSkills: true, - wantState: autoinstall.State{LastVersion: "1.30.0", InstalledWithoutConsent: true, ID: "treatment-machine"}, - wantOutcome: protos.AitoolsAutoInstallOutcomeInstalled, + // The failure goes only to the debug log, also in a terminal. + name: "a failed install is silent", + env: map[string]string{"DATABRICKS_SKILLS_BASE_URL": "http://127.0.0.1:1"}, + wantState: autoinstall.State{LastVersion: "1.30.0", Attempts: 1, LastAttempt: autoInstallTestNow, Consented: true, Installing: true, ID: "treatment-machine"}, + wantOutcome: protos.AitoolsAutoInstallOutcomeFailed, }, { - // Holdout and treatment machines both wait for a run that can ask. - name: "a holdout machine that cannot ask waits too", - state: `{"id": "holdout-machine"}`, - stderrRedirected: true, - input: "\n", - wantState: autoinstall.State{ID: "holdout-machine"}, + name: "an agent that got no skills is a failed attempt, retried later", + unwritableSkillsDir: true, + agent: "CLAUDECODE", + stdinPiped: true, + stdoutRedirected: true, + stderrRedirected: true, + wantState: autoinstall.State{LastVersion: "1.30.0", Attempts: 1, LastAttempt: autoInstallTestNow, Consented: true, Installing: true, ID: "treatment-machine"}, + wantOutcome: protos.AitoolsAutoInstallOutcomeFailed, }, } for _, tc := range tests { @@ -294,23 +153,14 @@ func TestAutoInstallPrompt(t *testing.T) { agentEnv = []string{tc.agent, "1"} } home := setupAutoInstallHome(t, tc.state, agentEnv...) - t.Cleanup(autoinstall.ResetDeclined) if tc.installState != "" { dir := filepath.Join(home, ".databricks", "aitools", "skills") require.NoError(t, os.MkdirAll(dir, 0o755)) require.NoError(t, os.WriteFile(filepath.Join(dir, ".state.json"), []byte(tc.installState), 0o600)) } - if tc.inContainer { - inContainer = func() bool { return true } - } if tc.unwritableSkillsDir { require.NoError(t, os.WriteFile(filepath.Join(home, ".cursor", "skills"), nil, 0o644)) } - if tc.handPlacedSkill { - handPlaced := filepath.Join(home, ".cursor", "skills", "databricks-test") - require.NoError(t, os.MkdirAll(handPlaced, 0o755)) - require.NoError(t, os.WriteFile(filepath.Join(handPlaced, "NOTES.md"), []byte("my notes"), 0o644)) - } t.Setenv("TERM", "xterm") for k, v := range tc.env { t.Setenv(k, v) @@ -323,7 +173,8 @@ func TestAutoInstallPrompt(t *testing.T) { if tc.stderrRedirected { errW = &stderr } - var in io.Reader = strings.NewReader(tc.input) + // An answer to a question, which nobody asks. + var in io.Reader = strings.NewReader("n\n") if !tc.stdinPiped { in = cmdio.FakeTTYReader(in) } @@ -332,14 +183,14 @@ func TestAutoInstallPrompt(t *testing.T) { runAutoInstallHook(ctx) assert.Empty(t, stdout.String()) - assert.Equal(t, tc.wantPrompt, strings.Contains(stderr.String(), "Install Databricks AI tools for Cursor? [Y/n]: "), "prompted") - for _, want := range tc.wantStderr { - assert.Contains(t, stderr.String(), want) + wantStderr := "" + if tc.wantSkills { + wantStderr = "Installed Databricks AI tools for Cursor. Turn off: databricks aitools auto-install disable. Remove: databricks aitools uninstall\n" } + assert.Equal(t, wantStderr, stderr.String()) _, err := os.Stat(filepath.Join(home, ".cursor", "skills", "databricks-test", "SKILL.md")) assert.Equal(t, tc.wantSkills, err == nil, "Cursor has the skill") - assert.Equal(t, tc.wantSkills, strings.Contains(stderr.String(), "Installed Databricks AI tools for Cursor."), "notice names Cursor") state, err := autoinstall.Load(ctx) require.NoError(t, err) @@ -358,42 +209,95 @@ func TestAutoInstallPrompt(t *testing.T) { assert.Equal(t, protos.AitoolsHoldoutArmTreatment, e.HoldoutArm) } } - if tc.wantOutcome == "" { - assert.Empty(t, outcomes) - } else { - assert.Equal(t, []protos.AitoolsAutoInstallOutcome{tc.wantOutcome}, outcomes) - } + assert.Equal(t, []protos.AitoolsAutoInstallOutcome{tc.wantOutcome}, outcomes) }) } } -// A run that cannot ask on a machine with no stored ID saves the ID it drew, -// so that later runs keep the machine's holdout bucket. -func TestAutoInstallKeepsTheIDWhenItCannotAsk(t *testing.T) { - setupAutoInstallHome(t, "{}") - t.Setenv("TERM", "xterm") - var stderr bytes.Buffer - run := func() autoinstall.State { - ctx := cmdio.InContext(t.Context(), cmdio.NewIO(t.Context(), flags.OutputText, strings.NewReader("\n"), io.Discard, cmdio.FakeTTY(&stderr), "", "")) - ctx = telemetry.WithNewLogger(ctx) - runAutoInstallHook(ctx) - assert.Empty(t, telemetry.BufferedEvents(ctx)) - state, err := autoinstall.Load(ctx) - require.NoError(t, err) - return state +// A run on a machine whose user never agreed stops before it changes or sends +// anything: it installs nothing, leaves the state file as it was (the version +// stays unsettled, and no machine ID is drawn), takes no run lock, looks no +// gate up and reports nothing. +func TestAutoInstallWithoutConsent(t *testing.T) { + tests := []struct { + name string + // state seeds the state file; with none, the machine has no file. + state string + // agent is a coding agent's env var, set to 1. + agent string + // terminal makes every stream a test terminal. + terminal bool + }{ + {name: "no terminal", state: `{"id": "treatment-machine"}`}, + {name: "a terminal", state: `{"id": "treatment-machine"}`, terminal: true}, + {name: "a coding agent", state: `{"id": "treatment-machine"}`, agent: "CLAUDECODE"}, + {name: "no state file"}, + {name: "no machine ID yet", state: `{}`}, + {name: "a retry", state: `{"id": "treatment-machine", "last_version": "1.30.0", "attempts": 1, "last_attempt": "2000-01-01T00:00:00Z"}`}, + {name: "a holdout machine", state: `{"id": "holdout-machine"}`}, + {name: "a newer version", state: `{"id": "treatment-machine", "last_version": "1.29.0"}`}, } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + var agentEnv []string + if tc.agent != "" { + agentEnv = []string{tc.agent, "1"} + } + home := setupAutoInstallHome(t, tc.state, agentEnv...) + stateFile := filepath.Join(home, ".databricks", "aitools", "auto-install.json") + if tc.state == "" { + require.NoError(t, os.Remove(stateFile)) + } + before, _ := os.ReadFile(stateFile) + t.Cleanup(func() { gateOn = autoinstall.GateOn }) + gateOn = func(context.Context, string) (bool, error) { + t.Error("the gate was looked up") + return true, nil + } + var stderr bytes.Buffer + var in io.Reader = strings.NewReader("") + var out, errW io.Writer = io.Discard, &stderr + if tc.terminal { + t.Setenv("TERM", "xterm") + in, out, errW = cmdio.FakeTTYReader(in), cmdio.FakeTTY(out), cmdio.FakeTTY(errW) + } + ctx := cmdio.InContext(t.Context(), cmdio.NewIO(t.Context(), flags.OutputText, in, out, errW, "", "")) + ctx = telemetry.WithNewLogger(ctx) + assert.Nil(t, runAutoInstallHook(ctx)) + + assert.Empty(t, stderr.String()) + assert.NoDirExists(t, filepath.Join(home, ".cursor", "skills")) + after, _ := os.ReadFile(stateFile) + assert.Equal(t, string(before), string(after), "the state is not written") + if tc.state == "" { + assert.NoFileExists(t, stateFile) + } + assert.NoFileExists(t, filepath.Join(home, ".databricks", "aitools", "auto-install.lock"), "the run lock is not taken") + assert.Empty(t, telemetry.BufferedEvents(ctx)) + }) + } +} - first := run() - assert.NotEmpty(t, first.ID) - assert.Empty(t, first.LastVersion, "the version is not settled") - assert.Equal(t, first, run()) - assert.NotContains(t, stderr.String(), "Install Databricks AI tools") +// A machine whose user agrees after a run of a version installs on the next +// run of that version: the run without the consent left the version unsettled. +func TestAutoInstallAfterConsentOnTheSameVersion(t *testing.T) { + home := setupAutoInstallHome(t, `{"id": "treatment-machine"}`) + outcomes, state := runAutoInstallAt(t, 0) + assert.Empty(t, outcomes) + assert.Equal(t, autoinstall.State{ID: "treatment-machine"}, state) + + _, err := autoinstall.SetConsent(t.Context(), autoinstall.ConsentGiven) + require.NoError(t, err) + outcomes, state = runAutoInstallAt(t, time.Second) + assert.Equal(t, []protos.AitoolsAutoInstallOutcome{protos.AitoolsAutoInstallOutcomeInstalled}, outcomes) + assert.Equal(t, autoinstall.State{LastVersion: "1.30.0", Consented: true, ID: "treatment-machine"}, state) + assert.FileExists(t, filepath.Join(home, ".cursor", "skills", "databricks-test", "SKILL.md")) } // A machine that cannot reach the compatibility manifest waits for the lookup // after one command of a version, not after each of them. func TestAutoInstallLooksTheGateUpOncePerVersion(t *testing.T) { - setupAutoInstallHome(t, "", "CLAUDECODE", "1") + setupAutoInstallHome(t, "") lookups := 0 t.Cleanup(func() { gateOn = autoinstall.GateOn }) gateOn = func(context.Context, string) (bool, error) { @@ -410,7 +314,7 @@ func TestAutoInstallLooksTheGateUpOncePerVersion(t *testing.T) { return state } - want := autoinstall.State{LastVersion: "1.30.0", Attempts: autoinstall.MaxAttempts, ID: "treatment-machine"} + want := autoinstall.State{LastVersion: "1.30.0", Attempts: autoinstall.MaxAttempts, Consented: true, ID: "treatment-machine"} assert.Equal(t, want, run()) assert.Equal(t, want, run()) assert.Equal(t, 1, lookups) @@ -424,7 +328,7 @@ func TestAutoInstallLooksTheGateUpOncePerVersion(t *testing.T) { // the gate on. The run stops instead of installing: it records the version as // a failed lookup does, and returns the signal for the CLI to end by. func TestAutoInstallStopsWhenTheGateLookupIsInterrupted(t *testing.T) { - home := setupAutoInstallHome(t, "", "CLAUDECODE", "1") + home := setupAutoInstallHome(t, "") ctx := cmdio.MockDiscard(t.Context()) ctx = telemetry.WithNewLogger(ctx) origNotify := notifyInterrupt @@ -448,49 +352,13 @@ func TestAutoInstallStopsWhenTheGateLookupIsInterrupted(t *testing.T) { assert.Equal(t, process.InterruptSignals(), caught) assert.Empty(t, telemetry.BufferedEvents(ctx)) assert.NoDirExists(t, filepath.Join(home, ".cursor", "skills")) - want := autoinstall.State{LastVersion: "1.30.0", Attempts: autoinstall.MaxAttempts, ID: "treatment-machine"} + want := autoinstall.State{LastVersion: "1.30.0", Attempts: autoinstall.MaxAttempts, Consented: true, ID: "treatment-machine"} state, err := autoinstall.Load(ctx) require.NoError(t, err) assert.Equal(t, want, state) assert.Equal(t, syscall.SIGHUP, sig) } -// Ctrl+C right after the question was answered stops the run as Ctrl+C at the -// question does: nothing is installed, the version is settled as unanswered, -// and the signal is returned for the CLI to end by. -func TestAutoInstallStopsWhenInterruptedAfterAnAnswer(t *testing.T) { - home := setupAutoInstallHome(t, "") - t.Setenv("TERM", "xterm") - origNotify := notifyInterrupt - t.Cleanup(func() { notifyInterrupt = origNotify }) - notifyInterrupt = func(ctx context.Context, sigs ...os.Signal) (context.Context, func() os.Signal) { - if !slices.Equal(sigs, []os.Signal{os.Interrupt}) { - // The gate lookup is not interrupted. - return origNotify(ctx, sigs...) - } - // The question reads the answer, and then Ctrl+C arrives. - return ctx, func() os.Signal { return os.Interrupt } - } - var stderr bytes.Buffer - ctx := cmdio.InContext(t.Context(), cmdio.NewIO(t.Context(), flags.OutputText, cmdio.FakeTTYReader(strings.NewReader("y\n")), cmdio.FakeTTY(io.Discard), cmdio.FakeTTY(&stderr), "", "")) - ctx = telemetry.WithNewLogger(ctx) - sig := runAutoInstallHook(ctx) - - assert.Equal(t, os.Interrupt, sig) - assert.Contains(t, stderr.String(), "Install Databricks AI tools for Cursor? [Y/n]: ") - assert.NoDirExists(t, filepath.Join(home, ".cursor", "skills")) - state, err := autoinstall.Load(ctx) - require.NoError(t, err) - assert.Equal(t, autoinstall.State{LastVersion: "1.30.0", ID: "treatment-machine"}, state) - var outcomes []protos.AitoolsAutoInstallOutcome - for _, e := range telemetry.BufferedEvents(ctx) { - if e := e.AitoolsAutoInstallEvent; e != nil { - outcomes = append(outcomes, e.Outcome) - } - } - assert.Equal(t, []protos.AitoolsAutoInstallOutcome{protos.AitoolsAutoInstallOutcomeUnanswered}, outcomes) -} - // Without a signal, stopping reports none. func TestNotifyInterruptWithoutASignal(t *testing.T) { ctx, stop := notifyInterrupt(t.Context(), os.Interrupt) @@ -501,9 +369,9 @@ func TestNotifyInterruptWithoutASignal(t *testing.T) { // A failed attempt is retried only after a wait that doubles with each failed // attempt, so a source that stays broken does not slow down the commands that -// follow it. The run is a coding agent's call with no terminal. +// follow it. func TestAutoInstallWaitsBeforeARetry(t *testing.T) { - setupAutoInstallHome(t, "", "CLAUDECODE", "1") + setupAutoInstallHome(t, "") skillsURL := os.Getenv("DATABRICKS_SKILLS_BASE_URL") t.Setenv("DATABRICKS_SKILLS_BASE_URL", "http://127.0.0.1:1") failed := []protos.AitoolsAutoInstallOutcome{protos.AitoolsAutoInstallOutcomeFailed} @@ -542,14 +410,14 @@ 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", InstalledWithoutConsent: true, ID: "treatment-machine"}, state) + assert.Equal(t, autoinstall.State{LastVersion: "1.31.0", Consented: true, ID: "treatment-machine"}, state) } // A first install that saved install state but did not give Cursor the skills // is retried as a first install, so Cursor gets them once its skills // directory can be written. func TestAutoInstallRetriesAnAgentThatGotNoSkills(t *testing.T) { - home := setupAutoInstallHome(t, "", "CLAUDECODE", "1") + home := setupAutoInstallHome(t, "") skillsDir := filepath.Join(home, ".cursor", "skills") require.NoError(t, os.WriteFile(skillsDir, nil, 0o644)) @@ -566,8 +434,7 @@ 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) - // 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.Equal(t, autoinstall.State{LastVersion: "1.30.0", Consented: true, ID: "treatment-machine"}, state) assert.FileExists(t, filepath.Join(skillsDir, "databricks-test", "SKILL.md")) } @@ -604,7 +471,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, InstalledWithoutConsent: true, ID: "treatment-machine"}, state) + assert.Equal(t, autoinstall.State{LastVersion: "1.30.0", Installing: true, InstallStateDigest: digest, Consented: true, ID: "treatment-machine"}, state) assert.NoFileExists(t, filepath.Join(handPlaced, "SKILL.md")) assert.Equal(t, 1, pluginInstalls) @@ -612,14 +479,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, InstalledWithoutConsent: true, ID: "treatment-machine"}, state) + assert.Equal(t, autoinstall.State{LastVersion: "1.31.0", Installing: true, InstallStateDigest: digest, Consented: 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", InstalledWithoutConsent: true, ID: "treatment-machine"}, state) + assert.Equal(t, autoinstall.State{LastVersion: "1.32.0", Consented: 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")) @@ -640,7 +507,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", InstalledWithoutConsent: true, ID: "treatment-machine"}, state) + assert.Equal(t, autoinstall.State{LastVersion: "1.30.0", Consented: true, ID: "treatment-machine"}, state) moved := filepath.Join(home, ".databricks", "aitools", "skills", "databricks-test") require.NoError(t, os.MkdirAll(filepath.Dir(moved), 0o755)) @@ -648,7 +515,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", InstalledWithoutConsent: true, ID: "treatment-machine"}, state) + assert.Equal(t, autoinstall.State{LastVersion: "1.31.0", Consented: 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)) @@ -660,7 +527,7 @@ func TestAutoInstallSettlesARefusalThatWroteNothing(t *testing.T) { // so a later version finishes it instead of keeping the skills it left as the // user's. func TestAutoInstallKeepsAnUnfinishedInstallRefusedTheSkills(t *testing.T) { - home := setupAutoInstallHome(t, `{"id": "treatment-machine", "installing": true}`, "CLAUDECODE", "1") + home := setupAutoInstallHome(t, `{"id": "treatment-machine", "consented": true, "installing": true}`, "CLAUDECODE", "1") left := filepath.Join(home, ".databricks", "aitools", "skills", "databricks-test") require.NoError(t, os.MkdirAll(left, 0o755)) require.NoError(t, os.WriteFile(filepath.Join(left, "SKILL.md"), []byte("---\nname: databricks-test\n---\n"), 0o644)) @@ -670,14 +537,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, InstalledWithoutConsent: true, ID: "treatment-machine"}, state) + assert.Equal(t, autoinstall.State{LastVersion: "1.30.0", Installing: true, Consented: 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", InstalledWithoutConsent: true, ID: "treatment-machine"}, state) + assert.Equal(t, autoinstall.State{LastVersion: "1.31.0", Consented: true, ID: "treatment-machine"}, state) assert.FileExists(t, filepath.Join(handPlaced, "SKILL.md")) } @@ -702,54 +569,27 @@ 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, InstalledWithoutConsent: true, ID: "treatment-machine"} + return autoinstall.State{LastVersion: "1.30.0", Attempts: attempts, LastAttempt: autoInstallTestNow.Add(elapsed), Consented: true, Installing: true, ID: "treatment-machine"} } -// A run that has nothing to install or cannot ask skips before the gate -// lookup, so a cron job or a job pod does not wait for it on every run. The -// run has no terminal. +// A machine with no agent to install for skips before the gate lookup, so a +// cron job or a job pod does not wait for it on every run. The version is not +// settled, so an agent set up later is still found. func TestAutoInstallSkipsTheGateLookup(t *testing.T) { - tests := []struct { - name string - // agentEnv makes the run a coding agent's call, which installs - // without asking. - agentEnv []string - // noAgents removes Cursor's config dir: the machine has no agent - // to install for. - noAgents bool - }{ - { - // The coding agent's call keeps the run off the cannot-ask skip, - // so the skip is the no-agents one. - name: "a machine with no agent to install for", - agentEnv: []string{"CLAUDECODE", "1"}, - noAgents: true, - }, - { - name: "a run with no terminal and no coding agent cannot ask", - }, - } - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { - home := setupAutoInstallHome(t, "", tc.agentEnv...) - if tc.noAgents { - require.NoError(t, os.RemoveAll(filepath.Join(home, ".cursor"))) - } - t.Cleanup(func() { gateOn = autoinstall.GateOn }) - gateOn = func(context.Context, string) (bool, error) { - t.Error("the gate was looked up") - return true, nil - } - ctx := cmdio.MockDiscard(t.Context()) - ctx = telemetry.WithNewLogger(ctx) - runAutoInstallHook(ctx) - assert.Empty(t, telemetry.BufferedEvents(ctx)) - assert.NoDirExists(t, filepath.Join(home, ".cursor", "skills")) - state, err := autoinstall.Load(ctx) - require.NoError(t, err) - assert.Equal(t, autoinstall.State{ID: "treatment-machine"}, state, "the version is not settled") - }) + home := setupAutoInstallHome(t, "") + require.NoError(t, os.RemoveAll(filepath.Join(home, ".cursor"))) + t.Cleanup(func() { gateOn = autoinstall.GateOn }) + gateOn = func(context.Context, string) (bool, error) { + t.Error("the gate was looked up") + return true, nil } + ctx := cmdio.MockDiscard(t.Context()) + ctx = telemetry.WithNewLogger(ctx) + runAutoInstallHook(ctx) + assert.Empty(t, telemetry.BufferedEvents(ctx)) + state, err := autoinstall.Load(ctx) + require.NoError(t, err) + assert.Equal(t, autoinstall.State{Consented: true, ID: "treatment-machine"}, state, "the version is not settled") } // Root running in a user's home (sudo with HOME kept) leaves the home alone: @@ -770,16 +610,14 @@ 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", InstalledWithoutConsent: true, ID: "treatment-machine"}, state) + assert.Equal(t, autoinstall.State{LastVersion: "1.30.0", Consented: true, ID: "treatment-machine"}, state) }) } // runRootInUserHome runs the hook in a fresh home, as root in a user's home // when rootInHome is set, and counts the gate lookups. func runRootInUserHome(t *testing.T, rootInHome bool) (ctx context.Context, home string, lookups *int) { - // A coding agent's call installs without a question, so the user's run - // needs no terminal. - home = setupAutoInstallHome(t, "", "CLAUDECODE", "1") + home = setupAutoInstallHome(t, "") if rootInHome { // The state the setup seeds would hide a state file or lock file // the run creates. @@ -800,9 +638,9 @@ func runRootInUserHome(t *testing.T, rootInHome bool) (ctx context.Context, home } // `databricks aitools auto-install disable` run in another terminal while the -// run looks the gate up (or shows the prompt) stops the install. +// run looks the gate up stops the install. func TestAutoInstallStopsAtAnOptOutStoredWhileItDecides(t *testing.T) { - home := setupAutoInstallHome(t, "", "CLAUDECODE", "1") + home := setupAutoInstallHome(t, "") t.Cleanup(func() { gateOn = autoinstall.GateOn }) gateOn = func(ctx context.Context, _ string) (bool, error) { _, err := autoinstall.SetConsent(ctx, autoinstall.ConsentOptedOut) @@ -830,7 +668,7 @@ func TestAutoInstallStopsAtAnOptOutStoredWhileItDecides(t *testing.T) { // anything, instead of the run putting the tools back after the uninstall // reported success. Once the run is done, it removes what the run installed. func TestUninstallFailsWhileAnAutoInstallRuns(t *testing.T) { - home := setupAutoInstallHome(t, "", "CLAUDECODE", "1") + home := setupAutoInstallHome(t, "") noTelemetryAuth(t) skill := filepath.Join(home, ".cursor", "skills", "databricks-test", "SKILL.md") @@ -896,11 +734,6 @@ func TestAutoInstallStoresTheConsentOfAnExistingInstall(t *testing.T) { {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}, @@ -963,7 +796,7 @@ func TestToolsPlanNewAgents(t *testing.T) { assert.Equal(t, []string{"Claude Code", "Cursor"}, toolsPlan{plan: plan}.newAgents()) assert.Empty(t, toolsPlan{plan: plan[2:]}.newAgents(), "an agent that keeps its plugin gets nothing") - assert.Empty(t, toolsPlan{existing: &installer.InstallState{}, plan: plan}.newAgents(), "an update does not ask") + assert.Empty(t, toolsPlan{existing: &installer.InstallState{}, plan: plan}.newAgents(), "an update names no new agent") } // runAutoInstallHook runs the hook as the root command does after @@ -981,8 +814,9 @@ func runAutoInstallHook(ctx context.Context) os.Signal { // setupAutoInstallHome gives the run a clean environment with Cursor's config // dir, a skills server, the gate on and a released CLI version. state seeds -// the auto-install state (a treatment-arm machine id by default). env adds -// key/value pairs to the environment, such as a coding agent's env var. +// the auto-install state (by default, a treatment-arm machine id and the +// user's consent). env adds key/value pairs to the environment, such as a +// coding agent's env var. func setupAutoInstallHome(t *testing.T, state string, env ...string) string { t.Helper() home := t.TempDir() @@ -1008,13 +842,10 @@ func setupAutoInstallHome(t *testing.T, state string, env ...string) string { isolateAgents(t, kv...) t.Cleanup(func() { now = time.Now }) now = func() time.Time { return autoInstallTestNow } - // The test itself may run in a container. - t.Cleanup(func() { inContainer = autoinstall.InContainer }) - inContainer = func() bool { return false } require.NoError(t, os.MkdirAll(filepath.Join(home, ".cursor"), 0o755)) if state == "" { - state = `{"id": "treatment-machine"}` + state = `{"id": "treatment-machine", "consented": true}` } stateDir := filepath.Join(home, ".databricks", "aitools") require.NoError(t, os.MkdirAll(stateDir, 0o755)) diff --git a/cmd/aitools/autoinstall_run_unix_test.go b/cmd/aitools/autoinstall_run_unix_test.go index 2a3deb4d353..acec08d0d01 100644 --- a/cmd/aitools/autoinstall_run_unix_test.go +++ b/cmd/aitools/autoinstall_run_unix_test.go @@ -25,8 +25,8 @@ import ( ) // autoInstallSignalHelperEnv makes TestMain run the hook in a helper process, -// which the test signals at the step the value names: "question" or "lookup". -// The CLI ends by the signal, so it cannot run in the test process. +// which the test signals during the gate lookup. The CLI ends by the signal, +// so it cannot run in the test process. const autoInstallSignalHelperEnv = "AITOOLS_TEST_SIGNAL_HELPER" // gateLookupStarted is what the helper prints when its gate lookup starts. @@ -39,80 +39,57 @@ func init() { // runAutoInstallSignalHelperProcess runs the hook when // TestAutoInstallEndsByTheSignal re-executes the test binary as the helper. func runAutoInstallSignalHelperProcess() { - step := os.Getenv(autoInstallSignalHelperEnv) - if step == "" { + if os.Getenv(autoInstallSignalHelperEnv) == "" { return } // The root command ends the CLI by the signal that the hook returns; // exiting normally fails the test. - if sig := runAutoInstallSignalHelper(step); sig != nil { + if sig := runAutoInstallSignalHelper(); sig != nil { process.Raise(sig) } os.Exit(0) } -func runAutoInstallSignalHelper(step string) os.Signal { +func runAutoInstallSignalHelper() os.Signal { // The helper is a new process: it has the real clock, not the test's. now = func() time.Time { return autoInstallTestNow } - if step == "lookup" { - // Only the signal ends the lookup. - gateTimeout = time.Hour - // A lookup that waits for the manifest until it is stopped. - gateOn = func(ctx context.Context, _ string) (bool, error) { - fmt.Fprintln(os.Stderr, gateLookupStarted) - <-ctx.Done() - return false, ctx.Err() - } + // Only the signal ends the lookup. + gateTimeout = time.Hour + // A lookup that waits for the manifest until it is stopped. + gateOn = func(ctx context.Context, _ string) (bool, error) { + fmt.Fprintln(os.Stderr, gateLookupStarted) + <-ctx.Done() + return false, ctx.Err() } // TestMain has no *testing.T, so t.Context() is unavailable here. //nolint:gocritic ctx := context.Background() - // stdin is a pipe that nobody writes to, so the question waits for an - // answer. ctx = cmdio.InContext(ctx, cmdio.NewIO(ctx, flags.OutputText, cmdio.FakeTTYReader(os.Stdin), cmdio.FakeTTY(io.Discard), cmdio.FakeTTY(os.Stderr), "", "")) ctx = telemetry.WithNewLogger(ctx) return runAutoInstallHook(ctx) } -// A signal at the question or during the gate lookup ends the CLI by that -// signal, so that the shell stops the script or loop that ran the command, -// and only after the version is recorded: the next command neither asks nor -// looks the gate up again. +// A signal during the gate lookup ends the CLI by that signal, so that the +// shell stops the script or loop that ran the command, and only after the +// version is recorded: the next command does not look the gate up again. func TestAutoInstallEndsByTheSignal(t *testing.T) { - tests := []struct { - step string - sig syscall.Signal - wantState autoinstall.State - }{ - {"question", syscall.SIGINT, autoinstall.State{LastVersion: "1.30.0", ID: "treatment-machine"}}, - {"lookup", syscall.SIGINT, autoinstall.State{LastVersion: "1.30.0", Attempts: autoinstall.MaxAttempts, ID: "treatment-machine"}}, - {"lookup", syscall.SIGTERM, autoinstall.State{LastVersion: "1.30.0", Attempts: autoinstall.MaxAttempts, ID: "treatment-machine"}}, - {"lookup", syscall.SIGHUP, autoinstall.State{LastVersion: "1.30.0", Attempts: autoinstall.MaxAttempts, ID: "treatment-machine"}}, - } - for _, tc := range tests { - t.Run(tc.step+"/"+tc.sig.String(), func(t *testing.T) { + for _, sig := range []syscall.Signal{syscall.SIGINT, syscall.SIGTERM, syscall.SIGHUP} { + t.Run(sig.String(), func(t *testing.T) { // The helper inherits a SIGHUP ignored at start, as under nohup, // and then rightly leaves it alone. - if !slices.Contains(process.InterruptSignals(), os.Signal(tc.sig)) { - t.Skipf("%v was ignored when the test started", tc.sig) + if !slices.Contains(process.InterruptSignals(), os.Signal(sig)) { + t.Skipf("%v was ignored when the test started", sig) } setupAutoInstallHome(t, "") t.Setenv("TERM", "xterm") helper := exec.Command(os.Args[0]) - helper.Env = append(os.Environ(), autoInstallSignalHelperEnv+"="+tc.step) - stdin, err := helper.StdinPipe() - require.NoError(t, err) - t.Cleanup(func() { _ = stdin.Close() }) + helper.Env = append(os.Environ(), autoInstallSignalHelperEnv+"=1") stderr, err := helper.StderrPipe() require.NoError(t, err) require.NoError(t, helper.Start()) - want := gateLookupStarted - if tc.step == "question" { - want = "Install Databricks AI tools for Cursor? [Y/n]: " - } - output := waitForOutput(t, stderr, want) - require.NoError(t, helper.Process.Signal(tc.sig)) + output := waitForOutput(t, stderr, gateLookupStarted) + require.NoError(t, helper.Process.Signal(sig)) waitErr := make(chan error, 1) go func() { waitErr <- helper.Wait() }() @@ -122,7 +99,7 @@ func TestAutoInstallEndsByTheSignal(t *testing.T) { require.True(t, ok, "the helper exited with %v; it printed:\n%s", err, output) status := exitErr.Sys().(syscall.WaitStatus) assert.True(t, status.Signaled(), "the helper must end by the signal, got %v", err) - assert.Equal(t, tc.sig, status.Signal()) + assert.Equal(t, sig, status.Signal()) case <-time.After(10 * time.Second): _ = helper.Process.Kill() t.Fatal("the signal did not end the helper") @@ -130,7 +107,7 @@ func TestAutoInstallEndsByTheSignal(t *testing.T) { state, err := autoinstall.Load(t.Context()) require.NoError(t, err) - assert.Equal(t, tc.wantState, state) + assert.Equal(t, autoinstall.State{LastVersion: "1.30.0", Attempts: autoinstall.MaxAttempts, Consented: true, ID: "treatment-machine"}, state) }) } } diff --git a/libs/aitools/autoinstall/container.go b/libs/aitools/autoinstall/container.go deleted file mode 100644 index 75749e77649..00000000000 --- a/libs/aitools/autoinstall/container.go +++ /dev/null @@ -1,26 +0,0 @@ -package autoinstall - -import "os" - -// containerMarkers are the files container engines create in every container: -// Docker's /.dockerenv and Podman's /run/.containerenv. -// See https://docs.podman.io/en/latest/markdown/podman-run.1.html (/run/.containerenv). -var containerMarkers = []string{"/.dockerenv", "/run/.containerenv"} - -// InContainer reports whether the CLI runs in a Docker or Podman container. -// There the CLI cannot tell whether a terminal forwards keystrokes (`docker -// run -t` without `-i` does not), and the home directory often does not -// outlive the container, so a question asked there may be asked on every run. -func InContainer() bool { - return anyExists(containerMarkers) -} - -// anyExists reports whether any of paths exists. -func anyExists(paths []string) bool { - for _, p := range paths { - if _, err := os.Stat(p); err == nil { - return true - } - } - return false -} diff --git a/libs/aitools/autoinstall/container_test.go b/libs/aitools/autoinstall/container_test.go deleted file mode 100644 index 5065a479e3d..00000000000 --- a/libs/aitools/autoinstall/container_test.go +++ /dev/null @@ -1,22 +0,0 @@ -package autoinstall - -import ( - "os" - "path/filepath" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestAnyExists(t *testing.T) { - dir := t.TempDir() - marker := filepath.Join(dir, ".dockerenv") - missing := filepath.Join(dir, ".containerenv") - - assert.False(t, anyExists(nil)) - assert.False(t, anyExists([]string{missing})) - - require.NoError(t, os.WriteFile(marker, nil, 0o600)) - assert.True(t, anyExists([]string{missing, marker})) -} diff --git a/libs/aitools/autoinstall/decide.go b/libs/aitools/autoinstall/decide.go index c440c7a5f8d..c9678483a85 100644 --- a/libs/aitools/autoinstall/decide.go +++ b/libs/aitools/autoinstall/decide.go @@ -36,6 +36,9 @@ const ( ReasonAlreadyRan Reason = "already_ran" ReasonRetriesExhausted Reason = "retries_exhausted" ReasonRetryNotDue Reason = "retry_not_due" + // The user never agreed to installing the tools. The version is left + // unsettled, so the first run after the user agrees installs. + ReasonNoConsent Reason = "no_consent" // Settle the version without installing. All but ReasonGateOff are // reported: the feature is not launched while the gate is off. @@ -52,7 +55,7 @@ const ( // settles the version. A run that is not due changes nothing. func (r Reason) Due() bool { switch r { - case ReasonSkippedCommand, ReasonOnRuntime, ReasonCacheDisabled, ReasonDevelopmentBuild, ReasonRootInUserHome, ReasonAlreadyRan, ReasonRetriesExhausted, ReasonRetryNotDue: + case ReasonSkippedCommand, ReasonOnRuntime, ReasonCacheDisabled, ReasonDevelopmentBuild, ReasonRootInUserHome, ReasonAlreadyRan, ReasonRetriesExhausted, ReasonRetryNotDue, ReasonNoConsent: return false case ReasonSkippedCI, ReasonSkippedOptOut, ReasonGateOff, ReasonSkippedHoldout, ReasonRun: return true @@ -79,7 +82,8 @@ type Inputs struct { // that another user owns (see RootInUserHome). RootInUserHome bool - // State is the persisted state: last version, attempts and opt-out. + // State is the persisted state: last version, attempts and the user's + // consent. State State // Now is the time of the run. @@ -131,8 +135,12 @@ func Decide(in Inputs) Reason { return ReasonAlreadyRan case in.CI: return ReasonSkippedCI - case in.EnvOptOut, in.State.OptedOut: + case in.EnvOptOut, in.State.Consent() == ConsentOptedOut: return ReasonSkippedOptOut + // Without the user's yes nothing is installed. CI and the opt-out come + // first, so they settle the version and are reported whatever the consent. + case in.State.Consent() == ConsentUnknown: + return ReasonNoConsent // A source or agent CLI that stays broken would otherwise make every // following command wait for a failing attempt. The wait is for the // install only: CI and the opt-out settle the version during it. diff --git a/libs/aitools/autoinstall/decide_test.go b/libs/aitools/autoinstall/decide_test.go index 15e991c290e..32ef4b4ff68 100644 --- a/libs/aitools/autoinstall/decide_test.go +++ b/libs/aitools/autoinstall/decide_test.go @@ -8,8 +8,10 @@ import ( ) func TestDecide(t *testing.T) { - // eligible is a run of a released version never seen before, with the gate on, in the treatment arm. + // eligible is a run of a released version never seen before on a machine + // whose user agreed, with the gate on, in the treatment arm. eligible := Inputs{ + State: State{Consented: true}, Version: "1.30.0", Now: time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC), GateOn: true, @@ -31,48 +33,59 @@ func TestDecide(t *testing.T) { {name: "root in a user's home", modify: func(in *Inputs) { in.RootInUserHome = true }, want: ReasonRootInUserHome}, {name: "root in a user's home before the state", modify: func(in *Inputs) { in.RootInUserHome = true - in.State = State{LastVersion: "1.30.0", Attempts: MaxAttempts} + in.State = State{Consented: true, LastVersion: "1.30.0", Attempts: MaxAttempts} in.CI = true }, want: ReasonRootInUserHome}, {name: "same version, settled", modify: func(in *Inputs) { in.State.LastVersion = "1.30.0" }, want: ReasonAlreadyRan}, - {name: "same version, failed before", modify: func(in *Inputs) { in.State = State{LastVersion: "1.30.0", Attempts: 3} }, want: ReasonRun}, - {name: "same version, last attempt left", modify: func(in *Inputs) { in.State = State{LastVersion: "1.30.0", Attempts: MaxAttempts - 1} }, want: ReasonRun}, - {name: "same version, retries exhausted", modify: func(in *Inputs) { in.State = State{LastVersion: "1.30.0", Attempts: MaxAttempts} }, want: ReasonRetriesExhausted}, + {name: "same version, failed before", modify: func(in *Inputs) { in.State = State{Consented: true, LastVersion: "1.30.0", Attempts: 3} }, want: ReasonRun}, + {name: "same version, last attempt left", modify: func(in *Inputs) { in.State = State{Consented: true, LastVersion: "1.30.0", Attempts: MaxAttempts - 1} }, want: ReasonRun}, + {name: "same version, retries exhausted", modify: func(in *Inputs) { in.State = State{Consented: true, LastVersion: "1.30.0", Attempts: MaxAttempts} }, want: ReasonRetriesExhausted}, {name: "same version, failed just now", modify: func(in *Inputs) { - in.State = State{LastVersion: "1.30.0", Attempts: 1, LastAttempt: in.Now} + in.State = State{Consented: true, LastVersion: "1.30.0", Attempts: 1, LastAttempt: in.Now} }, want: ReasonRetryNotDue}, {name: "same version, retry due", modify: func(in *Inputs) { - in.State = State{LastVersion: "1.30.0", Attempts: 1, LastAttempt: in.Now.Add(-firstRetryDelay)} + in.State = State{Consented: true, LastVersion: "1.30.0", Attempts: 1, LastAttempt: in.Now.Add(-firstRetryDelay)} }, want: ReasonRun}, {name: "same version, retries exhausted while waiting", modify: func(in *Inputs) { - in.State = State{LastVersion: "1.30.0", Attempts: MaxAttempts, LastAttempt: in.Now} + in.State = State{Consented: true, LastVersion: "1.30.0", Attempts: MaxAttempts, LastAttempt: in.Now} }, want: ReasonRetriesExhausted}, {name: "CI before the retry wait", modify: func(in *Inputs) { - in.State = State{LastVersion: "1.30.0", Attempts: 1, LastAttempt: in.Now} + in.State = State{Consented: true, LastVersion: "1.30.0", Attempts: 1, LastAttempt: in.Now} in.CI = true }, want: ReasonSkippedCI}, {name: "opt-out before the retry wait", modify: func(in *Inputs) { in.State = State{LastVersion: "1.30.0", Attempts: 1, LastAttempt: in.Now, OptedOut: true} }, want: ReasonSkippedOptOut}, {name: "retry wait before the gate", modify: func(in *Inputs) { - in.State = State{LastVersion: "1.30.0", Attempts: 1, LastAttempt: in.Now} + in.State = State{Consented: true, LastVersion: "1.30.0", Attempts: 1, LastAttempt: in.Now} in.GateOn = false }, want: ReasonRetryNotDue}, {name: "new version while the old one waits", modify: func(in *Inputs) { - in.State = State{LastVersion: "1.29.0", Attempts: 1, LastAttempt: in.Now} + in.State = State{Consented: true, LastVersion: "1.29.0", Attempts: 1, LastAttempt: in.Now} }, want: ReasonRun}, - {name: "new version after retries exhausted", modify: func(in *Inputs) { in.State = State{LastVersion: "1.29.0", Attempts: MaxAttempts} }, want: ReasonRun}, + {name: "new version after retries exhausted", modify: func(in *Inputs) { in.State = State{Consented: true, LastVersion: "1.29.0", Attempts: MaxAttempts} }, want: ReasonRun}, {name: "older CLI after a newer one ran", modify: func(in *Inputs) { in.State.LastVersion = "1.31.0" }, want: ReasonAlreadyRan}, - {name: "older CLI while a newer one retries", modify: func(in *Inputs) { in.State = State{LastVersion: "1.31.0", Attempts: 2} }, want: ReasonAlreadyRan}, + {name: "older CLI while a newer one retries", modify: func(in *Inputs) { in.State = State{Consented: true, LastVersion: "1.31.0", Attempts: 2} }, want: ReasonAlreadyRan}, {name: "newer CLI after an older one ran", modify: func(in *Inputs) { in.State.LastVersion = "1.29.5" }, want: ReasonRun}, {name: "CI", modify: func(in *Inputs) { in.CI = true }, want: ReasonSkippedCI}, {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: "persisted opt-out", modify: func(in *Inputs) { in.State = State{OptedOut: true} }, want: ReasonSkippedOptOut}, + {name: "env opt-out over a stored consent", modify: func(in *Inputs) { in.EnvOptOut = true }, want: ReasonSkippedOptOut}, + {name: "opt-out before the gate", modify: func(in *Inputs) { in.State = State{OptedOut: true}; in.GateOn = false }, want: ReasonSkippedOptOut}, + + {name: "unknown consent", modify: func(in *Inputs) { in.State = State{} }, want: ReasonNoConsent}, + {name: "unknown consent on a retry", modify: func(in *Inputs) { in.State = State{LastVersion: "1.30.0", Attempts: 3} }, want: ReasonNoConsent}, + {name: "CI before the consent", modify: func(in *Inputs) { in.State = State{}; in.CI = true }, want: ReasonSkippedCI}, + {name: "env opt-out before the consent", modify: func(in *Inputs) { in.State = State{}; in.EnvOptOut = true }, want: ReasonSkippedOptOut}, + {name: "consent before the retry wait", modify: func(in *Inputs) { + in.State = State{LastVersion: "1.30.0", Attempts: 1, LastAttempt: in.Now} + }, want: ReasonNoConsent}, + {name: "consent before the gate", modify: func(in *Inputs) { in.State = State{}; in.GateOn = false }, want: ReasonNoConsent}, + {name: "consent before the holdout", modify: func(in *Inputs) { in.State = State{}; in.Bucket = 0 }, want: ReasonNoConsent}, + {name: "settled version before the consent", modify: func(in *Inputs) { in.State = State{LastVersion: "1.30.0"} }, want: ReasonAlreadyRan}, {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}, {name: "holdout", modify: func(in *Inputs) { in.Bucket = HoldoutPercent - 1 }, want: ReasonSkippedHoldout}, @@ -125,7 +138,7 @@ func TestRetryDue(t *testing.T) { } func TestReasonDue(t *testing.T) { - notDue := []Reason{ReasonSkippedCommand, ReasonOnRuntime, ReasonCacheDisabled, ReasonDevelopmentBuild, ReasonRootInUserHome, ReasonAlreadyRan, ReasonRetriesExhausted, ReasonRetryNotDue} + notDue := []Reason{ReasonSkippedCommand, ReasonOnRuntime, ReasonCacheDisabled, ReasonDevelopmentBuild, ReasonRootInUserHome, ReasonAlreadyRan, ReasonRetriesExhausted, ReasonRetryNotDue, ReasonNoConsent} due := []Reason{ReasonSkippedCI, ReasonSkippedOptOut, ReasonGateOff, ReasonSkippedHoldout, ReasonRun} for _, r := range notDue { assert.False(t, r.Due(), r) diff --git a/libs/aitools/autoinstall/run.go b/libs/aitools/autoinstall/run.go index ab9ec43240a..0aad17a4378 100644 --- a/libs/aitools/autoinstall/run.go +++ b/libs/aitools/autoinstall/run.go @@ -95,7 +95,7 @@ func Record(ctx context.Context, version string, attempts int, id string, now ti // StartAttempt records attempt as Record does, unless the state is opted out // by then, and reports whether it did. A run counts the attempt right before // it installs, so an opt-out stored after the run read the state (during the -// gate lookup or the install prompt, say) still stops it. +// gate lookup, say) still stops it. func StartAttempt(ctx context.Context, version string, attempt int, id string, now time.Time) (started bool, err error) { err = updateState(ctx, func(s *State) { if s.OptedOut { @@ -135,15 +135,9 @@ func RecordUnfinished(ctx context.Context, version, id string) error { }) } -// MarkInstalling sets State.Installing before a first install starts, and -// State.InstalledWithoutConsent when the user has not answered. +// MarkInstalling sets State.Installing before a first install starts. func MarkInstalling(ctx context.Context) error { - return updateState(ctx, func(s *State) { - s.Installing = true - if s.Consent() == ConsentUnknown { - s.InstalledWithoutConsent = true - } - }) + return updateState(ctx, func(s *State) { s.Installing = true }) } // SaveInstallStateDigest sets State.InstallStateDigest after a first install @@ -166,12 +160,6 @@ func SaveID(ctx context.Context, id string) (string, error) { return id, err } -// Accept records that the user answered "yes" at the install prompt of -// version (State.AcceptedVersion). -func Accept(ctx context.Context, version string) error { - return updateState(ctx, func(s *State) { s.AcceptedVersion = version }) -} - // TryLock claims the machine-wide auto-install lock so that concurrent CLI // processes (agents often run several at once) do not install at the same // time. ok is false when another process holds it or it cannot be taken; that diff --git a/libs/aitools/autoinstall/run_test.go b/libs/aitools/autoinstall/run_test.go index 59841b6056c..cacdf79b118 100644 --- a/libs/aitools/autoinstall/run_test.go +++ b/libs/aitools/autoinstall/run_test.go @@ -169,38 +169,7 @@ 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", 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") + assert.Equal(t, State{LastVersion: "1.30.0", Installing: true, InstallStateDigest: "digest", ID: "machine"}, s) } func TestRecordStoresTheLastFailedAttempt(t *testing.T) { diff --git a/libs/aitools/autoinstall/state.go b/libs/aitools/autoinstall/state.go index 92a456f1943..4c3d2f5c95d 100644 --- a/libs/aitools/autoinstall/state.go +++ b/libs/aitools/autoinstall/state.go @@ -44,26 +44,19 @@ type State struct { // OptedOut turns auto-install off for every later version. It is set by // `databricks aitools auto-install disable`, by a global-scope - // `databricks aitools uninstall`, by declining the install prompt and by a - // "no" to the skills prompt of `databricks apps init`. + // `databricks aitools uninstall` and by a "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 + // up, by a "yes" to the skills prompt of `databricks apps init`, and by a + // run that finds a global installation made by the CLI. 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. - AcceptedVersion string `json:"accepted_version,omitempty"` - // Installing is set while auto-install makes a first install, and stays // set when the install did not finish, including one that was refused // the skills (see RecordUnfinished). The skills such an install left @@ -80,12 +73,6 @@ 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. @@ -179,7 +166,6 @@ func (s State) Consent() Consent { 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 diff --git a/libs/aitools/autoinstall/state_test.go b/libs/aitools/autoinstall/state_test.go index ecbf1ccbcf0..e2452edb98b 100644 --- a/libs/aitools/autoinstall/state_test.go +++ b/libs/aitools/autoinstall/state_test.go @@ -77,9 +77,11 @@ func TestLoadStateOfEarlierVersions(t *testing.T) { want: State{LastVersion: "1.27.0", OptedOut: true, ID: "machine"}, }, { + // accepted_version, the version whose question after a command + // was answered yes, is ignored. 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"}, + want: State{LastVersion: "1.27.0", Installing: true, ID: "machine"}, }, { name: "1.28 opted out during retries", @@ -100,6 +102,16 @@ func TestLoadStateOfEarlierVersions(t *testing.T) { want = ConsentOptedOut } assert.Equal(t, want, s.Consent()) + + // A write keeps only the fields this CLI knows. + _, err = SaveID(ctx, "other") + require.NoError(t, err) + data, err := os.ReadFile(filepath.Join(home, ".databricks", "aitools", stateFileName)) + require.NoError(t, err) + assert.NotContains(t, string(data), "accepted_version") + s, err = Load(ctx) + require.NoError(t, err) + assert.Equal(t, tc.want, s) }) } } @@ -187,7 +199,6 @@ func TestGiveConsentIfUnknown(t *testing.T) { 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}}, } { diff --git a/libs/apps/vite/bridge.go b/libs/apps/vite/bridge.go index 8964d69d228..7b658e83c7d 100644 --- a/libs/apps/vite/bridge.go +++ b/libs/apps/vite/bridge.go @@ -981,8 +981,6 @@ func (vb *Bridge) Start() error { }) if !vb.autoApprove { - // Stop does not end the read, so it can outlive the command. - cmdio.MarkStdinReadInBackground() go vb.readStdinLines(os.Stdin) } diff --git a/libs/cmdio/ask.go b/libs/cmdio/ask.go index c3765d790b7..82772c6d38d 100644 --- a/libs/cmdio/ask.go +++ b/libs/cmdio/ask.go @@ -69,8 +69,7 @@ func Ask(ctx context.Context, question, defaultVal string) (string, error) { // done and returns ctx.Err(). Reading the input cannot be interrupted, so the // read keeps running in the background and its result is discarded. The // caller must not read the input again after a cancelled call, because the -// abandoned read would consume the next line; a cancelled call turns off line -// prompts for the rest of the process (see MarkStdinReadInBackground). +// abandoned read would consume the next line. func AskCancellable(ctx context.Context, question, defaultVal string) (string, error) { type answer struct { ans string @@ -84,9 +83,6 @@ func AskCancellable(ctx context.Context, question, defaultVal string) (string, e select { case <-ctx.Done(): - // The abandoned read takes the next line, so later prompts in this - // process must not ask. - MarkStdinReadInBackground() return "", ctx.Err() case a := <-answers: return a.ans, a.err diff --git a/libs/cmdio/ask_test.go b/libs/cmdio/ask_test.go index a4292dde3a0..75fc64d7c54 100644 --- a/libs/cmdio/ask_test.go +++ b/libs/cmdio/ask_test.go @@ -201,8 +201,6 @@ func TestAskCancellable_Cancelled(t *testing.T) { ctx, cancel := context.WithCancel(t.Context()) ctx = InContext(ctx, NewIO(ctx, flags.OutputText, stdin, io.Discard, io.Discard, "", "")) cancel() - t.Cleanup(func() { stdinReadInBackground.Store(false) }) _, err := AskCancellable(ctx, "Question", "") assert.ErrorIs(t, err, context.Canceled) - assert.True(t, stdinReadInBackground.Load(), "the abandoned read turns off later line prompts") } diff --git a/libs/cmdio/capabilities.go b/libs/cmdio/capabilities.go index 2349081462a..f48c72a006a 100644 --- a/libs/cmdio/capabilities.go +++ b/libs/cmdio/capabilities.go @@ -57,16 +57,6 @@ func (c Capabilities) SupportsPrompt() bool { return c.SupportsInteractive() && c.stdinIsTTY && !c.stdinIsMSYSPipe } -// SupportsLinePrompt returns true if the terminal supports a plain-text line -// prompt (see [Ask]): it writes the question to stderr and reads the answer -// from stdin. stdout must be a terminal too: when it is piped to a pager, the -// pager reads the same terminal, so its keystrokes could answer the prompt. -// Unlike SupportsPrompt it does not depend on TERM=dumb or an MSYS2 pty pipe -// (see conpty.go), which only matter for the TUI prompts. -func (c Capabilities) SupportsLinePrompt() bool { - return c.stdinIsTTY && c.stdoutIsTTY && c.stderrIsTTY -} - // SupportsColor returns true if the given writer supports colored output. // This checks both TTY status and environment variables (NO_COLOR, TERM=dumb). func (c Capabilities) SupportsColor(w io.Writer) bool { diff --git a/libs/cmdio/capabilities_test.go b/libs/cmdio/capabilities_test.go index ca70f46ddda..63a8226d86e 100644 --- a/libs/cmdio/capabilities_test.go +++ b/libs/cmdio/capabilities_test.go @@ -66,22 +66,6 @@ func TestCapabilities_SupportsPrompt(t *testing.T) { } } -func TestCapabilities_SupportsLinePrompt(t *testing.T) { - full := Capabilities{stdinIsTTY: true, stdoutIsTTY: true, stderrIsTTY: true} - assert.True(t, full.SupportsLinePrompt()) - - // A plain-text line needs no redraw, so TERM=dumb, which turns off the - // TUI prompts, still gets it. - dumb := full - dumb.dumb = true - assert.False(t, dumb.SupportsPrompt()) - assert.True(t, dumb.SupportsLinePrompt()) - - assert.False(t, Capabilities{stdinIsTTY: false, stdoutIsTTY: true, stderrIsTTY: true}.SupportsLinePrompt(), "stdin not TTY") - assert.False(t, Capabilities{stdinIsTTY: true, stdoutIsTTY: false, stderrIsTTY: true}.SupportsLinePrompt(), "stdout not TTY") - assert.False(t, Capabilities{stdinIsTTY: true, stdoutIsTTY: true, stderrIsTTY: false}.SupportsLinePrompt(), "stderr not TTY") -} - func TestCapabilities_SupportsPager(t *testing.T) { tests := []struct { name string diff --git a/libs/cmdio/io.go b/libs/cmdio/io.go index e7b62d71e97..82a87a69f67 100644 --- a/libs/cmdio/io.go +++ b/libs/cmdio/io.go @@ -4,10 +4,8 @@ import ( "context" "errors" "io" - "os" "strings" "sync" - "sync/atomic" tea "github.com/charmbracelet/bubbletea" "github.com/databricks/cli/libs/flags" @@ -85,44 +83,6 @@ func IsPromptSupported(ctx context.Context) bool { return c.capabilities.SupportsPrompt() } -// IsLinePromptSupported reports whether a plain-text line prompt ([Ask]) can -// be shown and answered: stdin, stdout and stderr are terminals, this process -// is in the terminal's foreground process group (a background job that reads -// it is stopped), and no goroutine reads stdin in the background (see -// [MarkStdinReadInBackground]). Unlike IsPromptSupported, it does not depend -// on TERM=dumb or an MSYS2 pty pipe, which only matter for the TUI prompts. -func IsLinePromptSupported(ctx context.Context) bool { - c := fromContext(ctx) - if !c.capabilities.SupportsLinePrompt() || stdinReadInBackground.Load() { - return false - } - f, ok := c.in.(*os.File) - return !ok || inForeground(f) -} - -// stdinReadInBackground is set once a goroutine reads stdin for the rest of -// the process. -var stdinReadInBackground atomic.Bool - -// MarkStdinReadInBackground records that a goroutine reads os.Stdin and may -// outlive the command, so later line prompts in this process are not asked: -// that goroutine could take their answer. -func MarkStdinReadInBackground() { - stdinReadInBackground.Store(true) -} - -// DiscardInput discards what was typed at the stdin terminal but not read -// yet, so that a prompt asked after a long-running command reads only what is -// typed after the question. -func DiscardInput(ctx context.Context) error { - c := fromContext(ctx) - f, ok := c.in.(*os.File) - if !ok || !c.capabilities.stdinIsTTY { - return nil - } - return discardInput(f) -} - // IsInputTTY reports whether stdin is a terminal, so that a user can type // input into the command. Unlike IsPromptSupported, it does not depend on // stderr or TERM=dumb, which only matter for rendering prompts, and it accepts diff --git a/libs/cmdio/io_test.go b/libs/cmdio/io_test.go index 6c69f1923d5..b926dec3cd7 100644 --- a/libs/cmdio/io_test.go +++ b/libs/cmdio/io_test.go @@ -3,7 +3,6 @@ package cmdio import ( "bytes" "io" - "strings" "testing" "time" @@ -78,16 +77,3 @@ func TestHasTerminal(t *testing.T) { }) } } - -func TestIsLinePromptSupported(t *testing.T) { - ctx := t.Context() - terminal := InContext(ctx, NewIO(ctx, flags.OutputText, FakeTTYReader(strings.NewReader("")), FakeTTY(io.Discard), FakeTTY(io.Discard), "", "")) - assert.True(t, IsLinePromptSupported(terminal)) - - piped := InContext(ctx, NewIO(ctx, flags.OutputText, strings.NewReader(""), FakeTTY(io.Discard), FakeTTY(io.Discard), "", "")) - assert.False(t, IsLinePromptSupported(piped)) - - t.Cleanup(func() { stdinReadInBackground.Store(false) }) - MarkStdinReadInBackground() - assert.False(t, IsLinePromptSupported(terminal), "another goroutine reads stdin") -} diff --git a/libs/cmdio/terminal_darwin.go b/libs/cmdio/terminal_darwin.go deleted file mode 100644 index b0f2109b1d1..00000000000 --- a/libs/cmdio/terminal_darwin.go +++ /dev/null @@ -1,14 +0,0 @@ -package cmdio - -import ( - "os" - - "golang.org/x/sys/unix" -) - -// discardInput discards what was typed at the terminal f but not read yet. -// It is tcflush with TCIFLUSH, which libc implements as TIOCFLUSH with FREAD. -func discardInput(f *os.File) error { - const fread = 1 - return unix.IoctlSetPointerInt(int(f.Fd()), unix.TIOCFLUSH, fread) -} diff --git a/libs/cmdio/terminal_foreground.go b/libs/cmdio/terminal_foreground.go deleted file mode 100644 index d1022bbe75e..00000000000 --- a/libs/cmdio/terminal_foreground.go +++ /dev/null @@ -1,17 +0,0 @@ -//go:build linux || darwin - -package cmdio - -import ( - "os" - - "golang.org/x/sys/unix" -) - -// inForeground reports whether this process is in the foreground process -// group of the terminal f. A background job that reads its terminal is -// stopped (SIGTTIN) until the user brings it to the foreground. -func inForeground(f *os.File) bool { - pgrp, err := unix.IoctlGetInt(int(f.Fd()), unix.TIOCGPGRP) - return err == nil && pgrp == unix.Getpgrp() -} diff --git a/libs/cmdio/terminal_linux.go b/libs/cmdio/terminal_linux.go deleted file mode 100644 index 64367ee2d3f..00000000000 --- a/libs/cmdio/terminal_linux.go +++ /dev/null @@ -1,13 +0,0 @@ -package cmdio - -import ( - "os" - - "golang.org/x/sys/unix" -) - -// discardInput discards what was typed at the terminal f but not read yet -// (tcflush with TCIFLUSH). -func discardInput(f *os.File) error { - return unix.IoctlSetInt(int(f.Fd()), unix.TCFLSH, unix.TCIFLUSH) -} diff --git a/libs/cmdio/terminal_other.go b/libs/cmdio/terminal_other.go deleted file mode 100644 index 1e42d7819ca..00000000000 --- a/libs/cmdio/terminal_other.go +++ /dev/null @@ -1,17 +0,0 @@ -//go:build !linux && !darwin && !windows - -package cmdio - -import "os" - -// inForeground reports whether this process may read the terminal f. The -// release builds' platforms check it; others assume it may. -func inForeground(*os.File) bool { - return true -} - -// discardInput discards what was typed at the terminal f but not read yet. -// Only the release builds' platforms implement it. -func discardInput(*os.File) error { - return nil -} diff --git a/libs/cmdio/terminal_windows.go b/libs/cmdio/terminal_windows.go deleted file mode 100644 index 2462ff5e829..00000000000 --- a/libs/cmdio/terminal_windows.go +++ /dev/null @@ -1,18 +0,0 @@ -package cmdio - -import ( - "os" - - "golang.org/x/sys/windows" -) - -// inForeground reports whether this process may read the console f. Windows -// consoles have no background jobs, so it always may. -func inForeground(*os.File) bool { - return true -} - -// discardInput discards what was typed at the console f but not read yet. -func discardInput(f *os.File) error { - return windows.FlushConsoleInputBuffer(windows.Handle(f.Fd())) -} diff --git a/libs/telemetry/protos/README.md b/libs/telemetry/protos/README.md index 7af722e84cf..53e2ab3694b 100644 --- a/libs/telemetry/protos/README.md +++ b/libs/telemetry/protos/README.md @@ -40,15 +40,14 @@ within the upload timeout, when auth has already resolved. On the first run of a new CLI version, the CLI can install Databricks AI tools for the coding agents on the machine (see `databricks aitools auto-install --help`). It logs an `aitools_auto_install_event` with the outcome (`INSTALLED`, `UP_TO_DATE`, `KEPT`, `SKIPPED_CI`, `SKIPPED_OPTOUT`, -`SKIPPED_HOLDOUT`, `SKIPPED_NO_AGENTS`, `SKIPPED_PLATFORM`, `DECLINED`, `UNANSWERED`, `FAILED`, -`RETRIES_EXHAUSTED`), the machine's holdout arm and, for a failure, its error category: once per -version and machine, plus once per retry of a failed attempt. Nothing is logged for a version whose -outcome is settled, on Databricks Runtime, or while the feature is turned off remotely (the CI and -opt-out checks come first and are logged either way). A run that has to ask before installing but -cannot (a stream is not a terminal, or the CLI runs in the background) logs nothing and leaves the -version to a later run that can ask; a process killed at the prompt logs nothing either. An install -with no tools installed yet also logs an `aitools_install_event` with `trigger` `AUTO_FIRST_RUN`; -installs by `databricks aitools install` leave `trigger` unset. The holdout arm comes from a random -machine id kept in +`SKIPPED_HOLDOUT`, `SKIPPED_NO_AGENTS`, `SKIPPED_PLATFORM`, `FAILED`, `RETRIES_EXHAUSTED`), the +machine's holdout arm and, for a failure, its error category: once per version and machine, plus +once per retry of a failed attempt. `DECLINED` and `UNANSWERED` are no longer sent: auto-install +no longer asks. Nothing is logged for a version whose outcome is settled, on Databricks Runtime, or +while the feature is turned off remotely (the CI and opt-out checks come first and are logged +either way). A run on a machine whose user has not agreed to auto-install logs nothing and leaves +the version to a later run. An install with no tools installed yet also logs an +`aitools_install_event` with `trigger` `AUTO_FIRST_RUN`; installs by `databricks aitools install` +leave `trigger` unset. The holdout arm comes from a random machine id kept in `~/.databricks/aitools/auto-install.json`; the id itself is never sent. Like the other aitools events, these upload at exit only when the command resolved auth. diff --git a/libs/telemetry/protos/aitools_events.go b/libs/telemetry/protos/aitools_events.go index 377b7775c5f..f71a6b7224f 100644 --- a/libs/telemetry/protos/aitools_events.go +++ b/libs/telemetry/protos/aitools_events.go @@ -190,19 +190,19 @@ const ( AitoolsAutoInstallOutcomeSkippedCI AitoolsAutoInstallOutcome = "SKIPPED_CI" // The user turned auto-install off: DATABRICKS_AITOOLS_AUTO_INSTALL=false, // `aitools auto-install disable`, a global `aitools uninstall`, "no" at - // the prompt of an earlier version, or "no" to the skills prompt of - // `apps init`. + // the prompt of an earlier CLI, or "no" to the skills prompt of `apps + // init`. AitoolsAutoInstallOutcomeSkippedOptOut AitoolsAutoInstallOutcome = "SKIPPED_OPTOUT" // The machine is in the holdout cohort. AitoolsAutoInstallOutcomeSkippedHoldout AitoolsAutoInstallOutcome = "SKIPPED_HOLDOUT" // No supported coding agent has a config directory on the machine. AitoolsAutoInstallOutcomeSkippedNoAgents AitoolsAutoInstallOutcome = "SKIPPED_NO_AGENTS" // The user answered "no" at the install prompt, which also turns - // auto-install off. + // auto-install off. No longer sent: auto-install no longer asks. AitoolsAutoInstallOutcomeDeclined AitoolsAutoInstallOutcome = "DECLINED" // The install prompt got no answer: stdin was closed, Ctrl+C was pressed, - // it timed out, or the answer was neither yes nor no. Nothing is installed - // and auto-install stays on, so the next CLI version asks again. + // it timed out, or the answer was neither yes nor no. No longer sent: + // auto-install no longer asks. AitoolsAutoInstallOutcomeUnanswered AitoolsAutoInstallOutcome = "UNANSWERED" // The attempt failed or timed out; a later run of the same version // retries. @@ -228,18 +228,15 @@ const ( // machine, plus once per retry after a failed attempt. A version whose outcome // is settled emits nothing, and so does a run that the remote gate turns off; // the CI and opt-out checks come before the gate, so they are emitted either -// way. A run that has to ask before installing but cannot emits nothing and -// leaves the version to a later run. An install with no tools installed yet -// also emits an AitoolsInstallEvent with Trigger AUTO_FIRST_RUN. +// way. A run on a machine whose user has not agreed to auto-install emits +// nothing and leaves the version to a later run. An install with no tools +// installed yet also emits an AitoolsInstallEvent with Trigger AUTO_FIRST_RUN. type AitoolsAutoInstallEvent struct { Outcome AitoolsAutoInstallOutcome `json:"outcome"` HoldoutArm AitoolsHoldoutArm `json:"holdout_arm"` // Whether a person may be at the terminal (cmdio.HasTerminal and no - // coding agent detected). Such a run asks before the first install of a - // version, so DECLINED and UNANSWERED come only with true; INSTALLED with - // true may still have run without asking (an update, or a retry after an - // accepted attempt). A measurable false, so no omitempty. + // coding agent detected). A measurable false, so no omitempty. Interactive bool `json:"interactive"` // Set for FAILED and RETRIES_EXHAUSTED.