Skip to content

Commit 511e865

Browse files
fix(desktop): stop orchestrator daemon cleanly on app close (anomalyco#655)
1 parent 581f200 commit 511e865

3 files changed

Lines changed: 133 additions & 25 deletions

File tree

‎packages/desktop/src-tauri/src/lib.rs‎

Lines changed: 25 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,21 @@ use orchestrator::manager::OrchestratorManager;
5555
use tauri::Manager;
5656
use workspace::watch::WorkspaceWatchState;
5757

58+
fn stop_managed_services(app_handle: &tauri::AppHandle) {
59+
if let Ok(mut engine) = app_handle.state::<EngineManager>().inner.lock() {
60+
EngineManager::stop_locked(&mut engine);
61+
}
62+
if let Ok(mut orchestrator) = app_handle.state::<OrchestratorManager>().inner.lock() {
63+
OrchestratorManager::stop_locked(&mut orchestrator);
64+
}
65+
if let Ok(mut openwork_server) = app_handle.state::<OpenworkServerManager>().inner.lock() {
66+
OpenworkServerManager::stop_locked(&mut openwork_server);
67+
}
68+
if let Ok(mut opencode_router) = app_handle.state::<OpenCodeRouterManager>().inner.lock() {
69+
OpenCodeRouterManager::stop_locked(&mut opencode_router);
70+
}
71+
}
72+
5873
pub fn run() {
5974
let builder = tauri::Builder::default()
6075
.plugin(tauri_plugin_deep_link::init())
@@ -133,27 +148,16 @@ pub fn run() {
133148
// Best-effort cleanup on app exit. Without this, background sidecars can keep
134149
// running after the UI quits (especially during dev), leading to multiple
135150
// orchestrator/opencode/openwork-server processes and stale ports.
136-
app.run(|app_handle, event| {
137-
if matches!(
138-
event,
139-
tauri::RunEvent::ExitRequested { .. } | tauri::RunEvent::Exit
140-
) {
141-
if let Ok(mut engine) = app_handle.state::<EngineManager>().inner.lock() {
142-
EngineManager::stop_locked(&mut engine);
143-
}
144-
if let Ok(mut orchestrator) = app_handle.state::<OrchestratorManager>().inner.lock() {
145-
OrchestratorManager::stop_locked(&mut orchestrator);
146-
}
147-
if let Ok(mut openwork_server) =
148-
app_handle.state::<OpenworkServerManager>().inner.lock()
149-
{
150-
OpenworkServerManager::stop_locked(&mut openwork_server);
151-
}
152-
if let Ok(mut opencode_router) =
153-
app_handle.state::<OpenCodeRouterManager>().inner.lock()
154-
{
155-
OpenCodeRouterManager::stop_locked(&mut opencode_router);
156-
}
151+
app.run(|app_handle, event| match event {
152+
tauri::RunEvent::ExitRequested { .. } | tauri::RunEvent::Exit => {
153+
stop_managed_services(&app_handle);
154+
}
155+
tauri::RunEvent::WindowEvent {
156+
event: tauri::WindowEvent::CloseRequested { .. },
157+
..
158+
} => {
159+
stop_managed_services(&app_handle);
157160
}
161+
_ => {}
158162
});
159163
}

‎packages/desktop/src-tauri/src/orchestrator/manager.rs‎

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -20,12 +20,28 @@ pub struct OrchestratorState {
2020

2121
impl OrchestratorManager {
2222
pub fn stop_locked(state: &mut OrchestratorState) {
23+
let data_dir = state
24+
.data_dir
25+
.clone()
26+
.unwrap_or_else(orchestrator::resolve_orchestrator_data_dir);
27+
28+
let shutdown_requested = match orchestrator::request_orchestrator_shutdown(&data_dir) {
29+
Ok(requested) => requested,
30+
Err(error) => {
31+
eprintln!("[orchestrator] Failed to request shutdown: {error}");
32+
false
33+
}
34+
};
35+
2336
if let Some(child) = state.child.take() {
24-
let _ = child.kill();
25-
}
26-
if let Some(dir) = state.data_dir.as_deref() {
27-
orchestrator::clear_orchestrator_auth(dir);
37+
// Prefer daemon-owned graceful shutdown so openwork-orchestrator can
38+
// terminate its managed OpenCode child before exiting.
39+
if !shutdown_requested {
40+
let _ = child.kill();
41+
}
2842
}
43+
44+
orchestrator::clear_orchestrator_auth(&data_dir);
2945
state.child_exited = true;
3046
state.data_dir = None;
3147
state.last_stdout = None;

‎packages/desktop/src-tauri/src/orchestrator/mod.rs‎

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -183,6 +183,31 @@ pub fn wait_for_orchestrator(
183183
Err(last_error.unwrap_or_else(|| "Timed out waiting for orchestrator".to_string()))
184184
}
185185

186+
pub fn request_orchestrator_shutdown(data_dir: &str) -> Result<bool, String> {
187+
let base_url = read_orchestrator_state(data_dir)
188+
.and_then(|state| state.daemon.map(|daemon| daemon.base_url))
189+
.map(|url| url.trim().to_string())
190+
.filter(|url| !url.is_empty());
191+
192+
let Some(base_url) = base_url else {
193+
return Ok(false);
194+
};
195+
196+
let url = format!("{}/shutdown", base_url.trim_end_matches('/'));
197+
let agent = ureq::AgentBuilder::new()
198+
.timeout(std::time::Duration::from_millis(1500))
199+
.build();
200+
201+
agent
202+
.post(&url)
203+
.set("Accept", "application/json")
204+
.set("Content-Type", "application/json")
205+
.send_string("")
206+
.map_err(|e| format!("Failed to request orchestrator shutdown at {url}: {e}"))?;
207+
208+
Ok(true)
209+
}
210+
186211
pub fn spawn_orchestrator_daemon(
187212
app: &AppHandle,
188213
options: &OrchestratorSpawnOptions,
@@ -257,6 +282,69 @@ pub fn spawn_orchestrator_daemon(
257282
.map_err(|e| format!("Failed to start orchestrator: {e}"))
258283
}
259284

285+
#[cfg(test)]
286+
mod tests {
287+
use super::request_orchestrator_shutdown;
288+
use std::fs;
289+
use std::io::{Read, Write};
290+
use std::net::TcpListener;
291+
use std::thread;
292+
use uuid::Uuid;
293+
294+
#[test]
295+
fn request_shutdown_returns_false_without_state() {
296+
let dir = std::env::temp_dir().join(format!(
297+
"openwork-orchestrator-shutdown-missing-{}",
298+
Uuid::new_v4()
299+
));
300+
fs::create_dir_all(&dir).expect("create test dir");
301+
302+
let stopped = request_orchestrator_shutdown(&dir.to_string_lossy()).expect("request");
303+
assert!(!stopped);
304+
305+
let _ = fs::remove_dir_all(dir);
306+
}
307+
308+
#[test]
309+
fn request_shutdown_posts_to_daemon_endpoint() {
310+
let listener = TcpListener::bind("127.0.0.1:0").expect("bind shutdown listener");
311+
let port = listener.local_addr().expect("listener addr").port();
312+
313+
let handle = thread::spawn(move || {
314+
let (mut stream, _) = listener.accept().expect("accept shutdown request");
315+
let mut buffer = [0u8; 2048];
316+
let bytes = stream.read(&mut buffer).expect("read request");
317+
let request = String::from_utf8_lossy(&buffer[..bytes]);
318+
assert!(request.starts_with("POST /shutdown "));
319+
stream
320+
.write_all(
321+
b"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: 11\r\nConnection: close\r\n\r\n{\"ok\":true}",
322+
)
323+
.expect("write response");
324+
});
325+
326+
let dir = std::env::temp_dir().join(format!(
327+
"openwork-orchestrator-shutdown-state-{}",
328+
Uuid::new_v4()
329+
));
330+
fs::create_dir_all(&dir).expect("create state dir");
331+
let state_path = dir.join("openwork-orchestrator-state.json");
332+
fs::write(
333+
&state_path,
334+
format!(
335+
"{{\"daemon\":{{\"pid\":1,\"port\":{port},\"baseUrl\":\"http://127.0.0.1:{port}\",\"startedAt\":1}}}}"
336+
),
337+
)
338+
.expect("write state file");
339+
340+
let stopped = request_orchestrator_shutdown(&dir.to_string_lossy()).expect("request");
341+
assert!(stopped);
342+
343+
handle.join().expect("server thread");
344+
let _ = fs::remove_dir_all(dir);
345+
}
346+
}
347+
260348
pub fn orchestrator_status_from_state(
261349
data_dir: &str,
262350
last_error: Option<String>,

0 commit comments

Comments
 (0)