From a453ed329e128215b2c0c83a9c26c2e7e5af734d Mon Sep 17 00:00:00 2001 From: John Speaks Date: Fri, 20 Nov 2026 00:16:18 +0000 Subject: [PATCH 1/4] Overlap independent launch and configure lookups ug claude started the Anthropic picker catalog only after configure's discovery finished, and configure fetched the Copilot catalog and the provider-mode web-search model strictly after the gateway probe. All of these are independent round trips: start them alongside the probe and discovery on daemon threads and read the results where they were read before. A launch shape whose routing never reads the catalog abandons the speculative request instead of waiting out its retries. ug configure also read the workspace policy after discovery completed; read it while discovery runs. Co-authored-by: Isaac --- src/ucode/cli.py | 223 +++++++++++++++++++++++++++----------- tests/test_cli.py | 270 +++++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 425 insertions(+), 68 deletions(-) diff --git a/src/ucode/cli.py b/src/ucode/cli.py index b46ba214a..7bdb380ed 100644 --- a/src/ucode/cli.py +++ b/src/ucode/cli.py @@ -573,8 +573,8 @@ def _find_profile_name(workspace: str, workspace_id: str | None) -> str | None: return find_profile_name_for_host(workspace) -def _start_in_background[T](fn: Callable[..., T], *args: object) -> Future[T]: - """Run ``fn(*args)`` on a daemon thread; the returned future carries its result or exception. +def _start_in_background[T](fn: Callable[..., T], *args: object, **kwargs: object) -> Future[T]: + """Run ``fn(*args, **kwargs)`` on a daemon thread; the returned future carries its result. Not a ``ThreadPoolExecutor`` worker, which interpreter exit joins: a caller that raises before reading the result must exit without waiting out the abandoned call's network retries. @@ -583,7 +583,7 @@ def _start_in_background[T](fn: Callable[..., T], *args: object) -> Future[T]: def run() -> None: try: - future.set_result(fn(*args)) + future.set_result(fn(*args, **kwargs)) except BaseException as exc: future.set_exception(exc) @@ -603,6 +603,7 @@ def configure_shared_state( custom_oauth: CustomOAuthConfig | None = None, clear_custom_oauth: bool = False, claude_server_side_web_search: bool | None = None, + on_authenticated: Callable[[dict], None] | None = None, ) -> dict: """Log into Databricks, verify Unity Gateway, fetch model lists, persist state. @@ -622,6 +623,9 @@ def configure_shared_state( in ``_launch_tool``) and the gateway was verified by that earlier configure. Only the local profile resolution and the shared state assembly still run; the saved model lists are preserved. + ``on_authenticated``, when given, runs once with a snapshot of the assembled + state as soon as the workspace's token is available — callers overlap their + own authenticated lookups with the probe and discovery that follow. """ workspace = normalize_workspace_url(workspace) if not split_workspace_key(workspace)[1]: @@ -645,6 +649,31 @@ def configure_shared_state( databricks_ai_tools_enabled = False fetch_all = tools is None + want_claude = ( + fetch_all + or "claude" in tools + or "opencode" in tools + or "kilo" in tools + or "copilot" in tools + or "pi" in tools + ) + want_gemini = ( + fetch_all + or "gemini" in tools + or "opencode" in tools + or "kilo" in tools + or "pi" in tools + or "antigravity" in tools + ) + # Claude's web-search server also needs a Responses-capable model. + want_codex = ( + fetch_all or "codex" in tools or "claude" in tools or "copilot" in tools or "pi" in tools + ) + # Codex smart routing can select OSS models such as GLM, so a Codex-only + # configure must persist that discovered family too. + want_oss = fetch_all or "opencode" in tools or "kilo" in tools or "codex" in tools + want_copilot = fetch_all or "copilot" in tools + # Assemble the shared workspace state that doesn't depend on model discovery: # workspace, profile, auth mode, base URLs. `profile` may still be None here; # each path below resolves it once, where a host->profile lookup is reliable @@ -773,6 +802,8 @@ def configure_shared_state( with spinner("Verifying Unity Gateway..."): if not cli_custom_oauth: token = get_databricks_token(workspace, profile) + if on_authenticated is not None: + on_authenticated(dict(state)) # The listing is independent of the probe, so overlap the two round trips. The probe still # gates the launch; its failure abandons the listing rather than waiting for it. model_services_discovery = ( @@ -780,37 +811,24 @@ def configure_shared_state( if skip_model_discovery else _start_in_background(discover_model_services, workspace, token) ) + # These listings don't depend on the probe, the discovery, or each other either; a result + # the probe's failure makes unnecessary is abandoned on its daemon thread. + web_search_discovery = ( + _start_in_background(discover_codex_models, workspace, token) + if skip_model_discovery and want_claude + else None + ) + copilot_catalog_discovery = ( + _start_in_background(list_anthropic_model_catalog, workspace, token) + if want_copilot and not skip_model_discovery + else None + ) model_service_probe = probe_unity_gateway_capabilities(workspace, token) if model_service_probe.resource_available: print_success("Unity Gateway connected") else: print_warning(f"Model service: {model_service_probe.detail}") - want_claude = ( - fetch_all - or "claude" in tools - or "opencode" in tools - or "kilo" in tools - or "copilot" in tools - or "pi" in tools - ) - want_gemini = ( - fetch_all - or "gemini" in tools - or "opencode" in tools - or "kilo" in tools - or "pi" in tools - or "antigravity" in tools - ) - # Claude's web-search server also needs a Responses-capable model. - want_codex = ( - fetch_all or "codex" in tools or "claude" in tools or "copilot" in tools or "pi" in tools - ) - # Codex smart routing can select OSS models such as GLM, so a Codex-only - # configure must persist that discovered family too. - want_oss = fetch_all or "opencode" in tools or "kilo" in tools or "codex" in tools - want_copilot = fetch_all or "copilot" in tools - claude_reason: str | None = None gemini_reason: str | None = None codex_reason: str | None = None @@ -829,8 +847,9 @@ def configure_shared_state( # search (claude only) still needs one Responses-capable model, so fetch # just that with a single call. if want_claude: + assert web_search_discovery is not None with spinner("Fetching available models..."): - ws_models, _ = discover_codex_models(workspace, token) + ws_models, _ = web_search_discovery.result() if ws_models: web_search_model = ws_models[0] else: @@ -857,10 +876,11 @@ def configure_shared_state( if want_oss: oss_models, oss_reason = ms_oss, ms_reason if want_copilot: + assert copilot_catalog_discovery is not None copilot_models = copilot_agent.catalog_from_listings( cached_model_service_entries(workspace), [*claude_models.values(), *codex_models], - list_anthropic_model_catalog(workspace, token), + copilot_catalog_discovery.result(), ) copilot_reason = ms_reason or claude_reason or codex_reason if claude_models: @@ -921,6 +941,7 @@ def _configure_shared_workspace_states( custom_oauth: CustomOAuthConfig | None = None, clear_custom_oauth: bool = False, claude_server_side_web_search: bool | None = None, + on_authenticated: Callable[[dict], None] | None = None, ) -> list[dict]: if len(workspaces) != 1: raise RuntimeError(f"Expected exactly one workspace, got {len(workspaces)}.") @@ -942,6 +963,7 @@ def _configure_shared_workspace_states( force_login=force_login, use_pat=use_pat, databricks_ai_tools_enabled=databricks_ai_tools_enabled, + on_authenticated=on_authenticated, **custom_oauth_kwargs, **optional_kwargs, ) @@ -1170,6 +1192,15 @@ def _setup_single_agent( agents rejects them (see :func:`_reject_managed_model_source`). """ previous_workspace = state_workspace_key(load_state()) + # The workspace policy doesn't depend on model discovery, so read the fresh policy while + # discovery runs instead of after it. + policy_future: Future[ManagedConfigResult] | None = None + + def _start_fresh_policy_fetch(state: dict) -> None: + nonlocal policy_future + if apply_managed and tool in _FRESH_POLICY_AGENTS: + policy_future = _start_in_background(_refresh_configured_policy, state) + states = _configure_shared_workspace_states( workspace_entries, [tool], @@ -1179,6 +1210,7 @@ def _setup_single_agent( custom_oauth=custom_oauth, clear_custom_oauth=custom_oauth is None, claude_server_side_web_search=claude_server_side_web_search, + on_authenticated=_start_fresh_policy_fetch, ) state = states[0] parent_schema = None @@ -1186,7 +1218,10 @@ def _setup_single_agent( live_expansions: dict[str, list[str]] | None = None if apply_managed and tool in _FRESH_POLICY_AGENTS: # Explicit configure always reads the workspace policy fresh, so it can install it. - managed, _ = _refresh_configured_policy(state) + if policy_future is not None: + managed, _ = policy_future.result() + else: + managed, _ = _refresh_configured_policy(state) elif apply_managed: # Other agents only read the policy; they never install it. managed, _ = _read_policy_for_other_agent(state) @@ -1488,6 +1523,13 @@ def _configure_workspace_command( ) return 0 + # The workspace policy doesn't depend on model discovery, so read it while that runs. + policy_future: Future[ManagedConfigResult] | None = None + + def _start_fresh_policy_fetch(authenticated_state: dict) -> None: + nonlocal policy_future + policy_future = _start_in_background(_refresh_configured_policy, authenticated_state) + states = _configure_shared_workspace_states( workspace_entries, selected_tools, @@ -1497,6 +1539,7 @@ def _configure_workspace_command( custom_oauth=custom_oauth, clear_custom_oauth=custom_oauth is None, claude_server_side_web_search=claude_server_side_web_search, + on_authenticated=_start_fresh_policy_fetch, ) state = states[0] save_state(state) @@ -1504,7 +1547,10 @@ def _configure_workspace_command( # A published managed config means the admin dictates the setup: apply it to every enabled agent # now rather than prompting the developer to pick. Configure always reads fresh so it never # applies a config the admin has since changed. - managed, _ = _refresh_configured_policy(state) + if policy_future is not None: + managed, _ = policy_future.result() + else: + managed, _ = _refresh_configured_policy(state) refuse_user_scope_over_managed_config(state.get("workspace"), managed) managed_tools = managed_enabled_tools(managed) if managed is not None else [] if managed is not None and managed_tools: @@ -4349,6 +4395,65 @@ def _launch_tool( and (managed is None or managed_provider or managed_parent_schema) ): os.environ[claude_agent.GATEWAY_MODEL_DISCOVERY_ENV_VAR] = "1" + # The Anthropic picker catalog depends only on inputs settled above, so start it + # speculatively here and overlap it with the discovery and probe that + # `configure_shared_state` runs. A launch shape whose routing wouldn't read the catalog + # abandons the request on its daemon thread. + picker_catalog_future: Future | None = None + picker_catalog_started_profile: str | None = None + launch_only_auto_picker = ( + tool == AGENT_CLAUDE + and smart_routing_config.auto_mode_enabled() + and not smart_routing_v2.claude_print_mode(ctx.args) + and _routes_launch( + tool, + ctx.args, + smart_routing_enabled=smart_routing_enabled, + explicit_prompt=explicit_prompt, + model=model or forwarded_model, + provider=provider, + ) + ) + unmanaged_picker_catalog = ( + tool == "claude" + and managed is None + and not provider + and not parent_schema + and family_defaults is None + and not launch_only_auto_picker + ) + # Provider launches resolve their service first: a relayed one skips this catalog + # (`relayed` below), and that's only known after a lookup, so only a source that + # never relays — a Unity Catalog location — starts the catalog here. + scoped_picker_catalog = ( + tool == "claude" + and not provider + and bool(managed_parent_schema or (managed is None and bool(parent_schema))) + ) + if unmanaged_picker_catalog or scoped_picker_catalog: + picker_catalog_started_profile = _get_catalog_profile(state) + # A token fetched before `configure_shared_state`'s auth check can fail on stale + # credentials the auth step below would repair; skip the speculation and let the + # normal path recover rather than changing that flow. + try: + picker_catalog_token = get_databricks_token( + state["workspace"], picker_catalog_started_profile + ) + except Exception: + picker_catalog_started_profile = None + else: + picker_catalog_future = _start_in_background( + list_anthropic_model_catalog, + state["workspace"], + picker_catalog_token, + **( + {} + if unmanaged_picker_catalog + else {"provider": provider} + if provider + else {"parent_schema": parent_schema} + ), + ) state = configure_shared_state( state["workspace"], profile=state.get("profile"), @@ -4487,12 +4592,18 @@ def _launch_tool( ) ) if should_fetch_claude_picker_catalog: - token = get_databricks_token(state["workspace"], catalog_profile) - picker_catalog = list_anthropic_model_catalog( - state["workspace"], - token, - **({"provider": provider} if provider else {"parent_schema": parent_schema}), - ) + if ( + picker_catalog_future is not None + and picker_catalog_started_profile == catalog_profile + ): + picker_catalog = picker_catalog_future.result() + else: + token = get_databricks_token(state["workspace"], catalog_profile) + picker_catalog = list_anthropic_model_catalog( + state["workspace"], + token, + **({"provider": provider} if provider else {"parent_schema": parent_schema}), + ) error = picker_catalog.error_msg if error: if provider: @@ -4595,33 +4706,19 @@ def _launch_tool( resolved_model = model if model and tool == "claude" and not provider and not claude_inputs_from_configure: route_root_model = None - launch_only_auto_picker = ( - tool == AGENT_CLAUDE - and smart_routing_config.auto_mode_enabled() - and not smart_routing_v2.claude_print_mode(ctx.args) - and _routes_launch( - tool, - ctx.args, - smart_routing_enabled=smart_routing_enabled, - explicit_prompt=explicit_prompt, - model=model or forwarded_model, - provider=provider, - ) - ) # List the gateway's models in ug's own /model picker so GPT rows get the `[1m]` hint. # Claude Code's own discovery lists them without it, so they would run at 200K. - if ( - tool == "claude" - and managed is None - and not provider - and not parent_schema - and family_defaults is None - and not launch_only_auto_picker - ): - discovered = list_anthropic_model_catalog( - state["workspace"], - get_databricks_token(state["workspace"], catalog_profile), - ) + if unmanaged_picker_catalog: + if ( + picker_catalog_future is not None + and picker_catalog_started_profile == catalog_profile + ): + discovered = picker_catalog_future.result() + else: + discovered = list_anthropic_model_catalog( + state["workspace"], + get_databricks_token(state["workspace"], catalog_profile), + ) if discovered.model_ids: picker_catalog = claude_agent.default_model_picker_catalog( state.get("claude_models") or {}, diff --git a/tests/test_cli.py b/tests/test_cli.py index 0ba931c0f..7bc6fc649 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -4,6 +4,7 @@ import base64 import contextlib +from concurrent.futures import Future import json import os import re @@ -6566,6 +6567,7 @@ def fake_configure_shared_state( use_pat=False, databricks_ai_tools_enabled=None, clear_custom_oauth=False, + **_kwargs, ): captured["workspace"] = workspace captured["profile"] = profile @@ -7896,21 +7898,31 @@ def test_skip_model_discovery_never_starts_the_listing(self, monkeypatch): cli_mod, *_ = TestConfigureSharedStateUsePat._stub_deps(monkeypatch, pat_token=None) started: list[object] = [] listings: list[str] = [] - monkeypatch.setattr(cli_mod, "_start_in_background", lambda fn, *args: started.append(fn)) + + def fake_start(fn, *args): + started.append(fn) + future: Future = Future() + future.set_result(results[fn]) + return future + + monkeypatch.setattr(cli_mod, "_start_in_background", fake_start) monkeypatch.setattr( cli_mod, "discover_model_services", lambda w, t: listings.append(w) or ({}, [], [], [], None), ) - monkeypatch.setattr( - cli_mod, "discover_codex_models", lambda w, t: (["system.ai.gpt-5"], None) - ) + def web_search_lookup(w, t): + return (["system.ai.gpt-5"], None) + + monkeypatch.setattr(cli_mod, "discover_codex_models", web_search_lookup) + results = {web_search_lookup: (["system.ai.gpt-5"], None)} state = cli_mod.configure_shared_state( self.WS, profile="DEFAULT", tools=["claude"], skip_model_discovery=True ) - assert started == [] + # Only the web-search lookup runs; the family listing never starts. + assert started == [web_search_lookup] assert listings == [] # Provider mode keeps its separate single-call web-search lookup. assert state["web_search_model"] == "system.ai.gpt-5" @@ -7950,6 +7962,254 @@ def fake_get(url, token, **kwargs): assert len(requests) == 2 +class TestConfigureSharedStateOverlapsWebSearchAndCopilotCatalog: + """The provider-mode web-search lookup and the Copilot catalog listing also run while the + gateway probe is in flight, so a slow round trip doesn't queue behind another.""" + + WS = "https://example.databricks.com" + WAIT_SECONDS = 5 + + def test_web_search_lookup_runs_while_probe_is_in_flight(self, monkeypatch): + cli_mod, *_ = TestConfigureSharedStateUsePat._stub_deps(monkeypatch, pat_token=None) + lookup_started = threading.Event() + + def lookup(workspace, token): + lookup_started.set() + return ["system.ai.gpt-5"], None + + def probe(workspace, token): + assert lookup_started.wait(self.WAIT_SECONDS), "web-search lookup did not overlap" + return MODEL_SERVICE_PROBE + + monkeypatch.setattr(cli_mod, "discover_codex_models", lookup) + monkeypatch.setattr(cli_mod, "probe_unity_gateway_capabilities", probe) + + state = cli_mod.configure_shared_state( + self.WS, profile="DEFAULT", tools=["claude"], skip_model_discovery=True + ) + + assert state["web_search_model"] == "system.ai.gpt-5" + + def test_probe_failure_does_not_wait_for_web_search_lookup(self, monkeypatch): + cli_mod, *_ = TestConfigureSharedStateUsePat._stub_deps(monkeypatch, pat_token=None) + lookup_started = threading.Event() + release_lookup = threading.Event() + lookup_threads: list[threading.Thread] = [] + + def lookup(workspace, token): + lookup_threads.append(threading.current_thread()) + lookup_started.set() + release_lookup.wait(self.WAIT_SECONDS) + return ["system.ai.gpt-5"], None + + def probe(workspace, token): + assert lookup_started.wait(self.WAIT_SECONDS), "web-search lookup did not overlap" + raise RuntimeError("probe exploded") + + monkeypatch.setattr(cli_mod, "discover_codex_models", lookup) + monkeypatch.setattr(cli_mod, "probe_unity_gateway_capabilities", probe) + + try: + with pytest.raises(RuntimeError, match="probe exploded"): + cli_mod.configure_shared_state( + self.WS, profile="DEFAULT", tools=["claude"], skip_model_discovery=True + ) + assert [thread.daemon for thread in lookup_threads] == [True] + finally: + release_lookup.set() + for thread in lookup_threads: + thread.join(self.WAIT_SECONDS) + + def test_web_search_and_probe_delays_overlap_in_wall_clock_time(self, monkeypatch): + cli_mod, *_ = TestConfigureSharedStateUsePat._stub_deps(monkeypatch, pat_token=None) + delay = 0.3 + + def lookup(workspace, token): + time.sleep(delay) + return ["system.ai.gpt-5"], None + + def probe(workspace, token): + time.sleep(delay) + return MODEL_SERVICE_PROBE + + monkeypatch.setattr(cli_mod, "discover_codex_models", lookup) + monkeypatch.setattr(cli_mod, "probe_unity_gateway_capabilities", probe) + + started = time.perf_counter() + state = cli_mod.configure_shared_state( + self.WS, profile="DEFAULT", tools=["claude"], skip_model_discovery=True + ) + elapsed = time.perf_counter() - started + + assert state["web_search_model"] == "system.ai.gpt-5" + assert elapsed < delay * 2, f"lookups ran serially ({elapsed:.2f}s)" + + def test_copilot_catalog_runs_while_probe_is_in_flight(self, monkeypatch): + cli_mod, *_ = TestConfigureSharedStateUsePat._stub_deps(monkeypatch, pat_token=None) + catalog_started = threading.Event() + + def catalog(workspace, token): + catalog_started.set() + return db_mod.AnthropicModelCatalog( + model_ids=["claude-sonnet-5"], + model_id_to_display_name={"claude-sonnet-5": "Claude Sonnet 5"}, + ) + + def probe(workspace, token): + assert catalog_started.wait(self.WAIT_SECONDS), "catalog did not overlap the probe" + return MODEL_SERVICE_PROBE + + monkeypatch.setattr(cli_mod, "list_anthropic_model_catalog", catalog) + monkeypatch.setattr(cli_mod, "probe_unity_gateway_capabilities", probe) + + state = cli_mod.configure_shared_state(self.WS, profile="DEFAULT", tools=["copilot"]) + + assert state[copilot_agent.CATALOG_STATE_KEY] is not None + + def test_skip_preflight_starts_no_lookups(self, monkeypatch): + cli_mod, *_ = TestConfigureSharedStateUsePat._stub_deps(monkeypatch, pat_token=None) + started: list[object] = [] + monkeypatch.setattr(cli_mod, "_start_in_background", lambda fn, *args: started.append(fn)) + + cli_mod.configure_shared_state( + self.WS, profile="DEFAULT", tools=["claude"], skip_preflight=True + ) + + assert started == [] + + +class TestLaunchOverlapsPickerCatalogWithConfigure: + """The Anthropic picker catalog is settled by inputs known before `configure_shared_state` + runs, so the launch starts it speculatively and reads the result where it always did.""" + + WS = "https://example.databricks.com" + WAIT_SECONDS = 5 + + @staticmethod + def _invoke_with_overlapped_catalog( + monkeypatch, *, managed, argv=("claude",), persisted_provider=None + ): + state = dict(MINIMAL_STATE) + catalog_started = threading.Event() + release_catalog = threading.Event() + catalog_threads: list[threading.Thread] = [] + configure_done = threading.Event() + catalog_during_configure = threading.Event() + picker_catalog = db_mod.AnthropicModelCatalog( + model_ids=["main.default.claude-sonnet-5"], + model_id_to_display_name={"main.default.claude-sonnet-5": "Claude Sonnet 5"}, + ) + + def fake_catalog(*_args, **_kwargs): + catalog_threads.append(threading.current_thread()) + catalog_started.set() + release_catalog.wait(TestLaunchOverlapsPickerCatalogWithConfigure.WAIT_SECONDS) + return picker_catalog + + def fake_configure_shared_state(*_args, **_kwargs): + assert catalog_started.wait( + TestLaunchOverlapsPickerCatalogWithConfigure.WAIT_SECONDS + ), "picker catalog did not start during configure" + catalog_during_configure.set() + return state + + configure = MagicMock( + side_effect=lambda _tool, configured, *_args, **_kwargs: configured + ) + launch = MagicMock() + monkeypatch.setattr(cli_mod, "ensure_bootstrap_dependencies", lambda *_a, **_k: None) + monkeypatch.setattr(cli_mod, "load_state", lambda: state) + monkeypatch.setattr(cli_mod, "ensure_provider_state", lambda *_a: state) + monkeypatch.setattr(cli_mod, "_fetch_managed_config", lambda _state: (managed, False)) + monkeypatch.setattr( + cli_mod, "get_provider_service", lambda _state, _tool: persisted_provider + ) + monkeypatch.setattr(cli_mod, "get_databricks_token", lambda *_a: "token") + monkeypatch.setattr(cli_mod, "configure_shared_state", fake_configure_shared_state) + monkeypatch.setattr(cli_mod, "resolve_provider_models", lambda *a, **k: (None, None, False)) + monkeypatch.setattr(cli_mod, "list_anthropic_model_catalog", fake_catalog) + monkeypatch.setattr(cli_mod, "configure_tool", configure) + monkeypatch.setattr(cli_mod, "launch_agent", launch) + + try: + result = runner.invoke(app, list(argv)) + finally: + release_catalog.set() + for thread in catalog_threads: + thread.join(TestLaunchOverlapsPickerCatalogWithConfigure.WAIT_SECONDS) + + return { + "result": result, + "state": state, + "configure": configure, + "launch": launch, + "picker_catalog": picker_catalog, + "catalog_during_configure": catalog_during_configure, + "catalog_thread": catalog_threads[0] if catalog_threads else None, + } + + def test_unmanaged_picker_catalog_starts_during_configure(self, monkeypatch): + calls = self._invoke_with_overlapped_catalog( + monkeypatch, managed=None, persisted_provider=None + ) + + assert calls["result"].exit_code == 0, calls["result"].output + assert calls["catalog_during_configure"].is_set() + assert calls["catalog_thread"] is not None and calls["catalog_thread"].daemon + + def test_scoped_picker_catalog_starts_during_configure(self, monkeypatch): + managed = { + "enabled_agents": { + "claude": {"model_config": {"unity_catalog_location": "main.default"}} + } + } + calls = self._invoke_with_overlapped_catalog(monkeypatch, managed=managed) + + assert calls["result"].exit_code == 0, calls["result"].output + assert calls["catalog_during_configure"].is_set() + + def test_overlapped_catalog_feeds_configure_tool_unchanged(self, monkeypatch): + calls = self._invoke_with_overlapped_catalog(monkeypatch, managed=None) + + assert "main.default.claude-sonnet-5" in ( + calls["configure"].call_args.kwargs["picker_catalog"].model_ids + ) + + def test_catalog_error_still_fails_the_launch(self, monkeypatch): + state = dict(MINIMAL_STATE) + error_catalog = db_mod.AnthropicModelCatalog( + model_ids=[], model_id_to_display_name={}, error_msg="HTTP 403 Forbidden" + ) + monkeypatch.setattr(cli_mod, "ensure_bootstrap_dependencies", lambda *_a, **_k: None) + monkeypatch.setattr(cli_mod, "load_state", lambda: state) + monkeypatch.setattr(cli_mod, "ensure_provider_state", lambda *_a: state) + managed = { + "enabled_agents": { + "claude": {"model_config": {"unity_catalog_location": "main.default"}} + } + } + monkeypatch.setattr(cli_mod, "_fetch_managed_config", lambda _state: (managed, False)) + monkeypatch.setattr(cli_mod, "get_databricks_token", lambda *_a: "token") + monkeypatch.setattr( + cli_mod, "configure_shared_state", MagicMock(return_value=state) + ) + monkeypatch.setattr(cli_mod, "resolve_provider_models", lambda *a, **k: (None, None, False)) + monkeypatch.setattr( + cli_mod, + "list_anthropic_model_catalog", + MagicMock(return_value=error_catalog), + ) + monkeypatch.setattr(cli_mod, "configure_tool", MagicMock()) + monkeypatch.setattr(cli_mod, "launch_agent", MagicMock()) + + result = runner.invoke(app, ["claude"]) + + assert result.exit_code == 1 + assert "Could not discover Claude models for Unity Catalog location main.default" in ( + result.output + ) + + class TestConfigureNoLongerValidates: @pytest.fixture(autouse=True) def _no_managed_config(self, monkeypatch): From 68cefccdc313d782c8c92cd639648737ab045271 Mon Sep 17 00:00:00 2001 From: John Speaks Date: Fri, 20 Nov 2026 01:17:01 +0000 Subject: [PATCH 2/4] Guard the overlapped policy fetch and speculative catalog The background policy refresh now checks an abort flag before every write, and a configure that fails while the read is in flight sets it, so a failed configure or a Ctrl-C can no longer install or write machine state from a daemon thread. The refresh's warnings are captured and printed at the join, keeping output order as the serial flow had it. The speculative picker catalog joins only when its result is healthy: a catalog error from the pre-auth token is discarded and the launch refetches with the live token instead of failing or dropping the picker. The provider-mode web-search and Copilot listings fall back to inline fetches instead of asserting on their futures. Co-authored-by: Isaac --- src/ucode/cli.py | 157 +++++++++++++++----- src/ucode/managed_config.py | 33 ++++- src/ucode/ui/__init__.py | 18 +++ tests/test_claude_search_discovery.py | 2 +- tests/test_cli.py | 206 ++++++++++++++++++++++++-- tests/test_managed_config.py | 33 +++++ 6 files changed, 390 insertions(+), 59 deletions(-) diff --git a/src/ucode/cli.py b/src/ucode/cli.py index 7bdb380ed..86cb56d9a 100644 --- a/src/ucode/cli.py +++ b/src/ucode/cli.py @@ -245,6 +245,7 @@ from ucode.string_utils import is_valid_catalog_schema, is_valid_catalog_schema_name from ucode.ug_headers import CODING_AGENT_HEADER, parse_header_line, without_header from ucode.ui import ( + captured_warnings, console, heading, print_err, @@ -847,9 +848,12 @@ def configure_shared_state( # search (claude only) still needs one Responses-capable model, so fetch # just that with a single call. if want_claude: - assert web_search_discovery is not None with spinner("Fetching available models..."): - ws_models, _ = web_search_discovery.result() + ws_models, _ = ( + web_search_discovery.result() + if web_search_discovery is not None + else discover_codex_models(workspace, token) + ) if ws_models: web_search_model = ws_models[0] else: @@ -876,11 +880,15 @@ def configure_shared_state( if want_oss: oss_models, oss_reason = ms_oss, ms_reason if want_copilot: - assert copilot_catalog_discovery is not None + copilot_gateway_catalog = ( + copilot_catalog_discovery.result() + if copilot_catalog_discovery is not None + else list_anthropic_model_catalog(workspace, token) + ) copilot_models = copilot_agent.catalog_from_listings( cached_model_service_entries(workspace), [*claude_models.values(), *codex_models], - copilot_catalog_discovery.result(), + copilot_gateway_catalog, ) copilot_reason = ms_reason or claude_reason or codex_reason if claude_models: @@ -1044,20 +1052,46 @@ def _save_headless_model_source( return state -def _refresh_configured_policy(state: dict) -> ManagedConfigResult: +def _refresh_configured_policy( + state: dict, *, should_install: Callable[[], bool] | None = None +) -> ManagedConfigResult: """Read and install the workspace policy for an explicit configure. Configure saves the selected workspace before the policy step. When that step cannot switch the machine (no administrator access), the machine stays managed for its installed workspace, so put the saved selection back on it: launches keep working there, and the error explains the switch. + ``should_install`` stops a background refresh before any write once its configure has failed. """ try: - return refresh_managed_config(state, force_refresh=True) + return refresh_managed_config(state, force_refresh=True, should_install=should_install) except ManagedPolicyInstallDenied: _keep_installed_workspace_selected(state) raise +def _refresh_configured_policy_job( + state: dict, should_install: Callable[[], bool] +) -> tuple[ManagedConfigResult, list[str]]: + """The policy refresh run concurrently with discovery, collecting its warnings for the main + thread so a live spinner is never redrawn over them.""" + with captured_warnings() as warnings: + try: + result = _refresh_configured_policy(state, should_install=should_install) + except BaseException: + # Configure is failing anyway; its spinner is gone, so surface the warnings now. + for message in warnings: + print_warning(message) + raise + return result, warnings + + +def _join_policy_refresh(future: Future) -> ManagedConfigResult: + result, warnings = future.result() + for message in warnings: + print_warning(message) + return result + + def _keep_installed_workspace_selected(state: dict) -> str | None: """Put the saved selection back on the machine's installed workspace when it differs. @@ -1193,25 +1227,35 @@ def _setup_single_agent( """ previous_workspace = state_workspace_key(load_state()) # The workspace policy doesn't depend on model discovery, so read the fresh policy while - # discovery runs instead of after it. - policy_future: Future[ManagedConfigResult] | None = None + # discovery runs instead of after it. The abort flag keeps a configure that fails while the + # read is in flight from installing anything: the refresh checks it before every write. + policy_future: Future | None = None + policy_aborted = threading.Event() def _start_fresh_policy_fetch(state: dict) -> None: nonlocal policy_future - if apply_managed and tool in _FRESH_POLICY_AGENTS: - policy_future = _start_in_background(_refresh_configured_policy, state) - - states = _configure_shared_workspace_states( - workspace_entries, - [tool], - force_login=True, - use_pat=use_pat, - databricks_ai_tools_enabled=databricks_ai_tools_enabled, - custom_oauth=custom_oauth, - clear_custom_oauth=custom_oauth is None, - claude_server_side_web_search=claude_server_side_web_search, - on_authenticated=_start_fresh_policy_fetch, - ) + if apply_managed and tool in _FRESH_POLICY_AGENTS and not policy_aborted.is_set(): + policy_future = _start_in_background( + _refresh_configured_policy_job, + state, + lambda: not policy_aborted.is_set(), + ) + + try: + states = _configure_shared_workspace_states( + workspace_entries, + [tool], + force_login=True, + use_pat=use_pat, + databricks_ai_tools_enabled=databricks_ai_tools_enabled, + custom_oauth=custom_oauth, + clear_custom_oauth=custom_oauth is None, + claude_server_side_web_search=claude_server_side_web_search, + on_authenticated=_start_fresh_policy_fetch, + ) + except BaseException: + policy_aborted.set() + raise state = states[0] parent_schema = None managed = None @@ -1219,7 +1263,11 @@ def _start_fresh_policy_fetch(state: dict) -> None: if apply_managed and tool in _FRESH_POLICY_AGENTS: # Explicit configure always reads the workspace policy fresh, so it can install it. if policy_future is not None: - managed, _ = policy_future.result() + try: + managed, _ = _join_policy_refresh(policy_future) + except BaseException: + policy_aborted.set() + raise else: managed, _ = _refresh_configured_policy(state) elif apply_managed: @@ -1523,24 +1571,36 @@ def _configure_workspace_command( ) return 0 - # The workspace policy doesn't depend on model discovery, so read it while that runs. - policy_future: Future[ManagedConfigResult] | None = None + # The workspace policy doesn't depend on model discovery, so read it while that runs. The + # abort flag keeps a configure that fails while the read is in flight from installing + # anything: the refresh checks it before every write. + policy_future: Future | None = None + policy_aborted = threading.Event() def _start_fresh_policy_fetch(authenticated_state: dict) -> None: nonlocal policy_future - policy_future = _start_in_background(_refresh_configured_policy, authenticated_state) - - states = _configure_shared_workspace_states( - workspace_entries, - selected_tools, - force_login=True, - use_pat=use_pat, - databricks_ai_tools_enabled=databricks_ai_tools_enabled, - custom_oauth=custom_oauth, - clear_custom_oauth=custom_oauth is None, - claude_server_side_web_search=claude_server_side_web_search, - on_authenticated=_start_fresh_policy_fetch, - ) + if not policy_aborted.is_set(): + policy_future = _start_in_background( + _refresh_configured_policy_job, + authenticated_state, + lambda: not policy_aborted.is_set(), + ) + + try: + states = _configure_shared_workspace_states( + workspace_entries, + selected_tools, + force_login=True, + use_pat=use_pat, + databricks_ai_tools_enabled=databricks_ai_tools_enabled, + custom_oauth=custom_oauth, + clear_custom_oauth=custom_oauth is None, + claude_server_side_web_search=claude_server_side_web_search, + on_authenticated=_start_fresh_policy_fetch, + ) + except BaseException: + policy_aborted.set() + raise state = states[0] save_state(state) @@ -1548,7 +1608,11 @@ def _start_fresh_policy_fetch(authenticated_state: dict) -> None: # now rather than prompting the developer to pick. Configure always reads fresh so it never # applies a config the admin has since changed. if policy_future is not None: - managed, _ = policy_future.result() + try: + managed, _ = _join_policy_refresh(policy_future) + except BaseException: + policy_aborted.set() + raise else: managed, _ = _refresh_configured_policy(state) refuse_user_scope_over_managed_config(state.get("workspace"), managed) @@ -4592,12 +4656,18 @@ def _launch_tool( ) ) if should_fetch_claude_picker_catalog: + picker_catalog = None if ( picker_catalog_future is not None and picker_catalog_started_profile == catalog_profile ): picker_catalog = picker_catalog_future.result() - else: + if picker_catalog.error_msg: + # The speculative request rode a token fetched before configure's auth step, + # so its failure may be stale credentials that step repaired; refetch with + # the live token rather than failing the launch on it. + picker_catalog = None + if picker_catalog is None: token = get_databricks_token(state["workspace"], catalog_profile) picker_catalog = list_anthropic_model_catalog( state["workspace"], @@ -4709,12 +4779,17 @@ def _launch_tool( # List the gateway's models in ug's own /model picker so GPT rows get the `[1m]` hint. # Claude Code's own discovery lists them without it, so they would run at 200K. if unmanaged_picker_catalog: + discovered = None if ( picker_catalog_future is not None and picker_catalog_started_profile == catalog_profile ): discovered = picker_catalog_future.result() - else: + if discovered.error_msg: + # Stale pre-auth credentials may have failed the speculative request; refetch + # with the live token instead of silently launching without the picker. + discovered = None + if discovered is None: discovered = list_anthropic_model_catalog( state["workspace"], get_databricks_token(state["workspace"], catalog_profile), diff --git a/src/ucode/managed_config.py b/src/ucode/managed_config.py index ef0aec97f..15792d49e 100644 --- a/src/ucode/managed_config.py +++ b/src/ucode/managed_config.py @@ -479,6 +479,10 @@ class ManagedPolicyInstallDenied(RuntimeError): """``ug configure`` could not install, replace, or remove the machine policy (e.g. no sudo).""" +class PolicyRefreshAborted(RuntimeError): + """A concurrent policy refresh gave up before writing because its configure failed.""" + + class ManagedConfigResult(NamedTuple): """The launch-path refresh outcome: the ``manifest`` to apply (None when absent or dropped) and ``feature_disabled``, True when the coding-agent-configs feature is off server-side.""" @@ -1041,7 +1045,12 @@ def _record_refresh( print_warning(f"Could not save the workspace policy refresh record: {exc}") -def refresh_managed_config(state: dict, *, force_refresh: bool = False) -> ManagedConfigResult: +def refresh_managed_config( + state: dict, + *, + force_refresh: bool = False, + should_install: Callable[[], bool] | None = None, +) -> ManagedConfigResult: """Read the workspace policy; a launch replays what ``ug configure`` saved. A launch reads the control plane only when nothing is saved for the workspace yet; it never @@ -1076,7 +1085,9 @@ def refresh_managed_config(state: dict, *, force_refresh: bool = False) -> Manag return ManagedConfigResult(saved, False) host = split_workspace_key(workspace)[0] if not _machine_policy_installable() and _installed_config(workspace) is None: - return _refresh_user_cache(state, workspace, force_refresh=force_refresh) + return _refresh_user_cache( + state, workspace, force_refresh=force_refresh, should_install=should_install + ) if config_io.is_dry_run() and not force_refresh: return ManagedConfigResult(load_managed_state(workspace), False) if not force_refresh: @@ -1100,9 +1111,11 @@ def refresh_managed_config(state: dict, *, force_refresh: bool = False) -> Manag normalize_managed_config(raw) if raw is not None else None, reason is not None and _is_feature_disabled(reason), ) + _check_install_allowed(should_install) _record_refresh(workspace, result) return result pending_config_hash = None + _check_install_allowed(should_install) try: save_managed_state( workspace, @@ -1165,6 +1178,7 @@ def refresh_managed_config(state: dict, *, force_refresh: bool = False) -> Manag normalize_managed_config(raw) if raw is not None else None, reason is not None and _is_feature_disabled(reason), ) + _check_install_allowed(should_install) _record_refresh(workspace, result, pending_config_hash=pending_config_hash) return result @@ -1177,6 +1191,12 @@ def _machine_policy_supported() -> bool: return current_os() in (OS.LINUX, OS.MACOS, OS.WINDOWS) +def _check_install_allowed(should_install: Callable[[], bool] | None) -> None: + """Stop a background refresh before it writes once its configure has failed.""" + if should_install is not None and not should_install(): + raise PolicyRefreshAborted("configure failed while the policy read was in flight") + + def _machine_policy_installable() -> bool: """Whether this machine can hold the installed workspace policy (Linux, macOS, or Windows, not opted out with ``UG_SKIP_OS_SETTINGS``).""" @@ -1189,7 +1209,13 @@ def _can_install_policy(explicit_configure: bool) -> bool: return _machine_policy_installable() and explicit_configure -def _refresh_user_cache(state: dict, workspace: str, *, force_refresh: bool) -> ManagedConfigResult: +def _refresh_user_cache( + state: dict, + workspace: str, + *, + force_refresh: bool, + should_install: Callable[[], bool] | None = None, +) -> ManagedConfigResult: """Cache policy per user when machine installation is unavailable. A launch replays the saved read and only reads the control plane when none is saved, @@ -1205,6 +1231,7 @@ def _refresh_user_cache(state: dict, workspace: str, *, force_refresh: bool) -> except RuntimeError as exc: return ManagedConfigResult(_persisted_fallback(workspace, str(exc)), False) raw, reason = get_managed_config(split_workspace_key(workspace)[0], token) + _check_install_allowed(should_install) if reason is not None: if _is_feature_disabled(reason): _save_user_cache(workspace, {}, outcome=_OUTCOME_FEATURE_DISABLED) diff --git a/src/ucode/ui/__init__.py b/src/ucode/ui/__init__.py index acd8abbfb..acacb0364 100644 --- a/src/ucode/ui/__init__.py +++ b/src/ucode/ui/__init__.py @@ -181,9 +181,27 @@ def print_success(message: str) -> None: def print_warning(message: str) -> None: + sink = getattr(_warning_sink, "messages", None) + if sink is not None: + sink.append(message) + return console.print(f"[bold yellow]![/bold yellow] {message}") +_warning_sink = threading.local() + + +@contextmanager +def captured_warnings() -> Iterator[list[str]]: + """Collect this thread's ``print_warning`` output instead of printing it.""" + messages: list[str] = [] + _warning_sink.messages = messages + try: + yield messages + finally: + _warning_sink.messages = None + + def print_warning_err(message: str) -> None: """``print_warning`` on stderr, for when stdout is a machine-read stream.""" err_console.print(f"[bold yellow]![/bold yellow] {message}") diff --git a/tests/test_claude_search_discovery.py b/tests/test_claude_search_discovery.py index f83f00d10..472b3ccf2 100644 --- a/tests/test_claude_search_discovery.py +++ b/tests/test_claude_search_discovery.py @@ -49,7 +49,7 @@ def search_setup(tmp_path, monkeypatch): "discover_model_services", lambda *_: ({"opus": CLAUDE_MODEL}, [SEARCH_MODEL], [], [], None), ) - monkeypatch.setattr(claude, "refresh_managed_config", lambda *_: SimpleNamespace(manifest=None)) + monkeypatch.setattr(claude, "refresh_managed_config", lambda *a, **_k: SimpleNamespace(manifest=None)) def run_claude(command, **kwargs): if command == ["claude", "--version"]: diff --git a/tests/test_cli.py b/tests/test_cli.py index 7bc6fc649..5e3d02ba9 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -25,6 +25,7 @@ import ucode.cli as cli_mod import ucode.databricks as db_mod +import ucode.managed_config as mc_mod import ucode.managed_files as managed_files from ucode import agents, tls from ucode.agents import copilot as copilot_agent @@ -1176,7 +1177,7 @@ def test_auto_version_survives_materialization_and_does_not_leak( monkeypatch.setenv("SMART_ROUTER_CONFIG_VERSION", version) managed = {"enabled_agents": {"claude": {"smart_routing_enabled": True}}} monkeypatch.setattr("ucode.cli.install_databricks_cli", lambda *a, **k: None) - monkeypatch.setattr("ucode.cli.refresh_managed_config", lambda state: (managed, False)) + monkeypatch.setattr("ucode.cli.refresh_managed_config", lambda state, **_k: (managed, False)) before = _routing_env() observed = [] with _launch_policy_patches(managed) as calls: @@ -1379,7 +1380,7 @@ def test_bare_launch_keeps_a_known_version_over_managed_smart_routing(self, monk monkeypatch.setenv("SMART_ROUTER_CONFIG_VERSION", smart_routing_config.SUBAGENT_ONLY_V0) managed = {"enabled_agents": {"claude": {"smart_routing_enabled": True}}} monkeypatch.setattr("ucode.cli.install_databricks_cli", lambda *a, **k: None) - monkeypatch.setattr("ucode.cli.refresh_managed_config", lambda state: (managed, False)) + monkeypatch.setattr("ucode.cli.refresh_managed_config", lambda state, **_k: (managed, False)) observed = [] with _launch_policy_patches(managed) as calls: @@ -1550,7 +1551,7 @@ def write_managed(path, text): monkeypatch.setattr(managed_files.sys.stdin, "isatty", lambda: True) monkeypatch.setattr(claude, "CLAUDE_BACKUP_PATH", tmp_path / "claude.backup") monkeypatch.setattr( - claude, "refresh_managed_config", lambda *a: SimpleNamespace(manifest=None) + claude, "refresh_managed_config", lambda *a, **_k: SimpleNamespace(manifest=None) ) monkeypatch.setattr(claude, "_resolve_web_search_model", lambda state: None) monkeypatch.setattr(claude, "save_state", lambda state: None) @@ -6154,7 +6155,7 @@ def test_single_codex_agent_passes_managed_parent_directly(self, monkeypatch): assert result.exit_code == 0, result.output assert "(Provider: Databricks)" in _strip_ansi(result.output) - refresh.assert_called_once_with(state, force_refresh=True) + refresh.assert_called_once_with(state, force_refresh=True, should_install=None) configure.assert_called_once_with( "codex", state, parent_schema="main.models", provider=None, with_vscode=True ) @@ -6223,7 +6224,7 @@ def test_single_copilot_agent_passes_managed_parent_directly(self, monkeypatch): assert result.exit_code == 0, result.output assert "(Provider: Databricks)" in _strip_ansi(result.output) - refresh.assert_called_once_with(state, force_refresh=True) + refresh.assert_called_once_with(state, force_refresh=True, should_install=None) configure.assert_called_once_with( "copilot", state, parent_schema="main.models", provider=None, with_vscode=True ) @@ -6259,7 +6260,7 @@ def test_single_codex_switch_reconciles_managed_mcps_before_restoring_saved_entr calls = [] monkeypatch.setattr(cli_mod, "load_state", lambda: {"workspace": "https://a.com"}) monkeypatch.setattr(cli_mod, "_configure_shared_workspace_states", lambda *a, **k: [state]) - monkeypatch.setattr(cli_mod, "_refresh_configured_policy", lambda state: (None, None)) + monkeypatch.setattr(cli_mod, "_refresh_configured_policy", lambda state, **_k: (None, None)) monkeypatch.setattr(cli_mod, "refuse_user_scope_over_managed_config", lambda *a: None) monkeypatch.setattr(cli_mod, "configure_single_tool", lambda *a, **k: state) monkeypatch.setattr(cli_mod, "_record_unmanaged_configured_agents", lambda s, t: s) @@ -8078,6 +8079,68 @@ def test_skip_preflight_starts_no_lookups(self, monkeypatch): assert started == [] +class TestFailedConfigureAbortsPolicyInstall: + """A configure that fails while its background policy read is in flight must not install + anything: the abort flag stops the refresh before every write.""" + + WS = "https://example.databricks.com" + + @staticmethod + def _run_failing_configure(monkeypatch, failure, block_fetch): + import ucode.managed_config as mc_mod + + def fake_configure_shared_state(workspace, *, on_authenticated=None, **_kwargs): + if on_authenticated is not None: + on_authenticated({"workspace": workspace, "profile": None}) + raise failure + + fetch_started = threading.Event() + + def blocked_fetch(ws, token): + fetch_started.set() + assert block_fetch.wait(5), "policy fetch was never released" + return {"enabled_agents": {}}, None + + installs: list = [] + monkeypatch.setattr(cli_mod, "load_state", lambda: {}) + monkeypatch.setattr(cli_mod, "configure_shared_state", fake_configure_shared_state) + monkeypatch.setattr(mc_mod, "get_managed_config", blocked_fetch) + monkeypatch.setattr(mc_mod, "get_databricks_token", lambda ws, profile: "tok") + monkeypatch.setattr(mc_mod, "published_agent_config_used", lambda: False) + monkeypatch.setattr(mc_mod, "_machine_policy_installable", lambda: False) + monkeypatch.setattr(mc_mod, "_installed_config", lambda workspace: None) + monkeypatch.setattr(mc_mod, "save_managed_state", lambda ws, cfg, **kw: installs.append(ws)) + + with pytest.raises(type(failure)): + cli_mod._setup_single_agent( + [(TestFailedConfigureAbortsPolicyInstall.WS, None)], + "claude", + apply_managed=True, + ) + + assert fetch_started.wait(5), "the policy fetch never ran" + block_fetch.set() + # The background refresh notices the abort at its write gate, after the fetch returns. + deadline = time.monotonic() + 5 + while time.monotonic() < deadline and not mc_mod.USER_MANAGED_CONFIG_PATH.exists(): + time.sleep(0.01) + return installs + + def test_discovery_failure_never_installs(self, monkeypatch): + installs = self._run_failing_configure( + monkeypatch, RuntimeError("discovery failed"), threading.Event() + ) + assert installs == [] + assert not mc_mod.USER_MANAGED_CONFIG_PATH.exists() + + def test_keyboard_interrupt_never_installs(self, monkeypatch): + installs = self._run_failing_configure( + monkeypatch, KeyboardInterrupt(), threading.Event() + ) + assert installs == [] + assert not mc_mod.USER_MANAGED_CONFIG_PATH.exists() + + class TestLaunchOverlapsPickerCatalogWithConfigure: """The Anthropic picker catalog is settled by inputs known before `configure_shared_state` runs, so the launch starts it speculatively and reads the result where it always did.""" @@ -8100,7 +8163,10 @@ def _invoke_with_overlapped_catalog( model_id_to_display_name={"main.default.claude-sonnet-5": "Claude Sonnet 5"}, ) + catalog_calls: list = [] + def fake_catalog(*_args, **_kwargs): + catalog_calls.append(threading.current_thread()) catalog_threads.append(threading.current_thread()) catalog_started.set() release_catalog.wait(TestLaunchOverlapsPickerCatalogWithConfigure.WAIT_SECONDS) @@ -8146,6 +8212,7 @@ def fake_configure_shared_state(*_args, **_kwargs): "picker_catalog": picker_catalog, "catalog_during_configure": catalog_during_configure, "catalog_thread": catalog_threads[0] if catalog_threads else None, + "catalog_calls": catalog_calls, } def test_unmanaged_picker_catalog_starts_during_configure(self, monkeypatch): @@ -8175,6 +8242,115 @@ def test_overlapped_catalog_feeds_configure_tool_unchanged(self, monkeypatch): calls["configure"].call_args.kwargs["picker_catalog"].model_ids ) + def test_joined_catalog_makes_exactly_one_request(self, monkeypatch): + calls = self._invoke_with_overlapped_catalog( + monkeypatch, managed=None, persisted_provider=None + ) + + assert calls["result"].exit_code == 0, calls["result"].output + assert len(calls["catalog_calls"]) == 1 + + def test_profile_mismatch_refetches_serially(self, monkeypatch): + state = dict(MINIMAL_STATE) + catalog_started = threading.Event() + release_catalog = threading.Event() + picker_catalog = db_mod.AnthropicModelCatalog( + model_ids=["main.default.claude-sonnet-5"], + model_id_to_display_name={"main.default.claude-sonnet-5": "Claude Sonnet 5"}, + ) + + def fake_catalog(*_args, **_kwargs): + catalog_started.set() + release_catalog.wait(self.WAIT_SECONDS) + return picker_catalog + + def fake_configure_shared_state(*_args, **_kwargs): + # Configure resolves a profile the speculation didn't know about. + assert catalog_started.wait(self.WAIT_SECONDS) + return {**state, "profile": "resolved-profile"} + + configure = MagicMock(side_effect=lambda _tool, configured, *_a, **_k: configured) + monkeypatch.setattr(cli_mod, "ensure_bootstrap_dependencies", lambda *_a, **_k: None) + monkeypatch.setattr(cli_mod, "load_state", lambda: state) + monkeypatch.setattr(cli_mod, "ensure_provider_state", lambda *_a: state) + monkeypatch.setattr(cli_mod, "_fetch_managed_config", lambda _state: (None, False)) + monkeypatch.setattr(cli_mod, "get_provider_service", lambda _s, _t: None) + monkeypatch.setattr(cli_mod, "get_databricks_token", lambda *_a: "token") + monkeypatch.setattr(cli_mod, "configure_shared_state", fake_configure_shared_state) + monkeypatch.setattr(cli_mod, "resolve_provider_models", lambda *a, **k: (None, None, False)) + monkeypatch.setattr(cli_mod, "list_anthropic_model_catalog", MagicMock(side_effect=fake_catalog)) + monkeypatch.setattr(cli_mod, "configure_tool", configure) + monkeypatch.setattr(cli_mod, "launch_agent", MagicMock()) + + try: + result = runner.invoke(app, ["claude"]) + finally: + release_catalog.set() + + assert result.exit_code == 0, result.output + # The speculative result was discarded, so the catalog was fetched twice. + assert cli_mod.list_anthropic_model_catalog.call_count == 2 + + def test_speculative_catalog_error_refetches_with_live_token(self, monkeypatch): + error_catalog = db_mod.AnthropicModelCatalog( + model_ids=[], model_id_to_display_name={}, error_msg="HTTP 401 Unauthorized" + ) + good_catalog = db_mod.AnthropicModelCatalog( + model_ids=["main.default.claude-sonnet-5"], + model_id_to_display_name={"main.default.claude-sonnet-5": "Claude Sonnet 5"}, + ) + state = dict(MINIMAL_STATE) + configure = MagicMock(side_effect=lambda _tool, configured, *_a, **_k: configured) + monkeypatch.setattr(cli_mod, "ensure_bootstrap_dependencies", lambda *_a, **_k: None) + monkeypatch.setattr(cli_mod, "load_state", lambda: state) + monkeypatch.setattr(cli_mod, "ensure_provider_state", lambda *_a: state) + monkeypatch.setattr(cli_mod, "_fetch_managed_config", lambda _state: (None, False)) + monkeypatch.setattr(cli_mod, "get_provider_service", lambda _s, _t: None) + monkeypatch.setattr(cli_mod, "get_databricks_token", lambda *_a: "token") + monkeypatch.setattr(cli_mod, "configure_shared_state", MagicMock(return_value=state)) + monkeypatch.setattr(cli_mod, "resolve_provider_models", lambda *a, **k: (None, None, False)) + monkeypatch.setattr( + cli_mod, + "list_anthropic_model_catalog", + MagicMock(side_effect=[error_catalog, good_catalog]), + ) + monkeypatch.setattr(cli_mod, "configure_tool", configure) + monkeypatch.setattr(cli_mod, "launch_agent", MagicMock()) + + result = runner.invoke(app, ["claude"]) + + assert result.exit_code == 0, result.output + assert cli_mod.list_anthropic_model_catalog.call_count == 2 + assert "main.default.claude-sonnet-5" in ( + configure.call_args.kwargs["picker_catalog"].model_ids + ) + + def test_relayed_provider_launch_starts_no_catalog(self, monkeypatch): + state = {**MINIMAL_STATE, "provider_services": {"claude": "main.default.relay"}} + monkeypatch.setattr(cli_mod, "ensure_bootstrap_dependencies", lambda *_a, **_k: None) + monkeypatch.setattr(cli_mod, "load_state", lambda: state) + monkeypatch.setattr(cli_mod, "ensure_provider_state", lambda *_a: state) + monkeypatch.setattr(cli_mod, "_fetch_managed_config", lambda _state: (None, False)) + monkeypatch.setattr( + cli_mod, "get_provider_service", lambda _s, _t: "main.default.relay" + ) + monkeypatch.setattr(cli_mod, "get_databricks_token", lambda *_a: "token") + monkeypatch.setattr(cli_mod, "configure_shared_state", MagicMock(return_value=state)) + monkeypatch.setattr( + cli_mod, "resolve_provider_models", lambda *a, **k: (None, None, True) + ) + monkeypatch.setattr( + cli_mod, + "list_anthropic_model_catalog", + MagicMock(side_effect=AssertionError("relayed launch must not fetch the catalog")), + ) + monkeypatch.setattr(cli_mod, "configure_tool", MagicMock()) + monkeypatch.setattr(cli_mod, "launch_agent", MagicMock()) + + result = runner.invoke(app, ["claude"]) + + assert result.exit_code == 0, result.output + def test_catalog_error_still_fails_the_launch(self, monkeypatch): state = dict(MINIMAL_STATE) error_catalog = db_mod.AnthropicModelCatalog( @@ -8330,7 +8506,7 @@ def test_explicit_configure_switch_restores_saved_mcp_entries( monkeypatch.setattr(state_mod, "APP_DIR", state_mod.STATE_PATH.parent) monkeypatch.setattr(state_mod, "build_agent_state", lambda state: {}) monkeypatch.setattr(cli_mod, "save_state", mcp.save_state) - monkeypatch.setattr(cli_mod, "_refresh_configured_policy", lambda state: (None, None)) + monkeypatch.setattr(cli_mod, "_refresh_configured_policy", lambda state, **_k: (None, None)) monkeypatch.setattr(cli_mod, "refuse_user_scope_over_managed_files", lambda tools: None) monkeypatch.setattr(cli_mod, "refuse_user_scope_over_managed_config", lambda *args: None) monkeypatch.setattr(cli_mod, "check_gateway_endpoint", lambda state, tool: True) @@ -9072,7 +9248,9 @@ def test_only_claude_and_codex_force_the_policy_read(self, monkeypatch, tool, fo monkeypatch.setattr( cli_mod, "refresh_managed_config", - lambda state, force_refresh=False: calls.append(force_refresh) or (None, False), + lambda state, force_refresh=False, **_k: ( + calls.append(force_refresh) or (None, False) + ), ) monkeypatch.setattr(cli_mod, "configure_single_tool", lambda tool, state, **k: state) monkeypatch.setattr(cli_mod, "_record_unmanaged_configured_agents", lambda s, t: s) @@ -9260,12 +9438,12 @@ def _fetch(state): def test_fetches_fresh_when_enabled(self, monkeypatch): monkeypatch.setattr( - "ucode.cli.refresh_managed_config", lambda state: ({"enabled_agents": {}}, False) + "ucode.cli.refresh_managed_config", lambda state, **_k: ({"enabled_agents": {}}, False) ) assert self._fetch({"workspace": "https://w"}) == ({"enabled_agents": {}}, False) def test_feature_disabled_returns_none_and_the_flag(self, monkeypatch): - monkeypatch.setattr("ucode.cli.refresh_managed_config", lambda state: (None, True)) + monkeypatch.setattr("ucode.cli.refresh_managed_config", lambda state, **_k: (None, True)) assert self._fetch({"workspace": "https://w"}) == (None, True) @@ -9282,7 +9460,7 @@ def test_a_removed_model_list_no_longer_skips_discovery(self, monkeypatch): } fresh = {"enabled_agents": {"claude": {"model_config": {}}}} monkeypatch.setattr("ucode.cli.load_managed_state", lambda ws: stale_cache) - monkeypatch.setattr("ucode.cli.refresh_managed_config", lambda state: (fresh, False)) + monkeypatch.setattr("ucode.cli.refresh_managed_config", lambda state, **_k: (fresh, False)) state = dict(MINIMAL_STATE) with ( @@ -9321,9 +9499,9 @@ def _run( monkeypatch.setattr("ucode.cli.load_state", lambda: {"workspace": "https://w"}) if coding_agent_config_feature_disabled: - monkeypatch.setattr("ucode.cli.refresh_managed_config", lambda state: (None, True)) + monkeypatch.setattr("ucode.cli.refresh_managed_config", lambda state, **_k: (None, True)) else: - monkeypatch.setattr("ucode.cli.refresh_managed_config", lambda state: (managed, False)) + monkeypatch.setattr("ucode.cli.refresh_managed_config", lambda state, **_k: (managed, False)) monkeypatch.setattr("ucode.cli.load_managed_state", lambda ws: cached) monkeypatch.setattr( @@ -9454,7 +9632,7 @@ def test_skip_preflight_still_resolves_an_agent_from_the_managed_config(self, mo "default_agent": "claude", "enabled_agents": {"claude": {"model_config": {"default_model": "m"}}}, } - monkeypatch.setattr("ucode.cli.refresh_managed_config", lambda state: (managed, False)) + monkeypatch.setattr("ucode.cli.refresh_managed_config", lambda state, **_k: (managed, False)) monkeypatch.setattr("ucode.cli._fetch_budget_recommendation", lambda state, m: None) monkeypatch.setattr("ucode.cli._print_managed_summary", lambda *a, **k: None) seen: dict = {} diff --git a/tests/test_managed_config.py b/tests/test_managed_config.py index 2f522d0e2..a50225317 100644 --- a/tests/test_managed_config.py +++ b/tests/test_managed_config.py @@ -2257,3 +2257,36 @@ def test_windows_saves_machine_wide(self, monkeypatch): assert self._saved() == {"mdm_os": "Windows"} assert not mc_mod.USER_MANAGED_CONFIG_PATH.exists() assert mc_mod.saved_mdm_os() == "Windows" + + +class TestRefreshInstallGuard: + """A configure that failed while its background policy read was in flight aborts the read + before it writes anything (see _setup_single_agent's abort flag).""" + + @pytest.fixture(autouse=True) + def _stub_token(self, monkeypatch): + monkeypatch.setattr(mc_mod, "get_databricks_token", lambda ws, profile: "tok") + + def test_aborted_guard_writes_nothing(self, monkeypatch): + saved: list = [] + monkeypatch.setattr(mc_mod, "get_managed_config", lambda ws, tok: (RAW_MANIFEST, None)) + monkeypatch.setattr( + mc_mod, "save_managed_state", lambda ws, cfg, **kwargs: saved.append((ws, cfg)) + ) + + with pytest.raises(mc_mod.PolicyRefreshAborted): + refresh_managed_config(_state(), force_refresh=True, should_install=lambda: False) + + assert saved == [] + + def test_passing_guard_installs_as_usual(self, monkeypatch): + saved: list = [] + monkeypatch.setattr(mc_mod, "get_managed_config", lambda ws, tok: (RAW_MANIFEST, None)) + monkeypatch.setattr( + mc_mod, "save_managed_state", lambda ws, cfg, **kwargs: saved.append((ws, cfg)) + ) + + result = refresh_managed_config(_state(), force_refresh=True, should_install=lambda: True) + + assert result == (normalize_managed_config(RAW_MANIFEST), False) + assert saved == [(WORKSPACE, RAW_MANIFEST)] From 26d1f1c361a66f936c890a6dc5fd5e497578e70e Mon Sep 17 00:00:00 2001 From: John Speaks Date: Fri, 20 Nov 2026 01:51:53 +0000 Subject: [PATCH 3/4] Collect policy refresh warnings into a shared list The job appends its captured warnings even when the refresh raises, and the join prints the list, so a failing refresh surfaces its warnings without the worker thread ever touching the console. Co-authored-by: Isaac --- src/ucode/cli.py | 35 ++++++++++++++++++----------------- tests/test_cli.py | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 55 insertions(+), 17 deletions(-) diff --git a/src/ucode/cli.py b/src/ucode/cli.py index 86cb56d9a..5829be71e 100644 --- a/src/ucode/cli.py +++ b/src/ucode/cli.py @@ -1070,26 +1070,23 @@ def _refresh_configured_policy( def _refresh_configured_policy_job( - state: dict, should_install: Callable[[], bool] -) -> tuple[ManagedConfigResult, list[str]]: + state: dict, should_install: Callable[[], bool], warnings: list[str] +) -> ManagedConfigResult: """The policy refresh run concurrently with discovery, collecting its warnings for the main thread so a live spinner is never redrawn over them.""" - with captured_warnings() as warnings: + with captured_warnings() as captured: try: - result = _refresh_configured_policy(state, should_install=should_install) - except BaseException: - # Configure is failing anyway; its spinner is gone, so surface the warnings now. - for message in warnings: - print_warning(message) - raise - return result, warnings + return _refresh_configured_policy(state, should_install=should_install) + finally: + warnings.extend(captured) -def _join_policy_refresh(future: Future) -> ManagedConfigResult: - result, warnings = future.result() - for message in warnings: - print_warning(message) - return result +def _join_policy_refresh(future: Future, warnings: list[str]) -> ManagedConfigResult: + try: + return future.result() + finally: + for message in warnings: + print_warning(message) def _keep_installed_workspace_selected(state: dict) -> str | None: @@ -1231,6 +1228,7 @@ def _setup_single_agent( # read is in flight from installing anything: the refresh checks it before every write. policy_future: Future | None = None policy_aborted = threading.Event() + policy_warnings: list[str] = [] def _start_fresh_policy_fetch(state: dict) -> None: nonlocal policy_future @@ -1239,6 +1237,7 @@ def _start_fresh_policy_fetch(state: dict) -> None: _refresh_configured_policy_job, state, lambda: not policy_aborted.is_set(), + policy_warnings, ) try: @@ -1264,7 +1263,7 @@ def _start_fresh_policy_fetch(state: dict) -> None: # Explicit configure always reads the workspace policy fresh, so it can install it. if policy_future is not None: try: - managed, _ = _join_policy_refresh(policy_future) + managed, _ = _join_policy_refresh(policy_future, policy_warnings) except BaseException: policy_aborted.set() raise @@ -1576,6 +1575,7 @@ def _configure_workspace_command( # anything: the refresh checks it before every write. policy_future: Future | None = None policy_aborted = threading.Event() + policy_warnings: list[str] = [] def _start_fresh_policy_fetch(authenticated_state: dict) -> None: nonlocal policy_future @@ -1584,6 +1584,7 @@ def _start_fresh_policy_fetch(authenticated_state: dict) -> None: _refresh_configured_policy_job, authenticated_state, lambda: not policy_aborted.is_set(), + policy_warnings, ) try: @@ -1609,7 +1610,7 @@ def _start_fresh_policy_fetch(authenticated_state: dict) -> None: # applies a config the admin has since changed. if policy_future is not None: try: - managed, _ = _join_policy_refresh(policy_future) + managed, _ = _join_policy_refresh(policy_future, policy_warnings) except BaseException: policy_aborted.set() raise diff --git a/tests/test_cli.py b/tests/test_cli.py index 5e3d02ba9..875e9118c 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -8141,6 +8141,43 @@ def test_keyboard_interrupt_never_installs(self, monkeypatch): assert not mc_mod.USER_MANAGED_CONFIG_PATH.exists() +class TestPolicyRefreshWarningsPrintAtJoin: + """The background policy refresh collects its warnings instead of printing over a live + spinner; the join prints them on the main thread in the old serial order.""" + + def test_warnings_are_captured_then_printed_at_join(self, monkeypatch, capsys): + def refresh_with_warning(state, *, should_install=None): + cli_mod.print_warning("policy changed upstream") + return ManagedConfigResult(None, False) + + monkeypatch.setattr(cli_mod, "_refresh_configured_policy", refresh_with_warning) + warnings: list[str] = [] + future = cli_mod._start_in_background( + cli_mod._refresh_configured_policy_job, {}, lambda: True, warnings + ) + + result = cli_mod._join_policy_refresh(future, warnings) + + assert result == (None, False) + assert "policy changed upstream" in capsys.readouterr().out + + def test_failed_refresh_prints_its_warnings_before_raising(self, monkeypatch, capsys): + def failing_refresh(state, *, should_install=None): + cli_mod.print_warning("policy changed upstream") + raise RuntimeError("install denied") + + monkeypatch.setattr(cli_mod, "_refresh_configured_policy", failing_refresh) + warnings: list[str] = [] + future = cli_mod._start_in_background( + cli_mod._refresh_configured_policy_job, {}, lambda: True, warnings + ) + + with pytest.raises(RuntimeError, match="install denied"): + cli_mod._join_policy_refresh(future, warnings) + + assert "policy changed upstream" in capsys.readouterr().out + + class TestLaunchOverlapsPickerCatalogWithConfigure: """The Anthropic picker catalog is settled by inputs known before `configure_shared_state` runs, so the launch starts it speculatively and reads the result where it always did.""" From b8c3fafc8a2706f98fecc8ae0e3796a4765c9dac Mon Sep 17 00:00:00 2001 From: John Speaks Date: Fri, 20 Nov 2026 14:04:04 +0000 Subject: [PATCH 4/4] Fix ruff findings on the overlap branch Co-authored-by: Isaac --- tests/test_claude_search_discovery.py | 4 ++- tests/test_cli.py | 52 +++++++++++++-------------- 2 files changed, 29 insertions(+), 27 deletions(-) diff --git a/tests/test_claude_search_discovery.py b/tests/test_claude_search_discovery.py index 472b3ccf2..47c5b4188 100644 --- a/tests/test_claude_search_discovery.py +++ b/tests/test_claude_search_discovery.py @@ -49,7 +49,9 @@ def search_setup(tmp_path, monkeypatch): "discover_model_services", lambda *_: ({"opus": CLAUDE_MODEL}, [SEARCH_MODEL], [], [], None), ) - monkeypatch.setattr(claude, "refresh_managed_config", lambda *a, **_k: SimpleNamespace(manifest=None)) + monkeypatch.setattr( + claude, "refresh_managed_config", lambda *a, **_k: SimpleNamespace(manifest=None) + ) def run_claude(command, **kwargs): if command == ["claude", "--version"]: diff --git a/tests/test_cli.py b/tests/test_cli.py index 875e9118c..466142f80 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -4,7 +4,6 @@ import base64 import contextlib -from concurrent.futures import Future import json import os import re @@ -13,6 +12,7 @@ import threading import time import tomllib +from concurrent.futures import Future from importlib import metadata from pathlib import Path from unittest.mock import MagicMock, call, patch @@ -1177,7 +1177,9 @@ def test_auto_version_survives_materialization_and_does_not_leak( monkeypatch.setenv("SMART_ROUTER_CONFIG_VERSION", version) managed = {"enabled_agents": {"claude": {"smart_routing_enabled": True}}} monkeypatch.setattr("ucode.cli.install_databricks_cli", lambda *a, **k: None) - monkeypatch.setattr("ucode.cli.refresh_managed_config", lambda state, **_k: (managed, False)) + monkeypatch.setattr( + "ucode.cli.refresh_managed_config", lambda state, **_k: (managed, False) + ) before = _routing_env() observed = [] with _launch_policy_patches(managed) as calls: @@ -1380,7 +1382,9 @@ def test_bare_launch_keeps_a_known_version_over_managed_smart_routing(self, monk monkeypatch.setenv("SMART_ROUTER_CONFIG_VERSION", smart_routing_config.SUBAGENT_ONLY_V0) managed = {"enabled_agents": {"claude": {"smart_routing_enabled": True}}} monkeypatch.setattr("ucode.cli.install_databricks_cli", lambda *a, **k: None) - monkeypatch.setattr("ucode.cli.refresh_managed_config", lambda state, **_k: (managed, False)) + monkeypatch.setattr( + "ucode.cli.refresh_managed_config", lambda state, **_k: (managed, False) + ) observed = [] with _launch_policy_patches(managed) as calls: @@ -7912,6 +7916,7 @@ def fake_start(fn, *args): "discover_model_services", lambda w, t: listings.append(w) or ({}, [], [], [], None), ) + def web_search_lookup(w, t): return (["system.ai.gpt-5"], None) @@ -8134,9 +8139,7 @@ def test_discovery_failure_never_installs(self, monkeypatch): assert not mc_mod.USER_MANAGED_CONFIG_PATH.exists() def test_keyboard_interrupt_never_installs(self, monkeypatch): - installs = self._run_failing_configure( - monkeypatch, KeyboardInterrupt(), threading.Event() - ) + installs = self._run_failing_configure(monkeypatch, KeyboardInterrupt(), threading.Event()) assert installs == [] assert not mc_mod.USER_MANAGED_CONFIG_PATH.exists() @@ -8193,7 +8196,6 @@ def _invoke_with_overlapped_catalog( catalog_started = threading.Event() release_catalog = threading.Event() catalog_threads: list[threading.Thread] = [] - configure_done = threading.Event() catalog_during_configure = threading.Event() picker_catalog = db_mod.AnthropicModelCatalog( model_ids=["main.default.claude-sonnet-5"], @@ -8216,9 +8218,7 @@ def fake_configure_shared_state(*_args, **_kwargs): catalog_during_configure.set() return state - configure = MagicMock( - side_effect=lambda _tool, configured, *_args, **_kwargs: configured - ) + configure = MagicMock(side_effect=lambda _tool, configured, *_args, **_kwargs: configured) launch = MagicMock() monkeypatch.setattr(cli_mod, "ensure_bootstrap_dependencies", lambda *_a, **_k: None) monkeypatch.setattr(cli_mod, "load_state", lambda: state) @@ -8315,7 +8315,9 @@ def fake_configure_shared_state(*_args, **_kwargs): monkeypatch.setattr(cli_mod, "get_databricks_token", lambda *_a: "token") monkeypatch.setattr(cli_mod, "configure_shared_state", fake_configure_shared_state) monkeypatch.setattr(cli_mod, "resolve_provider_models", lambda *a, **k: (None, None, False)) - monkeypatch.setattr(cli_mod, "list_anthropic_model_catalog", MagicMock(side_effect=fake_catalog)) + monkeypatch.setattr( + cli_mod, "list_anthropic_model_catalog", MagicMock(side_effect=fake_catalog) + ) monkeypatch.setattr(cli_mod, "configure_tool", configure) monkeypatch.setattr(cli_mod, "launch_agent", MagicMock()) @@ -8368,14 +8370,10 @@ def test_relayed_provider_launch_starts_no_catalog(self, monkeypatch): monkeypatch.setattr(cli_mod, "load_state", lambda: state) monkeypatch.setattr(cli_mod, "ensure_provider_state", lambda *_a: state) monkeypatch.setattr(cli_mod, "_fetch_managed_config", lambda _state: (None, False)) - monkeypatch.setattr( - cli_mod, "get_provider_service", lambda _s, _t: "main.default.relay" - ) + monkeypatch.setattr(cli_mod, "get_provider_service", lambda _s, _t: "main.default.relay") monkeypatch.setattr(cli_mod, "get_databricks_token", lambda *_a: "token") monkeypatch.setattr(cli_mod, "configure_shared_state", MagicMock(return_value=state)) - monkeypatch.setattr( - cli_mod, "resolve_provider_models", lambda *a, **k: (None, None, True) - ) + monkeypatch.setattr(cli_mod, "resolve_provider_models", lambda *a, **k: (None, None, True)) monkeypatch.setattr( cli_mod, "list_anthropic_model_catalog", @@ -8403,9 +8401,7 @@ def test_catalog_error_still_fails_the_launch(self, monkeypatch): } monkeypatch.setattr(cli_mod, "_fetch_managed_config", lambda _state: (managed, False)) monkeypatch.setattr(cli_mod, "get_databricks_token", lambda *_a: "token") - monkeypatch.setattr( - cli_mod, "configure_shared_state", MagicMock(return_value=state) - ) + monkeypatch.setattr(cli_mod, "configure_shared_state", MagicMock(return_value=state)) monkeypatch.setattr(cli_mod, "resolve_provider_models", lambda *a, **k: (None, None, False)) monkeypatch.setattr( cli_mod, @@ -9285,9 +9281,7 @@ def test_only_claude_and_codex_force_the_policy_read(self, monkeypatch, tool, fo monkeypatch.setattr( cli_mod, "refresh_managed_config", - lambda state, force_refresh=False, **_k: ( - calls.append(force_refresh) or (None, False) - ), + lambda state, force_refresh=False, **_k: calls.append(force_refresh) or (None, False), ) monkeypatch.setattr(cli_mod, "configure_single_tool", lambda tool, state, **k: state) monkeypatch.setattr(cli_mod, "_record_unmanaged_configured_agents", lambda s, t: s) @@ -9536,9 +9530,13 @@ def _run( monkeypatch.setattr("ucode.cli.load_state", lambda: {"workspace": "https://w"}) if coding_agent_config_feature_disabled: - monkeypatch.setattr("ucode.cli.refresh_managed_config", lambda state, **_k: (None, True)) + monkeypatch.setattr( + "ucode.cli.refresh_managed_config", lambda state, **_k: (None, True) + ) else: - monkeypatch.setattr("ucode.cli.refresh_managed_config", lambda state, **_k: (managed, False)) + monkeypatch.setattr( + "ucode.cli.refresh_managed_config", lambda state, **_k: (managed, False) + ) monkeypatch.setattr("ucode.cli.load_managed_state", lambda ws: cached) monkeypatch.setattr( @@ -9669,7 +9667,9 @@ def test_skip_preflight_still_resolves_an_agent_from_the_managed_config(self, mo "default_agent": "claude", "enabled_agents": {"claude": {"model_config": {"default_model": "m"}}}, } - monkeypatch.setattr("ucode.cli.refresh_managed_config", lambda state, **_k: (managed, False)) + monkeypatch.setattr( + "ucode.cli.refresh_managed_config", lambda state, **_k: (managed, False) + ) monkeypatch.setattr("ucode.cli._fetch_budget_recommendation", lambda state, m: None) monkeypatch.setattr("ucode.cli._print_managed_summary", lambda *a, **k: None) seen: dict = {}