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): wait out the teardown a switch starts and name its refusal (#2315)

Call White86e4750ef8d9
diff --git a/core/backend_restart.py b/core/backend_restart.py
index 3832d8b94..9a333dac0 100644
--- a/core/backend_restart.py
+++ b/core/backend_restart.py
@@ -19,8 +19,14 @@ logger = logging.getLogger(__name__)
DEFAULT_DRAIN_TIMEOUT_SECONDS = 300.0
_POLL_INTERVAL_SECONDS = 0.1
# After an interruption only teardown remains: native processes exiting and
-# requests to a stopped runtime failing. Work still live past this is a fault.
-_INTERRUPT_SETTLE_SECONDS = 10.0
+# requests to a stopped runtime failing. By then the user's work is already
+# interrupted, so the switch waits for that teardown rather than refusing
+# beside it. This is a fault threshold, not a proof over every runtime: a
+# healthy teardown takes seconds even on slow storage, and one still running
+# past it keeps the switch's exclusions until it settles, so the refusal is
+# accurate and a retry afterwards proceeds. It stays well inside the 300 s
+# Model Hub RPC timeout the Web UI waits under.
+_INTERRUPT_SETTLE_SECONDS = 120.0
_NATIVE_BACKENDS = frozenset({"claude", "codex", "opencode"})
_T = TypeVar("_T")
@@ -528,7 +534,16 @@ class BackendRestartCoordinator:
await locks.enter_async_context(self._request_locks.setdefault(backend, asyncio.Lock()))
restart = self._tasks.get(backend)
if restart is not None and not restart.done():
- raise NativeMigrationBlockedError("backend_restart_in_progress", (backend,))
+ # A backend still held as migrating under its lock is a
+ # teardown an earlier switch handed off: the work it
+ # interrupted is still stopping. Anything else is an
+ # ordinary restart, which may be draining live work.
+ reason = (
+ "migration_teardown_in_progress"
+ if backend in self._migration_backends
+ else "backend_restart_in_progress"
+ )
+ raise NativeMigrationBlockedError(reason, (backend,))
self._assert_no_native_login(targets)
lease = NativeCredentialLease(targets, state_dir=self._native_state_dir()).acquire(recovery=True)
self._migration_backends.update(targets)
@@ -541,8 +556,8 @@ class BackendRestartCoordinator:
await self.controller.agent_service.prepare_backend_restart(backend)
# A forced restart owns the interruption and teardown, and it
# reopens admission only after the teardown. The switch waits
- # for it at most the settle window, and leaving early, by
- # timeout or cancellation, never cuts the teardown short.
+ # for it up to the settle bound, and leaving early, by timeout
+ # or cancellation, never cuts the teardown short.
for backend in targets:
if await self._has_active_turns(backend):
restarts[backend] = self._start_restart(backend, drain_timeout=0)
diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.py
index e8dc09602..4a73a5f68 100644
--- a/core/handlers/model_hub/service.py
+++ b/core/handlers/model_hub/service.py
@@ -828,8 +828,14 @@ async def _rollback_replacement_before_settling(
raise cancelled
+# Guard refusals that mean work a switch interrupted on the selected backends
+# is still stopping. Every other refusal, such as a CLI running outside Avibe
+# or an ordinary restart draining live work, stays the generic busy code.
+_RUNTIME_STOPPING_REASONS = frozenset({"native_runtime_busy", "migration_teardown_in_progress"})
+
+
def _log_native_refusal(operation: str, error: Any) -> None:
- # The client sees only a generic busy/blocked code. Keep the credential-free
+ # The client sees only a closed 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)",
@@ -7198,7 +7204,12 @@ class ModelHubService:
raise ModelHubError("migration_reauthorization_required", status=409) from None
except NativeMigrationBlockedError as error:
_log_native_refusal("Model Hub migration", error)
- raise ModelHubError("migration_native_busy", status=409) from None
+ code = (
+ "migration_runtime_stopping"
+ if error.reason in _RUNTIME_STOPPING_REASONS
+ else "migration_native_busy"
+ )
+ raise ModelHubError(code, status=409) from None
except (NativeOAuthPermissionError, PermissionError):
raise ModelHubError("migration_permission_needed", status=409) from None
except (TakeoverStateError, NativeOAuthError):
diff --git a/docs/plans/model-hub-contracts/api.md b/docs/plans/model-hub-contracts/api.md
index 63253f5a1..e0274ac95 100644
--- a/docs/plans/model-hub-contracts/api.md
+++ b/docs/plans/model-hub-contracts/api.md
@@ -1615,7 +1615,8 @@ Minimum v5 set:
`candidate_suppliers_changed`, `mode_switch_blocked`, `engine_down`,
`runtime_platform_unsupported`, `reauth_confirmation_required`,
`native_source_already_exists`, `native_login_in_progress`,
-`migration_item_conflict`, `migration_native_busy`, `migration_permission_needed`,
+`migration_item_conflict`, `migration_native_busy`, `migration_runtime_stopping`,
+`migration_permission_needed`,
`migration_configuration_blocked`, `migration_recovery_pending`,
`migration_credentials_invalid`, `source_model_tiers_managed`, `turn_not_found`,
`provenance_unavailable`, `probe_no_candidate`, `direct_mode`.
@@ -1633,8 +1634,12 @@ native channel and the response does not assert that a native Source already exi
Migration action errors are closed, redacted boundary codes:
-- `migration_native_busy`: a managed native process could not be drained or an
- external CLI still owns the credential.
+- `migration_native_busy`: an external CLI still owns the credential, or a managed
+ native process could not be retired.
+- `migration_runtime_stopping`: work Avibe itself interrupted on the selected
+ backends did not finish stopping within the guard's settle bound, or an earlier
+ teardown still holds them. Nothing was migrated and a retry shortly afterwards
+ proceeds; no external CLI is involved.
- `migration_permission_needed`: the selected native store or file operation requires
permission that was not granted.
- `migration_configuration_blocked`: a malformed, unsupported, conflicting, or
diff --git a/docs/plans/model-hub-native-takeover.md b/docs/plans/model-hub-native-takeover.md
index ab4d9dab1..ba9f4a949 100644
--- a/docs/plans/model-hub-native-takeover.md
+++ b/docs/plans/model-hub-native-takeover.md
@@ -157,9 +157,15 @@ explicitly authorized acceptance check.
down instead of being awaited), strictly retires credential-bearing processes
that are then idle, and checks for external CLI users, which are never
terminated. The interruption runs as a forced backend restart, which keeps
- admission closed until its teardown completes. The switch waits for it only
- for a short settle window and refuses as busy after that. Leaving early, by
- timeout or cancellation, never cuts the teardown short. A mode switch in
+ admission closed until its teardown completes. Because the user's work is
+ already interrupted by then, the switch waits for that teardown. The wait
+ has a fault threshold, not a proof over every runtime: a healthy teardown
+ takes seconds, and one still running past the threshold keeps the switch's
+ exclusions until it settles. Migration reports that refusal, and a retry
+ beside the teardown it handed off, as `migration_runtime_stopping`, so a
+ retry after the teardown proceeds. An ordinary restart in progress stays
+ `migration_native_busy`. Leaving early, by timeout or cancellation, never
+ cuts the teardown short. A mode switch in
either direction enters it, since a turn left running keeps the mode it
started in. Every interrupted conversation turn gets one visible notice, and
a Harness Run, including one owned by a background Activity, settles as a
diff --git a/tests/scenarios/INDEX.yaml b/tests/scenarios/INDEX.yaml
index 8bf2fc629..fe76845e0 100644
--- a/tests/scenarios/INDEX.yaml
+++ b/tests/scenarios/INDEX.yaml
@@ -54,6 +54,7 @@ capabilities:
- tests/test_model_hub_persisted_migration.py
- tests/test_native_process_inventory.py
- tests/test_native_takeover_lifecycle.py
+ - tests/test_model_hub_native_takeover.py
- tests/test_internal_server.py
- tests/test_member_management_parity.py
- tests/test_model_hub_provenance.py
diff --git a/tests/scenarios/model_hub/catalog.yaml b/tests/scenarios/model_hub/catalog.yaml
index 002cd3bea..112b68227 100644
--- a/tests/scenarios/model_hub/catalog.yaml
+++ b/tests/scenarios/model_hub/catalog.yaml
@@ -57,6 +57,7 @@ capability:
- tests/test_model_hub_persisted_migration.py
- tests/test_native_process_inventory.py
- tests/test_native_takeover_lifecycle.py
+ - tests/test_model_hub_native_takeover.py
- tests/test_internal_server.py
- tests/scenarios/model_hub/test_model_hub_native_oauth_scenarios.py
- tests/scenarios/model_hub/test_model_hub_valuation_scenarios.py
@@ -1328,6 +1329,20 @@ scenarios:
- tests/test_scheduled_tasks.py::test_refresh_ending_the_last_activity_keeps_the_runs_first_cause
- tests/test_session_delivery_fsm.py::test_forced_refresh_tells_a_restored_conversation_turn_why_it_stopped
- tests/test_agent_service.py::test_force_end_backend_activities_settles_pending_runs
+ - id: MH-MIG-013
+ name: A switch waits out the teardown of the work it interrupted instead of refusing beside it
+ status: covered
+ kind: migration
+ layer: unit
+ test: tests/test_native_takeover_lifecycle.py::test_switch_waits_out_a_teardown_that_takes_its_bounded_worst_case
+ - id: MH-MIG-014
+ name: A migration refused while Avibe's own interrupted work is still stopping says so in the dialog, not that an outside CLI holds the backend
+ status: covered
+ kind: migration
+ layer: unit
+ test: tests/test_model_hub_native_takeover.py::test_refused_migration_says_whether_avibe_or_an_outside_cli_holds_the_backend
+ related_tests:
+ - ui/src/components/settings/models/MigrationDialog.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_native_takeover.py b/tests/test_model_hub_native_takeover.py
index ac6b259b5..54c8cae13 100644
--- a/tests/test_model_hub_native_takeover.py
+++ b/tests/test_model_hub_native_takeover.py
@@ -671,3 +671,40 @@ def test_mode_only_adoption_refuses_a_native_config_the_cli_cannot_parse(
# MH-MIG-009: the guard interrupts running work, so a switch that is
# refused anyway must be refused before it is entered.
assert entered == []
+
+
[email protected]("reason,code", [
+ ("native_runtime_busy", "migration_runtime_stopping"),
+ ("migration_teardown_in_progress", "migration_runtime_stopping"),
+ # An ordinary restart may be draining live work for minutes, not stopping
+ # interrupted work, so it is not reported as about to finish.
+ ("backend_restart_in_progress", "migration_native_busy"),
+ ("external_native_processes", "migration_native_busy"),
+])
+def test_refused_migration_says_whether_avibe_or_an_outside_cli_holds_the_backend(
+ monkeypatch, tmp_path, reason, code,
+):
+ """MH-MIG-014: work Avibe itself interrupted and is still stopping is not a CLI
+ running outside Avibe; telling the user to quit external CLIs sends them the
+ wrong way while a retry in a moment would succeed."""
+ from core.backend_restart import NativeMigrationBlockedError
+
+ home = tmp_path / "native"
+ _write_codex_oauth(home)
+ _isolate_native_home(monkeypatch, home)
+ service, store, _ = _service(tmp_path, migration_home=home)
+ store.config.agents["codex"].mode = "direct"
+ item_ids = [item["id"] for item in service.migration_scan()["items"]]
+
+ @asynccontextmanager
+ async def refusing(backends, *, external_processes=True):
+ raise NativeMigrationBlockedError(reason, backends)
+ yield # pragma: no cover - required async context-manager shape
+
+ service.migration_guard = refusing
+ with pytest.raises(ModelHubError) as refusal:
+ asyncio.run(service.migration_apply(item_ids, clean_api_keys=True))
+
+ assert (refusal.value.status, refusal.value.code) == (409, code)
+ assert store.config.agents["codex"].mode == "direct"
+ assert service.migration_journal.load() is None
diff --git a/tests/test_native_takeover_lifecycle.py b/tests/test_native_takeover_lifecycle.py
index 967610ad1..7925f1749 100644
--- a/tests/test_native_takeover_lifecycle.py
+++ b/tests/test_native_takeover_lifecycle.py
@@ -206,6 +206,39 @@ async def test_busy_guard_interrupts_running_work_then_retires_and_yields(drain_
assert not admissions and not turns
+async def test_switch_waits_out_a_teardown_that_takes_its_bounded_worst_case(monkeypatch):
+ """MH-MIG-013: by the time the switch waits, the user's work is already
+ interrupted. Refusing beside the teardown loses the work and the switch
+ together, so a healthy teardown that runs well past the old 10 s window,
+ as the forced stop of a live runtime does on slow storage, must complete
+ the switch under the production threshold."""
+ controller, _, admissions, turns = controller_fixture(busy=True)
+ service = controller.agent_service
+ coordinator = BackendRestartCoordinator(
+ controller, AsyncMock(), process_inventory=Mock(return_value=()), drain_timeout=0.01, poll_interval=0.001,
+ )
+ controller.backend_restart_coordinator = coordinator
+ loop = asyncio.get_running_loop()
+ elapsed = 0.0
+ real_time = loop.time
+ monkeypatch.setattr(loop, "time", lambda: real_time() + elapsed)
+
+ async def slow_teardown(backend, forced):
+ nonlocal elapsed
+ # Owner cancellation and tidy-up plus a SIGTERM-to-SIGKILL runtime stop.
+ elapsed += 15.0
+ await asyncio.sleep(0.01)
+ service.backend_runtime_active.return_value = False
+
+ coordinator._refresh.side_effect = slow_teardown
+ async with coordinator.migration_guard(("codex",)):
+ assert admissions == turns == {"codex"}
+ coordinator._refresh.assert_awaited_once_with("codex", True)
+ service.agents["codex"].retire_for_native_migration.assert_awaited_once()
+ assert admissions == turns == set()
+
+
@pytest.mark.asyncio
@pytest.mark.parametrize("leaves", ["cancelled", "settle_window"])
async def test_abandoned_switch_keeps_admission_closed_until_teardown_completes(leaves):
@@ -244,7 +277,9 @@ async def test_abandoned_switch_keeps_admission_closed_until_teardown_completes(
# config writer starts beside it, and a retry refuses at once.
with pytest.raises(NativeMigrationBlockedError, match="native_auth_in_progress"):
NativeCredentialLease(("codex",)).acquire()
- with pytest.raises(NativeMigrationBlockedError, match="backend_restart_in_progress"):
+ # The retry is refused as the handed-off teardown, not as an ordinary
+ # restart, so it can be reported as interrupted work still stopping.
+ with pytest.raises(NativeMigrationBlockedError, match="migration_teardown_in_progress"):
async with coordinator.migration_guard(("codex",)):
pytest.fail("a retry entered beside an unfinished teardown")
finally:
diff --git a/ui/src/components/settings/models/MigrationDialog.test.tsx b/ui/src/components/settings/models/MigrationDialog.test.tsx
index 12c7bdad3..12211229a 100644
--- a/ui/src/components/settings/models/MigrationDialog.test.tsx
+++ b/ui/src/components/settings/models/MigrationDialog.test.tsx
@@ -290,7 +290,7 @@ describe('MigrationDialog — the settings default', () => {
const start = within(dialog).getByRole('button', { name: 'Start migration' });
await user.click(start);
- await waitFor(() => expect(showToast).toHaveBeenCalledWith('Migration failed, please retry', 'error'));
+ expect((await within(dialog).findByRole('alert')).textContent).toBe('Migration failed, please retry');
expect(onClose).not.toHaveBeenCalled();
expect((start as HTMLButtonElement).disabled).toBe(false);
@@ -314,12 +314,13 @@ describe('MigrationDialog — the settings default', () => {
it.each([
['migration_native_busy', 'Something is still using these assistants. Retry in a moment; if it keeps failing, quit any CLI running outside Avibe, including terminal sessions, IDE extensions and desktop apps.'],
+ ['migration_runtime_stopping', 'The task these assistants were running in Avibe is still stopping. Try again in a moment.'],
['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.'],
['migration_configuration_blocked', 'Adjust the native configuration, then scan again.'],
['migration_reauthorization_required', 'This backend was already migrated, and the changed native login cannot be verified as a new authorization. The original files are unchanged. Sign in again for the existing source in Model Hub instead of importing this login.'],
- ] as const)('maps %s to concise localized copy', async (code, message) => {
+ ] as const)('explains a batch refused as %s inside the dialog', async (code, message) => {
vi.spyOn(modelsApi, 'scanMigration').mockResolvedValue({ items: [{ ...CODEX_KEY }] });
vi.spyOn(modelsApi, 'applyMigration').mockRejectedValue(new ApiCallError(code));
renderDialog();
@@ -329,7 +330,10 @@ describe('MigrationDialog — the settings default', () => {
await waitFor(() => expect(within(dialog).getByText('OpenAI')).toBeTruthy());
await user.click(within(dialog).getByRole('button', { name: 'Start migration' }));
- await waitFor(() => expect(showToast).toHaveBeenCalledWith(message, 'error'));
+ // The dialog stays open on the same selection, so the reason stays beside
+ // the retry instead of fading out of a toast at the edge of the screen.
+ expect((await within(dialog).findByRole('alert')).textContent).toBe(message);
+ expect(showToast).not.toHaveBeenCalledWith(message, 'error');
});
it('keeps selection and explains configuration or credential verification failure in Chinese', async () => {
@@ -344,10 +348,9 @@ describe('MigrationDialog — the settings default', () => {
await within(dialog).findByText('OpenAI');
await user.click(within(dialog).getByRole('button', { name: '开始迁移' }));
- await waitFor(() => expect(showToast).toHaveBeenCalledWith(
+ expect((await within(dialog).findByRole('alert')).textContent).toBe(
'无法验证已保存的配置或凭据。请检查配置文件和认证是否有效后重试,或在模型网关中手动添加供应商。',
- 'error',
- ));
+ );
expect(onClose).not.toHaveBeenCalled();
expect(rowCheckboxes(dialog)[0].getAttribute('aria-checked')).toBe('true');
expect((within(dialog).getByRole('button', { name: '开始迁移' }) as HTMLButtonElement).disabled).toBe(false);
@@ -403,10 +406,7 @@ describe('MigrationDialog — the settings default', () => {
await waitFor(() => expect(within(dialog).getByText('OpenAI')).toBeTruthy());
await user.click(within(dialog).getByRole('button', { name: 'Start migration' }));
- await waitFor(() => expect(showToast).toHaveBeenCalledWith(
- 'Migration is unfinished. Retry to continue.',
- 'error',
- ));
+ expect((await within(dialog).findByRole('alert')).textContent).toBe('Migration is unfinished. Retry to continue.');
expect(screen.getByRole('dialog')).toBeTruthy();
expect(onApplied).not.toHaveBeenCalled();
expect(onClose).not.toHaveBeenCalled();
@@ -943,6 +943,42 @@ describe('MigrationDialog — the setup scope', () => {
expect(applied).toEqual([[CODEX_KEY.id], [LEGACY.id]]);
});
+ it('freezes the selection while a batch is in flight so its refusal describes the rows shown', async () => {
+ let refuse: (error: unknown) => void = () => {};
+ vi.spyOn(modelsApi, 'scanMigration').mockResolvedValue({ items: [{ ...CODEX_KEY }] });
+ vi.spyOn(modelsApi, 'applyMigration').mockImplementation(
+ () => new Promise((_resolve, reject) => { refuse = reject; }),
+ );
+ renderDialog();
+ const user = userEvent.setup();
+
+ const dialog = await screen.findByRole('dialog');
+ await within(dialog).findByText('OpenAI');
+ await user.click(within(dialog).getByRole('button', { name: 'Start migration' }));
+ await within(dialog).findByRole('button', { name: 'Migrating…' });
+
+ await user.click(rowCheckboxes(dialog)[0]);
+ expect(rowCheckboxes(dialog)[0].getAttribute('aria-checked')).toBe('true');
+
+ refuse(new ApiCallError('migration_runtime_stopping'));
+ await within(dialog).findByRole('alert');
+ expect(rowCheckboxes(dialog)[0].getAttribute('aria-checked')).toBe('true');
+ });
+
+ it('drops the refusal once the selection it explained changes', async () => {
+ vi.spyOn(modelsApi, 'applyMigration').mockRejectedValue(new ApiCallError('migration_runtime_stopping'));
+ renderSetup({ scan: [CODEX_KEY, LEGACY] });
+ const user = userEvent.setup();
+
+ const dialog = await screen.findByRole('dialog');
+ await user.click(within(dialog).getByRole('checkbox', { name: /sk-…9f21/ }));
+ await user.click(within(dialog).getByRole('button', { name: 'Start migration' }));
+ await within(dialog).findByRole('alert');
+
+ await user.click(within(dialog).getByRole('checkbox', { name: /sk-…9f21/ }));
+ expect(within(dialog).queryByRole('alert')).toBeNull();
+ });
+
it('returns to the same selection after a failed batch', async () => {
vi.spyOn(modelsApi, 'applyMigration').mockRejectedValue(
new ApiCallError('migration_native_busy', 'busy'),
@@ -954,7 +990,7 @@ describe('MigrationDialog — the setup scope', () => {
await user.click(within(dialog).getByRole('checkbox', { name: /sk-…9f21/ }));
await user.click(within(dialog).getByRole('button', { name: 'Start migration' }));
- await waitFor(() => expect(showToast).toHaveBeenCalled());
+ await within(dialog).findByRole('alert');
const confirm = await within(dialog).findByRole('button', { name: 'Start migration' });
expect((confirm as HTMLButtonElement).disabled).toBe(false);
expect(within(dialog).getByRole('checkbox', { name: /sk-…9f21/ }).getAttribute('aria-checked')).toBe('true');
diff --git a/ui/src/components/settings/models/MigrationDialog.tsx b/ui/src/components/settings/models/MigrationDialog.tsx
index 77940dd28..7a665d8c5 100644
--- a/ui/src/components/settings/models/MigrationDialog.tsx
+++ b/ui/src/components/settings/models/MigrationDialog.tsx
@@ -112,6 +112,7 @@ const DEFAULT_SCOPE = () => true;
const MIGRATION_ERROR_KEYS: Record<string, TranslationKey> = {
migration_native_busy: 'settings.models.migration.errors.nativeBusy',
+ migration_runtime_stopping: 'settings.models.migration.errors.runtimeStopping',
migration_permission_needed: 'settings.models.migration.errors.permissionNeeded',
migration_recovery_pending: 'settings.models.migration.errors.recoveryPending',
migration_item_conflict: 'settings.models.migration.errors.itemConflict',
@@ -280,6 +281,8 @@ export const MigrationDialog: React.FC<{
const [ownLoading, setOwnLoading] = React.useState(true);
const [applying, setApplying] = React.useState(false);
const [phase, setPhase] = React.useState<SetupPhase>({ kind: 'select' });
+ /** Why the last batch was refused, shown beside the selection it is retried from. */
+ const [applyError, setApplyError] = React.useState<TranslationKey | null>(null);
/** Consent to also delete the copied API keys natively. Subscription logins
* always move: a rotating refresh token cannot have two owners. */
const [cleanApiKeys, setCleanApiKeys] = React.useState(false);
@@ -298,6 +301,7 @@ export const MigrationDialog: React.FC<{
setPhase({ kind: 'select' });
setCompleted(0);
setCleanApiKeys(false);
+ setApplyError(null);
}, [open]);
React.useEffect(() => {
@@ -342,8 +346,13 @@ export const MigrationDialog: React.FC<{
.map((group) => group.backend),
);
const toggle = (backend: AgentBackend) => {
+ // A batch in flight owns its selection, like every other control here: its
+ // outcome, success or refusal, then always describes the rows on screen.
+ if (applying) return;
const group = grouped.find((item) => item.backend === backend);
if (!group || !groupSelectable(group)) return;
+ // The reason explained the batch that was refused, not the one now selected.
+ setApplyError(null);
if (controlled) {
// Toggling any member selects or deselects the whole linked group.
const next = new Set(value.selectedBackends);
@@ -378,6 +387,7 @@ export const MigrationDialog: React.FC<{
// raced the render, or a caller invoking the confirm path some other way.
if (!writable || applying || selectedCount === 0) return;
setApplying(true);
+ setApplyError(null);
if (scope === 'setup') setPhase({ kind: 'applying', count: selectedCount });
try {
const ids = appliable.map((i) => i.id);
@@ -399,10 +409,13 @@ export const MigrationDialog: React.FC<{
const key =
MIGRATION_ERROR_KEYS[code ?? ''] ??
'settings.models.migration.applyFailed';
- showToast(t(key) as string, 'error');
if (code === 'migration_credentials_invalid') {
+ // The dialog closes, so the reason outlives it as a toast.
+ showToast(t(key) as string, 'error');
onApplied?.(0);
onClose();
+ } else {
+ setApplyError(key);
}
}
} finally {
@@ -481,7 +494,7 @@ export const MigrationDialog: React.FC<{
key={item.id}
item={item}
checked={!group.blocked && selectedBackends.has(group.backend)}
- selectable={!group.blocked && isImportable(item)}
+ selectable={!applying && !group.blocked && isImportable(item)}
onToggle={() => toggle(group.backend)}
/>
))}
@@ -491,7 +504,10 @@ export const MigrationDialog: React.FC<{
<div className="flex items-start gap-3 rounded-xl border border-border px-3.5 py-3">
<Checkbox
checked={cleanApiKeys}
- onCheckedChange={setCleanApiKeys}
+ onCheckedChange={(checked) => {
+ setCleanApiKeys(checked);
+ setApplyError(null);
+ }}
disabled={applying}
label={t('settings.models.migration.cleanApiKeys') as string}
className="mt-px"
@@ -503,6 +519,9 @@ export const MigrationDialog: React.FC<{
</div>
)}
<p className="px-1 text-[12px] leading-relaxed text-muted">{t('settings.models.migration.interruptNotice')}</p>
+ {applyError && (
+ <p role="alert" className="px-1 text-[12px] font-semibold leading-relaxed text-destructive-ink">{t(applyError)}</p>
+ )}
</div>
)}
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 3b08e58eb..afa722bfc 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -2048,6 +2048,7 @@
"interruptNotice": "Migrating interrupts any task the selected assistants are running in Avibe.",
"errors": {
"nativeBusy": "Something is still using these assistants. Retry in a moment; if it keeps failing, quit any CLI running outside Avibe, including terminal sessions, IDE extensions and desktop apps.",
+ "runtimeStopping": "The task these assistants were running in Avibe is still stopping. Try again in a moment.",
"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 c83a214e6..84ea2ebe1 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -2048,6 +2048,7 @@
"interruptNotice": "迁移会中断所选助手在 Avibe 中正在运行的任务。",
"errors": {
"nativeBusy": "这些助手仍在被占用。请稍后重试;如果仍然失败,请退出在 Avibe 之外运行的 CLI(包括终端、IDE 插件和桌面应用)。",
+ "runtimeStopping": "这些助手刚才在 Avibe 中运行的任务还在停止中,请稍后重试。",
"permissionNeeded": "请允许访问凭据,再重试。",
"recoveryPending": "迁移尚未完成,请重试以继续。",
"itemConflict": "无法验证已保存的配置或凭据。请检查配置文件和认证是否有效后重试,或在模型网关中手动添加供应商。",