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.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(macos): report stale login sessions (#3012)
Call White6ae99554220f
diff --git a/core/internal_server.py b/core/internal_server.pyindex 06b831808..086733b53 100644--- a/core/internal_server.py+++ b/core/internal_server.py@@ -747,8 +747,12 @@ def create_app(@app.get("/internal/health")async def _health() -> dict[str, Any]:from vibe.desktop_runtime import desktop_runtime_id+ from vibe.macos_session_diagnostics import current_macos_session_statepayload = {"ok": True, "service": "vibe-remote-internal", "version": 1}+ session_state = current_macos_session_state()+ if session_state is not None:+ payload["macos_login_session_state"] = session_stateruntime_id = desktop_runtime_id()if runtime_id is not None:payload["desktop_runtime_id"] = runtime_iddiff --git a/docs/plans/macos-session-diagnostics.md b/docs/plans/macos-session-diagnostics.mdindex fc61dae3b..fe84ce46d 100644--- a/docs/plans/macos-session-diagnostics.md+++ b/docs/plans/macos-session-diagnostics.md@@ -34,10 +34,39 @@ and recovery.The obvious periodic-timer logger is intentionally rejected: it adds noise whileproviding no extra evidence during a persistent failure.+## Confirmed explicit-logout result (2026-10-27)++The waiting case was reproduced on the Mac mini on **October 27, 2026**. The+owner logged out and logged back in: `loginwindow` restarted at **01:33** and+Dock/Finder appeared in the new desktop at **01:38** (Asia/Shanghai). The Avibe+service and UI server had started at 23:02 in the old session, survived logout+as PPID 1 orphans, and continued to spawn children in that dead session.++The old diagnostic recorded `launchctl print gui/501` as `command_failed` because+calling it from the dead session returned “Reentrancy avoided”; that left the+GUI-domain and ASID fields inconclusive. The stronger process-local signal was+then confirmed: `getpwuid(501)` failed with `KeyError`, while Directory Services+and `security list-keychains` also failed. Avault authorization failed in 36 ms+with `not_completed` and an underlying `errSecParam`. Only `vibe restart` run+from Terminal in the new desktop session repaired the instance; restarting from+inside Avibe would inherit the dead session.++The monitor now treats the service process's own Directory Services+`user_lookup_failed` result as the positive `stale_login_session` signal. A+`launchctl` GUI-domain command failure alone remains inconclusive. The signal+was added to the existing bounded, redacted transition monitor and is kept+separate from ordinary GUI-domain absence.+## Residual Manual Matrix-- Lock/unlock and VNC disconnect/reconnect: expect no transition unless console,- GUI-domain, ASID-match, or DNS state actually changes.+The classifier's explicit no-flag cases are represented in focused tests:+Fast User Switching with both users logged in, lock/unlock, VNC, and sleep/wake+(including a recreated GUI ASID) remain non-stale; a genuinely absent GUI domain+is classified as `no_gui_session`, not stale. A real manual re-run can still+validate these shapes on additional macOS versions.++- Lock/unlock and VNC disconnect/reconnect: any diagnostic transition is+ informational; neither case may be classified as `stale_login_session`.- Fast User Switching with both users logged in: expect a console-user transitionwhile the Avibe GUI domain stays available and ASIDs stay matched.- Explicit or automatic logout/login: observe GUI-domain disappearance and@@ -46,12 +75,13 @@ providing no extra evidence during a persistent failure.- Sleep/wake, VPN, and network reconfiguration: observe DNS failure/recoverywithout logging DNS servers or addresses.-These diagnostics collect evidence for the next occurrence; they do not prove-the stale-Aqua-domain hypothesis or change service lifecycle behavior.+These diagnostics record the confirmed stale-session signal and remain+best-effort; they do not start, stop, or restart service lifecycle state.## Todo- [x] Add injected parsers/probes and a transition-deduplicating monitor.- [x] Attach the monitor to service startup and shutdown on macOS only.- [x] Add focused parsing, transition, failure, and non-macOS tests.-- [x] Run focused pytest and Ruff before delivery.+- [x] Confirm the explicit logout/login case and record the positive process-local signal.+- [x] Expose the stale-session reason consistently through Vault, Doctor, CLI, and Web surfaces.diff --git a/docs/plans/macos-stale-session-auto-recovery.md b/docs/plans/macos-stale-session-auto-recovery.mdnew file mode 100644index 000000000..2649b66c4--- /dev/null+++ b/docs/plans/macos-stale-session-auto-recovery.md@@ -0,0 +1,98 @@+# macOS stale-session automatic recovery proposal++## Decision requested++Part 1 detects an Avibe process that survived an ended macOS login session and+asks the user to run `vibe restart` from the current desktop. This proposal+covers automatic replacement after the next login only; it is design material,+not an implementation in this PR.++## Recommendation++Install one per-user macOS `LaunchAgent` in the user's `gui/<uid>` domain,+owned by the selected Avibe installation. It should use `RunAtLoad` and start a+new service only after the user has logged into the desktop. The service's+existing `service.lock` and orphan handling remain the single takeover+mechanism: a new instance must first observe the old owner, wait for its+bounded retirement policy, and never kill an unrelated process merely because+it has the same executable name.++The LaunchAgent should be an opt-in, explicit lifecycle integration rather+than an unconditional installer side effect. The Tauri shell's launch-at-login+setting should enable or disable the same owner-controlled registration and+should adopt an existing daemon only after a fresh-session health check. If the+health check reports `stale_login_session`, the shell must not adopt it: it+should leave the stale owner untouched, start the new instance through the+normal lifecycle path, and let `service.lock`/orphan handling settle the+handoff.++## Lifecycle semantics++- `vibe start`: ensure the per-user launcher is installed when the user has+ opted into launch-at-login, then start the service in the current session.+- `vibe stop`: stop the current instance but retain the launcher preference;+ `RunAtLoad` must not immediately defeat an intentional stop. This likely+ needs a short-lived disabled marker or launchctl kickstart suppression that+ the next explicit `start` clears.+- `vibe restart`: stop and start the current generation in the same session;+ it is still the explicit repair for an already-stale instance.+- `vibe upgrade`: install the new generation, preserve the launch preference,+ and replace/reload the LaunchAgent atomically. Do not leave a plist pointing+ at a removed uv-tool path or an old desktop bundle.+- Uninstall must remove only Avibe's labeled LaunchAgent and its marker. It+ must stop the owned service first, preserve user data, and never remove a+ user-created unrelated launch item.++## Installation variants and shell adoption++For uv-tool installs, the launcher should point at a stable Avibe launcher or+an absolute interpreter/tool path that `vibe upgrade` can repair. It must not+capture a transient virtualenv path. For desktop-bundled installs, the+launcher should point at the signed bundle's stable helper/CLI entry point;+Tauri and CLI must agree on the label, owner metadata, and service lock.++The desktop shell currently has launch-at-login and adopts an existing daemon.+Adoption needs a freshness gate: compare the service's session identity with the+current GUI session and reject a `stale_login_session` result. Otherwise the+shell can reconnect to a dead-session daemon and recreate the incident. The+shell should also distinguish "launcher started this generation" from "found a+healthy pre-existing service" for safe stop/quit behavior.++## Headless and SSH-only Macs++A LaunchAgent in `gui/<uid>` is intentionally a desktop-session feature. A+headless Mac or SSH-only user should not receive a fake GUI launcher or a+Keychain dialog expectation. Keep explicit `vibe start`/`stop`/`restart`+semantics available over SSH, report `no_gui_session` when a GUI-only action is+impossible, and document a separate system/service-manager integration if+headless boot is needed. Automatic login-session replacement should remain+disabled unless the user selects a headless-compatible mode and its credential+backend is usable without Aqua.++## Linux parity++Do not force macOS LaunchAgent concepts into Linux. The Linux parity contract+should be an optional per-user `systemd --user` unit with `WantedBy=default.target`+and the same freshness, lock, stop-marker, upgrade, and uninstall semantics.+Where systemd is unavailable, retain manual lifecycle commands. The shared+contract is "start once per current user session and never adopt a stale+instance," not a shared unit-file format.++## Rollback and trade-offs++The recommended launcher gives the best recovery for the confirmed logout /+login failure and keeps Avibe local-first, but it adds another lifecycle owner,+installer migration work, and platform-specific stop semantics. A simpler+alternative is to have only the Tauri shell repair stale daemons on startup;+that avoids a new launcher but does not recover uv-tool/headless CLI users and+fails when the shell is not installed or disabled. A fully automatic stale+process kill is rejected: it risks interrupting work and crosses the existing+service ownership safety boundary.++Rollback should be a versioned launcher migration: disable the new launcher,+remove only its label and marker, and fall back to the existing manual/Tauri+startup path. Keep the service lock and state files intact so rollback does not+wipe credentials, pairing, remote access, or workspace data. Before shipping,+owner decisions are needed on launch-at-login default/opt-in, intentional-stop+marker duration, Tauri adoption UX, and whether headless Linux/macOS+registration is in scope.diff --git a/tests/test_avault_authorization.py b/tests/test_avault_authorization.pyindex 3c08a2826..18b6c9a2c 100644--- a/tests/test_avault_authorization.py+++ b/tests/test_avault_authorization.py@@ -43,6 +43,36 @@ def test_exit_77_reports_authorization_required_until_the_key_reads_again(mac_avassert api.get_avault_authorization_status()["required"] is False+def test_stale_login_session_replaces_raw_avault_failure(mac_avault, monkeypatch):+ mac_avault()+ monkeypatch.setattr(api, "macos_login_session_state", lambda: "stale_login_session")++ with pytest.raises(api.AvaultStaleLoginSessionError) as exc:+ api.avault_pubkey()++ assert exc.value.code == "stale_login_session"+ assert isinstance(exc.value, api.AvaultStaleLoginSessionBeforeHandoffError)+ with pytest.raises(api.AvaultStaleLoginSessionError) as exc:+ api.avault_deliver_run(_secret(), ["sh", "-c", "exit 0"])+ assert isinstance(exc.value, api.AvaultPreHandoffError)+ status = api.get_avault_authorization_status()+ assert status["login_session_state"] == "stale_login_session"+++def test_target_service_state_comes_from_the_running_service(monkeypatch):+ from vibe import internal_client++ monkeypatch.setattr(api.platform, "system", lambda: "Darwin")+ monkeypatch.setattr(internal_client, "health_identity_sync", lambda: {+ "ok": True,+ "service": "vibe-remote-internal",+ "version": 1,+ "macos_login_session_state": "stale_login_session",+ })++ assert api.macos_login_session_state(service_pid=4242) == "stale_login_session"++def test_avault_without_the_contract_keeps_todays_failures(mac_avault):avault = mac_avault(version="0.1.7", unauthorized_status=70)@@ -91,6 +121,23 @@ def test_agent_authorization_frame_becomes_the_same_pre_handoff_error(mac_avaultassert api.get_avault_authorization_status()["required"] is True+def test_stale_agent_authorization_frame_preserves_pre_handoff(monkeypatch):+ from vibe.avault_agent import AvaultAgentAuthorizationRequiredError++ class Client:+ def deliver_inject(self, **_kwargs):+ raise AvaultAgentAuthorizationRequiredError("macOS Keychain needs a one-time authorization")++ monkeypatch.setattr(api, "_avault_agent_client", Client)+ monkeypatch.setattr(api, "_require_avault_grant_delivery_surface", lambda _feature: None)+ monkeypatch.setattr(api, "macos_login_session_state", lambda: "stale_login_session")++ with pytest.raises(api.AvaultStaleLoginSessionBeforeHandoffError) as exc:+ api.avault_agent_deliver_inject(grant_id="vgr_1", path="/tmp/out.env", fmt="dotenv", secrets=[])++ assert isinstance(exc.value, api.AvaultPreHandoffError)++def _wait_for_attempt() -> dict:deadline = time.monotonic() + 10while time.monotonic() < deadline:@@ -127,6 +174,14 @@ def test_concurrent_authorize_requests_share_one_avault_dialog(mac_avault):@pytest.mark.parametrize(("setup", "reason", "runs_avault"),[+ (+ lambda avault, monkeypatch: (+ avault.flag("deny"),+ monkeypatch.setattr(api, "macos_login_session_state", lambda: "stale_login_session"),+ ),+ "stale_login_session",+ True,+ ),(lambda avault, monkeypatch: avault.flag("deny"), "not_completed", True),(lambda avault, monkeypatch: (@@ -148,7 +203,10 @@ def test_authorize_failures_are_classified_without_parsing_avault_text(mac_avaulassert result["ok"] is False and result["reason"] == reasonassert ("key authorize" in avault.calls()) is runs_avaultif runs_avault:- assert result["detail"].startswith("avault:")+ if reason == "stale_login_session":+ assert "detail" not in result+ else:+ assert result["detail"].startswith("avault:")def test_authorize_needs_an_avault_with_the_contract(mac_avault):@@ -187,6 +245,25 @@ def test_status_readers_and_failed_calls_never_authorize(mac_avault, monkeypatchassert doctor["status"] == "warn" and "repair" not in doctor+def test_doctor_reports_stale_login_session_with_restart_action(monkeypatch):+ monkeypatch.setattr(api.platform, "system", lambda: "Darwin")+ monkeypatch.setattr(cli.runtime, "resolve_service_owner_pid", lambda include_starting=False: 4242)+ calls = []++ def probe(**kwargs):+ calls.append(kwargs)+ return "stale_login_session"++ monkeypatch.setattr(api, "macos_login_session_state", probe)++ item = cli._macos_login_session_doctor_items(language="en")[0]++ assert item["status"] == "fail"+ assert item["code"] == "stale_login_session"+ assert calls == [{"service_pid": 4242}]+ assert "vibe restart" in item["action"]++def test_cli_authorize_is_for_the_user_not_an_agent(mac_avault, monkeypatch, capsys):avault = mac_avault()monkeypatch.setenv("AVIBE_SESSION_ID", "ses_agent")@@ -198,6 +275,19 @@ def test_cli_authorize_is_for_the_user_not_an_agent(mac_avault, monkeypatch, capassert avault.calls() == []+def test_cli_authorize_reports_stale_login_session_without_raw_detail(mac_avault, monkeypatch, capsys):+ avault = mac_avault()+ avault.flag("deny")+ monkeypatch.delenv("AVIBE_SESSION_ID", raising=False)+ monkeypatch.setattr(api, "macos_login_session_state", lambda: "stale_login_session")++ assert cli.cmd_vault_key_authorize(None) == 1+ error = capsys.readouterr().err+ assert '"code": "stale_login_session"' in error+ assert "errSecParam" not in error+ assert "vibe restart" in error++def test_cli_authorize_reports_success_and_failures(mac_avault, monkeypatch, capsys):import jsondiff --git a/tests/test_dependency_inspection.py b/tests/test_dependency_inspection.pyindex 9c4ead3e6..25690a58d 100644--- a/tests/test_dependency_inspection.py+++ b/tests/test_dependency_inspection.py@@ -61,6 +61,7 @@ def probes(monkeypatch):monkeypatch.setattr(api, "_show_runtime_dependencies_status", probe(GROUPS[2]))monkeypatch.setattr(api, "_model_hub_engine_dependency_status", probe(GROUPS[3]))monkeypatch.setattr(tmux_runtime, "tmux_status", probe(GROUPS[4]))+ monkeypatch.setattr(api, "macos_login_session_state", lambda: "healthy")return calls@@ -77,7 +78,7 @@ def test_selective_checks_preserve_complete_rows_and_only_probe_their_owners(proassert result["deps"] == [row for row in complete["deps"] if row["id"] in requested]assert result["reconciling"] is Falseassert result["reconciling_dependencies"] == []- assert set(result) == {"ok", "deps", "reconciling", "reconciling_dependencies"}+ assert set(result) == {"ok", "deps", "reconciling", "reconciling_dependencies", "login_session_state"}assert [group for group, _ in probes] == [group for group in GROUPS if set(group).intersection(requested)]diff --git a/tests/test_macos_session_diagnostics.py b/tests/test_macos_session_diagnostics.pyindex 505ea6181..459967e3a 100644--- a/tests/test_macos_session_diagnostics.py+++ b/tests/test_macos_session_diagnostics.py@@ -11,6 +11,7 @@ from vibe.macos_session_diagnostics import (MacOSSessionMonitor,MacOSSessionProbe,SessionContext,+ login_session_state,parse_gui_domain_asid,parse_launchctl_asid,)@@ -95,6 +96,7 @@ def context(gui_asid: int | None = 120001,gui_available: bool | None = True,gui_error: str | None = None,+ service_error: str | None = None,) -> SessionContext:return SessionContext(service_pid=4242,@@ -103,6 +105,7 @@ def context(service_asid=service_asid,gui_asid=gui_asid,gui_domain_available=gui_available,+ service_error_class=service_error,gui_error_class=gui_error,)@@ -135,6 +138,52 @@ def make_monitor(logger: logging.Logger, probe, *, dns_interval: float = 300.0):return monitor, threads+def test_monitor_exposes_cached_service_state() -> None:+ logger = logging.getLogger("macos-session-state-test")+ monitor, _threads = make_monitor(+ logger,+ FakeProbe(+ [context(service_error="user_lookup_failed")],+ [DnsProbeState("healthy")],+ ),+ )++ assert monitor.current_state == "unknown"+ monitor.poll_once(now=0.0)+ assert monitor.current_state == "stale_login_session"+++def test_stale_login_session_uses_directory_services_failure_from_recorded_case() -> None:+ probe = MacOSSessionProbe(+ service_pid=4242,+ service_uid=501,+ command_runner=lambda command, timeout: CommandResult(1, "Reentrancy avoided"),+ console_user_reader=lambda: ("cyh", None),+ service_user_reader=lambda uid: (None, "user_lookup_failed"),+ )++ captured = probe.capture_context()++ assert captured.gui_domain_available is None+ assert captured.asid_match is None+ assert captured.service_error_class == "user_lookup_failed"+ assert login_session_state(captured) == "stale_login_session"+++def test_login_session_classifier_does_not_flag_normal_session_shapes() -> None:+ # Fast User Switching, lock/unlock, VNC, and sleep/wake can change the+ # foreground user or GUI ASID without invalidating this process's login.+ normal = [+ context(console_user="other-user"), # Fast User Switching+ context(), # lock/unlock+ context(), # VNC+ context(gui_asid=120002), # sleep/wake recreation+ ]+ assert [login_session_state(item) for item in normal] == ["healthy"] * 4+ assert login_session_state(context(gui_available=False, gui_error="absent")) == "no_gui_session"+ assert login_session_state(context(gui_asid=120002)) == "healthy"++def test_launchctl_snapshot_parsing_uses_security_context_fixture() -> None:assert parse_launchctl_asid(SERVICE_LAUNCHCTL_FIXTURE) == 120001assert parse_gui_domain_asid(GUI_LAUNCHCTL_FIXTURE) == 120001@@ -189,6 +238,7 @@ def test_initial_snapshot_is_single_compact_event_and_unchanged_poll_is_silent(c"event": "macos_session_snapshot","gui_asid": 120001,"gui_domain_available": True,+ "login_session_state": "healthy","reason": ["service_start"],"service_asid": 120001,"service_pid": 4242,@@ -213,6 +263,7 @@ def test_fast_user_switch_logs_only_console_user_transition(caplog) -> None:assert payloads[-1]["reason"] == ["console_user_change"]assert payloads[-1]["gui_domain_available"] is Trueassert payloads[-1]["asid_match"] is True+ assert payloads[-1]["login_session_state"] == "healthy"assert probe.dns_calls == 2@@ -259,6 +310,7 @@ def test_asid_mismatch_transition_is_logged(caplog) -> None:transition = event_payloads(caplog)[-1]assert transition["reason"] == ["gui_domain_change", "asid_match_change"]assert transition["asid_match"] is False+ assert transition["login_session_state"] == "healthy"def test_dns_failure_is_deduplicated_until_recovery(caplog) -> None:diff --git a/tests/test_member_management_parity.py b/tests/test_member_management_parity.pyindex f4ee6a89b..946c8572b 100644--- a/tests/test_member_management_parity.py+++ b/tests/test_member_management_parity.py@@ -118,7 +118,7 @@ def test_complete_registered_api_management_inventory():for method in (getattr(route, "methods", None) or ())if method not in {"HEAD", "OPTIONS"}}- assert len(endpoints) == 294+ assert len(endpoints) == 295# Editors who use Vault read avault's authorization state; the handler admits only# instance managers to raise the Keychain dialog on the host.for method in ("GET", "POST"):diff --git a/tests/test_vault_api.py b/tests/test_vault_api.pyindex b733ad548..907b716e4 100644--- a/tests/test_vault_api.py+++ b/tests/test_vault_api.py@@ -3373,7 +3373,28 @@ def test_agent_deliver_run_treats_connect_failure_as_pre_handoff(monkeypatch):)-def test_agent_deliver_fetch_uses_finite_timeout(monkeypatch):+++def test_agent_connect_failure_in_stale_session_preserves_pre_handoff(monkeypatch):+ from vibe.avault_agent import AvaultAgentError++ class FakeManager:+ def client(self, *, timeout=None):+ raise AvaultAgentError("failed to connect to avault agent: [Errno 2] No such file or directory")++ monkeypatch.setattr(api, "_require_avault_grant_delivery_surface", lambda _feature: None)+ monkeypatch.setattr(api, "_avault_agent_manager", lambda: FakeManager())+ monkeypatch.setattr(api, "macos_login_session_state", lambda: "stale_login_session")++ with pytest.raises(api.AvaultStaleLoginSessionBeforeHandoffError) as exc:+ api.avault_agent_deliver_run(+ grant_id="vgr_grant",+ secrets=[{"name": "GRANT_KEY", "env": "GRANT_KEY", "envelope": _sealed()}],+ command=["python3", "-c", "pass"],+ )++ assert isinstance(exc.value, api.AvaultPreHandoffError)+ assert exc.value.code == "stale_login_session"seen_timeout = []class FakeClient:diff --git a/ui/e2e/workbench-general/sidebar-floating.spec.ts b/ui/e2e/workbench-general/sidebar-floating.spec.tsindex c49613342..8ae02221d 100644--- a/ui/e2e/workbench-general/sidebar-floating.spec.ts+++ b/ui/e2e/workbench-general/sidebar-floating.spec.ts@@ -22,7 +22,7 @@ async function serveProduct(page: Page, lang: Lang = 'en') {const inheritedReads = new Set(['/api/session', '/api/config', '/api/csrf-token', '/api/projects','/api/workbench/projects-bootstrap', '/api/sessions', '/api/agents',- '/api/inbox', '/api/version', '/api/events',+ '/api/inbox', '/api/version', '/api/events', '/api/macos/login-session','/api/desktop/computer-use/status',]);await page.route('**/api/**', (route) => {@@ -38,6 +38,7 @@ async function serveProduct(page: Page, lang: Lang = 'en') {if (path === '/api/dock') return route.fulfill({ json: {dock: { order: ['files', 'terminal', 'editor', 'library'], pins: [] },} });+ if (path === '/api/macos/login-session') return route.fulfill({ json: { ok: true, state: 'healthy' } });if (inheritedReads.has(path)) return route.fallback();audit.unknown.push(`${request.method()} ${request.url()}`);return route.abort();diff --git a/ui/src/components/AppShell.test.tsx b/ui/src/components/AppShell.test.tsxindex aa80ea012..d1034ba26 100644--- a/ui/src/components/AppShell.test.tsx+++ b/ui/src/components/AppShell.test.tsx@@ -49,6 +49,7 @@ const viewport = vi.hoisted(() => {const api = vi.hoisted(() => ({getConfig: vi.fn(),getVersion: vi.fn(),+ getMacOSLoginSessionStatus: vi.fn(),}));const status = vi.hoisted(() => ({ state: 'ready' as const }));const inbox = vi.hoisted(() => ({ totalUnread: 0 }));@@ -207,6 +208,7 @@ beforeEach(() => {i18n = makeI18n();api.getConfig.mockResolvedValue({ platforms: { enabled: [] } });api.getVersion.mockResolvedValue({ version: 'test' });+ api.getMacOSLoginSessionStatus.mockResolvedValue({ ok: true, state: 'healthy' });});afterEach(() => {@@ -215,6 +217,87 @@ afterEach(() => {vi.clearAllMocks();});+describe('AppShell stale login session notice', () => {+ it('shows the restart instruction when the service outlived the macOS login session', async () => {+ api.getMacOSLoginSessionStatus.mockResolvedValue({ ok: true, state: 'stale_login_session' });++ render(+ <MemoryRouter initialEntries={['/']}>+ <Routes>+ <Route element={<AppShell />}>+ <Route path="/" element={<div>workbench</div>} />+ </Route>+ </Routes>+ </MemoryRouter>,+ );++ await waitFor(() => expect(screen.getByRole('alert').textContent).toContain('errors.stale_login_session'));+ });++ it('reserves notice space on full-height app surfaces', async () => {+ api.getMacOSLoginSessionStatus.mockResolvedValue({ ok: true, state: 'stale_login_session' });++ render(+ <MemoryRouter initialEntries={['/apps/terminal']}>+ <Routes>+ <Route element={<AppShell />}>+ <Route path="/apps/terminal" element={<div data-testid="terminal-surface" />} />+ </Route>+ </Routes>+ </MemoryRouter>,+ );++ await screen.findByRole('alert');+ expect(document.querySelector('main')?.className).toContain('flex-col');+ expect(screen.getByTestId('terminal-surface').parentElement?.className).toContain('min-h-0 flex-1 p-0');+ });+ it('keeps the notice above mobile chat surfaces', async () => {+ api.getMacOSLoginSessionStatus.mockResolvedValue({ ok: true, state: 'stale_login_session' });++ render(+ <MemoryRouter initialEntries={['/chat/session-2']}>+ <Routes>+ <Route element={<AppShell />}>+ <Route path="/chat/:sessionId" element={<div data-testid="chat-surface" />} />+ </Route>+ </Routes>+ </MemoryRouter>,+ );++ const notice = await screen.findByRole('alert');+ expect(notice.className).toContain('fixed inset-x-0 top-0 z-50');+ expect(screen.getByTestId('chat-surface')).toBeTruthy();+ });++ it('rechecks the state while the Workbench stays visible', async () => {+ Object.defineProperty(document, 'visibilityState', { configurable: true, value: 'visible' });+ const intervalSpy = vi.spyOn(window, 'setInterval').mockImplementation((callback) => {+ void Promise.resolve().then(() => (callback as () => void)());+ return 1;+ });+ api.getMacOSLoginSessionStatus+ .mockResolvedValueOnce({ ok: true, state: 'healthy' })+ .mockResolvedValueOnce({ ok: true, state: 'stale_login_session' });++ try {+ render(+ <MemoryRouter initialEntries={['/']}>+ <Routes>+ <Route element={<AppShell />}>+ <Route path="/" element={<div>workbench</div>} />+ </Route>+ </Routes>+ </MemoryRouter>,+ );+ await waitFor(() => expect(api.getMacOSLoginSessionStatus).toHaveBeenCalledTimes(1));+ await waitFor(() => expect(api.getMacOSLoginSessionStatus).toHaveBeenCalledTimes(2));+ await waitFor(() => expect(screen.getByRole('alert')).toBeTruthy());+ } finally {+ intervalSpy.mockRestore();+ }+ });+});+describe('AppShell setup access', () => {it.each([{ remote: false, instanceKind: 'personal' as const },@@ -906,7 +989,7 @@ describe('AppShell remote Apps access', () => {const surface = await screen.findByTestId('show-page-surface');expect(screen.queryByRole('banner')).toBeNull();expect(document.querySelector('nav.fixed.inset-x-0.bottom-0')).toBeNull();- expect(surface.parentElement?.className).toContain('h-full p-0');+ expect(surface.parentElement?.className).toContain('min-h-0 flex-1 p-0');expect(surface.parentElement?.className).not.toContain('px-4 py-5');});@@ -924,10 +1007,27 @@ describe('AppShell remote Apps access', () => {const surface = await screen.findByTestId('builtin-app-surface');expect(screen.queryByRole('banner')).toBeNull();expect(document.querySelector('nav.fixed.inset-x-0.bottom-0')).toBeNull();- expect(surface.parentElement?.className).toContain('h-full p-0');+ expect(surface.parentElement?.className).toContain('min-h-0 flex-1 p-0');expect(surface.parentElement?.className).not.toContain('px-4 py-5');});+ it('keeps the sidebar offset for desktop embedded apps', async () => {+ viewport.isDesktop = true;+ render(+ <MemoryRouter initialEntries={['/apps/terminal']}>+ <Routes>+ <Route element={<AppShell />}>+ <Route path="/apps/terminal" element={<div data-testid="desktop-terminal-surface" />} />+ </Route>+ </Routes>+ </MemoryRouter>,+ );++ const surface = await screen.findByTestId('desktop-terminal-surface');+ expect(document.querySelector('main')?.className).toContain('md:ml-[var(--app-sidebar-w)]');+ expect(surface.parentElement?.className).toContain('md:px-10 md:py-8');+ });+it.each([['owner', true],['member', false],diff --git a/ui/src/components/AppShell.tsx b/ui/src/components/AppShell.tsxindex 927265d9a..9c6875b43 100644--- a/ui/src/components/AppShell.tsx+++ b/ui/src/components/AppShell.tsx@@ -1,7 +1,7 @@import { DesktopDragRegion } from './DesktopDragRegion';import { DesktopWindowChrome } from './DesktopWindowChrome';import { desktopDragRegion } from '../lib/desktopShell';-import React, { useCallback, useEffect, useRef, useState } from 'react';+import React, { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react';import { Link, Navigate, NavLink, Outlet, useLocation, useNavigate } from 'react-router-dom';import { AlertTriangle, FolderTree, Grid2x2, Inbox, LayoutGrid, Plus, Settings } from 'lucide-react';import { useTranslation } from 'react-i18next';@@ -33,6 +33,7 @@ import logoImg from '../assets/logo.png';import { useViewportHeightVar } from '../lib/useViewportHeightVar';import { APP_SHELL_SCROLL_ID, forgetMobileProjectsListUnlessPreserved } from '../lib/mobileProjectsListMemory';import { useIsDesktop } from '../lib/useIsDesktop';+import { onPageReactivated } from '../lib/pageActivity';import { adoptPersistedLanguage } from '../lib/useLanguageSelection';import { isOwnerOnlyPath } from '../lib/adminNavigation';import { useSettingsResumePath } from '../lib/settingsSectionMemory';@@ -90,6 +91,69 @@ const MobileNavLink: React.FC<{ item: ShellNavItem }> = ({ item }) => {type CenterButton = { label: string; icon: React.ComponentType<{ className?: string }>; to?: string; onClick?: () => void };+const MACOS_SESSION_NOTICE_REFRESH_MS = 30_000;+const MACOS_SESSION_NOTICE_HEIGHT_VAR = '--macos-stale-login-session-notice-h';++const MacOSStaleLoginSessionNotice: React.FC<{ overlay?: boolean }> = ({ overlay = false }) => {+ const { t } = useTranslation();+ const api = useApi();+ const [stale, setStale] = useState(false);++ useEffect(() => {+ let active = true;+ const read = () => {+ if (document.visibilityState !== 'visible') return;+ void api.getMacOSLoginSessionStatus().then((result) => {+ if (active) setStale(result.state === 'stale_login_session');+ }).catch(() => {+ // A diagnostic notice must not make the Workbench unavailable.+ });+ };+ read();+ const interval = window.setInterval(read, MACOS_SESSION_NOTICE_REFRESH_MS);+ const stopReactivation = onPageReactivated(read);+ return () => {+ active = false;+ window.clearInterval(interval);+ stopReactivation();+ };+ }, [api]);++ const noticeRef = useRef<HTMLDivElement>(null);++ useLayoutEffect(() => {+ const notice = noticeRef.current;+ const main = notice?.closest('main');+ if (!overlay || !stale || !notice || !main) return undefined;++ const updateHeight = () => {+ main.style.setProperty(MACOS_SESSION_NOTICE_HEIGHT_VAR, `${notice.getBoundingClientRect().height}px`);+ };+ updateHeight();+ const observer = typeof ResizeObserver === 'undefined' ? null : new ResizeObserver(updateHeight);+ observer?.observe(notice);+ return () => {+ observer?.disconnect();+ main.style.removeProperty(MACOS_SESSION_NOTICE_HEIGHT_VAR);+ };+ }, [overlay, stale]);++ if (!stale) return null;+ return (+ <div+ ref={noticeRef}+ role="alert"+ className={clsx(+ 'shrink-0 mx-4 mb-4 flex items-start gap-3 rounded-xl border border-destructive/35 bg-destructive/8 px-4 py-3 text-[13px] leading-snug text-destructive-ink md:mx-10',+ overlay && 'fixed inset-x-0 top-0 z-50 m-0 rounded-none border-x-0 border-t-0 px-4 pb-3 pt-[calc(0.75rem+env(safe-area-inset-top))] md:hidden',+ )}+ >+ <AlertTriangle className="mt-0.5 size-4 shrink-0" />+ <span>{t('errors.stale_login_session')}</span>+ </div>+ );+};+// Workbench mobile tabs flank a raised new-session action.const MobileTabBar: React.FC<{ items: ShellNavItem[]; center?: CenterButton }> = ({ items, center }) => {// No center action means a plain even row of tabs.@@ -419,6 +483,7 @@ export const AppShell: React.FC = () => {const isSettings = settingsOpen;const isShowPageApp = surfaceLocation.pathname.startsWith('/apps/show/');const isBuiltinApp = isStandaloneAppRoutePath(surfaceLocation.pathname);+ const isFullHeightApp = chromeless || isBuiltinApp || isShowPageApp;const isFullScreenMobile = isChat || isSearch || isSettings || isShowPageApp || isBuiltinApp;// `/` is the Workbench canvas root and the only route board 04 draws. It reads// the surface location, so Settings opened over the home keeps the home's own@@ -595,10 +660,11 @@ export const AppShell: React.FC = () => {// Mobile: the internal scroll area of the locked flex-column shell, so// the document itself never scrolls. Desktop: normal flow (min-h-screen// + sidebar offset).- chromeless- // Single-app tab: no sidebar offset, no scroll, no page glow — the app body- // is the only thing in the viewport and sizes itself to this box (h-full).- ? 'min-h-0 flex-1 overflow-hidden'+ isFullHeightApp+ ? clsx(+ 'min-h-0 flex flex-1 flex-col overflow-hidden',+ !chromeless && 'md:ml-[var(--app-sidebar-w)] md:min-h-screen md:flex-none md:overflow-visible md:pb-0',+ ): settingsCoversSidebar? 'min-h-0 flex-1 overflow-hidden md:min-h-screen md:flex-none md:overflow-visible md:pb-0': isFullScreenMobile@@ -618,10 +684,11 @@ export const AppShell: React.FC = () => {))}>+ <MacOSStaleLoginSessionNotice overlay={(isChat || isSearch) && !isDesktop} /><div className={clsx('w-full',- chromeless- ? 'h-full'+ isFullHeightApp+ ? clsx('min-h-0 flex-1 p-0', !chromeless && 'md:mx-auto md:h-auto md:px-10 md:py-8'): isSettings? 'h-full p-0 md:h-auto md:min-h-screen': isFullScreenMobilediff --git a/ui/src/components/settings/SettingsDependenciesPage.tsx b/ui/src/components/settings/SettingsDependenciesPage.tsxindex ada671e24..259b4be96 100644--- a/ui/src/components/settings/SettingsDependenciesPage.tsx+++ b/ui/src/components/settings/SettingsDependenciesPage.tsx@@ -3,6 +3,7 @@ import { Link } from 'react-router-dom';import { useTranslation } from 'react-i18next';import {ArrowUpRight,+ AlertTriangle,Download,Hexagon,KeyRound,@@ -57,7 +58,7 @@ export const SettingsDependenciesPage: React.FC = () => {const api = useApi();const { showToast } = useToast();- const { checks, refresh: refreshDependencies, checking } = useDependencyChecks(api.listDependencies);+ const { checks, refresh: refreshDependencies, checking, loginSessionState } = useDependencyChecks(api.listDependencies);const [busy, setBusy] = useState<string | null>(null);useEffect(() => { void refreshDependencies(); }, [refreshDependencies]);// A closed backend reason/message is often a snake_case token rather than human copy. Localize any@@ -153,6 +154,13 @@ export const SettingsDependenciesPage: React.FC = () => {<span className="text-[13px] leading-snug text-foreground">{t('settings.dependencies.autoBanner')}</span></div>+ {loginSessionState === 'stale_login_session' && (+ <div role="alert" className="flex items-start gap-3 rounded-xl border border-destructive/35 bg-destructive/8 px-5 py-3.5 text-[13px] leading-snug text-destructive-ink">+ <AlertTriangle className="mt-0.5 size-4 shrink-0" />+ <span>{t('errors.stale_login_session')}</span>+ </div>+ )}+{Object.entries(DEP_META).map(([id, meta]) => {const check = checks[id];const d = check.data;diff --git a/ui/src/components/settings/useDependencyChecks.ts b/ui/src/components/settings/useDependencyChecks.tsindex 0b73bc281..b2d22292d 100644--- a/ui/src/components/settings/useDependencyChecks.ts+++ b/ui/src/components/settings/useDependencyChecks.ts@@ -30,6 +30,7 @@ export function useDependencyChecks(read: ReadDependencies) {])),));const requests = useRef(new Map<string, AbortController>());+ const [loginSessionState, setLoginSessionState] = useState<DependenciesResult['login_session_state']>(undefined);const timers = useRef(new Map<string, ReturnType<typeof setTimeout>>());useEffect(() => {@@ -66,6 +67,7 @@ export function useDependencyChecks(read: ReadDependencies) {if (!result.ok || !Array.isArray(result.deps) || ids.some((id) => !result.deps.some((dep) => dep.id === id))) {throw new Error('Incomplete dependency inspection');}+ setLoginSessionState(result.login_session_state);const byId = new Map(result.deps.map((dep) => [dep.id, dep]));update((_previous, id) => ({data: byId.get(id)!, checking: false, error: null,@@ -87,5 +89,5 @@ export function useDependencyChecks(read: ReadDependencies) {}));}, [read]);- return { checks, refresh, checking: Object.values(checks).some((check) => check.checking) };+ return { checks, refresh, checking: Object.values(checks).some((check) => check.checking), loginSessionState };}diff --git a/ui/src/components/ui/avault-authorization-notice.tsx b/ui/src/components/ui/avault-authorization-notice.tsxindex cb7d1a365..70bd111d6 100644--- a/ui/src/components/ui/avault-authorization-notice.tsx+++ b/ui/src/components/ui/avault-authorization-notice.tsx@@ -21,7 +21,17 @@ export function AvaultAuthorizationNotice({ forceVisible = false, className }: {const attempt = status?.attempt ?? null;const running = attempt?.state === 'running';const outcome = requested && !running ? attempt : null;- if (!forceVisible && !status?.required && !running && !outcome) return null;+ const staleLoginSession = status?.login_session_state === 'stale_login_session';+ if (!forceVisible && !status?.required && !running && !outcome && !staleLoginSession) return null;++ if (staleLoginSession) {+ return (+ <div role="alert" className={cn('flex items-start gap-2.5 rounded-xl border border-destructive/35 bg-destructive/8 px-4 py-3 text-sm', className)}>+ <KeyRound className="mt-0.5 size-4 shrink-0 text-destructive-ink" />+ <span className="leading-snug text-destructive-ink">{t('errors.stale_login_session')}</span>+ </div>+ );+ }const onAuthorize = () => {setRequested(true);diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsxindex 71f19bfde..7010baead 100644--- a/ui/src/components/workbench/ChatPage.tsx+++ b/ui/src/components/workbench/ChatPage.tsx@@ -2909,7 +2909,7 @@ export const ChatPage: React.FC = () => {<divref={chatSurfaceRef}style={windowChrome ? { paddingTop: '48px' } : undefined}- className="fixed inset-0 z-40 flex flex-col bg-background pt-[env(safe-area-inset-top)] md:relative md:inset-auto md:z-auto md:-mx-10 md:-my-8 md:h-[var(--app-vvh)] md:bg-transparent md:pt-0"+ className="fixed inset-x-0 bottom-0 top-[var(--macos-stale-login-session-notice-h,0px)] z-40 flex flex-col bg-background pt-[env(safe-area-inset-top)] md:relative md:inset-auto md:z-auto md:-mx-10 md:-my-8 md:h-[var(--app-vvh)] md:bg-transparent md:pt-0"onKeyDown={annotation.handleShortcutKeyDown}onPointerDownCapture={focusCanvas}{...fileDropHandlers}diff --git a/ui/src/components/workbench/SearchPage.tsx b/ui/src/components/workbench/SearchPage.tsxindex f8781b96f..0c2534d02 100644--- a/ui/src/components/workbench/SearchPage.tsx+++ b/ui/src/components/workbench/SearchPage.tsx@@ -101,7 +101,7 @@ export const SearchPage: React.FC = () => {// Full-screen focused surface (like ChatPage): fixed over the shell, its own// header is the top of the screen, and it scrolls internally. Desktop never// routes here (sidebar field + ⌘K own search), but keep it sane if hit.- <div className="fixed inset-0 z-40 flex flex-col bg-background pt-[env(safe-area-inset-top)] md:absolute">+ <div className="fixed inset-x-0 bottom-0 top-[var(--macos-stale-login-session-notice-h,0px)] z-40 flex flex-col bg-background pt-[env(safe-area-inset-top)] md:absolute">{/* Header — back chevron + active search field (design.pen P6Nsz/KmsNV). */}<header data-tauri-drag-region={desktopDragRegion()} className="flex shrink-0 items-center gap-2.5 border-b border-border bg-background/92 px-4 py-3 backdrop-blur"><Buttondiff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsxindex ede2a12bf..15c15f3a8 100644--- a/ui/src/context/ApiContext.tsx+++ b/ui/src/context/ApiContext.tsx@@ -609,6 +609,7 @@ export type ApiContextType = {detectCli: (binary: string, backend?: string) => Promise<CliDetectionResult>;installAgent: (name: string) => Promise<InstallResult>;listDependencies: (options?: DependencyReadOptions) => Promise<DependenciesResult>;+ getMacOSLoginSessionStatus: () => Promise<MacOSLoginSessionStatus>;installDependency: (dep: string) => Promise<InstallResult>;getBackendConnection: (name: AgentBackendId) => Promise<BackendConnectionState>;getBackendRuntime: (name: string, cliPath?: string) => Promise<BackendRuntimeInfo>;@@ -1995,11 +1996,18 @@ export type AvaultAuthorizationStatus = {required: boolean;detected_at: string | null;attempt: AvaultAuthorizationAttempt | null;+ login_session_state?: MacOSLoginSessionStatus['state'];+};++export type MacOSLoginSessionStatus = {+ ok: boolean;+ state: 'healthy' | 'stale_login_session' | 'no_gui_session' | 'unknown' | 'not_applicable';};export type DependenciesResult = {ok: boolean;deps: DependencyItem[];+ login_session_state?: MacOSLoginSessionStatus['state'];reconciling?: boolean;reconciling_dependencies?: string[];};@@ -3622,6 +3630,7 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ childrenconst path = `/api/dependencies${query ? `?${query}` : ''}`;return withApiDeadline(15_000, signal, (requestSignal) => getJson(path, { signal: requestSignal }));},+ getMacOSLoginSessionStatus: () => getJson('/api/macos/login-session'),installDependency: (dep) => startAndPollDependencyInstall(dep),getBackendConnection: (name) => getJson(`/api/backend/${encodeURIComponent(name)}/connection`),getBackendRuntime: (name, cliPath) => getJson(`/api/backend/${encodeURIComponent(name)}/runtime${cliPath === undefined ? '' : `?cli_path=${encodeURIComponent(cliPath)}`}`),diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex ff3f0ce3d..838661c4d 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -2849,6 +2849,7 @@},"errors": {"avault_authorization_required": "avault needs a one-time macOS Keychain authorization on the Mac running Avibe. Choose Authorize avault, then answer the dialog on that Mac.",+ "stale_login_session": "Avibe is still running in a macOS login session that has ended. Open Terminal on the Mac's current desktop, run `vibe restart`, then try again. Do not retry this operation.","invalid_field_name": "Use 1–64 lowercase letters, digits or underscores for field names, starting with a letter.","cache_ttl_unsupported": "That cache lifetime is not supported by this route. Use the built-in estimate or a provider-compatible value.","field_exists": "A field with this name already exists. Choose a different name.",diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex a5373da13..90610b163 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -2849,6 +2849,7 @@},"errors": {"avault_authorization_required": "avault 需要在运行 Avibe 的 Mac 上完成一次性的 macOS 钥匙串授权。请选择「授权 avault」,然后在那台 Mac 上回应对话框。",+ "stale_login_session": "Avibe 仍运行在一个已经结束的 macOS 登录会话中。请在 Mac 当前桌面的终端运行 `vibe restart`,然后重试。请不要重复重试此操作。","invalid_field_name": "字段名须为 1–64 个小写字母、数字或下划线,且以字母开头。","cache_ttl_unsupported": "此路由不支持该缓存时长。请使用内置估计或符合供应商能力的值。","field_exists": "此字段名已存在,请使用其他名称。",diff --git a/vibe/api.py b/vibe/api.pyindex 2493aeaf3..7fb7fcf77 100644--- a/vibe/api.py+++ b/vibe/api.py@@ -2527,6 +2527,12 @@ def _notify_vault_request_created(request: dict | None) -> None:def _vault_api_error_from_avault(exc: "AvaultError", *, prefix: str) -> VaultApiError:+ if isinstance(exc, AvaultStaleLoginSessionError):+ return VaultApiError(+ backend_t("errors.staleLoginSession"),+ code=exc.code,+ status=409,+ )message = str(exc)if isinstance(exc, AvaultAuthorizationRequiredError):return VaultApiError(f"{prefix}: {message}", code=exc.code, status=409)@@ -9429,6 +9435,16 @@ class AvaultPreHandoffError(AvaultError):"""avault failed before receiving an envelope or performing delivery."""+class AvaultStaleLoginSessionError(AvaultError):+ """The Avibe process outlived the macOS login session that owns its user services."""++ code = "stale_login_session"+++class AvaultStaleLoginSessionBeforeHandoffError(AvaultStaleLoginSessionError, AvaultPreHandoffError):+ """The stale-session check stopped a Vault operation before any handoff."""++class AvaultAuthorizationRequiredError(AvaultError):"""macOS Keychain has not yet approved this avault binary for the master key.@@ -9532,6 +9548,13 @@ def _run_avault(raise AvaultPreHandoffError("avault binary not found") from excexcept subprocess.TimeoutExpired as exc:raise AvaultError("avault timed out") from exc+ if proc.returncode != 0 and macos_login_session_state() == "stale_login_session":+ error = (+ AvaultStaleLoginSessionBeforeHandoffError+ if proc.returncode == _AVAULT_EXIT_AUTHORIZATION_REQUIRED+ else AvaultStaleLoginSessionError+ )+ raise error(backend_t("errors.staleLoginSession"))if proc.returncode == _AVAULT_EXIT_AUTHORIZATION_REQUIRED:raise _avault_authorization_required(_avault_detail(proc))if proc.returncode == 0:@@ -9543,6 +9566,15 @@ def _raise_if_agent_authorization_required(exc: Exception) -> None:"""Re-raise a resident-agent ``keychain_authorization_required`` frame as Avibe's error."""from vibe.avault_agent import AvaultAgentAuthorizationRequiredError+ if isinstance(exc, AvaultStaleLoginSessionError):+ raise+ if macos_login_session_state() == "stale_login_session":+ error = (+ AvaultStaleLoginSessionBeforeHandoffError+ if isinstance(exc, AvaultAgentAuthorizationRequiredError) or _avault_agent_error_is_absent(str(exc))+ else AvaultStaleLoginSessionError+ )+ raise error(backend_t("errors.staleLoginSession")) from excif isinstance(exc, AvaultAgentAuthorizationRequiredError):raise _avault_authorization_required(str(exc)) from exc@@ -9710,6 +9742,8 @@ def avault_deliver_run(secrets: list[dict], command: list[str]) -> dict:status, so it is raised as ``AvaultAuthorizationRequiredError`` (stillfail-closed) only when ``_deliver_run_needed_authorization`` confirms it."""+ if macos_login_session_state() == "stale_login_session":+ raise AvaultStaleLoginSessionBeforeHandoffError(backend_t("errors.staleLoginSession"))path = _require_avault_path()payload = json.dumps([@@ -10062,7 +10096,8 @@ def avault_key_authorize() -> dict:Returns ``{"ok", "reason", "detail"?}``. ``reason`` is ``authorized``,``not_applicable`` (no Keychain off macOS), ``avault_missing``,- ``avault_upgrade_required``, ``timed_out``, ``no_gui_session`` (this process+ ``avault_upgrade_required``, ``timed_out``, ``stale_login_session`` (the+ process outlived its macOS login session), ``no_gui_session`` (this processprovably cannot show the dialog), or ``not_completed`` (denied, cancelled,still cooling down, or failed; avault's own ``detail`` says which)."""@@ -10090,29 +10125,60 @@ def avault_key_authorize() -> dict:avault_authorization.clear_authorization_required()return {"ok": True, "reason": "authorized"}# avault exits 70 for a deny, a cancel, the cooldown after one, and a session- # that cannot show the dialog alike; tell the last apart from this process's- # own login session instead of parsing avault's text.- result = {"ok": False, "reason": "no_gui_session" if _process_cannot_show_macos_dialogs() else "not_completed"}+ # that cannot show the dialog alike; classify the process's own session first.+ session_state = macos_login_session_state()+ if session_state == "stale_login_session":+ result = {"ok": False, "reason": session_state}+ elif session_state == "no_gui_session" or _process_cannot_show_macos_dialogs():+ result = {"ok": False, "reason": "no_gui_session"}+ else:+ result = {"ok": False, "reason": "not_completed"}detail = _avault_detail(proc)- if detail:+ if detail and result["reason"] != "stale_login_session":result["detail"] = detail[-_AVAULT_AUTHORIZE_DETAIL_LIMIT:]return result+def macos_login_session_state(*, service_pid: int | None = None) -> str:+ """Return the redacted login-session state for this process or a target service."""+ if platform.system() != "Darwin":+ return "not_applicable"+ try:+ from vibe.macos_session_diagnostics import MacOSSessionProbe, login_session_state++ target = service_pid is not None and service_pid != os.getpid()+ if target:+ try:+ from vibe.internal_client import health_identity_sync++ service_state = (health_identity_sync() or {}).get("macos_login_session_state")+ if service_state in {"healthy", "stale_login_session", "no_gui_session", "unknown"}:+ return service_state+ except Exception: # noqa: BLE001 - diagnostics must never block a Vault call+ pass+ context = MacOSSessionProbe(+ service_pid=service_pid,+ service_pid_is_target=target,+ ).capture_context()+ return login_session_state(context)+ except Exception: # noqa: BLE001 - diagnostics must never block a Vault call+ return "unknown"+++def get_macos_login_session_status() -> dict:+ """Expose only the actionable login-session state to Web/remote surfaces."""+ state = macos_login_session_state()+ return {"ok": True, "state": state}++def _process_cannot_show_macos_dialogs() -> bool:"""True only when this process provably runs outside the logged-in desktop session.- A process started over SSH, or with nobody logged in at the desktop, has no- window server to show the Keychain dialog on. An inconclusive probe is not- proof, so it reads as False.+ The result distinguishes an ended login session from a normal headless or+ SSH-launched process so the user receives the only recovery that can work."""- try:- from vibe.macos_session_diagnostics import MacOSSessionProbe-- context = MacOSSessionProbe().capture_context()- except Exception: # noqa: BLE001 - a diagnostic only refines the message- return False- return context.gui_domain_available is False or context.asid_match is False+ state = macos_login_session_state()+ return state in {"stale_login_session", "no_gui_session"}def get_avault_authorization_status() -> dict:@@ -10123,6 +10189,7 @@ def get_avault_authorization_status() -> dict:"required": record is not None,"detected_at": record.get("detected_at") if record else None,"attempt": avault_authorization.current_attempt(),+ "login_session_state": macos_login_session_state(),}@@ -10574,6 +10641,7 @@ def dependencies_status(*, offline: bool = False, dependency_ids: list[str] | Noor generation_before != generation_after),"reconciling_dependencies": sorted(active_before | active_after),+ "login_session_state": macos_login_session_state(),}diff --git a/vibe/authorization.py b/vibe/authorization.pyindex acf73df58..6a7ebe1ab 100644--- a/vibe/authorization.py+++ b/vibe/authorization.py@@ -573,6 +573,7 @@ _MEMBER_HTTP_RULES = tuple(("PUT", r"^/api/projects/[^/]+/agents-md$"),# General instance settings; mixed writes retain access-administration guards.("GET", r"^/api/doctor$"),+ ("GET", r"^/api/macos/login-session$"),("PUT", r"^/api/workbench/prefs$"),("GET", r"^/api/cli/detect$"),("GET", r"^/api/slack/manifest$"),diff --git a/vibe/cli.py b/vibe/cli.pyindex efcee9371..54bf4bd43 100644--- a/vibe/cli.py+++ b/vibe/cli.py@@ -449,9 +449,26 @@ def _retyped_placement_refusal(return exc+STALE_LOGIN_SESSION_CODE = "stale_login_session"AVAULT_AUTHORIZATION_REQUIRED_CODE = "avault_authorization_required"+def _is_stale_login_session(exc: Exception) -> bool:+ return getattr(exc, "code", None) == STALE_LOGIN_SESSION_CODE+++def _stale_login_session_cli_error(help_command: str | None) -> TaskCliError:+ return TaskCliError(+ "Avibe is still running in a macOS login session that has ended",+ code=STALE_LOGIN_SESSION_CODE,+ hint=(+ "Do not retry. Ask the user to open Terminal on the Mac's current desktop, run `vibe restart`, "+ "then try again from Avibe."+ ),+ help_command=help_command,+ )++def _is_avault_authorization_required(exc: Exception) -> bool:return getattr(exc, "code", None) == AVAULT_AUTHORIZATION_REQUIRED_CODE@@ -477,7 +494,9 @@ def _avault_authorization_required_cli_error(help_command: str | None) -> TaskCldef _avault_cli_error(exc: Exception, message: str, *, code: str = "avault_failed", help_command: str | None = None) -> TaskCliError:- if _is_avault_authorization_required(exc):+ if _is_stale_login_session(exc):+ code = STALE_LOGIN_SESSION_CODE+ elif _is_avault_authorization_required(exc):code = AVAULT_AUTHORIZATION_REQUIRED_CODEreturn TaskCliError(message, code=code, help_command=help_command)@@ -493,7 +512,9 @@ def _print_task_error(exc: Exception, *, help_command: str | None = None) -> Non# payload builder below.if isinstance(exc, UnresolvableSessionTarget) and exc.reason == "reserved":exc = _reserved_session_cli_error(exc)- if _is_avault_authorization_required(exc):+ if _is_stale_login_session(exc):+ exc = _stale_login_session_cli_error(getattr(exc, "help_command", None) or help_command)+ elif _is_avault_authorization_required(exc):exc = _avault_authorization_required_cli_error(getattr(exc, "help_command", None) or help_command)from storage.resource_access_service import (HARNESS_ACCESS_FORBIDDEN_CODE,@@ -10848,6 +10869,11 @@ def cmd_vault_inject(args):# (code, message, hint) for each ``api.avault_key_authorize`` failure reason._AVAULT_AUTHORIZE_FAILURES = {+ "stale_login_session": (+ "stale_login_session",+ "Avibe is still running in a macOS login session that has ended",+ "Do not retry. Open Terminal on the Mac's current desktop, run `vibe restart`, then try again from Avibe.",+ ),"not_completed": ("avault_authorization_not_completed","avault authorization did not complete",@@ -12272,6 +12298,44 @@ def _show_runtime_doctor_items(*, language: str = "en", deep: bool = False) -> lreturn items+def _macos_login_session_doctor_items(*, language: str = "en") -> list[dict]:+ if platform.system() != "Darwin":+ return []+ owner_pid = runtime.resolve_service_owner_pid(include_starting=False)+ if owner_pid:+ state = api.macos_login_session_state(service_pid=owner_pid)+ else:+ return [{+ "status": "pass",+ "code": "login_session_local_fallback",+ "message": i18n_t("doctor.item.loginSessionLocalFallback", language),+ }]+ if state == "stale_login_session":+ return [{+ "status": "fail",+ "code": "stale_login_session",+ "message": i18n_t("doctor.item.staleLoginSession", language),+ "action": i18n_t("doctor.action.staleLoginSession", language),+ }]+ if state == "no_gui_session":+ return [{+ "status": "pass",+ "code": "no_gui_session",+ "message": i18n_t("doctor.item.noGuiSession", language),+ }]+ if state == "unknown":+ return [{+ "status": "warn",+ "code": "login_session_unknown",+ "message": i18n_t("doctor.item.loginSessionUnknown", language),+ }]+ return [{+ "status": "pass",+ "code": "login_session_healthy",+ "message": i18n_t("doctor.item.loginSessionHealthy", language),+ }]++def _doctor(*, deep: bool = False, language: str = "en"):"""Run diagnostic checks and return results in UI-compatible format.@@ -12648,6 +12712,7 @@ def _doctor(*, deep: bool = False, language: str = "en"):*_service_generation_items(language=language),*_restart_state_items(language=language),*_runtime_architecture_items(language=language),+ *_macos_login_session_doctor_items(language=language),*_show_git_checkpoint_items(language=language),*_scheduled_task_weekday_items(language=language),]:diff --git a/vibe/i18n/en.json b/vibe/i18n/en.jsonindex 741b9c008..7415c1477 100644--- a/vibe/i18n/en.json+++ b/vibe/i18n/en.json@@ -6,6 +6,7 @@},"errors": {"agentModelRequired": "Select a model for the {backend} Agent or Session in Avibe before running it.",+ "staleLoginSession": "Avibe is still running in a macOS login session that has ended. Open Terminal on the Mac's current desktop, run `vibe restart`, then try again. Do not retry this operation.","modelHubDisabled": "Model Hub is disabled on this instance, so {backend} has no model to run on.","modelGatewayOff": "The model gateway is off, so {backend} has no model to run on. Open Models and click Retry, then choose a model.","modelSourceRequired": "{backend} has no model source yet. Add an API key or a subscription in Models.",@@ -1375,6 +1376,11 @@"cliPath": "PATH resolves vibe to {path}","splitLaunchers": "Stable vibe launchers select different installs: {launchers}","launchersInStep": "{count} stable vibe launchers select Avibe {version}",+ "loginSessionHealthy": "The Avibe service is running in the current macOS login session",+ "loginSessionLocalFallback": "No running Avibe service was found; macOS login-session status was not used as service health",+ "loginSessionUnknown": "The macOS login session could not be verified",+ "noGuiSession": "No desktop GUI session is available; this is expected for headless or SSH use",+ "staleLoginSession": "Avibe is still running in a macOS login session that has ended","serviceGenerationBehind": "The running service is Avibe {version} ({generation}), older than the last activated install {activatedVersion} ({activatedGeneration})","cliNotUvTool": "Active vibe executable is not the uv tool installation","cliEditable": "uv tool installation is editable: {path}",@@ -1461,6 +1467,7 @@"cliPathPrecedence": "Put ~/.local/bin before system Python bin directories when using the uv tool installation.","splitLaunchers": "Run `{repairCommand}` to point every launcher at Avibe {version}.","splitLaunchersTied": "These installs tie as the last activation, so the repair cannot choose one: {launchers}. Run the Avibe installer again; its new install moves every launcher.",+ "staleLoginSession": "Open Terminal on the Mac's current desktop and run `vibe restart`, then try again from Avibe. Do not retry the failed operation.","serviceGenerationBehind": "Run `{restartCommand}` to run the last activated install.","cliNotUvTool": "uv tool package-integrity checks are skipped for this executable.","cliEditable": "Reinstall Avibe from a normal wheel. Do not use 'uv tool install --editable .' for the live local CLI.",diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.jsonindex 3acb4db91..f6f29eaaa 100644--- a/vibe/i18n/zh.json+++ b/vibe/i18n/zh.json@@ -6,6 +6,7 @@},"errors": {"agentModelRequired": "请先在 Avibe 中为 {backend} Agent 或会话选择模型。",+ "staleLoginSession": "Avibe 仍运行在一个已经结束的 macOS 登录会话中。请在 Mac 当前桌面的终端运行 `vibe restart`,然后重试。请不要重复重试此操作。","modelHubDisabled": "本实例已停用模型网关,{backend} 没有可用的模型。","modelGatewayOff": "模型网关已关闭,{backend} 没有可用的模型。请前往「模型」页点击「重试」,然后选择模型。","modelSourceRequired": "{backend} 还没有模型来源。请在「模型」页添加 API Key 或订阅。",@@ -1375,6 +1376,11 @@"cliPath": "PATH 解析到 vibe:{path}","splitLaunchers": "稳定 vibe 启动器指向了不同的安装:{launchers}","launchersInStep": "{count} 个稳定 vibe 启动器都指向 Avibe {version}",+ "loginSessionHealthy": "Avibe 服务运行在当前 macOS 登录会话中",+ "loginSessionLocalFallback": "未发现正在运行的 Avibe 服务;未将 macOS 登录会话状态作为服务健康状态",+ "loginSessionUnknown": "无法验证 macOS 登录会话",+ "noGuiSession": "没有可用的桌面 GUI 会话;无头或 SSH 使用属于正常情况",+ "staleLoginSession": "Avibe 仍运行在一个已经结束的 macOS 登录会话中","serviceGenerationBehind": "运行中的服务是 Avibe {version}({generation}),比最近激活的安装 {activatedVersion}({activatedGeneration})旧","cliNotUvTool": "当前 vibe 可执行文件不是 uv tool 安装","cliEditable": "uv tool 安装是 editable:{path}",@@ -1461,6 +1467,7 @@"cliPathPrecedence": "使用 uv tool 安装时,将 ~/.local/bin 放在系统 Python bin 目录之前。","splitLaunchers": "运行 `{repairCommand}`,让所有启动器都指向 Avibe {version}。","splitLaunchersTied": "这些安装同为最后激活,修复无法从中选择:{launchers}。请重新运行 Avibe 安装程序,它的新安装会让所有启动器一起切换过去。",+ "staleLoginSession": "请在 Mac 当前桌面的终端运行 `vibe restart`,然后从 Avibe 重试。请不要重复重试失败的操作。","serviceGenerationBehind": "运行 `{restartCommand}`,改为运行最近激活的安装。","cliNotUvTool": "此可执行文件将跳过 uv tool 包完整性检查。","cliEditable": "从普通 wheel 重新安装 Avibe。运行中的本地 CLI 不要使用 'uv tool install --editable .'。",diff --git a/vibe/macos_session_diagnostics.py b/vibe/macos_session_diagnostics.pyindex 7c9fcd768..67a8cee21 100644--- a/vibe/macos_session_diagnostics.py+++ b/vibe/macos_session_diagnostics.py@@ -41,6 +41,7 @@ class CommandResult:CommandRunner = Callable[[Sequence[str], float], CommandResult]ConsoleUserReader = Callable[[], tuple[str | None, str | None]]+ServiceUserReader = Callable[[int], tuple[str | None, str | None]]def run_bounded_command(command: Sequence[str], timeout: float) -> CommandResult:@@ -85,6 +86,23 @@ def read_console_user() -> tuple[str | None, str | None]:return None, "os_error"+def read_service_user(service_uid: int) -> tuple[str | None, str | None]:+ """Resolve the service UID through the process's own Directory Services context."""+ if pwd is None:+ return None, "tool_missing"+ try:+ return pwd.getpwuid(service_uid).pw_name, None+ except KeyError:+ # A process inherited from an ended macOS login can keep running while+ # Directory Services no longer resolves its original user. This is the+ # positive signal that does not depend on launchctl's GUI-domain query.+ return None, "user_lookup_failed"+ except PermissionError:+ return None, "permission"+ except OSError:+ return None, "os_error"++def parse_launchctl_asid(output: str) -> int | None:"""Extract the audit session ID from a launchctl security context."""security_context = _SECURITY_CONTEXT_RE.search(output)@@ -131,6 +149,22 @@ class SessionContext:return self.service_asid == self.gui_asid+def is_stale_login_session(context: SessionContext) -> bool:+ """Return true only for the process-local Directory Services failure signal."""+ return context.service_error_class == "user_lookup_failed"+++def login_session_state(context: SessionContext) -> str:+ """Classify the current process without treating inconclusive probes as stale."""+ if is_stale_login_session(context):+ return "stale_login_session"+ if context.gui_domain_available is False:+ return "no_gui_session"+ if context.gui_domain_available is None:+ return "unknown"+ return "healthy"++@dataclass(frozen=True)class DnsProbeState:state: str@@ -153,6 +187,7 @@ class SessionDiagnosticSnapshot:"gui_asid": self.context.gui_asid,"gui_domain_available": self.context.gui_domain_available,"asid_match": self.context.asid_match,+ "login_session_state": login_session_state(self.context),"dns_state": self.dns.state,}optional_fields = {@@ -175,6 +210,8 @@ class MacOSSessionProbe:service_uid: int | None = None,command_runner: CommandRunner = run_bounded_command,console_user_reader: ConsoleUserReader = read_console_user,+ service_user_reader: ServiceUserReader = read_service_user,+ service_pid_is_target: bool = False,command_timeout: float = DEFAULT_COMMAND_TIMEOUT_SECONDS,dns_hostname: str = DNS_PROBE_HOSTNAME,) -> None:@@ -182,6 +219,8 @@ class MacOSSessionProbe:self.service_uid = service_uid if service_uid is not None else os.getuid()self._command_runner = command_runnerself._console_user_reader = console_user_reader+ self._service_user_reader = service_user_reader+ self._service_pid_is_target = service_pid_is_targetself._command_timeout = command_timeoutself._dns_hostname = dns_hostnameself._service_asid: int | None = None@@ -193,6 +232,12 @@ class MacOSSessionProbe:console_user, console_error = None, "probe_error"service_error = None+ if not self._service_pid_is_target:+ try:+ _service_user, service_user_error = self._service_user_reader(self.service_uid)+ except Exception:+ service_user_error = "probe_error"+ service_error = service_user_errorif self._service_asid is None:result = self._command_runner(["/bin/launchctl", "print", f"pid/{self.service_pid}"],@@ -200,10 +245,11 @@ class MacOSSessionProbe:)if result.returncode == 0:self._service_asid = parse_launchctl_asid(result.output)- if self._service_asid is None:+ if self._service_asid is None and service_error is None:service_error = "parse_error"else:- service_error = _command_error_class(result)+ if service_error is None:+ service_error = _command_error_class(result)gui_result = self._command_runner(["/bin/launchctl", "print", f"gui/{self.service_uid}"],@@ -254,6 +300,8 @@ def _context_transition_reasons(previous: SessionContext, current: SessionContexcurrent.console_error_class,):reasons.append("console_user_change")+ if previous.service_error_class != current.service_error_class:+ reasons.append("service_identity_change")if (previous.gui_domain_available,previous.gui_asid,@@ -303,6 +351,11 @@ class MacOSSessionMonitor:self._last_snapshot: SessionDiagnosticSnapshot | None = Noneself._last_dns_probe_at: float | None = None+ @property+ def current_state(self) -> str:+ snapshot = self._last_snapshot+ return "unknown" if snapshot is None else login_session_state(snapshot.context)+def start(self) -> None:if not self._enabled or self._thread is not None:return@@ -403,8 +456,7 @@ class MacOSSessionMonitor:payload = json.dumps(snapshot.event(reasons), sort_keys=True, separators=(",", ":"))context = snapshot.contextwarning = (- context.gui_domain_available is not True- or context.asid_match is False+ login_session_state(context) != "healthy"or snapshot.dns.state == "failed"or snapshot.dns.error_class is not Noneor any(@@ -422,13 +474,24 @@ class MacOSSessionMonitor:self._logger.info("macos_session_diagnostic %s", payload)+_active_monitor: MacOSSessionMonitor | None = None+++def current_macos_session_state() -> str | None:+ """Return the service process's cached session state, if diagnostics run."""+ monitor = _active_monitor+ return None if monitor is None else monitor.current_state++def start_macos_session_diagnostics(logger: logging.Logger,*,platform: str = sys.platform,) -> MacOSSessionMonitor:"""Start diagnostics best-effort; probe failures never block the service."""+ global _active_monitormonitor = MacOSSessionMonitor(logger, platform=platform)+ _active_monitor = monitortry:monitor.start()except Exception:diff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex 951ba6c16..f2b52288c 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -5848,6 +5848,13 @@ def vault_agent_pubkey_get():return _vault_error_response(exc)[email protected]("/api/macos/login-session", methods=["GET"])+def macos_login_session_get():+ from vibe import api++ return jsonify(api.get_macos_login_session_status())++@app.route("/api/vault/avault-authorization", methods=["GET"])def vault_avault_authorization_get():from vibe import api