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.

chore(merge): sync origin/master into avibe-agent

cyhe3c626482bb2
diff --cc core/controller.py
index 9db75f2b1,e2a3b884d..9b7ce008b
--- a/core/controller.py
+++ b/core/controller.py
@@@ -317,12 -324,8 +325,13 @@@ class Controller
# Background task for cleanup
self.cleanup_task: Optional[asyncio.Task] = None
+ self.vibey_model_supply_task: Optional[asyncio.Task] = None
+ from modules.agents.vibey.recovery import VibeyRecovery
+
+ # The single owner of Vibey's settlement outside a Turn.
+ self.vibey_recovery = VibeyRecovery(self)
self.trace_retention_task: Optional[asyncio.Task] = None
+ self.web_ui_watchdog_task: Optional[asyncio.Task] = None
self._trace_retention_executor: Optional[Any] = None
self._trace_retention_cancel_event: Optional[threading.Event] = None
self._trace_retention_future: Optional[Any] = None
@@@ -1247,15 -1171,22 +1264,30 @@@
e,
exc_info=True,
)
+ try:
+ # The service's own `stop()` retires the schedule at shutdown.
+ start_discovery = getattr(
+ getattr(self, "model_hub_service", None),
+ "start_background_discovery",
+ None,
+ )
+ if callable(start_discovery):
+ start_discovery()
+ except Exception as e:
+ logger.error(
+ "Failed to start Model Hub background discovery: %s",
+ e,
+ exc_info=True,
+ )
+ try:
+ # Off the readiness path: on a first start the seed may wait for a
+ # models.dev copy, and nothing below needs it.
+ if getattr(self, "vibey_model_supply_task", None) is None:
+ self.vibey_model_supply_task = asyncio.create_task(self._seed_vibey_model_supply())
+ except Exception as e:
+ logger.error("Failed to start Vibey's model supply seed: %s", e, exc_info=True)
+
try:
if self.cleanup_task is None or self.cleanup_task.done():
self.cleanup_task = asyncio.create_task(self.periodic_cleanup())
@@@ -2418,16 -2350,16 +2459,26 @@@
pass
self.cleanup_task = None
+ async def _cancel_vibey_model_supply_task() -> None:
+ task = getattr(self, "vibey_model_supply_task", None)
+ if task is not None and not task.done():
+ task.cancel()
+ try:
+ await task
+ except asyncio.CancelledError:
+ pass
+ self.vibey_model_supply_task = None
+
+ async def _cancel_web_ui_watchdog_task() -> None:
+ task = self.web_ui_watchdog_task
+ if task and not task.done():
+ task.cancel()
+ try:
+ await task
+ except asyncio.CancelledError:
+ pass
+ self.web_ui_watchdog_task = None
+
async def _cancel_trace_retention_task() -> None:
cancel_event = getattr(self, "_trace_retention_cancel_event", None)
if cancel_event is not None:
@@@ -2472,7 -2404,7 +2523,8 @@@
logger.debug(f"Internal dispatch server status write skipped: {e}")
_stop_loop_coroutine(_cancel_cleanup_task(), "Idle cleanup task")
+ _stop_loop_coroutine(_cancel_vibey_model_supply_task(), "Vibey model supply seed")
+ _stop_loop_coroutine(_cancel_web_ui_watchdog_task(), "Web UI watchdog task")
# Retention cancellation is cooperative at a delete-batch boundary;
# wait for that bounded join instead of abandoning the worker after
# the generic five-second cleanup timeout.
diff --cc core/handlers/model_hub/provenance.py
index 0e4b43095,beba20678..a08106509
--- a/core/handlers/model_hub/provenance.py
+++ b/core/handlers/model_hub/provenance.py
@@@ -597,8 -596,28 +631,28 @@@ def render_turn_outcome_copy
)
params["blockers"] = ", ".join(rendered)
if params.get("backend"):
- params["backend"] = i18n_t(f"modelHub.backends.{params['backend']}", language)
+ params["backend"] = display_name_for_backend(params["backend"])
- return i18n_t(copy.key, language, **params)
+ text = i18n_t(copy.key, language, **params)
+ failure = projection.last_upstream_failure
+ rule = _turn_outcome_rule(projection)
+ suffix_key = (
+ rule.connection_failure_key
+ if failure is not None and failure.connection_error
+ else (
+ rule.upstream_failure_key
+ if failure is not None and failure.http_status is not None
+ else rule.upstream_failure_without_status_key
+ )
+ )
+ if failure is not None and suffix_key is not None:
+ text = " ".join((
+ text,
+ i18n_t(
+ suffix_key, language,
+ source=failure.source, status=failure.http_status, detail=failure.detail,
+ ),
+ ))
+ return text
# The request id for a turn's own single attempt: the native CLI path, where
@@@ -734,16 -750,18 +791,21 @@@ class GatewayTurnTerminalizer
return self
def __exit__(self, exc_type, _exc, _traceback) -> None:
- if self._downstream_canceled or exc_type is asyncio.CancelledError:
- return
- self.commit_exit()
- if self._exit_committed:
- # A classified exit is this request's whole ending; the
- # unclassified fallback below is only for requests without one.
- return
- self._registry._terminalize_gateway_exit(
- self.turn_id,
- request_id=self._request_id,
- stream_started=self._stream_started,
- )
+ try:
+ if self._downstream_canceled or exc_type is asyncio.CancelledError:
+ return
++ self.commit_exit()
++ if self._exit_committed:
++ # A classified exit is this request's whole ending; the
++ # unclassified fallback below is only for requests without one.
++ return
+ self._registry._terminalize_gateway_exit(
+ self.turn_id,
+ request_id=self._request_id,
+ stream_started=self._stream_started,
+ )
+ finally:
+ self._registry.close_gateway_request(self._prepared_turn_id, request_id=self._request_id)
def resolution_model(self, gateway_model_id: str) -> Optional[str]:
"""Return the uniquely prepared caller model for this gateway request."""
diff --cc core/handlers/model_hub/rpc.py
index 36ab0a1f0,94ad72d6d..7becb3b24
--- a/core/handlers/model_hub/rpc.py
+++ b/core/handlers/model_hub/rpc.py
@@@ -121,8 -121,9 +122,9 @@@ async def dispatch_model_hub_rpc
backend,
)
if operation == "agent_model_candidates":
+ service.request_inventory_refresh()
backend = payload.get("backend")
- if backend in ("claude", "codex", "opencode"):
+ if backend in NATIVE_CLI_BACKENDS:
await _refresh_agent_presence(service, (backend,))
if backend != "opencode":
await service.reconcile_builtin_models((backend,))
diff --cc core/handlers/model_hub/service.py
index ff1f86a04,e32490436..0203b838c
--- a/core/handlers/model_hub/service.py
+++ b/core/handlers/model_hub/service.py
@@@ -137,9 -134,8 +137,10 @@@ from .provenance import
BoundedProvenanceStore,
ENGINE_DOWN_TURN_OUTCOME,
ExactHopBlocker,
+ HopOrigin,
+ ServedHopHeaderTooLarge,
TurnOutcomeProjectionInput,
+ TurnUpstreamFailure,
exact_hop_blockers,
no_candidate_decision,
produce_turn_outcome,
@@@ -276,10 -272,25 +277,25 @@@ _MODELS_DEV_CANDIDATE_FIELDS =
)
-AGENT_CHAIN_CONTRACT_VERSION = 10
-PROBE_RESULT_CONTRACT_VERSION = 10
+AGENT_CHAIN_CONTRACT_VERSION = 11
+PROBE_RESULT_CONTRACT_VERSION = 11
_SOURCE_DISCOVERY_TIMEOUT_SECONDS = 15
_SOURCE_PROBE_TIMEOUT_SECONDS = 60
+ # Background inventory refresh. The first tick doubles as the startup delay, so
+ # a stale Source catches up shortly after boot without boot waiting on upstream.
+ _BACKGROUND_DISCOVERY_INTERVAL = timedelta(hours=6)
+ _BACKGROUND_DISCOVERY_JITTER = 0.2
+ _BACKGROUND_DISCOVERY_TICK = timedelta(minutes=5)
+ _BACKGROUND_DISCOVERY_RETRY_BASE = timedelta(minutes=15)
+ _BACKGROUND_DISCOVERY_RETRY_CAP = timedelta(hours=6)
+ # A viewer of Source inventory asks for listings at most this old.
+ _VIEWED_DISCOVERY_AGE = timedelta(minutes=30)
+ # A credential waiting on the user cannot list models until the user acts.
+ _UNDISCOVERABLE_SOURCE_DETAILS = frozenset({
+ "models.source.needs_action.oauth_expired",
+ "models.source.needs_action.credential_revoked",
+ "models.source.needs_action.account_banned",
+ })
_REORDER_ORDER_UNSET = object()
# Settlement generations are minted per attempt start and live only in this
# runtime's ledger, which restarts with the process. Every generation this
@@@ -8471,11 -8564,13 +8855,15 @@@ class ModelHubService
failed_source: Optional[ModelHubSourceConfig] = None
failed_reason: Optional[EventReason] = None
+ last_upstream_failure = (
+ recovery_request.last_upstream_failure if recovery_request is not None else None
+ )
window_closed = False
non_retryable_failure = False
+ attempted = False
globally_blocked_source_ids: set[str] = set()
+ unsupported_hops: set[tuple[str, str]] = set()
+ unsupported_reason: str | None = None
while True:
async with self._mutation_lock:
if recovery_request is not None and recovery_request.expired:
diff --cc tests/conftest.py
index 8c9e92db3,df7612aba..283641e7f
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@@ -121,10 -121,10 +121,14 @@@ _CALLER_ENV =
# that Runtime, and every stop, restart and start refuses or claims by its id.
"AVIBE_DESKTOP_RUNTIME_ID",
"AVIBE_DESKTOP_RUNTIME_ROOT",
+ "AVIBE_COMPUTER_USE_DRIVER_PATH",
+ "AVIBE_COMPUTER_USE_POLICY_PATH",
+ "AVIBE_COMPUTER_USE_STATE_DIR",
+ "AVIBE_COMPUTER_USE_SNAPSHOT_PATH",
+ # A pytest run as a `vibe watch` command inherits that cycle's identity, which
+ # puts the bundled GitHub waiters under test into managed-watch mode.
+ "AVIBE_WATCH_ID",
+ "AVIBE_WATCH_LAST_DELIVERY",
)
# What the run started with, for `uses_real_paths` tests and the tripwire.
_AMBIENT_ENV = {name: os.environ.get(name) for name in (*_HOME_ENV, *_CALLER_ENV)}
diff --cc tests/scenarios/auth_setup/catalog.yaml
index c4410f009,208252f63..0db00cd1d
--- a/tests/scenarios/auth_setup/catalog.yaml
+++ b/tests/scenarios/auth_setup/catalog.yaml
@@@ -473,20 -473,41 +473,58 @@@ scenarios
- ui/src/components/onboarding/AssistantSetup.test.tsx
- ui/e2e/onboarding-fidelity/provider-gate.spec.ts
- id: AUTH-SETUP-127
+ name: A mis-pasted Hub OAuth callback stays recoverable and a scheme-less callback address signs in
+ status: covered
+ kind: historical_regression
+ layer: scenario
+ backend: shared
+ test: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::test_hub_oauth_mispaste_stays_recoverable_and_schemeless_address_signs_in
+ supporting_tests:
+ - tests/test_model_hub_runtime.py::test_oauth_paste_reaches_the_engine_as_the_value_it_is
+ - tests/test_model_hub_runtime.py::test_oauth_paste_that_cannot_exchange_keeps_the_flow_awaiting
+ - tests/test_model_hub_runtime.py::test_oauth_engine_failure_names_what_the_user_can_do
+ - tests/test_model_hub_runtime.py::test_oauth_failure_detail_is_the_engine_reason_on_one_bounded_line
+ - ui/src/components/settings/models/serverCopy.test.ts
+ - ui/src/components/settings/models/SettingsModelsPage.render.test.tsx
+ - id: AUTH-SETUP-128
+ name: The desktop pet leaves its setup-pending state once setup is finished in the main window
+ status: partial
+ kind: happy_path
+ layer: scenario
+ missing_layer: ui-e2e
+ backend: web
+ reason: >-
+ the rule is a browser rule across two windows with no new server boundary:
+ the pet route sits behind the login and authorization gates but is exempt
+ from the setup redirect, shows its own setup-pending state, and re-reads
+ the configuration past the config cache on every summon, focus and
+ visibility change, so finishing the wizard in the main window clears it
+ without a restart. The route tests drive the real setup gate, summon store
+ and config read against controlled responses; the packaged two-window
+ journey through the desktop shell's pet window is a manual check.
+ owning_layer: L4 integrated acceptance (packaged desktop shell against a live instance)
+ partial_evidence:
+ covers: the server half at the real boundary — the `/pet` shell document, authentication refusal of the config read, a signed-in pet read that reports setup pending with the fields the setup rule reads, completion from a second client through CSRF, and the pet's per-call re-read seeing it; the browser rules are the supporting tests below, against controlled responses
+ test: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::test_pet_window_reads_setup_finished_in_the_main_window_closed_loop
+ supporting_tests:
+ - ui/src/pet/PetPage.test.tsx
+ - ui/src/lib/remoteAuth.test.ts
+ - ui/src/App.remoteAuth.test.tsx
++ - id: AUTH-SETUP-129
+ name: Built-in Vibey takes its first model in setup and completes setup without a CLI
+ status: covered
+ kind: happy_path
+ layer: scenario
+ backend: vibey
+ test: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::test_builtin_vibey_model_pick_completes_setup_without_a_cli
+ # The scenario owns the server boundary the setup card calls: the candidates read, the
+ # catalog write that refuses a moved supplier projection and commits nothing, the
+ # built-in Agent's model, the runnable named route, the default and completion. The
+ # browser side — which candidates the card offers, the order of the two writes, and
+ # the entry gate ranking the built-in backend after any runnable CLI assistant — is
+ # the supporting tests below, against controlled responses.
+ supporting_tests:
+ - ui/src/components/onboarding/BuiltinAssistant.test.tsx
+ - ui/src/components/onboarding/entryGate.test.ts
+ - ui/e2e/onboarding-fidelity/lineup.spec.ts
next_priority: []
diff --cc tests/scenarios/auth_setup/test_auth_setup_scenarios.py
index 0adbe5b40,d03423ec8..d909d0cd3
--- a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py
+++ b/tests/scenarios/auth_setup/test_auth_setup_scenarios.py
@@@ -4376,107 -4567,6 +4580,107 @@@ def test_explicit_opencode_model_recove
store.close()
+def test_builtin_vibey_model_pick_completes_setup_without_a_cli(monkeypatch, tmp_path):
- """AUTH-SETUP-127: Vibey candidates -> catalog write -> Agent model -> runnable route -> completion.
++ """AUTH-SETUP-129: Vibey candidates -> catalog write -> Agent model -> runnable route -> completion.
+
+ The setup card for the built-in backend reads its candidates, adds a pick its catalog
+ lacks with the suppliers it displayed, names it as the built-in Agent's model and then
+ lets setup finish on that Agent alone. Every step here is the HTTP route the card
+ calls; the Hub service is wired to the real Agent store the way the controller wires it.
+ """
+ from core.vibe_agents import VibeAgentStore
+ from tests.test_model_hub_api import _service
+
+ monkeypatch.setenv("VIBE_MODEL_HUB_ENABLED", "1")
+ V2Config.default().save()
+ service, store, _adapter = _service(tmp_path / "hub")
+ agents = VibeAgentStore()
+ service.named_agents_override = lambda backend: [
+ (agent.name, agent.model)
+ for agent in agents.list_agents(include_disabled=False)
+ if agent.backend == backend
+ ]
+ monkeypatch.setattr(ui_server, "_model_hub_service", lambda: service)
+ source = ModelHubSourceConfig(
+ id="src_vibey001",
+ kind="api_key",
+ vendor="custom",
+ display_name="Mock Lab",
+ protocol="openai_chat",
+ supply_channel="hub",
+ billing="metered",
+ state=ModelHubSourceStateConfig(status="standby"),
+ models=[ModelHubModelConfig(id=model, provenance="discovered") for model in ("mock-large", "mock-mini")],
+ credential_ref="cred_vibey001",
+ )
+ store.config.sources = [source]
+ store.config.agents["vibey"].sources.order = [source.id]
+ client = app.test_client()
+ headers = csrf_headers(client)
+ try:
+ listed = client.get("/api/agents").get_json()
+ vibey = next(row for row in listed["agents"] if row["backend"] == "vibey")
+ assert vibey["model"] is None
+
+ candidates = client.get("/api/models/agents/vibey/models/candidates").get_json()["candidates"]
+ pick = next(row for row in candidates["providers"] if row["id"] == "mock-mini")
+ suppliers = [{"source_id": row["source_id"], "model_id": row["model_id"]} for row in pick["suppliers"]]
+ assert suppliers == [{"source_id": source.id, "model_id": "mock-mini"}]
+
+ def vibey_supply():
+ rows = client.get("/api/models/agents").get_json()["agents"]
+ return next(row for row in rows if row["backend"] == "vibey")
+
+ baseline = vibey_supply()["catalog_models"]
+ assert baseline == []
+ # The row the card builds for a candidate: what the candidate states, nothing more.
+ added = {
+ "id": pick["id"], "display_name": pick["display_name"], "origin": pick["origin"],
+ "models_dev_id": None, "context_window": None, "max_output_tokens": None,
+ "input_modalities": [], "output_modalities": [], "supports_tools": None,
+ "supports_reasoning": None, "reasoning_efforts": list(pick["reasoning_efforts"]),
+ "locked": False, "routeable": True,
+ }
+ before = store.config.to_payload()
+ stale = client.put(
+ "/api/models/agents/vibey/models",
+ json={"baseline": baseline, "models": [*baseline, added], "expected_suppliers": {"mock-mini": []}},
+ headers=headers,
+ )
+ # A pick whose suppliers moved after the card showed them commits nothing.
+ assert stale.status_code == 409, stale.get_json()
+ assert stale.get_json()["error"] == "candidate_suppliers_changed"
+ assert store.config.to_payload() == before
+
+ written = client.put(
+ "/api/models/agents/vibey/models",
+ json={"baseline": baseline, "models": [*baseline, added], "expected_suppliers": {"mock-mini": suppliers}},
+ headers=headers,
+ )
+ assert written.status_code == 200, written.get_json()
+ assert [row["id"] for row in vibey_supply()["catalog_models"]] == ["mock-mini"]
+
+ named = client.patch(f"/api/agents/{vibey['name']}", json={"model": "mock-mini"}, headers=headers)
+ assert named.status_code == 200, named.get_json()
+ assert agents.require(vibey["name"]).model == "mock-mini"
+ supply = vibey_supply()
+ assert supply["cli_present"] is False
+ route = next(row for row in supply["named_agents"] if row["name"] == vibey["name"])
+ assert route["effective_model_id"] == "mock-mini"
+ assert route["supply_status"] in {"ok", "degraded"}
+ assert route["route_reason"] != "route_unconfigured"
+
+ # With no CLI assistant able to run, setup enters on the built-in Agent.
+ chosen = client.post("/api/agents/default", json={"name": vibey["name"]}, headers=headers)
+ assert chosen.status_code == 200, chosen.get_json()
+ completed = client.post("/api/config", json={"setup_completed": True}, headers=headers)
+ assert completed.status_code == 200, completed.get_json()
+ assert V2Config.load().setup_completed
+ assert agents.get_default_agent().name == vibey["name"]
+ finally:
+ agents.close()
+
+
@pytest.mark.parametrize("setup_host", ["192.0.2.5", "fd00::1", "2001:db8::5", "[2001:db8::5]"])
async def test_cloud_pairing_origin_reaches_effective_ui_listener(monkeypatch, setup_host):
"""Scenario: AUTH-SETUP-907 — every origin consumer reaches the widened UI bind."""
diff --cc tests/test_model_hub_failure_presentation.py
index 1d272a953,df1e3869f..9e0365d66
--- a/tests/test_model_hub_failure_presentation.py
+++ b/tests/test_model_hub_failure_presentation.py
@@@ -21,7 -20,7 +25,8 @@@ from core.handlers.model_hub.provenanc
render_turn_outcome_copy,
)
from core.handlers.model_hub.turn_gateway import ModelHubTurnGateway
+ from core.run_settlement import SETTLED_BY_TERMINAL_RESULT
+from modules.agents.catalog import AGENT_BACKENDS
from modules.agents.model_hub import ModelHubRuntimeRouter, bind_launch
from modules.im import MessageContext
from tests.test_model_hub_l3 import _canonicalize_fixed_test_routes, _outcome
diff --cc ui/src/components/settings/models/types.ts
index b8c4e6a3e,4df3f900e..1f9ba53c9
--- a/ui/src/components/settings/models/types.ts
+++ b/ui/src/components/settings/models/types.ts
@@@ -630,8 -624,8 +630,9 @@@ export type TurnProvenance =
stream_started: boolean;
http_status?: number | null;
upstream_error_code?: string | null;
+ upstream_detail?: string;
local_error_detail?: string;
+ origin?: { provider: string; api: SourceProtocol; model: string };
stripped_reasoning_efforts?: string[];
declared_reasoning_efforts?: string[];
} | null;