Skip to content

armgit / avibe

Public Imported from GitHub
0

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

fix(desktop): close macOS Computer Use acceptance gaps (#2407)

Max2dd45abe9a35
diff --git a/core/computer_use.py b/core/computer_use.py
index 0237b7834..44211f4a9 100644
--- a/core/computer_use.py
+++ b/core/computer_use.py
@@ -450,17 +450,23 @@ def desktop_computer_use_shell_is_live(
lock_path: Path | None = None,
shell_lock_held: Callable[[Path], bool] = _shell_lock_is_held,
) -> bool:
- """Whether a valid native state record is still owned by a live shell."""
+ """Whether the native shell owns the Computer Use lock.
+
+ Missing or damaged optional state does not mean that the native shell is
+ absent: the shell acquires the lock before it reads or repairs that state.
+ The lock is therefore the support signal, while a valid state record
+ remains the source for the feature's effective status.
+ """
target = state_path or computer_use_state_path()
try:
state = read_computer_use_state(target)
except ComputerUseStateError:
- return False
- if state is None or state.state == "stopped":
- return False
+ state = None
resolved_lock_path = lock_path or target.with_name(COMPUTER_USE_LOCK_FILE)
- return shell_lock_held(resolved_lock_path)
+ if not shell_lock_held(resolved_lock_path):
+ return False
+ return state is None or state.state != "stopped"
def _unix_socket_accepts(path: str, *, timeout: float = 0.1) -> bool:
diff --git a/desktop/runtime-host/src/computer_use.rs b/desktop/runtime-host/src/computer_use.rs
index 915ea2a58..b9ebebec6 100644
--- a/desktop/runtime-host/src/computer_use.rs
+++ b/desktop/runtime-host/src/computer_use.rs
@@ -628,6 +628,7 @@ fn stable_failure_reason(reason: &str) -> &'static str {
"state_unwritable" => "state_unwritable",
"assets_invalid" => "assets_invalid",
"spawn_failed" => "spawn_failed",
+ "socket_path_too_long" => "socket_path_too_long",
"daemon_exited" => "daemon_exited",
"health_timeout" => "health_timeout",
"endpoint_busy" => "endpoint_busy",
@@ -1018,6 +1019,7 @@ mod tests {
fn health_failures_persist_only_the_stable_reason_set() {
for (raw, expected) in [
("spawn_failed", "spawn_failed"),
+ ("socket_path_too_long", "socket_path_too_long"),
("daemon_exited", "daemon_exited"),
("health_timeout", "health_timeout"),
("endpoint_busy", "endpoint_busy"),
diff --git a/desktop/src-tauri/src/computer_use.rs b/desktop/src-tauri/src/computer_use.rs
index 896775af8..f4f5bcb16 100644
--- a/desktop/src-tauri/src/computer_use.rs
+++ b/desktop/src-tauri/src/computer_use.rs
@@ -3,6 +3,8 @@
use std::ffi::c_void;
use std::fs::File;
use std::io::{self, Read};
+use std::os::unix::ffi::OsStrExt;
+use std::os::unix::fs::{MetadataExt, PermissionsExt};
use std::path::{Path, PathBuf};
use std::process::Stdio;
use std::ptr;
@@ -31,8 +33,9 @@ use tauri::plugin::{Builder as PluginBuilder, TauriPlugin};
use tauri::{AppHandle, Manager, RunEvent};
use tauri_plugin_dialog::{DialogExt, MessageDialogKind};
use tokio::io::{AsyncBufReadExt, AsyncWrite, AsyncWriteExt, BufReader};
-use tokio::process::{Child, ChildStdin, Command};
+use tokio::process::{Child, ChildStderr, ChildStdin, Command};
use tokio::sync::{mpsc, oneshot};
+use tokio::task::JoinHandle;
use tokio::time::{sleep, timeout, timeout_at};
const STATE_DIR_ENV: &str = "AVIBE_COMPUTER_USE_STATE_DIR";
@@ -48,6 +51,10 @@ const PERMISSION_REQUEST_TIMEOUT: Duration = Duration::from_secs(5);
const PERMISSION_CHILD_TIMEOUT: Duration = Duration::from_secs(10);
const START_BACKOFF: Duration = Duration::from_secs(1);
const COMPUTER_USE_SCHEMA: u64 = COMPUTER_USE_SCHEMA_VERSION as u64;
+const DARWIN_SOCKET_PATH_MAX_BYTES: usize = 103;
+const SOCKET_DIRECTORY_MODE: u32 = 0o700;
+const SOCKET_FLAVOR_HEX_BYTES: usize = 12;
+const DAEMON_STDERR_TAIL_BYTES: usize = 8 * 1024;
fn driver_command(driver: &Path) -> Command {
let mut command = Command::new(driver);
@@ -120,6 +127,7 @@ enum Event {
Toggle,
RuntimeReady { origin: LoopbackOrigin, adoption: bool },
RuntimeLost,
+ RuntimeStopped,
Activated,
RetryStart { id: u64 },
PermissionProbeFinished { id: u64, result: PermissionChildRun },
@@ -173,6 +181,10 @@ impl Controller {
let _ = self.sender.send(Event::RuntimeLost);
}
+ pub(crate) fn runtime_stopped(&self) {
+ let _ = self.sender.send(Event::RuntimeStopped);
+ }
+
pub(crate) fn activated(&self) {
let _ = self.sender.send(Event::Activated);
}
@@ -201,6 +213,10 @@ struct Paths {
impl Paths {
fn resolve(app: &AppHandle) -> Result<Self, Box<dyn std::error::Error>> {
let state_dir = configured_path(app.path().app_data_dir()?, STATE_DIR_ENV);
+ std::fs::create_dir_all(&state_dir)?;
+ let owner_uid = std::fs::metadata(&state_dir)?.uid();
+ let socket = short_socket_path(&state_dir, owner_uid);
+ ensure_private_socket_directory(socket.parent().expect("socket directory"), owner_uid)?;
let executable = std::env::current_exe()?;
let resource_dir = app.path().resource_dir()?;
let driver = configured_path(bundled_driver_path(&executable), DRIVER_PATH_ENV);
@@ -208,7 +224,7 @@ impl Paths {
let snapshot = configured_path(resource_dir.join("computer-use/tools-v0.31.0.json"), SNAPSHOT_PATH_ENV);
Ok(Self {
state_file: state_dir.join(COMPUTER_USE_STATE_FILE),
- socket: state_dir.join(COMPUTER_USE_SOCKET_FILE),
+ socket,
state_dir,
driver,
policy,
@@ -223,6 +239,47 @@ impl Paths {
}
}
+fn short_socket_path(state_dir: &Path, owner_uid: u32) -> PathBuf {
+ let mut digest = Sha256::new();
+ digest.update(state_dir.as_os_str().as_bytes());
+ let flavor = format!("{:x}", digest.finalize());
+ let flavor = &flavor[..SOCKET_FLAVOR_HEX_BYTES];
+ PathBuf::from("/tmp")
+ .join(format!("avibe-cua-{owner_uid}-{flavor}"))
+ .join(COMPUTER_USE_SOCKET_FILE)
+}
+
+fn ensure_private_socket_directory(path: &Path, owner_uid: u32) -> io::Result<()> {
+ match std::fs::create_dir(path) {
+ Ok(()) => {}
+ Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {}
+ Err(error) => return Err(error),
+ }
+ let metadata = std::fs::symlink_metadata(path)?;
+ if !metadata.file_type().is_dir() {
+ return Err(io::Error::new(
+ io::ErrorKind::PermissionDenied,
+ "computer-use socket directory is not a real directory",
+ ));
+ }
+ if metadata.uid() != owner_uid {
+ return Err(io::Error::new(
+ io::ErrorKind::PermissionDenied,
+ "computer-use socket directory is not owned by the desktop user",
+ ));
+ }
+ let mut permissions = metadata.permissions();
+ permissions.set_mode(SOCKET_DIRECTORY_MODE);
+ std::fs::set_permissions(path, permissions)
+}
+
+fn socket_path_preflight(path: &Path) -> Result<(), &'static str> {
+ if path.as_os_str().as_bytes().len() > DARWIN_SOCKET_PATH_MAX_BYTES {
+ return Err("socket_path_too_long");
+ }
+ Ok(())
+}
+
fn configured_path(default: PathBuf, variable: &str) -> PathBuf {
configured_path_with_value(default, std::env::var_os(variable), test_path_overrides_enabled())
}
@@ -254,6 +311,7 @@ fn bundled_driver_path(executable: &Path) -> PathBuf {
struct Daemon {
child: Child,
stdin: Option<ChildStdin>,
+ stderr_tail: JoinHandle<Vec<u8>>,
}
struct PermissionProbe {
@@ -360,6 +418,7 @@ impl RuntimeState {
self.runtime_ready(origin, adoption).await;
}
Event::RuntimeLost => self.runtime_lost().await,
+ Event::RuntimeStopped => self.runtime_stopped().await,
Event::Activated => self.activated().await,
Event::RetryStart { id } => self.retry_start(id).await,
Event::PermissionProbeFinished { id, result } => {
@@ -438,8 +497,18 @@ impl RuntimeState {
}
async fn runtime_lost(&mut self) {
+ self.set_runtime_lost(false).await;
+ }
+
+ async fn runtime_stopped(&mut self) {
+ self.set_runtime_lost(true).await;
+ }
+
+ async fn set_runtime_lost(&mut self, clear_origin: bool) {
self.invalidate_start_retry();
- self.origin = None;
+ if clear_origin {
+ self.origin = None;
+ }
self.capabilities.begin_adoption();
let directive = self.lifecycle.capabilities(RuntimeSupport::Unknown, silent_grants());
self.apply(directive).await;
@@ -464,10 +533,17 @@ impl RuntimeState {
self.publish_view();
}
}
- if !self.lifecycle.enabled()
- || self.lifecycle.phase() == ComputerUsePhase::Error
- || self.capabilities.current() != RuntimeSupport::Supported
- {
+ if !self.lifecycle.enabled() || self.lifecycle.phase() == ComputerUsePhase::Error {
+ return;
+ }
+ if self.lifecycle.phase() == ComputerUsePhase::NeedsRuntime {
+ if let Some(directive) =
+ runtime_reprobe_directive(&mut self.lifecycle, &mut self.capabilities, self.origin.as_ref()).await
+ {
+ self.apply(directive).await;
+ }
+ }
+ if self.capabilities.current() != RuntimeSupport::Supported {
return;
}
match self.lifecycle.phase() {
@@ -596,6 +672,16 @@ impl RuntimeState {
return HealthResult::Unhealthy("shutdown_requested".to_owned());
}
self.stop_daemon().await;
+ if let Err(reason) = socket_path_preflight(&self.paths.socket) {
+ self.diagnostics.record(
+ "computer-use.socket-preflight",
+ &[
+ ("reason", reason.to_owned()),
+ ("path_bytes", self.paths.socket.as_os_str().as_bytes().len().to_string()),
+ ],
+ );
+ return HealthResult::Unhealthy(reason.to_owned());
+ }
if let Err(reason) = self.reclaim_endpoint().await {
return HealthResult::Unhealthy(reason);
}
@@ -666,6 +752,9 @@ impl RuntimeState {
let _ = daemon.child.kill().await;
let _ = daemon.child.wait().await;
}
+ if let Ok(Ok(stderr_tail)) = timeout(PROCESS_STOP_TIMEOUT, daemon.stderr_tail).await {
+ record_daemon_stderr(&self.diagnostics, &stderr_tail);
+ }
let _ = std::fs::remove_file(&self.paths.socket);
}
@@ -804,6 +893,27 @@ fn restored_lifecycle(stored: &StoredComputerUseState, assets_valid: bool) -> Co
lifecycle
}
+async fn runtime_reprobe_directive(
+ lifecycle: &mut ComputerUseLifecycle,
+ capabilities: &mut CapabilityCache,
+ origin: Option<&LoopbackOrigin>,
+) -> Option<LifecycleDirective> {
+ if !lifecycle.enabled() || lifecycle.phase() != ComputerUsePhase::NeedsRuntime {
+ return None;
+ }
+ let origin = origin?;
+ let support = capabilities.observe(probe_capabilities(origin).await);
+ let grants = if support == RuntimeSupport::Supported {
+ silent_grants()
+ } else {
+ Grants {
+ accessibility: false,
+ screen_recording: false,
+ }
+ };
+ Some(lifecycle.capabilities(support, grants))
+}
+
fn retry_is_current(id: u64, current_id: u64, lifecycle: &ComputerUseLifecycle) -> bool {
id == current_id && lifecycle.enabled() && lifecycle.phase() == ComputerUsePhase::Starting
}
@@ -894,11 +1004,52 @@ fn spawn_daemon(driver: &Path, socket: &Path, host_bundle_id: &str, policy: &Pat
.env("CUA_DRIVER_MANAGED_POLICY_FILE", policy)
.stdin(Stdio::piped())
.stdout(Stdio::null())
- .stderr(Stdio::null())
+ .stderr(Stdio::piped())
.kill_on_drop(true);
let mut child = command.spawn()?;
let stdin = child.stdin.take();
- Ok(Daemon { child, stdin })
+ let stderr = child
+ .stderr
+ .take()
+ .ok_or_else(|| io::Error::other("computer-use daemon stderr pipe was not available"))?;
+ let stderr_tail = tokio::spawn(capture_stderr_tail(stderr));
+ Ok(Daemon {
+ child,
+ stdin,
+ stderr_tail,
+ })
+}
+
+async fn capture_stderr_tail(mut stderr: ChildStderr) -> Vec<u8> {
+ let mut tail = Vec::with_capacity(DAEMON_STDERR_TAIL_BYTES);
+ let mut chunk = [0_u8; 4096];
+ loop {
+ let read = match tokio::io::AsyncReadExt::read(&mut stderr, &mut chunk).await {
+ Ok(0) | Err(_) => break,
+ Ok(read) => read,
+ };
+ if read >= DAEMON_STDERR_TAIL_BYTES {
+ tail.clear();
+ tail.extend_from_slice(&chunk[read - DAEMON_STDERR_TAIL_BYTES..read]);
+ continue;
+ }
+ let overflow = (tail.len() + read).saturating_sub(DAEMON_STDERR_TAIL_BYTES);
+ if overflow > 0 {
+ tail.drain(..overflow);
+ }
+ tail.extend_from_slice(&chunk[..read]);
+ }
+ tail
+}
+
+fn record_daemon_stderr(diagnostics: &BootstrapLog, stderr_tail: &[u8]) {
+ if stderr_tail.is_empty() {
+ return;
+ }
+ diagnostics.record(
+ "computer-use.daemon-stderr",
+ &[("tail", String::from_utf8_lossy(stderr_tail).into_owned())],
+ );
}
#[derive(Clone, Debug, Eq, PartialEq)]
@@ -2233,6 +2384,86 @@ done
);
}
+ #[test]
+ fn socket_path_is_short_and_isolated_by_state_directory_flavor() {
+ let first = short_socket_path(Path::new("/tmp/first-computer-use-state"), 501);
+ let second = short_socket_path(Path::new("/tmp/second-computer-use-state"), 501);
+
+ assert_ne!(first, second);
+ assert_eq!(
+ first.file_name().and_then(|name| name.to_str()),
+ Some(COMPUTER_USE_SOCKET_FILE)
+ );
+ assert!(first.as_os_str().as_bytes().len() <= DARWIN_SOCKET_PATH_MAX_BYTES);
+ assert!(first
+ .parent()
+ .and_then(Path::to_str)
+ .unwrap()
+ .starts_with("/tmp/avibe-cua-"));
+ }
+
+ #[test]
+ fn socket_directory_is_private_and_owned_by_the_state_directory_owner() {
+ let temporary = tempfile::tempdir().expect("temporary directory");
+ let state_dir = temporary.path().join("state");
+ std::fs::create_dir_all(&state_dir).expect("state directory");
+ let owner_uid = std::fs::metadata(&state_dir).expect("state metadata").uid();
+ let socket_dir = short_socket_path(&state_dir, owner_uid)
+ .parent()
+ .expect("socket directory")
+ .to_owned();
+
+ ensure_private_socket_directory(&socket_dir, owner_uid).expect("private socket directory");
+
+ let metadata = std::fs::metadata(socket_dir).expect("socket directory metadata");
+ assert_eq!(metadata.uid(), owner_uid);
+ assert_eq!(metadata.permissions().mode() & 0o777, SOCKET_DIRECTORY_MODE);
+ std::fs::remove_dir(short_socket_path(&state_dir, owner_uid).parent().unwrap())
+ .expect("remove socket directory");
+ }
+
+ #[test]
+ fn over_limit_socket_paths_are_classified_before_spawn() {
+ let path = PathBuf::from("/tmp").join("x".repeat(DARWIN_SOCKET_PATH_MAX_BYTES));
+ assert_eq!(socket_path_preflight(&path), Err("socket_path_too_long"));
+ }
+
+ #[tokio::test]
+ async fn daemon_stderr_tail_is_bounded_and_reaches_shell_diagnostics() {
+ let temporary = tempfile::tempdir().expect("temporary directory");
+ let driver = temporary.path().join("fake-cua-driver");
+ std::fs::write(
+ &driver,
+ "#!/bin/sh\nprintf 'daemon failed: %s\\n' 'socket unavailable' >&2\nexit 1\n",
+ )
+ .expect("stderr fixture");
+ let mut permissions = std::fs::metadata(&driver)
+ .expect("stderr fixture metadata")
+ .permissions();
+ permissions.set_mode(0o755);
+ std::fs::set_permissions(&driver, permissions).expect("stderr fixture executable");
+ let policy = temporary.path().join("policy.yaml");
+ std::fs::write(&policy, "version: 1\n").expect("policy fixture");
+ let mut daemon = spawn_daemon(
+ &driver,
+ &temporary.path().join("driver.sock"),
+ "bot.avibe.desktop.test",
+ &policy,
+ )
+ .expect("spawn stderr fixture");
+ daemon.child.wait().await.expect("stderr fixture exit");
+ let tail = daemon.stderr_tail.await.expect("stderr reader");
+
+ let path = temporary.path().join(BOOTSTRAP_LOG_NAME);
+ let diagnostics = BootstrapLog::at(path.clone());
+ record_daemon_stderr(&diagnostics, &tail);
+
+ let written = std::fs::read_to_string(path).expect("diagnostic log");
+ assert!(tail.len() <= DAEMON_STDERR_TAIL_BYTES);
+ assert!(written.contains("computer-use.daemon-stderr"));
+ assert!(written.contains("socket unavailable"));
+ }
+
#[test]
fn release_path_resolution_ignores_test_environment_overrides() {
let bundled = PathBuf::from("/Applications/Avibe.app/Contents/Helpers/cua-driver");
@@ -2278,6 +2509,67 @@ done
);
}
+ #[tokio::test]
+ async fn normal_runtime_reprobe_relaunches_persisted_enablement_on_the_same_origin() {
+ let record = ComputerUseRecord {
+ schema_version: COMPUTER_USE_SCHEMA_VERSION,
+ enabled: true,
+ state: ComputerUsePhase::NeedsRuntime,
+ reason: Some("runtime_unavailable".to_owned()),
+ shell_pid: 1,
+ instance_id: "reprobe-shell".to_owned(),
+ generation: 4,
+ driver_version: COMPUTER_USE_DRIVER_VERSION.to_owned(),
+ tool_snapshot: ToolSnapshot {
+ path: PathBuf::from("/tmp/tools.json"),
+ sha256: COMPUTER_USE_TOOL_SNAPSHOT_SHA256.to_owned(),
+ },
+ socket_path: None,
+ proxy_executable: None,
+ host_bundle_id: None,
+ };
+ let mut lifecycle = ComputerUseLifecycle::from_record(&record);
+ let mut capabilities = CapabilityCache::default();
+ capabilities.begin_adoption();
+
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
+ .await
+ .expect("capability listener");
+ let address = listener.local_addr().expect("capability listener address");
+ let origin = LoopbackOrigin::parse(&format!("http://{address}")).expect("loopback origin");
+ let server = tokio::spawn(async move {
+ use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};
+
+ let (mut stream, _) = listener.accept().await.expect("capability request");
+ let mut request = [0_u8; 1024];
+ let read = stream.read(&mut request).await.expect("capability request bytes");
+ assert!(String::from_utf8_lossy(&request[..read]).starts_with("GET /api/desktop/capabilities "));
+ let body =
+ format!(r#"{{"controller_id":"restarted-runtime","computer_use_schema":{COMPUTER_USE_SCHEMA}}}"#);
+ let response = format!(
+ "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
+ body.len()
+ );
+ stream
+ .write_all(response.as_bytes())
+ .await
+ .expect("capability response");
+ });
+ let directive = runtime_reprobe_directive(&mut lifecycle, &mut capabilities, Some(&origin))
+ .await
+ .expect("normal tick reprobe");
+ server.await.expect("capability server");
+
+ assert!(directive.spawn_daemon);
+ assert!(directive.write_state);
+ assert_eq!(capabilities.controller_id(), Some("restarted-runtime"));
+ assert_eq!(lifecycle.phase(), ComputerUsePhase::Starting);
+ assert_eq!(
+ runtime_reprobe_directive(&mut lifecycle, &mut capabilities, Some(&origin)).await,
+ None
+ );
+ }
+
#[test]
fn delayed_start_retry_is_invalidated_by_toggle_off_and_runtime_loss() {
let mut starting = ComputerUseLifecycle::off();
diff --git a/desktop/src-tauri/src/lib.rs b/desktop/src-tauri/src/lib.rs
index 5dee2ff5c..5e33f5a3e 100644
--- a/desktop/src-tauri/src/lib.rs
+++ b/desktop/src-tauri/src/lib.rs
@@ -902,7 +902,7 @@ fn stop_runtime(app: AppHandle, quit: bool) {
notifications::stop(&app);
#[cfg(target_os = "macos")]
if let Some(controller) = app.try_state::<computer_use::Controller>() {
- controller.runtime_lost();
+ controller.runtime_stopped();
}
tauri::async_runtime::spawn(async move {
let outcome = host.stop_owned_runtime().await;
@@ -2267,11 +2267,13 @@ mod tests {
assert!(english.screen_recording_title.contains("Screen Recording"));
assert!(english.screen_recording_guide.to_lowercase().contains("click +"));
assert!(english.screen_recording_guide.contains("drag"));
+ assert!(english.screen_recording_guide.contains("quit and reopen"));
let chinese = native_catalog_for_locales(["zh-CN".to_owned()]).computer_use;
assert!(chinese.screen_recording_title.contains("屏幕"));
assert!(chinese.screen_recording_guide.contains("拖"));
assert!(chinese.screen_recording_guide.contains("+"));
+ assert!(chinese.screen_recording_guide.contains("退出并重新打开"));
}
#[cfg(target_os = "macos")]
diff --git a/desktop/src-tauri/tests/shell_boundaries.rs b/desktop/src-tauri/tests/shell_boundaries.rs
index d560b8b99..980276e6f 100644
--- a/desktop/src-tauri/tests/shell_boundaries.rs
+++ b/desktop/src-tauri/tests/shell_boundaries.rs
@@ -800,6 +800,7 @@ fn native_lifecycle_authority_requires_the_runtime_identity_not_a_launch_attempt
);
assert!(stop.contains("ACTIVITY_IDLE"));
assert!(stop.contains("focus_or_restore_main_window(&app)"));
+ assert!(stop.contains("controller.runtime_stopped()"));
assert!(!stop.contains("start_runtime_monitor("));
assert!(!stop.contains("spawn_bootstrap("));
}
diff --git a/docs/plans/desktop-computer-use.md b/docs/plans/desktop-computer-use.md
index fe049c99a..e7862c07a 100644
--- a/docs/plans/desktop-computer-use.md
+++ b/docs/plans/desktop-computer-use.md
@@ -1095,3 +1095,76 @@ redirected to test-owned fakes.
helper CHECKIN under the outer bundle identity and no recorded helper
frontmost assertion. It did not establish generic idle focus, pointer, or
cursor acceptance, and it remains ungranted.
+
+## 2026-10-09 follow-up contract
+
+This follow-up is based on the post-merge acceptance ledger at
+`/tmp/avibe-cua-final-acceptance-ses9qeb46suvv-84fcff21/acceptance-ledger.md`
+and the frozen evidence roots
+`/tmp/avibe-cua-final-sd` and
+`/tmp/avibe-cua-phase1-acceptance-ses9qeb46suvv-be8e909/home`.
+The implementation branch starts from exact base
+`84fcff2101223a65ddc6f5b878d7ba61805ffb96`. The sensitive
+`live-step9-consented-retry-outcome.json` is excluded from implementation and
+publication.
+
+The five findings and their owning contracts are:
+
+1. **F1, Darwin socket and diagnostics.** The native shell derives a stable
+ per-user socket directory under `/tmp` from the current state-directory
+ flavor, keeps that directory owned by the current user with mode `0700`,
+ and records the absolute socket path in the existing state record. A
+ preflight rejects any Darwin socket path over 103 bytes with the stable
+ reason `socket_path_too_long`; it must not be reported as `daemon_exited`.
+ The managed daemon's stderr is drained into a bounded tail and appended to
+ the existing shell bootstrap diagnostics. Owning tests cover path
+ construction, flavor isolation, permissions, over-limit classification, and
+ stderr propagation.
+2. **F2, Screen Recording guidance.** English and Chinese native and
+ Workbench guidance must state that macOS may quit and reopen Avibe after the
+ Screen Recording grant. The two locales keep the same recovery steps and
+ consuming catalog/UI tests protect the parity.
+3. **F3, Workbench support on first install.** Workbench support is derived
+ from the live native shell's lock ownership. A live shell therefore keeps
+ Computer Use visible when the state record is missing or invalid; the
+ status reader remains responsible for returning `off/never_enabled` or
+ `unavailable/invalid_state_file`. This preserves the Phase 1 accepted
+ limitation that a terminal-started Runtime on the same machine may advertise
+ the shell's native Computer Use. A per-Runtime shell-adoption signal remains
+ future work.
+4. **F4, Runtime bootout cleanup.** The service shutdown boundary reaps the
+ exact UI process belonging to its desktop Runtime before releasing the
+ service lock. Ownership is checked through the existing Runtime id and the
+ existing UI process identity; no pattern kill is introduced. A managed
+ service shutdown reaps the UI only when no managed shutdown intent was
+ consumed, which covers launchd bootout and external termination. Every
+ managed stop or restart caller retains its existing UI lifecycle ownership,
+ regardless of its reason; this includes Workbench service stop,
+ service-only and full restart, and explicit unscoped `vibe stop`. The
+ lifecycle test covers unmanaged signal-driven service exit and exact UI
+ ownership, while the desktop Runtime stop tests retain the real process scan
+ and rescan contract.
+5. **F5, Runtime re-adoption.** When enablement persists in
+ `needs_runtime/runtime_unavailable`, the shell retains the last monitored
+ origin and normal ticks probe the Runtime capability endpoint again. A
+ supported response transitions through the existing lifecycle contract and
+ launches one new driver generation, preserving the current lease,
+ ownership, and no-replay behavior. An explicit user Runtime stop uses a
+ separate stopped event that clears the retained origin, so the shell does
+ not re-adopt a Runtime the user has stopped. Transient and unsupported
+ responses do not start a driver.
+
+Validation for this follow-up must include the owning Python, UI, and Rust
+tests; Ruff on changed Python; the UI build and relevant UI tests; Rust
+formatting, tests, and required Clippy/package/workflow checks; repository CI;
+an exact-head Codex review; and zero unresolved review threads. The PR is
+non-draft and remains unmerged until the owner authorizes merge.
+
+Known-by-design limits remain explicit: Step 9b, one normal Workbench Claude
+tool-driven desktop action, is deferred to real-machine acceptance; no Claude
+run, login, credential access, GUI action, TCC mutation, release, candidate
+Runtime restart, or owner Runtime restart is part of implementation. The
+accepted ad-hoc macOS Screen Recording `+`/drag recovery remains the Phase 1
+path. The optional resource-governance hermeticity and server-level Claude
+allowlist follow-ups are recorded for later triage and do not expand this
+change unless they remain strictly local and necessary.
diff --git a/main.py b/main.py
index 0b99c8428..737f5c1b2 100644
--- a/main.py
+++ b/main.py
@@ -110,17 +110,22 @@ def _log_shutdown_signal(logger: logging.Logger, signum: int) -> None:
logger.info("Received signal %s", signum)
-def _log_shutdown_intent(logger: logging.Logger, signum: int) -> None:
+def _log_shutdown_intent(logger: logging.Logger, signum: int) -> dict | None:
if signum != signal.SIGTERM or not shutdown_intent_required():
- return
+ return None
intent = consume_shutdown_intent(os.getpid(), signum)
if intent is None:
logger.warning(
"No managed shutdown intent found for SIGTERM pid=%s; honoring signal",
os.getpid(),
)
- return
+ return None
logger.info("Accepted managed shutdown intent: %s", intent)
+ return intent
+
+
+def _should_reap_desktop_runtime_ui(shutdown_intent: dict | None) -> bool:
+ return shutdown_intent is None
def _stop_macos_session_diagnostics(monitor: Any) -> None:
@@ -132,6 +137,22 @@ def _stop_macos_session_diagnostics(monitor: Any) -> None:
logging.getLogger(__name__).debug("macOS session diagnostics cleanup failed")
+def _stop_owned_desktop_runtime_ui(logger: logging.Logger) -> None:
+ """Reap the UI that belongs to this desktop Runtime before service exit."""
+
+ try:
+ from vibe import runtime
+ from vibe.desktop_runtime import desktop_caller_provenance
+
+ runtime_ids = desktop_caller_provenance()
+ if not runtime_ids:
+ return
+ if not runtime.stop_ui(stop_remote_access=False, runtime_ids=runtime_ids):
+ logger.warning("Desktop Runtime UI did not stop during service shutdown")
+ except Exception:
+ logger.warning("Failed to stop the desktop Runtime UI during service shutdown", exc_info=True)
+
+
def _request_controller_loop_stop(controller: Any) -> bool:
"""Ask a running controller loop to exit so its finally block can clean up."""
@@ -147,6 +168,7 @@ def main():
lock_acquired = False
macos_session_diagnostics = None
controller = None
+ shutdown_intent = None
try:
acquire_service_instance_lock()
lock_acquired = True
@@ -200,13 +222,13 @@ def main():
shutdown_initiated = False
def _handle_shutdown(signum, frame):
- nonlocal shutdown_initiated
+ nonlocal shutdown_initiated, shutdown_intent
if shutdown_initiated:
return
shutdown_initiated = True
try:
_log_shutdown_signal(logger, signum)
- _log_shutdown_intent(logger, signum)
+ shutdown_intent = _log_shutdown_intent(logger, signum)
logger.info("Shutting down after signal %s", signum)
except Exception:
pass
@@ -226,6 +248,8 @@ def main():
try:
controller.run()
finally:
+ if _should_reap_desktop_runtime_ui(shutdown_intent):
+ _stop_owned_desktop_runtime_ui(logger)
_stop_macos_session_diagnostics(macos_session_diagnostics)
except ServiceAlreadyRunningError as e:
diff --git a/tests/test_computer_use.py b/tests/test_computer_use.py
index bbcf2a20d..0f99b4d00 100644
--- a/tests/test_computer_use.py
+++ b/tests/test_computer_use.py
@@ -90,15 +90,15 @@ def test_desktop_state_path_ignores_avibe_home(tmp_path: Path) -> None:
@pytest.mark.parametrize(
("arrange", "lock_held", "expected"),
[
- ("missing", True, False),
- ("invalid", True, False),
+ ("missing", True, True),
+ ("invalid", True, True),
("stopped", True, False),
("off", True, True),
("ready", False, False),
("ready", True, True),
],
)
-def test_shell_support_requires_valid_state_owned_by_live_native_lock(
+def test_shell_support_follows_live_native_lock_across_optional_state_shapes(
tmp_path: Path,
arrange: str,
lock_held: bool,
diff --git a/tests/test_desktop_computer_capabilities.py b/tests/test_desktop_computer_capabilities.py
index 9e6169348..3aeba94d4 100644
--- a/tests/test_desktop_computer_capabilities.py
+++ b/tests/test_desktop_computer_capabilities.py
@@ -141,6 +141,33 @@ def test_workbench_status_supports_adopted_runtime_when_native_shell_is_live(
assert response.headers["Cache-Control"] == "no-store"
+ ("status", "reason"),
+ [("off", "never_enabled"), ("unavailable", "invalid_state_file")],
+)
+def test_workbench_keeps_first_install_and_recovery_visible_for_live_shell(
+ monkeypatch, status, reason
+):
+ monkeypatch.setattr(ui_server, "desktop_computer_use_shell_is_live", lambda: True)
+ monkeypatch.setattr(
+ ui_server,
+ "effective_computer_use_status",
+ lambda: ComputerUseStatus(status, reason),
+ )
+
+ response = app.test_client().get(
+ "/api/desktop/computer-use/status",
+ base_url="http://127.0.0.1:5123",
+ )
+
+ assert response.status_code == 200
+ assert response.get_json() == {
+ "supported": True,
+ "status": status,
+ "reason": reason,
+ }
+
+
def test_workbench_status_supports_shell_started_runtime_from_the_same_state_source(
monkeypatch,
) -> None:
diff --git a/tests/test_desktop_runtime_stop.py b/tests/test_desktop_runtime_stop.py
index 834d4966c..ce44167d5 100644
--- a/tests/test_desktop_runtime_stop.py
+++ b/tests/test_desktop_runtime_stop.py
@@ -16,6 +16,7 @@ from __future__ import annotations
import contextlib
import errno
import json
+import logging
import os
import secrets
import shutil
@@ -157,7 +158,11 @@ def stop_env(monkeypatch):
return real_kill(pid, sig)
monkeypatch.setattr(os, "kill", recording_kill)
- monkeypatch.setattr(runtime, "stop_pid", lambda pid, timeout=5: effects["stop_pid"].append(pid) or False)
+ monkeypatch.setattr(
+ runtime,
+ "stop_pid",
+ lambda pid, timeout=5, **kwargs: effects["stop_pid"].append(pid) or False,
+ )
# The OpenCode server is stopped with its tool tree; record that stop the same way.
from modules.agents.opencode import server as opencode_server
@@ -219,6 +224,30 @@ def _assert_refused_untouched(stop_env, capsys, reason, *children):
assert all(_alive(child) for child in children)
+def test_service_shutdown_reaps_only_its_real_desktop_ui_child(spawn, monkeypatch):
+ import main as service_main
+
+ owned = spawn(RUNTIME_ID, "ui")
+ foreign = spawn(OTHER_ID, "ui")
+ monkeypatch.setattr(
+ desktop_runtime,
+ "desktop_caller_provenance",
+ lambda: frozenset({RUNTIME_ID}),
+ )
+ logger = logging.getLogger("test.desktop-runtime.service-shutdown")
+ paths.ensure_data_dirs()
+
+ paths.get_runtime_ui_pid_path().write_text(str(foreign.pid), encoding="utf-8")
+ service_main._stop_owned_desktop_runtime_ui(logger)
+ assert _alive(foreign)
+
+ paths.get_runtime_ui_pid_path().write_text(str(owned.pid), encoding="utf-8")
+ service_main._stop_owned_desktop_runtime_ui(logger)
+
+ owned.wait(timeout=10)
+ assert _alive(foreign)
+
+
def test_the_service_ui_installer_and_opencode_carrying_the_id_are_all_stopped(spawn, stop_env, bundle):
ui = spawn(RUNTIME_ID, "ui")
# Started by the UI, the installer tree is abandoned once the UI has stopped.
@@ -540,6 +569,18 @@ def test_with_nothing_running_and_a_free_lock_the_stop_succeeds(stop_env):
assert stop_env["status"] == [("stopped",)]
+def test_plain_stop_declares_ui_ownership_to_the_service(stop_env, monkeypatch):
+ captured = {}
+ monkeypatch.setattr(
+ runtime,
+ "stop_service",
+ lambda **kwargs: captured.update(kwargs) or False,
+ )
+
+ assert cli.cmd_stop() == 0
+ assert captured["shutdown_reason"] == "full_stop"
+
+
def test_a_full_stop_keeps_a_surviving_opencode_server_non_fatal(spawn, stop_env, monkeypatch):
# Only the desktop host replaces the bundle OpenCode runs from; a full stop
# also serves people and the upgrade and restart flows, and keeps its exit.
diff --git a/tests/test_macos_session_diagnostics.py b/tests/test_macos_session_diagnostics.py
index f64d7daf8..505ea6181 100644
--- a/tests/test_macos_session_diagnostics.py
+++ b/tests/test_macos_session_diagnostics.py
@@ -344,6 +344,8 @@ def test_service_main_owns_monitor_shutdown(monkeypatch) -> None:
import core.process_diagnostics
import main as service_main
import vibe.sentry_integration
+ from vibe import runtime
+ from vibe import desktop_runtime
calls: list[str] = []
handlers = {}
@@ -388,6 +390,16 @@ def test_service_main_owns_monitor_shutdown(monkeypatch) -> None:
monkeypatch.setattr(service_main, "acquire_service_instance_lock", lambda: calls.append("lock.acquire"))
monkeypatch.setattr(service_main, "release_service_instance_lock", lambda: calls.append("lock.release"))
+ monkeypatch.setattr(
+ desktop_runtime,
+ "desktop_caller_provenance",
+ lambda: frozenset({"desktop-runtime"}),
+ )
+ monkeypatch.setattr(
+ runtime,
+ "stop_ui",
+ lambda **kwargs: calls.append(f"desktop-ui.stop:{kwargs}") or True,
+ )
monkeypatch.setattr(service_main, "load_config", lambda: loaded_config)
monkeypatch.setattr(service_main, "setup_logging", lambda level: None)
monkeypatch.setattr(service_main, "apply_claude_sdk_patches", lambda: None)
@@ -425,3 +437,9 @@ def test_service_main_owns_monitor_shutdown(monkeypatch) -> None:
assert "loop.stop.scheduled" not in calls
assert calls.index("controller.run") < calls.index("diagnostics.stop")
assert calls.index("controller.after-signal") < calls.index("lock.release")
+ desktop_ui_stop = (
+ "desktop-ui.stop:{'stop_remote_access': False, "
+ "'runtime_ids': frozenset({'desktop-runtime'})}"
+ )
+ assert calls.index("controller.after-signal") < calls.index(desktop_ui_stop)
+ assert calls.index(desktop_ui_stop) < calls.index("lock.release")
diff --git a/tests/test_restart_supervisor.py b/tests/test_restart_supervisor.py
index 78ceb37a0..da4374de5 100644
--- a/tests/test_restart_supervisor.py
+++ b/tests/test_restart_supervisor.py
@@ -905,6 +905,25 @@ def test_stop_runtime_for_restart_stops_ui_and_service(monkeypatch, tmp_path):
assert sorted(calls) == ["stop_service", "stop_ui"]
+def test_service_only_restart_marks_shutdown_to_preserve_ui(monkeypatch):
+ captured = {}
+
+ def stop_service(**kwargs):
+ captured.update(kwargs)
+ return True
+
+ monkeypatch.setattr(runtime, "stop_service", stop_service)
+
+ assert restart_supervisor._stop_runtime_for_restart(
+ stop_ui=False,
+ runtime_ids=frozenset({"runtime-a"}),
+ )[4] is True
+ assert captured == {
+ "runtime_ids": frozenset({"runtime-a"}),
+ "shutdown_reason": "service_restart",
+ }
+
+
def test_schedule_restart_service_scope_adds_flag(monkeypatch, tmp_path):
"""A service-only restart passes ``--scope service`` to the supervisor job;
the default ``all`` scope adds no flag (back-compat for CLI/upgrade)."""
diff --git a/tests/test_service_logging_handlers.py b/tests/test_service_logging_handlers.py
index d9db86147..553a932c9 100644
--- a/tests/test_service_logging_handlers.py
+++ b/tests/test_service_logging_handlers.py
@@ -214,6 +214,16 @@ def test_shutdown_intent_missing_is_logged_not_ignored(monkeypatch, caplog):
assert "honoring signal" in caplog.text
+def test_only_unmanaged_service_shutdown_reaps_the_desktop_runtime_ui():
+ assert main._should_reap_desktop_runtime_ui(None) is True
+ assert main._should_reap_desktop_runtime_ui({"reason": "stop_service"}) is False
+ assert main._should_reap_desktop_runtime_ui({"reason": "stop_pid"}) is False
+ assert main._should_reap_desktop_runtime_ui({"reason": "service_restart"}) is False
+ assert main._should_reap_desktop_runtime_ui({"reason": "full_stop"}) is False
+ assert main._should_reap_desktop_runtime_ui({"reason": "restart"}) is False
+ assert main._should_reap_desktop_runtime_ui({"reason": "future_managed_reason"}) is False
+
+
def test_shutdown_signal_logging_is_lightweight(monkeypatch, caplog):
monkeypatch.setattr(main.os, "getpid", lambda: 123)
monkeypatch.setattr(main.os, "getppid", lambda: 1)
diff --git a/tests/test_ui_server_logs.py b/tests/test_ui_server_logs.py
index 49d94525a..118714d8f 100644
--- a/tests/test_ui_server_logs.py
+++ b/tests/test_ui_server_logs.py
@@ -1,13 +1,16 @@
from __future__ import annotations
+import logging
import os
+import signal
from datetime import datetime
from pathlib import Path
+import main as service_main
from config import paths
-from vibe.ui_server import app
-from vibe import runtime
from tests.ui_server_test_helpers import csrf_headers
+from vibe import runtime
+from vibe.ui_server import app
def _set_mtime(path, timestamp: str) -> None:
@@ -301,8 +304,25 @@ def test_control_stop_uses_locked_service_stop(monkeypatch, tmp_path):
paths.get_runtime_pid_path().write_text("12345", encoding="utf-8")
calls = []
+ monkeypatch.setattr(service_main, "shutdown_intent_required", lambda: True)
+ monkeypatch.setattr(
+ service_main,
+ "consume_shutdown_intent",
+ lambda pid, signum: {"pid": pid, "signum": signum, "reason": "stop_pid"},
+ )
+
+ def stop_service():
+ calls.append("stop_service")
+ intent = service_main._log_shutdown_intent(
+ logging.getLogger("test.web-control-stop"),
+ signal.SIGTERM,
+ )
+ if service_main._should_reap_desktop_runtime_ui(intent):
+ calls.append("service_reaped_ui")
+ return True
+
monkeypatch.setattr(runtime, "pid_alive", lambda pid: pid == 12345)
- monkeypatch.setattr(runtime, "stop_service", lambda: calls.append("stop_service") or True)
+ monkeypatch.setattr(runtime, "stop_service", stop_service)
monkeypatch.setattr(runtime, "stop_process", lambda pid_path: calls.append(("stop_process", pid_path)) or True)
client = app.test_client()
@@ -311,6 +331,7 @@ def test_control_stop_uses_locked_service_stop(monkeypatch, tmp_path):
assert response.status_code == 200
assert calls == ["stop_service"]
assert response.get_json()["status"]["state"] == "stopped"
+ assert response.get_json()["status"]["ui_pid"] == 67890
def test_control_restart_schedules_restart_job(monkeypatch, tmp_path):
diff --git a/ui/src/components/workbench/ComputerUseStatusLine.test.tsx b/ui/src/components/workbench/ComputerUseStatusLine.test.tsx
index 806b20540..6d9372236 100644
--- a/ui/src/components/workbench/ComputerUseStatusLine.test.tsx
+++ b/ui/src/components/workbench/ComputerUseStatusLine.test.tsx
@@ -3,6 +3,8 @@
import { cleanup, render, screen, waitFor } from '@testing-library/react';
import { afterEach, describe, expect, it, vi } from 'vitest';
+import en from '../../i18n/en.json';
+import zh from '../../i18n/zh.json';
import { ComputerUseStatusLine } from './ComputerUseStatusLine';
import { computerUseStatusCopy } from './computerUseStatusCopy';
@@ -29,6 +31,11 @@ describe('computerUseStatusCopy', () => {
expect(copy.detail).not.toContain('screen_recording');
});
+ it('keeps the Screen Recording relaunch guidance in both consumed locales', () => {
+ expect(en.workbench.home.computerUse.screenRecordingDetail).toContain('quit and reopen');
+ expect(zh.workbench.home.computerUse.screenRecordingDetail).toContain('退出并重新打开');
+ });
+
it('keeps unknown permission reasons localized', () => {
const copy = computerUseStatusCopy(
{ status: 'needs_permission', reason: 'future_permission' },
@@ -62,6 +69,7 @@ describe('computerUseStatusCopy', () => {
['endpoint_busy', 'endpointBusyDetail'],
['endpoint_unremovable', 'endpointUnremovableDetail'],
['socket_unreachable', 'socketUnreachableDetail'],
+ ['socket_path_too_long', 'socketPathTooLongDetail'],
])('maps error reason %s to dedicated localized remediation', (reason, key) => {
const detail = computerUseStatusCopy(
{ status: 'error', reason },
diff --git a/ui/src/components/workbench/computerUseStatusCopy.ts b/ui/src/components/workbench/computerUseStatusCopy.ts
index b2280135b..e223a21fc 100644
--- a/ui/src/components/workbench/computerUseStatusCopy.ts
+++ b/ui/src/components/workbench/computerUseStatusCopy.ts
@@ -29,6 +29,7 @@ export type ComputerUseCopyKey =
| 'workbench.home.computerUse.endpointBusyDetail'
| 'workbench.home.computerUse.endpointUnremovableDetail'
| 'workbench.home.computerUse.socketUnreachableDetail'
+ | 'workbench.home.computerUse.socketPathTooLongDetail'
| 'workbench.home.computerUse.unavailable'
| 'workbench.home.computerUse.unavailableDetail'
| 'workbench.home.computerUse.invalidStateFileDetail'
@@ -53,6 +54,7 @@ const errorDetailKeys: Record<string, ComputerUseCopyKey> = {
endpoint_busy: 'workbench.home.computerUse.endpointBusyDetail',
endpoint_unremovable: 'workbench.home.computerUse.endpointUnremovableDetail',
socket_unreachable: 'workbench.home.computerUse.socketUnreachableDetail',
+ socket_path_too_long: 'workbench.home.computerUse.socketPathTooLongDetail',
};
const unavailableDetailKeys: Record<string, ComputerUseCopyKey> = {
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 128875f9b..225102e34 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -54,7 +54,7 @@
"needsPermissionAccessibility": "Computer Use — Accessibility permission needed",
"needsPermissionScreenRecording": "Computer Use — Screen Recording needed; add Avibe in System Settings",
"screenRecordingTitle": "Screen Recording permission needed",
- "screenRecordingGuide": "Avibe opened System Settings → Privacy & Security → Screen & System Audio Recording. Click + or drag Avibe into the list, then enable it. Return to Avibe; it will start automatically after both permissions are granted.",
+ "screenRecordingGuide": "Avibe opened System Settings → Privacy & Security → Screen & System Audio Recording. Click + or drag Avibe into the list, then enable it. macOS may quit and reopen Avibe after the Screen Recording grant; return to Avibe when it reopens. It will start automatically after both permissions are granted.",
"needsRuntime": "Computer Use — restart the Avibe service",
"runtimeUnavailable": "Computer Use — waiting for the Avibe service",
"runtimeTooOld": "Computer Use — restart the Avibe service",
@@ -70,7 +70,8 @@
"driver_health_failed": "Computer Use — the managed driver failed its health check; reopen, update, or reinstall Avibe",
"endpoint_busy": "Computer Use — its previous driver endpoint is still busy; turn it off and on to retry",
"endpoint_unremovable": "Computer Use — its previous driver endpoint could not be cleared; turn it off and on to retry",
- "socket_unreachable": "Computer Use — the managed driver could not be reached; turn it off and on to retry"
+ "socket_unreachable": "Computer Use — the managed driver could not be reached; turn it off and on to retry",
+ "socket_path_too_long": "Computer Use — macOS could not create its driver socket; update or reinstall Avibe"
},
"invalidState": "Computer Use — state file needs repair; toggle to replace it",
"unavailable": "Computer Use — bundled driver unavailable",
@@ -2940,7 +2941,7 @@
"readyDetail": "The managed driver is available for the current Workbench session.",
"needsPermission": "Computer Use needs permission",
"accessibilityDetail": "Allow Avibe under Privacy & Security → Accessibility, then return here.",
- "screenRecordingDetail": "In Screen & System Audio Recording, click + or drag Avibe into the list, then enable it.",
+ "screenRecordingDetail": "In Screen & System Audio Recording, click + or drag Avibe into the list, then enable it. macOS may quit and reopen Avibe after the grant; return when it reopens.",
"unknownPermissionDetail": "Allow Avibe in the required Privacy & Security permission pane, then return here.",
"needsRuntime": "Computer Use is waiting for the Avibe service",
"runtimeUnavailableDetail": "The service is restarting or has not confirmed Computer Use support yet.",
@@ -2964,7 +2965,8 @@
"invalidStateFileDetail": "The native Computer Use state is damaged. Use the native toggle to replace it.",
"snapshotInvalidDetail": "The verified Computer Use tool snapshot is missing or changed. Update or reinstall the Avibe desktop app.",
"shellNotRunningDetail": "Open or reopen the Avibe desktop app to make Computer Use available.",
- "daemonUnreachableDetail": "The desktop driver is not reachable. Turn Computer Use off and on; reopen Avibe if it repeats."
+ "daemonUnreachableDetail": "The desktop driver is not reachable. Turn Computer Use off and on; reopen Avibe if it repeats.",
+ "socketPathTooLongDetail": "macOS could not create the managed driver socket. Update or reinstall the Avibe desktop app."
},
"continueOnPhone": "Continue on your phone",
"connectChatApps": "Connect chat apps in <settings>Settings</settings>"
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 1398b4feb..88e71a1e9 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -54,7 +54,7 @@
"needsPermissionAccessibility": "电脑操作 — 需要辅助功能权限",
"needsPermissionScreenRecording": "电脑操作 — 需要屏幕录制权限;请在系统设置中添加 Avibe",
"screenRecordingTitle": "需要屏幕录制权限",
- "screenRecordingGuide": "Avibe 已打开“系统设置 → 隐私与安全性 → 屏幕与系统音频录制”。请点击 +,或将 Avibe 拖入列表,然后启用它。授权两个权限后返回 Avibe,应用会自动启动。",
+ "screenRecordingGuide": "Avibe 已打开“系统设置 → 隐私与安全性 → 屏幕与系统音频录制”。请点击 +,或将 Avibe 拖入列表,然后启用它。获得“屏幕录制”授权后,macOS 可能会退出并重新打开 Avibe;应用重新打开后请返回。两个权限都授权后,应用会自动启动。",
"needsRuntime": "电脑操作 — 请重启 Avibe 服务",
"runtimeUnavailable": "电脑操作 — 正在等待 Avibe 服务",
"runtimeTooOld": "电脑操作 — 请重启 Avibe 服务",
@@ -70,7 +70,8 @@
"driver_health_failed": "电脑操作 — 受管理的驱动健康检查失败;请重新打开、更新或重新安装 Avibe",
"endpoint_busy": "电脑操作 — 上一个驱动端点仍在使用;请关闭后重新开启",
"endpoint_unremovable": "电脑操作 — 无法清理上一个驱动端点;请关闭后重新开启",
- "socket_unreachable": "电脑操作 — 无法连接受管理的驱动;请关闭后重新开启"
+ "socket_unreachable": "电脑操作 — 无法连接受管理的驱动;请关闭后重新开启",
+ "socket_path_too_long": "电脑操作 — macOS 无法创建驱动端点;请更新或重新安装 Avibe"
},
"invalidState": "电脑操作 — 状态文件需要修复;切换开关可替换",
"unavailable": "电脑操作 — 内置驱动不可用",
@@ -2940,7 +2941,7 @@
"readyDetail": "当前工作台会话可以使用受管理的驱动。",
"needsPermission": "电脑操作需要权限",
"accessibilityDetail": "请在“隐私与安全性 → 辅助功能”中允许 Avibe,然后返回这里。",
- "screenRecordingDetail": "在“屏幕与系统音频录制”中点击 +,或将 Avibe 拖入列表,然后启用它。",
+ "screenRecordingDetail": "在“屏幕与系统音频录制”中点击 +,或将 Avibe 拖入列表,然后启用它。授权后 macOS 可能会退出并重新打开 Avibe;应用重新打开后请返回。",
"unknownPermissionDetail": "请在“隐私与安全性”中允许 Avibe 所需的权限,然后返回这里。",
"needsRuntime": "电脑操作正在等待 Avibe 服务",
"runtimeUnavailableDetail": "服务正在重启,或尚未确认支持电脑操作。",
@@ -2964,7 +2965,8 @@
"invalidStateFileDetail": "原生电脑操作状态已损坏。请使用原生开关重新生成状态。",
"snapshotInvalidDetail": "已验证的电脑操作工具快照缺失或发生变化。请更新或重新安装 Avibe 桌面应用。",
"shellNotRunningDetail": "请打开或重新打开 Avibe 桌面应用,以使用电脑操作。",
- "daemonUnreachableDetail": "桌面驱动当前无法连接。请关闭并重新开启电脑操作;如果问题重复出现,请重新打开 Avibe。"
+ "daemonUnreachableDetail": "桌面驱动当前无法连接。请关闭并重新开启电脑操作;如果问题重复出现,请重新打开 Avibe。",
+ "socketPathTooLongDetail": "macOS 无法创建受管理的驱动端点。请更新或重新安装 Avibe 桌面应用。"
},
"continueOnPhone": "在手机 APP 上继续",
"connectChatApps": "聊天应用可在<settings>设置</settings>中连接"
diff --git a/vibe/cli.py b/vibe/cli.py
index d0c16c275..eb58b2fee 100644
--- a/vibe/cli.py
+++ b/vibe/cli.py
@@ -14025,7 +14025,7 @@ def cmd_stop(*, expect_runtime_id: str | None = None):
ui_was_running = _pid_file_points_to_live_process(paths.get_runtime_ui_pid_path())
try:
- service_stopped = runtime.stop_service(runtime_ids=provenance)
+ service_stopped = runtime.stop_service(runtime_ids=provenance, shutdown_reason="full_stop")
ui_stopped = runtime.stop_ui(runtime_ids=provenance)
except runtime.DesktopRuntimeClaimRefused as refusal:
_print_provenance_refusal("desktopRuntime.stopRefused", refusal)
diff --git a/vibe/restart_supervisor.py b/vibe/restart_supervisor.py
index 92f9fe96b..3e8ab8b2f 100644
--- a/vibe/restart_supervisor.py
+++ b/vibe/restart_supervisor.py
@@ -335,9 +335,13 @@ def _stop_ui_for_restart(runtime_ids: frozenset[str]) -> tuple[bool, dict[str, f
return bool(stopped), timings, _rounded_seconds(time.monotonic() - started_at), _read_recorded_ui_pid()
-def _stop_service_for_restart(runtime_ids: frozenset[str]) -> tuple[bool, float]:
+def _stop_service_for_restart(
+ runtime_ids: frozenset[str],
+ *,
+ shutdown_reason: str = "restart",
+) -> tuple[bool, float]:
started_at = time.monotonic()
- stopped = runtime.stop_service(runtime_ids=runtime_ids)
+ stopped = runtime.stop_service(runtime_ids=runtime_ids, shutdown_reason=shutdown_reason)
return bool(stopped), _rounded_seconds(time.monotonic() - started_at)
@@ -349,7 +353,10 @@ def _stop_runtime_for_restart(
# Service-only restart: leave the UI process untouched so the open Web
# UI survives. Report its still-recorded pid; ``ui_stopped`` is True only
# to satisfy the "did the UI stop" guard (we deliberately did not stop it).
- service_stopped, stop_service_seconds = _stop_service_for_restart(runtime_ids)
+ service_stopped, stop_service_seconds = _stop_service_for_restart(
+ runtime_ids,
+ shutdown_reason="service_restart",
+ )
return True, {}, 0.0, _read_recorded_ui_pid(), service_stopped, stop_service_seconds
with ThreadPoolExecutor(max_workers=2, thread_name_prefix="avibe-restart-stop") as executor:
ui_future = executor.submit(_stop_ui_for_restart, runtime_ids)
diff --git a/vibe/runtime.py b/vibe/runtime.py
index 33e49629c..d9212e246 100644
--- a/vibe/runtime.py
+++ b/vibe/runtime.py
@@ -1059,7 +1059,7 @@ def _pid_reservation_is_fresh(pid_path: Path, pid: int, *, max_age: float = SERV
return time.time() - latest_signal <= max_age
-def stop_pid(pid: int, timeout: float = 5) -> bool:
+def stop_pid(pid: int, timeout: float = 5, *, shutdown_reason: str = "stop_pid") -> bool:
if not isinstance(pid, int) or pid <= 0:
return False
if not pid_alive(pid):
@@ -1068,7 +1068,7 @@ def stop_pid(pid: int, timeout: float = 5) -> bool:
if os.name == "nt":
return _terminate_process_windows(pid, timeout=timeout)
- write_shutdown_intent(pid, signum=signal.SIGTERM, reason="stop_pid")
+ write_shutdown_intent(pid, signum=signal.SIGTERM, reason=shutdown_reason)
try:
logger.info(
"Sending managed SIGTERM to pid=%s command=%s",
@@ -2516,7 +2516,11 @@ def start_ui(
return pid
-def stop_service(*, runtime_ids: frozenset[str] = frozenset()):
+def stop_service(
+ *,
+ runtime_ids: frozenset[str] = frozenset(),
+ shutdown_reason: str = "stop_service",
+):
"""Stop every service process; with ``runtime_ids``, only when all are that Runtime's.
The ids are checked on the very processes this stop selected, before any
@@ -2542,7 +2546,10 @@ def stop_service(*, runtime_ids: frozenset[str] = frozenset()):
stopped_all = True
for pid in target_pids:
- stopped = stop_pid(pid, timeout=5)
+ if shutdown_reason == "stop_service":
+ stopped = stop_pid(pid, timeout=5)
+ else:
+ stopped = stop_pid(pid, timeout=5, shutdown_reason=shutdown_reason)
if stopped:
_clear_service_pid_reservation(pid)
continue