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.

feat(memory): wire cloud model service client

cyhd34f0aa77984
diff --git a/config/v2_config.py b/config/v2_config.py
index 6ab217e14..15bd2a4cb 100644
--- a/config/v2_config.py
+++ b/config/v2_config.py
@@ -1705,6 +1705,11 @@ class AudioAsrConfig:
_MEMORY_MAX_URL_BYTES = 2048
_MEMORY_MAX_MODEL_BYTES = 512
_MEMORY_MAX_API_KEY_BYTES = 16 * 1024
+_MEMORY_CLOUD_MODEL_ALIAS = "avibe-cloud-chat"
+_MEMORY_CLOUD_MULTIMODAL_ALIAS = "avibe-cloud-multimodal"
+
+MemoryMode = Literal["platform", "custom"]
+MemoryCloudScope = Literal["organization", "platform"]
@dataclass
@@ -1762,6 +1767,100 @@ class MemoryProcessingConfig:
)
+@dataclass
+class MemoryCloudCapabilities:
+ asr: bool = False
+ chat: bool = False
+ embedding: bool = False
+ multimodal: bool = False
+
+ def validate(self) -> None:
+ if any(
+ not isinstance(value, bool)
+ for value in (self.asr, self.chat, self.embedding, self.multimodal)
+ ):
+ raise ValueError("Config 'memory.cloud.capabilities' values must be booleans")
+
+ def memory_available(self) -> bool:
+ return self.chat and self.embedding
+
+
+@dataclass
+class MemoryCloudConfig:
+ """Cached Cloud Model Service resolution and write-only model key."""
+
+ scope: MemoryCloudScope | None = None
+ capabilities: MemoryCloudCapabilities = field(default_factory=MemoryCloudCapabilities)
+ embedding_identity: str | None = None
+ revision: int | None = None
+ quota_enforced: bool = False
+ model_access_key: str | None = field(default=None, repr=False)
+ proxy_base_url: str | None = None
+ source_instance_id: str = ""
+ organization_attached: bool = False
+ transition_notice_pending: bool = False
+ applied_embedding_identity: str | None = None
+ runtime_apply_pending: bool = False
+
+ def validate(self) -> None:
+ if self.scope is not None and self.scope not in get_args(MemoryCloudScope):
+ raise ValueError("Config 'memory.cloud.scope' must be 'organization', 'platform', or null")
+ self.capabilities.validate()
+ if self.embedding_identity is not None:
+ self.embedding_identity = _validate_memory_text(
+ self.embedding_identity,
+ name="memory.cloud.embedding_identity",
+ maximum=_MEMORY_MAX_MODEL_BYTES,
+ )
+ if self.applied_embedding_identity is not None:
+ self.applied_embedding_identity = _validate_memory_text(
+ self.applied_embedding_identity,
+ name="memory.cloud.applied_embedding_identity",
+ maximum=_MEMORY_MAX_MODEL_BYTES,
+ )
+ if self.revision is not None and (
+ isinstance(self.revision, bool)
+ or not isinstance(self.revision, int)
+ or self.revision < 0
+ ):
+ raise ValueError("Config 'memory.cloud.revision' must be a non-negative integer or null")
+ for name, value in (
+ ("quota_enforced", self.quota_enforced),
+ ("organization_attached", self.organization_attached),
+ ("transition_notice_pending", self.transition_notice_pending),
+ ("runtime_apply_pending", self.runtime_apply_pending),
+ ):
+ if not isinstance(value, bool):
+ raise ValueError(f"Config 'memory.cloud.{name}' must be a boolean")
+ if not isinstance(self.source_instance_id, str):
+ raise ValueError("Config 'memory.cloud.source_instance_id' must be a string")
+ self.source_instance_id = self.source_instance_id.strip()
+ if len(self.source_instance_id.encode("utf-8")) > _MEMORY_MAX_MODEL_BYTES:
+ raise ValueError("Config 'memory.cloud.source_instance_id' is invalid")
+ if self.proxy_base_url is not None:
+ self.proxy_base_url = _validate_memory_url(
+ self.proxy_base_url,
+ name="cloud.proxy",
+ )
+ if self.model_access_key is not None:
+ self.model_access_key = _validate_memory_key(
+ self.model_access_key,
+ name="cloud.model_access_key",
+ )
+ if not self.model_access_key.startswith("mak_"):
+ raise ValueError("Config 'memory.cloud.model_access_key' is invalid")
+
+ def memory_capability_available(self) -> bool:
+ return bool(
+ self.capabilities.memory_available()
+ and self.embedding_identity
+ and self.proxy_base_url
+ )
+
+ def runtime_ready(self) -> bool:
+ return self.memory_capability_available() and bool(self.model_access_key)
+
+
@dataclass
class MemoryDiagnosticsConfig:
# Retained only so older config files continue to load. Provider call
@@ -1785,13 +1884,17 @@ class MemoryConfig:
"""Persisted local EverOS configuration; credentials are API-write-only."""
enabled: bool = False
+ mode: MemoryMode | None = None
processing: MemoryProcessingConfig = field(default_factory=MemoryProcessingConfig)
+ cloud: MemoryCloudConfig = field(default_factory=MemoryCloudConfig)
diagnostics: MemoryDiagnosticsConfig = field(default_factory=MemoryDiagnosticsConfig)
recovery_intent: MemoryRecoveryIntent | None = None
def validate(self) -> None:
if not isinstance(self.enabled, bool):
raise ValueError("Config 'memory.enabled' must be a boolean")
+ if self.mode is not None and self.mode not in get_args(MemoryMode):
+ raise ValueError("Config 'memory.mode' must be 'platform', 'custom', or null")
if self.recovery_intent is not None and (
not isinstance(self.recovery_intent, str)
or self.recovery_intent not in MEMORY_RECOVERY_INTENTS
@@ -1800,10 +1903,102 @@ class MemoryConfig:
"Config 'memory.recovery_intent' must be 'rebuild', 'factory_reset', or null"
)
self.processing.validate()
+ self.cloud.validate()
self.diagnostics.validate()
- if self.enabled and not (self.processing.llm.complete() and self.processing.embedding.complete()):
+ if (
+ self.enabled
+ and not self.cloud_runtime_selected()
+ and not self.custom_processing_complete()
+ ):
raise ValueError("Both Memory processing endpoints must be complete before enabling Memory")
+ def custom_processing_complete(self) -> bool:
+ return self.processing.llm.complete() and self.processing.embedding.complete()
+
+ def cloud_runtime_selected(self) -> bool:
+ if self.cloud.scope == "organization":
+ # A pending enterprise transition is deliberately fenced on the
+ # last applied custom identity until the user confirms the rebuild.
+ return self.cloud.organization_attached
+ return self.cloud.scope == "platform" and self.mode == "platform"
+
+ def runtime_source(self) -> Literal["cloud", "custom", "unavailable"]:
+ if self.cloud_runtime_selected():
+ return "cloud" if self.cloud.runtime_ready() else "unavailable"
+ if self.custom_processing_complete():
+ return "custom"
+ return "unavailable"
+
+ def settings_mode(self) -> Literal["organization", "platform", "custom"]:
+ if self.cloud.scope == "organization":
+ # An organization without the complete Memory pair cannot replace
+ # a released working custom setup. Fresh installs still get the
+ # read-only managed state instead of a misleading platform fallback.
+ if self.custom_processing_complete() and not (
+ self.cloud.memory_capability_available()
+ or self.cloud.organization_attached
+ or self.cloud.transition_notice_pending
+ ):
+ return "custom"
+ return "organization"
+ if self.cloud.scope == "platform" and self.mode == "platform":
+ return "platform"
+ return "custom"
+
+ def runtime_processing(self) -> MemoryProcessingConfig:
+ """Return the sidecar-facing endpoints without changing saved custom slots."""
+
+ if not self.cloud_runtime_selected():
+ return self.processing
+ if not self.cloud.runtime_ready():
+ return MemoryProcessingConfig()
+ base_url = self.cloud.proxy_base_url
+ key = self.cloud.model_access_key
+ embedding_identity = self.cloud.embedding_identity
+ multimodal = None
+ if self.cloud.capabilities.multimodal:
+ multimodal = MemoryEndpointConfig(
+ base_url=f"{base_url}/mm",
+ model=_MEMORY_CLOUD_MULTIMODAL_ALIAS,
+ api_key=key,
+ )
+ return MemoryProcessingConfig(
+ llm=MemoryEndpointConfig(
+ base_url=base_url,
+ model=_MEMORY_CLOUD_MODEL_ALIAS,
+ api_key=key,
+ ),
+ embedding=MemoryEndpointConfig(
+ base_url=base_url,
+ model=f"avibe-cloud-embedding-{embedding_identity}",
+ api_key=key,
+ ),
+ rerank=None,
+ multimodal=multimodal,
+ )
+
+ def runtime_embedding_identity(self) -> tuple[str, str | None, str | None]:
+ if self.cloud_runtime_selected():
+ # Capability removal clears the live status identity, but the last
+ # applied value remains the comparison baseline for a checked resume.
+ return (
+ "cloud",
+ self.cloud.embedding_identity
+ or self.cloud.applied_embedding_identity,
+ None,
+ )
+ return (
+ "custom",
+ self.processing.embedding.base_url,
+ self.processing.embedding.model,
+ )
+
+ def effective_multimodal_available(self) -> bool:
+ if self.cloud_runtime_selected():
+ # Cloud chat is the declared fallback when no dedicated mm slot exists.
+ return self.cloud.runtime_ready() and self.cloud.capabilities.chat
+ return bool(self.processing.multimodal and self.processing.multimodal.complete())
+
def _validate_memory_url(value: object, *, name: str) -> Optional[str]:
if value is None or value == "":
@@ -1905,7 +2100,30 @@ def memory_config_to_payload(
processing["multimodal"] = endpoint_payload(memory.processing.multimodal)
payload = {
"enabled": memory.enabled,
+ "mode": memory.mode,
"processing": processing,
+ "cloud": {
+ "scope": memory.cloud.scope,
+ "capabilities": {
+ "asr": memory.cloud.capabilities.asr,
+ "chat": memory.cloud.capabilities.chat,
+ "embedding": memory.cloud.capabilities.embedding,
+ "multimodal": memory.cloud.capabilities.multimodal,
+ },
+ "embedding_identity": memory.cloud.embedding_identity,
+ "revision": memory.cloud.revision,
+ "quota_enforced": memory.cloud.quota_enforced,
+ "model_access_key": (
+ memory.cloud.model_access_key if include_secrets else None
+ ),
+ "has_model_access_key": bool(memory.cloud.model_access_key),
+ "proxy_base_url": memory.cloud.proxy_base_url,
+ "source_instance_id": memory.cloud.source_instance_id,
+ "organization_attached": memory.cloud.organization_attached,
+ "transition_notice_pending": memory.cloud.transition_notice_pending,
+ "applied_embedding_identity": memory.cloud.applied_embedding_identity,
+ "runtime_apply_pending": memory.cloud.runtime_apply_pending,
+ },
"diagnostics": {
"log_provider_calls": memory.diagnostics.log_provider_calls,
},
@@ -1955,6 +2173,14 @@ def memory_config_from_payload(payload: object) -> MemoryConfig:
payload.get("diagnostics", {}),
name="memory.diagnostics",
)
+ cloud_payload = _optional_memory_object(
+ payload.get("cloud", {}),
+ name="memory.cloud",
+ )
+ cloud_capabilities_payload = _optional_memory_object(
+ cloud_payload.get("capabilities", {}),
+ name="memory.cloud.capabilities",
+ )
legacy_present = "embedding_change_pending" in payload
legacy_pending = payload.get("embedding_change_pending", False)
@@ -1977,6 +2203,7 @@ def memory_config_from_payload(payload: object) -> MemoryConfig:
memory = MemoryConfig(
enabled=payload.get("enabled", False),
+ mode=payload.get("mode"),
recovery_intent=recovery_intent,
processing=MemoryProcessingConfig(
llm=MemoryEndpointConfig(
@@ -2003,6 +2230,20 @@ def memory_config_from_payload(payload: object) -> MemoryConfig:
else None
),
),
+ cloud=MemoryCloudConfig(
+ **_filter_dataclass_fields(
+ MemoryCloudConfig,
+ {
+ **cloud_payload,
+ "capabilities": MemoryCloudCapabilities(
+ **_filter_dataclass_fields(
+ MemoryCloudCapabilities,
+ cloud_capabilities_payload,
+ )
+ ),
+ },
+ )
+ ),
diagnostics=MemoryDiagnosticsConfig(
**_filter_dataclass_fields(
MemoryDiagnosticsConfig,
diff --git a/core/memory/runtime.py b/core/memory/runtime.py
index e167396cc..18cc83d17 100644
--- a/core/memory/runtime.py
+++ b/core/memory/runtime.py
@@ -774,13 +774,14 @@ class MemoryRuntime:
if self._store is None:
self._insight_reader = None
return
- rerank = config.processing.rerank
- multimodal = config.processing.multimodal
+ processing = config.runtime_processing()
+ rerank = processing.rerank
+ multimodal = processing.multimodal
base_urls = tuple(
value
for value in (
- config.processing.llm.base_url,
- config.processing.embedding.base_url,
+ processing.llm.base_url,
+ processing.embedding.base_url,
rerank.base_url if rerank else None,
multimodal.base_url if multimodal else None,
)
@@ -789,8 +790,8 @@ class MemoryRuntime:
exact_redaction_values = tuple(
value
for value in (
- config.processing.llm.api_key,
- config.processing.embedding.api_key,
+ processing.llm.api_key,
+ processing.embedding.api_key,
rerank.api_key if rerank else None,
multimodal.api_key if multimodal else None,
)
@@ -1049,6 +1050,25 @@ class MemoryRuntime:
self._runtime_error = "memory_factory_reset_failed"
return {"ok": False, "error": self._runtime_error}
+ if config.cloud_runtime_selected() and config.runtime_source() == "unavailable":
+ # A managed scope losing either half of the chat+embedding pair is
+ # a pause, never a fallback to saved custom providers. Capture can
+ # keep queuing while claims and the old sidecar stay fenced.
+ self.module.pause_claims()
+ await self._stop_worker()
+ await self._sidecar.stop()
+ self._config = deepcopy(config)
+ self._restart_config = deepcopy(config)
+ self._configure_insight_reader(config)
+ self._provider = EverOSPort(self._socket_path)
+ self.module.replace_provider(self._provider)
+ self._runtime_error = "memory_cloud_model_unavailable"
+ return {
+ "ok": True,
+ "state": "paused",
+ "reason": self._runtime_error,
+ }
+
embedding_changed = (
not skip_embedding_guard
and _embedding_configuration_changed(self._config, config)
@@ -1349,13 +1369,11 @@ class MemoryRuntime:
"""Return the stable explicit opt-in generation without probing providers."""
snapshot = self._processing_runtime_snapshot()
- multimodal = self._config.processing.multimodal
- if snapshot.transition_active or not self._config.enabled or multimodal is None:
- return None
- try:
- if not multimodal.complete():
- return None
- except Exception:
+ if (
+ snapshot.transition_active
+ or not self._config.enabled
+ or not self._config.effective_multimodal_available()
+ ):
return None
return snapshot.generation
@@ -2455,30 +2473,31 @@ class MemoryRuntime:
async def preflight(self, config: MemoryConfig | None = None) -> dict[str, Any]:
candidate = deepcopy(config or self._config)
+ processing = candidate.runtime_processing()
provider = EverOSPort(
self._socket_path,
- llm_base_url=candidate.processing.llm.base_url,
- llm_model=candidate.processing.llm.model,
- llm_api_key=candidate.processing.llm.api_key,
- embedding_base_url=candidate.processing.embedding.base_url,
- embedding_model=candidate.processing.embedding.model,
- embedding_api_key=candidate.processing.embedding.api_key,
- rerank_base_url=(candidate.processing.rerank.base_url if candidate.processing.rerank else None),
- rerank_model=(candidate.processing.rerank.model if candidate.processing.rerank else None),
- rerank_api_key=(candidate.processing.rerank.api_key if candidate.processing.rerank else None),
+ llm_base_url=processing.llm.base_url,
+ llm_model=processing.llm.model,
+ llm_api_key=processing.llm.api_key,
+ embedding_base_url=processing.embedding.base_url,
+ embedding_model=processing.embedding.model,
+ embedding_api_key=processing.embedding.api_key,
+ rerank_base_url=(processing.rerank.base_url if processing.rerank else None),
+ rerank_model=(processing.rerank.model if processing.rerank else None),
+ rerank_api_key=(processing.rerank.api_key if processing.rerank else None),
multimodal_base_url=(
- candidate.processing.multimodal.base_url
- if candidate.processing.multimodal
+ processing.multimodal.base_url
+ if processing.multimodal
else None
),
multimodal_model=(
- candidate.processing.multimodal.model
- if candidate.processing.multimodal
+ processing.multimodal.model
+ if processing.multimodal
else None
),
multimodal_api_key=(
- candidate.processing.multimodal.api_key
- if candidate.processing.multimodal
+ processing.multimodal.api_key
+ if processing.multimodal
else None
),
preflight_call_recorder=self._record_preflight_call,
@@ -3689,15 +3708,16 @@ class MemoryRuntime:
def _provider_kwargs(config: MemoryConfig) -> dict[str, str | None]:
- rerank = config.processing.rerank
- multimodal = config.processing.multimodal
+ processing = config.runtime_processing()
+ rerank = processing.rerank
+ multimodal = processing.multimodal
return {
- "llm_base_url": config.processing.llm.base_url,
- "llm_model": config.processing.llm.model,
- "llm_api_key": config.processing.llm.api_key,
- "embedding_base_url": config.processing.embedding.base_url,
- "embedding_model": config.processing.embedding.model,
- "embedding_api_key": config.processing.embedding.api_key,
+ "llm_base_url": processing.llm.base_url,
+ "llm_model": processing.llm.model,
+ "llm_api_key": processing.llm.api_key,
+ "embedding_base_url": processing.embedding.base_url,
+ "embedding_model": processing.embedding.model,
+ "embedding_api_key": processing.embedding.api_key,
"rerank_base_url": rerank.base_url if rerank else None,
"rerank_model": rerank.model if rerank else None,
"rerank_api_key": rerank.api_key if rerank else None,
@@ -3714,7 +3734,7 @@ def _attachment_capture_status(
) -> Literal["ready", "not_configured", "unavailable"]:
"""Project explicit IM attachment-capture readiness from config and health."""
- if config.processing.multimodal is None:
+ if not config.effective_multimodal_available():
return "not_configured"
if not IM_ATTACHMENT_CAPTURE_PLATFORMS:
return "unavailable"
@@ -3754,12 +3774,7 @@ def _active_compatible_root_formats(artifact_manager: MemoryArtifactPort) -> tup
def _embedding_configuration_changed(current: MemoryConfig, candidate: MemoryConfig) -> bool:
"""Compare only settings that define the embedding vector space."""
- current_embedding = current.processing.embedding
- candidate_embedding = candidate.processing.embedding
- return (
- current_embedding.base_url != candidate_embedding.base_url
- or current_embedding.model != candidate_embedding.model
- )
+ return current.runtime_embedding_identity() != candidate.runtime_embedding_identity()
def _same_embedding_identity(current: MemoryConfig, candidate: MemoryConfig) -> bool:
@@ -3795,7 +3810,8 @@ def _rebuild_settings_usable(settings: EverOSProcessSettings) -> bool:
def _memory_processing_complete(config: MemoryConfig) -> bool:
"""Return whether both configured processing providers can be contacted."""
- return config.processing.llm.complete() and config.processing.embedding.complete()
+ processing = config.runtime_processing()
+ return processing.llm.complete() and processing.embedding.complete()
def _rebuild_public_result(result: RebuildProcessResult) -> dict[str, Any]:
diff --git a/tests/fixtures/memory/released_mode_initialization.json b/tests/fixtures/memory/released_mode_initialization.json
new file mode 100644
index 000000000..b210b5655
--- /dev/null
+++ b/tests/fixtures/memory/released_mode_initialization.json
@@ -0,0 +1,54 @@
+[
+ {
+ "name": "released complete manual configuration",
+ "config": {
+ "mode": "self_host",
+ "version": "v2",
+ "slack": { "bot_token": "" },
+ "runtime": { "default_cwd": "." },
+ "agents": {},
+ "memory": {
+ "enabled": true,
+ "processing": {
+ "llm": {
+ "base_url": "https://llm.example.test/v1",
+ "model": "chat-v1",
+ "api_key": "llm-secret"
+ },
+ "embedding": {
+ "base_url": "https://embedding.example.test/v1",
+ "model": "embedding-v1",
+ "api_key": "embedding-secret"
+ }
+ }
+ }
+ },
+ "expected_mode": "custom"
+ },
+ {
+ "name": "released empty manual configuration",
+ "config": {
+ "mode": "self_host",
+ "version": "v2",
+ "slack": { "bot_token": "" },
+ "runtime": { "default_cwd": "." },
+ "agents": {},
+ "memory": {
+ "enabled": false,
+ "processing": {
+ "llm": {
+ "base_url": null,
+ "model": null,
+ "api_key": null
+ },
+ "embedding": {
+ "base_url": null,
+ "model": null,
+ "api_key": null
+ }
+ }
+ }
+ },
+ "expected_mode": "platform"
+ }
+]
diff --git a/tests/test_memory_runtime.py b/tests/test_memory_runtime.py
index 1519444c5..f24e38f40 100644
--- a/tests/test_memory_runtime.py
+++ b/tests/test_memory_runtime.py
@@ -77,6 +77,8 @@ from core.memory.types import (
from config.v2_config import (
AgentsConfig,
MEMORY_RECOVERY_INTENTS,
+ MemoryCloudCapabilities,
+ MemoryCloudConfig,
MemoryConfig,
MemoryDiagnosticsConfig,
MemoryEndpointConfig,
@@ -3659,6 +3661,72 @@ async def test_runtime_reconciliation_restarts_sidecar_with_fresh_child_settings
await memory_runtime_factory.close(runtime)
+async def test_cloud_capability_removal_pauses_claims_keeps_capture_and_resumes_same_identity(
+ memory_runtime_factory,
+) -> None:
+ factory = FakeEverOSProcessFactory()
+ cloud = MemoryCloudConfig(
+ scope="organization",
+ capabilities=MemoryCloudCapabilities(chat=True, embedding=True),
+ embedding_identity="emb-v1",
+ applied_embedding_identity="emb-v1",
+ model_access_key="mak_first",
+ proxy_base_url="https://backend.example.test/v1/model",
+ source_instance_id="instance-1",
+ organization_attached=True,
+ )
+ initial = MemoryConfig(enabled=True, mode="platform", cloud=cloud)
+ runtime = memory_runtime_factory(
+ initial,
+ artifact_manager=_installed_artifact(),
+ process_factory=factory,
+ )
+ assert (await runtime.reconcile(initial))["ok"] is True
+
+ removed = replace(
+ initial,
+ cloud=replace(
+ cloud,
+ capabilities=replace(cloud.capabilities, embedding=False),
+ embedding_identity=None,
+ ),
+ )
+ paused = await runtime.reconcile(removed)
+ assert paused == {
+ "ok": True,
+ "state": "paused",
+ "reason": "memory_cloud_model_unavailable",
+ }
+ assert runtime.module._worker._claims_paused is True
+ assert factory.supervised[0].stopped is True
+
+ receipt = await runtime.module.capture(
+ CaptureRequest(
+ source_message_id="queued-during-capability-pause",
+ session_id="session-1",
+ principal_id=PRINCIPAL,
+ project_id=PROJECT,
+ provenance="user_input",
+ text="keep this queued",
+ occurred_at_ms=1_725_000_001_234,
+ )
+ )
+ assert isinstance(receipt, CaptureAccepted)
+
+ restored = replace(
+ removed,
+ cloud=replace(
+ removed.cloud,
+ capabilities=replace(removed.cloud.capabilities, embedding=True),
+ embedding_identity="emb-v1",
+ ),
+ )
+ assert (await runtime.reconcile(restored))["ok"] is True
+ assert runtime.module._worker._claims_paused is False
+ assert len(factory.supervised) == 2
+ await memory_runtime_factory.close(runtime)
+
+
async def test_runtime_reconciliation_rolls_sidecar_for_rerank_configuration(
memory_runtime_factory,
) -> None:
diff --git a/tests/test_model_service.py b/tests/test_model_service.py
new file mode 100644
index 000000000..a782c35a7
--- /dev/null
+++ b/tests/test_model_service.py
@@ -0,0 +1,539 @@
+from __future__ import annotations
+
+from copy import deepcopy
+import json
+from pathlib import Path
+
+import pytest
+
+from config.v2_config import (
+ AgentsConfig,
+ MemoryCloudCapabilities,
+ MemoryCloudConfig,
+ MemoryConfig,
+ MemoryEndpointConfig,
+ MemoryProcessingConfig,
+ RuntimeConfig,
+ SlackConfig,
+ V2Config,
+ memory_config_to_payload,
+)
+from core.memory import process as memory_process
+from core.memory import runtime as memory_runtime
+from core.memory.everos import MULTIMODAL_EXPLICIT_ENV
+from vibe import model_service, ui_memory_routes
+
+
+FIXTURE_PATH = Path(__file__).parent / "fixtures" / "memory" / "released_mode_initialization.json"
+
+
+def _status(
+ *,
+ scope: str = "platform",
+ chat: bool = True,
+ embedding: bool = True,
+ multimodal: bool = False,
+ identity: str | None = "emb-v1",
+ revision: int = 1,
+) -> dict:
+ return {
+ "mode": scope,
+ "capabilities": {
+ "asr": False,
+ "chat": chat,
+ "embedding": embedding,
+ "multimodal": multimodal,
+ },
+ "embedding_identity": identity,
+ "quota": {"enforced": False},
+ "revision": revision,
+ }
+
+
+def _mint(
+ key: str = "mak_first",
+ *,
+ rotated: bool = False,
+ previous_valid_until: str | None = None,
+) -> dict:
+ return {
+ "key": key,
+ "created_at": "2026-08-17T00:00:00Z",
+ "rotated": rotated,
+ "previous_valid_until": previous_valid_until,
+ }
+
+
+def _paired_config(memory: MemoryConfig | None = None) -> V2Config:
+ config = V2Config(
+ mode="self_host",
+ version="v2",
+ slack=SlackConfig(bot_token=""),
+ runtime=RuntimeConfig(default_cwd="."),
+ agents=AgentsConfig(),
+ memory=memory or MemoryConfig(),
+ )
+ cloud = config.remote_access.vibe_cloud
+ cloud.enabled = True
+ cloud.backend_url = "https://backend.example.test"
+ cloud.instance_id = "instance-1"
+ cloud.instance_secret = "device-secret"
+ return config
+
+
+def _manual_memory() -> MemoryConfig:
+ return MemoryConfig(
+ enabled=True,
+ processing=MemoryProcessingConfig(
+ llm=MemoryEndpointConfig(
+ "https://llm.example.test/v1",
+ "chat-v1",
+ "llm-secret",
+ ),
+ embedding=MemoryEndpointConfig(
+ "https://embedding.example.test/v1",
+ "embedding-v1",
+ "embedding-secret",
+ ),
+ ),
+ )
+
+
+def _resolved(
+ current: MemoryConfig,
+ payload: dict,
+ *,
+ minted: dict | None = None,
+) -> MemoryConfig:
+ return model_service._resolved_memory( # noqa: SLF001
+ current,
+ status=model_service._status_from_payload(payload), # noqa: SLF001
+ instance_id="instance-1",
+ proxy_base_url="https://backend.example.test/v1/model",
+ minted=(
+ model_service._mint_from_payload(minted) # noqa: SLF001
+ if minted is not None
+ else None
+ ),
+ )
+
+
+def test_released_memory_shapes_initialize_mode_without_reinterpreting_manual_config(
+ tmp_path: Path,
+) -> None:
+ fixtures = json.loads(FIXTURE_PATH.read_text(encoding="utf-8"))
+
+ for fixture in fixtures:
+ config_path = tmp_path / f"{fixture['name']}.json"
+ config_path.write_text(json.dumps(fixture["config"]), encoding="utf-8")
+ loaded = V2Config.load(config_path).memory
+ assert loaded.mode is None, fixture["name"]
+ assert (
+ model_service._memory_mode_after_initialization(loaded) # noqa: SLF001
+ == fixture["expected_mode"]
+ ), fixture["name"]
+
+
+def test_fresh_paired_install_gets_zero_config_cloud_memory_with_write_only_key(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _paired_config().save()
+ requests: list[tuple[str, str]] = []
+ reconciled: list[MemoryConfig] = []
+
+ def device_request(_config: V2Config, method: str, suffix: str) -> dict:
+ requests.append((method, suffix))
+ return _status(multimodal=False) if method == "GET" else _mint()
+
+ def reconcile(candidate: MemoryConfig) -> bool:
+ reconciled.append(deepcopy(candidate))
+ model_service._clear_apply_pending(candidate) # noqa: SLF001
+ return True
+
+ monkeypatch.setattr(model_service, "_device_request", device_request)
+ monkeypatch.setattr(model_service, "_reconcile_candidate", reconcile)
+
+ assert model_service.sync_model_service_once()["ok"] is True
+
+ memory = V2Config.load().memory
+ runtime = memory.runtime_processing()
+ assert requests == [
+ ("GET", "model-service"),
+ ("POST", "model-access-key"),
+ ]
+ assert memory.mode == "platform"
+ assert memory.settings_mode() == "platform"
+ assert memory.enabled is True
+ assert memory.cloud.model_access_key == "mak_first"
+ assert memory.cloud.embedding_identity == "emb-v1"
+ assert runtime.llm.base_url == "https://backend.example.test/v1/model"
+ assert runtime.llm.model == "avibe-cloud-chat"
+ assert runtime.embedding.model == "avibe-cloud-embedding-emb-v1"
+ assert runtime.llm.api_key == "mak_first"
+ assert runtime.multimodal is None
+ assert memory.effective_multimodal_available() is True
+ assert reconciled
+ projected = memory_config_to_payload(memory)
+ assert projected["cloud"]["model_access_key"] is None
+ assert projected["cloud"]["has_model_access_key"] is True
+
+
+def test_enterprise_attachment_pauses_custom_until_acknowledged() -> None:
+ current = _manual_memory()
+ status = model_service._status_from_payload( # noqa: SLF001
+ _status(scope="organization")
+ )
+ assert model_service._status_needs_model_key(current, status) is False # noqa: SLF001
+ candidate = _resolved(
+ current,
+ _status(scope="organization"),
+ )
+
+ assert candidate.settings_mode() == "organization"
+ assert candidate.cloud.transition_notice_pending is True
+ assert candidate.cloud.organization_attached is False
+ assert candidate.cloud.model_access_key is None
+ assert candidate.recovery_intent == "rebuild"
+ assert candidate.runtime_source() == "custom"
+ assert candidate.runtime_embedding_identity() == (
+ "custom",
+ "https://embedding.example.test/v1",
+ "embedding-v1",
+ )
+
+ ready_to_acknowledge = deepcopy(candidate)
+ ready_to_acknowledge.cloud.model_access_key = "mak_first"
+ current = _paired_config(ready_to_acknowledge)
+ target, confirm_rebuild = ui_memory_routes._memory_settings_patch( # noqa: SLF001
+ current,
+ {"acknowledge_transition": True, "confirm_rebuild": True},
+ )
+ acknowledged = ui_memory_routes._memory_candidate_config( # noqa: SLF001
+ current,
+ target,
+ ).memory
+ assert confirm_rebuild is True
+ assert acknowledged.cloud.transition_notice_pending is False
+ assert acknowledged.cloud.organization_attached is True
+ assert acknowledged.runtime_source() == "cloud"
+ assert acknowledged.runtime_embedding_identity() == ("cloud", "emb-v1", None)
+ assert (
+ ui_memory_routes._memory_embedding_configuration_changed( # noqa: SLF001
+ current,
+ _paired_config(acknowledged),
+ )
+ is True
+ )
+
+
+def test_enterprise_transition_acknowledgement_cannot_edit_custom_endpoints() -> None:
+ pending = _resolved(
+ _manual_memory(),
+ _status(scope="organization"),
+ )
+ pending.cloud.model_access_key = "mak_first"
+
+ with pytest.raises(ValueError, match="invalid_memory_patch"):
+ ui_memory_routes._memory_settings_patch( # noqa: SLF001
+ _paired_config(pending),
+ {
+ "acknowledge_transition": True,
+ "confirm_rebuild": True,
+ "processing": {
+ "embedding": {"model": "unauthorized-new-model"},
+ },
+ },
+ )
+
+
+def test_org_without_memory_pair_does_not_transition_released_custom_config() -> None:
+ current = _manual_memory()
+ candidate = _resolved(
+ current,
+ _status(
+ scope="organization",
+ chat=True,
+ embedding=False,
+ identity=None,
+ ),
+ )
+
+ assert candidate.settings_mode() == "custom"
+ assert candidate.runtime_source() == "custom"
+ assert candidate.cloud.transition_notice_pending is False
+ assert candidate.cloud.organization_attached is False
+ assert candidate.recovery_intent is None
+
+ fresh = _resolved(
+ MemoryConfig(),
+ _status(
+ scope="organization",
+ chat=False,
+ embedding=False,
+ identity=None,
+ ),
+ )
+ assert fresh.enabled is False
+ assert fresh.settings_mode() == "organization"
+ assert fresh.cloud.organization_attached is True
+ assert fresh.runtime_source() == "unavailable"
+
+
+def test_enterprise_without_memory_pair_pauses_an_active_platform_instance() -> None:
+ platform = MemoryConfig(
+ enabled=True,
+ mode="platform",
+ cloud=MemoryCloudConfig(
+ scope="platform",
+ capabilities=MemoryCloudCapabilities(chat=True, embedding=True),
+ embedding_identity="emb-platform",
+ applied_embedding_identity="emb-platform",
+ model_access_key="mak_first",
+ proxy_base_url="https://backend.example.test/v1/model",
+ source_instance_id="instance-1",
+ ),
+ )
+
+ paused = _resolved(
+ platform,
+ _status(
+ scope="organization",
+ chat=False,
+ embedding=False,
+ identity=None,
+ revision=2,
+ ),
+ )
+
+ assert paused.settings_mode() == "organization"
+ assert paused.cloud.organization_attached is True
+ assert paused.cloud.applied_embedding_identity == "emb-platform"
+ assert paused.enabled is True
+ assert paused.runtime_source() == "unavailable"
+
+
+def test_fresh_managed_instance_enables_when_organization_adds_memory_pair() -> None:
+ waiting = _resolved(
+ MemoryConfig(),
+ _status(
+ scope="organization",
+ chat=False,
+ embedding=False,
+ identity=None,
+ ),
+ )
+
+ activated = _resolved(
+ waiting,
+ _status(scope="organization", identity="emb-org", revision=2),
+ minted=_mint(),
+ )
+
+ assert activated.enabled is True
+ assert activated.cloud.organization_attached is True
+ assert activated.cloud.applied_embedding_identity == "emb-org"
+ assert activated.runtime_source() == "cloud"
+ assert activated.recovery_intent is None
+
+
+def test_capability_removal_pauses_and_resume_checks_last_applied_identity() -> None:
+ attached = MemoryConfig(
+ enabled=True,
+ mode="platform",
+ cloud=MemoryCloudConfig(
+ scope="organization",
+ capabilities=MemoryCloudCapabilities(chat=True, embedding=True),
+ embedding_identity="emb-v1",
+ applied_embedding_identity="emb-v1",
+ model_access_key="mak_first",
+ proxy_base_url="https://backend.example.test/v1/model",
+ source_instance_id="instance-1",
+ organization_attached=True,
+ ),
+ )
+ removed = _resolved(
+ attached,
+ _status(
+ scope="organization",
+ chat=False,
+ embedding=True,
+ identity="emb-v1",
+ revision=2,
+ ),
+ )
+ assert removed.runtime_source() == "unavailable"
+ assert removed.runtime_embedding_identity() == ("cloud", "emb-v1", None)
+ assert removed.recovery_intent is None
+
+ same_identity = _resolved(
+ removed,
+ _status(scope="organization", identity="emb-v1", revision=3),
+ )
+ assert same_identity.runtime_source() == "cloud"
+ assert same_identity.recovery_intent is None
+
+ changed_identity = _resolved(
+ removed,
+ _status(scope="organization", identity="emb-v2", revision=4),
+ )
+ assert changed_identity.runtime_source() == "cloud"
+ assert changed_identity.recovery_intent == "rebuild"
+
+
+def test_platform_to_organization_upstream_change_is_an_identity_change() -> None:
+ platform = MemoryConfig(
+ enabled=True,
+ mode="platform",
+ cloud=MemoryCloudConfig(
+ scope="platform",
+ capabilities=MemoryCloudCapabilities(chat=True, embedding=True),
+ embedding_identity="emb-platform",
+ applied_embedding_identity="emb-platform",
+ model_access_key="mak_first",
+ proxy_base_url="https://backend.example.test/v1/model",
+ source_instance_id="instance-1",
+ ),
+ )
+
+ organization = _resolved(
+ platform,
+ _status(scope="organization", identity="emb-organization", revision=2),
+ )
+
+ assert organization.cloud.organization_attached is True
+ assert organization.runtime_embedding_identity() == (
+ "cloud",
+ "emb-organization",
+ None,
+ )
+ assert organization.recovery_intent == "rebuild"
+
+
[email protected]("dedicated_multimodal", [False, True])
+def test_cloud_aliases_and_mak_flow_through_existing_everos_environment(
+ dedicated_multimodal: bool,
+ tmp_path: Path,
+) -> None:
+ memory = MemoryConfig(
+ enabled=True,
+ mode="platform",
+ cloud=MemoryCloudConfig(
+ scope="platform",
+ capabilities=MemoryCloudCapabilities(
+ chat=True,
+ embedding=True,
+ multimodal=dedicated_multimodal,
+ ),
+ embedding_identity="emb-v1",
+ applied_embedding_identity="emb-v1",
+ model_access_key="mak_first",
+ proxy_base_url="https://backend.example.test/v1/model",
+ source_instance_id="instance-1",
+ ),
+ )
+ settings = memory_runtime._process_settings(memory) # noqa: SLF001
+ environment = memory_process._memory_child_environment( # noqa: SLF001
+ python=Path("/usr/bin/python3"),
+ memory_dir=tmp_path / "memory",
+ provider_root=tmp_path / "provider",
+ attachments_root=tmp_path / "attachments",
+ settings=settings,
+ role=None,
+ )
+
+ assert environment["EVEROS_LLM__BASE_URL"] == ("https://backend.example.test/v1/model")
+ assert environment["EVEROS_LLM__MODEL"] == "avibe-cloud-chat"
+ assert environment["EVEROS_LLM__API_KEY"] == "mak_first"
+ assert environment["EVEROS_EMBEDDING__MODEL"] == ("avibe-cloud-embedding-emb-v1")
+ assert environment["EVEROS_EMBEDDING__API_KEY"] == "mak_first"
+ assert memory.effective_multimodal_available() is True
+ if dedicated_multimodal:
+ assert environment["EVEROS_MULTIMODAL__BASE_URL"] == ("https://backend.example.test/v1/model/mm")
+ assert environment["EVEROS_MULTIMODAL__MODEL"] == ("avibe-cloud-multimodal")
+ assert MULTIMODAL_EXPLICIT_ENV in environment
+ else:
+ assert environment["EVEROS_MULTIMODAL__BASE_URL"] == (environment["EVEROS_LLM__BASE_URL"])
+ assert environment["EVEROS_MULTIMODAL__MODEL"] == (environment["EVEROS_LLM__MODEL"])
+ assert MULTIMODAL_EXPLICIT_ENV not in environment
+
+
+def test_mak_rotation_does_not_change_embedding_identity_and_rolls_back_on_apply_failure(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ current = MemoryConfig(
+ enabled=True,
+ mode="platform",
+ cloud=MemoryCloudConfig(
+ scope="platform",
+ capabilities=MemoryCloudCapabilities(chat=True, embedding=True),
+ embedding_identity="emb-v1",
+ applied_embedding_identity="emb-v1",
+ model_access_key="mak_old",
+ proxy_base_url="https://backend.example.test/v1/model",
+ source_instance_id="instance-1",
+ ),
+ )
+ config = _paired_config()
+ snapshots = [deepcopy(current)]
+
+ monkeypatch.setattr(
+ V2Config,
+ "load",
+ classmethod(lambda cls: _paired_config(deepcopy(snapshots[-1]))),
+ )
+ monkeypatch.setattr(
+ model_service,
+ "_device_request",
+ lambda *_args: _mint(
+ "mak_new",
+ rotated=True,
+ previous_valid_until="2026-08-17T00:05:00Z",
+ ),
+ )
+
+ def persist(_expected: MemoryConfig, candidate: MemoryConfig) -> V2Config:
+ snapshots.append(deepcopy(candidate))
+ return _paired_config(deepcopy(candidate))
+
+ reconcile_results = iter([False, True])
+ monkeypatch.setattr(model_service, "_persist_candidate", persist)
+ monkeypatch.setattr(
+ model_service,
+ "_reconcile_candidate",
+ lambda _candidate: next(reconcile_results),
+ )
+
+ with pytest.raises(
+ model_service.ModelServiceResolutionError,
+ match="model_access_key_apply_failed",
+ ):
+ model_service.rotate_model_access_key(config)
+
+ assert snapshots[0].runtime_embedding_identity() == (
+ "cloud",
+ "emb-v1",
+ None,
+ )
+ assert snapshots[1].runtime_embedding_identity() == (
+ "cloud",
+ "emb-v1",
+ None,
+ )
+ assert snapshots[1].cloud.model_access_key == "mak_new"
+ assert snapshots[-1].cloud.model_access_key == "mak_old"
+
+
+ "payload",
+ [
+ _mint() | {"unexpected": True},
+ _mint(rotated=True, previous_valid_until=None),
+ _mint(rotated=False, previous_valid_until="2026-08-17T00:05:00Z"),
+ _mint() | {"created_at": "2026-08-17T00:00:00"},
+ ],
+)
+def test_mak_response_requires_the_frozen_one_time_shape(payload: dict) -> None:
+ with pytest.raises(model_service.ModelServiceResolutionError):
+ model_service._mint_from_payload(payload) # noqa: SLF001
diff --git a/tests/test_remote_access_vibe_cloud.py b/tests/test_remote_access_vibe_cloud.py
index 2dbb36e75..8625e5b85 100644
--- a/tests/test_remote_access_vibe_cloud.py
+++ b/tests/test_remote_access_vibe_cloud.py
@@ -16,7 +16,7 @@ from config.v2_config import AgentsConfig, PlatformsConfig, RemoteAccessConfig,
from storage.db import create_sqlite_engine
from storage.models import remote_access_authorizations
from tests.ui_server_test_helpers import remote_session_cookie
-from vibe import remote_access, ui_server
+from vibe import model_service, remote_access, ui_server
from vibe import runtime
@@ -760,6 +760,12 @@ def test_pair_redeems_key_and_starts_connector(monkeypatch, tmp_path) -> None:
monkeypatch.setattr(remote_access, "start", lambda next_config: {"ok": True, "running": True})
monkeypatch.setattr(remote_access, "status", lambda next_config=None: {"ok": True, "running": True, "paired": True})
monkeypatch.setattr(remote_access, "report_runtime_status", lambda *args, **kwargs: {"ok": True})
+ refreshes: list[bool] = []
+ monkeypatch.setattr(
+ model_service,
+ "request_model_service_refresh",
+ lambda: refreshes.append(True),
+ )
result = remote_access.pair("vrp_test", "https://backend.test")
saved_payload = json.loads((tmp_path / "config" / "config.json").read_text(encoding="utf-8"))
@@ -770,6 +776,7 @@ def test_pair_redeems_key_and_starts_connector(monkeypatch, tmp_path) -> None:
assert saved_payload["remote_access"]["vibe_cloud"]["enabled"] is True
assert saved_payload["remote_access"]["vibe_cloud"]["tunnel_token"] == "tunnel-token"
assert saved_payload["remote_access"]["vibe_cloud"]["session_secret"]
+ assert refreshes == [True]
def test_pair_origin_service_follows_effective_ui_port(monkeypatch, tmp_path) -> None:
diff --git a/ui/src/components/settings/SettingsMemoryPage.tsx b/ui/src/components/settings/SettingsMemoryPage.tsx
index 29194c856..f727aae87 100644
--- a/ui/src/components/settings/SettingsMemoryPage.tsx
+++ b/ui/src/components/settings/SettingsMemoryPage.tsx
@@ -241,20 +241,18 @@ export const SettingsMemoryPage: React.FC = () => {
activeTab="memory"
title={t('memory.title')}
subtitle={t('memory.subtitle')}
- >
- {!remoteUnavailable && canAdminister && settings?.enabled === true ? (
- <div className="flex justify-end">
- <Button
- variant="secondary"
- size="xs"
- onClick={() => void restartEngine()}
- disabled={restarting || rebuildRequired || rebuildBusy || repairBusy || repairMutationBusy}
- >
- {restarting ? <Loader2 className="animate-spin" /> : <RotateCw />}
- {t('memory.status.restartEngine')}
- </Button>
- </div>
+ actions={!remoteUnavailable && canAdminister && settings?.enabled === true ? (
+ <Button
+ variant="secondary"
+ size="xs"
+ onClick={() => void restartEngine()}
+ disabled={restarting || rebuildRequired || rebuildBusy || repairBusy || repairMutationBusy}
+ >
+ {restarting ? <Loader2 className="animate-spin" /> : <RotateCw />}
+ {t('memory.status.restartEngine')}
+ </Button>
) : null}
+ >
{remoteUnavailable ? (
<div className="flex flex-col items-center gap-2 rounded-2xl border border-border bg-surface p-10 text-center">
<ShieldAlert className="size-6 text-muted" />
diff --git a/ui/src/components/settings/memory/MemorySettingsPanel.test.tsx b/ui/src/components/settings/memory/MemorySettingsPanel.test.tsx
index 11a7cb4d7..c6227773e 100644
--- a/ui/src/components/settings/memory/MemorySettingsPanel.test.tsx
+++ b/ui/src/components/settings/memory/MemorySettingsPanel.test.tsx
@@ -51,6 +51,7 @@ const endpoint = (baseUrl: string) => ({
const legacySettings: MemorySettings = {
status: 'ok',
enabled: true,
+ mode: 'custom',
im_attachment_capture_available: true,
processing: {
llm: endpoint('https://old.example.test/v1'),
@@ -68,6 +69,7 @@ const emptyEndpoint = {
const firstSetupSettings: MemorySettings = {
status: 'ok',
enabled: false,
+ mode: 'custom',
im_attachment_capture_available: true,
processing: {
llm: emptyEndpoint,
@@ -81,6 +83,194 @@ afterEach(() => {
});
describe('MemorySettingsPanel', () => {
+ it('renders the personal Avibe Cloud state without exposing endpoint fields', () => {
+ render(
+ <MemorySettingsPanel
+ settings={{ ...legacySettings, mode: 'platform', cloud_available: true }}
+ maintenance={null}
+ maintenanceError={null}
+ dependencyReady
+ onSaved={() => undefined}
+ onReloadSettings={() => undefined}
+ onReloadMaintenance={() => undefined}
+ onClearAll={() => undefined}
+ clearing={false}
+ />,
+ );
+
+ expect(screen.getByText('memory.settings.avibeCloudTitle')).toBeTruthy();
+ expect(screen.getByText('memory.settings.avibeCloudFree')).toBeTruthy();
+ expect(screen.getByRole('button', { name: 'memory.settings.useCustomEndpoints' })).toBeTruthy();
+ expect(screen.queryByText('memory.settings.llmTitle')).toBeNull();
+ expect(screen.queryByRole('button', { name: 'memory.settings.save' })).toBeNull();
+ });
+
+ it('renders the organization state as read-only model management', () => {
+ render(
+ <MemorySettingsPanel
+ settings={{ ...legacySettings, mode: 'organization', managed: true }}
+ maintenance={null}
+ maintenanceError={null}
+ dependencyReady
+ onSaved={() => undefined}
+ onReloadSettings={() => undefined}
+ onReloadMaintenance={() => undefined}
+ onClearAll={() => undefined}
+ clearing={false}
+ />,
+ );
+
+ expect(screen.getByText('memory.settings.organizationManaged')).toBeTruthy();
+ expect(screen.getByRole('switch', { name: 'memory.settings.enableLabel' })).toBeTruthy();
+ expect(screen.queryByText('memory.settings.llmTitle')).toBeNull();
+ expect(screen.queryByRole('button', { name: 'memory.settings.save' })).toBeNull();
+ });
+
+ it('keeps fresh managed Memory unavailable until the organization provides the pair', () => {
+ render(
+ <MemorySettingsPanel
+ settings={{
+ ...firstSetupSettings,
+ mode: 'organization',
+ managed: true,
+ cloud_available: false,
+ }}
+ maintenance={null}
+ maintenanceError={null}
+ dependencyReady
+ onSaved={() => undefined}
+ onReloadSettings={() => undefined}
+ onReloadMaintenance={() => undefined}
+ onClearAll={() => undefined}
+ clearing={false}
+ />,
+ );
+
+ expect(screen.getByText('memory.settings.organizationManaged')).toBeTruthy();
+ expect((screen.getByRole('switch', {
+ name: 'memory.settings.enableLabel',
+ }) as HTMLButtonElement).disabled).toBe(true);
+ expect(screen.queryByText('memory.settings.customEndpointsTitle')).toBeNull();
+ });
+
+ it('does not re-enable a paused personal cloud mode before its capability pair returns', () => {
+ render(
+ <MemorySettingsPanel
+ settings={{
+ ...firstSetupSettings,
+ mode: 'platform',
+ cloud_available: false,
+ capability_paused: true,
+ }}
+ maintenance={null}
+ maintenanceError={null}
+ dependencyReady
+ onSaved={() => undefined}
+ onReloadSettings={() => undefined}
+ onReloadMaintenance={() => undefined}
+ onClearAll={() => undefined}
+ clearing={false}
+ />,
+ );
+
+ expect((screen.getByRole('switch', {
+ name: 'memory.settings.enableLabel',
+ }) as HTMLButtonElement).disabled).toBe(true);
+ expect(screen.getByText('memory.settings.cloudPausedTitle')).toBeTruthy();
+ });
+
+ it('opens the unchanged custom editor and confirms a cloud-to-custom identity switch', async () => {
+ api.saveMemorySettings.mockResolvedValue(legacySettings);
+ const user = userEvent.setup();
+ render(
+ <MemorySettingsPanel
+ settings={{ ...legacySettings, mode: 'platform', cloud_available: true }}
+ maintenance={null}
+ maintenanceError={null}
+ dependencyReady
+ onSaved={() => undefined}
+ onReloadSettings={() => undefined}
+ onReloadMaintenance={() => undefined}
+ onClearAll={() => undefined}
+ clearing={false}
+ />,
+ );
+
+ await user.click(screen.getByRole('button', { name: 'memory.settings.useCustomEndpoints' }));
+ expect(screen.getByText('memory.settings.customEndpointsTitle')).toBeTruthy();
+ expect(screen.getByText('memory.settings.llmTitle')).toBeTruthy();
+ await user.click(screen.getByRole('button', { name: 'memory.settings.save' }));
+ expect(api.saveMemorySettings).not.toHaveBeenCalled();
+ await user.click(screen.getByRole('button', { name: 'confirm-rebuild' }));
+
+ await waitFor(() => expect(api.saveMemorySettings).toHaveBeenCalledWith({
+ mode: 'custom',
+ confirm_rebuild: true,
+ }));
+ });
+
+ it('acknowledges enterprise attachment through the rebuild confirmation flow', async () => {
+ api.saveMemorySettings.mockResolvedValue({
+ ...legacySettings,
+ mode: 'organization',
+ managed: true,
+ });
+ const user = userEvent.setup();
+ render(
+ <MemorySettingsPanel
+ settings={{
+ ...legacySettings,
+ mode: 'organization',
+ managed: true,
+ cloud_available: true,
+ transition_notice_pending: true,
+ rebuild_required: true,
+ }}
+ maintenance={null}
+ maintenanceError={null}
+ dependencyReady
+ onSaved={() => undefined}
+ onReloadSettings={() => undefined}
+ onReloadMaintenance={() => undefined}
+ onClearAll={() => undefined}
+ clearing={false}
+ />,
+ );
+
+ expect(screen.queryByRole('button', { name: 'memory.settings.retryRebuild' })).toBeNull();
+ await user.click(screen.getByRole('button', { name: 'memory.settings.organizationTransitionAction' }));
+ await user.click(screen.getByRole('button', { name: 'confirm-rebuild' }));
+ await waitFor(() => expect(api.saveMemorySettings).toHaveBeenCalledWith({
+ acknowledge_transition: true,
+ confirm_rebuild: true,
+ }));
+ });
+
+ it('applies the Memory toggle immediately outside custom mode', async () => {
+ api.saveMemorySettings.mockResolvedValue({
+ ...legacySettings,
+ mode: 'platform',
+ enabled: false,
+ });
+ const user = userEvent.setup();
+ render(
+ <MemorySettingsPanel
+ settings={{ ...legacySettings, mode: 'platform', cloud_available: true }}
+ maintenance={null}
+ maintenanceError={null}
+ dependencyReady
+ onSaved={() => undefined}
+ onReloadSettings={() => undefined}
+ onReloadMaintenance={() => undefined}
+ onClearAll={() => undefined}
+ clearing={false}
+ />,
+ );
+
+ await user.click(screen.getByRole('switch', { name: 'memory.settings.enableLabel' }));
+ await waitFor(() => expect(api.saveMemorySettings).toHaveBeenCalledWith({ enabled: false }));
+ });
+
it('hides multimodal configuration until IM attachment capture is available', () => {
render(
<MemorySettingsPanel
diff --git a/ui/src/components/settings/memory/MemorySettingsPanel.tsx b/ui/src/components/settings/memory/MemorySettingsPanel.tsx
index f3902305a..75caa9ffd 100644
--- a/ui/src/components/settings/memory/MemorySettingsPanel.tsx
+++ b/ui/src/components/settings/memory/MemorySettingsPanel.tsx
@@ -1,7 +1,16 @@
import { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
-import { ArrowUpRight, Loader2, RefreshCw, ShieldAlert, Trash2 } from 'lucide-react';
+import {
+ ArrowUpRight,
+ Building2,
+ Cloud,
+ Loader2,
+ RefreshCw,
+ ShieldAlert,
+ SlidersHorizontal,
+ Trash2,
+} from 'lucide-react';
import { Badge } from '../../ui/badge';
import { Button } from '../../ui/button';
@@ -172,6 +181,7 @@ export const MemorySettingsPanel: React.FC<{
const api = useApi();
const { showToast } = useToast();
const [enabledDraft, setEnabledDraft] = useState(settings.enabled);
+ const [modeDraft, setModeDraft] = useState<MemorySettings['mode']>(settings.mode);
const [llmDraft, setLlmDraft] = useState<EndpointDraft>(() => draftFromConfig(settings.processing.llm));
const [embeddingDraft, setEmbeddingDraft] = useState<EndpointDraft>(() => draftFromConfig(settings.processing.embedding));
const [rerankDraft, setRerankDraft] = useState<EndpointDraft>(() => draftFromConfig(settings.processing.rerank ?? EMPTY_ENDPOINT));
@@ -184,6 +194,7 @@ export const MemorySettingsPanel: React.FC<{
// Reset drafts whenever a fresh settings snapshot lands (initial load or after a save).
useEffect(() => {
setEnabledDraft(settings.enabled);
+ setModeDraft(settings.mode);
setLlmDraft(draftFromConfig(settings.processing.llm));
setEmbeddingDraft(draftFromConfig(settings.processing.embedding));
setRerankDraft(draftFromConfig(settings.processing.rerank ?? EMPTY_ENDPOINT));
@@ -195,10 +206,13 @@ export const MemorySettingsPanel: React.FC<{
const canClearRequiredKeys = !enabledDraft;
const canClearMemory = maintenance?.can_clear === true;
const busy = saving || rebuildBusy || repairBusy || mutationBusy;
+ const customMode = modeDraft === 'custom';
const buildPatch = (): MemorySettingsPatch => {
const patch: MemorySettingsPatch = {};
if (enabledDraft !== settings.enabled) patch.enabled = enabledDraft;
+ if (modeDraft !== settings.mode && modeDraft !== 'organization') patch.mode = modeDraft;
+ if (!customMode) return patch;
// Required keys can clear only while the resulting state stays disabled.
const allowRequiredClear = !enabledDraft;
const llmPatch = buildEndpointPatch(
@@ -319,7 +333,10 @@ export const MemorySettingsPanel: React.FC<{
return;
}
if (
- identityChanged(embeddingDraft, settings.processing.embedding)
+ (
+ modeDraft !== settings.mode
+ || identityChanged(embeddingDraft, settings.processing.embedding)
+ )
&& !factoryResetRequired
) {
// Retain the draft and open confirmation; the same patch is replayed with
@@ -367,12 +384,62 @@ export const MemorySettingsPanel: React.FC<{
}
};
+ const setMemoryEnabled = (checked: boolean) => {
+ setEnabledDraft(checked);
+ if (!customMode) void submitPatch({ enabled: checked });
+ };
+
+ const usePlatformMode = () => {
+ if (settings.mode === 'platform') {
+ setModeDraft('platform');
+ return;
+ }
+ setPendingPatch({ mode: 'platform' });
+ setConfirmRebuildOpen(true);
+ };
+
+ const acknowledgeOrganizationTransition = () => {
+ setPendingPatch({ acknowledge_transition: true });
+ setConfirmRebuildOpen(true);
+ };
+
return (
<div className="flex flex-col gap-4">
{rebuildRequired ? (
- <div className="flex flex-col gap-1 rounded-xl border border-gold/40 bg-gold/10 px-4 py-3">
- <span className="text-[13px] font-semibold text-foreground">{t('memory.settings.rebuildRequiredTitle')}</span>
- <span className="text-[12px] leading-snug text-muted">{t('memory.settings.rebuildRequiredDescription')}</span>
+ <div className="flex flex-wrap items-center justify-between gap-3 rounded-xl border border-gold/40 bg-gold/10 px-4 py-3">
+ <div className="flex min-w-0 flex-col gap-1">
+ <span className="text-[13px] font-semibold text-foreground">{t('memory.settings.rebuildRequiredTitle')}</span>
+ <span className="text-[12px] leading-snug text-muted">{t('memory.settings.rebuildRequiredDescription')}</span>
+ </div>
+ {!factoryResetRequired && !settings.transition_notice_pending ? (
+ <Button variant="secondary" size="sm" onClick={() => void retryRebuild()} disabled={busy}>
+ {rebuildBusy ? <Loader2 className="size-3.5 animate-spin" /> : <RefreshCw className="size-3.5" />}
+ {rebuildBusy ? t('memory.settings.retryingRebuild') : t('memory.settings.retryRebuild')}
+ </Button>
+ ) : null}
+ </div>
+ ) : null}
+
+ {settings.transition_notice_pending ? (
+ <div className="flex flex-wrap items-center justify-between gap-3 rounded-xl border border-gold/40 bg-gold/10 px-4 py-3">
+ <div className="flex min-w-0 flex-col gap-1">
+ <span className="text-[13px] font-semibold text-foreground">{t('memory.settings.organizationTransitionTitle')}</span>
+ <span className="text-[12px] leading-snug text-muted">{t('memory.settings.organizationTransitionDescription')}</span>
+ </div>
+ <Button
+ size="sm"
+ onClick={acknowledgeOrganizationTransition}
+ disabled={busy || !settings.cloud_available}
+ >
+ {t('memory.settings.organizationTransitionAction')}
+ </Button>
+ </div>
+ ) : null}
+
+ {settings.capability_paused ? (
+ <div className="rounded-xl border border-gold/40 bg-gold/10 px-4 py-3">
+ <span className="text-[13px] font-semibold text-foreground">{t('memory.settings.cloudPausedTitle')}</span>
+ <p className="mt-1 text-[12px] leading-snug text-muted">{t('memory.settings.cloudPausedDescription')}</p>
</div>
) : null}
@@ -395,83 +462,137 @@ export const MemorySettingsPanel: React.FC<{
</div>
<Switch
checked={enabledDraft}
- onCheckedChange={setEnabledDraft}
- disabled={busy || factoryResetRequired || rebuildRequired || (!enabledDraft && !dependencyReady)}
+ onCheckedChange={setMemoryEnabled}
+ disabled={
+ busy
+ || factoryResetRequired
+ || rebuildRequired
+ || (!enabledDraft && !dependencyReady)
+ || (!enabledDraft && !customMode && !settings.cloud_available)
+ }
label={t('memory.settings.enableLabel')}
/>
</div>
- <EndpointFields
- title={t('memory.settings.llmTitle')}
- help={t('memory.settings.llmHelp')}
- helpLabel={t('memory.settings.llmHelpLabel')}
- draft={llmDraft}
- original={settings.processing.llm}
- onChange={setLlmDraft}
- disabled={busy}
- canClearKey={canClearRequiredKeys}
- />
+ {modeDraft === 'platform' ? (
+ <div className="overflow-hidden rounded-xl border border-border bg-surface">
+ <div className="flex items-center justify-between gap-4 border-b border-border px-4 py-3.5">
+ <div className="flex min-w-0 items-center gap-3">
+ <span className="grid size-9 shrink-0 place-items-center rounded-lg bg-mint/15 text-mint-ink">
+ <Cloud className="size-5" />
+ </span>
+ <div className="min-w-0">
+ <h3 className="text-[13px] font-semibold text-foreground">{t('memory.settings.avibeCloudTitle')}</h3>
+ <p className="text-[11.5px] leading-snug text-muted">{t('memory.settings.avibeCloudIncluded')}</p>
+ </div>
+ </div>
+ <Badge variant="success">{t('memory.settings.avibeCloudFree')}</Badge>
+ </div>
+ <p className="px-4 py-4 text-[12px] leading-relaxed text-muted">{t('memory.settings.avibeCloudDescription')}</p>
+ <div className="flex flex-wrap items-center justify-between gap-3 border-t border-border bg-background/40 px-4 py-3">
+ <span className="text-[11.5px] text-muted">{t('memory.settings.customPrompt')}</span>
+ <Button variant="secondary" size="sm" onClick={() => setModeDraft('custom')} disabled={busy}>
+ {t('memory.settings.useCustomEndpoints')}
+ </Button>
+ </div>
+ </div>
+ ) : null}
- <EndpointFields
- title={t('memory.settings.embeddingTitle')}
- help={t('memory.settings.embeddingHelp')}
- helpLabel={t('memory.settings.embeddingHelpLabel')}
- draft={embeddingDraft}
- original={settings.processing.embedding}
- onChange={setEmbeddingDraft}
- disabled={busy}
- identityHint={t('memory.settings.embeddingIdentityHint')}
- canClearKey={canClearRequiredKeys}
- />
+ {modeDraft === 'organization' ? (
+ <div className="flex items-center gap-3 rounded-xl border border-border bg-surface px-4 py-4">
+ <span className="grid size-9 shrink-0 place-items-center rounded-lg bg-cyan/15 text-cyan-ink">
+ <Building2 className="size-5" />
+ </span>
+ <span className="text-[13px] font-medium text-foreground">{t('memory.settings.organizationManaged')}</span>
+ </div>
+ ) : null}
- <EndpointFields
- title={t('memory.settings.rerankTitle')}
- help={t('memory.settings.rerankHelp')}
- helpLabel={t('memory.settings.rerankHelpLabel')}
- draft={rerankDraft}
- original={settings.processing.rerank ?? EMPTY_ENDPOINT}
- onChange={setRerankDraft}
- disabled={busy}
- identityHint={t('memory.settings.rerankIdentityHint')}
- canClearKey
- clearKeyLabel={t('memory.settings.rerankClearLabel')}
- />
+ {customMode ? (
+ <>
+ <div className="flex flex-wrap items-center justify-between gap-3 rounded-xl border border-border bg-surface px-4 py-3">
+ <div className="flex min-w-0 items-center gap-3">
+ <span className="grid size-9 shrink-0 place-items-center rounded-lg bg-violet/15 text-violet-ink">
+ <SlidersHorizontal className="size-5" />
+ </span>
+ <div className="min-w-0">
+ <h3 className="text-[13px] font-semibold text-foreground">{t('memory.settings.customEndpointsTitle')}</h3>
+ <p className="text-[11.5px] leading-snug text-muted">{t('memory.settings.customEndpointsDescription')}</p>
+ </div>
+ </div>
+ {settings.cloud_available && !settings.managed ? (
+ <Button variant="secondary" size="sm" onClick={usePlatformMode} disabled={busy}>
+ {t('memory.settings.useAvibeCloud')}
+ </Button>
+ ) : null}
+ </div>
- {settings.im_attachment_capture_available === true ? (
- <EndpointFields
- title={t('memory.settings.multimodalTitle')}
- help={t('memory.settings.multimodalHelp')}
- helpLabel={t('memory.settings.multimodalHelpLabel')}
- draft={multimodalDraft}
- original={settings.processing.multimodal ?? EMPTY_ENDPOINT}
- onChange={setMultimodalDraft}
- disabled={busy}
- identityHint={t('memory.settings.multimodalIdentityHint')}
- canClearKey
- clearKeyLabel={t('memory.settings.multimodalClearLabel')}
- />
+ <EndpointFields
+ title={t('memory.settings.llmTitle')}
+ help={t('memory.settings.llmHelp')}
+ helpLabel={t('memory.settings.llmHelpLabel')}
+ draft={llmDraft}
+ original={settings.processing.llm}
+ onChange={setLlmDraft}
+ disabled={busy}
+ canClearKey={canClearRequiredKeys}
+ />
+
+ <EndpointFields
+ title={t('memory.settings.embeddingTitle')}
+ help={t('memory.settings.embeddingHelp')}
+ helpLabel={t('memory.settings.embeddingHelpLabel')}
+ draft={embeddingDraft}
+ original={settings.processing.embedding}
+ onChange={setEmbeddingDraft}
+ disabled={busy}
+ identityHint={t('memory.settings.embeddingIdentityHint')}
+ canClearKey={canClearRequiredKeys}
+ />
+
+ <EndpointFields
+ title={t('memory.settings.rerankTitle')}
+ help={t('memory.settings.rerankHelp')}
+ helpLabel={t('memory.settings.rerankHelpLabel')}
+ draft={rerankDraft}
+ original={settings.processing.rerank ?? EMPTY_ENDPOINT}
+ onChange={setRerankDraft}
+ disabled={busy}
+ identityHint={t('memory.settings.rerankIdentityHint')}
+ canClearKey
+ clearKeyLabel={t('memory.settings.rerankClearLabel')}
+ />
+
+ {settings.im_attachment_capture_available === true ? (
+ <EndpointFields
+ title={t('memory.settings.multimodalTitle')}
+ help={t('memory.settings.multimodalHelp')}
+ helpLabel={t('memory.settings.multimodalHelpLabel')}
+ draft={multimodalDraft}
+ original={settings.processing.multimodal ?? EMPTY_ENDPOINT}
+ onChange={setMultimodalDraft}
+ disabled={busy}
+ identityHint={t('memory.settings.multimodalIdentityHint')}
+ canClearKey
+ clearKeyLabel={t('memory.settings.multimodalClearLabel')}
+ />
+ ) : null}
+ </>
) : null}
{error ? (
<div className="rounded-xl border border-destructive/40 bg-destructive/10 px-4 py-3 text-sm text-destructive-ink">{error}</div>
) : null}
- {maintenanceError ? (
+ {customMode && maintenanceError ? (
<div className="rounded-xl border border-border bg-surface px-4 py-3 text-[12px] text-muted">{maintenanceError}</div>
) : null}
- <div className="flex flex-wrap items-center justify-between gap-3">
+ {customMode ? <div className="flex flex-wrap items-center justify-between gap-3">
<div className="flex flex-wrap items-center gap-2">
<Button onClick={() => void save()} disabled={busy}>
{saving ? <Loader2 className="size-3.5 animate-spin" /> : null}
{saving ? t('memory.settings.saving') : t('memory.settings.save')}
</Button>
- {rebuildRequired && !factoryResetRequired ? (
- <Button variant="secondary" onClick={() => void retryRebuild()} disabled={busy}>
- {rebuildBusy ? <Loader2 className="size-3.5 animate-spin" /> : <RefreshCw className="size-3.5" />}
- {rebuildBusy ? t('memory.settings.retryingRebuild') : t('memory.settings.retryRebuild')}
- </Button>
- ) : null}
</div>
<Button
variant="destructive"
@@ -482,9 +603,9 @@ export const MemorySettingsPanel: React.FC<{
<Trash2 className="size-3.5" />
{t('memory.clear.button')}
</Button>
- </div>
+ </div> : null}
- <div className="rounded-xl border border-border bg-surface p-4">
+ {customMode ? <div className="rounded-xl border border-border bg-surface p-4">
<h3 className="mb-2 text-[13px] font-semibold text-foreground">{t('memory.settings.disclosureTitle')}</h3>
<ul className="flex flex-col gap-1.5">
{(t('memory.settings.disclosure', { returnObjects: true }) as string[]).map((line, idx) => (
@@ -500,7 +621,7 @@ export const MemorySettingsPanel: React.FC<{
</li>
) : null}
</ul>
- </div>
+ </div> : null}
<ConfirmDialog
open={confirmRebuildOpen}
diff --git a/ui/src/components/settings/memory/memoryCopyContract.test.ts b/ui/src/components/settings/memory/memoryCopyContract.test.ts
index 4eb8c1f34..2cb4e047f 100644
--- a/ui/src/components/settings/memory/memoryCopyContract.test.ts
+++ b/ui/src/components/settings/memory/memoryCopyContract.test.ts
@@ -6,6 +6,55 @@ import zh from '../../../i18n/zh.json';
const BUNDLES = { en, zh } as const;
describe('Memory UI copy contracts', () => {
+ it('keeps the three-state model-source copy aligned with the approved frames', () => {
+ expect({
+ title: en.memory.settings.avibeCloudTitle,
+ price: en.memory.settings.avibeCloudFree,
+ included: en.memory.settings.avibeCloudIncluded,
+ description: en.memory.settings.avibeCloudDescription,
+ prompt: en.memory.settings.customPrompt,
+ customAction: en.memory.settings.useCustomEndpoints,
+ customTitle: en.memory.settings.customEndpointsTitle,
+ customDescription: en.memory.settings.customEndpointsDescription,
+ cloudAction: en.memory.settings.useAvibeCloud,
+ managed: en.memory.settings.organizationManaged,
+ }).toEqual({
+ title: 'Avibe Cloud',
+ price: 'Free',
+ included: 'Included with Avibe. Nothing to set up.',
+ description: "Memory works out of the box. Your messages are processed by Avibe's cloud models.",
+ prompt: 'Using your own provider instead?',
+ customAction: 'Use custom endpoints',
+ customTitle: 'Custom endpoints',
+ customDescription: 'Your own provider, models and keys.',
+ cloudAction: 'Use Avibe Cloud',
+ managed: 'Models are managed by your organization.',
+ });
+ expect({
+ title: zh.memory.settings.avibeCloudTitle,
+ price: zh.memory.settings.avibeCloudFree,
+ included: zh.memory.settings.avibeCloudIncluded,
+ description: zh.memory.settings.avibeCloudDescription,
+ prompt: zh.memory.settings.customPrompt,
+ customAction: zh.memory.settings.useCustomEndpoints,
+ customTitle: zh.memory.settings.customEndpointsTitle,
+ customDescription: zh.memory.settings.customEndpointsDescription,
+ cloudAction: zh.memory.settings.useAvibeCloud,
+ managed: zh.memory.settings.organizationManaged,
+ }).toEqual({
+ title: 'Avibe 云端',
+ price: '免费',
+ included: 'Avibe 自带,无需设置。',
+ description: '记忆功能开箱即用。你的消息由 Avibe 的云端模型处理。',
+ prompt: '想改用自己的服务商?',
+ customAction: '改用自定义接口',
+ customTitle: '自定义接口',
+ customDescription: '使用你自己的服务商、模型和密钥。',
+ cloudAction: '改用 Avibe 云端',
+ managed: '模型由你的组织统一管理。',
+ });
+ });
+
it.each(['en', 'zh'] as const)('describes runtime capabilities beyond models in %s', (language) => {
const text = BUNDLES[language].memory.processingRecord.runtime.capabilitiesHelp;
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index 8eb7bcce1..87176625e 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -1860,6 +1860,11 @@ export type MemoryProcessingConfig = {
export type MemorySettings = {
status: 'ok';
enabled: boolean;
+ mode: 'organization' | 'platform' | 'custom';
+ cloud_available?: boolean;
+ managed?: boolean;
+ transition_notice_pending?: boolean;
+ capability_paused?: boolean;
im_attachment_capture_available?: boolean;
repair_available?: boolean;
processing: MemoryProcessingConfig;
@@ -1879,6 +1884,8 @@ export type MemoryEndpointPatch = {
export type MemorySettingsPatch = {
enabled?: boolean;
+ mode?: 'platform' | 'custom';
+ acknowledge_transition?: true;
processing?: {
llm?: MemoryEndpointPatch;
embedding?: MemoryEndpointPatch;
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 4b04ab976..0f28bf3c7 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -4469,7 +4469,22 @@
"loading": "Loading settings…",
"loadFailed": "Couldn't load Memory settings.",
"enableLabel": "Memory",
- "enableHint": "When on, Avibe distills your conversations and your Agent's work notes into a searchable personal memory. Each user's memory stays separate.",
+ "enableHint": "Remembers what matters from your conversations.",
+ "avibeCloudTitle": "Avibe Cloud",
+ "avibeCloudFree": "Free",
+ "avibeCloudIncluded": "Included with Avibe. Nothing to set up.",
+ "avibeCloudDescription": "Memory works out of the box. Your messages are processed by Avibe's cloud models.",
+ "customPrompt": "Using your own provider instead?",
+ "useCustomEndpoints": "Use custom endpoints",
+ "customEndpointsTitle": "Custom endpoints",
+ "customEndpointsDescription": "Your own provider, models and keys.",
+ "useAvibeCloud": "Use Avibe Cloud",
+ "organizationManaged": "Models are managed by your organization.",
+ "organizationTransitionTitle": "Your organization now manages Memory models",
+ "organizationTransitionDescription": "Memory processing is paused. Confirm the change to rebuild the local index with your organization's embedding model; queued messages are kept.",
+ "organizationTransitionAction": "Review and rebuild",
+ "cloudPausedTitle": "Organization Memory models are unavailable",
+ "cloudPausedDescription": "Memory processing is paused and new messages keep queuing. It resumes after your organization restores both chat and embedding models.",
"dependencyNotReady": "The memory-runtime dependency isn't ready yet. Install or repair it from Settings → Dependencies, then try enabling Memory again.",
"goToDependencies": "Open Dependencies",
"llmTitle": "Language model (LLM)",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index e59fe7890..711fcb9f5 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -4469,7 +4469,22 @@
"loading": "正在加载设置…",
"loadFailed": "无法加载记忆设置。",
"enableLabel": "记忆",
- "enableHint": "开启后,Avibe 会从你的对话和 Agent 的工作记录中提炼出可搜索的个人记忆。每个用户的记忆相互独立。",
+ "enableHint": "记住对话中真正重要的内容。",
+ "avibeCloudTitle": "Avibe 云端",
+ "avibeCloudFree": "免费",
+ "avibeCloudIncluded": "Avibe 自带,无需设置。",
+ "avibeCloudDescription": "记忆功能开箱即用。你的消息由 Avibe 的云端模型处理。",
+ "customPrompt": "想改用自己的服务商?",
+ "useCustomEndpoints": "改用自定义接口",
+ "customEndpointsTitle": "自定义接口",
+ "customEndpointsDescription": "使用你自己的服务商、模型和密钥。",
+ "useAvibeCloud": "改用 Avibe 云端",
+ "organizationManaged": "模型由你的组织统一管理。",
+ "organizationTransitionTitle": "你的组织现在统一管理记忆模型",
+ "organizationTransitionDescription": "记忆处理已暂停。确认后将使用组织的向量模型重建本地索引;排队中的消息会保留。",
+ "organizationTransitionAction": "确认并重建",
+ "cloudPausedTitle": "组织的记忆模型暂不可用",
+ "cloudPausedDescription": "记忆处理已暂停,新消息会继续排队。组织恢复聊天和向量模型后将自动继续。",
"dependencyNotReady": "memory-runtime 依赖尚未就绪。请先在「设置 → 依赖」中安装或修复,然后重新尝试启用记忆。",
"goToDependencies": "前往依赖页面",
"llmTitle": "语言模型(LLM)",
diff --git a/vibe/model_service.py b/vibe/model_service.py
new file mode 100644
index 000000000..06239f40e
--- /dev/null
+++ b/vibe/model_service.py
@@ -0,0 +1,443 @@
+"""Paired-device Cloud Model Service resolution for local Memory."""
+
+from __future__ import annotations
+
+from copy import deepcopy
+from dataclasses import dataclass
+from datetime import datetime
+import logging
+import threading
+from typing import Any, Mapping
+
+from config.v2_config import (
+ MemoryCloudCapabilities,
+ MemoryConfig,
+ V2Config,
+ memory_config_to_payload,
+)
+
+
+logger = logging.getLogger(__name__)
+
+MODEL_SERVICE_POLL_SECONDS = 60
+_SYNC_LOCK = threading.Lock()
+_WORKER_LOCK = threading.Lock()
+_REFRESH_EVENT = threading.Event()
+_WORKER_STARTED = False
+
+
+class ModelServiceResolutionError(RuntimeError):
+ pass
+
+
+@dataclass(frozen=True)
+class ModelServiceStatus:
+ scope: str
+ capabilities: MemoryCloudCapabilities
+ embedding_identity: str | None
+ quota_enforced: bool
+ revision: int
+
+ def memory_available(self) -> bool:
+ return self.capabilities.memory_available() and bool(self.embedding_identity)
+
+
+@dataclass(frozen=True)
+class ModelAccessKeyMint:
+ key: str
+ created_at: str
+ rotated: bool
+ previous_valid_until: str | None
+
+
+def _iso8601(value: object, *, nullable: bool = False) -> str | None:
+ if nullable and value is None:
+ return None
+ if not isinstance(value, str) or not value.strip():
+ raise ModelServiceResolutionError("model_service_invalid_response")
+ candidate = value.strip()
+ try:
+ parsed = datetime.fromisoformat(candidate.replace("Z", "+00:00"))
+ except ValueError as exc:
+ raise ModelServiceResolutionError("model_service_invalid_response") from exc
+ if parsed.tzinfo is None:
+ raise ModelServiceResolutionError("model_service_invalid_response")
+ return candidate
+
+
+def _status_from_payload(payload: object) -> ModelServiceStatus:
+ if not isinstance(payload, Mapping):
+ raise ModelServiceResolutionError("model_service_invalid_response")
+ scope = payload.get("mode")
+ capabilities = payload.get("capabilities")
+ embedding_identity = payload.get("embedding_identity")
+ quota = payload.get("quota")
+ revision = payload.get("revision")
+ if scope not in {"organization", "platform"}:
+ raise ModelServiceResolutionError("model_service_invalid_response")
+ if not isinstance(capabilities, Mapping):
+ raise ModelServiceResolutionError("model_service_invalid_response")
+ required_capabilities = {"asr", "chat", "embedding", "multimodal"}
+ if not required_capabilities.issubset(capabilities) or any(
+ not isinstance(capabilities.get(name), bool) for name in required_capabilities
+ ):
+ raise ModelServiceResolutionError("model_service_invalid_response")
+ if embedding_identity is not None and (not isinstance(embedding_identity, str) or not embedding_identity.strip()):
+ raise ModelServiceResolutionError("model_service_invalid_response")
+ if bool(capabilities["embedding"]) != bool(embedding_identity):
+ raise ModelServiceResolutionError("model_service_invalid_response")
+ if not isinstance(quota, Mapping) or not isinstance(quota.get("enforced"), bool):
+ raise ModelServiceResolutionError("model_service_invalid_response")
+ if isinstance(revision, bool) or not isinstance(revision, int) or revision < 0:
+ raise ModelServiceResolutionError("model_service_invalid_response")
+ return ModelServiceStatus(
+ scope=str(scope),
+ capabilities=MemoryCloudCapabilities(
+ asr=capabilities["asr"],
+ chat=capabilities["chat"],
+ embedding=capabilities["embedding"],
+ multimodal=capabilities["multimodal"],
+ ),
+ embedding_identity=embedding_identity.strip() if embedding_identity else None,
+ quota_enforced=quota["enforced"],
+ revision=revision,
+ )
+
+
+def _mint_from_payload(payload: object) -> ModelAccessKeyMint:
+ if not isinstance(payload, Mapping) or set(payload) != {
+ "key",
+ "created_at",
+ "rotated",
+ "previous_valid_until",
+ }:
+ raise ModelServiceResolutionError("model_access_key_invalid_response")
+ key = payload.get("key")
+ rotated = payload.get("rotated")
+ previous_valid_until = payload.get("previous_valid_until")
+ if (
+ not isinstance(key, str)
+ or not key.startswith("mak_")
+ or not isinstance(rotated, bool)
+ or (not rotated and previous_valid_until is not None)
+ or (rotated and previous_valid_until is None)
+ ):
+ raise ModelServiceResolutionError("model_access_key_invalid_response")
+ created_at = _iso8601(payload.get("created_at"))
+ previous = _iso8601(previous_valid_until, nullable=True)
+ assert isinstance(created_at, str)
+ return ModelAccessKeyMint(
+ key=key,
+ created_at=created_at,
+ rotated=rotated,
+ previous_valid_until=previous,
+ )
+
+
+def _device_request(
+ config: V2Config,
+ method: str,
+ suffix: str,
+) -> dict[str, Any]:
+ from vibe import remote_access
+
+ return remote_access._device_json_request(config, method, suffix) # noqa: SLF001
+
+
+def _memory_mode_after_initialization(memory: MemoryConfig) -> str:
+ if memory.mode is not None:
+ return memory.mode
+ return "custom" if memory.custom_processing_complete() else "platform"
+
+
+def _status_needs_model_key(memory: MemoryConfig, status: ModelServiceStatus) -> bool:
+ if not status.memory_available():
+ return False
+ if status.scope == "organization":
+ if memory.cloud.organization_attached:
+ return True
+ if memory.cloud.transition_notice_pending:
+ return False
+ return not (_memory_mode_after_initialization(memory) == "custom" and memory.custom_processing_complete())
+ return _memory_mode_after_initialization(memory) == "platform"
+
+
+def _resolved_memory(
+ current: MemoryConfig,
+ *,
+ status: ModelServiceStatus,
+ instance_id: str,
+ proxy_base_url: str,
+ minted: ModelAccessKeyMint | None,
+) -> MemoryConfig:
+ candidate = deepcopy(current)
+ previous = deepcopy(current)
+ first_resolution = candidate.cloud.source_instance_id != instance_id
+ if first_resolution:
+ candidate.cloud.model_access_key = None
+ candidate.cloud.organization_attached = False
+ candidate.cloud.transition_notice_pending = False
+ candidate.cloud.applied_embedding_identity = None
+ if candidate.mode is None:
+ candidate.mode = _memory_mode_after_initialization(candidate)
+ if candidate.mode == "platform" and status.memory_available():
+ candidate.enabled = True
+
+ candidate.cloud.scope = status.scope # type: ignore[assignment]
+ candidate.cloud.capabilities = status.capabilities
+ candidate.cloud.embedding_identity = status.embedding_identity
+ candidate.cloud.revision = status.revision
+ candidate.cloud.quota_enforced = status.quota_enforced
+ candidate.cloud.proxy_base_url = proxy_base_url
+ candidate.cloud.source_instance_id = instance_id
+ if minted is not None:
+ candidate.cloud.model_access_key = minted.key
+
+ if status.scope == "organization":
+ if status.memory_available():
+ if candidate.cloud.organization_attached:
+ first_managed_activation = (
+ candidate.cloud.applied_embedding_identity is None
+ )
+ if (
+ candidate.cloud.applied_embedding_identity is not None
+ and candidate.cloud.applied_embedding_identity != status.embedding_identity
+ ):
+ candidate.recovery_intent = "rebuild"
+ candidate.cloud.applied_embedding_identity = status.embedding_identity
+ if first_managed_activation:
+ candidate.enabled = True
+ elif candidate.cloud.transition_notice_pending:
+ candidate.recovery_intent = "rebuild"
+ elif candidate.mode == "custom" and previous.custom_processing_complete():
+ candidate.cloud.transition_notice_pending = True
+ candidate.recovery_intent = "rebuild"
+ else:
+ if (
+ previous.cloud.scope == "platform"
+ and previous.cloud.applied_embedding_identity is not None
+ and previous.cloud.applied_embedding_identity != status.embedding_identity
+ ):
+ candidate.recovery_intent = "rebuild"
+ candidate.cloud.organization_attached = True
+ candidate.cloud.applied_embedding_identity = status.embedding_identity
+ candidate.enabled = True
+ elif candidate.cloud.organization_attached:
+ # Keep the last applied identity while paused so re-enable can
+ # distinguish an unchanged provider from one that needs rebuild.
+ candidate.cloud.transition_notice_pending = False
+ elif not (
+ candidate.mode == "custom" and previous.custom_processing_complete()
+ ):
+ # Scope binding remains managed even with no Memory pair. Only a
+ # complete configuration that was actively custom is grandfathered;
+ # every other installation pauses instead of falling back.
+ candidate.cloud.organization_attached = True
+ candidate.cloud.applied_embedding_identity = (
+ previous.cloud.applied_embedding_identity
+ )
+ else:
+ was_organization_cloud = previous.cloud.scope == "organization" and previous.cloud.organization_attached
+ candidate.cloud.organization_attached = False
+ candidate.cloud.transition_notice_pending = False
+ if candidate.mode == "platform" and status.memory_available():
+ if (
+ (was_organization_cloud or previous.cloud.scope == "platform")
+ and previous.cloud.applied_embedding_identity is not None
+ and previous.cloud.applied_embedding_identity != status.embedding_identity
+ ):
+ candidate.recovery_intent = "rebuild"
+ candidate.cloud.applied_embedding_identity = status.embedding_identity
+ elif was_organization_cloud:
+ candidate.recovery_intent = "rebuild"
+ candidate.cloud.applied_embedding_identity = None
+
+ candidate.cloud.runtime_apply_pending = current.cloud.runtime_apply_pending or candidate != current
+ candidate.validate()
+ return candidate
+
+
+def _persist_candidate(current: MemoryConfig, candidate: MemoryConfig) -> V2Config:
+ from vibe import api
+
+ return api.save_memory_config(
+ memory_config_to_payload(candidate, include_secrets=True),
+ recovery_intent=candidate.recovery_intent,
+ expected=current,
+ )
+
+
+def _clear_apply_pending(expected: MemoryConfig) -> None:
+ from config.v2_config import atomic_update_memory
+
+ def clear(current: MemoryConfig) -> MemoryConfig:
+ if current != expected:
+ return current
+ current.cloud.runtime_apply_pending = False
+ return current
+
+ atomic_update_memory(clear)
+
+
+def _reconcile_candidate(candidate: MemoryConfig) -> bool:
+ from vibe import internal_client
+ from vibe.async_bridge import run_coroutine_blocking
+
+ try:
+ result = run_coroutine_blocking(internal_client.reconcile_memory())
+ except Exception:
+ return False
+ body = result.get("body") if isinstance(result, dict) else None
+ if not isinstance(body, dict):
+ return False
+ if body.get("ok") is True:
+ _clear_apply_pending(candidate)
+ return True
+ if candidate.recovery_intent == "rebuild" and body.get("error") == "memory_embedding_rebuild_required":
+ _clear_apply_pending(candidate)
+ return True
+ return False
+
+
+def sync_model_service_once(config: V2Config | None = None) -> dict[str, Any]:
+ """Refresh one paired instance's model status and hot-apply Memory changes."""
+
+ if not _SYNC_LOCK.acquire(blocking=False):
+ return {"ok": True, "skipped": "already_running"}
+ try:
+ config = config or V2Config.load()
+ credentials = config.remote_access.vibe_cloud.runtime_credentials()
+ if credentials is None:
+ return {"ok": False, "configured": False}
+ backend_url, instance_id, _device_secret = credentials
+ status = _status_from_payload(_device_request(config, "GET", "model-service"))
+ current = V2Config.load().memory
+ current_key = current.cloud.model_access_key if current.cloud.source_instance_id == instance_id else None
+ minted = None
+ if _status_needs_model_key(current, status) and not current_key:
+ minted = _mint_from_payload(_device_request(config, "POST", "model-access-key"))
+ candidate = _resolved_memory(
+ current,
+ status=status,
+ instance_id=instance_id,
+ proxy_base_url=f"{backend_url.rstrip('/')}/v1/model",
+ minted=minted,
+ )
+ if candidate == current and not current.cloud.runtime_apply_pending:
+ return {"ok": True, "configured": True, "changed": False}
+ if candidate == current:
+ applied = _reconcile_candidate(current)
+ return {
+ "ok": applied,
+ "configured": True,
+ "changed": False,
+ "apply_pending": not applied,
+ }
+ saved = _persist_candidate(current, candidate).memory
+ applied = _reconcile_candidate(saved)
+ return {
+ "ok": applied,
+ "configured": True,
+ "changed": True,
+ "apply_pending": not applied,
+ }
+ finally:
+ _SYNC_LOCK.release()
+
+
+def rotate_model_access_key(config: V2Config | None = None) -> dict[str, Any]:
+ """Rotate mak and apply it through the same sidecar settings ladder."""
+
+ with _SYNC_LOCK:
+ config = config or V2Config.load()
+ credentials = config.remote_access.vibe_cloud.runtime_credentials()
+ if credentials is None:
+ raise ModelServiceResolutionError("model_service_not_configured")
+ _backend_url, instance_id, _device_secret = credentials
+ current = V2Config.load().memory
+ if current.cloud.source_instance_id != instance_id or not current.cloud_runtime_selected():
+ raise ModelServiceResolutionError("model_service_not_configured")
+ minted = _mint_from_payload(_device_request(config, "POST", "model-access-key"))
+ candidate = deepcopy(current)
+ candidate.cloud.model_access_key = minted.key
+ candidate.cloud.runtime_apply_pending = True
+ candidate.validate()
+ saved = _persist_candidate(current, candidate).memory
+ if not _reconcile_candidate(saved):
+ rollback = deepcopy(current)
+ rollback.cloud.runtime_apply_pending = False
+ _persist_candidate(saved, rollback)
+ _reconcile_candidate(rollback)
+ raise ModelServiceResolutionError("model_access_key_apply_failed")
+ return {
+ "ok": True,
+ "rotated": minted.rotated,
+ "created_at": minted.created_at,
+ "previous_valid_until": minted.previous_valid_until,
+ }
+
+
+def ensure_model_access_key(config: V2Config | None = None) -> V2Config:
+ """Mint the first local mak immediately before a cloud-mode switch."""
+
+ with _SYNC_LOCK:
+ config = config or V2Config.load()
+ credentials = config.remote_access.vibe_cloud.runtime_credentials()
+ if credentials is None:
+ raise ModelServiceResolutionError("model_service_not_configured")
+ _backend_url, instance_id, _device_secret = credentials
+ current = V2Config.load().memory
+ if (
+ current.cloud.source_instance_id != instance_id
+ or not current.cloud.memory_capability_available()
+ or current.cloud.scope not in {"platform", "organization"}
+ ):
+ raise ModelServiceResolutionError("model_service_not_configured")
+ if current.cloud.model_access_key:
+ return V2Config.load()
+ minted = _mint_from_payload(_device_request(config, "POST", "model-access-key"))
+ candidate = deepcopy(current)
+ candidate.cloud.model_access_key = minted.key
+ candidate.validate()
+ return _persist_candidate(current, candidate)
+
+
+def request_model_service_refresh() -> None:
+ _REFRESH_EVENT.set()
+
+
+def _worker_loop(initial_config: V2Config | None) -> None:
+ config = initial_config
+ while True:
+ try:
+ sync_model_service_once(config)
+ except Exception as exc:
+ # Resolution failures can originate in a remote response. Keep the
+ # periodic worker observable without echoing that response into logs.
+ logger.warning(
+ "Cloud Model Service sync failed (%s)",
+ type(exc).__name__,
+ )
+ config = None
+ if _REFRESH_EVENT.wait(MODEL_SERVICE_POLL_SECONDS):
+ _REFRESH_EVENT.clear()
+
+
+def start_model_service_polling(config: V2Config | None = None) -> None:
+ global _WORKER_STARTED
+
+ with _WORKER_LOCK:
+ if _WORKER_STARTED:
+ return
+ worker = threading.Thread(
+ target=_worker_loop,
+ args=(config,),
+ name="vibe-model-service-sync",
+ daemon=True,
+ )
+ _WORKER_STARTED = True
+ try:
+ worker.start()
+ except Exception:
+ _WORKER_STARTED = False
+ raise
diff --git a/vibe/remote_access.py b/vibe/remote_access.py
index d3f73aaf4..eedde400f 100644
--- a/vibe/remote_access.py
+++ b/vibe/remote_access.py
@@ -3605,8 +3605,10 @@ def start_runtime_monitoring(config: V2Config | None = None) -> None:
start_status_heartbeat(config)
start_authorization_revision_polling(config)
from vibe.project_access_sync import start_project_access_sync
+ from vibe.model_service import start_model_service_polling
start_project_access_sync(config)
+ start_model_service_polling(config)
start_resource_acl_sync_polling(config)
@@ -4258,6 +4260,12 @@ def pair(pairing_key: str, backend_url: str, device_name: str = "avibe") -> dict
remote_access_authorization_service.delete_for_instance(previous_instance_id)
except Exception:
logger.warning("Old remote authorization cleanup failed after pairing", exc_info=True)
+ try:
+ from vibe.model_service import request_model_service_refresh
+
+ request_model_service_refresh()
+ except Exception:
+ logger.warning("Cloud Model Service refresh could not be requested", exc_info=True)
start_result = start(config)
_report_runtime_status_async(config, event="pair", last_error=start_result.get("error"))
return {**status(config), "ok": True, "pairing": {"ok": True}, "start": start_result}
diff --git a/vibe/ui_memory_routes.py b/vibe/ui_memory_routes.py
index f67c0a64e..53b0b03fd 100644
--- a/vibe/ui_memory_routes.py
+++ b/vibe/ui_memory_routes.py
@@ -112,6 +112,18 @@ def _memory_settings_projection(memory: object) -> dict:
payload = memory_config_to_payload(memory)
payload.pop("diagnostics", None)
+ payload.pop("cloud", None)
+ payload["mode"] = memory.settings_mode()
+ payload["cloud_available"] = memory.cloud.memory_capability_available()
+ payload["managed"] = memory.settings_mode() == "organization"
+ payload["transition_notice_pending"] = (
+ memory.cloud.transition_notice_pending
+ )
+ payload["capability_paused"] = (
+ memory.enabled
+ and memory.cloud_runtime_selected()
+ and memory.runtime_source() == "unavailable"
+ )
return payload
@@ -162,12 +174,22 @@ def _memory_settings_patch(current: V2Config, patch_payload: object) -> tuple[di
from config.v2_config import memory_config_to_payload
if not isinstance(patch_payload, dict) or not set(patch_payload).issubset(
- {"enabled", "processing", "confirm_rebuild"}
+ {
+ "enabled",
+ "processing",
+ "mode",
+ "acknowledge_transition",
+ "confirm_rebuild",
+ }
):
raise ValueError("invalid_memory_patch")
confirm_rebuild = patch_payload.get("confirm_rebuild", False)
if not isinstance(confirm_rebuild, bool):
raise ValueError("invalid_memory_patch")
+ if "acknowledge_transition" in patch_payload and not set(
+ patch_payload
+ ).issubset({"acknowledge_transition", "confirm_rebuild"}):
+ raise ValueError("invalid_memory_patch")
target = memory_config_to_payload(current.memory, include_secrets=True)
endpoints = ("llm", "embedding", "rerank", "multimodal")
for endpoint in endpoints:
@@ -177,8 +199,40 @@ def _memory_settings_patch(current: V2Config, patch_payload: object) -> tuple[di
if not isinstance(patch_payload["enabled"], bool):
raise ValueError("invalid_memory_patch")
target["enabled"] = patch_payload["enabled"]
+ if "mode" in patch_payload:
+ mode = patch_payload["mode"]
+ if (
+ mode not in {"platform", "custom"}
+ or current.memory.cloud.scope == "organization"
+ ):
+ raise ValueError("invalid_memory_patch")
+ if (
+ mode == "platform"
+ and not current.memory.cloud.memory_capability_available()
+ ):
+ raise ValueError("memory_cloud_unavailable")
+ target["mode"] = mode
+ if "acknowledge_transition" in patch_payload:
+ if (
+ patch_payload["acknowledge_transition"] is not True
+ or not current.memory.cloud.transition_notice_pending
+ or current.memory.cloud.scope != "organization"
+ or not current.memory.cloud.memory_capability_available()
+ ):
+ raise ValueError("invalid_memory_patch")
+ target["cloud"]["organization_attached"] = True
+ target["cloud"]["transition_notice_pending"] = False
+ target["cloud"]["applied_embedding_identity"] = (
+ current.memory.cloud.embedding_identity
+ )
processing_patch = patch_payload.get("processing")
if processing_patch is not None:
+ target_mode = target.get("mode")
+ if target_mode == "platform" or (
+ current.memory.settings_mode() != "custom"
+ and target_mode != "custom"
+ ):
+ raise ValueError("invalid_memory_patch")
if not isinstance(processing_patch, dict) or not set(processing_patch).issubset(endpoints):
raise ValueError("invalid_memory_patch")
for endpoint in endpoints:
@@ -224,18 +278,9 @@ def _memory_candidate_config(current: V2Config, memory_payload: dict) -> V2Confi
def _memory_embedding_configuration_changed(current: V2Config, candidate: V2Config) -> bool:
"""Return whether the normalized vector-space identity would change."""
- current_embedding = current.memory.processing.embedding
- candidate_embedding = candidate.memory.processing.embedding
-
- def normalized(value: str | None) -> str | None:
- stripped = (value or "").strip()
- return stripped or None
-
return (
- normalized(current_embedding.base_url)
- != normalized(candidate_embedding.base_url)
- or normalized(current_embedding.model)
- != normalized(candidate_embedding.model)
+ current.memory.runtime_embedding_identity()
+ != candidate.memory.runtime_embedding_identity()
)
@@ -270,8 +315,9 @@ def _memory_preflight_required(candidate: V2Config) -> bool:
"""Require live admission unless a disabled candidate is still incomplete."""
memory = candidate.memory
+ processing = memory.runtime_processing()
return memory.enabled or (
- memory.processing.llm.complete() and memory.processing.embedding.complete()
+ processing.llm.complete() and processing.embedding.complete()
)
@@ -780,31 +826,93 @@ async def _apply_memory_settings_patch(
)
pending_marker = current.memory.recovery_intent == "rebuild"
pending_factory_reset = current.memory.recovery_intent == "factory_reset"
- except (TypeError, ValueError):
- return _memory_response({"status": "failed", "error": "memory_invalid_input"}, status_code=400)
+ factory_reset_repair = (
+ pending_factory_reset
+ and _memory_factory_reset_repair_patch(patch_payload)
+ )
- factory_reset_repair = (
- pending_factory_reset and _memory_factory_reset_repair_patch(patch_payload)
- )
+ # Validate the complete request before consuming a one-time mak
+ # response. A valid cloud switch keeps the minted key if a later
+ # provider preflight fails because no read surface can recover it.
+ if identity_changed and not confirm_rebuild and not factory_reset_repair:
+ return _memory_response(
+ {
+ "status": "failed",
+ "error": "memory_embedding_rebuild_required",
+ },
+ status_code=409,
+ )
- # Unconfirmed identity change never writes — including on empty roots —
- # so a check-then-save race cannot quietly accept a new vector space.
- # A factory-reset repair is the one deliberate exception: the reset
- # marker guarantees the next retry will wipe any remaining old root
- # before activating the corrected endpoint.
- if identity_changed and not confirm_rebuild and not factory_reset_repair:
+ if pending_factory_reset and not factory_reset_repair:
+ return _memory_response(
+ {"status": "failed", "error": "memory_operation_in_progress"},
+ status_code=409,
+ )
+
+ needs_cloud_key = (
+ isinstance(patch_payload, dict)
+ and (
+ patch_payload.get("mode") == "platform"
+ or patch_payload.get("acknowledge_transition") is True
+ )
+ and not current.memory.cloud.model_access_key
+ )
+ if needs_cloud_key:
+ from vibe.model_service import ensure_model_access_key
+
+ await asyncio.to_thread(ensure_model_access_key, current)
+ current = await asyncio.to_thread(V2Config.load)
+ target_payload, confirm_rebuild = _memory_settings_patch(
+ current,
+ patch_payload,
+ )
+ candidate = _memory_candidate_config(current, target_payload)
+ identity_changed = _memory_embedding_configuration_changed(
+ current,
+ candidate,
+ )
+ rerank_changed = _memory_rerank_configuration_changed(
+ current,
+ candidate,
+ )
+ multimodal_changed = _memory_multimodal_configuration_changed(
+ current,
+ candidate,
+ )
+ pending_marker = current.memory.recovery_intent == "rebuild"
+ pending_factory_reset = (
+ current.memory.recovery_intent == "factory_reset"
+ )
+ factory_reset_repair = (
+ pending_factory_reset
+ and _memory_factory_reset_repair_patch(patch_payload)
+ )
+ except ValueError as exc:
+ if str(exc) == "memory_cloud_unavailable":
+ return _memory_response(
+ {"status": "failed", "error": "memory_cloud_unavailable"},
+ status_code=409,
+ )
return _memory_response(
- {
- "status": "failed",
- "error": "memory_embedding_rebuild_required",
- },
- status_code=409,
+ {"status": "failed", "error": "memory_invalid_input"},
+ status_code=400,
)
+ except TypeError:
+ return _memory_response(
+ {"status": "failed", "error": "memory_invalid_input"},
+ status_code=400,
+ )
+ except Exception as exc:
+ from vibe.model_service import ModelServiceResolutionError
- if pending_factory_reset and not factory_reset_repair:
+ if isinstance(exc, ModelServiceResolutionError):
+ return _memory_response(
+ {"status": "failed", "error": "memory_cloud_unavailable"},
+ status_code=409,
+ )
return _memory_response(
- {"status": "failed", "error": "memory_operation_in_progress"},
- status_code=409,
+ {"status": "failed", "error": "memory_store_unavailable"},
+ status_code=503,
)
if factory_reset_repair: