返回 CodeWhale
control_socket.rs
根目录 / crates / tui / src / tui / control_socket.rs
1 //! Per-session control socket — the supervised-operation control surface.
2 //!
3 //! This module is the codewhale side of "session control/communication API
4 //! for supervised operation" (#5533). When the
5 //! `[control_socket]` config table sets `enabled = true`, the interactive
6 //! TUI binds one unix domain socket per *running* session at
7 //!
8 //! ```text
9 //! <sessions-dir>/<session-id>/control.sock (mode 0600)
10 //! ```
11 //!
12 //! where `<sessions-dir>` is the same directory the session store uses
13 //! (`SessionManager::sessions_dir`, typically `~/.codewhale/sessions`) and
14 //! `<session-id>` is the session the TUI currently owns. The socket lives
15 //! inside the per-session artifact directory, so `delete_session` and the
16 //! orphan-reclaim sweep remove it together with the rest of the session's
17 //! artifacts, and a crashed process leaves at most a stale socket file that
18 //! the next bind takes over (connect-probe + unlink, a known-good
19 //! socket-ownership pattern).
20 //!
21 //! # Transport
22 //!
23 //! Newline-framed JSON-RPC, one request per connection: connect, write one
24 //! request line, read one response line, close. Requests:
25 //!
26 //! ```json
27 //! {"id":"1","method":"message","params":{"text":"hello"}}
28 //! {"id":"2","method":"interrupt","params":{}}
29 //! {"id":"3","method":"status","params":{}}
30 //! ```
31 //!
32 //! Success responses echo the id and carry a `type`-tagged result:
33 //!
34 //! ```json
35 //! {"id":"1","result":{"type":"message_sent","delivery":"dispatched"}}
36 //! {"id":"2","result":{"type":"interrupted","cancelled":true}}
37 //! {"id":"3","result":{"type":"status","turn_state":"idle","goal":{"objective":null,"status":"active","paused":false}}}
38 //! ```
39 //!
40 //! Failures are `{"id":…,"error":{"code":…,"message":…}}` with codes
41 //! `invalid_request`, `command_error`, `timeout`, and `server_unavailable`.
42 //!
43 //! # Verbs
44 //!
45 //! - `message` — delivers `text` as a structured user message through the
46 //! ordinary composer dispatch path (`dispatch_composer_message`): dispatched
47 //! immediately when the app is idle, queued when a turn is in flight
48 //! (queued delivery is the default under load, matching the supervisor
49 //! contract). After a failed or interrupted turn, queued messages remain
50 //! held until `Enter` or `/queue send`. The response's `delivery` field
51 //! reports which happened.
52 //! - `interrupt` — the exact Esc-shaped "cancel the active turn" body
53 //! (`escape_cancel_request`), shared with the Esc key path so the two
54 //! cannot drift. `cancelled` reports whether active work was in flight.
55 //! - `status` — answered by the socket thread directly from a snapshot the
56 //! event loop republishes every iteration: `turn_state`
57 //! (`idle | in_progress | waiting`) and `goal`
58 //! (`objective`, `status`, `paused`).
59 //!
60 //! # Wiring (insertion points)
61 //!
62 //! 1. `run_event_loop` (crates/tui/src/tui/ui/event_loop.rs) constructs a
63 //! [`SessionControl`] once and, at the top of the frame loop, calls
64 //! [`SessionControl::reconcile`] (bind/rebind/unbind when the owned
65 //! session id changes), [`SessionControl::update_status`] (publish the
66 //! snapshot for `status`), and [`SessionControl::drain`] (execute queued
67 //! verbs on the UI thread).
68 //! 2. The socket runs on background threads; verbs that touch UI state cross
69 //! to the event loop over an mpsc channel and answer over a response
70 //! channel with a 5 s timeout (a dispatch-to-app pattern).
71 //!
72 //! The feature is off unless `[control_socket] enabled = true`; an unset
73 //! table changes nothing. Unix-only: on non-unix platforms the config key
74 //! parses but binding is refused at runtime.
75
76 use std::io;
77 #[cfg(unix)]
78 use std::io::{BufRead, BufReader, Read, Write};
79 use std::path::{Path, PathBuf};
80 use std::sync::atomic::{AtomicBool, Ordering};
81 use std::sync::{Arc, Mutex, mpsc};
82 use std::time::{Duration, Instant};
83
84 #[cfg(unix)]
85 use std::fs;
86 #[cfg(unix)]
87 use std::os::unix::fs::FileTypeExt;
88 #[cfg(unix)]
89 use std::os::unix::net::{UnixListener, UnixStream};
90 #[cfg(unix)]
91 use std::thread;
92
93 #[cfg(any(unix, test))]
94 use serde::Deserialize;
95 use serde::Serialize;
96
97 use crate::tui::app::{App, ComposerSubmitAction, QueuedMessage, SubmitDisposition};
98 use crate::tui::ui::{DispatchRecovery, dispatch_composer_message, escape_cancel_request};
99 use codewhale_tui_kit::streaming::StreamDisplayClock;
100
101 /// Socket file name inside the per-session artifact directory.
102 pub(crate) const SOCKET_FILE_NAME: &str = "control.sock";
103
104 /// Hard cap on one request line (initial-request bound).
105 #[cfg(unix)]
106 const MAX_REQUEST_BYTES: usize = 1024 * 1024;
107
108 /// Accept-loop poll interval while the listener is idle.
109 #[cfg(unix)]
110 const CONNECTION_POLL_INTERVAL: Duration = Duration::from_millis(100);
111
112 /// A client that connects and never sends is dropped after this long.
113 #[cfg(unix)]
114 const REQUEST_READ_TIMEOUT: Duration = Duration::from_secs(5);
115
116 /// Response writes give up after this long rather than blocking forever.
117 #[cfg(unix)]
118 const RESPONSE_WRITE_TIMEOUT: Duration = Duration::from_secs(5);
119
120 /// How long a verb may wait for the event loop to handle it
121 /// (`APP_RESPONSE_TIMEOUT`).
122 #[cfg(unix)]
123 const DISPATCH_RESPONSE_TIMEOUT: Duration = Duration::from_secs(5);
124
125 /// Minimum pause between bind retries after a refused takeover, so another
126 /// live process holding the socket cannot turn the per-frame reconcile into
127 /// a connect-probe and warn-log flood. Shortened under `#[cfg(test)]` so the
128 /// backoff itself is testable without sleeping for seconds.
129 #[cfg(not(test))]
130 const BIND_RETRY_BACKOFF: Duration = Duration::from_secs(5);
131 #[cfg(test)]
132 const BIND_RETRY_BACKOFF: Duration = Duration::from_millis(200);
133
134 // ── Protocol ────────────────────────────────────────────────────────────────
135
136 /// One request line: `{"id": … , "method": … , "params": …}`.
137 #[cfg(any(unix, test))]
138 #[derive(Debug, Deserialize)]
139 struct Request {
140 id: String,
141 #[serde(flatten)]
142 method: Method,
143 }
144
145 #[cfg(any(unix, test))]
146 #[derive(Debug, Deserialize)]
147 #[serde(tag = "method", content = "params", rename_all = "snake_case")]
148 enum Method {
149 Message(MessageParams),
150 Interrupt(EmptyParams),
151 Status(EmptyParams),
152 }
153
154 #[cfg(any(unix, test))]
155 #[derive(Debug, Deserialize)]
156 struct MessageParams {
157 text: String,
158 }
159
160 #[cfg(any(unix, test))]
161 #[derive(Debug, Deserialize)]
162 struct EmptyParams {}
163
164 /// A verb the socket thread hands to the event loop, plus the way back.
165 #[derive(Debug)]
166 pub(crate) struct PendingCommand {
167 pub(crate) id: String,
168 pub(crate) command: ControlCommand,
169 pub(crate) respond_to: mpsc::Sender<String>,
170 /// Set by whichever side acts first: the event loop about to execute the
171 /// verb, or the socket side giving up on it at the response timeout. A
172 /// verb the client was told timed out is therefore never executed later,
173 /// so retrying it cannot deliver a message twice or interrupt a later
174 /// turn.
175 claimed: Arc<AtomicBool>,
176 }
177
178 impl PendingCommand {
179 /// Claim the verb for execution. `false` means the client already gave
180 /// up on it (and was told so): drop it without running it.
181 pub(crate) fn claim(&self) -> bool {
182 !self.claimed.swap(true, Ordering::AcqRel)
183 }
184 }
185
186 #[cfg_attr(not(unix), allow(dead_code))]
187 #[derive(Debug)]
188 pub(crate) enum ControlCommand {
189 Message { text: String },
190 Interrupt,
191 }
192
193 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
194 #[serde(rename_all = "snake_case")]
195 pub(crate) enum TurnState {
196 Idle,
197 InProgress,
198 Waiting,
199 }
200
201 /// Goal state visible to supervisors over the `status` verb.
202 #[derive(Debug, Clone, PartialEq, Eq, Serialize)]
203 pub(crate) struct GoalSnapshot {
204 pub(crate) objective: Option<String>,
205 pub(crate) status: String,
206 pub(crate) paused: bool,
207 }
208
209 /// The `status` answer, republished by the event loop every iteration.
210 #[derive(Debug, Clone, PartialEq, Eq)]
211 pub(crate) struct StatusSnapshot {
212 pub(crate) turn_state: TurnState,
213 pub(crate) goal: GoalSnapshot,
214 }
215
216 /// Success envelope (`SuccessResponse` shape).
217 #[derive(Debug, Serialize)]
218 struct SuccessResponse {
219 id: String,
220 result: ResponseResult,
221 }
222
223 #[cfg_attr(not(unix), allow(dead_code))]
224 #[derive(Debug, Serialize)]
225 #[serde(tag = "type", rename_all = "snake_case")]
226 enum ResponseResult {
227 MessageSent {
228 delivery: &'static str,
229 },
230 Interrupted {
231 cancelled: bool,
232 },
233 Status {
234 turn_state: TurnState,
235 goal: GoalSnapshot,
236 },
237 }
238
239 /// Error envelope (`ErrorResponse` shape).
240 #[derive(Debug, Serialize)]
241 struct ErrorResponse {
242 id: String,
243 error: ErrorBody,
244 }
245
246 #[derive(Debug, Serialize)]
247 struct ErrorBody {
248 code: &'static str,
249 message: String,
250 }
251
252 fn response_ok(id: String, result: ResponseResult) -> String {
253 serde_json::to_string(&SuccessResponse { id, result }).unwrap_or_else(|_| {
254 r#"{"id":"","error":{"code":"internal_error","message":"failed to encode response"}}"#
255 .to_string()
256 })
257 }
258
259 fn response_error(id: &str, code: &'static str, message: String) -> String {
260 serde_json::to_string(&ErrorResponse {
261 id: id.to_string(),
262 error: ErrorBody { code, message },
263 })
264 .unwrap_or_else(|_| {
265 r#"{"id":"","error":{"code":"internal_error","message":"failed to encode response"}}"#
266 .to_string()
267 })
268 }
269
270 // ── UI-side handle ──────────────────────────────────────────────────────────
271
272 /// The event-loop side of the control surface. Cheap to poll every frame:
273 /// reconcile/update/drain are all no-ops (or near no-ops) when disabled.
274 pub(crate) struct SessionControl {
275 enabled: bool,
276 sessions_dir: Option<PathBuf>,
277 bound_session: Option<String>,
278 socket: Option<ControlSocketHandle>,
279 commands_tx: Option<mpsc::Sender<PendingCommand>>,
280 commands_rx: mpsc::Receiver<PendingCommand>,
281 status: Arc<Mutex<StatusSnapshot>>,
282 /// When the last bind attempt failed (e.g. another live process owns the
283 /// socket), retries for *that session* back off so a refused takeover
284 /// cannot become a per-frame connect-probe and log flood.
285 last_bind_failure: Option<(String, Instant)>,
286 }
287
288 impl SessionControl {
289 pub(crate) fn new(enabled: bool) -> Self {
290 Self::new_with_sessions_dir(enabled, None)
291 }
292
293 /// Test seam: `sessions_dir` bypasses `SessionManager::default_location()`
294 /// so tests never touch the real `~/.codewhale/sessions`.
295 fn new_with_sessions_dir(enabled: bool, sessions_dir: Option<PathBuf>) -> Self {
296 let (commands_tx, commands_rx) = mpsc::channel();
297 Self {
298 enabled,
299 sessions_dir,
300 bound_session: None,
301 socket: None,
302 commands_tx: enabled.then_some(commands_tx),
303 commands_rx,
304 status: Arc::new(Mutex::new(StatusSnapshot {
305 turn_state: TurnState::Idle,
306 goal: GoalSnapshot {
307 objective: None,
308 status: "active".to_string(),
309 paused: false,
310 },
311 })),
312 last_bind_failure: None,
313 }
314 }
315
316 /// Bind/rebind the socket when the owned session id appears or changes,
317 /// and unbind when it disappears (session switch or teardown). Runs on
318 /// the event-loop thread but only spawns a thread on an actual change.
319 pub(crate) fn reconcile(&mut self, current_session_id: Option<&str>) {
320 if !self.enabled {
321 return;
322 }
323 let Some(id) = current_session_id
324 .map(str::trim)
325 .filter(|id| !id.is_empty())
326 else {
327 // No session yet (fresh session before the first snapshot) or
328 // the id went away: release whatever we hold.
329 self.socket = None;
330 self.bound_session = None;
331 return;
332 };
333 if self.bound_session.as_deref() == Some(id) {
334 return;
335 }
336 // A refused takeover must not retry every frame: back off so the
337 // connect probe and its warning log run at most every few seconds.
338 // Keyed on the session id so switching sessions is never delayed by
339 // another session's refusal.
340 if let Some((failed_id, failed_at)) = &self.last_bind_failure
341 && failed_id == id
342 && failed_at.elapsed() < BIND_RETRY_BACKOFF
343 {
344 return;
345 }
346 // Session id changed: drop the old listener first so the socket file
347 // is unlinked before the new one binds.
348 self.socket = None;
349 self.bound_session = None;
350
351 let sessions_dir = match self.sessions_dir.clone() {
352 Some(dir) => dir,
353 None => {
354 let manager =
355 match codewhale_engine::session_manager::SessionManager::default_location() {
356 Ok(manager) => manager,
357 Err(error) => {
358 tracing::warn!(%error, "control socket: cannot resolve the sessions directory");
359 return;
360 }
361 };
362 let dir = manager.sessions_dir().to_path_buf();
363 self.sessions_dir = Some(dir.clone());
364 dir
365 }
366 };
367 let Some(commands_tx) = self.commands_tx.clone() else {
368 return;
369 };
370 match bind_control_socket(&sessions_dir, id, commands_tx, Arc::clone(&self.status)) {
371 Ok(handle) => {
372 tracing::info!(
373 session = id,
374 path = %sessions_dir.join(id).join(SOCKET_FILE_NAME).display(),
375 "control socket listening"
376 );
377 self.bound_session = Some(id.to_string());
378 self.socket = Some(handle);
379 self.last_bind_failure = None;
380 }
381 Err(error) => {
382 tracing::warn!(session = id, %error, "control socket: bind failed; session control unavailable");
383 self.last_bind_failure = Some((id.to_string(), Instant::now()));
384 }
385 }
386 }
387
388 /// Republish the `status` snapshot from the current app state. Runs every
389 /// frame; the mutex write happens only when something actually changed.
390 pub(crate) fn update_status(&self, app: &App) {
391 if !self.enabled {
392 return;
393 }
394 let snapshot = snapshot_from_app(app);
395 let Ok(mut guard) = self.status.try_lock() else {
396 return; // the socket thread is answering a `status` request; skip a frame
397 };
398 if *guard != snapshot {
399 *guard = snapshot;
400 }
401 }
402
403 /// Execute verbs queued by the socket thread on the UI thread and answer
404 /// their clients.
405 pub(crate) async fn drain(
406 &mut self,
407 app: &mut App,
408 config: &codewhale_runtime::config::Config,
409 engine_handle: &codewhale_engine::core::engine::EngineHandle,
410 current_streaming_text: &mut String,
411 stream_display_clock: &mut StreamDisplayClock,
412 ) {
413 if !self.enabled {
414 return;
415 }
416 while let Ok(pending) = self.commands_rx.try_recv() {
417 if !pending.claim() {
418 continue;
419 }
420 let response = execute_command(
421 app,
422 config,
423 engine_handle,
424 current_streaming_text,
425 stream_display_clock,
426 pending.id.clone(),
427 pending.command,
428 )
429 .await;
430 // The client may have disconnected while we worked; that must
431 // never fail the loop.
432 let _ = pending.respond_to.send(response);
433 }
434 }
435 }
436
437 /// The session's coarse turn state, shared by the control-socket `status`
438 /// answer and the session-state hook transitions (#6004). `Waiting` covers
439 /// every wait on the person — an open approval prompt, a presented
440 /// `request_user_input` question, or a parked goal continuation — not only
441 /// the continuation wait it used to map.
442 pub(crate) fn turn_state_from_app(app: &App) -> TurnState {
443 if app.goal_continuation_waiting
444 || app.pending_user_input_prompt.is_some()
445 || app.view_stack.top_kind() == Some(crate::tui::views::ModalKind::Approval)
446 {
447 return TurnState::Waiting;
448 }
449 if app.is_loading || matches!(app.runtime_turn_status.as_deref(), Some("in_progress")) {
450 return TurnState::InProgress;
451 }
452 TurnState::Idle
453 }
454
455 fn snapshot_from_app(app: &App) -> StatusSnapshot {
456 let turn_state = turn_state_from_app(app);
457 // A paused goal parks its objective in `paused_goal_objective`, so the
458 // snapshot surfaces the objective that is actually in flight.
459 let objective = app
460 .goal
461 .objective
462 .clone()
463 .or_else(|| app.paused_goal_objective.clone());
464 StatusSnapshot {
465 turn_state,
466 goal: GoalSnapshot {
467 objective,
468 status: app.goal.status.as_str().to_string(),
469 paused: app.paused || app.paused_goal_objective.is_some(),
470 },
471 }
472 }
473
474 /// Execute one verb on the UI thread and return its response line.
475 async fn execute_command(
476 app: &mut App,
477 config: &codewhale_runtime::config::Config,
478 engine_handle: &codewhale_engine::core::engine::EngineHandle,
479 current_streaming_text: &mut String,
480 stream_display_clock: &mut StreamDisplayClock,
481 id: String,
482 command: ControlCommand,
483 ) -> String {
484 match command {
485 ControlCommand::Message { text } => {
486 if text.trim().is_empty() {
487 return response_error(
488 &id,
489 "invalid_request",
490 "message text must not be empty".to_string(),
491 );
492 }
493 // Queued delivery is the default under load: while a turn is in
494 // flight the message waits like any queued follow-up; an idle
495 // app dispatches immediately.
496 let busy =
497 app.is_loading || matches!(app.runtime_turn_status.as_deref(), Some("in_progress"));
498 let disposition = if busy {
499 SubmitDisposition::Queue
500 } else {
501 SubmitDisposition::Immediate
502 };
503 let message = QueuedMessage::new(text, None).without_owner_input();
504 // Delivery failures surface through the app's own status/toast
505 // and recovery paths; the verb still answers with what it asked
506 // for (dispatched vs queued).
507 let _ = dispatch_composer_message(
508 app,
509 config,
510 engine_handle,
511 message,
512 DispatchRecovery::Immediate,
513 ComposerSubmitAction::Submit(disposition),
514 )
515 .await;
516 app.needs_redraw = true;
517 let delivery = if busy { "queued" } else { "dispatched" };
518 response_ok(id, ResponseResult::MessageSent { delivery })
519 }
520 ControlCommand::Interrupt => {
521 let had_active_work = app.is_loading
522 || app.is_compacting
523 || app.manual_compaction_queued
524 || app.goal_continuation_waiting
525 || app.paused
526 || app.paused_goal_objective.is_some()
527 || matches!(app.runtime_turn_status.as_deref(), Some("in_progress"));
528 if !had_active_work {
529 // Nothing Esc-cancel would cancel: quiet no-op, like an Esc
530 // on an idle app that has nothing else to act on.
531 return response_ok(id, ResponseResult::Interrupted { cancelled: false });
532 }
533 let _ = escape_cancel_request(
534 app,
535 engine_handle,
536 current_streaming_text,
537 stream_display_clock,
538 );
539 app.needs_redraw = true;
540 response_ok(id, ResponseResult::Interrupted { cancelled: true })
541 }
542 }
543 }
544
545 // ── Socket server (unix only) ───────────────────────────────────────────────
546
547 /// Bound listener + its accept thread. Dropping unbinds: the accept thread
548 /// stops within one poll interval, the socket file is unlinked if this
549 /// process still owns it, and in-flight connections finish on their own.
550 #[cfg(unix)]
551 pub(crate) struct ControlSocketHandle {
552 stop: Arc<AtomicBool>,
553 thread: Option<thread::JoinHandle<()>>,
554 }
555
556 #[cfg(unix)]
557 impl Drop for ControlSocketHandle {
558 fn drop(&mut self) {
559 self.stop.store(true, Ordering::Release);
560 if let Some(thread) = self.thread.take() {
561 // The accept loop polls at CONNECTION_POLL_INTERVAL and never
562 // blocks on a connection (each connection has its own thread),
563 // so this join is bounded and cannot deadlock.
564 let _ = thread.join();
565 }
566 }
567 }
568
569 #[cfg(unix)]
570 impl std::fmt::Debug for ControlSocketHandle {
571 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
572 f.debug_struct("ControlSocketHandle")
573 .field("stopped", &self.stop.load(Ordering::Relaxed))
574 .finish_non_exhaustive()
575 }
576 }
577
578 #[cfg(not(unix))]
579 #[derive(Debug)]
580 #[allow(dead_code)] // kept so the SessionControl field type is portable
581 pub(crate) struct ControlSocketHandle;
582
583 /// Bind `<sessions-dir>/<session-id>/control.sock` (0600) and serve it.
584 /// Refused when another live process already serves that path; a stale file
585 /// (crash leftover, nothing answering) is taken over.
586 #[cfg(unix)]
587 pub(crate) fn bind_control_socket(
588 sessions_dir: &Path,
589 session_id: &str,
590 commands_tx: mpsc::Sender<PendingCommand>,
591 status: Arc<Mutex<StatusSnapshot>>,
592 ) -> io::Result<ControlSocketHandle> {
593 let session_dir = sessions_dir.join(session_id);
594 fs::create_dir_all(&session_dir)?;
595 let path = session_dir.join(SOCKET_FILE_NAME);
596 prepare_socket_path(&path)?;
597
598 let listener = UnixListener::bind(&path)?;
599 let identity = socket_file_identity(&path);
600 codewhale_config::private_directory::tighten_mode(&path, 0o600)
601 .map_err(|error| std::io::Error::other(error.to_string()))?;
602 listener.set_nonblocking(true)?;
603
604 let stop = Arc::new(AtomicBool::new(false));
605 let thread_stop = Arc::clone(&stop);
606 let thread = thread::Builder::new()
607 .name(format!("codewhale-control-{session_id}"))
608 .spawn(move || {
609 while !thread_stop.load(Ordering::Acquire) {
610 match listener.accept() {
611 Ok((stream, _)) => {
612 // The listener is nonblocking, and on BSD-family platforms
613 // (macOS, FreeBSD) an accepted socket *inherits* O_NONBLOCK
614 // from the listener — Linux does not. The per-connection
615 // handler expects blocking reads/writes (bounded by request
616 // caps and timeouts), so make that explicit: without it, a
617 // read on macOS returns EAGAIN mid-frame on a large request
618 // and the connection dies with a broken pipe on the client.
619 let _ = stream.set_nonblocking(false);
620 // One thread per connection: a silent client
621 // must not stall other clients or the stop check.
622 let tx = commands_tx.clone();
623 let status = Arc::clone(&status);
624 if let Err(error) = thread::Builder::new()
625 .name("codewhale-control-conn".to_string())
626 .spawn(move || {
627 handle_connection(stream, &tx, &status);
628 })
629 {
630 tracing::warn!(%error, "failed to spawn control socket connection thread");
631 }
632 }
633 Err(error) if error.kind() == io::ErrorKind::WouldBlock => {
634 thread::sleep(CONNECTION_POLL_INTERVAL);
635 }
636 Err(error) if error.kind() == io::ErrorKind::Interrupted => {}
637 Err(error) => {
638 // Listener gone (e.g. the session dir was removed out from
639 // under us) — stop serving; connections fail to connect from
640 // here on, which is the honest state.
641 tracing::debug!(%error, "control socket listener closed");
642 break;
643 }
644 }
645 }
646 if let Some(identity) = identity
647 && socket_file_identity(&path) == Some(identity)
648 {
649 let _ = fs::remove_file(&path);
650 }
651 })?;
652
653 Ok(ControlSocketHandle {
654 stop,
655 thread: Some(thread),
656 })
657 }
658
659 #[cfg(not(unix))]
660 pub(crate) fn bind_control_socket(
661 _sessions_dir: &Path,
662 _session_id: &str,
663 _commands_tx: mpsc::Sender<PendingCommand>,
664 _status: Arc<Mutex<StatusSnapshot>>,
665 ) -> io::Result<ControlSocketHandle> {
666 Err(io::Error::new(
667 io::ErrorKind::Unsupported,
668 "the per-session control socket is unix-only",
669 ))
670 }
671
672 /// Take over the socket path, or refuse when a live server already holds it.
673 #[cfg(unix)]
674 fn prepare_socket_path(path: &Path) -> io::Result<()> {
675 match fs::symlink_metadata(path) {
676 Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()),
677 Err(error) => Err(error),
678 Ok(metadata) => {
679 if !metadata.file_type().is_socket() {
680 // A plain file (or directory) in the way: not ours to keep.
681 fs::remove_file(path)?;
682 return Ok(());
683 }
684 match UnixStream::connect(path) {
685 // Someone answers: a live process owns this session's socket.
686 // Do not steal it (a "socket busy" refusal).
687 Ok(_) => Err(io::Error::new(
688 io::ErrorKind::AddrInUse,
689 format!("control socket already live at {}", path.display()),
690 )),
691 // Stale: the file exists but nothing listens. Take over.
692 Err(_) => {
693 fs::remove_file(path)?;
694 Ok(())
695 }
696 }
697 }
698 }
699 }
700
701 /// (device, inode) so an unlink never removes a file this process did not bind.
702 #[cfg(unix)]
703 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
704 struct SocketFileIdentity {
705 dev: u64,
706 ino: u64,
707 }
708
709 #[cfg(unix)]
710 fn socket_file_identity(path: &Path) -> Option<SocketFileIdentity> {
711 let metadata = fs::metadata(path).ok()?;
712 use std::os::unix::fs::MetadataExt;
713 Some(SocketFileIdentity {
714 dev: metadata.dev(),
715 ino: metadata.ino(),
716 })
717 }
718
719 /// Serve exactly one request: read one bounded line, answer, close.
720 #[cfg(unix)]
721 fn handle_connection(
722 stream: UnixStream,
723 commands_tx: &mpsc::Sender<PendingCommand>,
724 status: &Arc<Mutex<StatusSnapshot>>,
725 ) {
726 let _ = stream.set_read_timeout(Some(REQUEST_READ_TIMEOUT));
727 let _ = stream.set_write_timeout(Some(RESPONSE_WRITE_TIMEOUT));
728 let mut stream = BufReader::new(stream);
729
730 let line = match read_request_line(&mut stream) {
731 Ok(Some(line)) => line,
732 Ok(None) => return, // EOF, empty frame, or timeout: close silently
733 Err(error) if error.kind() == io::ErrorKind::InvalidData => {
734 // Oversized frame: the reader drained it, so the client can
735 // finish writing and read this rejection.
736 let response = response_error("", "invalid_request", error.to_string());
737 write_response_line(stream.get_mut(), &response);
738 return;
739 }
740 Err(_) => return,
741 };
742 let trimmed = line.trim();
743 if trimmed.is_empty() {
744 return;
745 }
746
747 let request: Request = match serde_json::from_str(trimmed) {
748 Ok(request) => request,
749 Err(error) => {
750 let response =
751 response_error("", "invalid_request", format!("invalid request: {error}"));
752 write_response_line(stream.get_mut(), &response);
753 return;
754 }
755 };
756
757 let response = match request.method {
758 Method::Status(_) => {
759 let snapshot = status
760 .lock()
761 .unwrap_or_else(|poisoned| poisoned.into_inner())
762 .clone();
763 response_ok(
764 request.id,
765 ResponseResult::Status {
766 turn_state: snapshot.turn_state,
767 goal: snapshot.goal,
768 },
769 )
770 }
771 Method::Message(params) => dispatch_to_app(
772 request.id,
773 ControlCommand::Message { text: params.text },
774 commands_tx,
775 ),
776 Method::Interrupt(_) => dispatch_to_app(request.id, ControlCommand::Interrupt, commands_tx),
777 };
778 write_response_line(stream.get_mut(), &response);
779 }
780
781 /// Hand a verb to the event loop and wait (bounded) for its answer.
782 #[cfg(unix)]
783 fn dispatch_to_app(
784 id: String,
785 command: ControlCommand,
786 commands_tx: &mpsc::Sender<PendingCommand>,
787 ) -> String {
788 dispatch_to_app_within(id, command, commands_tx, DISPATCH_RESPONSE_TIMEOUT)
789 }
790
791 #[cfg(unix)]
792 fn dispatch_to_app_within(
793 id: String,
794 command: ControlCommand,
795 commands_tx: &mpsc::Sender<PendingCommand>,
796 timeout: Duration,
797 ) -> String {
798 let (respond_to, rx) = mpsc::channel();
799 let claimed = Arc::new(AtomicBool::new(false));
800 if let Err(error) = commands_tx.send(PendingCommand {
801 id: id.clone(),
802 command,
803 respond_to,
804 claimed: Arc::clone(&claimed),
805 }) {
806 return response_error(
807 &id,
808 "server_unavailable",
809 format!("failed to dispatch request: {error}"),
810 );
811 }
812 let answer = match rx.recv_timeout(timeout) {
813 // Withdraw the verb unless the event loop already claimed it: a
814 // timeout reply must mean "not executed", or a retry duplicates it.
815 Err(mpsc::RecvTimeoutError::Timeout) if !claimed.swap(true, Ordering::AcqRel) => {
816 return response_error(
817 &id,
818 "timeout",
819 format!(
820 "timed out waiting for the app to handle the request after {} ms; it was not executed",
821 timeout.as_millis()
822 ),
823 );
824 }
825 // Claimed and executing: its answer (or the channel closing) is due.
826 Err(mpsc::RecvTimeoutError::Timeout) => rx.recv().map_err(|_| ()),
827 Ok(response) => Ok(response),
828 Err(mpsc::RecvTimeoutError::Disconnected) => Err(()),
829 };
830 answer.unwrap_or_else(|()| {
831 response_error(
832 &id,
833 "server_unavailable",
834 "request handling failed: app response channel closed".to_string(),
835 )
836 })
837 }
838
839 /// One newline-terminated line, bounded. `Ok(None)` = EOF before any content.
840 /// The cap is enforced *while* reading (a hostile peer cannot make us buffer
841 /// an unbounded line), and on oversize the remainder of the frame is
842 /// discarded through a fixed-size buffer — memory stays bounded, and a client
843 /// that wrote the whole request can still receive the rejection.
844 #[cfg(unix)]
845 fn read_request_line(stream: &mut BufReader<UnixStream>) -> io::Result<Option<String>> {
846 let mut capped = stream.by_ref().take(MAX_REQUEST_BYTES as u64 + 1);
847 let mut line = Vec::new();
848 let read = capped.read_until(b'\n', &mut line)?;
849 if read == 0 {
850 return Ok(None); // EOF before any content
851 }
852 if line.last() != Some(&b'\n') {
853 // The frame exceeded the cap (or was torn mid-line). Discard the
854 // remainder so a well-behaved client finishes its write and reads
855 // the rejection; a torn frame's write lands nowhere and is ignored.
856 let mut buf = [0u8; 8192];
857 loop {
858 match stream.read(&mut buf) {
859 Ok(0) | Err(_) => break,
860 Ok(n) => {
861 if buf[..n].contains(&b'\n') {
862 break;
863 }
864 }
865 }
866 }
867 return Err(io::Error::new(
868 io::ErrorKind::InvalidData,
869 format!("request exceeds {MAX_REQUEST_BYTES} bytes"),
870 ));
871 }
872 Ok(Some(String::from_utf8_lossy(&line).into_owned()))
873 }
874
875 #[cfg(unix)]
876 fn write_response_line(stream: &mut UnixStream, value: &str) {
877 let _ = writeln!(stream, "{value}");
878 let _ = stream.flush();
879 }
880
881 #[cfg(test)]
882 mod tests {
883 use super::*;
884
885 // ── Verb parsing ──────────────────────────────────────────────────────
886
887 #[test]
888 fn parses_each_verb_request() {
889 let message: Request =
890 serde_json::from_str(r#"{"id":"1","method":"message","params":{"text":"hi"}}"#)
891 .expect("message request");
892 assert_eq!(message.id, "1");
893 assert!(matches!(message.method, Method::Message(p) if p.text == "hi"));
894
895 for (raw, want) in [
896 (
897 r#"{"id":"2","method":"interrupt","params":{}}"#,
898 "interrupt",
899 ),
900 (r#"{"id":"3","method":"status","params":{}}"#, "status"),
901 ] {
902 let request: Request = serde_json::from_str(raw).expect("verb request");
903 let got = match request.method {
904 Method::Message(_) => "message",
905 Method::Interrupt(_) => "interrupt",
906 Method::Status(_) => "status",
907 };
908 assert_eq!(got, want);
909 }
910 }
911
912 /// #6516: `relaunch` was advertised but always failed, because no
913 /// `/relaunch` command exists. It is gone; a supervisor still sending it
914 /// gets a parse error naming the verbs that do exist.
915 #[test]
916 fn retired_relaunch_verb_is_rejected() {
917 let error =
918 serde_json::from_str::<Request>(r#"{"id":"3","method":"relaunch","params":{}}"#)
919 .expect_err("relaunch must not parse");
920 let message = error.to_string();
921 assert!(message.contains("unknown variant"), "{message}");
922 assert!(message.contains("status"), "{message}");
923 }
924
925 #[test]
926 fn rejects_unknown_verb() {
927 let error = serde_json::from_str::<Request>(r#"{"id":"1","method":"dance","params":{}}"#)
928 .expect_err("unknown verb must not parse");
929 let message = error.to_string();
930 assert!(message.contains("unknown variant"), "{message}");
931 }
932
933 #[test]
934 fn rejects_missing_or_wrong_params() {
935 // message without `text`
936 let error = serde_json::from_str::<Request>(r#"{"id":"1","method":"message","params":{}}"#)
937 .expect_err("message without text must not parse");
938 assert!(error.to_string().contains("missing field"), "{error}");
939
940 // missing params entirely
941 let error = serde_json::from_str::<Request>(r#"{"id":"1","method":"status"}"#)
942 .expect_err("missing params must not parse");
943 assert!(!error.to_string().is_empty());
944
945 // non-string text
946 let error =
947 serde_json::from_str::<Request>(r#"{"id":"1","method":"message","params":{"text":7}}"#)
948 .expect_err("numeric text must not parse");
949 assert!(!error.to_string().is_empty());
950
951 // non-string id
952 let error = serde_json::from_str::<Request>(r#"{"id":7,"method":"status","params":{}}"#)
953 .expect_err("numeric id must not parse");
954 assert!(!error.to_string().is_empty());
955 }
956
957 #[test]
958 fn serializes_responses_in_the_response_envelope_shape() {
959 let sent = response_ok(
960 "1".into(),
961 ResponseResult::MessageSent { delivery: "queued" },
962 );
963 assert_eq!(
964 sent,
965 r#"{"id":"1","result":{"type":"message_sent","delivery":"queued"}}"#
966 );
967
968 let interrupted = response_ok("2".into(), ResponseResult::Interrupted { cancelled: true });
969 assert_eq!(
970 interrupted,
971 r#"{"id":"2","result":{"type":"interrupted","cancelled":true}}"#
972 );
973
974 let status = response_ok(
975 "4".into(),
976 ResponseResult::Status {
977 turn_state: TurnState::Idle,
978 goal: GoalSnapshot {
979 objective: Some("ship it".to_string()),
980 status: "active".to_string(),
981 paused: false,
982 },
983 },
984 );
985 assert_eq!(
986 status,
987 r#"{"id":"4","result":{"type":"status","turn_state":"idle","goal":{"objective":"ship it","status":"active","paused":false}}}"#
988 );
989
990 let error = response_error("9", "invalid_request", "nope".to_string());
991 assert_eq!(
992 error,
993 r#"{"id":"9","error":{"code":"invalid_request","message":"nope"}}"#
994 );
995 }
996
997 // ── Socket framing (unix) ─────────────────────────────────────────────
998
999 #[cfg(unix)]
1000 fn test_endpoint() -> (
1001 tempfile::TempDir,
1002 PathBuf,
1003 mpsc::Receiver<PendingCommand>,
1004 ControlSocketHandle,
1005 ) {
1006 let temp = tempfile::TempDir::new().expect("temp dir");
1007 let sessions_dir = temp.path().join("sessions");
1008 let (tx, rx) = mpsc::channel();
1009 let status = Arc::new(Mutex::new(StatusSnapshot {
1010 turn_state: TurnState::Idle,
1011 goal: GoalSnapshot {
1012 objective: Some("goal".to_string()),
1013 status: "active".to_string(),
1014 paused: false,
1015 },
1016 }));
1017 let handle = bind_control_socket(&sessions_dir, "test-session", tx, status).expect("bind");
1018 (
1019 temp,
1020 sessions_dir.join("test-session").join(SOCKET_FILE_NAME),
1021 rx,
1022 handle,
1023 )
1024 }
1025
1026 #[cfg(unix)]
1027 fn request_response(path: &Path, request: &str) -> String {
1028 let mut stream = UnixStream::connect(path).expect("connect");
1029 stream
1030 .set_read_timeout(Some(Duration::from_secs(5)))
1031 .expect("read timeout");
1032 writeln!(stream, "{request}").expect("write request");
1033 let mut response = String::new();
1034 BufReader::new(stream)
1035 .read_line(&mut response)
1036 .expect("read response");
1037 response
1038 }
1039
1040 #[cfg(unix)]
1041 #[test]
1042 fn status_verb_answers_over_the_socket() {
1043 let (_temp, path, _rx, _handle) = test_endpoint();
1044 let response = request_response(&path, r#"{"id":"4","method":"status","params":{}}"#);
1045 let value: serde_json::Value = serde_json::from_str(&response).expect("response is json");
1046 assert_eq!(value["id"], "4");
1047 assert_eq!(value["result"]["type"], "status");
1048 assert_eq!(value["result"]["turn_state"], "idle");
1049 assert_eq!(value["result"]["goal"]["objective"], "goal");
1050 assert_eq!(value["result"]["goal"]["paused"], false);
1051 }
1052
1053 #[cfg(unix)]
1054 #[test]
1055 fn message_verb_reaches_the_app_channel_and_answers() {
1056 let (_temp, path, rx, _handle) = test_endpoint();
1057
1058 // The test stands in for the event loop on the other end of the
1059 // channel: it receives the verb and answers like `drain` would.
1060 let server = std::thread::spawn(move || {
1061 let pending = rx
1062 .recv_timeout(Duration::from_secs(5))
1063 .expect("verb queued");
1064 assert_eq!(pending.id, "1");
1065 match pending.command {
1066 ControlCommand::Message { text } => assert_eq!(text, "hello"),
1067 other => panic!("expected Message, got {other:?}"),
1068 }
1069 pending
1070 .respond_to
1071 .send(response_ok(
1072 "1".into(),
1073 ResponseResult::MessageSent {
1074 delivery: "dispatched",
1075 },
1076 ))
1077 .expect("answer");
1078 });
1079
1080 let response = request_response(
1081 &path,
1082 r#"{"id":"1","method":"message","params":{"text":"hello"}}"#,
1083 );
1084 server.join().expect("server thread");
1085 let value: serde_json::Value = serde_json::from_str(&response).expect("response is json");
1086 assert_eq!(value["id"], "1");
1087 assert_eq!(value["result"]["type"], "message_sent");
1088 assert_eq!(value["result"]["delivery"], "dispatched");
1089 }
1090
1091 #[cfg(unix)]
1092 #[test]
1093 fn a_timed_out_verb_is_never_executed_later() {
1094 let (tx, rx) = mpsc::channel();
1095 let response = dispatch_to_app_within(
1096 "7".into(),
1097 ControlCommand::Interrupt,
1098 &tx,
1099 Duration::from_millis(20),
1100 );
1101 let value: serde_json::Value = serde_json::from_str(&response).expect("response is json");
1102 assert_eq!(value["error"]["code"], "timeout");
1103 // The event loop reaches the queued verb only now: the client was
1104 // told it timed out, so it must not run (a retry would duplicate it).
1105 let pending = rx.try_recv().expect("verb stayed queued");
1106 assert!(!pending.claim(), "a withdrawn verb must not execute");
1107 }
1108
1109 #[cfg(unix)]
1110 #[test]
1111 fn malformed_json_gets_invalid_request_error() {
1112 let (_temp, path, _rx, _handle) = test_endpoint();
1113 let response = request_response(&path, "{not json");
1114 let value: serde_json::Value = serde_json::from_str(&response).expect("response is json");
1115 assert_eq!(value["id"], "");
1116 assert_eq!(value["error"]["code"], "invalid_request");
1117 }
1118
1119 #[cfg(unix)]
1120 #[test]
1121 fn unknown_verb_gets_invalid_request_error() {
1122 let (_temp, path, _rx, _handle) = test_endpoint();
1123 let response = request_response(&path, r#"{"id":"7","method":"dance","params":{}}"#);
1124 let value: serde_json::Value = serde_json::from_str(&response).expect("response is json");
1125 assert_eq!(value["id"], "");
1126 assert_eq!(value["error"]["code"], "invalid_request");
1127 }
1128
1129 #[cfg(unix)]
1130 #[test]
1131 fn empty_line_closes_without_a_response() {
1132 let (_temp, path, _rx, _handle) = test_endpoint();
1133 let mut stream = UnixStream::connect(&path).expect("connect");
1134 stream
1135 .set_read_timeout(Some(Duration::from_secs(5)))
1136 .expect("read timeout");
1137 writeln!(stream).expect("write empty line");
1138 let mut response = String::new();
1139 let read = BufReader::new(stream)
1140 .read_line(&mut response)
1141 .expect("read");
1142 assert_eq!(read, 0, "empty line must close the connection silently");
1143 assert!(response.is_empty());
1144 }
1145
1146 #[cfg(unix)]
1147 #[test]
1148 fn oversized_request_is_rejected_with_an_error() {
1149 let (_temp, path, _rx, _handle) = test_endpoint();
1150 let mut stream = UnixStream::connect(&path).expect("connect");
1151 stream
1152 .set_read_timeout(Some(Duration::from_secs(5)))
1153 .expect("read timeout");
1154 let blob = "x".repeat(MAX_REQUEST_BYTES + 16);
1155 let request = format!(r#"{{"id":"1","method":"message","params":{{"text":"{blob}"}}}}"#);
1156 writeln!(stream, "{request}").expect("write oversized request");
1157 let mut response = String::new();
1158 BufReader::new(stream)
1159 .read_line(&mut response)
1160 .expect("read rejection");
1161 let value: serde_json::Value = serde_json::from_str(&response).expect("response is json");
1162 assert_eq!(value["error"]["code"], "invalid_request");
1163 }
1164
1165 #[cfg(unix)]
1166 #[test]
1167 fn bind_refuses_a_live_socket_and_takes_over_a_stale_file() {
1168 let temp = tempfile::TempDir::new().expect("temp dir");
1169 let sessions_dir = temp.path().join("sessions");
1170 let socket_path = sessions_dir.join("test-session").join(SOCKET_FILE_NAME);
1171 let status = Arc::new(Mutex::new(StatusSnapshot {
1172 turn_state: TurnState::Idle,
1173 goal: GoalSnapshot {
1174 objective: None,
1175 status: "active".to_string(),
1176 paused: false,
1177 },
1178 }));
1179 let (tx, _rx) = mpsc::channel();
1180
1181 // A stale plain file is taken over.
1182 fs::create_dir_all(socket_path.parent().expect("parent")).expect("mkdir");
1183 fs::write(&socket_path, b"stale").expect("write stale file");
1184 let handle = bind_control_socket(
1185 &sessions_dir,
1186 "test-session",
1187 tx.clone(),
1188 Arc::clone(&status),
1189 )
1190 .expect("bind over a stale file");
1191 drop(handle);
1192
1193 // A live listener is refused.
1194 let _ = fs::remove_file(&socket_path);
1195 let live = UnixListener::bind(&socket_path).expect("bind live listener");
1196 let error = bind_control_socket(&sessions_dir, "test-session", tx, status)
1197 .expect_err("must refuse a live socket");
1198 assert_eq!(error.kind(), io::ErrorKind::AddrInUse);
1199 drop(live);
1200 let _ = fs::remove_file(&socket_path);
1201 }
1202
1203 #[cfg(unix)]
1204 #[test]
1205 fn drop_unbinds_and_unlinks_the_socket() {
1206 let temp = tempfile::TempDir::new().expect("temp dir");
1207 let sessions_dir = temp.path().join("sessions");
1208 let socket_path = sessions_dir.join("test-session").join(SOCKET_FILE_NAME);
1209 let (tx, _rx) = mpsc::channel();
1210 let status = Arc::new(Mutex::new(StatusSnapshot {
1211 turn_state: TurnState::Idle,
1212 goal: GoalSnapshot {
1213 objective: None,
1214 status: "active".to_string(),
1215 paused: false,
1216 },
1217 }));
1218 let handle = bind_control_socket(&sessions_dir, "test-session", tx, status).expect("bind");
1219 assert!(socket_path.exists(), "socket file exists while bound");
1220 drop(handle);
1221 // The accept thread unlinks within one poll interval.
1222 let deadline = std::time::Instant::now() + Duration::from_secs(5);
1223 while socket_path.exists() && std::time::Instant::now() < deadline {
1224 std::thread::sleep(Duration::from_millis(20));
1225 }
1226 assert!(
1227 !socket_path.exists(),
1228 "socket file must be unlinked after drop"
1229 );
1230 }
1231
1232 #[cfg(unix)]
1233 #[test]
1234 fn reconcile_backs_off_after_a_refused_takeover() {
1235 let temp = tempfile::TempDir::new().expect("temp dir");
1236 let sessions_dir = temp.path().join("sessions");
1237 let socket_path = sessions_dir.join("sess").join(SOCKET_FILE_NAME);
1238 fs::create_dir_all(socket_path.parent().expect("parent")).expect("mkdir");
1239
1240 let mut control = SessionControl::new_with_sessions_dir(true, Some(sessions_dir.clone()));
1241
1242 // A live listener occupies the path: the takeover is refused.
1243 let live = UnixListener::bind(&socket_path).expect("bind live listener");
1244 control.reconcile(Some("sess"));
1245 assert!(
1246 control.bound_session.is_none(),
1247 "refused bind must not claim"
1248 );
1249
1250 // The other process goes away, but the backoff still holds.
1251 drop(live);
1252 let _ = fs::remove_file(&socket_path);
1253 control.reconcile(Some("sess"));
1254 assert!(
1255 control.bound_session.is_none(),
1256 "backoff must suppress an immediate rebind"
1257 );
1258
1259 // After the backoff window, the same session binds successfully.
1260 std::thread::sleep(BIND_RETRY_BACKOFF + Duration::from_millis(50));
1261 control.reconcile(Some("sess"));
1262 assert_eq!(control.bound_session.as_deref(), Some("sess"));
1263
1264 // Reconcile with the same id is a no-op; a different id rebinds.
1265 control.reconcile(Some("sess"));
1266 assert_eq!(control.bound_session.as_deref(), Some("sess"));
1267 control.reconcile(Some("other"));
1268 assert_eq!(control.bound_session.as_deref(), Some("other"));
1269 drop(control);
1270 }
1271 }
1272
1272 lines RUST