Skip to content

Computer use CLI for AI agents

fix: keep a started sandbox running after its launcher exits (#672)

Lahfir2f6507051f67
diff --git a/apps/docs/content/docs/sandboxes/macos.mdx b/apps/docs/content/docs/sandboxes/macos.mdx
index 5f060bde7..2e39f6cfc 100644
--- a/apps/docs/content/docs/sandboxes/macos.mdx
+++ b/apps/docs/content/docs/sandboxes/macos.mdx
@@ -82,7 +82,7 @@ agent-desktop sandbox start work --window --set title="Review build"
The window's title is the sandbox name unless you pass `--set title=<text>`. Closing the window shuts the VM down. A sandbox that is already running headless must be stopped before it can open a window.
-`start` answers `running` only once the guest answers over SSH. Until then it answers `working`; repeat `sandbox status` before `sandbox exec`.
+`start` answers `running` only once the guest answers over SSH. Until then it answers `working`; repeat `sandbox status` before `sandbox exec`. The VM host runs in its own session, so a started sandbox keeps running after the command that started it exits, including when the caller that launched it is later terminated.
## Limits
diff --git a/providers/macos/vmhost.swift b/providers/macos/vmhost.swift
index 8f0b1440c..45dfef53a 100644
--- a/providers/macos/vmhost.swift
+++ b/providers/macos/vmhost.swift
@@ -776,6 +776,19 @@ struct IpCommand {
}
}
+/// Leaves the caller's POSIX session so a launcher that exits or is killed does not take a running sandbox
+/// host down with it. A process-group leader may not start a session, so one first joins its parent's group, or its session leader's when the parent is gone.
+enum CallerSession {
+ static func leave() {
+ if getsid(0) == getpid() || setsid() != -1 { return }
+ for group in [getpgid(getppid()), getsid(0)] {
+ if setpgid(0, group) == 0, setsid() != -1 { return }
+ }
+ let reason = String(cString: strerror(errno))
+ FileHandle.standardError.write(Data("vmhost: could not leave the caller's session, so the sandbox stops with its launcher: \(reason)\n".utf8))
+ }
+}
+
enum VMHost {
static func run(_ arguments: [String]) -> Int32 {
do {
@@ -785,6 +798,7 @@ enum VMHost {
case "install":
try InstallCommand.execute(rest)
case "run":
+ CallerSession.leave()
try RunCommand.execute(rest)
case "clone":
try CloneCommand.execute(rest)