Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

fix(model-hub): make migration optional when switching to the gateway (#2276)

Call White95beefc91fa5
diff --git a/core/backend_restart.py b/core/backend_restart.py
index 0154676e5..30ff62d98 100644
--- a/core/backend_restart.py
+++ b/core/backend_restart.py
@@ -214,6 +214,18 @@ def _native_executable_backend(executable: str, binaries: Mapping[str, str]) ->
return None
+def _launcher_family(executable: str) -> str | None:
+ """Name the interpreter family that could run a native CLI as its script."""
+ name = executable.replace("\\", "/").rsplit("/", 1)[-1].lower().removesuffix(".exe")
+ if re.fullmatch(r"(?:pythonw?|pypy)(?:\d+(?:\.\d+)*)?", name):
+ return "python"
+ if name.lstrip("-") in {"sh", "bash", "dash", "zsh", "ksh", "ash"}:
+ return "shell"
+ if name in {"node", "nodejs", "bun"}:
+ return "javascript"
+ return None
+
+
def _native_process_backend(command: list[str], binaries: Mapping[str, str]) -> str | None:
"""Match a direct executable or interpreter entrypoint, never script arguments."""
if not command:
@@ -222,16 +234,14 @@ def _native_process_backend(command: list[str], binaries: Mapping[str, str]) ->
if direct:
return direct
name = command[0].replace("\\", "/").rsplit("/", 1)[-1].lower().removesuffix(".exe")
- if re.fullmatch(r"(?:pythonw?|pypy)(?:\d+(?:\.\d+)*)?", name):
- family = "python"
+ family = _launcher_family(command[0])
+ if family == "python":
values = {"--check-hash-based-pycs"}
flags = set()
- elif name.lstrip("-") in {"sh", "bash", "dash", "zsh", "ksh", "ash"}:
- family = "shell"
+ elif family == "shell":
values = {"--rcfile", "--init-file"}
flags = {"--noprofile", "--norc", "--login", "--posix", "--restricted", "--verbose", "--debugger"}
- elif name in {"node", "nodejs", "bun"}:
- family = "javascript"
+ elif family == "javascript":
values = {
"--require", "--import", "--loader", "--experimental-loader", "--conditions",
"--env-file", "--env-file-if-exists", "--title", "--icu-data-dir",
@@ -329,11 +339,16 @@ def native_cli_processes(binaries: Mapping[str, str]) -> tuple[int, ...]:
continue
command = info.get("cmdline")
if not command:
- # A known other executable with inaccessible owner metadata
- # is not a CLI match; same-user unreadable command lines are
- # conservatively refused rather than silently skipped.
+ # A known other executable is not a CLI match, whether its
+ # owner metadata or its command line is what cannot be read.
+ # The second is every same-user setuid program, such as the
+ # ``login`` behind each macOS Terminal window. A same-user
+ # process with no name, or a launcher that could be running
+ # the CLI as its script, is conservatively refused instead.
name = str(info.get("name") or "")
- if owner is None and _native_process_backend([name], binaries) is None:
+ if _native_process_backend([name], binaries) is None and (
+ owner is None or (name and _launcher_family(name) is None)
+ ):
continue
raise NativeMigrationBlockedError("process_inventory_unavailable", backends)
if _native_process_backend(command, binaries) is not None:
@@ -479,7 +494,7 @@ class BackendRestartCoordinator:
@asynccontextmanager
async def migration_guard(
- self, backends: tuple[str, ...]
+ self, backends: tuple[str, ...], *, external_processes: bool = True
) -> AsyncIterator[Callable[[], Awaitable[None]]]:
"""Yield an idle recheck under the same lease and closed admissions.
@@ -488,6 +503,9 @@ class BackendRestartCoordinator:
No external process is ever terminated by the check. Authentication
reconciliation is synchronous and available only to this guard's task
after retirement, while its existing lease and both gates remain owned.
+ A mode-only switch passes ``external_processes=False``: it changes no
+ native credential, so a CLI running outside Avibe is not a reader it
+ has to exclude.
"""
targets = self._migration_targets(backends)
closed: list[str] = []
@@ -534,6 +552,8 @@ class BackendRestartCoordinator:
if await self._has_active_turns(backend):
raise NativeMigrationBlockedError("native_runtime_busy", (backend,))
self._assert_no_native_login(targets)
+ if not external_processes:
+ return
pids = await asyncio.to_thread(self._process_inventory, self._native_binaries(targets))
if pids:
raise NativeMigrationBlockedError("external_native_processes", targets, pids=pids)
diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.py
index ac66418d2..8aeb55406 100644
--- a/core/handlers/model_hub/service.py
+++ b/core/handlers/model_hub/service.py
@@ -773,6 +773,18 @@ async def _rollback_replacement_before_settling(
raise cancelled
+def _log_native_refusal(operation: str, error: Any) -> None:
+ # The client sees only a generic busy/blocked code. Keep the credential-free
+ # NativeMigrationBlockedError reason, backends and pids in the log instead.
+ logger.warning(
+ "%s refused: %s (backends=%s, pids=%s)",
+ operation,
+ error.reason,
+ ",".join(error.backends),
+ ",".join(str(pid) for pid in error.pids),
+ )
+
+
def _binding(source: ModelHubSourceConfig) -> SourceBinding:
if not source.credential_ref:
raise ModelHubError("engine_down", status=503)
@@ -1015,7 +1027,7 @@ class ModelHubService:
@staticmethod
@asynccontextmanager
- async def _unavailable_migration_guard(backends):
+ async def _unavailable_migration_guard(backends, *, external_processes=True):
# A stand-alone UI service cannot retire Controller-owned credentials.
# Tests explicitly inject a fixture-only guard; production is wired by
# the Controller's shared backend lifecycle coordinator.
@@ -4779,9 +4791,10 @@ class ModelHubService:
if mode == "hub":
from core.backend_restart import NativeMigrationBlockedError
- # A UI scan is advisory. Serialize with takeover, then recheck
- # native absence while writers and launches are held out. Never
- # treat mode-only consent as permission to import a new login.
+ # Serialize with takeover and retire the managed runtime so the
+ # next launch goes through the Hub. Mode-only consent never imports
+ # a login: native auth stays native beside the Hub, where the
+ # migration dialog can still take it over later.
async with self._migration_lock:
async with self._mutation_lock:
current = self.store.load()
@@ -4789,10 +4802,9 @@ class ModelHubService:
if agent.mode == "hub":
return self._agent_payload(current, agent)
try:
- async with self.migration_guard((backend,)) as verify_idle:
+ async with self.migration_guard((backend,), external_processes=False) as verify_idle:
async with self._mutation_lock:
- # Inventory must follow the last asynchronous drain:
- # a CLI may have logged in and exited during it.
+ # Recheck idleness after the last asynchronous drain.
await verify_idle()
previous = self.store.load()
available = await asyncio.to_thread(
@@ -4812,22 +4824,19 @@ class ModelHubService:
self.migration_journal.completed() or {}
).get("retained_native_ids"),
)
- # Retained auth stays native beside the Hub, but a
- # config the CLI cannot parse fails every launch.
- if any(
- item.backend == backend and (
- item.proposed_action == "import"
- or item.config_blocker
- )
- for item in available
- ):
+ # Native auth stays beside the Hub, but a config
+ # the CLI cannot parse fails every launch.
+ if any(item.backend == backend and item.config_blocker for item in available):
raise ModelHubError("mode_switch_blocked", status=409)
config = self._clone_config(previous)
self._agent(config, backend).mode = "hub"
await self._commit_synced(previous, config)
committed = self.store.load()
return self._agent_payload(committed, self._agent(committed, backend))
- except (NativeMigrationBlockedError, TakeoverStateError, OSError):
+ except NativeMigrationBlockedError as error:
+ _log_native_refusal("Model Hub mode switch", error)
+ raise ModelHubError("mode_switch_blocked", status=409) from None
+ except (TakeoverStateError, OSError):
raise ModelHubError("mode_switch_blocked", status=409) from None
async with self._mutation_lock:
previous = self.store.load()
@@ -6979,7 +6988,8 @@ class ModelHubService:
raise ModelHubError("migration_credentials_invalid", status=409) from None
except MigrationReauthorizationRequiredError:
raise ModelHubError("migration_reauthorization_required", status=409) from None
- except NativeMigrationBlockedError:
+ except NativeMigrationBlockedError as error:
+ _log_native_refusal("Model Hub migration", error)
raise ModelHubError("migration_native_busy", status=409) from None
except (NativeOAuthPermissionError, PermissionError):
raise ModelHubError("migration_permission_needed", status=409) from None
diff --git a/docs/plans/model-hub-contracts/api.md b/docs/plans/model-hub-contracts/api.md
index 7be0bbb36..438b13fb1 100644
--- a/docs/plans/model-hub-contracts/api.md
+++ b/docs/plans/model-hub-contracts/api.md
@@ -48,7 +48,7 @@ remain readable; ephemeral envelopes use only the terminal version.
| GET `/api/models/agents/<backend>/sources` | → `{agent: AgentSupply}` | Returns the authoritative effective order and eligibility. |
| PUT `/api/models/agents/<backend>/sources` | `{order: string[], force?: boolean, would_remove_hops?: RouteHopRef[], would_interrupt?: SupplyGap[]}` → guarded `409` or `{agent: AgentSupply}` | Atomically replaces default membership/order, preserves manual overrides, and guards effective hop removal or protected-supply loss. Pure reordering needs no guard. |
| POST `/api/models/agents/<backend>/chains/reorder` | `{order?: string[], force?: boolean, would_remove_hops?: RouteHopRef[], would_interrupt?: SupplyGap[]}` → guarded `409` or `{agent: AgentSupply}` | Compatibility default-order entry point with the same guards as Sources PUT. Never reorders manual arrays. Without order, returns the current projection. New UI uses Sources PUT. |
-| PATCH `/api/models/agents/<backend>/mode` | `{mode}` → `{agent: AgentSupply}` | Explicit `hub` / `direct` switch. Direct-to-Hub rechecks native absence under the shared migration guard and returns `mode_switch_blocked` if credentials require consent. It does not auto-create or adopt a native Source; native custody takeover is the grouped migration transaction. Hub-to-Direct remains mode-only. |
+| PATCH `/api/models/agents/<backend>/mode` | `{mode}` → `{agent: AgentSupply}` | Explicit `hub` / `direct` switch. Direct-to-Hub serializes with takeover under the shared migration guard, drains and retires the managed runtime, and returns `mode_switch_blocked` only for a native config the CLI cannot parse or a guard refusal. Native auth, including an importable login, stays native beside the Hub and remains a migration candidate; CLIs running outside Avibe do not block the switch because it changes no native credential. It does not auto-create or adopt a native Source; native custody takeover is the optional grouped migration transaction. Hub-to-Direct remains mode-only. |
| GET `/api/models/agents/<backend>/models` | → `{agent: {backend, mode, catalog_models}}` | Picker-safe catalog read. It exposes no Source order, Route, or credential-bearing supplier data. Every OpenCode row carries required `native_protocol`; Claude and Codex rows omit it. |
| GET `/api/models/agents/<backend>/models/candidates` | → `{candidates: {builtin: Candidate[], providers: Candidate[], in_list: Candidate[]}}` | Server-owned picker projection. It returns addable built-ins, deduplicated ordered-provider inventory, and every current menu row with the same exact supplier projection; it is independent of backend mode and contains no credentials. Every OpenCode Candidate carries server-derived `native_protocol`; other backends omit it. Only `in_list` candidates may carry optional `group_if_removed: "builtin" | "providers" | null`, naming the group where that id would be offered after removal. A `providers` candidate whose id names a cached models.dev model exactly also carries that match's `models_dev_id`, `context_window`, `max_output_tokens`, `input_modalities`, `output_modalities`, `supports_tools`, and `supports_reasoning` together; those seven are absent otherwise. |
| PUT `/api/models/agents/<backend>/models` | `{baseline: BackendModel[], models: BackendModel[], expected_suppliers?: {<id>: [{source_id, model_id}]}, force?: boolean, would_remove_hops?: RouteHopRef[], would_interrupt?: SupplyGap[]}` → guarded `409`, stale-candidate `409`, `{agent: AgentSupply}`, or `{agent: AgentSupply, removed_hops: RouteHopRef[], interrupted: SupplyGap[]}` | Applies one full-list backend catalog edit with optimistic merge. OpenCode rows require a literal `native_protocol: openai_responses | anthropic`; rows for other backends forbid it. Each caller addition still absent from the latest list starts automatic without a route key. A listed supplier-projection mismatch refuses atomically with the separate exact shape `{ok: false, contract_version, error: "candidate_suppliers_changed", detail, changed}`; a concurrently added row keeps its existing Route. A routeful removal uses the exact echoed-plan guard and then atomically removes its Route; empty-route removal is ordinary success. Supplier inventory remains unchanged. |
diff --git a/tests/scenarios/INDEX.yaml b/tests/scenarios/INDEX.yaml
index c77ea8d25..81876fa23 100644
--- a/tests/scenarios/INDEX.yaml
+++ b/tests/scenarios/INDEX.yaml
@@ -52,6 +52,7 @@ capabilities:
- tests/test_model_hub_config.py
- tests/test_model_hub_legacy_opencode_migration.py
- tests/test_model_hub_persisted_migration.py
+ - tests/test_native_process_inventory.py
- tests/test_member_management_parity.py
- tests/test_model_hub_provenance.py
- tests/test_model_hub_retention.py
diff --git a/tests/scenarios/model_hub/catalog.yaml b/tests/scenarios/model_hub/catalog.yaml
index c774708ce..52aaaab57 100644
--- a/tests/scenarios/model_hub/catalog.yaml
+++ b/tests/scenarios/model_hub/catalog.yaml
@@ -54,6 +54,7 @@ capability:
- tests/scenarios/model_hub/test_model_hub_turn_contract_scenarios.py
- tests/scenarios/model_hub/test_model_hub_migration_scenarios.py
- tests/test_model_hub_persisted_migration.py
+ - tests/test_native_process_inventory.py
- tests/scenarios/model_hub/test_model_hub_native_oauth_scenarios.py
- tests/scenarios/model_hub/test_model_hub_valuation_scenarios.py
- tests/e2e/test_model_hub_guards.py
@@ -1247,6 +1248,17 @@ scenarios:
kind: migration
layer: scenario
test: tests/scenarios/model_hub/test_model_hub_migration_scenarios.py::test_mh_mig_007_default_apply_copies_api_keys_and_withdraws_only_subscriptions
+ - id: MH-MIG-008
+ name: Migration is optional, so switching to the gateway neither imports native auth nor waits for external CLIs
+ status: covered
+ kind: migration
+ layer: unit
+ test: tests/test_native_process_inventory.py::test_running_cli_does_not_block_a_mode_only_switch
+ related_tests:
+ - tests/test_model_hub_native_takeover.py::test_mode_only_adoption_never_imports_native_auth
+ - tests/test_native_takeover_lifecycle.py::test_same_user_setuid_program_does_not_block_inventory
+ - ui/src/components/settings/models/BackendSupplyModeCard.test.tsx
+ - ui/src/components/settings/models/SettingsModelsPage.render.test.tsx
- id: MH-TAKEOVER-001
name: Recoverable failures walk the configured route and exhaust only at its end
status: covered
diff --git a/tests/test_model_hub_api.py b/tests/test_model_hub_api.py
index bca4fd97f..0c71f1196 100644
--- a/tests/test_model_hub_api.py
+++ b/tests/test_model_hub_api.py
@@ -4598,7 +4598,7 @@ def test_agents_endpoint_projects_each_enabled_named_agent_live(tmp_path):
@asynccontextmanager
-async def _idle_mode_guard(backends):
+async def _idle_mode_guard(backends, *, external_processes=True):
async def verify_idle():
pass
yield verify_idle
diff --git a/tests/test_model_hub_native_takeover.py b/tests/test_model_hub_native_takeover.py
index bcc8bd437..9910f4cca 100644
--- a/tests/test_model_hub_native_takeover.py
+++ b/tests/test_model_hub_native_takeover.py
@@ -28,7 +28,7 @@ from tests.scenarios.model_hub.test_model_hub_migration_scenarios import (
@pytest.mark.parametrize("backend", ["claude", "codex", "opencode"])
@pytest.mark.parametrize("native_present", [False, True])
@pytest.mark.parametrize("boundary", ["entry", "verify"])
-def test_mode_only_adoption_checks_native_absence_inside_guard(
+def test_mode_only_adoption_never_imports_native_auth(
monkeypatch, tmp_path, backend, native_present, boundary,
):
home = tmp_path / "native"
@@ -49,7 +49,7 @@ def test_mode_only_adoption_checks_native_absence_inside_guard(
'{"openai":{"type":"api","key":"fixture-key"}}')
@asynccontextmanager
- async def guard(backends):
+ async def guard(backends, *, external_processes=True):
assert backends == (backend,)
assert not service._mutation_lock.locked()
if boundary == "entry":
@@ -61,15 +61,11 @@ def test_mode_only_adoption_checks_native_absence_inside_guard(
yield verify
service.migration_guard = guard
- if native_present:
- with pytest.raises(ModelHubError) as failure:
- asyncio.run(service.set_agent_mode(backend, "hub"))
- assert failure.value.code == "mode_switch_blocked"
- assert store.config.agents[backend].mode == "direct"
- assert service.migration_scan()["items"]
- else:
- assert asyncio.run(service.set_agent_mode(backend, "hub"))["mode"] == "hub"
- assert checks
+ # Migration is optional: native auth stays native beside the Hub and is
+ # still offered for takeover afterwards.
+ assert asyncio.run(service.set_agent_mode(backend, "hub"))["mode"] == "hub"
+ assert checks
+ assert bool(service.migration_scan()["items"]) is native_present
assert not store.config.sources
assert not adapter.provisioned and not adapter.oauth_provisioned
assert service.migration_journal.load() is None
@@ -631,7 +627,7 @@ def test_mode_only_adoption_refuses_a_native_config_the_cli_cannot_parse(
assert not any(item["proposed_action"] == "import" for item in service.migration_scan()["items"])
@asynccontextmanager
- async def guard(backends):
+ async def guard(backends, *, external_processes=True):
async def verify():
return None
yield verify
diff --git a/tests/test_native_process_inventory.py b/tests/test_native_process_inventory.py
index 298172ac6..743f4bdf1 100644
--- a/tests/test_native_process_inventory.py
+++ b/tests/test_native_process_inventory.py
@@ -305,3 +305,27 @@ async def test_real_guard_does_not_confuse_data_with_a_configured_script(monkeyp
assert inventory.call_count == 2
assert not admissions and not turns
controller.agent_service.force_cancel_backend_turns.assert_not_awaited()
+
+
[email protected]("backend", ["claude", "codex", "opencode"])
+def test_running_cli_does_not_block_a_mode_only_switch(monkeypatch, tmp_path, backend):
+ """MH-MIG-008: a running CLI never blocks the switch to the gateway.
+
+ Takeover must exclude every native reader; a mode-only switch changes no
+ native credential, so an IDE extension or terminal CLI may keep running.
+ """
+ config = V2Config.default()
+ native = getattr(config.agents, backend)
+ native.cli_path = f"/fixture/custom-{backend}"
+ config.model_hub.agents[backend].mode = "direct"
+ config.save()
+ service, _, _ = _service(tmp_path, migration_home=Path.home())
+ service.store = V2ModelHubConfigStore()
+ controller, coordinator, admissions, turns = _configured_owner(to_app_config(config))
+ controller.model_hub_service = service
+ coordinator._process_inventory = native_cli_processes
+ service.migration_guard = coordinator.migration_guard
+ monkeypatch.setattr(psutil, "process_iter", lambda attrs: [_row([native.cli_path])])
+ assert asyncio.run(service.set_agent_mode(backend, "hub"))["mode"] == "hub"
+ assert V2Config.load().model_hub.agents[backend].mode == "hub"
+ assert not admissions and not turns
diff --git a/tests/test_native_takeover_lifecycle.py b/tests/test_native_takeover_lifecycle.py
index aa07c809f..957b824d5 100644
--- a/tests/test_native_takeover_lifecycle.py
+++ b/tests/test_native_takeover_lifecycle.py
@@ -342,16 +342,30 @@ def test_process_inventory_matches_executables_not_prompt_arguments(monkeypatch,
assert native_cli_processes(dict.fromkeys(("claude", "codex", "opencode"), "")) == ((123,) if matched else ())
-def test_incomplete_same_user_inventory_refuses(monkeypatch):
[email protected]("name", [None, "codex", "node", "python3.12", "zsh"])
+def test_incomplete_same_user_inventory_refuses(monkeypatch, name):
import psutil
monkeypatch.setattr(psutil, "process_iter", lambda attrs: [SimpleNamespace(info={
"pid": 123, "uids": SimpleNamespace(real=os.getuid()), "status": "running", "cmdline": None,
+ "name": name,
})])
with pytest.raises(NativeMigrationBlockedError, match="process_inventory_unavailable"):
native_cli_processes({"codex": "codex"})
+def test_same_user_setuid_program_does_not_block_inventory(monkeypatch):
+ # macOS runs a setuid ``login`` behind every Terminal window; its command
+ # line is unreadable to the same user but it can never be a native CLI.
+ import psutil
+
+ monkeypatch.setattr(psutil, "process_iter", lambda attrs: [SimpleNamespace(info={
+ "pid": 123, "uids": SimpleNamespace(real=os.getuid()), "status": "sleeping", "cmdline": [],
+ "name": "login",
+ })])
+ assert native_cli_processes({"codex": "codex", "claude": "claude"}) == ()
+
+
@pytest.mark.asyncio
async def test_cancelled_thread_writer_keeps_lease_until_worker_finishes():
started = threading.Event()
diff --git a/ui/src/components/settings/models/BackendSupplyModeCard.test.tsx b/ui/src/components/settings/models/BackendSupplyModeCard.test.tsx
new file mode 100644
index 000000000..def27aaf2
--- /dev/null
+++ b/ui/src/components/settings/models/BackendSupplyModeCard.test.tsx
@@ -0,0 +1,89 @@
+// @vitest-environment jsdom
+//
+// Migration is optional on the way to the gateway: declining the takeover the
+// card offers still makes the switch, while declining an import asked for from
+// the Direct strip leaves the backend on Direct.
+import { cleanup, render, screen, waitFor, within } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { I18nextProvider } from 'react-i18next';
+import { MemoryRouter } from 'react-router-dom';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import i18n from '@/i18n';
+import type { AgentSupply, MigrationItem, RuntimeDependency } from './types';
+
+const showToast = vi.hoisted(() => vi.fn());
+vi.mock('@/context/ToastContext', () => ({ useToast: () => ({ showToast }) }));
+
+import { BackendSupplyModeCard } from './BackendSupplyModeCard';
+import { modelsApi } from './modelsApi';
+
+const DIRECT: AgentSupply = { backend: 'claude', cli_present: true, mode: 'direct', menu_kind: 'fixed' };
+
+const CLAUDE_KEY: MigrationItem = {
+ id: 'mig_claude_key',
+ backend: 'claude',
+ kind: 'api_key',
+ masked_detail: 'sk-ant-…1c05',
+ proposed_action: 'import',
+ selected: true,
+ notes_key: null,
+ vendor: 'anthropic',
+ display_name: 'Anthropic',
+ masked_credential: 'sk-ant-…1c05',
+};
+
+const RUNTIME: RuntimeDependency = {
+ contract_version: 10,
+ manifest: { name: 'cliproxyapi', resolution: 'resolved', version: '1', source_sha: 'a'.repeat(40), assets: [] },
+ status: { installed_version: '1', verified: true, health: 'ok' },
+};
+
+beforeEach(async () => {
+ await i18n.changeLanguage('en');
+ vi.spyOn(modelsApi, 'listAgents').mockResolvedValue([DIRECT]);
+ vi.spyOn(modelsApi, 'getRuntimeStatus').mockResolvedValue(RUNTIME);
+ vi.spyOn(modelsApi, 'scanMigration').mockResolvedValue({ items: [CLAUDE_KEY] });
+});
+
+afterEach(() => {
+ cleanup();
+ vi.restoreAllMocks();
+ showToast.mockReset();
+});
+
+const renderCard = () =>
+ render(
+ <MemoryRouter>
+ <I18nextProvider i18n={i18n}>
+ <BackendSupplyModeCard backend="claude" />
+ </I18nextProvider>
+ </MemoryRouter>,
+ );
+
+describe('BackendSupplyModeCard', () => {
+ it.each([
+ ['switching to the gateway', /Gateway mode/, true],
+ ['importing from the Direct strip', null, false],
+ ] as const)('declining the migration offered while %s', async (_, radio, switches) => {
+ const apply = vi.spyOn(modelsApi, 'applyMigration');
+ const setMode = vi.spyOn(modelsApi, 'setAgentMode').mockResolvedValue({ ...DIRECT, mode: 'hub' });
+ renderCard();
+
+ if (radio) await userEvent.click(await screen.findByRole('radio', { name: radio }));
+ else await userEvent.click(await screen.findByRole('button', { name: /Import to gateway/ }));
+ const dialog = await screen.findByRole('dialog');
+ await waitFor(() => expect(within(dialog).getByText('Anthropic')).toBeTruthy());
+ expect(setMode).not.toHaveBeenCalled();
+ await userEvent.click(within(dialog).getByRole('button', { name: 'Later' }));
+
+ if (switches) {
+ await waitFor(() => expect(setMode).toHaveBeenCalledWith('claude', 'hub'));
+ await waitFor(() => expect(showToast).toHaveBeenCalledWith('Switched to Gateway', 'success'));
+ } else {
+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
+ expect(setMode).not.toHaveBeenCalled();
+ }
+ expect(apply).not.toHaveBeenCalled();
+ });
+});
diff --git a/ui/src/components/settings/models/BackendSupplyModeCard.tsx b/ui/src/components/settings/models/BackendSupplyModeCard.tsx
index 513917912..87542d213 100644
--- a/ui/src/components/settings/models/BackendSupplyModeCard.tsx
+++ b/ui/src/components/settings/models/BackendSupplyModeCard.tsx
@@ -83,7 +83,9 @@ export const BackendSupplyModeCard: React.FC<{ backend: AgentBackend }> = ({ bac
const [agent, setAgent] = React.useState<AgentSupply | null>(null);
const [detected, setDetected] = React.useState<MigrationItem[]>([]);
const [switching, setSwitching] = React.useState<AgentMode | null>(null);
- const [migrateOpen, setMigrateOpen] = React.useState(false);
+ /** Why the migration dialog is open: offered on the way to the gateway, or
+ * asked for from the Direct strip. Only the first switches when declined. */
+ const [migrateOpen, setMigrateOpen] = React.useState<'switch' | 'import' | null>(null);
const [agentReads] = React.useState(() => createAgentCollectionReadAuthority(modelsApi));
const aliveRef = React.useRef(true);
React.useEffect(() => {
@@ -116,17 +118,19 @@ export const BackendSupplyModeCard: React.FC<{ backend: AgentBackend }> = ({ bac
void scan();
}, [load, scan]);
- const setMode = async (mode: AgentMode) => {
+ const setMode = async (mode: AgentMode, offerMigration = true) => {
if (!agent || agent.mode === mode || switching) return;
setSwitching(mode);
try {
const next = mode === 'hub'
? await (async () => {
- const result = await resumeGatewayAdoption(modelsApi, agentReads, backend);
- if (!result.ok) throw new Error(result.failure.reason);
- if (result.candidates.length > 0) {
- if (aliveRef.current) setMigrateOpen(true);
- return null;
+ if (offerMigration) {
+ const result = await resumeGatewayAdoption(modelsApi, agentReads, backend);
+ if (!result.ok) throw new Error(result.failure.reason);
+ if (result.candidates.length > 0) {
+ if (aliveRef.current) setMigrateOpen('switch');
+ return null;
+ }
}
return modelsApi.setAgentMode(backend, 'hub');
})()
@@ -239,7 +243,7 @@ export const BackendSupplyModeCard: React.FC<{ backend: AgentBackend }> = ({ bac
className="shrink-0"
onClick={(e) => {
e.stopPropagation();
- setMigrateOpen(true);
+ setMigrateOpen('import');
}}
>
<ArrowDownToLine className="size-3.5" />
@@ -250,12 +254,14 @@ export const BackendSupplyModeCard: React.FC<{ backend: AgentBackend }> = ({ bac
</OptionCard>
</CardContent>
+ {/* Migration is optional: declining it still makes the requested switch. */}
<MigrationDialog
- open={migrateOpen}
+ open={migrateOpen !== null}
eligible={(item) => item.backend === backend}
- onClose={() => setMigrateOpen(false)}
+ onDecline={migrateOpen === 'switch' ? () => void setMode('hub', false) : undefined}
+ onClose={() => setMigrateOpen(null)}
onApplied={() => {
- setMigrateOpen(false);
+ setMigrateOpen(null);
void load();
void scan();
}}
diff --git a/ui/src/components/settings/models/MigrationDialog.test.tsx b/ui/src/components/settings/models/MigrationDialog.test.tsx
index 8edd4e939..679c752ce 100644
--- a/ui/src/components/settings/models/MigrationDialog.test.tsx
+++ b/ui/src/components/settings/models/MigrationDialog.test.tsx
@@ -313,7 +313,7 @@ describe('MigrationDialog — the settings default', () => {
});
it.each([
- ['migration_native_busy', 'Close the CLI or finish its tasks, then retry.'],
+ ['migration_native_busy', 'Quit the running CLI, including terminal sessions, IDE extensions and desktop apps, or let its tasks finish, then retry.'],
['migration_permission_needed', 'Allow credential access, then retry.'],
['migration_recovery_pending', 'Migration is unfinished. Retry to continue.'],
['migration_item_conflict', 'Migration could not verify the saved configuration or its credentials. Check the files and authentication before retrying, or add the source manually in Model Hub.'],
diff --git a/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx b/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx
index 4ff3209bf..72ca8f7c2 100644
--- a/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx
+++ b/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx
@@ -299,9 +299,12 @@ afterEach(() => {
});
describe('SettingsModelsPage surface branches', () => {
- it('opens the consent dialog before Direct-to-Hub takeover and leaves Direct unchanged on cancel', async () => {
+ it.each([
+ ['right away', false],
+ ['after a refused takeover', true],
+ ] as const)('offers migration before Direct-to-Hub and still switches when it is declined %s', async (_, refused) => {
vi.spyOn(modelsApi, 'scanMigration').mockResolvedValue({ items: [migrationCandidate] });
- const apply = vi.spyOn(modelsApi, 'applyMigration');
+ const apply = vi.spyOn(modelsApi, 'applyMigration').mockRejectedValue(new ApiCallError('migration_native_busy'));
const setMode = vi.spyOn(modelsApi, 'setAgentMode').mockResolvedValue({ ...directAgent('claude'), mode: 'hub' });
renderPage([], [directAgent('claude')]);
@@ -309,11 +312,18 @@ describe('SettingsModelsPage surface branches', () => {
const dialog = await screen.findByRole('dialog');
expect(within(dialog).getByRole('checkbox', { name: /Claude native login/ })).toBeTruthy();
expect(within(dialog).getByText(/After migration|迁移后/)).toBeTruthy();
+ expect(setMode).not.toHaveBeenCalled();
+ if (refused) {
+ await userEvent.click(within(dialog).getByRole('button', { name: /Start migration|开始迁移/i }));
+ await waitFor(() => expect(apply).toHaveBeenCalledOnce());
+ expect(screen.getByRole('dialog')).toBeTruthy();
+ }
await userEvent.click(within(dialog).getByRole('button', { name: /Later|稍后/i }));
- expect(apply).not.toHaveBeenCalled();
- expect(setMode).not.toHaveBeenCalled();
+ await waitFor(() => expect(setMode).toHaveBeenCalledWith('claude', 'hub'));
+ expect(setMode).toHaveBeenCalledOnce();
+ expect(apply).toHaveBeenCalledTimes(refused ? 1 : 0);
});
it('uses the ordinary mode switch when Direct has no migration candidates', async () => {
diff --git a/ui/src/components/settings/models/SettingsModelsPage.tsx b/ui/src/components/settings/models/SettingsModelsPage.tsx
index b23d0845c..bd402d517 100644
--- a/ui/src/components/settings/models/SettingsModelsPage.tsx
+++ b/ui/src/components/settings/models/SettingsModelsPage.tsx
@@ -1007,6 +1007,26 @@ export const SettingsModelsPage: React.FC = () => {
}
});
};
+ const enterGateway = async (backend: AgentBackend) => {
+ const echoed = await modelsApi.setAgentMode(backend, 'hub');
+ setSwitchFailures((previous) => {
+ const next = new Set(previous);
+ next.delete(backend);
+ return next;
+ });
+ await agentSaved(echoed);
+ };
+ // Migration is optional: declining it still switches the backend it was
+ // offered for, which keeps its native login beside the gateway.
+ const declineMigration = (backend: AgentBackend) => {
+ void agentWriteRegistry.track(backend, async () => {
+ try {
+ await enterGateway(backend);
+ } catch {
+ setSwitchFailures((previous) => new Set(previous).add(backend));
+ }
+ });
+ };
const switchToGateway = (agent: AgentSupply) => {
if (agentWrites.has(agent.backend)) return;
setAdoptAgent(agent);
@@ -1028,13 +1048,7 @@ export const SettingsModelsPage: React.FC = () => {
setMigrationOpen(true);
return;
}
- const echoed = await modelsApi.setAgentMode(agent.backend, 'hub');
- setSwitchFailures((previous) => {
- const next = new Set(previous);
- next.delete(agent.backend);
- return next;
- });
- await agentSaved(echoed);
+ await enterGateway(agent.backend);
} catch {
setSwitchFailures((previous) => new Set(previous).add(agent.backend));
} finally {
@@ -1850,6 +1864,7 @@ export const SettingsModelsPage: React.FC = () => {
eligible={migrationBackend
? (item) => item.backend === migrationBackend
: undefined}
+ onDecline={migrationBackend ? () => declineMigration(migrationBackend) : undefined}
onClose={() => {
setMigrationOpen(false);
setMigrationBackend(null);
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 7b83915fb..4fb2097be 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -2042,7 +2042,7 @@
},
"applying": "Migrating…",
"errors": {
- "nativeBusy": "Close the CLI or finish its tasks, then retry.",
+ "nativeBusy": "Quit the running CLI, including terminal sessions, IDE extensions and desktop apps, or let its tasks finish, then retry.",
"permissionNeeded": "Allow credential access, then retry.",
"recoveryPending": "Migration is unfinished. Retry to continue.",
"itemConflict": "Migration could not verify the saved configuration or its credentials. Check the files and authentication before retrying, or add the source manually in Model Hub.",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 5d319f2ad..c4b1a586e 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -2042,7 +2042,7 @@
},
"applying": "迁移中…",
"errors": {
- "nativeBusy": "请先关闭 CLI 或完成任务,再重试。",
+ "nativeBusy": "请先退出正在运行的 CLI(包括终端、IDE 插件和桌面应用),或等待任务完成,再重试。",
"permissionNeeded": "请允许访问凭据,再重试。",
"recoveryPending": "迁移尚未完成,请重试以继续。",
"itemConflict": "无法验证已保存的配置或凭据。请检查配置文件和认证是否有效后重试,或在模型网关中手动添加供应商。",